Search code examples
pythonpython-3.xpython-unittest

Run python unittest in context of specific directory


In my python application, I open mp3 files with relative paths from where the program was started. To keep it simple, I made a minimal reproduction of the problem I have in my project here.

Basically, I have a structure like this:

src
└─ main.py
test
└─ test_main.py

In main.py I have a simple function that prints and returns the current working directory:

def get_cwd() -> str:
    directory = os.path.basename(os.getcwd())
    print('Current directory =', directory)
    return directory

So if I cd into the src folder and run python main.py I see:

Current directory = src

This is the desired behavior, as in my program the file paths to the mp3 files are relative to src.

The problem arises when I try to write tests. I can't seem to get a test like this to pass, no matter what I pass to --start-directory and --top-level-directory:

def test_get_cwd(self):
    print('testing get_cwd()')
    current_dir = get_cwd()
    self.assertIsNotNone(current_dir)
    self.assertEqual(current_dir, 'src')

The question: How can I run my tests as if they were running in the context of a specific directory if they are saved to a different directory?

Constraints:

  • the tests must import using absolute paths, as in my example: from src.main import get_cwd

Solution

  • There is a os function to change the directory, try adding os.chdir('src') to your test.

    import unittest
    import os
    
    from src.main import get_cwd
    
    
    class TestMain(unittest.TestCase):
    
        def test_get_cwd(self):
            os.chdir('src')
            print('testing get_cwd()')
            current_dir = get_cwd()
            self.assertIsNotNone(current_dir)
            self.assertEqual(current_dir, 'src')