Python: unit tests in different folder than production code?

Viewed 124

I've read multiple articles and questions on StackOverflow and was wondering why no one uses the following structure for unit tests in Python:

MyProject/
    main/
        module1/
            my_file.py
    test/
        module1/
            test_my_file.py

What I've read is that you either:

  1. Put test_my_file.py in the same directory as my_file.py:

    MyProject/
        module1/
            my_file.py
            test_my_file.py
    
  2. Put test_my_file.py in a directory named test in the same directory as my_file.py:

    MyProject/
        module1/
            my_file.py
            test/
                test_my_file.py
    

Notes:

  1. I come from a Java world: having unit test code at the same place as production code feels weird to me.
  2. I'm very new to Python: there's probably some obvious reason I'm missing here. (My first guess would be that it has something to do with modules)
1 Answers

Maybe it's because I also wrote a lot of Java code before coming to Python, but I also keep my tests in a separate folder from production code on most of my Python projects. The only hassle is that sometimes you have to mess around with PYTHONPATH or relative imports to help the tests find the production code for importing.

In this project, I set the PYTHONPATH in my tox configuration.

setenv = PYTHONPATH=plugin/PySrc
commands =
     py.test plugin/PySrc/ test/PySrc/ --cov-report term-missing --cov plugin/PySrc/
     coverage xml
Related