How to force pytest to rewrite a statement in non-test modules

We defined all our user statements in a separate python file, which is not a test module.

For example: custom_asserts.py

 class CustomAsserts(object): def silly_assert(self, foo, bar): assert foo == bar , 'some error message' 

If we use assert directly in tests, we will get additional information about AssertionError, which is very useful.

Conclusion of direct use in tests:

 > assert 'foo' == 'bar', 'some error message' E AssertionError: some error message E assert 'foo' == 'bar' E - foo E + bar 

But we found that if we call the approval method that we defined in a separate module, additional information will not be displayed.

 from custom_asserts import CustomAsserts asserts = CustomAsserts() def test_silly(): asserts.silly_assert('foo', 'bar') 

Result after running the test:

 > assert 'foo' == 'bar', 'some error message' E AssertionError: some error message 

And we also found this in the pytest docs: Advanced Claims Introspection

pytest only overwrites the test modules directly detected by its test collection process, therefore claims in supporting modules that are not the test modules themselves will not be overwritten.

So my question is, is there a way to let pytest do the same thing as rewriting other modules as test modules? Or is there some hacker way to achieve this?

+3
source share
1 answer

Update:

Pytest 3.0 introduced a new register_assert_rewrite method to implement this exact function. If you are using pytest 3.0 or later, try this. register_assert_rewrite

Original answer:

This is kind of wired to answer my own question, but I think I found a solution and want to share.

The trick is how to build pytest test modules. We can define python_files in pytest.ini so that pytest considers more modules as test modules.

For example, in my case, all of my custom claim modules end with β€œclaims”, so my pytest.ini :

 [pytest] python_files = *asserts.py test_*.py *_test.py 

Another tricky thing is in conftest.py . It seems we need to avoid importing the claims module into conftest.py . My assumption is that it looks like the pytest technology uses assert to overwrite, actually overwrites the .pyc file, and since conftest.py loaded before assembly, if we import the claims module, the .pyc module will be generated before the collection, which pytest can do unable to overwrite .pyc file again.

So, in my conftest.py, I should do something like:

 @pytest.fixture(autouse=Ture) def setup_asserts(request): from custom_asserts import CustomAsserts request.instance.asserts = CustomAsserts() 

And I will get additional error information in the same way as using the assert keyword directly in the test script.

+4
source

Source: https://habr.com/ru/post/1262470/


All Articles