1

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.

Marty Wallace
  • 34,046
  • 53
  • 137
  • 200
  • See related question http://stackoverflow.com/questions/1849311/how-should-i-organize-python-source-code – Mihai8 Jun 22 '13 at 10:16

2 Answers2

0

This depends on which test runner you want to use.

pytest

I recently learned to like pytest.

It has a section about how to organize the code.

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()
User
  • 14,131
  • 2
  • 40
  • 59
0

I have always loved nosetests, so here is my solution:

Problem

App

    __init__.py
    main.py

Tests

    __init__.py
    tests.py

Then, open the command prompt, CD to /path/to/Problem and type:

nosetests Tests

it will automatically recognize and run the tests. However, read this:

Any python source file, directory or package that matches the testMatch regular expression (by default: (?:^|[b_.-])[Tt]est) will be collected as a test (or source for collection of tests). [...]

Within a test directory or package, any python source file matching testMatch will be examined for test cases. Within a test module, functions and classes whose names match testMatch and TestCase subclasses with any name will be loaded and executed as tests.

This basically means that your tests (both your files and function/methods/classes) have to begin with the "test" or "Test" word.

More on Nosetests usage here: Basic Usage.

Community
  • 1
  • 1
Markon
  • 4,480
  • 1
  • 27
  • 39