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