2017-06-14 65 views
3

我有一段代码,它有一个广泛的测试套件,我们使用py.test来运行它。我最近遇到了一个问题,那就是一个新的模块应该导入一个不同的模块来正确运行。但是,由于该模块是在测试套件的其他地方导入的,因此py.test不会引发错误。直到很久以后,这个bug才出现。我创建了一个最小可重现的例子。Py.test掩码缺少进口

最小可重复实施例

项目结构:

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

如果这些文件包含以下代码:

fail/thing.py

import fail 

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

fail/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_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 ========== 

我的问题

我quesiton分为三个部分:

  1. 这是什么问题的根本原因是什么?
  2. 这是py.test的预期行为还是我应该提出一个问题?
  3. 有什么我可以做pytest的用户,我得到更好的保证,我不会在未来搞砸了进口

回答

0

同样的事情发生时,你在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