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

davka
  • 13,974
  • 11
  • 61
  • 86

2 Answers2

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

Rakibul Islam
  • 954
  • 1
  • 14
  • 25
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.

knh190
  • 2,744
  • 1
  • 16
  • 30