Why the very same code works in main and not in unittest?

Pablo De Nápoli nospam at devnull.com
Fri Aug 20 16:02:22 UTC 2021


Still working on my project of a D wrapped for libmpdec 
(https://www.bytereef.org/mpdecimal/).

Consider the following code:

     void main()
     {
       mpd_context_t ctx;
       mpd_t* a;
       mpd_ieee_context(&ctx, 128);
       a= mpd_new(&ctx);
     }

It seems to work fine. mpd_new is a C function for allocating a 
new mpdecimal object via
malloc, prototype:

mpd_t *mpd_new(mpd_context_t *ctx);

see the documentation at:

https://www.bytereef.org/mpdecimal/doc/libmpdec/decimals.html?highlight=mpd_new#std:topic-mpd_new

However, if I put the very same code in the unittest section of a 
module, it fails with
a segmentation fault and I don't understand why!

     Personally, I found the unittest mechanism rather obscure. 
For instance I have tried to debug the problem using gdb and I 
found that the following code was run
     	
     module dub_test_root;
     2	import std.typetuple;
     3	static import mpdec.decimal;
     4	static import mpdec.mpdec;
     5	alias allModules = TypeTuple!(mpdec.decimal, mpdec.mpdec);
     6	
     7							import std.stdio;
     8							import core.runtime;
     9	
     10							void main() { writeln("All unit tests have been run 
successfully."); }
     11							shared static this() {
     12								version (Have_tested) {
     13									import tested;
     14									import core.runtime;
     15									import std.exception;
     16									Runtime.moduleUnitTester = () => true;
     17									enforce(runUnitTests!allModules(new 
ConsoleTestResultWriter), "Unit tests failed.");
     18								}
     19							}
     20	

I didn't even new that this code was there! (and I didn't manage 
to set a breakpoint
in my unit test, is there a way to do that?). I rather prefer a 
separate test program!






More information about the Digitalmars-d-learn mailing list