Search code examples
unit-testingdata-structuresprojectcode-organization

Python programmation project structure with unit testing


I have been programming for a while, but never really got deep into it. Now I'm working in a reasearch center and I need to make my stuff coherent and compatible. My coworkers proposed to me a "Standard" method of organizing my project:

Project
  |_ LICENCE.txt
  |_ README.txt

  |_ code
     |_ main.py
     |_ __init__.py

  |_ tests
     |_ context.py
     |_ test_main.py

That way they say it will be easier to do unit testing and all.

I have visited tens of websites that do exactly the same thing, so I figured it wouldn,t be that bad: wrong. I have been trying for the whole weekend now to make this work and I feel like I'm just getting colder.

Here is what I have: IDE image with project structure with context.py open in the window

From what I have read in the past few days, This is the correct method, my problem is, no matter how I write it, the code won't recognize bidon.py, nor the funcitons defined in it.

bidon.py is just a file containing

def add(x, y):
    return x+y


def sub(x, y):
    return x-y

in context it is not possible to use the function add, but when the test file and the .py are in the same folder, it seems to work...

But why doesn't it work even though I have added the path? I tried (in the context.py):

import code

import code
import bidon

from code import bidion

from code import *

from code import bidon
from bidon import *

from code import bidon
from bidon import add

none of these worked.

It gets worse when I try to use the context.py in a test file. For example in test_bidon.py, I have

import unittest
from .context import code

class TestBidon(unittest.TestCase):
    def test_add(self):
        result = add(10, 5)
        self.assertEqual(result, 15)


if __name__ == "__main___":
    unittest.main()

This creates an error telling me that test_bidon.py is not a package? Again, I tried multiple combinaisons, none worked. Please help me figure this out! I'm out of options and I don't want to spend another day looking for nothing.


Solution

  • I have found a way to do what I wanted. I made a github of my Basic project architecture as I wanted it. There is still work to do in the setup file, but the master now works.

    url: https://github.com/PyMarc2/BasicProjectArchitecture

    Basically, I don't know why, but it didn't work well when the setup file was in the test folder. Instead, put the setup file right in the project folder.

    (os.path.abspath(os.path.join(os.path.dirname(__file__), testFolderNameSetup)))
    

    That command is what saved me.

    Thank you!