Skip to content
Advertisement

how to add a package to sys path for testing

This question is occasioned by instructions in the python guide for adding a project to sys path to use in tests, which do not seem to work unless I am misunderstanding the instructions

I have a directory structure for a python project like this

JavaScript

According to the python guide, I should create a test/context.py file and add this

JavaScript

Then, in my test/test_something.py file, it says I can do this

JavaScript

The guide says “This will always work as expected”.

but, when I cd into test and run

JavaScript

I get an error

JavaScript

and the error message specifically refers to this: from .context import sample

Question: How can I add my sample package to the sys path correctly?

When answering, can you also clarify if the solution will handle absolute imports within the sample package. For example, my sample.a imports sample.b etc. When I had my tests structured a different way, I did an absolute import of sample.a, but since it has a relative import of from .b import Boo, it produced a similar error

Update

JavaScript

Update

if I run the following command from root directory

JavaScript

It says , “Ran 0 tests in 0.000s”

If, as was suggested in the comments by @cuongnv, I run this from root directory

JavaScript

or this (without the file extension)

JavaScript

It says “Import by filename is not supported”

Advertisement

Answer

Question: How can I add my sample package to the sys path correctly?

You’re doing it the right way, but you missed declaring your folder to be a package. Try solution of Christian, it should work.

Your path is stored in sys.path. By doing this:

JavaScript

You’re telling your python to add upper folder (of current file) into your path. As sys.path is a list, you can using other methods of list like insert, append

In your case, you’re inserting your upper dir at top of the path list.

See:

JavaScript

So, from here, when you have

JavaScript

your python will try to look in path to see if there is any sample package.

Unfortunately, it can’t find sample as you didn’t make it as a package because your forgot __init__.py in sample folder.

Hope my explanation would help you to understand and you can handle other situations different to this.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement