Publicado en Testing

Unit Tests

In this blogpost we will be talking about unit test in python, specifically, unittest python framework. Testing our code is really important because it can reveal unexpected outcomes or weird behaviors on our code. Let’s take for example the file calc.py which has the following functions.

Screen Shot 2019-02-02 at 1.03.08 PM

As we can see there are just basic arithmetic functions. Now we create the file test_calc.py to test if our functions are working as expected. Once we create the file we import the unittest library and our previously created file, calc.

Screen Shot 2019-02-02 at 1.08.11 PM.png

We now create or testing class, this can have the name you want as long as it inherits form unittest.Testcase. The methods in this class will test our functions from calc.py, methods in the test file must start with the word test followed by an underscore and then the name you want, by convention we use the name of the function to test. Let’s take the following example test_calc.py.

Screen Shot 2019-02-02 at 1.24.50 PM

The first thing you see in every method is the self.assertEqual(arguments), this function test the given function with the given values and what it should return, for example let’s take the following function.

Screen Shot 2019-02-02 at 1.29.42 PM

In this line of code we are calling the assertEqual function then the first argument is the function to evaluate, in this case is calc.add with the given parameters, in this case 10 and 5. The next argument is the output that the function must return. Now let’s run our test file to check if our methods are working as expected. We use the following command to run the test file.

Screen Shot 2019-02-02 at 1.32.17 PM

If all test are correct we will have the following output in our terminal.

Screen Shot 2019-02-02 at 1.37.10 PM.png

Where the top points mean that every test was successfully passed, if one or more tests are not passed, then a F will appear instead of the period.

Deja un comentario