Skip to content

Commit 47ae99a

Browse files
authored
Mocking the built-in print function in the decorator tests (#8)
1 parent 929f95c commit 47ae99a

File tree

7 files changed

+72
-49
lines changed

7 files changed

+72
-49
lines changed

src/decorator/tests/mylog_test.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
"""
2+
Set of pytests for the @logme decorator.
3+
4+
I used the following reference to understand how to mock the "open" function:
5+
https://docs.python.org/3.3/library/unittest.mock.html#mock-open
6+
7+
I used the same principle for the "print" function, used in these tests.
8+
"""
9+
from unittest.mock import patch
10+
11+
from decorator.logging.mylog import LOG_FILE_NAME, Level, logme
12+
13+
14+
@patch("builtins.open", create=True)
15+
@patch("builtins.print", create=True)
16+
def test_logme_for_none(mock_print, mock_open):
17+
"""
18+
GIVEN logging for a function
19+
WHEN logme is called with no level set
20+
THEN there is no writing to output log file
21+
"""
22+
mock_print.__name__ = "print"
23+
24+
# logme returns a wrapper function for the passed function
25+
wrapper = logme(mock_print)()
26+
27+
# this is where the logic happens
28+
wrapper()
29+
30+
# no writing to log happened
31+
mock_open.assert_not_called()
32+
# but target function was called
33+
mock_print.assert_called_once()
34+
35+
@patch("builtins.open", create=True)
36+
@patch("builtins.print", create=True)
37+
def test_logme_for_info(mock_print, mock_open):
38+
"""
39+
GIVEN logging for a function
40+
WHEN logme is called with INFO level
41+
THEN there is one write call to output log file
42+
"""
43+
mock_print.__name__ = "print"
44+
45+
# logme returns a wrapper function for the passed function, and I am calling it directly
46+
logme(mock_print, level=Level.INFO)()
47+
48+
# one write call to the log output
49+
mock_open.assert_called_with(LOG_FILE_NAME, "a+")
50+
# target function was called
51+
mock_print.assert_called_once()
52+
53+
@patch("builtins.open", create=True)
54+
@patch("builtins.print", create=True)
55+
def test_logme_for_debug(mock_print, mock_open):
56+
"""
57+
GIVEN logging for a function
58+
WHEN logme is called with INFO level
59+
THEN there are two write calls to output log file
60+
"""
61+
mock_print.__name__ = "print"
62+
63+
# logme returns a wrapper function for the passed function, and I am calling it directly
64+
logme(print, level=Level.DEBUG)()
65+
66+
# in this case, two write calls to the log output
67+
assert mock_open.call_count == 2
68+
# target function was called
69+
mock_print.assert_called_once()
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
"""
2+
Using the @logme decorator.
3+
"""
14
from logging.mylog import logme, Level
25

36
@logme

src/learning/tests/mylog_test.py

Lines changed: 0 additions & 49 deletions
This file was deleted.

0 commit comments

Comments
 (0)