Skip to content

Commit

Permalink
feat: use warnings instead of logging
Browse files Browse the repository at this point in the history
  • Loading branch information
taobojlen committed Jul 22, 2024
1 parent 5a7e0c4 commit 5033cd8
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
8 changes: 7 additions & 1 deletion src/zeal/listeners.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import logging
import warnings
from abc import ABC, abstractmethod
from collections import defaultdict
from contextlib import contextmanager
Expand Down Expand Up @@ -86,7 +87,12 @@ def _alert(self, model: type[models.Model], field: str, message: str):
if should_error:
raise self.error_class(message)
else:
logger.warning(message)
warnings.warn_explicit(
message,
UserWarning,
filename=caller.filename,
lineno=caller.lineno,
)


class NPlusOneListener(Listener):
Expand Down
18 changes: 9 additions & 9 deletions tests/test_listeners.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import logging
import re
import warnings

import pytest
from djangoproject.social.models import Post, User
Expand All @@ -17,16 +17,16 @@ def test_can_log_errors(settings, caplog):
[user_1, user_2] = UserFactory.create_batch(2)
PostFactory.create(author=user_1)
PostFactory.create(author=user_2)
with caplog.at_level(logging.WARNING):
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
for user in User.objects.all():
_ = list(user.posts.all())
assert (
re.search(
r"N\+1 detected on User\.posts at .*\/test_listeners\.py:22 in test_can_log_errors",
caplog.text,
)
is not None
), f"{caplog.text} does not match regex"
assert len(w) == 1
assert issubclass(w[0].category, UserWarning)
assert re.search(
r"N\+1 detected on User\.posts at .*\/test_listeners\.py:23 in test_can_log_errors",
str(w[0].message),
)


def test_errors_include_caller():
Expand Down

0 comments on commit 5033cd8

Please sign in to comment.