Importing resources for unit testing using pytest: module level or test level?

I learned about the benefits of test-based development and am trying to develop my first TDD application using pytest and the setuptools parameter develop. Still good. One question I have is: where should resources be imported that should be tested in my modules test_*?

For example, I could import at the module level:

from app.module1 import resource1, resource2

def test_resource1():
    assert test_resource1 == "expected value 1"

def test_resource2():
    assert test_resource2 == "expected value 2"

On the other hand, it seems that it makes sense to import in each test function:

def test_resource1():
    from app.module1 import resource1
    assert test_resource1 == "expected value 1"

def test_resource2():
    from app.module1 import resource2
    assert test_resource2 == "expected value 2"

This, of course, assumes that the resources that need to be tested are no longer needed.

Besides the differences in the required characters for input, is there an advantage to doing this or that?

+4
4

: " ".

.

, : import pdb; pdb.set_trace() __import__('pdb').set_trace().

+2

/, , , . , .

+1

, A , B . , ( ).

( ), , , ( )

, , , py.test / ( )

, .

+1

( , ) python.

When importing at the class / function level there is no use. If you are worried about namespace conflicts between the objects you import, instead of from app.module1 import resource1do, import app.module1and call app.module1.resource1in your test. This template is also recommended in the python docs idioms and anti-idioms for the reasons described here https://docs.python.org/2/howto/doanddont.html .

+1
source

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


All Articles