Testing in Python

After having seen how to test in R.

Let’s see how to do the same in Python:

Writing a tests-oriented program

A good practice demands that we should try to write our test before we code the program we intended to.

Or at least, try to write the code in a way that is easier to test in the future.
Fighting our natural tendency to write the code you desperately want to write and then the tests.

To do that, follow these guidelines:


Continue reading “Testing in Python”

Testing in R

To test a given function in R, I use the package ‘testthat’.

A very nice intro to the package is present here: https://journal.r-project.org/archive/2011/RJ-2011-002/RJ-2011-002.pdf

However, in order to write good quality code and to do it only once, you got to carry out a paradigm shift in your writing procedure:

How to write a tests-oriented program

You might have the natural tendency to write the tests after your code.

However, this is not the best approach, indeed, after that, you might need to rewrite big part of the code, to make it more ‘testable’.

In order to avoid that, you need to write your test before the program.

Certainly, this is is a bit harder to implement, especially the first times.

Therefore, to make it easier, follow these guidelines:


  • Independent files:
    • One for the program, one for the tests
  • Code stile for the program:
    • Atomicity:
      • A single R file for each task/objective.
      • Single functions for each step of your algorithm. This will help later in the test
    • A main function to be invoked. This will list all the functions (steps) of the program.
  • Tests, in and out:
    • Within the program file
      • Tests that define and check the inputs
      • Tests that define and check the outputs
    • Within the test file
      • A test with correct inputs
      • Wrong inputs
      • Exceptions
Continue reading “Testing in R”