pytest usage summary

I had rarely written ** "test code" ** until now, but I had the opportunity to write python test code and learned how to use it in a hurry. In this article, I've focused on how to use pytest, a framework for unit testing python.

Reference: Official documentation (https://docs.pytest.org/en/latest/contents.html)


What is pytest

A framework for unit testing in python. There is a similar one called unittest, but pytest seems to be more popular. The following are the features of pytest

--Detailed information when the test fails --Automatically discover modules and functions to be tested --By using the fixture function, you can pre-process tests such as mocking. (See below) --Compliant with unittest

Installation

pip install -U pytest

Easy to use

Simple unit test

Basically, you can run the test as follows.

--Write the test case with ʻassert --Runpytest`

If you enter the file name and method name in test_ *, the test code will be found automatically (you can specify it yourself).

test_sample.py


def func(x):
    return x + 1

def test_answer():
    assert func(3) == 5

Create the above test_sample.py file and Run pytest.

Then, the following test result is displayed.

Test results
========================================== test session starts ===========================================
platform darwin -- Python 3.7.6, pytest-5.4.3, py-1.8.1, pluggy-0.13.1
rootdir: /Users/xin/work/study/pytest
plugins: hypothesis-5.5.4, arraydiff-0.3, remotedata-0.3.2, openfiles-0.4.0, doctestplus-0.5.0, astropy-header-0.1.2
collected 1 item                                                                                         

test_sample.py F                                                                                   [100%]

================================================ FAILURES ================================================
______________________________________________ test_answer _______________________________________________

    def test_answer():
>       assert func(3) == 5
E       assert 4 == 5
E        +  where 4 = func(3)

test_sample.py:5: AssertionError
======================================== short test summary info =========================================
FAILED test_sample.py::test_answer - assert 4 == 5
=========================================== 1 failed in 0.18s ============================================

Exception handling test

Exception testing is possible with pytest.raises

error_sample.py


import pytest

def f():
    raise SystemExit(1)

def test_mytest():
    with pytest.raises(SystemExit):
        f()

Running multiple tests in a class

By creating a class with Test as a prefix, you can test the internal test methods at the same time.

test_class.py


class TestClass:
    def test_one(self):
        x = "this"
        assert "h" in x

    def test_two(self):
        x = "hello"
        assert hasattr(x, "check")

fixture

What is a fixture?

A tool provided to set up the test execution environment. I will pick up some useful ones. See below for details (https://docs.pytest.org/en/latest/fixture.html)

tmpdir The tmpdir fixture allows you to create a unique directory that is temporarily available during testing.

test_tempdir.py


import os

def test_create_file(tmpdir):
    p = tmpdir.mkdir("sub").join("hello.txt") #Creating a temporary directory
    p.write("content")
    assert p.read() == "content"
    assert len(tmpdir.listdir()) == 1
    assert 0

monkeypatch The monkeypatch fixture allows you to mock an object. For example, suppose you have the following product code, and one get_value () is a function that cannot be easily executed.

monkeypatch_product.py


def return_value(): #Product code
    a = get_value()
    return a

def get_value(): #Functions that cannot be easily executed
    return 1

At this time, you can execute the test by replacing get_value () with your own mock function by using monkeypatch.setattr.

monkeypatch_test.py


import monkeypatch_product

#Test code
def test_return_value(monkeypatch):
    def mock_get_value():
        return 100

    #Replaced with mock function
    monkeypatch.setattr(monkeypatch_product, "get_value", mock_get_value)
    res = monkeypatch_product.return_value()
    assert res == 100

You can also mock environment variables with monkeypatch.setenv.

monkeypatch_env.py


import os

#Product code
def get_os_user_lower():
    username = os.getenv("USER")

    if username is None:
        raise OSError("USER environment is not set.")

    return username.lower()

#Test code
def test_get_os_user_lower(monkeypatch):
    monkeypatch.setenv("USER", "TestingUser")
    assert get_os_user_lower() == "testinguser"

Recommended Posts

pytest usage summary
pytest summary
Summary of pyenv usage
pandas Matplotlib Summary by usage
Super basic usage of pytest
pytest
Convenient usage summary of Flask
Pipenv usage summary (for myself)
Basic usage of Pandas Summary
Installation and easy usage of pytest
Python Summary
samba summary
Django Summary
python-pptx summary
pytest memo
Linux Summary
Python summary
Django Summary
pyenv summary
String summary 1
matplotlib summary