如何为py.test中的所有测试跨模块共享变量 [英] how to share a variable across modules for all tests in py.test

查看:77
本文介绍了如何为py.test中的所有测试跨模块共享变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个由 py​​.test 运行的测试,这些测试位于多个文件的多个类中.

I have multiple tests run by py.test that are located in multiple classes in multiple files.

与 py.test 使用的每个文件中每个类的每个方法共享一个大字典的最简单方法是什么 - 我不想复制它?

What is the simplest way to share a large dictionary - which I do not want to duplicate - with every method of every class in every file to be used by py.test?

简而言之,我需要为每个测试创建一个全局变量".在 py.test 之外,我没有使用这个变量,所以我不想将它存储在被测试的文件中.我经常使用 py.test 的装置,但这对于这种需求来说似乎有点过分了.也许这是唯一的方法?

In short, I need to make a "global variable" for every test. Outside of py.test, I have no use for this variable, so I don't want to store it in the files being tested. I made frequent use of py.test's fixtures, but this seems overkill for this need. Maybe it's the only way?

推荐答案

更新:pytest-namespace 钩子已弃用/删除.请勿使用.有关详细信息,请参阅 #3735.

您提到了一个显而易见且最不神奇的选择:使用夹具.您可以在您的模块中使用 pytestmark = pytest.mark.usefixtures('big_dict') 将其应用到整个模块,但它不会在您的命名空间中,因此明确请求它可能是最好的.

You mention the obvious and least magical option: using a fixture. You can apply it to entire modules using pytestmark = pytest.mark.usefixtures('big_dict') in your module, but then it won't be in your namespace so explicitly requesting it might be best.

或者,您可以使用钩子将内容分配到 pytest 命名空间:

Alternatively you can assign things into the pytest namespace using the hook:

# conftest.py

def pytest_namespace():
    return {'my_big_dict': {'foo': 'bar'}}

现在你有了 pytest.my_big_dict.不过,夹具可能仍然更好.

And now you have pytest.my_big_dict. The fixture is probably still nicer though.

这篇关于如何为py.test中的所有测试跨模块共享变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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