Testing Python Programs using Pytest

Testing Python Programs using Pytest

Pytest: Pytest is a third-party testing framework and is widely used in the industry. It automatically discovers and executes test functions and supports advanced features such as fixtures, parameterized tests, and powerful plugins. Pytest is widely used in the Python community.

To use Pytest, we first need to install Pytest package.

Execute the below command in the terminal.

  1. Create a test file: Create a new Python file and name it something descriptive, such as test_file.py. This file will contain your test cases.

  2. Write test functions: In the test file, define test functions that start with test_ or end with _test. Each test function should perform specific assertions to check if your code behaves as expected.

    For example:

     import mainfile
    
     def test_multiply():
         result= mainfile.multiply(12,6)
         assert result==72
    
  3. Make sure to import the main file in the test file and use assert to store the expected test result.
    in our example we are importing mainfile as the python file containing the multiply function is mainfile.py

  4. Execute the test script by running the below command.