Share this post

Assert an expression is unchanged over a code block

Most (all?) testing packages in R are built around the idea of testing a value at a particular moment in time e.g. “Check that a == 2right now”.

The prior post detailed a function to test an expected changed in value of a particular expression before & after some particular code is run. E.g. I might not know how long a data.frame is, but I do know that it should grow by 2 rows during the execution of some function.

This post shows a simplification of yesterday’s testing function which only tests that a value is unchanged over a block of code.

assert_unchanged()

The following code tests the validity of a statement over a code block.

The statement to test is of the form [after] [logical operator] [before].

E.g.

a == a + 1 – when we expect the value of a to be incremented by 1

nrow(df) == nrow(df) - 3 – when we expect 3 rows to be removed from the data.frame df

Conclusion

Be able to test multiple statements are unchanged over a code block. The call signature of such a function is going to need thinking though i.e. is it more sensible to:

Have a signature like assert_unchanged(code, ...) which shifts the code to be first followed by a varying number of statements, or

Have a call signature of assert_unchanged(...) and automatically interpret the last item in the argument list be interpreted as the code block, and the preceding arguments are the tests? (This is similar to how ensurer does some argument unpacking)

More checks needed to see that this behaves nicely when calling functions.

More verbose error with the actual evaluated values of the before/after shown e.g. “The following statement has changed value: b. ‘2’ => ‘3’”