pytest_addoption
时间: 2023-09-24 20:09:55 浏览: 104
`pytest_addoption` is a hook function in pytest that allows you to define command-line options that can be used when running your tests. This function is called once at the beginning of the test session and can be used to add options to the `pytest` command.
You can use `pytest_addoption` to add custom options to `pytest`, such as specifying a test database, specifying a directory to search for test files, or specifying a test configuration file. These options can then be accessed in your test functions through the `request` fixture.
Here's an example of how to use `pytest_addoption` to add a custom `--env` option to `pytest`:
```python
# conftest.py
def pytest_addoption(parser):
parser.addoption("--env", action="store", default="dev",
help="Specify the test environment: dev, stage or prod")
# test_example.py
def test_example(request):
env = request.config.getoption("--env")
assert env == "dev"
```
In this example, we define a custom `--env` option in `pytest_addoption` and then use the `request` fixture to retrieve the value of this option in our test function. If no `--env` option is specified when running the tests, the default value of `"dev"` will be used.
阅读全文