How to get the temporary path using pytest tmpdir.as_cwd

2.7k Views Asked by At

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?

2

There are 2 best solutions below

0
hoefling On BEST ANSWER

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.

0
DobromirM On

From the documentation:

You can use the tmpdir fixture which will provide a temporary directory unique to the test invocation, created in the base temporary directory.

Whereas, getcwd stands for Get Current Working directory, and returns the directory from which your python process has been started.