Python nose test with relative pandas file path

717 Views Asked by At

I am trying to write a unit test for a piece of code that includes using pandas to read a CSV file from a relative path. The directory structure is:

./
./thing1/main.py
./thing1/test_main.py
./thing1/dat/file.csv
./otherthings/...

In main.py, I have:

def doThings:
    pandas.read_csv('dat/file.csv')

if __name__ == '__main__':
    doThings()

In test_main.py, I have

class TestMain:
    def setup(self):
        doThings()

    def test_thing(self):
        pass  # there's other logic in here

Things work fine if I run main.py, but when I ask Anaconda to "run project tests", I get an IOError complaining that 'dat/file.csv' does not exist. It's related to the fact that it's a relative path, since when I change it to /home/user/.../thing1/dat/file.csv, it works. Is there a way that I can make the unit test work while keeping the relative path?

1

There are 1 best solutions below

1
On

I have the same problem. If you call os.path.abspath() on your relative path you'll see that the absolute path is wrong. The only workaround I found was to change the relative path to absolute to the test file path by using __file__ and then moving up one level to exclude the file name:

testImgPath = os.path.abspath(os.path.join(__file__, '../', 'testFiles', 'imgName.jpg'))