简体   繁体   English

Py.Test包含配置文件

[英]Py.Test with configuration files

The title may be vague so I try to explain the scenario here. 标题可能含糊不清,所以我试着在这里解释一下这个场景。

I want to test an python module Foo on multiple devices. 我想在多个设备上测试一个python模块Foo。 I have created a test_Foo.py file. 我创建了一个test_Foo.py文件。

Now all these devices with Foo on it require different settings. 现在所有这些带有Foo的设备都需要不同的设置。 For example Device A needs to have Foo constructed & tested with param X and Device B needs to have Foo constructed & tested with param Y. Where the param is for example the device ID. 例如,设备A需要使用参数X构造和测试Foo,并且设备B需要使用参数Y构造和测试Foo。其中参数是例如设备ID。

Is it possible (and how) to control my test_Foo.py to use a configuration file. 是否可能(以及如何)控制我的test_Foo.py以使用配置文件。 I use YAML files as configuration for other modules, argparse.ArgumentParser, but I wonder I can use the same concept in Py.Test. 我使用YAML文件作为其他模块的配置,argparse.ArgumentParser,但我想我可以在Py.Test中使用相同的概念。

Do you have control of which command line parameters that will be used to invoke py.test in each environment? 您是否可以控制将在每个环境中调用py.test的命令行参数? If that's the case you can configure your test suit to add command line parameters that can in turn be used by other fixtures to configure themselves accordingly. 如果是这种情况,您可以配置您的测试套件以添加命令行参数,这些参数又可以被其他灯具用于相应地进行自我配置。

Please see an example here: http://pytest.org/latest/example/simple.html#pass-different-values-to-a-test-function-depending-on-command-line-options 请在此处查看示例: http//pytest.org/latest/example/simple.html#pass-different-values-to-a-test-function-depending-on-command-line-options

Adapting the example for your case, it would be something like: 根据您的情况调整示例,它将类似于:

# content of conftest.py
import pytest

def pytest_addoption(parser):
    parser.addoption("--device", action="store", 
        help="device: A or B")

@pytest.fixture
def param(request):
    device = request.config.getoption("--device")
    if device == 'A':
        return X()
    elif device == 'B':
        return Y()

And now for your test file: 现在为您的测试文件:

# contents of test_Foo.py
def test_Foo(param):
    foo = Foo(param)
    # test foo

This allows you to invoke py.test like this: 这允许你像这样调用py.test

py.test --device=A

And the that would make test_Foo receive a X object. 这将使test_Foo收到一个X对象。

You can of course extend this to receive an yaml filename instead and read the options from there, implementing a fixture accordingly. 您当然可以扩展它以接收yaml文件名,并从那里读取选项,相应地实现一个夹具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM