I have a code and I need to pass the arguments like name from terminal. Here is my code and how to pass the arguments. I am getting a "File not found" kind error that I don't understand.
I have tried the command in the terminal: pytest <filename>.py -almonds
I should get the name printed as "almonds"
@pytest.mark.parametrize("name") def print_name(name): print ("Displaying name: %s" % name)
ArgumentParser(description="run test on --host") parser. add_argument('--host', help='host to run tests on (default: %(default)s)', default=DEFAULT_HOST) args, notknownargs = parser. parse_known_args() if notknownargs: print("pytest arguments? : {}".
You can pass arguments to fixtures with the params keyword argument in the fixture decorator, and you can also pass arguments to tests with the @pytest.
you can put @pytest. mark. parametrize style parametrization on the test functions to parametrize input/output values as well.
In Python, arguments are passed to a script from the command line using the sys package. The argv member of sys ( sys.argv) will store all the information in the command line entry and can be accessed inside the Python script. Python’s getopt module can also be used to parse named arguments. Let’s go through some examples.
Then you can run from the command line with a command line argument: pytest -s tests/my_test_module.py --name abc Share Improve this answer Follow edited May 28 '19 at 21:06
This will execute all tests in all files whose names follow the form test_*.py or \*_test.py in the current directory and its subdirectories. More generally, pytest follows standard test discovery rules.
Also, there is no need to print result in your function in test cases. Note3: pytest is a module run by python, which is not able to get sys.argv directly
In your pytest test, don't use @pytest.mark.parametrize
:
def test_print_name(name): print ("Displaying name: %s" % name)
In conftest.py
:
def pytest_addoption(parser): parser.addoption("--name", action="store", default="default name") def pytest_generate_tests(metafunc): # This is called for every test. Only get/set command line arguments # if the argument is specified in the list of test "fixturenames". option_value = metafunc.config.option.name if 'name' in metafunc.fixturenames and option_value is not None: metafunc.parametrize("name", [option_value])
Then you can run from the command line with a command line argument:
pytest -s tests/my_test_module.py --name abc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With