I'd like to pass a command line argument to py.test for fixture creation. For example, I'd like to pass a database hostname to the fixture creation below, so it won't be hard-coded:
import pytest
def pytest_addoption(parser):
    parser.addoption("--hostname", action="store", default='127.0.0.1', help="specify IP of test host")
@pytest.fixture(scope='module')
def db(request):
    return 'CONNECTED TO [' + request.config.getoption('--hostname') + '] SUCCESSFULLY!'
def test_1(db):
    print db
    assert 0
Unfortunately, the default is not set, if the argument is omitted from the command line:
$ py.test test_opt.py
=================================================================== test session starts ====================================================================
platform linux2 -- Python 2.7.5 -- pytest-2.3.5
collected 1 items
test_opt.py E
========================================================================== ERRORS ==========================================================================
_________________________________________________________________ ERROR at setup of test_1 _________________________________________________________________
request = <FixtureRequest for <Module 'test_opt.py'>>
    @pytest.fixture(scope='module')
    def db(request):
>       return 'CONNECTED TO [' + request.config.getoption('--hostname') + '] SUCCESSFULLY!'
test_opt.py:8:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <_pytest.config.Config object at 0x220c4d0>, name = '--hostname'
    def getoption(self, name):
        """ return command line option value.
            :arg name: name of the option.  You may also specify
                the literal ``--OPT`` option instead of the "dest" option name.
            """
        name = self._opt2dest.get(name, name)
        try:
            return getattr(self.option, name)
        except AttributeError:
>           raise ValueError("no option named %r" % (name,))
E           ValueError: no option named '--hostname'
What am I missing? ... Incidentally, specifying the hostname on the command line also fails:
$ py.test --hostname=192.168.0.1 test_opt.py
Usage: py.test [options] [file_or_dir] [file_or_dir] [...]
py.test: error: no such option: --hostname
TIA!
What is the layout of your files?  It seems you are trying to put all this code in the test_opt.py module.  However the pytest_addoption() hook will only get read from a conftest.py file.  So you should try moving the pytest_addoption() function to a conftest.py file in the same directory as test_opt.py.
In general while fixtures can be defined in test modules any hooks need to be placed in a conftest.py file for py.test to use them.
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