Skip to content

Commit

Permalink
Fix code style and flake8 errors (Delgan#354)
Browse files Browse the repository at this point in the history
Co-authored-by: Delgan <delgan.py@gmail.com>
  • Loading branch information
AndrewYakimets and Delgan authored Oct 26, 2020
1 parent a9a2438 commit 1b41299
Show file tree
Hide file tree
Showing 27 changed files with 81 additions and 56 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
`_Unreleased`_
==============

- Fix ``flake8`` errors and improve code readability (`#353 <https://github.com/Delgan/loguru/issues/353>`_, thanks `@AndrewYakimets <https://github.com/AndrewYakimets>`_).


`0.5.3`_ (2020-09-20)
=====================

Expand Down
1 change: 0 additions & 1 deletion docs/_extensions/autodoc_stub_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import os
import sys
import types
import code


def get_module_docstring(filepath):
Expand Down
11 changes: 10 additions & 1 deletion loguru/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,16 @@

__all__ = ["logger"]

logger = _Logger(_Core(), None, 0, False, False, False, False, True, None, {})
logger = _Logger(core=_Core(),
exception=None,
depth=0,
record=False,
lazy=False,
colors=False,
raw=False,
capture=True,
patcher=None,
extra={})

if _defaults.LOGURU_AUTOINIT and _sys.stderr:
logger.add(_sys.stderr)
Expand Down
1 change: 0 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import os
import re

try:
Expand Down
2 changes: 0 additions & 2 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@
import contextlib
import loguru
import logging
import itertools
import pytest
import os
import subprocess
import sys
import time
import warnings
Expand Down
3 changes: 2 additions & 1 deletion tests/test_activation.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,8 @@ def test_log_before_disable(writer):


def test_multiple_activations():
n = lambda: len(logger._core.activation_list)
def n():
return len(logger._core.activation_list)

assert n() == 0
logger.enable("")
Expand Down
4 changes: 2 additions & 2 deletions tests/test_add_option_backtrace.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ def test_backtrace(writer):
logger.add(writer, format="{message}", backtrace=True)
try:
1 / 0
except:
except Exception:
logger.exception("")
result_with = writer.read().strip()

Expand All @@ -18,7 +18,7 @@ def test_backtrace(writer):
logger.add(writer, format="{message}", backtrace=False)
try:
1 / 0
except:
except Exception:
logger.exception("")
result_without = writer.read().strip()

Expand Down
1 change: 0 additions & 1 deletion tests/test_add_option_catch.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import sys
import pytest
from loguru import logger
import loguru
import re
import time

Expand Down
4 changes: 2 additions & 2 deletions tests/test_add_option_diagnose.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ def test_diagnose(writer):
logger.add(writer, format="{message}", diagnose=True)
try:
1 / 0
except:
except Exception:
logger.exception("")
result_with = writer.read().strip()

Expand All @@ -17,7 +17,7 @@ def test_diagnose(writer):
logger.add(writer, format="{message}", diagnose=False)
try:
1 / 0
except:
except Exception:
logger.exception("")
result_without = writer.read().strip()

Expand Down
1 change: 0 additions & 1 deletion tests/test_add_option_enqueue.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,6 @@ def test_not_caught_exception_queue_put(writer, capsys):
logger.remove()

out, err = capsys.readouterr()
lines = err.strip().splitlines()
assert writer.read() == "It's fine\n"
assert out == ""
assert err == ""
Expand Down
5 changes: 4 additions & 1 deletion tests/test_add_sinks.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,10 @@ def test_file_sink_folder_creation(rep, tmpdir):
@repetitions
def test_function_sink(rep):
a = []
func = lambda log_message: a.append(log_message)

def func(log_message):
a.append(log_message)

log(func, rep)
assert a == [expected] * rep

Expand Down
2 changes: 0 additions & 2 deletions tests/test_contextualize.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import loguru
from loguru import logger
import threading
import asyncio
import importlib
import sys
import pytest

Expand Down
2 changes: 0 additions & 2 deletions tests/test_coroutine_sink.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
import pytest
import logging
import loguru
import time
import threading
import os
import re
import multiprocessing
from loguru import logger
Expand Down
4 changes: 2 additions & 2 deletions tests/test_defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ def test_string(value, monkeypatch):
def test_bool_positive(value, monkeypatch):
key = "VALID_BOOL_POS"
monkeypatch.setenv(key, value)
assert env(key, bool) == True
assert env(key, bool) is True


@pytest.mark.parametrize("value", ["NO", "0", "false"])
def test_bool_negative(value, monkeypatch):
key = "VALID_BOOL_NEG"
monkeypatch.setenv(key, value)
assert env(key, bool) == False
assert env(key, bool) is False


def test_int(monkeypatch):
Expand Down
1 change: 0 additions & 1 deletion tests/test_filesink_compression.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ def creation_time(filepath):
j = logger.add(str(tmpdir.join("test.log")), compression="tar.gz")
logger.debug("test")

filesink = next(iter(logger._core.handlers.values()))._sink
monkeypatch.setattr(loguru._file_sink, "get_ctime", creation_time)

logger.remove(j)
Expand Down
19 changes: 9 additions & 10 deletions tests/test_filesink_rotation.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@
import time
import tempfile
import pathlib
import platform
import builtins
from collections import namedtuple
from unittest.mock import MagicMock, PropertyMock
import loguru
from loguru import logger
Expand Down Expand Up @@ -128,7 +126,7 @@ def linux_xattr_attributeerror_filesystem(monkeypatch, monkeypatch_filesystem):


def test_renaming(tmpdir):
i = logger.add(str(tmpdir.join("file.log")), rotation=0, format="{message}")
logger.add(str(tmpdir.join("file.log")), rotation=0, format="{message}")

time.sleep(0.1)
logger.debug("a")
Expand All @@ -154,7 +152,7 @@ def test_renaming(tmpdir):

def test_no_renaming(monkeypatch_date, tmpdir):
monkeypatch_date(2018, 1, 1, 0, 0, 0, 0)
i = logger.add(str(tmpdir.join("file_{time}.log")), rotation=0, format="{message}")
logger.add(str(tmpdir.join("file_{time}.log")), rotation=0, format="{message}")

monkeypatch_date(2019, 1, 1, 0, 0, 0, 0)
logger.debug("a")
Expand Down Expand Up @@ -196,7 +194,9 @@ def test_size_rotation(monkeypatch_date, tmpdir, size):
@pytest.mark.parametrize(
"when, hours",
[
# hours = [Should not trigger, should trigger, should not trigger, should trigger, should trigger]
# hours = [
# Should not trigger, should trigger, should not trigger, should trigger, should trigger
# ]
("13", [0, 1, 20, 4, 24]),
("13:00", [0.2, 0.9, 23, 1, 48]),
("13:00:00", [0.5, 1.5, 10, 15, 72]),
Expand Down Expand Up @@ -383,7 +383,7 @@ def test_time_rotation_windows_no_setctime(
reload_filesink_ctime_functions(monkeypatch)

monkeypatch_date(2018, 10, 27, 5, 0, 0, 0)
i = logger.add(str(tmpdir.join("test.{time}.log")), format="{message}", rotation="2 h")
logger.add(str(tmpdir.join("test.{time}.log")), format="{message}", rotation="2 h")
logger.info("1")
monkeypatch_date(2018, 10, 27, 6, 30, 0, 0)
logger.info("2")
Expand Down Expand Up @@ -414,7 +414,7 @@ def raising_setctime(filepath, timestamp):
reload_filesink_ctime_functions(monkeypatch)

monkeypatch_date(2018, 10, 27, 5, 0, 0, 0)
i = logger.add(str(tmpdir.join("test.{time}.log")), format="{message}", rotation="2 h")
logger.add(str(tmpdir.join("test.{time}.log")), format="{message}", rotation="2 h")
logger.info("1")
monkeypatch_date(2018, 10, 27, 6, 30, 0, 0)
logger.info("2")
Expand All @@ -430,7 +430,7 @@ def raising_setctime(filepath, timestamp):
def test_function_rotation(monkeypatch_date, tmpdir):
monkeypatch_date(2018, 1, 1, 0, 0, 0, 0)
x = iter([False, True, False])
i = logger.add(
logger.add(
str(tmpdir.join("test_{time}.log")), rotation=lambda *_: next(x), format="{message}"
)
logger.debug("a")
Expand Down Expand Up @@ -477,10 +477,9 @@ def creation_time(filepath):
assert os.path.basename(filepath) == "test.log"
return datetime.datetime(2018, 1, 1, 0, 0, 0, 0).timestamp()

i = logger.add(str(tmpdir.join("test.log")), rotation=10, format="{message}")
logger.add(str(tmpdir.join("test.log")), rotation=10, format="{message}")
logger.debug("X")

filesink = next(iter(logger._core.handlers.values()))._sink
monkeypatch.setattr(loguru._file_sink, "get_ctime", creation_time)

logger.debug("Y" * 20)
Expand Down
7 changes: 4 additions & 3 deletions tests/test_get_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@


def test_with_sys_getframe(monkeypatch):
patched = lambda: None
monkeypatch.setattr(sys, "_getframe", patched)
def patched():
return
monkeypatch.setattr(sys, "_getframe", patched())
get_frame_module = importlib.reload(loguru._get_frame)
assert get_frame_module.get_frame == patched
assert get_frame_module.get_frame == patched()


def test_without_sys_getframe(monkeypatch):
Expand Down
15 changes: 11 additions & 4 deletions tests/test_interception.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,15 @@ def emit(self, record):


def test_formatting(writer):
fmt = "{name} - {file.name} - {function} - {level.name} - {level.no} - {line} - {module} - {message}"
expected = "tests.test_interception - test_interception.py - test_formatting - DEBUG - 10 - 31 - test_interception - This is the message\n"
fmt = (
"{name} - {file.name} - {function} - {level.name} - "
"{level.no} - {line} - {module} - {message}"
)

expected = (
"tests.test_interception - test_interception.py - test_formatting - DEBUG - "
"10 - 38 - test_interception - This is the message\n"
)

with make_logging_logger("tests", InterceptHandler()) as logging_logger:
logger.add(writer, format=fmt)
Expand Down Expand Up @@ -94,7 +101,7 @@ def test_exception(writer):

try:
1 / 0
except:
except Exception:
logging_logger.exception("Oops...")

lines = writer.read().strip().splitlines()
Expand Down Expand Up @@ -150,4 +157,4 @@ def test_using_logging_function(writer):
logging.warning("ABC")

result = writer.read()
assert result == "test_using_logging_function 150 test_interception test_interception.py ABC\n"
assert result == "test_using_logging_function 157 test_interception test_interception.py ABC\n"
14 changes: 7 additions & 7 deletions tests/test_opt.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def test_exception_boolean(writer):

try:
1 / 0
except:
except Exception:
logger.opt(exception=True).debug("Error {0} {record}", 1, record="test")

lines = writer.read().strip().splitlines()
Expand All @@ -70,7 +70,7 @@ def test_exception_exc_info(writer):

try:
1 / 0
except:
except Exception:
exc_info = sys.exc_info()

logger.opt(exception=exc_info).debug("test")
Expand All @@ -86,7 +86,7 @@ def test_exception_class(writer):

try:
1 / 0
except:
except Exception:
_, exc_class, _ = sys.exc_info()

logger.opt(exception=exc_class).debug("test")
Expand All @@ -102,7 +102,7 @@ def test_exception_log_funcion(writer):

try:
1 / 0
except:
except Exception:
logger.opt(exception=True).log(50, "Error")

lines = writer.read().strip().splitlines()
Expand All @@ -128,13 +128,13 @@ def laziness():

logger.opt(lazy=True).log(20, "3: {}", laziness)

a = logger.add(writer, level=15, format="{level.no} => {message}")
b = logger.add(writer, level=20, format="{level.no} => {message}")
i = logger.add(writer, level=15, format="{level.no} => {message}")
logger.add(writer, level=20, format="{level.no} => {message}")

logger.log(17, "4: {}", counter)
logger.opt(lazy=True).log(14, "5: {lazy}", lazy=lambda: counter)

logger.remove(a)
logger.remove(i)

logger.opt(lazy=True).log(16, "6: {0}", lambda: counter)

Expand Down
1 change: 0 additions & 1 deletion tests/test_patch.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import pytest
from loguru import logger


Expand Down
3 changes: 1 addition & 2 deletions tests/test_pickling.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import logging
import pickle
import asyncio
import sys
import datetime

import pytest
Expand Down Expand Up @@ -140,7 +139,7 @@ def __reduce__():
logger.add(handler, format="=> {message}", catch=False)

pickled = pickle.dumps(logger)
unpickled = pickle.loads(pickled)
pickle.loads(pickled)

logger.info("Ok")
out, err = capsys.readouterr()
Expand Down
13 changes: 10 additions & 3 deletions tests/test_propagation.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,15 @@ def emit(self, record):


def test_formatting(capsys):
fmt = "%(name)s - %(filename)s - %(funcName)s - %(levelname)s - %(levelno)s - %(lineno)d - %(module)s - %(message)s"
expected = "tests.test_propagation - test_propagation.py - test_formatting - DEBUG - 10 - 20 - test_propagation - This is my message\n"
fmt = (
"%(name)s - %(filename)s - %(funcName)s - %(levelname)s - "
"%(levelno)s - %(lineno)d - %(module)s - %(message)s"
)

expected = (
"tests.test_propagation - test_propagation.py - test_formatting - DEBUG - "
"10 - 27 - test_propagation - This is my message\n"
)

with make_logging_logger("tests.test_propagation", StreamHandler(sys.stderr), fmt):
logger.add(PropagateHandler(), format="{message}")
Expand Down Expand Up @@ -76,7 +83,7 @@ def test_exception(capsys, use_opt):

try:
1 / 0
except:
except Exception:
if use_opt:
logger.opt(exception=True).error("Oops...")
else:
Expand Down
Loading

0 comments on commit 1b41299

Please sign in to comment.