[Python] Setting os.environ["TMP"] works in the code but not in pytest tests

Discussão em 'Python' iniciado por Stack, Agosto 6, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following python code:

    import tempfile
    import os

    def test_paul_confused():
    os.environ["TMP"] = "/home/fedora"
    assert tempfile.gettempdir() == "/home/fedora"
    print(tempfile.gettempdir())

    test_paul_confused()


    When I run this code from the command line I get the expected result:

    (fedora) [fedora@ip-10-254-6-135 ~]$ uv run pytest.py
    /home/fedora


    However when I run the code via pytest, the TMP directory doesn't get set correctly!

    (fedora) [fedora@ip-10-254-6-135 ~]$ uv run pytest pytest.py
    ============================ test session starts =============================
    platform linux -- Python 3.13.5, pytest-8.4.1, pluggy-1.6.0
    rootdir: /home/fedora
    collected 0 items / 1 error

    =================================== ERRORS ===================================
    _________________________ ERROR collecting pytest.py _________________________
    pytest.py:9: in <module>
    test_paul_confused()
    pytest.py:6: in test_paul_confused
    assert tempfile.gettempdir() == "/home/fedora"
    E AssertionError: assert '/tmp' == '/home/fedora'
    E + where '/tmp' = <function gettempdir at 0xffffb3d83d80>()
    E + where <function gettempdir at 0xffffb3d83d80> = tempfile.gettempdir
    ========================== short test summary info ===========================
    ERROR pytest.py - AssertionError: assert '/tmp' == '/home/fedora'
    !!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!
    ============================== 1 error in 0.07s ==============================
    (fedora) [fedora@ip-10-254-6-135 ~]$


    Why is this code behaving differently in testing than when it's run outside of testing?

    Continue reading...

Compartilhe esta Página