1 minute read


To gain experience using Pytest I am going to write code that works like a calculator.

I will test it using pytest.

Then I’ll automate and streamline the test and delivery process.

You can find more articles of this series with the Pytest tag


Pre-requisites

Pytest is delivered as a python package and can be installed via pip. You will need to have a python interpreter installed.

Pytest looks for test in files that follow a specific naming convention.

  • If no arguments are specified then collection starts from testpaths (if configured) or the current directory. Alternatively, command line arguments can be used in any combination of directories, file names or node ids.
  • Recurse into directories, unless they match norecursedirs.
  • In those directories, search for test_*.py or *_test.py files, imported by their test package name.
  • From those files, collect test items:
    test prefixed test functions or methods outside of class
    test prefixed test functions or methods inside Test prefixed test classes (without an __init__ method)

Installation

To get started, let’s install pytest through pip via the cli


pip install pytest

Clone the code

You can clone the next repository in order to have code and tests ready to be fired with the push of a button.


git clone https://github.com/estebanherlein/introtopytest

Project Structure

Right now our project will consist of a file called calculator.py which holds the code to be tested, a file called test_calculator.py where we will write our tests and a readme.md file to hold important project information.


/
--/v1
	--calculator.py
	--test_calculator.py
--readme.md

Running our tests

To run our tests for the first time write this command on the cli while on the root folder of the cloned project


pytest

If you only want to run the tests located on the V1 folder you can change the current path of your cli to that folder to run the command from there.