首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >pytest独立导入不同测试文件中的同一模块

pytest独立导入不同测试文件中的同一模块
EN

Stack Overflow用户
提问于 2019-03-19 03:58:54
回答 1查看 745关注 0票数 2

下面的subject模块包含两个函数,其中一个处理全局变量。

mod.py:

代码语言:javascript
复制
def global_setter():
    global x
    x = 123
    print("setter x:", x)


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

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

test_1.py

代码语言:javascript
复制
import pytest

import mod


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

test_2.py

代码语言:javascript
复制
import pytest

import mod


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

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

代码语言:javascript
复制
$ 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

-

代码语言:javascript
复制
======================= 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 ========================

如果同时运行,则第二个测试将失败。

代码语言:javascript
复制
$ 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_函数进行最少更改的情况下实现它?上面的玩具示例说明了我在较大的代码库和许多测试中遇到的问题。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-19 04:07:35

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

您有几个选择。

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

的设置

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55229163

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档