在测试中创建和导入辅助函数,而无需使用 py.test 在测试目录中创建包 [英] Create and import helper functions in tests without creating packages in test directory using py.test

查看:20
本文介绍了在测试中创建和导入辅助函数,而无需使用 py.test 在测试目录中创建包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

如何在测试文件中导入辅助函数而不在 test 目录中创建包?

How can I import helper functions in test files without creating packages in the test directory?


上下文

我想创建一个可以在多个测试中导入的测试辅助函数.比如说,像这样:

I'd like to create a test helper function that I can import in several tests. Say, something like this:

# In common_file.py

def assert_a_general_property_between(x, y):
    # test a specific relationship between x and y
    assert ...


# In test/my_test.py

def test_something_with(x):
    some_value = some_function_of_(x)
    assert_a_general_property_between(x, some_value)

使用 Python 3.5 和 py.test 2.8.2


当前的解决方案"

我目前通过在我的项目的 test 目录(现在是一个包)中导入一个模块来做到这一点,但如果可能的话,我想用其他一些机制来做到这一点(以便我的 test 目录没有包,只有测试,并且测试可以在已安装的包版本上运行,推荐 这里是关于良好实践的 py.test 文档).

I'm currently doing this via importing a module inside my project's test directory (which is now a package), but I'd like to do it with some other mechanism if possible (so that my test directory doesn't have packages but just tests, and the tests can be run on an installed version of the package, as is recommended here in the py.test documentation on good practices).

推荐答案

我的选择是在 tests 目录中创建一个额外的目录,然后将其添加到 conftest 中的 pythonpath 中.

my option is to create an extra dir in tests dir and add it to pythonpath in the conftest so.

tests/
    helpers/
      utils.py
      ...
    conftest.py
setup.cfg

conftest.py

import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), 'helpers'))

setup.cfg

[pytest]
norecursedirs=tests/helpers

这个模块可以通过 import utils 使用,只需要注意名称冲突.

this module will be available with import utils, only be careful to name clashing.

这篇关于在测试中创建和导入辅助函数,而无需使用 py.test 在测试目录中创建包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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