gpt4 book ai didi

python - 具有全局固定装置时,如何将 Python 单元测试转换为 pytest?

转载 作者:太空狗 更新时间:2023-10-30 02:45:22 24 4
gpt4 key购买 nike

我确实有一组使用 Python 的 unittest 模块编写的单元测试。他们使用 setUpModule() 函数加载一个全局变量,其中包含运行测试(包括一些 HTTP session )所需的共享“内容”。

当使用 unittest 运行我的测试时,它们运行良好。使用 py.test 他们失败了。

我对它进行了一些修补,使其使用旧的 pytest fixture 函数(碰巧与 unittest 的名称不同)运行。它有效,但仅当未在多个线程上执行时有效,这是我确实想使用的功能。

文档示例对我来说毫无用处,因为我确实有大约 20 个类 (unittest.TestCase),每个类中有 10 个测试。显然我不想为每个测试添加一个新参数。

到目前为止,我使用类 setUp() 方法在 self 中加载共享字典,并在每个测试中从那里使用它。

#!/usr/bin/env python
# conftest.py
@pytest.fixture(scope="session")
def manager():
return { "a": "b"}

现在是测试:

#!/usr/bin/env python
# tests.py

class VersionTests(unittest.TestCase):

def setUp(self):
self.manager = manager

def test_create_version(self):
# do something with self.manager
pass

请记住,我需要一个适用于多线程的解决方案,一次调用 fixture 。

最佳答案

pytest 确实可以运行 unittest 测试,如 Support for unittest.TestCase / Integration of fixtures 中所述.棘手的部分是使用 pytest funcargs fixtures直接不鼓励:

While pytest supports receiving fixtures via test function arguments for non-unittest test methods, unittest.TestCase methods cannot directly receive fixture function arguments as implementing that is likely to inflict on the ability to run general unittest.TestCase test suites.

假设我们有一个这样的测试模块,使用标准的 unittest 初始化工具:

# test_unittest_tests.py (for the sake of clarity!)
import unittest

manager = None

def setUpModule():
global manager
manager = {1: 2}

class UnittestTests(unittest.TestCase):
def setUp(self):
self.manager = manager

def test_1_in_manager(self):
assert 1 in self.manager

def test_a_in_manager(self):
assert 'a' in self.manager

当使用 unittest 运行时,它会产生以下输出:

$ python -m unittest -v test_unittest_tests
...
test_1_in_manager (test_unittest_tests.UnittestTests) ... ok
test_a_in_manager (test_unittest_tests.UnittestTests) ... FAIL
...

test_a_in_manager 按预期失败。 manager 目录中没有任何 'a' 键。

我们设置了一个 conftest.py 来为这些测试提供范围内的 pytest fixture。例如,在不破坏标准 unittest 行为的情况下,根本不需要使用 pytest autouse 来测试它们。 :

# conftest.py
import pytest

@pytest.fixture(scope='session', autouse=True)
def manager_session(request):
# create a session-scoped manager
request.session.manager = {'a': 'b'}

@pytest.fixture(scope='module', autouse=True)
def manager_module(request):
# set the sessions-scoped manager to the tests module at hand
request.module.manager = request.session.manager

使用 pytest(使用 pytest-xdist)运行测试进行并行化,产生以下输出:

$ py.test -v -n2
...
[gw1] PASSED test_unittest_tests.py:17: UnittestTests.test_a_in_manager
[gw0] FAILED test_unittest_tests.py:14: UnittestTests.test_1_in_manager
...

现在 test_1_in_manager 失败了; pytest 提供的管理器字典中没有任何 1 键。

关于python - 具有全局固定装置时,如何将 Python 单元测试转换为 pytest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24838948/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com