5

I have a question about how to correctly import module in python unit test module. this is my directory structure

project -
        | _ Library _
        |            |_ TimeCalculator.py
        | _ Test _
                  |_ UnittestFile.py

and I want to test the function in TimeCalculator.py so in UnittestFile.py I write

from .Library.TimeCalculator import TimeCalculator

but the error come out saying ImportError: attempted relative import with no known parent package
I want to ask how to import without setting the PATH in this case.

0

1 Answer 1

6

As stated in python - Running unittest with typical test directory structure - Stack Overflow, you should create a __init__.py file in both folders, Library and Test.

For your specific structure:

project
├── Library
│   ├── __init__.py         # make it a package
│   └── TimeCalculator.py
└── test
    ├── __init__.py         # also make test a package
    └── UnittestFile.py

Then, you should remove the first . from your import sentence:

from Library.TimeCalculator import TimeCalculator

PD: Not sure if is a repeated question, because the answer is almost the same than python - Running unittest with typical test directory structure - Stack Overflow but is sightly different because he has to remove the first .

Sign up to request clarification or add additional context in comments.

1 Comment

I think that's a good duplicate target. The . just seems like a typo.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.