I ran into a dilemma when writing a PyUnit test case that read in sample data from a text file in the same package as the test. How I could successfully reference the relative location of the file changed depending on how I executed the code. So for example, when I ran the unit test in isolation, it passed, but when I ran the test as part of a suite, it failed, because the code was being executed from a different location. I needed to find a way to determine the relative location of the file at run-time no matter how it was executed.
1 2 3 4 5 6 7 8 9
import os, sys, inspect def execution_path(filename): return os.path.join(os.path.dirname(inspect.getfile(sys._getframe(1))), filename) # open a file in a test open(execution_path('sample.txt')).read() # get the absolute path of the file os.path.abspath(execution_path('sample.txt'))
The key is to use introspection to examine the call stack and get information about the calling function--the same function that wants to reliably reference the file within the package.
And of course, I eventaully refactored the function into a separate package so I could import it into multiple tests.
To derive this solution, I found the following resources very useful, and you might too: http://www.peterbe.com/plog/python-package-execution-path http://www.faqs.org/docs/diveintopython/regression_path.html http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 http://docs.python.org/lib/module-sys.html