Can arbirary configuration for tests be set in pytest.ini?

房东的猫 提交于 2021-02-10 07:45:45

问题


I want to centralize configuration for my tests and it seems like pytest.ini would be the place but im having trouble finding an example/feature for this.

For example I have a directory with files my tests might need called "test_resources". this is my structure:

├── pytest.ini
├── myproject
│    └── someFunctionsOne
│        ├── one.py
│        └── two.py
└── tests
    ├── integration
    │   └── someFunctionsOneTestblah.py
    ├── test_resources
    │   ├── sample-data.json
    │   └── test-data-blahablahb.csv
    └── unit
        └── someFunctionsOne
            ├── one.py
            └── two.py

I want to set the path of "test_resources" in pytest.ini. So integration and unit tests know where to find that folder- I'd like to avoid hard coding paths like this in my test files themselves.

Is there a feature to set arbitrary config in pytest.ini and retrieve it from tests? I suspect I might have other config settings like this for my tests and if all that lives in the pytest.ini file that makes things much clearer for other devs on this project- one place to go for all test configuration stuff. I already have a configuration file for my application which is loaded when it starts but thats different. I want to isolate the unit/integration test config from my application config. pytest.ini seems like the best place because its already there and used by the tests. This way I dont need to create another config file and roll my own mechanism for loading it for the tests

Also, I know there is nothing preventing me from using configparser or even loading and parsing pytest.ini myself but if tests are already using it I was hoping there would be a built in feature to read arbitrary kvs from it or something like that


回答1:


You define custom keys in pytest.ini same way as you define custom command line arguments, only using the Parser.addini method:

# conftest.py

def pytest_addoption(parser):
    parser.addini("mykey", help="help for my key", default="fizz")

(Note that pytest_addoption hook impls should be located in the top-level conftest.py).

You now can define mykey in pytest.ini:

[pytest]
mykey = buzz

Access mykey value in tests:

def test_spam(request):
    value = request.config.getini("mykey")
    assert value == "buzz"


来源:https://stackoverflow.com/questions/61432346/can-arbirary-configuration-for-tests-be-set-in-pytest-ini

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!