Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

testing - Python imports for tests using nose - what is best practice for imports of modules above current package

This is a question which is asked frequently in different forms, and often obtains "lol you're not doing it properly" responses. Pretty sure that's because there's a common sense scenario people (including me) are trying to use as an implementation, and the solution is not obvious (if you've not done it before).

Would accept an answer which "lets the fly out of the bottle".

Given

project/
    __init__.py
    /code
        __init__.py
        sut.py
    /tests
        __init__.py
        test_sut.py

Where tests_sut.py starts:

import code.sut

Running nosetests in the root dir leads to:

ImportError: No module named code.sut

Avenues traveled:

a) do a relative using

from ..code import sut

b) add root of project to PYTHONPATH

c) use the

sys.path.append

to add the .. path before the imports at the start of each test module.

d) just remember to do a

setup.py 

on the project to install the modules into the site-packages before running tests.


So the requirement is to have tests located beneath the test package root which have access to the project. Each of the above don't feel "natural" to me, have proved problematic or seem like too much hard work!

In java this works, but basically by dint of your build tool / IDE placing all your classes on the classpath. Perhaps the issue is I'm expecting "magic" from Python? Have noted in the Flask webframework tests, option d) seems to be preferred.

In any case, statements below recommending a preferred solution would remove the feeling of "unnaturalness" in my own.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I had the same problem and found an answer in a related question work for me.

Just remove the __init__.py in the project root.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...