Skip to content

Commit

Permalink
Replace "tmpdir" fixture with "tmp_path" in tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Delgan committed Jun 11, 2022
1 parent 9677aae commit 74d52a6
Show file tree
Hide file tree
Showing 20 changed files with 793 additions and 813 deletions.
36 changes: 35 additions & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import asyncio
import builtins
import contextlib
import datetime
import logging
import os
import pathlib
import sys
import threading
import time
Expand Down Expand Up @@ -35,6 +38,12 @@ def run(coro):

asyncio.run = run

if sys.version_info < (3, 6):

@pytest.fixture
def tmp_path(tmp_path):
yield pathlib.Path(str(tmp_path))


def parse(text, *, strip=False, strict=True):
parser = loguru._colorizer.AnsiParser()
Expand All @@ -47,6 +56,19 @@ def parse(text, *, strip=False, strict=True):
return parser.colorize(tokens, "")


def check_dir(dir, *, files=None, size=None):
actual_files = set(dir.iterdir())
if size is not None:
assert len(actual_files) == size
if files is not None:
assert len(actual_files) == len(files)
for name, content in files:
filepath = dir / name
assert filepath in actual_files
if content is not None:
assert filepath.read_text() == content


@contextlib.contextmanager
def default_threading_excepthook():
if not hasattr(threading, "excepthook"):
Expand Down Expand Up @@ -166,7 +188,19 @@ def fake_localtime(t=None):
# Freezegun does not permit to override timezone name.
monkeypatch.setattr(freezegun.api, "fake_localtime", fake_localtime)

with freezegun.freeze_time(date) as frozen:
ctimes = {}

__open__ = builtins.open

def patched_open(filepath, *args, **kwargs):
if not os.path.exists(filepath):
ctimes[filepath] = datetime.datetime.now().timestamp()
return __open__(filepath, *args, **kwargs)

with freezegun.freeze_time(date) as frozen, monkeypatch.context() as context:
context.setattr(loguru._file_sink, "get_ctime", ctimes.__getitem__)
context.setattr(loguru._file_sink, "set_ctime", ctimes.__setitem__)
context.setattr(builtins, "open", patched_open)
yield frozen

return freeze_time
Expand Down
31 changes: 15 additions & 16 deletions tests/test_add_option_kwargs.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,32 @@
import io

import pytest

from loguru import logger


def test_file_mode_a(tmpdir):
file = tmpdir.join("test.log")
file.write("base\n")
logger.add(str(file), format="{message}", mode="a")
def test_file_mode_a(tmp_path):
file = tmp_path / "test.log"
file.write_text("base\n")
logger.add(file, format="{message}", mode="a")
logger.debug("msg")
assert file.read() == "base\nmsg\n"
assert file.read_text() == "base\nmsg\n"


def test_file_mode_w(tmpdir):
file = tmpdir.join("test.log")
file.write("base\n")
logger.add(str(file), format="{message}", mode="w")
def test_file_mode_w(tmp_path):
file = tmp_path / "test.log"
file.write_text("base\n")
logger.add(file, format="{message}", mode="w")
logger.debug("msg")
assert file.read() == "msg\n"
assert file.read_text() == "msg\n"


def test_file_buffering(tmpdir):
file = tmpdir.join("test.log")
logger.add(str(file), format="{message}", buffering=-1)
def test_file_buffering(tmp_path):
file = tmp_path / "test.log"
logger.add(file, format="{message}", buffering=-1)
logger.debug("x" * (io.DEFAULT_BUFFER_SIZE // 2))
assert file.read() == ""
assert file.read_text() == ""
logger.debug("x" * (io.DEFAULT_BUFFER_SIZE * 2))
assert file.read() != ""
assert file.read_text() != ""


def test_invalid_function_kwargs():
Expand Down
35 changes: 16 additions & 19 deletions tests/test_add_sinks.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import sys

import pytest

from loguru import logger

message = "test message"
Expand Down Expand Up @@ -59,18 +58,18 @@ def test_devnull(rep):
"sink_from_path",
[str, pathlib.Path, lambda path: open(path, "a"), lambda path: pathlib.Path(path).open("a")],
)
def test_file_sink(rep, sink_from_path, tmpdir):
file = tmpdir.join("test.log")
def test_file_sink(rep, sink_from_path, tmp_path):
file = tmp_path / "test.log"
sink = sink_from_path(str(file))
log(sink, rep)
assert file.read() == expected * rep
assert file.read_text() == expected * rep


@repetitions
def test_file_sink_folder_creation(rep, tmpdir):
file = tmpdir.join("some", "sub", "folder", "not", "existing", "test.log")
log(str(file), rep)
assert file.read() == expected * rep
def test_file_sink_folder_creation(rep, tmp_path):
file = tmp_path.joinpath("some", "sub", "folder", "not", "existing", "test.log")
log(file, rep)
assert file.read_text() == expected * rep


@repetitions
Expand Down Expand Up @@ -141,27 +140,25 @@ def flush(self):
assert flushed == [expected] * rep


def test_file_sink_ascii_encoding(tmpdir):
file = tmpdir.join("test.log")
logger.add(
str(file), encoding="ascii", format="{message}", errors="backslashreplace", catch=False
)
def test_file_sink_ascii_encoding(tmp_path):
file = tmp_path / "test.log"
logger.add(file, encoding="ascii", format="{message}", errors="backslashreplace", catch=False)
logger.info("天")
logger.remove()
assert file.read_text("ascii") == "\\u5929\n"


def test_file_sink_utf8_encoding(tmpdir):
file = tmpdir.join("test.log")
logger.add(str(file), encoding="utf8", format="{message}", errors="strict", catch=False)
def test_file_sink_utf8_encoding(tmp_path):
file = tmp_path / "test.log"
logger.add(file, encoding="utf8", format="{message}", errors="strict", catch=False)
logger.info("天")
logger.remove()
assert file.read_text("utf8") == "天\n"


def test_file_sink_default_encoding(tmpdir):
file = tmpdir.join("test.log")
logger.add(str(file), format="{message}", errors="strict", catch=False)
def test_file_sink_default_encoding(tmp_path):
file = tmp_path / "test.log"
logger.add(file, format="{message}", errors="strict", catch=False)
logger.info("天")
logger.remove()
assert file.read_text("utf8") == "天\n"
Expand Down
9 changes: 4 additions & 5 deletions tests/test_configure.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import sys

import pytest

from loguru import logger


def test_handlers(capsys, tmpdir):
file = tmpdir.join("test.log")
def test_handlers(capsys, tmp_path):
file = tmp_path / "test.log"

handlers = [
{"sink": str(file), "format": "FileSink: {message}"},
{"sink": file, "format": "FileSink: {message}"},
{"sink": sys.stdout, "format": "StdoutSink: {message}"},
]

Expand All @@ -18,7 +17,7 @@ def test_handlers(capsys, tmpdir):

out, err = capsys.readouterr()

assert file.read() == "FileSink: test\n"
assert file.read_text() == "FileSink: test\n"
assert out == "StdoutSink: test\n"
assert err == ""

Expand Down
8 changes: 4 additions & 4 deletions tests/test_coroutine_sink.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,10 +261,10 @@ async def worker():
assert err == "A\nB\nC\nD\n"


def test_complete_file_noop(tmpdir):
filepath = tmpdir.join("test.log")
def test_complete_file_noop(tmp_path):
filepath = tmp_path / "test.log"

logger.add(str(filepath), format="{message}", catch=False)
logger.add(filepath, format="{message}", catch=False)
logger.info("A")

async def worker():
Expand All @@ -276,7 +276,7 @@ async def worker():

logger.info("D")

assert filepath.read() == "A\nB\nC\nD\n"
assert filepath.read_text() == "A\nB\nC\nD\n"


def test_complete_function_noop():
Expand Down
9 changes: 3 additions & 6 deletions tests/test_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,14 +129,11 @@ def test_stdout_formatting(freeze_time, capsys):
assert err == ""


def test_file_formatting(freeze_time, tmpdir):
def test_file_formatting(freeze_time, tmp_path):
with freeze_time("2015-12-25 19:13:18", ("A", -5400)):
logger.add(str(tmpdir.join("{time:YYYY [MM] DD HHmmss ZZ}.log")))
logger.add(tmp_path / "{time:YYYY [MM] DD HHmmss ZZ}.log")
logger.debug("Z")
files = tmpdir.listdir()
assert len(files) == 1
result = files[0].basename
assert result == "2015 MM 25 191318 -0130.log"
assert list(tmp_path.iterdir()) == [tmp_path / "2015 MM 25 191318 -0130.log"]


def test_missing_struct_time_fields(writer, freeze_time):
Expand Down
12 changes: 6 additions & 6 deletions tests/test_exceptions_catch.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,9 @@ def bar(c):
assert writer.output.endswith("ZeroDivisionError: division by zero\n")


def test_file_sink_ascii_encoding(tmpdir):
file = tmpdir.join("test.log")
logger.add(str(file), format="", encoding="ascii", errors="backslashreplace", catch=False)
def test_file_sink_ascii_encoding(tmp_path):
file = tmp_path / "test.log"
logger.add(file, format="", encoding="ascii", errors="backslashreplace", catch=False)
a = "天"

try:
Expand All @@ -79,9 +79,9 @@ def test_file_sink_ascii_encoding(tmpdir):
assert result.count("-> '\\u5929'") == 1


def test_file_sink_utf8_encoding(tmpdir):
file = tmpdir.join("test.log")
logger.add(str(file), format="", encoding="utf8", errors="strict", catch=False)
def test_file_sink_utf8_encoding(tmp_path):
file = tmp_path / "test.log"
logger.add(file, format="", encoding="utf8", errors="strict", catch=False)
a = "天"

try:
Expand Down
Loading

0 comments on commit 74d52a6

Please sign in to comment.