3

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)

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

For what it's worth,

I too come from the Java community, and I'm getting started with Python. And I'm having this exact same question.

I ask three different sources:

Tests are put in files of the form test_*.py or *_test.py, and are usually placed in a directory called tests/ in a package’s root.

  • Github CoPilot (Powered by ChatGPT 4):

In Python, it is common practice to separate tests into a dedicated folder, typically named tests or test, rather than placing them in the same folder as the production code. This helps to keep the project organized and makes it easier to manage and run tests.

  • Mistral:

In Python, the organization of tests can vary depending on the project and the preferences of the development team. However, it is common practice to separate tests into a dedicated folder, similar to how it is done in Java. This approach helps keep the production code and test code organized and makes it easier to manage and maintain.

Conclusion: you may go ahead and place your tests in a separate folder if this is compliant with your team rules or if you're working on a new project!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.