独立的 py.test(忽略 __init__.py 文件) [英] standalone py.test (ignore __init__.py files)

查看:61
本文介绍了独立的 py.test(忽略 __init__.py 文件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 python 模块(我们称之为 M1),它是独立的(唯一的导入是到 collections),在一个包含丑陋的包中.部分丑陋之处在于包的 __init__.py 文件中.但是 M1 很好很干净,并且包含一些与 py.test 一起使用的测试函数.

I have a simple python module (let's call it M1) which is standalone (the only import is to collections), inside a package containing ugliness. Part of the ugliness is in the package's __init__.py file. But M1 is nice and clean, and contains some test functions for use with py.test.

现在,我想测试M1并忽略所有丑陋.但是 py.test 想要运行 __init__.py -- 有什么办法可以防止这种情况发生?我真的无法修复 __init__.pycode> 文件,并且我希望将我的测试函数与 M1 模块内容本身一起包含.

Now, I would like to test M1 and ignore all the ugliness. But py.test wants to run __init__.py -- is there any way I can prevent this? I really can't fix the __init__.py file at this time, and I want to keep my test functions contained right alongside the M1 module contents itself.

我已经阅读过这个问题:`py.test` 和 `__init__.py` 文件解释了问题但没有提供解决方案.

I've already read this SO question: `py.test` and `__init__.py` files which explains the issue but offers no solution.

我的 __init__.py 文件看起来像这样;它只是将项目推广到包装范围:

my __init__.py file looks something like this; it's just promoting items into package scope:

from .M1 import CleanThing1, CleanThing2
from .Evil1 import UglyThing1, UglyThing2

问题是 Evil1 模块需要一些 PYTHONPATH 黑客才能正确执行,当我运行时

and the problem is that the Evil1 module requires some PYTHONPATH hackery to execute properly, and when I run

py.test mymodule/M1.py

由于 Evil1 模块而失败.但我现在只想测试 M1 模块.

it fails because of the Evil1 module. But I just want to test the M1 module right now.

推荐答案

您可以使 __init__.py 文件知道 py.test,如此处.

You can make the __init__.py file aware of py.test as described here.

所以基本上创建一个具有以下内容的 mymodule/conftest.py 文件

So basically create a mymodule/conftest.py file with the following content

def pytest_configure(config):
    import sys
    sys._called_from_test = True

def pytest_unconfigure(config):
    del sys._called_from_test

并在 __init__.py 文件中简单地检查您是否在 py.test 会话中,如

and in the __init__.py file simply check if you are inside the py.test session like

import sys
if hasattr(sys, '_called_from_test'):
    # called from within a test run
    pass
else:
    # failing imports
    from .M1 import CleanThing1, CleanThing2
    from .Evil1 import UglyThing1, UglyThing2

这样我就可以在没有导入错误的情况下运行 py.test mymodule/M1.py.

This way I could run py.test mymodule/M1.py without the import errors.

包结构现在看起来像(我希望类似于你的结构)

The package structure now looks like (I hope that resembles your structure)

package
   |   
   |- __init__.py
   |- mymodule/
         |- M1.py
         |- conftest.py  

这篇关于独立的 py.test(忽略 __init__.py 文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆