1 /+
2 Unittest utils
3 +/
4 module sily.unit;
5 
6 import sily.logger;
7 
8 import sily.bashfmt;
9 import sily.terminal;
10 
11 import std.stdio: writef;
12 import std.format: format;
13 import std.conv: to;
14 
15 private int _testPassed = 0;
16 private int _testFailed = 0;
17 private int _testTotal = 0;
18 
19 /**
20 Adds result of test
21 Params:
22     result = Did test pass (true - passed)
23 */
24 private void addTest(bool result) {
25     if (result == false) {
26         _testFailed += 1;
27     } else {
28         _testPassed += 1;
29     }
30     _testTotal += 1;
31 }
32 
33 /// Initialises unittest
34 public void startUnittest(int line = __LINE__, string file = __FILE__)() {
35     _testTotal = 0;
36     _testPassed = 0;
37     _testFailed = 0;
38     hr('-', to!dstring("Starting test at " ~ file ~ ":" ~ line.to!string), "\033[90m");
39 }
40 
41 /// Finishes unittest
42 public void writeReport(int line = __LINE__, string file = __FILE__)(bool exitOnError = false, bool color = true) {
43     // writef("Total tests:  %d\nPassed tests: %d\nFailed tests: %d\n",
44     //         _testTotal, _testPassed, _testFailed);
45     // if (_testFailed != 0 && exitOnError) throw new Error("Unittest failed.", file, line);
46     // TODO: if color
47     writef("Total tests:  %d\n", _testTotal);
48     writef("Passed tests: %s%d%s\n", cast(string) (_testPassed == 0 ? FG.ltred : FG.reset), _testPassed, cast(string) FG.reset);
49     writef("Failed tests: %s%d%s\n", cast(string) (_testFailed == 0 ? FG.reset : FG.ltred), _testFailed, cast(string) FG.reset);
50 
51     if (_testFailed != 0 && exitOnError) exit(ErrorCode.general);
52 }
53 
54 /// Tests if values are equals
55 public void assertEquals(T, S, int line = __LINE__, string file = __FILE__)
56                         (T t, S s, string message = "Expected '%s', got '%s'.") {
57     bool passed = t == s;
58     addTest(passed);
59     if (!passed) {
60         error!(line, file)(message.format(t.to!string, s.to!string));
61     }
62 }
63 
64 /// Tests if value is false
65 public void assertFalse(T, int line = __LINE__, string file = __FILE__)
66                        (T t, string message = "Expected '%s', got '%s'.") {
67     assertEquals!(T, bool, line, file)(t, false, message);
68 }
69 
70 /// Tests if value is true
71 public void assertTrue(T, int line = __LINE__, string file = __FILE__)
72                        (T t, string message = "Expected '%s', got '%s'.") {
73     assertEquals!(T, bool, line, file)(t, true, message);
74 }
75