Search code examples
pythonpython-unittestpython-moduledirectory-structure

What is the proper way to write unit tests on modules (in subdirectories) which use other modules in the parent directory in Python


Tried to describe it as best as I could in the title. I'm quite new to using python for a big project. Usually, I only use it for small scripts. I read through the manual and found out what is the proper way to make modules.

So I have the following file structure set up now:

- main.py
- module1
  - __init__.py
  - thing1.py
  - thing2.py
- module2
  - __init__.py
  - thingA.py
  - thingB.py

My project will run when I start main.py.

I know I can write simple unit tests for every 'thing' by using the if __name__ == '__main__': in every one of them which is what I do.

The file thingB.py needs thing2.py to work. As long as main.py is started, thingB will find thing2. But when I start thingB directly (to make its unit test run) in its own directory, it won't find thing2.

What is the proper approach for this?


Solution

  • You should run everything from your main directory:

    python -m module1.thing1
    python -m module2.thingA
    

    this way module1 and module2 can import from each other. Unit tests should be run in the same way:

    python -m unittest discover module1
    python -m unittest discover module2