How to arrange and set up unit testing in Python
Question: I am working on a project in Python, using Git for version control, and I've
decided it's time to add a couple of unit tests. However, I'm not sure about
the best way to go about this.

I have two main questions: which framework should I use and how should I
arrange my tests? For the first, I'm planning to use unittest since it is
built in to Python, but if there is a compelling reason to prefer something
else I'm open to suggestions. The second is a tougher question, because my
code is already somewhat disorganized, with lots of submodules and relative
imports. I'm not sure where to fit the testing code. Also, I'd prefer to keep
the testing code seperate from everything else if possible. Lastly, I want the
tests to be easy to run, preferably with a single commandline command and
minimal path setup.

How do large Python projects handle testing? I understand that there is
typically an automated system to run tests on all new checkins. How do they do
it? What are the best practices for setting up a testing system?


Answer: Test framework choosing is mostly about personal preferences, there are some
of widespread:

  * unittest — it's a clone of java's junit framework, so its syntax not so python-frendly
  * unittest2 — a featured unittest
  * pytest — comprehensive and complicated framework, but its source code is a little scary, so it's sometimes difficult to find solution if you have any issues 
  * nose — it grown from pytest but simpler, maybe its a good idea for you to use nose

Usual directory structure, for example, is:

    
    
    - project
    | - module_name
      | - submodule.py
    | - tests
      | requirements.txt
      | test_submodule.py
    | - requirements.txt
    

One of best practices is using virtualenv:

    
    
     $ virtualenv env  # create virtualenv
     $ env/bin/activate  # activate virtualenv
     $ pip install -r requirements.txt  # install project requirements
     $ pip install -r tests/requirements.txt  # install testing requirements
     $ py.test  # if you use pytest
    

