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

后端 未结 7 608
北恋
北恋 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:38

    While searching for a solution for this problem I came across this SO question and ended up adopting the same approach. Creating a helpers package, munging sys.path to make it importable and then just importing it...

    This did not seem the best approach, so, I created pytest-helpers-namespace. This plugin allows you to register helper functions on your conftest.py:

    import pytest
    
    pytest_plugins = ['helpers_namespace']
    
    @pytest.helpers.register
    def my_custom_assert_helper(blah):
        assert blah
    
    # One can even specify a custom name for the helper
    @pytest.helpers.register(name='assertme')
    def my_custom_assert_helper_2(blah):
        assert blah
    
    # And even namespace helpers
    @pytest.helpers.asserts.register(name='me')
    def my_custom_assert_helper_3(blah):
        assert blah
    

    And then, within a test case function body just use it like

    def test_this():
        assert pytest.helpers.my_custom_assert_helper(blah) 
    
    def test_this_2():
        assert pytest.helpers.assertme(blah)
    
    def test_this_3():
        assert pytest.helpers.asserts.me(blah)
    

    Its pretty simple and the documentation pretty small. Take a look and tell me if it addresses your problem too.

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