1

Say I have this test in tests.py

def test_user(username='defaultuser'):

Case 1

I want to pass the username to test from the command line, something like

$ pytest tests.py::test_user user1  # could be --username=user1

How do I do that?

Case 2

I want to pass a list of usernames to test, like

$ pytest tests.py::test_user "user1, user2, user3"

I want to achieve something like

@pytest.mark.parametrize("username", tokenize_and_validate(external_param))
def test_user(username):
    pass

def tokenize_and_validate(val):
    if not val:
        return 'defaultuser'
    return val.split(',')

How can I do that?

Thank you

1

2 Answers 2

2

When you pass a parameter from the command line at first you need to create a generator method to get the value from the command line this method run every test.

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

Follow the link for more details

Sign up to request clarification or add additional context in comments.

1 Comment

thanks! I guess I also need to add the "--name" option as in the solution you copied
0

To mock the data, you can use fixtures or use builtin unittest mocks.

from unittest import mock

@mock.patch(func_to_mock, side_effect=func_to_replace)
def test_sth(*args):
    pass

Command line options are also available.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.