Created
April 15, 2016 20:48
-
-
Save pineapplemachine/2224d68df5396235c8bd959b044c220c to your computer and use it in GitHub Desktop.
Assert using string formatting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /++ | |
| Written by Sophie Kirschner: sophiek@pineapplemachine.com | |
| zlib/libpng license: https://opensource.org/licenses/Zlib | |
| +/ | |
| module mach.error.assertf; | |
| private: | |
| import core.exception : AssertError; | |
| import std.format : format; | |
| public: | |
| /// Throws an AssertError when the condition is not met. | |
| void assertf( | |
| size_t line = __LINE__, string file = __FILE__, Args... | |
| )( | |
| lazy bool condition, in string message, Args args | |
| ){ | |
| assert({ | |
| // Putting the function body in an assert statement means it only | |
| // evaluates when assertions are normally evaluated, i.e. not in | |
| // release mode. | |
| if(!condition()) throw new AssertError(format(message, args), file, line, null); | |
| return true; | |
| }()); | |
| } | |
| unittest{ | |
| void fail(in void function() test){ | |
| bool caught = false; | |
| try{ | |
| test(); | |
| }catch(AssertError error){ | |
| caught = true; | |
| } | |
| assert(caught); | |
| } | |
| assertf(true, "hello %s", "world"); | |
| assertf((2 * 5) == (10 * 1), "hello %s", "world"); | |
| fail({assertf(false, "hello %s", "world");}); | |
| fail({assertf((2 * 5) != (10 * 1), "hello %s", "world");}); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment