How to access command line arguments from nonpython tests #8936
-
I'm writing something really similar to this yaml reader here: https://docs.pytest.org/en/6.2.x/example/nonpython.html Inside the YamlItem -> runtest method, I want to be able to check command line arguments.The old way before going to a plugin, I would load them as a fixture "cli_args" and pass that around to the testing method. I don't know how to pass a fixture into runtest, without getting "TypeError: init() missing 1 required positional argument: 'some-arg'". If it matters, I add a bunch of "addoption" in the pytest_addoption method, then load them to a dict with "request.config.getoption" inside the fixture. Maybe I can skip the fixture, and somehow access the getoption method inside this class? Here's the same exact example as in the link, in case you don't trust links / it gets moved: import pytest
def pytest_collect_file(parent, path):
if path.ext == ".yaml" and path.basename.startswith("test"):
return YamlFile.from_parent(parent, fspath=path)
class YamlFile(pytest.File):
def collect(self):
# We need a yaml parser, e.g. PyYAML.
import yaml
raw = yaml.safe_load(self.fspath.open())
for name, spec in sorted(raw.items()):
yield YamlItem.from_parent(self, name=name, spec=spec)
class YamlItem(pytest.Item):
def __init__(self, name, parent, spec):
super().__init__(name, parent)
self.spec = spec
def runtest(self):
for name, value in sorted(self.spec.items()):
#### NOTE: THIS is where I want to see what custom cli args I used <-------
# Some custom test execution (dumb example follows).
if name != value:
raise YamlException(self, name, value)
def repr_failure(self, excinfo):
"""Called when self.runtest() raises an exception."""
if isinstance(excinfo.value, YamlException):
return "\n".join(
[
"usecase execution failed",
" spec failed: {1!r}: {2!r}".format(*excinfo.value.args),
" no further details known at this point.",
]
)
def reportinfo(self):
return self.fspath, 0, f"usecase: {self.name}"
class YamlException(Exception):
"""Custom exception for error reporting.""" |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I finally found how to access the config, with this block of text here https://docs.pytest.org/en/6.2.x/deprecations.html#pytest-config-global. |
Beta Was this translation helpful? Give feedback.
I finally found how to access the config, with this block of text here https://docs.pytest.org/en/6.2.x/deprecations.html#pytest-config-global.
I'm guessing fixtures aren't supported with plugins. You're able to access the config through the pytest.Item that YamlItem is based on. It's just a self.config.getoption inside the runtest method.