Create and import helper functions in tests without creating packages in test directory using py.test

后端 未结 7 607
北恋
北恋 2020-12-24 04:57

Question

How can I import helper functions in test files without creating packages in the test directory?


Contex

相关标签:
7条回答
  • 2020-12-24 05:16

    You could define a helper class in conftest.py, then create a fixture that returns that class (or an instance of it, depending on what you need).

    import pytest
    
    
    class Helpers:
        @staticmethod
        def help_me():
            return "no"
    
    
    @pytest.fixture
    def helpers():
        return Helpers
    

    Then in your tests, you can use the fixture:

    def test_with_help(helpers):
        helpers.help_me()
    
    0 讨论(0)
  • 2020-12-24 05:16

    To access a method from different modules without creating packages, and have that function operate as a helper function I found the following helpful:

    conftest.py:

    @pytest.fixture
    def compare_test_vs_actual():
        def a_function(test, actual):
            print(test, actual)
        return a_function
    

    test_file.py:

    def test_service_command_add(compare_test_vs_actual):
        compare_test_vs_actual("hello", "world")
    
    0 讨论(0)
  • 2020-12-24 05:25

    As another option, this directory structure worked for me:

    mypkg/
        ...
    test_helpers/
        __init__.py
        utils.py  
        ...
    tests/
        my_test.py
        ...
    

    And then in my_test.py import the utilities using: from test_helpers import utils

    0 讨论(0)
  • 2020-12-24 05:28

    It is possible that some of you will be completely uphold by my suggestion. However, very simple way of using common function or value from other modules is to inject it directly into a common workspace. Example:
    conftest.py:

    import sys
    
    def my_function():
       return 'my_function() called'
    
    sys.modules['pytest'].common_funct = my_function
    

    test_me.py

    import pytest
    
    def test_A():
       print(pytest.common_funct())
    
    0 讨论(0)
  • 2020-12-24 05:34

    Create a helpers package in tests folder:

    tests/
        helpers/
          __init__.py
          utils.py
          ...
        # make sure no __init__.py in here!
    setup.cfg
    

    in setup.cfg:

    [pytest]
    norecursedirs=tests/helpers
    

    the helpers will be available with import helpers.

    0 讨论(0)
  • 2020-12-24 05:38

    my option is to create an extra dir in tests dir and add it to pythonpath in the conftest so.

    tests/
        helpers/
          utils.py
          ...
        conftest.py
    setup.cfg
    

    in the conftest.py

    import sys
    import os
    sys.path.append(os.path.join(os.path.dirname(__file__), 'helpers'))
    

    in setup.cfg

    [pytest]
    norecursedirs=tests/helpers
    

    this module will be available with import utils, only be careful to name clashing.

    0 讨论(0)
提交回复
热议问题