KnowHow

技術的なメモを中心にまとめます。
検索にて調べることができます。

pythonテストコードの書き方(pytest)

登録日 :2025/07/22 19:15
カテゴリ :Python基礎

pytestでテストを書くサンプル
以下のcalculation.pyを、pytestを使ってテストをするサンプルコード

calculation.py

import os.path


class Cal(object):
    def __init__(self):
        self.test_string = 'test'

    def save_tmp_file(self, dir_path, file_name):
        if not os.path.exists(dir_path):
            os.mkdir(dir_path)
        file_path = os.path.join(dir_path, file_name)
        with open(file_path, 'w') as f:
            f.write(self.test_string)

    @staticmethod
    def add_num_and_double(x, y):
        if type(x) is not int or type(y) is not int:
            raise ValueError
        result = x + y
        result *= 2
        return result

pytsetを使って、calculation.pyをテストする
test_pytest_calculation.py

import os
import pytest
import importlib
from test.calculation import Cal


# def test_add_mum_and_double():
#     cal = calcuration.Cal()
#     assert cal.add_num_and_double(1, 1) != 4


class TestCal(object):
    @classmethod
    def setup_class(cls):
        print('Test start')
        cls.cal = Cal()
        cls.test_file_name = 'test.txt'

    @classmethod
    def teardown_class(cls):
        print('Test end')
        del cls.cal

    def setup_method(self, method):
        print('start method={}'.format(method.__name__))

    def teardown_method(self, method):
        print('end method={}'.format(method.__name__))

    def test_add_mum_and_double(self):
        assert self.cal.add_num_and_double(1, 1) == 4

    @pytest.mark.skip(reason='skip!')
    def test_add_num_and_double_raise(self):
        with pytest.raises(ValueError):
            self.cal.add_num_and_double('1', '1')

    def test_add_option(self, request):
        os_name = request.config.getoption('--os-name')
        print('test_add_option', os_name)

    def test_save(self, tmpdir):
        print('test_save', tmpdir)
        self.cal.save_tmp_file(tmpdir, self.test_file_name)
        test_file_path = os.path.join(tmpdir, self.test_file_name)
        assert os.path.exists(test_file_path) is True

    def test_original_fixture(self, csv_file):
        print(csv_file)
        assert self.cal.add_num_and_double(1, 1) == 4