better assertions and __FILE__

Bruce Adams ifyoudontknowmebynow at searchdaweb.com
Thu Aug 16 16:43:20 PDT 2007


Bruce Adams Wrote:

> 
> Hi,
>     Another FAQ item I couldn't find. I'm looking to implement some wrappers around assert as assert is too primative and doesn't give me enough information. I want to go down the xUnit path E.g.
> 
> in the code:
>    assertEqual(foo,bar);
> 
> leading to output:
>    Equality assertion failed in file.cpp at line 10
>    Expected Value: 10
>    Actual Value: 5
> 
> I got as far as:
> 
> void assertEqual(Type)(Type actual_, 
>                                 Type expected_, 
> 		            char[] file_, 
> 		            uint line_) {
>    if (actual_ != expected_) {
>       writefln("Equality assertion failed");
>       writefln("actual:   '", actual_, "'");
>       writefln("expected: '", expected_, "'");
>       _d_assert(file_,line_);
>    }
> }
> 
> This lets me use:
> 
>    assertEqual!(string)("foo","bar",cast(char[])(__FILE__),__LINE__);
> 
> Where I'm having trouble is getting __FILE__ and __LINE__ added (presumably using a mixin) so I can avoid the cruft.
> 

Here are a few more things I've learned on my travels around the various D web-pages.

__FILE__ & __LINE__ are expanded by the tokeniser not the parser. This implies that they would not be available for use in mixins as they will already have been expanded. This is confirmed with a quick test. So what I'm trying to do is not currently possible.

I have seen two proposals for improvements to D bandied around.

1) "context" functions

// does not exist
void context(__line, __file) assertEqual(int a, int b) {
   if (a != b) {
     writefln("equality assertion failed");
     writefln("expected: ",a);
     writefln("actual: ",b);
     _d_assert(__line,__file);
   }
}

2) Access to the call stack through "trace" something like:

import std.trace;  // does not exist yet

void assertEqual(int a, int b) {
   if (a != b) {
     writefln("equality assertion failed");
     writefln("expected: ",a);
     writefln("actual: ",b);
     StackFrame callerFrame = getStack().up();
     uint callingLine = callerFrame.getLine();
     char[] callingFile = callerFrame.getFile();
     _d_assert(callingLine, callingFile);
   }
}

I think the latter has more appeal and more support. You can use it for generating stack traces and core dumps for example. However, I have no idea of what status these ideas are at. There's nothing in the issue tracking system. I'm not sure if that's the right place for frivolous feature requests. Has anyone heard anything on the grapevine?
Are there language development roadmap and feature request pages knocking around the web somewhere that I've yet to find?

Regards,

Bruce.






More information about the Digitalmars-d-learn mailing list