Search code examples
pythonpytesttemporary-directory

How to get the temporary path using pytest tmpdir.as_cwd


In a python test function

def test_something(tmpdir):
    with tmpdir.as_cwd() as p:
        print('here', p)
        print(os.getcwd())

I was expecting p and the os.getcwd() would give the same result. But in reality, p points to the directory of the test file whereas os.getcwd() points to the expected temporary file.

Is this expected behavior?


Solution

  • Take a look at the docs of py.path.as_cwd:

    return context manager which changes to current dir during the managed "with" context. On __enter__ it returns the old dir.

    The behaviour you are observing is thus correct:

    def test_something(tmpdir):
        print('current directory where you are before changing it:', os.getcwd())
        # the current directory will be changed now
        with tmpdir.as_cwd() as old_dir:
            print('old directory where you were before:', old_dir)
            print('current directory where you are now:', os.getcwd())
        print('you now returned to the old current dir', os.getcwd())
    

    Just remember that p in your example is not the "new" current dir you are changing to, it's the "old" one you changed from.