pythonpython-3.xunit-testingpluginspytest

How to pass variables during pytest call via python script(not command line)?


I am trying to run a test using pytest environment within a python script. I need the parameter called config which is defined in script.py to be used by the file 'test_functions.py' Below is my implementtion .

However I get the error

E       fixture 'config' not found  available fixtures: anyio_backend, anyio_backend_name, anyio_backend_options, cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, info, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
  use 'pytest --fixtures [testpath]' for help on them.`

contents of script.py

import pytest

if __name__ == '__main__':
   
    config = {
        'key1': 'value1',
        'key2': 'value2',
        # Add more key-value pairs as needed
    }


    class MyPlugin(object):
        def __init__(self, data):
            self.data = data

        @pytest.fixture
        def info(self, request):
            return self.data

    myplugin = MyPlugin(config)

    pytest.main(['test_functions.py'],plugins=[myplugin])    

content of test_functions.py' is as follows

def test_function(config):
    # Access the config dictionary
    print(config['monthly_or_weekly'])
    assert config['value1']=='value2'
  


Solution

  • You're trying to use config as a fixture in your test, but config isn't being defined as one in your code. You want something like this:

    import pytest
    
    @pytest.fixture
    def config():
        yield {
            'key1': 'value1',
            'key2': 'value2',
        }
    
    def test_function(config):
        print(config['key1'])
        print(config['key2'])