1 /**
2  * The test module defines some common components and imports that are useful
3  * for testing your application's logging behavior.
4  *
5  * Do not import this module outside the scope of any test code/unittests, as
6  * it may interfere with normal SLF4D operations.
7  */
8 module slf4d.test;
9 
10 import core.sync.mutex;
11 
12 /** 
13  * A convenience import of the main SLF4D package.
14  */
15 public import slf4d;
16 
17 /** 
18  * Imports the testing provider, since that's needed for most SLF4D-related tests.
19  */
20 public import slf4d.testing_provider;
21 
22 /** 
23  * A mutex to synchronize tests that affect the core logging state. You can
24  * either synchronize on this object, or call `acquireLoggingTestingLock()` to
25  * ensure that only your test has access to the logging state. Be sure that if
26  * you acquire a testing lock, that you release it afterwards with
27  * `releaseLoggingTestingLock()`.
28  */
29 public __gshared Mutex loggingTestingMutex;
30 
31 static this() {
32     loggingTestingMutex = new Mutex();
33 }
34 
35 /** 
36  * Acquires a lock for the SLF4D testing system. Call this before testing
37  * anything which interacts with a pre-configured testing setup for logging.
38  */
39 public void acquireLoggingTestingLock() {
40     loggingTestingMutex.lock_nothrow();
41 }
42 
43 /** 
44  * Releases a lock for the SLF4D testing system. Call this after testing
45  * anything that required the lock to be acquired.
46  */
47 public void releaseLoggingTestingLock() {
48     loggingTestingMutex.unlock_nothrow();
49 }
50 
51 /** 
52  * Resets the SLF4D logging state, and configures a new TestingLoggingProvider
53  * to be used, and returns it. This should only be called when you've acquired
54  * a lock for the testing system (or synchronized on the mutex).
55  * Returns: The logging provider.
56  */
57 public TestingLoggingProvider getTestingProvider() {
58     resetLoggingState();
59     TestingLoggingProvider testingProvider = new TestingLoggingProvider();
60     configureLoggingProvider(testingProvider);
61     return testingProvider;
62 }
63 
64 /**
65  * Convenience function to acquire a lock on the SLF4D logging state and run
66  * some code, then reset the logging state and release the lock.
67  * Params:
68  *   dg = The code to run.
69  */
70 public void withTestingLock(void delegate() dg) {
71     acquireLoggingTestingLock();
72     dg();
73     resetLoggingState();
74     releaseLoggingTestingLock();
75 }
76 
77 /**
78  * Convenience function to acquire a lock on the testing state, run some code
79  * (in the provided delegate function), then release the lock.
80  * Params:
81  *   dg = The code to run with the testing logging provider.
82  */
83 public void withTestingProvider(void delegate(TestingLoggingProvider) dg) {
84     acquireLoggingTestingLock();
85     dg(getTestingProvider());
86     resetLoggingState();
87     releaseLoggingTestingLock();
88 }