1 module dutils.testing; 2 3 import std.algorithm.comparison : equal; 4 import std.traits : isNumeric, isBoolean; 5 6 void assertEqual(T)(T actual, T expected) { 7 bool equals = false; 8 9 static if (isNumeric!T || isBoolean!T) { 10 equals = actual == expected; 11 } else { 12 equals = equal(actual, expected); 13 } 14 15 if (!equals) { 16 import std.conv : to; 17 18 string actualString; 19 string expectedString; 20 try { 21 actualString = actual.to!string; 22 expectedString = expected.to!string; 23 } catch (Exception exception) { 24 } 25 26 if (actualString != "" && expectedString != "") { 27 throw new Exception("Expected " ~ actualString ~ " to equal " ~ expectedString); 28 } 29 30 throw new Exception("Output did not equal expected output"); 31 } 32 } 33 34 unittest { 35 bool failed = false; 36 37 try { 38 assertEqual(true, false); 39 failed = true; 40 } catch (Exception exception) { 41 assert(exception.message == "Expected true to equal false"); 42 } 43 44 assert(failed == false); 45 } 46 47 unittest { 48 int add(int a, int b) { 49 return a + b; 50 } 51 52 assertEqual(add(12, 4), 16); 53 } 54 55 unittest { 56 assertEqual("testing", "testing"); 57 } 58 59 unittest { 60 bool failed = false; 61 62 try { 63 assertEqual("bad text", "testing"); 64 failed = true; 65 } catch (Exception exception) { 66 assert(exception.message == "Expected bad text to equal testing"); 67 } 68 69 assert(failed == false); 70 } 71 72 unittest { 73 assertEqual(123, 123); 74 } 75 76 unittest { 77 bool failed = false; 78 79 try { 80 assertEqual(123, 1232); 81 failed = true; 82 } catch (Exception exception) { 83 assert(exception.message == "Expected 123 to equal 1232"); 84 } 85 86 assert(failed == false); 87 } 88 89 unittest { 90 assertEqual([123, 1, 3, 4], [123, 1, 3, 4]); 91 } 92 93 unittest { 94 bool failed = false; 95 96 try { 97 assertEqual([123, 1, 3], [123, 1, 3, 4]); 98 failed = true; 99 } catch (Exception exception) { 100 assert(exception.message == "Expected [123, 1, 3] to equal [123, 1, 3, 4]"); 101 } 102 103 assert(failed == false); 104 }