Python - organising code and test suite
Question: I am very new to python, coming from a php background and cant figure out the
best way to organise my code.

Currently I am working through the project euler exercises to learn python. I
would like to have a directory for my solution to the problem and a directory
that mirrors this for tests.

So ideally:

    
    
    Problem
        App
            main.py
        Tests
            maintTest.py
    

Using php this is very easy as i can just require_once the correct file, or
amend the `include_path`.

How can this be achieved in python? Obviously this is a very simplistic
example - therefore some advice on how this is approached on a larger scale
would also be extremely grateful.


Answer: This depends on which test runner you want to use.

**pytest**

I recently learned to like [pytest](http://pytest.org/latest/getting-
started.html#our-first-test-run).

It has a section about [how to organize the
code](http://pytest.org/latest/goodpractises.html#choosing-a-test-layout-
import-rules).

If you can not import your main into the code then you can use the tricks
below.

**unittest**

When I use `unittest` I do it like this:

**with import main**

    
    
    Problem
        App
            main.py
        Tests
            test_main.py
    

`test_main.py`

    
    
    import sys
    import os
    import unittest
    sys.path.append(os.path.join(os.path.dirname(__file__), 'App'))
    import main
    
    # do the tests
    
    if __name__ == '__main__':
        unittest.run()
    

**or with import App.main**

    
    
    Problem
        App
            __init__.py
            main.py
        Tests
            test.py
            test_main.py
    

`test.py`

    
    
    import sys
    import os
    import unittest
    sys.path.append(os.path.dirname(__file__))
    

`test_main.py`

    
    
    from test import *
    import App.main
    
    # do the tests
    
    if __name__ == '__main__':
        unittest.run()
    

