'How to make pytest not to read tests directory as command line argument?

When I am trying to run pytest using command,

pytest testfolder/ --user=val1

testfolder/ is read as an argument in ArgumentParser().

In ArgumentParser(), I have some command line arguments where --user is only a mandatory argument and rest arguments have a default value. But this command changes the first argument's value to testfolder/, which I don't want. I want to specify the test folder name but not want it to be read as an argument of test.



Solution 1:[1]

Hope this help, you can try using the Parser class from pytest to command line arguments, via the addoption method which allows you to register a command line option, "After command line parsing, options are available on the pytest config object via config.option.NAME where NAME is usually set by passing a dest attribute, for example addoption("--long", dest="NAME", ...)". For example:

sample.py

def test_test_folder(test_folder):
    print(test_folder)

#def test_user(user):
#   print(user)

conftest.py

import pytest

def pytest_addoption(parser):
     parser.addoption("--test_folder", action="store", default="test", help="my option: test")
     #parser.addoption("--user", action="store", default="root", help="my option: root")

@pytest.fixture
def test_folder(request):
     return request.config.getoption("--test_folder")

#def user(request):
#     return request.config.getoption("--user")

output:

pytest -s sample.py --test_folder folder
============================================= test session starts =============================================
platform win32 -- Python 3.10.0, pytest-7.0.1, pluggy-1.0.0
rootdir: C:\Users\danie
plugins: Faker-13.0.0
collected 1 item

sample.py folder
.

============================================== 1 passed in 1.08s ==============================================

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ellhe-blaster