lundi 2 juillet 2018

Python imports for testing modules with additional dependencies

I want to have my tests in a separate folder from my package code, such that from the top level directory of my project I can run python sample/run.py or python tests/test_sample.py, and have both of them resolve all the imports properly.

My directory structure looks like this:

sample/
   __init__.py
   helper.py
   run.py
tests/
   context.py
   test_run.py

I know there are supposedly many ways to achieve this, as discussed here: Python imports for tests using nose - what is best practice for imports of modules above current package

However, when I try to run python tests/test_run.py, I get a ModuleNotFoundError for 'helper', because 'sample/run.py' imports 'sample/helper.py'.

In particular, I am trying to follow the convention (suggested in the Hitchhiker's Guide to Python) of explicitly modifying the path using:

import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

As a result, I have a blank sample/__init__.py, along with the following code files...


sample/run.py:

from helper import helper_fn
def run():
    helper_fn(5)
    return 'foo'
if __name__ == '__main__':
    run()

sample/helper.py:

def helper_fn(N):
    print(list(range(N)))

tests/context.py:

import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

import sample

tests/test_sample.py:

from context import sample
from sample import run

assert run.run() == 'foo'


So I have two questions:

  1. Why is Python unable to find the 'helper' module?
  2. How do I fix things so that I can run both sample/run.py and tests/test_run.py from the top-level directory?

Aucun commentaire:

Enregistrer un commentaire