0

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?

scippie
  • 2,011
  • 1
  • 26
  • 42
  • Aren't you storing the tests in a separate file? Your description is a bit ambiguous, you say you've read through the manual, I'm assuming the unittest docs, they're quite clear on tests living inside their own modules ([one example](https://docs.python.org/3.8/library/unittest.html#command-line-interface)). See also [this SO answer](https://stackoverflow.com/questions/61151/where-do-the-python-unit-tests-go). – Nobilis Aug 13 '20 at 11:12
  • I hadn't read about unit tests no, I was basing this question on [6.1.1 Executing modules as script](https://docs.python.org/3/tutorial/modules.html#executing-modules-as-scripts) which is sufficient for my needs... I think. – scippie Aug 13 '20 at 11:36

1 Answers1

0

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
Piotr Praszmo
  • 17,928
  • 1
  • 57
  • 65