How and where does py.test find fixtures

前端 未结 3 1561
别跟我提以往
别跟我提以往 2020-12-14 15:07

Where and how does py.test look for fixtures? I have the same code in 2 files in the same folder. When I delete conftest.py, cmdopt cannot be found running tes

3条回答
  •  执念已碎
    2020-12-14 15:35

    I had the same issue and spent a lot of time to find out a simple solution, this example is for others that have a similar situation as I had.

    • conftest.py:
    import pytest
    
    pytest_plugins = [
     "some_package.sonoftest"
    ]
    
    def pytest_addoption(parser):
      parser.addoption("--cmdopt", action="store", default="type1",
          help="my option: type1 or type2")
    
    @pytest.fixture
    def cmdopt(request):
      return request.config.getoption("--cmdopt")
    
    • some_package/sonoftest.py:
    import pytest
    
    @pytest.fixture
    def sono_cmdopt(request):
      return request.config.getoption("--cmdopt")
    
    • some_package/test_sample.py
    def test_answer1(cmdopt):
      if cmdopt == "type1":
          print ("first")
      elif cmdopt == "type2":
          print ("second")
      assert 0 # to see what was printed
    
    def test_answer2(sono_cmdopt):
      if sono_cmdopt == "type1":
          print ("first")
      elif sono_cmdopt == "type2":
          print ("second")
      assert 0 # to see what was printed
    

    You can find a similar example here: https://github.com/pytest-dev/pytest/issues/3039#issuecomment-464489204 and other here https://stackoverflow.com/a/54736376/6655459

    Description from official pytest documentation: https://docs.pytest.org/en/latest/reference.html?highlight=pytest_plugins#pytest-plugins

    As a note that the respective directories referred to in some_package.test_sample" need to have __init__.py files for the plugins to be loaded by pytest

提交回复
热议问题