title: Ensuring py.test includes the application directory in sys.path
body: <p>I have a project directory structure as follows (which I think is pretty standard):</p>
  
  <pre><code>my_project
      setup.py
      mypkg
          __init__.py
          foo.py
      tests
          functional
              test_f1.py
          unit
              test_u1.py
  </code></pre>
  
  <p>I'm using py.test for my testing framework, and I'd expect to be able to run <code>py.test tests</code> when in the <code>my_project</code> directory to run my tests. This does indeed work, until I try to import my application code using (for example) <code>import mypkg</code> in a test. At that point, I get the error "No module named mypkg". On doing a bit of investigation, it appears that <code>py.test</code> runs the tests with the directory of the test file in <code>sys.path</code>, but <em>not</em> the directory that <code>py.test</code> was run from.</p>
  
  <p>In order to work around this, I have added a <code>conftest.py</code> file to my <code>tests</code> directory, containing the following code:</p>
  
  <pre><code>import sys, os
  
  # Make sure that the application source directory (this directory's parent) is
  # on sys.path.
  
  here = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  sys.path.insert(0, here)
  </code></pre>
  
  <p>This seems to work, but is it a good way of making sure that the tests see the application code? Is there a better way of achieving this, or am I doing something wrong in how I have my project structured?</p>
  
  <p>I've looked at some other projects that use <code>py.test</code> (for example, <code>pip</code>) but I can't see code that does anything like this, and yet running <code>py.test tests</code> seems to work there. I don't know quite why, but I'm worried that they may have achieved the same result in a simpler way.</p>
  
  <p>I've looked in the <code>py.test</code> documentation, but I can't see an explanation of this problem or what the recommended approach is to deal with it.</p>