Python 检查模块是否作为(单元)测试启动
我编写了自己的模块,我们称之为Python 检查模块是否作为(单元)测试启动,python,python-import,Python,Python Import,我编写了自己的模块,我们称之为mymodule。为了改进它是否工作,我编写了测试。这就是结构的演变: django-mymodule |-mymodule (.py files in here) |-tests (.py files in here, they are unittests) |-... (docs and this stuff) 当模块安装到我的计算机时,我必须使用如下相对导入:来自。导入其他文件。当它作为测试启动时,导入必须如下所示:import otherfile。 因此,
mymodule
。为了改进它是否工作,我编写了测试
。这就是结构的演变:
django-mymodule
|-mymodule (.py files in here)
|-tests (.py files in here, they are unittests)
|-... (docs and this stuff)
当模块
安装到我的计算机时,我必须使用如下相对导入:来自。导入其他文件
。当它作为测试启动时,导入必须如下所示:import otherfile
。
因此,我必须这样做:
if is_run_as_test:
import otherfile
else:
from . import otherfile
这个
是如何运行的?还是我真的做错了什么?您可以通过检查您的测试框架是否已导入来实现这一点
在常规代码中导入它会很奇怪,因此可以假设代码正在测试期间运行
if 'unittest' in locals():
print('I am being run within a test')
我完全错了。我要做的是将整个包导入pythonpath,然后使用绝对导入。(当然是在测试文件中。)
这意味着:
- 我的模块中的相对导入没有问题
- 我不必为了能做测试而把模块搞得一团糟(这并不是一个好主意)
- 我可以从测试中访问模块
因此我在mymodule
中使用from.import somefile
。在测试中我添加了以下代码:
import unittest
import sys
sys.path.insert(0, '../../django-mymodule')
from mymodule import file1
感谢您的提示!如果您不测试代码时代码运行方式不同,您将如何测试代码?它不会运行方式不同,这只是因为使用python3-m unittest tests/test\u file1有不同的导入方式(在shell中)当我安装了这个模块时——正如这里所解释的:如果你的代码是python包格式的,那么你可以使用绝对导入,然后你可以从项目根目录运行测试。一开始我不理解你的第二篇文章,但现在当我知道该做什么时,它真的很清楚。谢谢你的帮助!这看起来不错,但对我来说不起作用。tests/file1
中的导入(现在):import unittest
,import sys
,sys.path.insert(0,../mymodule')
,import file1
中的导入:如果本地语言为'unittest'():从链接导入RawTextLink,RenderedTextLink其他:从。链接导入RenderedTextLink,RenderedTextLink
我做错了什么?