python - Py.test 掩码缺少导入

标签 python unit-testing import pytest

我有一段带有广泛测试套件的代码,我们使用 py.test 运行它。我最近遇到一个问题,一个新模块应该导入一个不同的模块才能正常运行。但是,因为该模块是在测试套件的其他地方导入的,所以 py.test 没有引发错误。直到很久以后,这个错误才出现。我创建了一个最小的可重现示例。

最小可重现示例

项目结构:

set.py
fail/
  __init__.py
  thing.py
  other.py
tests/
  test_thing.py
  test_other.py

这些文件包含以下代码:

失败/thing.py:

import fail

def needs_do_it():
    return fail.other.do_it() + 100

失败/other.py:

def do_it():
    return 100

tests/test_thing.py:

import fail.thing

def test_needs_do_it():
    assert fail.thing.needs_do_it() == 200

tests/test_other.py:

import fail.other

def test_do_it():
    assert fail.other.do_it() == 100

预期行为

如果您尝试运行 needs_do_it 函数,您应该得到一个错误, 因为只导入了fail,而不是fail.other:

>>> import fail.thing
>>> fail.thing.needs_do_it()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "fail/thing.py", line 4, in needs_do_it
    return fail.other.do_it() + 100
AttributeError: 'module' object has no attribute 'other'

那么,我希望在 py.test 下运行的测试会暴露 导入时出现此错误。然而,它完全掩盖了这个问题。

实际行为

因为 test_other.py 导入了 test.other,py.test 屏蔽了错误。

$ py.test

========== test session starts ==========
platform darwin -- Python 2.7.13, pytest-3.1.2, py-1.4.34, pluggy-0.4.0
rootdir: /Users/eswanson/Sandbox/pytest-test, inifile:
collected 2 items

tests/test_other.py .
tests/test_thing.py .
========== 2 passed in 0.01 seconds ==========

我的问题

我的问题分为三个部分:

  1. 此问题的根本原因是什么?
  2. 这是 py.test 的预期行为还是我应该提出问题?
  3. 作为 pytest 的用户,我能做些什么来更好地保证我将来不会搞砸进口

最佳答案

在 Python shell 中导入 fail.other 时也会发生同样的事情,因为 Python 模块是单例:

>>> import fail.thing
>>> fail.thing.needs_do_it()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/florian/tmp/fo/fail/thing.py", line 4, in needs_do_it
    return fail.other.do_it() + 100
AttributeError: module 'fail' has no attribute 'other'
>>> import fail.other
>>> fail.thing.needs_do_it()
200

关于python - Py.test 掩码缺少导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44548293/

相关文章:

javascript - jQuery TestSwarm 的现状?

drupal - 如何在 Drupal 中导入 View ?

java - 导入问题 Java TTest

android - 库不可导入

python - 如何让 VSCode 自动重新加载外部 *.py 模块?

python - 是否可以在脚本中获取特定 nautilus 窗口的目录?

java - 使用 JUnit 进行数据库单元测试

unit-testing - 在 spock 测试中创建不会作为测试运行的辅助方法

python - 切片查询集与切片 __in 子句中使用的列表相同吗?无法理解这种行为

python - 如何使用 Opencv 捕获帧