1

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?

Qi Chen
  • 1,648
  • 1
  • 10
  • 19

1 Answers1

1

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'))
Dewald Abrie
  • 1,392
  • 9
  • 21
  • `as_absolute = lambda path: os.path.abspath(os.path.join(__file__, "../", path))` !!! yess finallly. i've been messing with this for at least an hour. – O.rka Aug 24 '18 at 18:14