Skip to content

Commit

Permalink
Use tmp_path in ghostwriter tests
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
pganssle committed Jul 17, 2024
1 parent 6e7921e commit b381394
Showing 1 changed file with 20 additions and 12 deletions.
32 changes: 20 additions & 12 deletions hypothesis-python/tests/ghostwriter/test_ghostwriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import ast
import enum
import json
import os
import re
import socket
import unittest
Expand Down Expand Up @@ -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(
"""
Expand All @@ -467,17 +477,16 @@ def say_hello():
encoding="utf-8",
)
yield p
p.unlink()


@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(
"""
Expand All @@ -488,7 +497,6 @@ def py():
encoding="utf-8",
)
yield p
p.unlink()


def test_obj_name(temp_script_file, temp_script_file_with_py_function):
Expand Down

0 comments on commit b381394

Please sign in to comment.