Introduction to testing with Pytest on Colab
Pytest is a powerful testing tool for Python that can be used to test everything from individual functions and classes to entire applications. In this tutorial, you will learn how to use Pytest to write and run tests for your Python code.
Why do we need Pytest?
Pytest makes it easy to identify and isolate problems in your code, and helps you find and fix them faster.
How does it work?
Pytest can be installed using pip:
sudo pip install pytest
To run tests using pytest , run the pytest command from the command line:
This will run all of the tests in the current directory. To run a Pytest for a specific test file or test module specifying the filename or module name as a command-line argument as shown below will suffice:
Running Pytest in Colab:
Let’s say we have a function load_csv to read from a file in CSV format to create a Pandas dataframe. We have 3 scenarios for the function to behave in:
- If the dataframe is successfully created then the function returns a value of 1
- If the file does not exist in the file path specified, then it returns 2
- If the file is empty/ any other error, then return 3
The code corresponding to the 3 possible situations is shown below:
The logs in this case look something like:
Writing a Pytest on Colab:
We convert the cell containing function load_csv to a python file for it to behave like an individual test file. This can be achieved by adding %%file testfilename.py at the top of the code cell.
Example: %%file test_file_load.py
Upon execution, we can see that a python file has been created in the working directory.
And the function call is made from within a Class object. An assertion is made on the expected return value/ result of the function call, as shown in the code snippet below:
A Pytest for this particular python file can be carried out by typing in the next cell:
!python -m pytest test_file_load.py
Voila! And the test result is:
Watch it in action:
Feel free to access the notebook via the link: https://github.com/1382Lubster/pytest/blob/main/pytest_demo.ipynb
 docs.pytest.org. (n.d.). The writing and reporting of assertions in tests — pytest documentation. [online] Available at: https://docs.pytest.org/en/6.2.x/assert.html [Accessed 30 Jan. 2022].
 Marketing, J.P.G.A.D.S.B. 2019 G.I. passionate about digital, Data-Driven, H.B.B.M., Analytics, A.I. in L. and Change, D.S. to D.A. (2020). The Complete List Of Python Assert Statements. [online] Just Understanding Data. Available at: https://understandingdata.com/list-of-python-assert-statements-for-unit-tests/ [Accessed 30 Jan. 2022].
Connect with me on https://www.linkedin.com/in/lubna-khan-59843569/ to discuss more on this topic.