It helps to use fixtures in pytest.mark.parametrize

Overview

pytest-lazy-fixture travis-ci appveyor pypi

Use your fixtures in @pytest.mark.parametrize.

Installation

pip install pytest-lazy-fixture

Usage

import pytest

@pytest.fixture(params=[1, 2])
def one(request):
    return request.param

@pytest.mark.parametrize('arg1,arg2', [
    ('val1', pytest.lazy_fixture('one')),
])
def test_func(arg1, arg2):
    assert arg2 in [1, 2]

Also you can use it as a parameter in @pytest.fixture:

import pytest

@pytest.fixture(params=[
    pytest.lazy_fixture('one'),
    pytest.lazy_fixture('two')
])
def some(request):
    return request.param

@pytest.fixture
def one():
    return 1

@pytest.fixture
def two():
    return 2

def test_func(some):
    assert some in [1, 2]

Please see tests for more examples.

Contributing

Contributions are very welcome. Tests can be run with tox.

License

Distributed under the terms of the MIT license, pytest-lazy-fixture is free and open source software

Issues

If you encounter any problems, please file an issue along with a detailed description.

Comments
  • lazy-fixture breaks all the fixtures with autouse=True

    lazy-fixture breaks all the fixtures with autouse=True

    In my current project I have some fixtures which they use autouse=True. eg:

    def setup(autouse=True):
         self.var = 15
    

    After installing pytest-lazy-fixture, my tests can't find the self.var variable. If I remove the autouse=True and pass the fixture to my tests all work fine.

    Any ideas?

    opened by lefterisnik 10
  • Lazy fixtures not working at all

    Lazy fixtures not working at all

    I had a few lazy fixtures loaded in some of my tests like this:

    @pytest.mark.parametrize('user_group', [
            pytest.lazy_fixture('user_group_national_manager'),
            pytest.lazy_fixture('user_group_regional_manager'),	
            pytest.lazy_fixture('user_group_lwi_staff')	
        ])
    

    Now, when the tests are being loaded it fails collecting them with:

    /usr/local/lib/python3.6/dist-packages/pluggy/hooks.py:258: in __call__
        return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
    /usr/local/lib/python3.6/dist-packages/pluggy/manager.py:67: in _hookexec
        return self._inner_hookexec(hook, methods, kwargs)
    /usr/local/lib/python3.6/dist-packages/pluggy/manager.py:61: in <lambda>
        firstresult=hook.spec_opts.get('firstresult'),
    /usr/local/lib/python3.6/dist-packages/_pytest/python.py:242: in pytest_pycollect_makeitem
        res = list(collector._genfunctions(name, obj))
    /usr/local/lib/python3.6/dist-packages/_pytest/python.py:432: in _genfunctions
        self.ihook.pytest_generate_tests(metafunc=metafunc)
    /usr/local/lib/python3.6/dist-packages/pluggy/hooks.py:258: in __call__
        return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
    /usr/local/lib/python3.6/dist-packages/pluggy/manager.py:67: in _hookexec
        return self._inner_hookexec(hook, methods, kwargs)
    /usr/local/lib/python3.6/dist-packages/pluggy/manager.py:61: in <lambda>
        firstresult=hook.spec_opts.get('firstresult'),
    /usr/local/lib/python3.6/dist-packages/pytest_lazyfixture.py:70: in pytest_generate_tests
        normalize_metafunc_calls(metafunc, 'funcargs')
    /usr/local/lib/python3.6/dist-packages/pytest_lazyfixture.py:77: in normalize_metafunc_calls
        calls = normalize_call(callspec, metafunc, valtype, used_keys)
    /usr/local/lib/python3.6/dist-packages/pytest_lazyfixture.py:101: in normalize_call
        _, fixturenames_closure, arg2fixturedefs = fm.getfixtureclosure([val.name], metafunc.definition.parent)
    E   ValueError: not enough values to unpack (expected 3, got 2)
    

    If I changed the code to use tuples or arrays, the tests run but the lazy fixture is not loaded making the tests fail:

    @pytest.mark.parametrize('user_group', [
            (pytest.lazy_fixture('user_group_national_manager'),),
            (pytest.lazy_fixture('user_group_regional_manager'),),
            (pytest.lazy_fixture('user_group_lwi_staff'),)
        ])
    
        assert response.status_code == 200
    E   assert 403 == 200
    E    +  where 403 = <HttpResponseForbidden status_code=403, "text/html">.status_code
    

    This was working properly before the upgrade to 0.5.0

    I tried to use the format specified in the README with no luck. I had to remove the lazy fixture and use a different approach in the meantime.

    Any idea of what's broken?

    FYI, each fixture just creates a Group and adds the user to the created group. I assert the groups the user belongs to and it belongs to none so the fixture is not loaded when the test runs.

    opened by brian-barba-hernandez 8
  • Possible to expand the fixture return value in parametrize?

    Possible to expand the fixture return value in parametrize?

    I would like to parametrize a test with the return value of a fixture.

    Example:

    @pytest.fixture
    def links(browser): // assume broser was a fixture
        return browser.find_by_tag('a')
    
    @pytest.mark.parametrize("link", links) // here expand the links fixture return value
    def test_func(link):
         // test that link here
    

    Is this possible with pytest-lazy-fixture? (or maybe even pytest itself?) Or might it be a nice feature?

    opened by schtibe 7
  • lazy-fixture-0.5.2: function fixture runs before module fixture

    lazy-fixture-0.5.2: function fixture runs before module fixture

    pytest-5.1.3 lazy-fixture-0.5.2

    Example:

    import pytest
    from pytest_lazyfixture import lazy_fixture
    
    @pytest.fixture(scope="module")
    def module_fixture():
        print('using module fixture')
    
    @pytest.fixture
    def fixture1():
        print("using fixture1")
    
    @pytest.fixture
    def fixture2():
        print("using fixture2")
    
    @pytest.mark.usefixtures("module_fixture")
    @pytest.mark.parametrize("fixt", [lazy_fixture("fixture1"), lazy_fixture("fixture2")])
    def test_test(fixt):
        pass
    

    output

    smoke/test_test.py::test_test[fixt0] using fixture1
    using module fixture
    PASSED
    smoke/test_test.py::test_test[fixt1] using fixture2
    PASSED
    

    There is strange order - fixture1, module fixture, fixture2

    Same example without using lazy_fixture:

    @pytest.mark.usefixtures("module_fixture")
    def test_test1(fixture1):
        pass
    
    
    @pytest.mark.usefixtures("module_fixture")
    def test_test2(fixture2):
        pass
    

    output:

    smoke/test_test.py::test_test1 using module fixture
    using fixture1
    PASSED
    smoke/test_test.py::test_test2 using fixture2
    PASSED
    

    Executing order looks as designed - module fixture, fixture1, fixture2

    opened by lenvk 6
  • Broken by pytest 5.3.3

    Broken by pytest 5.3.3

    I haven't had time to investigate why, but it seems that the pytest 5.3.3 release broke pytest-lazy-fixture:

    Running the basic example from the README

    import pytest
    
    @pytest.fixture(params=[1, 2])
    def one(request):
        return request.param
    
    @pytest.mark.parametrize('arg1,arg2', [
        ('val1', pytest.lazy_fixture('one')),
    ])
    def test_func(arg1, arg2):
        assert arg2 in [1, 2]
    

    results in the following error:

    $ pytest test_lazy_fixture.py 
    ============================= test session starts ==============================
    platform linux -- Python 3.6.9, pytest-5.3.3, py-1.7.0, pluggy-0.12.0
    hypothesis profile 'default' -> database=DirectoryBasedExampleDatabase('/home/yannick/.hypothesis/examples')
    rootdir: /home/yannick
    plugins: xonsh-0.9.6, lazy-fixture-0.6.2, hypothesis-4.34.0
    collected 2 items                                                              
    
    test_lazy_fixture.py EE                                                  [100%]
    
    ==================================== ERRORS ====================================
    __________________ ERROR at setup of test_func[val1-arg20-1] ___________________
    file /home/yannick/test_lazy_fixture.py, line 7
      @pytest.mark.parametrize('arg1,arg2', [
          ('val1', pytest.lazy_fixture('one')),
      ])
      def test_func(arg1, arg2):
    file /home/yannick/test_lazy_fixture.py, line 3
      @pytest.fixture(params=[1, 2])
      def one(request):
    file /home/yannick/.local/lib/python3.6/site-packages/_pytest/fixtures.py, line 297
      def get_direct_param_fixture_func(request):
    E       recursive dependency involving fixture 'one' detected
    >       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, one, 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.
    
    /home/yannick/.local/lib/python3.6/site-packages/_pytest/fixtures.py:297
    __________________ ERROR at setup of test_func[val1-arg20-2] ___________________
    file /home/yannick/test_lazy_fixture.py, line 7
      @pytest.mark.parametrize('arg1,arg2', [
          ('val1', pytest.lazy_fixture('one')),
      ])
      def test_func(arg1, arg2):
    file /home/yannick/test_lazy_fixture.py, line 3
      @pytest.fixture(params=[1, 2])
      def one(request):
    file /home/yannick/.local/lib/python3.6/site-packages/_pytest/fixtures.py, line 297
      def get_direct_param_fixture_func(request):
    E       recursive dependency involving fixture 'one' detected
    >       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, one, 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.
    
    /home/yannick/.local/lib/python3.6/site-packages/_pytest/fixtures.py:297
    ============================== 2 errors in 0.02s ===============================
    

    If I have time, I'll have a closer look and report back on my findings.

    opened by YannickJadoul 5
  • error with pytest==5.3.0

    error with pytest==5.3.0

    Getting the following error after updating from pytest==5.2.4 to pytest==5.3.0. Using latest pytest-lazy-fixture.

    ../../.pyenv/versions/3.8.0/lib/python3.8/site-packages/pluggy/hooks.py:286: in __call__
        return self._hookexec(self, self.get_hookimpls(), kwargs)
    ../../.pyenv/versions/3.8.0/lib/python3.8/site-packages/pluggy/manager.py:92: in _hookexec
        return self._inner_hookexec(hook, methods, kwargs)
    ../../.pyenv/versions/3.8.0/lib/python3.8/site-packages/pluggy/manager.py:83: in <lambda>
        self._inner_hookexec = lambda hook, methods, kwargs: hook.multicall(
    ../../.pyenv/versions/3.8.0/lib/python3.8/site-packages/_pytest/python.py:208: in pytest_pycollect_makeitem
        res = outcome.get_result()
    ../../.pyenv/versions/3.8.0/lib/python3.8/site-packages/aiohttp/pytest_plugin.py:155: in pytest_pycollect_makeitem
        return list(collector._genfunctions(name, obj))
    ../../.pyenv/versions/3.8.0/lib/python3.8/site-packages/_pytest/python.py:404: in _genfunctions
        self.ihook.pytest_generate_tests.call_extra(methods, dict(metafunc=metafunc))
    ../../.pyenv/versions/3.8.0/lib/python3.8/site-packages/pluggy/hooks.py:324: in call_extra
        return self(**kwargs)
    ../../.pyenv/versions/3.8.0/lib/python3.8/site-packages/pluggy/hooks.py:286: in __call__
        return self._hookexec(self, self.get_hookimpls(), kwargs)
    ../../.pyenv/versions/3.8.0/lib/python3.8/site-packages/pluggy/manager.py:92: in _hookexec
        return self._inner_hookexec(hook, methods, kwargs)
    ../../.pyenv/versions/3.8.0/lib/python3.8/site-packages/pluggy/manager.py:83: in <lambda>
        self._inner_hookexec = lambda hook, methods, kwargs: hook.multicall(
    ../../.pyenv/versions/3.8.0/lib/python3.8/site-packages/pytest_lazyfixture.py:69: in pytest_generate_tests
        normalize_metafunc_calls(metafunc, 'funcargs')
    ../../.pyenv/versions/3.8.0/lib/python3.8/site-packages/pytest_lazyfixture.py:76: in normalize_metafunc_calls
        calls = normalize_call(callspec, metafunc, valtype, used_keys)
    ../../.pyenv/versions/3.8.0/lib/python3.8/site-packages/pytest_lazyfixture.py:111: in normalize_call
        newmetafunc = copy_metafunc(metafunc)
    ../../.pyenv/versions/3.8.0/lib/python3.8/site-packages/pytest_lazyfixture.py:85: in copy_metafunc
        copied._ids = copy.copy(metafunc._ids)
    E   AttributeError: 'Metafunc' object has no attribute '_ids'
    
    opened by discosultan 5
  • Use fixture names to generate test ids?

    Use fixture names to generate test ids?

    First off, thank you for writing this plugin, it fixes problems that have been bugging me for years.

    Given the following tests:

    import pytest
    from pytest_lazyfixture import lazy_fixture
    
    @pytest.fixture()
    def foo():
        return "foo"
    
    @pytest.fixture(params=['spam', 'eggs'])
    def bar(request):
        return f"bar-{request.param}"
    
    @pytest.mark.parametrize("data", [lazy_fixture("foo"),
                                      lazy_fixture("bar")])
    def test_the_thing(data):
        assert False    
    

    Pytest generates the following test names:

    > py.test test_lazy.py --collect-only
    ===================== test session starts =====================
    platform darwin -- Python 3.7.6, pytest-5.3.2, py-1.8.1, pluggy-0.13.1
    rootdir: /tmp
    plugins: xdist-1.26.1, flask-0.14.0, lazy-fixture-0.6.2, forked-1.1.3
    collected 3 items                                                                                                            
    <Module test_lazy.py>
      <Function test_the_thing[data0]>
      <Function test_the_thing[data1-spam]>
      <Function test_the_thing[data1-eggs]>
    

    Would it be possible to use the fixture name to generate these ids? It would be great to end up with these names instead:

    test_the_thing[foo]
    test_the_thing[bar-spam]
    test_the_thing[bar-eggs]
    opened by avirshup 4
  • 0.5.2 problem with pytest-asyncio

    0.5.2 problem with pytest-asyncio

    I made a PR to upgrade pytest-lazy-fixture 0.4.2 to 0.5.2.

    • PR: https://github.com/youknowone/ring/pull/106
    • CI: https://travis-ci.org/youknowone/ring/jobs/518829292

    It worked with 0.4.2 but doesn't work with 0.5.2 anymore. Any idea?

    The errors are refering about event loop

    E       RuntimeError: Task <Task pending coro=<test_complicated_key() running at /Users/youknowone/Projects/ring/tests/_test_func_asyncio.py:183> cb=[_run_until_complete_cb() at ~/.pyenv/versions/3.7.0/lib/python3.7/asyncio/base_events.py:150]> got Future <Future pending cb=[BaseSelectorEventLoop._sock_connect_done(22)()]> attached to a different loop
    

    Because upgrading pytest-lazy-fixture triggers the problem regardless of pytest-asyncio version, I guessed this may be a regression in pytest-lazy-fixture. Please let me know if the change in pytest-lazy-fixture is not a problem. Then I should change my code to fit in new version.

    opened by youknowone 4
  • indirect fixtures

    indirect fixtures

    Hi, you asked me about some example for the issue I tried to resolve by the pull request from yestrday. So I added test to test_lazyfixture.py. It is basicly about indirect lazy_fixtures in test generator, which can do some modificition (in examle it is list modificition, but in real life it is usualy some db modificition etc...). If you run tests, the new test will fail on TypeError: 'LazyFixture' object does not support indexing. Beacause LazyFixture is never inicialized. If you uncommented lines 15-24 in pytest_lazyfixture.py, the test will pass.

    opened by dburton90 4
  • Fixture with numpy array as value fails on 0.6.0

    Fixture with numpy array as value fails on 0.6.0

    This seems related to https://github.com/pytest-dev/pytest/issues/5946 (which is already fixed on pytest master), but it is still failing with the latest lazy-fixtures (pinning to 0.5.2 fixes it).

    Test script (variation of the one in https://github.com/pytest-dev/pytest/issues/5946):

    import numpy as np
    import pytest
    
    
    @pytest.mark.parametrize(
        'value',
        [
            np.arange(10, dtype=np.int64),
            np.arange(10, dtype=np.int32),
        ]
    )
    def test_bug(value):
        assert isinstance(value, np.ndarray)
    

    and this fails with:

    $ pytest test_pytest_bug.py -v
    ==================================================================== test session starts =====================================================================
    platform linux -- Python 3.7.3, pytest-5.2.2.dev23+ga20880cca, py-1.8.0, pluggy-0.12.0 -- /home/joris/miniconda3/envs/arrow-dev/bin/python
    cachedir: .pytest_cache
    hypothesis profile 'default' -> database=DirectoryBasedExampleDatabase('/home/joris/scipy/.hypothesis/examples')
    rootdir: /home/joris/scipy
    plugins: hypothesis-4.24.2, lazy-fixture-0.6.0
    collected 2 items                                                                                                                                            
    
    test_pytest_bug.py::test_bug[value0] ERROR                                                                                                             [ 50%]
    test_pytest_bug.py::test_bug[value1] ERROR                                                                                                             [100%]
    
    =========================================================================== ERRORS ===========================================================================
    _____________________________________________________________ ERROR at setup of test_bug[value0] _____________________________________________________________
    
    request = <FixtureRequest for <Function test_bug[value0]>>
    
        def fill(request):
            item = request._pyfuncitem
            fixturenames = getattr(item, "fixturenames", None)
            if fixturenames is None:
                fixturenames = request.fixturenames
        
            if hasattr(item, 'callspec'):
    >           for param, val in sorted_by_dependency(item.callspec.params, fixturenames):
    
    ../miniconda3/envs/arrow-dev/lib/python3.7/site-packages/pytest_lazyfixture.py:33: 
    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
    
    params = {'value': array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])}, fixturenames = ['value']
    
        def sorted_by_dependency(params, fixturenames):
            free_fm = []
            non_free_fm = defaultdict(list)
        
            for key in _sorted_argnames(params, fixturenames):
                val = params.get(key)
        
    >           if not val or not is_lazy_fixture(val) or val.name not in params:
    E           ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
    
    ../miniconda3/envs/arrow-dev/lib/python3.7/site-packages/pytest_lazyfixture.py:130: ValueError
    _____________________________________________________________ ERROR at setup of test_bug[value1] _____________________________________________________________
    
    request = <FixtureRequest for <Function test_bug[value1]>>
    
        def fill(request):
            item = request._pyfuncitem
            fixturenames = getattr(item, "fixturenames", None)
            if fixturenames is None:
                fixturenames = request.fixturenames
        
            if hasattr(item, 'callspec'):
    >           for param, val in sorted_by_dependency(item.callspec.params, fixturenames):
    
    ../miniconda3/envs/arrow-dev/lib/python3.7/site-packages/pytest_lazyfixture.py:33: 
    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
    
    params = {'value': array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int32)}, fixturenames = ['value']
    
        def sorted_by_dependency(params, fixturenames):
            free_fm = []
            non_free_fm = defaultdict(list)
        
            for key in _sorted_argnames(params, fixturenames):
                val = params.get(key)
        
    >           if not val or not is_lazy_fixture(val) or val.name not in params:
    E           ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
    
    ../miniconda3/envs/arrow-dev/lib/python3.7/site-packages/pytest_lazyfixture.py:130: ValueError
    ====================================================================== 2 error in 0.09s ======================================================================
    
    
    opened by jorisvandenbossche 3
  • Make LazyFixture iterable

    Make LazyFixture iterable

    This does work now:

    @pytest.mark.parametrize('arg1', [
       pytest.lazy_fixture('needs_db')
    ])
    @pytest.mark.django_db
    def test_some(arg1):
        assert ...
    

    But it's not quite what I need. The fixture needs_db returns a list and I'd like to parametrize test_some with that list:

    @pytest.mark.parametrize('arg1', pytest.lazy_fixture('needs_db'))
    @pytest.mark.django_db
    def test_some(arg1):
        assert ...
    

    This fails: TypeError: 'LazyFixture' object is not iterable

    Is it possible to support this use case? I'm not familiar with pytest's internals. :/

    opened by michael-k 3
  • Using fixture that returns a list of parameters, is it possible?

    Using fixture that returns a list of parameters, is it possible?

    Here's my fixture:

    @fixture
    def devices(scope='module');
        with connect(get_all_devices()) as connected_devices:
            yield connected_devices
    

    Here's how I want to use it:

    @parametrize('device', devices)
    def test_routine(device):
        device.do_something()
        assert device.is_ok()
    

    What I'm doing instead:

    def test_routine(subtests, devices):
        for index, device in enumerate(devices):
            with subtests.test(device, i=index):
                device.do_something()
                assert device.is_ok()
    

    Is this possible with lazy fixture or any other method?

    opened by bbk-riact 0
  • Pytest discovery changes test names when using multiple lazy fixtures

    Pytest discovery changes test names when using multiple lazy fixtures

    I have some test cases in which I need more than one lazy fixture (one for each parameter).

    The problem is that the pytest discovery is creating different test names in every run, which creates a problem in the interaction with tools like VScode. I don't know if it's a pytest issue or pytest-lazy-fixtures one.

    Here's an example of a test that uses two lazy fixtures:

    import pytest
    from pytest import fixture
    from pytest_lazyfixture import lazy_fixture
    
    
    @fixture(params=[1, 2, 3])
    def all_numbers(request):
        return request.param
    
    
    @fixture(params=["a", "b", "c"])
    def all_letters(request):
        return request.param
    
    
    @pytest.mark.parametrize(
        "number,letter",
        [lazy_fixture(["all_numbers", "all_letters"])]
    )
    def test_multiple_lazy(number, letter):
        print(number, letter)
    

    This is one pytest collect run:

     pytest --collect-only
    =================================================================== test session starts ====================================================================
    platform darwin -- Python 3.11.0, pytest-7.2.0, pluggy-0.13.1
    rootdir: /Users/fraimondo/dev/scratch/pytest_order
    plugins: typeguard-2.13.3, lazy-fixture-0.6.3
    collected 9 items                                                                                                                                          
    
    <Module test_multiple_lazy.py>
      <Function test_multiple_lazy[all_numbers-all_letters-a-1]>
      <Function test_multiple_lazy[all_numbers-all_letters-a-2]>
      <Function test_multiple_lazy[all_numbers-all_letters-a-3]>
      <Function test_multiple_lazy[all_numbers-all_letters-b-1]>
      <Function test_multiple_lazy[all_numbers-all_letters-b-2]>
      <Function test_multiple_lazy[all_numbers-all_letters-b-3]>
      <Function test_multiple_lazy[all_numbers-all_letters-c-1]>
      <Function test_multiple_lazy[all_numbers-all_letters-c-2]>
      <Function test_multiple_lazy[all_numbers-all_letters-c-3]>
    

    This is another one:

    pytest --collect-only
    =================================================================== test session starts ====================================================================
    platform darwin -- Python 3.11.0, pytest-7.2.0, pluggy-0.13.1
    rootdir: /Users/fraimondo/dev/scratch/pytest_order
    plugins: typeguard-2.13.3, lazy-fixture-0.6.3
    collected 9 items                                                                                                                                          
    
    <Module test_multiple_lazy.py>
      <Function test_multiple_lazy[all_numbers-all_letters-1-a]>
      <Function test_multiple_lazy[all_numbers-all_letters-1-b]>
      <Function test_multiple_lazy[all_numbers-all_letters-1-c]>
      <Function test_multiple_lazy[all_numbers-all_letters-2-a]>
      <Function test_multiple_lazy[all_numbers-all_letters-2-b]>
      <Function test_multiple_lazy[all_numbers-all_letters-2-c]>
      <Function test_multiple_lazy[all_numbers-all_letters-3-a]>
      <Function test_multiple_lazy[all_numbers-all_letters-3-b]>
      <Function test_multiple_lazy[all_numbers-all_letters-3-c]>
    
    opened by fraimondo 0
  • TypeError: 'LazyFixture' object is not subscriptable

    TypeError: 'LazyFixture' object is not subscriptable

    Hi there,

    I was trying to do the following code which results in a Exception being thrown. I was wondering if someone has found a way to use the returned object from a lazy_fixture in the parametrize values

    import pytest
    from pytest_lazyfixture import lazy_fixture
    
    @pytest.fixture
    def one():
        return {
            "foo1": "bar",
            "foo2": "baz",
        }
    
    @pytest.mark.parametrize(
        'attr1',
        [
            (lazy_fixture('one')["foo1"], ),
        ]
    )
    def test_func(attr1):
        assert attr1 == "bar"
    
    ============================================================================================================= test session starts =============================================================================================================
    platform linux -- Python 3.10.5, pytest-7.1.3, pluggy-1.0.0
    rootdir: /home/users/frank/workspace/pseudopiper, configfile: pytest.ini
    plugins: xdist-2.5.0, cov-4.0.0, lazy-fixture-0.6.3, clarity-1.0.1, icdiff-0.6, forked-1.4.0
    collected 0 items / 1 error
    
    =================================================================================================================== ERRORS ====================================================================================================================
    ___________________________________________________________________________________________________ ERROR collecting tests/test_foobar2.py ____________________________________________________________________________________________________
    tests/test_foobar2.py:14: in <module>
        (lazy_fixture('one')["foo1"], ),
    E   TypeError: 'LazyFixture' object is not subscriptable
    =========================================================================================================== short test summary info ===========================================================================================================
    ERROR tests/test_foobar2.py - TypeError: 'LazyFixture' object is not subscriptable
    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    ============================================================================================================== 1 error in 0.21s ===============================================================================================================
    
    opened by flazzarini 0
  • TypeError: 'LazyFixture' object is not iterable

    TypeError: 'LazyFixture' object is not iterable

    Hi there,

    I am running into issues with using a fixture, that loads a list of parameters that I want to use to parametrize tests. I am not sure, whether that is something, that can be done with your package and I just can't figure it out, or whether that would be a new feature.

    Here is a example on what I want to achieve:

    import pytest
    
    @pytest.fixture()
    def one(tmp_path):
        return list(str(tmp_path))
    
    @pytest.mark.parametrize("char", pytest.lazy_fixture('one'))
    def test_func(char):
        assert char.isascii()
    

    Do you have an idea on how to get my code running?

    Thanks a lot!

    opened by ChristianF88 3
  • pytest-lazy-fixture breaks with Traits in factoryboy 3.2.0: 'Maybe' object has no attribute 'call'

    pytest-lazy-fixture breaks with Traits in factoryboy 3.2.0: 'Maybe' object has no attribute 'call'

    After updating factoryboy to 3.2.0 my tests using lazy_fixture with fixtures that use Trait (in result using Maybe) raise AttributeError: 'Maybe' object has no attribute 'call'.

    python_version = "3.8"
    django = "~=3.0"
    factory-boy = "~=3.2.0"
    pytest = "~=5.4.3"
    pytest-factoryboy = "~=2.1.0"
    pytest-lazy-fixture = "~=0.6.3"
    

    Attached is a full traceback from failed test case.

    request = <FixtureRequest for <Function test_success>>
    
        def fill(request):
            item = request._pyfuncitem
            fixturenames = getattr(item, "fixturenames", None)
            if fixturenames is None:
                fixturenames = request.fixturenames
        
            if hasattr(item, 'callspec'):
                for param, val in sorted_by_dependency(item.callspec.params, fixturenames):
                    if val is not None and is_lazy_fixture(val):
                        item.callspec.params[param] = request.getfixturevalue(val.name)
                    elif param not in item.funcargs:
                        item.funcargs[param] = request.getfixturevalue(param)
        
    >       _fillfixtures()
    
    /home/django/venv/lib/python3.8/site-packages/pytest_lazyfixture.py:39: 
    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
    /home/django/venv/lib/python3.8/site-packages/pytest_factoryboy/fixture.py:188: in model_fixture
        factoryboy_request.evaluate(request)
    /home/django/venv/lib/python3.8/site-packages/pytest_factoryboy/plugin.py:83: in evaluate
        self.execute(request, function, deferred)
    /home/django/venv/lib/python3.8/site-packages/pytest_factoryboy/plugin.py:65: in execute
        self.results[model][attr] = function(request)
    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
    
    request = <SubRequest 'user' for <Function test_success>>
    
        def deferred(request):
    >       declaration.call(instance, step, context)
    E       AttributeError: 'Maybe' object has no attribute 'call'
    
    /home/django/venv/lib/python3.8/site-packages/pytest_factoryboy/fixture.py:294: AttributeError
    

    Seems like it could be a problem in pytest_factoryboy itself but I've seen it raised only for tests using lazy_fixture.

    opened by radekwlsk 3
  • mypy can't discover pytest.lazy_fixture under pytest 6

    mypy can't discover pytest.lazy_fixture under pytest 6

    If you have a test suite that uses pytest.lazy_fixture, and you're using pytest 6.0.0+, and you run mypy over your test suite, mypy complains with the error:

    test/test_something.py:42: error: Module has no attribute "lazy_fixture"
    

    The test suite itself passes without any problems; it is only the type checking of mypy that fails.

    This problem does not exist on pytest 5.4.3 or earlier.

    I presume something has changed in the plugin registration process that prevents mypy from seeing the lazy_fixture attribute.

    opened by freakboy3742 2
Releases(0.6.0)
Owner
Marsel Zaripov
Marsel Zaripov
pytest plugin providing a function to check if pytest is running.

pytest-is-running pytest plugin providing a function to check if pytest is running. Installation Install with: python -m pip install pytest-is-running

Adam Johnson 21 Nov 01, 2022
自动化爬取并自动测试所有swagger-ui.html显示的接口

swagger-hack 在测试中偶尔会碰到swagger泄露 常见的泄露如图: 有的泄露接口特别多,每一个都手动去试根本试不过来 于是用python写了个脚本自动爬取所有接口,配置好传参发包访问 原理是首先抓取http://url/swagger-resources 获取到有哪些标准及对应的文档地

jayus 534 Dec 29, 2022
A folder automation made using Watch-dog, it only works in linux for now but I assume, it will be adaptable to mac and PC as well

folder-automation A folder automation made using Watch-dog, it only works in linux for now but I assume, it will be adaptable to mac and PC as well Th

Parag Jyoti Paul 31 May 28, 2021
Cornell record & replay mock server

Cornell: record & replay mock server Cornell makes it dead simple, via its record and replay features to perform end-to-end testing in a fast and isol

HiredScoreLabs 134 Sep 15, 2022
The evaluator covering all of the metrics required by tasks within the DUE Benchmark.

DUE Evaluator The repository contains the evaluator covering all of the metrics required by tasks within the DUE Benchmark, i.e., set-based F1 (for KI

DUE Benchmark 4 Jan 21, 2022
Bayesian A/B testing

bayesian_testing is a small package for a quick evaluation of A/B (or A/B/C/...) tests using Bayesian approach.

Matus Baniar 35 Dec 15, 2022
Useful additions to Django's default TestCase

django-test-plus Useful additions to Django's default TestCase from REVSYS Rationale Let's face it, writing tests isn't always fun. Part of the reason

REVSYS 546 Dec 22, 2022
catsim - Computerized Adaptive Testing Simulator

catsim - Computerized Adaptive Testing Simulator Quick start catsim is a computerized adaptive testing simulator written in Python 3.4 (with modificat

Nguyễn Văn Anh Tuấn 1 Nov 29, 2021
Automatically mock your HTTP interactions to simplify and speed up testing

VCR.py 📼 This is a Python version of Ruby's VCR library. Source code https://github.com/kevin1024/vcrpy Documentation https://vcrpy.readthedocs.io/ R

Kevin McCarthy 2.3k Jan 01, 2023
Python 3 wrapper of Microsoft UIAutomation. Support UIAutomation for MFC, WindowsForm, WPF, Modern UI(Metro UI), Qt, IE, Firefox, Chrome ...

Python 3 wrapper of Microsoft UIAutomation. Support UIAutomation for MFC, WindowsForm, WPF, Modern UI(Metro UI), Qt, IE, Firefox, Chrome ...

yin kaisheng 1.6k Dec 29, 2022
A command-line tool and Python library and Pytest plugin for automated testing of RESTful APIs, with a simple, concise and flexible YAML-based syntax

1.0 Release See here for details about breaking changes with the upcoming 1.0 release: https://github.com/taverntesting/tavern/issues/495 Easier API t

909 Dec 15, 2022
Auto Click by pyautogui and excel operations.

Auto Click by pyautogui and excel operations.

Janney 2 Dec 21, 2021
This package is a python library with tools for the Molecular Simulation - Software Gromos.

This package is a python library with tools for the Molecular Simulation - Software Gromos. It allows you to easily set up, manage and analyze simulations in python.

14 Sep 28, 2022
A collection of benchmarking tools.

Benchmark Utilities About A collection of benchmarking tools. PYPI Package Table of Contents Using the library Installing and using the library Manual

Kostas Georgiou 2 Jan 28, 2022
Kent - Fake Sentry server for local development, debugging, and integration testing

Kent is a service for debugging and integration testing Sentry.

Will Kahn-Greene 100 Dec 15, 2022
frwk_51pwn is an open-sourced remote vulnerability testing and proof-of-concept development framework

frwk_51pwn Legal Disclaimer Usage of frwk_51pwn for attacking targets without prior mutual consent is illegal. frwk_51pwn is for security testing purp

51pwn 4 Apr 24, 2022
This project demonstrates selenium's ability to extract files from a website.

This project demonstrates selenium's ability to extract files from a website. I've added the challenge of connecting over TOR. This package also includes a personal archive site built in NodeJS and A

2 Jan 16, 2022
buX Course Enrollment Automation

buX automation BRACU - buX course enrollment automation Features: Automatically enroll into multiple courses at a time. Find courses just entering cou

Mohammad Shakib 1 Oct 06, 2022
pytest splinter and selenium integration for anyone interested in browser interaction in tests

Splinter plugin for the pytest runner Install pytest-splinter pip install pytest-splinter Features The plugin provides a set of fixtures to use splin

pytest-dev 238 Nov 14, 2022