简体   繁体   中英

pytest parameterization indirectly when using unittest framework

I'm using the python unittest and pytest frameworks together. I ran into a case where I have a fixture that generates signed header tokens, which I'm trying to mock locally. So I want to create a fixture that I can pass a payload to when the test runs. It doesn't seem like I can do it with pytest and unittest together, however.

pytest.fixture
def gen_headers(value):
  return "hey bud, you got a nice header!" + value["fake_head"]


class Tests(unittest.TestCase):

  @pytest.mark.parametrize("gen_headers", [{"fake_head": "hi :)"}], indirect=True)
    def test_func(self, gen_headers):
        do_ya_thing = api.request("get", headers=gen_headers)
        ...

the test fails TypeError: ... missing 1 required positional argument: ...

I tried using the paramterized python package, but I dont think it supports passing a custom input to the fixture at run time (test time), which is what I'm looking to do, since the thing being returned in gen_headers may change.

You can't easily combine parameterized fixtures with unittest. Any reason not to use pytest directly here?

With pytest alone you can easily gain access to the params using the request fixture.

import pytest


@pytest.fixture
def gen_headers(request):
    return "hey bud, you got a nice header!" + request.param["fake_head"]


class TestWithFixtures:
    @pytest.mark.parametrize(
        "gen_headers",
        [
            {"fake_head": "hi :)"},
            {"fake_head": "bye :("}
        ],
        indirect=True
    )
    def test_func(self, gen_headers):
        print(gen_headers)
============================= test session starts =============================
collecting ... collected 2 items

test.py::TestWithFixtures::test_func[gen_headers0] 
test.py::TestWithFixtures::test_func[gen_headers1] 

============================== 2 passed in 0.02s ==============================

PASSED                [ 50%]hey bud, you got a nice header!hi :)
PASSED                [100%]hey bud, you got a nice header!bye :(

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM