[TIP] I have some data files I want to use in my tests -- how do I specify where they are?

Olemis Lang olemis at gmail.com
Mon Dec 21 05:02:52 PST 2009

On Sun, Dec 20, 2009 at 11:46 AM, C. Titus Brown <ctb at msu.edu> wrote:
> On Sun, Dec 20, 2009 at 11:43:19AM -0500, Matthew Wilson wrote:
>> I'm writing some code to extract and yield some attachments out of
>> email messages.  I have a file named email_parsers.py and another file
>> in a tests/ subdirectory named test_email_parsers.py
>> I have a few email messages saved as text files. These files are in
>> that tests/ directory.
>> In my test code, I want to know how to open those email files.  Should
>> I use something like os.dirname(__file__)?
> that's what I use -- I calculate everything relative to the Python file using
> the data.

If the package is not in the local file system (e.g. it's packaged
inside an EGG file or whatever ) then this does not work. My
suggestion is :

  - Place data files inside `tests/data`
  - Add it to `package_data` in `setup.py`
  - In your test code use pkg_resources.(resource_filename |
resource_stream | resource_string)
    to load the data .

>> I know I won't always run my tests from the tests/ subdirectory
> ...so this does't matter :)

most of the time



Blog ES: http://simelo-es.blogspot.com/
Blog EN: http://simelo-en.blogspot.com/

Featured article:
Initial version of protocol-provider patch. Patch does not currently
apply cleanly - it hasn'...  -

More information about the testing-in-python mailing list