Skip to content

Tests: use the tmp_path fixture instead of tmpdir #242

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,9 @@ def _retrieve_file_from_web(url: str, path: str) -> None:
with open(path, "wb") as f:
f.write(data)
print("... success")


@pytest.fixture()
def tmpdir():
"""Override tmpdir to raise a ValueError."""
raise ValueError("Use the 'tmp_path' fixture instead of 'tmpdir'")
82 changes: 41 additions & 41 deletions tests/end2end/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"""Fixtures and bdd-given steps related to setup and cleanup for end2end testing."""

import logging
import os

from PyQt5.QtGui import QPixmap

Expand All @@ -33,8 +32,8 @@ def ensureqtbot(qtbot):


@pytest.fixture(autouse=True)
def mock_directories(tmpdir):
directory = tmpdir.join(".vimiv-data")
def mock_directories(tmp_path):
directory = tmp_path / ".vimiv-data"
utils.xdg.basedir = str(directory)
yield
utils.xdg.basedir = None
Expand Down Expand Up @@ -79,13 +78,13 @@ def faster_wait_times():
###############################################################################
@bdd.given("I start vimiv")
@bdd.given("I open any directory")
def start_vimiv(tmpdir):
start_directory(tmpdir)
def start_vimiv(tmp_path):
start_directory(tmp_path)


@bdd.given(bdd.parsers.parse("I start vimiv with {args}"))
def start_vimiv_with_args(tmpdir, args):
start_directory(tmpdir, args=args.split())
def start_vimiv_with_args(tmp_path, args):
start_directory(tmp_path, args=args.split())


@bdd.given("I run vimiv --version")
Expand All @@ -95,51 +94,51 @@ def run_vimiv_version():


@bdd.given("I start vimiv with --log-level <level>")
def start_vimiv_log_level(tmpdir, level):
start_directory(tmpdir, args=["--log-level", level])
def start_vimiv_log_level(tmp_path, level):
start_directory(tmp_path, args=["--log-level", level])


@bdd.given("I open a directory for which I do not have access permissions")
def start_directory_without_permission(tmpdir):
start_directory(tmpdir, permission=0o666)
def start_directory_without_permission(tmp_path):
start_directory(tmp_path, permission=0o666)


@bdd.given(bdd.parsers.parse("I open a directory with {n_children:d} paths"))
def start_directory_with_n_paths(tmpdir, n_children):
start_directory(tmpdir, n_children=n_children)
def start_directory_with_n_paths(tmp_path, n_children):
start_directory(tmp_path, n_children=n_children)


@bdd.given(bdd.parsers.parse("I open a directory with {n_images:d} images"))
def start_directory_with_n_images(tmpdir, n_images):
start_directory(tmpdir, n_images=n_images)
def start_directory_with_n_images(tmp_path, n_images):
start_directory(tmp_path, n_images=n_images)


@bdd.given("I open any image")
def start_any_image(tmpdir):
start_image(tmpdir)
def start_any_image(tmp_path):
start_image(tmp_path)


@bdd.given(bdd.parsers.parse("I open any image of size {size}"))
def start_any_image_of_size(tmpdir, size):
def start_any_image_of_size(tmp_path, size):
size = [int(elem) for elem in size.split("x")]
start_image(tmpdir, size=size)
start_image(tmp_path, size=size)


@bdd.given(bdd.parsers.parse("I open {n_images:d} images"))
def start_n_images(tmpdir, n_images):
start_image(tmpdir, n_images=n_images)
def start_n_images(tmp_path, n_images):
start_image(tmp_path, n_images=n_images)


@bdd.given(bdd.parsers.parse("I open {n_images:d} images with {args}"))
def start_n_images_with_args(tmpdir, n_images, args):
start_image(tmpdir, n_images=n_images, args=args.split())
def start_n_images_with_args(tmp_path, n_images, args):
start_image(tmp_path, n_images=n_images, args=args.split())


@bdd.given(bdd.parsers.parse("I open the image '{basename}'"))
def start_image_name(tmpdir, basename):
path = str(tmpdir.join(basename))
create_image(path)
start([path])
def start_image_name(tmp_path, basename):
filename = str(tmp_path / basename)
create_image(filename)
start([filename])


@bdd.given("I open an animated gif")
Expand Down Expand Up @@ -173,45 +172,46 @@ def check_stderr(output, text):
###############################################################################
# helpers #
###############################################################################
def start_directory(tmpdir, n_children=0, n_images=0, permission=0o777, args=None):
def start_directory(tmp_path, n_children=0, n_images=0, permission=0o777, args=None):
"""Run vimiv startup using one directory as the passed path."""
args = args if args is not None else []
directory = tmpdir.mkdir("directory")
os.chmod(str(directory), permission)
directory = tmp_path / "directory"
directory.mkdir(mode=permission)

for i in range(n_children):
directory.mkdir(f"child_{i + 1:02d}")
(directory / f"child_{i + 1:02d}").mkdir()

create_n_images(directory, n_images)

start([str(directory)] + args)
start([directory] + args)


def start_image(tmpdir, n_images=1, size=(300, 300), args=None):
def start_image(tmp_path, n_images=1, size=(300, 300), args=None):
"""Run vimiv startup using n images as the passed paths."""
paths = create_n_images(tmpdir, n_images, size=size)
args = paths if args is None else paths + args
start(args)
paths = create_n_images(tmp_path, n_images, size=size)
argv = paths if args is None else paths + args
start(argv)


def start(argv):
"""Run vimiv startup passing argv as argument list."""
argv = [str(arg) for arg in argv]
args = startup.setup_pre_app(argv)
startup.setup_post_app(args)


def create_n_images(tmpdir, number, size=(300, 300), imgformat="jpg"):
def create_n_images(directory, number, size=(300, 300), imgformat="jpg"):
paths = []
for i in range(1, number + 1):
basename = f"image.{imgformat}" if number == 1 else f"image_{i:02d}.{imgformat}"
path = str(tmpdir.join(basename))
create_image(path, size=size)
path = directory / basename
create_image(str(path.resolve()), size=size)
paths.append(path)
return paths


def create_image(path: str, *, size=(300, 300)):
QPixmap(*size).save(path)
def create_image(filename: str, *, size=(300, 300)):
QPixmap(*size).save(filename)


class Output:
Expand Down
6 changes: 4 additions & 2 deletions tests/end2end/features/command/test_expand_wildcards_bdd.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@


@pytest.fixture(autouse=True)
def home_directory(tmpdir, mocker):
def home_directory(tmp_path, mocker):
"""Fixture to mock os.path.expanduser to return a different home directory."""
new_home = str(tmpdir.mkdir("home"))
directory = tmp_path / "home"
directory.mkdir()
new_home = str(directory)

def expand_user(path):
return path.replace("~", new_home)
Expand Down
15 changes: 8 additions & 7 deletions tests/end2end/features/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"""Fixtures and bdd-like steps for usage during end2end testing."""

import os
import pathlib

from PyQt5.QtCore import Qt, QProcess, QTimer
from PyQt5.QtGui import QFocusEvent
Expand Down Expand Up @@ -253,17 +254,17 @@ def create_directory(name):

@bdd.when(bdd.parsers.parse("I create the file '{name}'"))
def create_file(name):
assert not os.path.exists(name), f"Not overriding existing file '{name}'"
with open(name, "w") as f:
f.write("")
path = pathlib.Path(name)
assert not path.exists(), f"Not overriding existing file '{name}'"
path.touch()


@bdd.when(bdd.parsers.parse("I create the tag file '{name}'"))
def create_tag_file(name):
os.makedirs(api.mark.tagdir, mode=0o700, exist_ok=True)
path = os.path.join(api.mark.tagdir, name)
with open(path, "w") as f:
f.write("")
directory = pathlib.Path(api.mark.tagdir)
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
path = directory / name
path.touch()


###############################################################################
Expand Down
24 changes: 12 additions & 12 deletions tests/end2end/features/image/test_imageopen_bdd.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,18 @@


@bdd.when("I open broken images")
def open_broken_images(tmpdir):
_open_file(tmpdir, b"\211PNG\r\n\032\n") # PNG
_open_file(tmpdir, b"000000JFIF") # JPG
_open_file(tmpdir, b"GIF89a") # GIF
_open_file(tmpdir, b"II") # TIFF
_open_file(tmpdir, b"BM") # BMP
def open_broken_images(tmp_path):
_open_file(tmp_path, b"\211PNG\r\n\032\n") # PNG
_open_file(tmp_path, b"000000JFIF") # JPG
_open_file(tmp_path, b"GIF89a") # GIF
_open_file(tmp_path, b"II") # TIFF
_open_file(tmp_path, b"BM") # BMP


def _open_file(tmpdir, data):
def _open_file(directory, data):
"""Open a file containing the bytes from data."""
path = str(tmpdir.join("broken"))
with open(path, "wb") as f:
f.write(data)
assert imghdr.what(path) is not None, "Invalid magic bytes in test setup"
api.open_paths([path])
path = directory / "broken"
path.write_bytes(data)
filename = str(path)
assert imghdr.what(filename) is not None, "Invalid magic bytes in test setup"
api.open_paths([filename])
4 changes: 2 additions & 2 deletions tests/integration/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ def create_custom_parser(default_parser, **sections):


@pytest.fixture()
def custom_configfile(tmpdir, custom_configparser):
def custom_configfile(tmp_path, custom_configparser):
"""Fixture to create a custom config file from a configparser."""

def create_custom_configfile(basename, read, default_parser, **sections):
parser = custom_configparser(default_parser, **sections)
path = tmpdir.join(basename)
path = tmp_path / basename
with open(path, "w") as f:
parser.write(f)
read(str(path))
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/test_read_bindings.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def reset_to_default(cleanup_helper):


@pytest.fixture(scope="function")
def keyspath(tmpdir, custom_configfile, request):
def keyspath(custom_configfile, request):
"""Fixture to create a custom keybindings file for reading."""
yield custom_configfile(
"keys.conf", keyfile.read, keyfile.get_default_parser, **request.param
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/test_read_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def reset_to_default(cleanup_helper):


@pytest.fixture(scope="function")
def configpath(tmpdir, custom_configfile, request):
def configpath(custom_configfile, request):
yield custom_configfile(
"vimiv.conf", configfile.read, configfile.get_default_parser, **request.param
)
Expand Down
5 changes: 3 additions & 2 deletions tests/unit/api/test_mark.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,9 @@ def mark(qtbot, mocker, monkeypatch):


@pytest.fixture(autouse=True)
def tagdir(tmpdir, mocker):
tmp_tagdir = tmpdir.mkdir("tags")
def tagdir(tmp_path, mocker):
tmp_tagdir = tmp_path / "tags"
tmp_tagdir.mkdir()
mocker.patch.object(Tag, "dirname", return_value=str(tmp_tagdir))
yield str(tmp_tagdir)

Expand Down
8 changes: 4 additions & 4 deletions tests/unit/commands/test_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,10 @@ def mixed_history():


@pytest.fixture()
def history_file(tmpdir, mocker):
path = str(tmpdir.join("history"))
mocker.patch.object(vimiv.commands.history, "filename", return_value=path)
yield path
def history_file(tmp_path, mocker):
filename = str(tmp_path / "history")
mocker.patch.object(vimiv.commands.history, "filename", return_value=filename)
yield filename


def test_update_history(history):
Expand Down
6 changes: 3 additions & 3 deletions tests/unit/config/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
("[SECTION]\na=0\na=1\n", "duplicate key"),
],
)
def test_sysexit_on_broken_config(mocker, tmpdir, content, message):
def test_sysexit_on_broken_config(mocker, tmp_path, content, message):
"""Ensure SystemExit is correctly raised for various broken config files.

Args:
Expand All @@ -36,8 +36,8 @@ def test_sysexit_on_broken_config(mocker, tmpdir, content, message):
print("Ensuring system exit with", message)
mock_logger = mocker.Mock()
parser = configparser.ConfigParser()
path = tmpdir.join("configfile")
path.write(content)
path = tmp_path / "configfile"
path.write_text(content)
with pytest.raises(SystemExit, match=str(customtypes.Exit.err_config)):
config.read_log_exception(parser, mock_logger, str(path))
mock_logger.critical.assert_called_once()
4 changes: 2 additions & 2 deletions tests/unit/config/test_external_configparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,11 @@ def parser():


@pytest.fixture()
def config(tmpdir):
def config(tmp_path):
"""Fixture to retrieve a written config file with external references."""
parser = configparser.ConfigParser()
parser[SECTION_NAME][OPTION_NAME] = "${env:" + ENV_VARIABLE.name + "}"
path = tmpdir.join("config.ini")
path = tmp_path / "config.ini"
with open(path, "w") as f:
parser.write(f)
yield str(path)
Expand Down
10 changes: 5 additions & 5 deletions tests/unit/config/test_styles.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def new_style(request):


@pytest.fixture
def style_file(tmpdir):
def style_file(tmp_path):
"""Fixture to create a style file with different properties."""

def create_style_file(color="#FFF", font=None, n_colors=16, header=True, **options):
Expand All @@ -33,9 +33,9 @@ def create_style_file(color="#FFF", font=None, n_colors=16, header=True, **optio
header. If False, omit the STYLE section header.
options: Further style options passed.
"""
path = str(tmpdir.join("style"))
filename = str(tmp_path / "style")
if not header:
return path
return filename
parser = configparser.ConfigParser()
parser.add_section("STYLE")
for i in range(n_colors):
Expand All @@ -44,9 +44,9 @@ def create_style_file(color="#FFF", font=None, n_colors=16, header=True, **optio
parser["STYLE"]["font"] = font
for key, value in options.items():
parser["STYLE"][key] = value
with open(path, "w") as f:
with open(filename, "w") as f:
parser.write(f)
return path
return filename

return create_style_file

Expand Down
Loading