unittest.TestCase类内部的参数化夹具

时间:2020-08-01 16:57:54

标签: python python-3.x unit-testing pytest python-unittest

我正在使用pytest,并且想使用参数化的pytest固定装置。如果我不使用类并运行pytest,则两个测试均会通过,但是在测试类中时,两个测试均会失败,但我无法弄清楚出了什么问题。

工作代码:

import pytest

@pytest.fixture
def db_fixture():
    def insert_records(data):
        return data
    db = insert_records
    yield db
    db = {}  # reset fixture


def test_create_record_one(db_fixture):
    result = db_fixture({"id": 1})
    assert result == {"id": 1}


def test_create_record_two(db_fixture):
    result = db_fixture({"id": 2})
    assert result == {"id": 2}

无效的代码:

import pytest
import unittest

class TestSample(unittest.TestCase):

    @staticmethod
    @pytest.fixture
    def db_fixture():
        def insert_records(data):
            return data
        db = insert_records
        yield db
        db = {}  # reset fixture

    @staticmethod
    def test_create_record_one(db_fixture):
        result = db_fixture({"id": 1})
        assert result == {"id": 1}

    @staticmethod
    def test_create_record_two(db_fixture):
        result = db_fixture({"id": 2})
        assert result == {"id": 2}

错误:

TypeError: test_create_record_one() missing 1 required positional argument: 'db_fixture'

1 个答案:

答案 0 :(得分:1)

您不能将unittest.TestCasepytest固定装置混合使用。尽管pytest知道unittest并可以基于unittest.TestCase执行有效的单元测试,但事实并非如此。

对于您而言,只需不要从unittest.TestCase中得出:

class TestSample:

    @staticmethod
    @pytest.fixture
    def db_fixture():
        def insert_records(data):
            return data
        db = insert_records
        yield db
        db = {}  # reset fixture

    @staticmethod
    def test_create_record_one(db_fixture):
        result = db_fixture({"id": 1})
        assert result == {"id": 1}
    ...