【问题标题】:pytest independent import of the same module from different test filespytest 从不同的测试文件中独立导入同一个模块
【发布时间】:2019-08-09 06:45:39
【问题描述】:

以下主题模块包含两个函数,其中一个操作全局变量。

mod.py:

def global_setter():
    global x
    x = 123
    print("setter x:", x)


def global_getter():
    print("getter x:", x)

每个函数都有一个测试文件。

test_1.py

import pytest

import mod


def test_set_x():
    mod.global_setter()
    assert mod.x == 123

test_2.py

import pytest

import mod


def test_get_x():
    with pytest.raises(NameError):
        mod.global_getter()

如果单独运行,这些测试通过

$ pytest -s -v test_1.py
========================== test session starts ==========================
platform linux -- Python 3.6.7, pytest-4.3.1, py-1.8.0, pluggy-0.9.0 -- /usr/bin/python3
cachedir: .pytest_cache
rootdir: /mnt/temp/test, inifile:
collected 1 item

test_1.py::test_set_x setter x: 123
PASSED

-

======================= 1 passed in 0.03 seconds ========================
$ pytest -s -v test_2.py
========================== test session starts ==========================
platform linux -- Python 3.6.7, pytest-4.3.1, py-1.8.0, pluggy-0.9.0 -- /usr/bin/python3
cachedir: .pytest_cache
rootdir: /mnt/temp/test, inifile:
collected 1 item

test_2.py::test_get_x PASSED

======================= 1 passed in 0.02 seconds ========================

如果一起运行,第二个测试失败。

$ pytest -s -v test_1.py test_2.py
========================== test session starts ==========================
platform linux -- Python 3.6.7, pytest-4.3.1, py-1.8.0, pluggy-0.9.0 -- /usr/bin/python3
cachedir: .pytest_cache
rootdir: /mnt/temp/test, inifile:
collected 2 items

test_1.py::test_set_x setter x: 123
PASSED
test_2.py::test_get_x getter x: 123
FAILED

=============================== FAILURES ================================
______________________________ test_get_x _______________________________

    def test_get_x():
        with pytest.raises(NameError):
>           mod.global_getter()
E           Failed: DID NOT RAISE <class 'NameError'>

test_2.py:8: Failed
================== 1 failed, 1 passed in 0.08 seconds ===================

似乎导入模块的状态在测试和测试文件之间存在差异。

为什么会发生这种情况,有没有办法告诉 pytest 为每个测试文件独立导入模块?如果是这样,有什么方法可以通过对 test_ 函数的最小更改来完成它?上面的玩具示例说明了一个问题,即我在具有大量测试的较大代码库中遇到的问题。

【问题讨论】:

  • 这是包的预期行为,您应该查看monkeypatching,它将为您优雅地处理此问题

标签: python pytest python-import


【解决方案1】:

这是意料之中的,因为通过 pytest 运行的所有测试都在单个进程中运行,并且您的第一个测试是通过将 x 添加到全局命名空间来改变全局状态。

您有几个选择。

  1. 重构您的代码以不使用全局变量。或者至少,将它封装在一个易于模拟的类中。
  2. 使用像pytest-xdist(参见Run py.test test in different process)这样的框架,它可以确保您的测试在不同的进程中运行。
  3. 在您的第二次测试之前添加一个夹具,这会显式取消设置全局变量x

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多