Function Repository Resource:

WriteUnitTest

Source Notebook

Write a formatted and readable unit test for any input

Contributed by: Jason Biggs

ResourceFunction["WriteUnitTest"][file,expr]

evaluates expr and uses the result to write a VerificationTest in file.

Details and Options

If file does not exist, it will be created. If it does exist, the new test will be added before the EndTestSection[] line.
If the option "ConfirmResults" is set to the default value of True, a dialog will appear showing the test before writing it to the file.

Examples

Basic Examples (2) 

Create a unit test and write it to file:

In[1]:=
ResourceFunction["WriteUnitTest"]["testFile1.wlt", f[x0_] :=
  Module[{x = x0},
   While[x > 0, x = Log[x]];
   x
   ];
 f[2.0]
 ]

Run the test:

In[2]:=
TestReport["testFile1.wlt"]
Out[2]=

Create a test for an input that issues a message:

In[3]:=
ResourceFunction["WriteUnitTest"]["testFile2.wlt", With[{res = NumericArray["badinput"]},
  {Head[res], NumericArrayQ[res]}]
 ]
In[4]:=
FilePrint["testFile2.wlt"]

Run the test:

In[5]:=
TestReport["testFile2.wlt"]
Out[5]=

Options (2) 

Use the option "ConfirmResults" to write the test to file without verifying the results:

In[6]:=
ResourceFunction["WriteUnitTest"]["testFile1.wlt", 2 + 2, "ConfirmResults" -> False];
In[7]:=
ResourceFunction["WriteUnitTest"]["testFile1.wlt", 3 + 3, "ConfirmResults" -> False];
In[8]:=
ResourceFunction["WriteUnitTest"]["testFile1.wlt", 1/0, "ConfirmResults" -> False];

Each test was appended to the file:

In[9]:=
TestReport["testFile1.wlt"]
Out[9]=

Version History

  • 2.1.0 – 24 July 2025
  • 2.0.0 – 25 July 2019
  • 1.0.0 – 15 May 2019

License Information