Skip to content

Commit

Permalink
tests: use tmp_path instead of tmpdir
Browse files Browse the repository at this point in the history
Signed-off-by: Henry Schreiner <[email protected]>
  • Loading branch information
henryiii committed Nov 25, 2024
1 parent aa09595 commit 1f782bd
Show file tree
Hide file tree
Showing 5 changed files with 186 additions and 195 deletions.
16 changes: 9 additions & 7 deletions nox/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,12 @@ def __init__(self, reason: str | None = None) -> None:
self.reason = reason


def which(program: str | os.PathLike[str], paths: Sequence[str] | None) -> str:
def which(
program: str | os.PathLike[str], paths: Sequence[str | os.PathLike[str]] | None
) -> str:
"""Finds the full path to an executable."""
if paths is not None:
full_path = shutil.which(program, path=os.pathsep.join(paths))
full_path = shutil.which(program, path=os.pathsep.join(str(p) for p in paths))
if full_path:
return os.fspath(full_path)

Expand Down Expand Up @@ -79,7 +81,7 @@ def run(
*,
env: Mapping[str, str | None] | None = ...,
silent: Literal[True],
paths: Sequence[str] | None = ...,
paths: Sequence[str | os.PathLike[str]] | None = ...,
success_codes: Iterable[int] | None = ...,
log: bool = ...,
external: ExternalType = ...,
Expand All @@ -96,7 +98,7 @@ def run(
*,
env: Mapping[str, str | None] | None = ...,
silent: Literal[False] = ...,
paths: Sequence[str] | None = ...,
paths: Sequence[str | os.PathLike[str]] | None = ...,
success_codes: Iterable[int] | None = ...,
log: bool = ...,
external: ExternalType = ...,
Expand All @@ -113,7 +115,7 @@ def run(
*,
env: Mapping[str, str | None] | None = ...,
silent: bool,
paths: Sequence[str] | None = ...,
paths: Sequence[str | os.PathLike[str]] | None = ...,
success_codes: Iterable[int] | None = ...,
log: bool = ...,
external: ExternalType = ...,
Expand All @@ -129,7 +131,7 @@ def run(
*,
env: Mapping[str, str | None] | None = None,
silent: bool = False,
paths: Sequence[str] | None = None,
paths: Sequence[str | os.PathLike[str]] | None = None,
success_codes: Iterable[int] | None = None,
log: bool = True,
external: ExternalType = False,
Expand All @@ -153,7 +155,7 @@ def run(
logger.info(full_cmd)

is_external_tool = paths is not None and not any(
cmd_path.startswith(path) for path in paths
cmd_path.startswith(str(path)) for path in paths
)
if is_external_tool:
if external == "error":
Expand Down
43 changes: 17 additions & 26 deletions tests/test_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,14 @@
import time
from pathlib import Path
from textwrap import dedent
from typing import TYPE_CHECKING, Any
from typing import Any
from unittest import mock

import pytest

import nox.command
import nox.popen

if TYPE_CHECKING:
from _pytest.compat import LEGACY_PATH

PYTHON = sys.executable

skip_on_windows_primary_console_session = pytest.mark.skipif(
Expand Down Expand Up @@ -214,36 +211,30 @@ def test_run_path_existent(tmp_path: Path) -> None:
)


def test_run_external_warns(
tmpdir: LEGACY_PATH, caplog: pytest.LogCaptureFixture
) -> None:
def test_run_external_warns(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
caplog.set_level(logging.WARNING)

nox.command.run([PYTHON, "--version"], silent=True, paths=[tmpdir.strpath])
nox.command.run([PYTHON, "--version"], silent=True, paths=[tmp_path])

assert "external=True" in caplog.text


def test_run_external_silences(
tmpdir: LEGACY_PATH, caplog: pytest.LogCaptureFixture
tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
caplog.set_level(logging.WARNING)

nox.command.run(
[PYTHON, "--version"], silent=True, paths=[tmpdir.strpath], external=True
)
nox.command.run([PYTHON, "--version"], silent=True, paths=[tmp_path], external=True)

assert "external=True" not in caplog.text


def test_run_external_raises(
tmpdir: LEGACY_PATH, caplog: pytest.LogCaptureFixture
) -> None:
def test_run_external_raises(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
caplog.set_level(logging.ERROR)

with pytest.raises(nox.command.CommandFailed):
nox.command.run(
[PYTHON, "--version"], silent=True, paths=[tmpdir.strpath], external="error"
[PYTHON, "--version"], silent=True, paths=[tmp_path], external="error"
)

assert "external=True" in caplog.text
Expand Down Expand Up @@ -430,8 +421,8 @@ def test_interrupt_handled_on_windows() -> None:
run_pytest_in_new_console_session("test_interrupt_handled")


def test_custom_stdout(capsys: pytest.CaptureFixture[str], tmpdir: LEGACY_PATH) -> None:
with open(str(tmpdir / "out.txt"), "w+") as stdout:
def test_custom_stdout(capsys: pytest.CaptureFixture[str], tmp_path: Path) -> None:
with (tmp_path / "out.txt").open("w+", encoding="utf-8") as stdout:
nox.command.run(
[
PYTHON,
Expand All @@ -453,16 +444,16 @@ def test_custom_stdout(capsys: pytest.CaptureFixture[str], tmpdir: LEGACY_PATH)
assert "err" in tempfile_contents


def test_custom_stdout_silent_flag(tmpdir: LEGACY_PATH) -> None:
with open(str(tmpdir / "out.txt"), "w+") as stdout: # noqa: SIM117
def test_custom_stdout_silent_flag(tmp_path: Path) -> None:
with (tmp_path / "out.txt").open("w+", encoding="utf-8") as stdout: # noqa: SIM117
with pytest.raises(ValueError, match="silent"):
nox.command.run([PYTHON, "-c", 'print("hi")'], stdout=stdout, silent=True)


def test_custom_stdout_failed_command(
capsys: pytest.CaptureFixture[str], tmpdir: LEGACY_PATH
capsys: pytest.CaptureFixture[str], tmp_path: Path
) -> None:
with open(str(tmpdir / "out.txt"), "w+") as stdout:
with (tmp_path / "out.txt").open("w+", encoding="utf-8") as stdout:
with pytest.raises(nox.command.CommandFailed):
nox.command.run(
[
Expand All @@ -485,8 +476,8 @@ def test_custom_stdout_failed_command(
assert "err" in tempfile_contents


def test_custom_stderr(capsys: pytest.CaptureFixture[str], tmpdir: LEGACY_PATH) -> None:
with open(str(tmpdir / "err.txt"), "w+") as stderr:
def test_custom_stderr(capsys: pytest.CaptureFixture[str], tmp_path: Path) -> None:
with (tmp_path / "err.txt").open("w+", encoding="utf-8") as stderr:
nox.command.run(
[
PYTHON,
Expand All @@ -509,9 +500,9 @@ def test_custom_stderr(capsys: pytest.CaptureFixture[str], tmpdir: LEGACY_PATH)


def test_custom_stderr_failed_command(
capsys: pytest.CaptureFixture[str], tmpdir: LEGACY_PATH
capsys: pytest.CaptureFixture[str], tmp_path: Path
) -> None:
with open(str(tmpdir / "out.txt"), "w+") as stderr:
with (tmp_path / "out.txt").open("w+", encoding="utf-8") as stderr:
with pytest.raises(nox.command.CommandFailed):
nox.command.run(
[
Expand Down
47 changes: 24 additions & 23 deletions tests/test_sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,6 @@
from nox import _options
from nox.logger import logger

if typing.TYPE_CHECKING:
from _pytest.compat import LEGACY_PATH

HAS_CONDA = shutil.which("conda") is not None
has_conda = pytest.mark.skipif(not HAS_CONDA, reason="Missing conda command.")

Expand Down Expand Up @@ -212,50 +209,54 @@ def test_explicit_non_interactive(self) -> None:

assert session.interactive is False

def test_chdir(self, tmpdir: LEGACY_PATH) -> None:
cdto = str(tmpdir.join("cdbby").ensure(dir=True))
def test_chdir(self, tmp_path: Path) -> None:
cdbby = tmp_path / "cdbby"
cdbby.mkdir()
current_cwd = os.getcwd()

session, _ = self.make_session_and_runner()

session.chdir(cdto)
session.chdir(str(cdbby))

assert os.getcwd() == cdto
assert cdbby.samefile(".")
os.chdir(current_cwd)

def test_chdir_ctx(self, tmpdir: LEGACY_PATH) -> None:
cdto = str(tmpdir.join("cdbby").ensure(dir=True))
current_cwd = os.getcwd()
def test_chdir_ctx(self, tmp_path: Path) -> None:
cdbby = tmp_path / "cdbby"
cdbby.mkdir()
current_cwd = Path.cwd().resolve()

session, _ = self.make_session_and_runner()

with session.chdir(cdto):
assert os.getcwd() == cdto
with session.chdir(cdbby):
assert cdbby.samefile(".")

assert os.getcwd() == current_cwd
assert current_cwd.samefile(".")

os.chdir(current_cwd)

def test_invoked_from(self, tmpdir: LEGACY_PATH) -> None:
cdto = str(tmpdir.join("cdbby").ensure(dir=True))
current_cwd = os.getcwd()
def test_invoked_from(self, tmp_path: Path) -> None:
cdbby = tmp_path / "cdbby"
cdbby.mkdir()
current_cwd = Path.cwd().resolve()

session, _ = self.make_session_and_runner()

session.chdir(cdto)
session.chdir(cdbby)

assert session.invoked_from == current_cwd
assert current_cwd.samefile(session.invoked_from)
os.chdir(current_cwd)

def test_chdir_pathlib(self, tmpdir: LEGACY_PATH) -> None:
cdto = str(tmpdir.join("cdbby").ensure(dir=True))
current_cwd = os.getcwd()
def test_chdir_pathlib(self, tmp_path: Path) -> None:
cdbby = tmp_path / "cdbby"
cdbby.mkdir()
current_cwd = Path.cwd().resolve()

session, _ = self.make_session_and_runner()

session.chdir(Path(cdto))
session.chdir(cdbby)

assert os.getcwd() == cdto
assert cdbby.samefile(".")
os.chdir(current_cwd)

def test_run_bad_args(self) -> None:
Expand Down
36 changes: 19 additions & 17 deletions tests/test_tox_to_nox.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,17 @@

from __future__ import annotations

import os
import sys
import textwrap
from typing import TYPE_CHECKING, Any
from pathlib import Path
from typing import TYPE_CHECKING

import pytest

if TYPE_CHECKING:
from collections.abc import Callable

from _pytest.compat import LEGACY_PATH

tox_to_nox = pytest.importorskip("nox.tox_to_nox")

Expand All @@ -33,21 +34,22 @@


@pytest.fixture
def makeconfig(tmpdir: LEGACY_PATH) -> Callable[[str], str]:
def makeconfig(tmp_path: Path) -> Callable[[str], str]:
def makeconfig(toxini_content: str) -> str:
tmpdir.join("tox.ini").write_text(toxini_content, encoding="utf8")
old = tmpdir.chdir()
tmp_path.joinpath("tox.ini").write_text(toxini_content, encoding="utf-8")
old = Path.cwd().resolve()
os.chdir(tmp_path)
try:
sys.argv = [sys.executable]
tox_to_nox.main()
return tmpdir.join("noxfile.py").read_text(encoding="utf8") # type: ignore[no-any-return]
return tmp_path.joinpath("noxfile.py").read_text(encoding="utf-8")
finally:
old.chdir()
os.chdir(old)

return makeconfig


def test_trivial(makeconfig: Callable[..., Any]) -> None:
def test_trivial(makeconfig: Callable[[str], str]) -> None:
result = makeconfig(
textwrap.dedent(
f"""
Expand All @@ -72,7 +74,7 @@ def py{PYTHON_VERSION_NODOT}(session):
)


def test_skipinstall(makeconfig: Callable[..., Any]) -> None:
def test_skipinstall(makeconfig: Callable[[str], str]) -> None:
result = makeconfig(
textwrap.dedent(
f"""
Expand All @@ -99,7 +101,7 @@ def py{PYTHON_VERSION_NODOT}(session):
)


def test_usedevelop(makeconfig: Callable[..., Any]) -> None:
def test_usedevelop(makeconfig: Callable[[str], str]) -> None:
result = makeconfig(
textwrap.dedent(
f"""
Expand Down Expand Up @@ -127,7 +129,7 @@ def py{PYTHON_VERSION_NODOT}(session):
)


def test_commands(makeconfig: Callable[..., Any]) -> None:
def test_commands(makeconfig: Callable[[str], str]) -> None:
result = makeconfig(
textwrap.dedent(
f"""
Expand Down Expand Up @@ -163,7 +165,7 @@ def lint(session):
)


def test_deps(makeconfig: Callable[..., Any]) -> None:
def test_deps(makeconfig: Callable[[str], str]) -> None:
result = makeconfig(
textwrap.dedent(
f"""
Expand Down Expand Up @@ -195,7 +197,7 @@ def lint(session):
)


def test_env(makeconfig: Callable[..., Any]) -> None:
def test_env(makeconfig: Callable[[str], str]) -> None:
result = makeconfig(
textwrap.dedent(
f"""
Expand Down Expand Up @@ -229,7 +231,7 @@ def lint(session):
)


def test_chdir(makeconfig: Callable[..., Any]) -> None:
def test_chdir(makeconfig: Callable[[str], str]) -> None:
result = makeconfig(
textwrap.dedent(
f"""
Expand Down Expand Up @@ -259,7 +261,7 @@ def lint(session):
)


def test_dash_in_envname(makeconfig: Callable[..., Any]) -> None:
def test_dash_in_envname(makeconfig: Callable[[str], str]) -> None:
result = makeconfig(
textwrap.dedent(
f"""
Expand Down Expand Up @@ -289,7 +291,7 @@ def test_with_dash(session):

@pytest.mark.skipif(TOX4, reason="Not supported in tox 4.")
def test_non_identifier_in_envname(
makeconfig: Callable[..., Any], capfd: pytest.CaptureFixture[str]
makeconfig: Callable[[str], str], capfd: pytest.CaptureFixture[str]
) -> None:
result = makeconfig(
textwrap.dedent(
Expand Down Expand Up @@ -325,7 +327,7 @@ def test_with_&(session):
)


def test_descriptions_into_docstrings(makeconfig: Callable[..., Any]) -> None:
def test_descriptions_into_docstrings(makeconfig: Callable[[str], str]) -> None:
result = makeconfig(
textwrap.dedent(
f"""
Expand Down
Loading

0 comments on commit 1f782bd

Please sign in to comment.