From 2762b7eb1833d745226199181a49b28c8a1fc44a Mon Sep 17 00:00:00 2001 From: Paul Ganssle Date: Wed, 17 Jul 2024 15:09:32 -0400 Subject: [PATCH] Use tmp_path in ghostwriter tests Before creating the temporary functions, moves the local directory to a clean temporary directory; this should guarantee that the files to be created don't exist, and handles cleanup automatically. This also works when the local directory that the tests are executed from is not writable, but the temporary directory is. --- .../tests/ghostwriter/test_ghostwriter.py | 36 +++++++++++-------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/hypothesis-python/tests/ghostwriter/test_ghostwriter.py b/hypothesis-python/tests/ghostwriter/test_ghostwriter.py index f63f881bf3..32b8a2a377 100644 --- a/hypothesis-python/tests/ghostwriter/test_ghostwriter.py +++ b/hypothesis-python/tests/ghostwriter/test_ghostwriter.py @@ -11,6 +11,7 @@ import ast import enum import json +import os import re import socket import unittest @@ -450,13 +451,22 @@ def test_get_imports_for_strategy(strategy, imports): @pytest.fixture -def temp_script_file(): - """Fixture to yield a Path to a temporary file in the local directory. File name will end - in .py and will include an importable function. +def in_temp_path(tmp_path): + """Fixture to execute tests in a temporary path.""" + old_path = Path.cwd() + os.chdir(tmp_path) + yield + os.chdir(old_path) + + +@pytest.fixture +def temp_script_file(in_temp_path): + """Fixture to create a script file in a temporary working directory. + + Changes the working directory to a temporary directory, then yields an extant file + whose name will end in .py and which includes an importable function. """ p = Path("my_temp_script.py") - if p.exists(): - raise FileExistsError(f"Did not expect {p} to exist during testing") p.write_text( dedent( """ @@ -466,18 +476,17 @@ def say_hello(): ), encoding="utf-8", ) - yield p - p.unlink() + return p @pytest.fixture -def temp_script_file_with_py_function(): - """Fixture to yield a Path to a temporary file in the local directory. File name will end - in .py and will include an importable function named "py" +def temp_script_file_with_py_function(in_temp_path): + """Fixture to create a python file in a temporary working directory. + + Changes the working directory to a temporary directory, then yields an extant file + whose name will end in .py and which includes an importable function named "py". """ p = Path("my_temp_script_with_py_function.py") - if p.exists(): - raise FileExistsError(f"Did not expect {p} to exist during testing") p.write_text( dedent( """ @@ -487,8 +496,7 @@ def py(): ), encoding="utf-8", ) - yield p - p.unlink() + return p def test_obj_name(temp_script_file, temp_script_file_with_py_function):