Search code examples
pythonpython-3.xpython-unittest

Python unittest gives file not found exception


I have a core class which is as below:

class GenerateDag(object):

    def __int__(self):
        pass

    def generate_dag(self, manifest: dict):
        """
        :return: bytes of the file passed
        """
        with open('../../resources/dag.py', 'rb') as f:
            return f.read()

TestCase:

def test_generate_dag(self):
        manifest = Mock()
        result = GenerateDag().generate_dag(manifest)
        expected = b"some-byte-content"
        assert result == expected   

The project structure is as follows:

enter image description here

When I create an instance something like this GenerateDag().generate_dag({}) it gives me the proper content of the file as I expected but however, but when I run the test case it gives me the below error:

FileNotFoundError: [Errno 2] No such file or directory: '/Users/../IdeaProjects/some-projct/provisioner/.tox/py38/lib/python3.8/resources/dag.py'

I also tried the below logic in the core class:

dir_path = os.path.dirname(pathlib.Path(__file__).parent.parent)
conf_path = os.path.join(dir_path, 'resources/dag.py')

But even this didn't help. So what else I am missing here? I run the tests through tox

P.S: My core class is in src/services


Solution

  • If I have a tree structure such as:

     |
     +- resources
       +-- __init__.py
       +-- data.txt
    

    Then to access that information I would use:

    from importlib.resources import files
    
    my_resource = files('resources').joinpath('data.txt')
    print(my_resource.read_bytes())
    

    You might want to put your resources directory under src/services directories which is your services module; in which case it would be:

    my_resource = files('services.resources').joinpath('data.txt')