nos
nos

Reputation: 20862

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?

Upvotes: 3

Views: 2860

Answers (2)

hoefling
hoefling

Reputation: 66171

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.

Upvotes: 6

DobromirM
DobromirM

Reputation: 2027

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.

Upvotes: 1

Related Questions