2

I'm working on a small Python package, and I'm writing unit tests for it. I have my package structure laid out in fairly typical Python fashion:

mypackage/
    mymodule.py
    test/
        test_mymodule.py

This particular module is designed to read the contents of a file, do a thing with said contents, and then return a value. In order to test this, I want to include some input files in my test suite.

I suppose I could organize them like this:

mypackage/
    mymodule.py
    test/
        test_mymodule.py
        test_input01.txt
        test_input02.txt

And then locate the files to read using the __file__ global variable.

My question is: is this a reasonably Pythonic way of organizing things? I'm concerned that guessing paths in this manner won't be reliable in any environment (e.g., if the package is installed via pip or etc.).

Specifically, I'm looking for either 1) some official documentation that supports this (or some other) approach, or 2) a well-regarded existing project that uses this (or some other) approach.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
CmdrMoozy
  • 3,870
  • 3
  • 19
  • 31
  • 1
    It's pretty much ok to use `__file__` for locating the current directory path and a place where the test data lives. As an example, see [pep8](https://github.com/jcrocholl/pep8) github project, particularly pay attention to how tests are organized in `testsuite` package - `*.py` files there with names like `E10.py`, `E11.py` are used as target files in tests. Hope that helps. – alecxe Jan 10 '14 at 00:23
  • You are very right - they do indeed use this exact technique. If it's good enough for the Python style guide, it's good enough for me. :) Add that as an answer and I'll accept it. Thanks! – CmdrMoozy Jan 10 '14 at 00:25

1 Answers1

2

It's pretty much ok to use __file__ for locating the current directory path and a place where the test data lives.

As an example, see pep8 github project, particularly pay attention to how tests are organized in testsuite package - *.py files there with names like E10.py, E11.py are used as target files in tests.

Also, pylint uses similar approach (based on __file__), but the test data is organized in subpackages.

Also, see:

Hope that helps.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 1
    In particular, one can see them using `__file__` to locate the test directory here: https://github.com/jcrocholl/pep8/blob/master/testsuite/support.py, and then using that constant to load test input files here: https://github.com/jcrocholl/pep8/blob/master/testsuite/test_api.py. It seems like this is a reliable way to implement this. :) – CmdrMoozy Jan 10 '14 at 00:40