Import parent directory for quick tests

I searched this site from top to bottom, but did not find a single way to actually accomplish what I want in Python3x. This is a simple toy application, so I decided that I could write some simple test cases in the statements and call it day. It generates reports, and so I would like to make sure that my code does nothing wrong with the changes.

My current directory structure: (only relevant parts are included)

project -model __init__.py my_file.py -test my_file_test.py 

I have a time when my_file_test.py imports the file my_file.py.

As I already said. I searched this site from top to bottom and no solution worked. My version of Python 3.2.3 runs on Fedora 17.

Attempts previously tried: https://stackoverflow.com/a/32072/import/32072/ ... Import modules from the parent folder Can anyone explain the relative import of python? How to do relative import in python

In every attempt, I get an error message:

ImportError: no module named * OR ValueError: Attempted relative import in non-package

What's going on here. I tried every accepted answer on SO in the same way as in all environments. Without doing anything interesting here, but as a .NET / Java / Ruby programmer, this turns out to be an absolute definition of intuitiveness.

EDIT: If this is important, I tried loading the class that I am trying to import into the REPL, and I get the following:

 >>> import datafileclass >>> datafileclass.methods Traceback (most recent call last): File "<stdin>", line 1, in <module> >>> x = datafileclass('sample_data/sample_input.csv') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'module' object is not callable 

If that matters ... I know that the functionality in the class works, but I cannot import it, which currently causes an inability to check. In the future, this will certainly cause integration problems. (names changed to protect the innocent) having received within a few weeks the desired functionality for this library iteration ... any help can be useful. Would do it in Ruby, but the client wants Python to be a learning experience,

+7
source share
1 answer

Create your code as follows:

 project -model __init__.py my_file.py -tests __init__.py test_my_file.py 

It is important to note that your tests directory must also be a modules directory (it has an empty __init__.py file in it).

Then in test_my_file.py use from model import my_file and from the top directory run python -m tests.test_my_file . This calls test_my_file as a module, which is why Python adjusts its import path to include your top level.

Even better, you can use pytest or the nose, and running py.test will automatically pick up the tests.

I understand that this does not answer your question, but it will be much easier for you to work with Python standards, and not with them. This means that you structure your project using tests in your own top-level directory.

+6
source

All Articles