RvdK
RvdK

Reputation: 19790

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. I have created a test_Foo.py file.

Now all these devices with Foo on it require different settings. 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.

Is it possible (and how) to control my test_Foo.py to use a configuration file. I use YAML files as configuration for other modules, argparse.ArgumentParser, but I wonder I can use the same concept in Py.Test.

Upvotes: 9

Views: 12170

Answers (1)

Bruno Oliveira
Bruno Oliveira

Reputation: 15245

Do you have control of which command line parameters that will be used to invoke py.test in each environment? 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

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 --device=A

And the that would make test_Foo receive a X object.

You can of course extend this to receive an yaml filename instead and read the options from there, implementing a fixture accordingly.

Upvotes: 12

Related Questions