Search code examples
pythonnose

'No such file or directory' error when using nosetests


I have a little Python project of which I recently made a Conda package. Making the package was a pain on its own, however, I recently started adding tests to this using nosetests, which made it even harder.

To introduce: my package takes a certain input, performs a lot of (quantum chemical) calculations and then generates a folder in the same directory as the script which calls the package, containing the output data (some .png files, .txt files and binary files)

Using nosetests, I would like to check whether these output files are how they should be. I created a Python test script (using unittest) which creates the input and calls my package. Next, it imports the created file and the test file. However, this is where it goes wrong. I get the error that this file does not exist:

FileNotFoundError: [Errno 2] No such file or directory: 'results\\output.txt'

The directory looks like this:

project-path\
- tests\
  - test-script.py
  - results\
    - output.txt

I call nose by running this in Anaconda prompt:

project-path> nosetests tests

And I import the file in the Python test script using:

result_file = open('results\\output.txt', 'r').read()

Does anyone know what goes wrong here? I think it has to do with the fact that the tests are executed in a test environment. In that case: how do I import my files?


Solution

  • Get the absolute path to output.txt, it is indeed the most reliable way to locate and open it.

    import os, sys
    
    basedir = os.path.dirname(sys.argv[0])
    filename = "output.txt"
    path = os.path.join(basedir, "results", filename)
    
    result_file = open(path, 'r').read()