-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_factory_examples.py
More file actions
285 lines (248 loc) · 10.7 KB
/
test_factory_examples.py
File metadata and controls
285 lines (248 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
#!/usr/bin/env python3
"""Practical examples and integration tests for the Logger Factory Pattern."""
import os
import pytest
import sys
import tempfile
from pathlib import Path
# Add parent directory to path for imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from pythonlogs import (
BasicLog,
LogLevel,
RotateWhen,
SizeRotatingLog,
TimedRotatingLog,
)
from pythonlogs.core.factory import LoggerFactory, LoggerType, clear_logger_registry
class TestFactoryExamples:
"""Integration tests demonstrating factory pattern usage."""
def setup_method(self):
"""Clear registry before each test."""
clear_logger_registry()
def test_basic_console_logging(self):
"""Test basic console logging example."""
logger = LoggerFactory.create_logger(LoggerType.BASIC, name="console_app", level=LogLevel.INFO)
# Test logging (won't fail, just exercises the code)
logger.info("Application started")
logger.warning("This is a warning")
logger.debug("This debug message should be filtered out")
assert logger.name == "console_app"
assert logger.level == 20 # INFO level
@pytest.mark.skipif(
sys.platform == "win32",
reason="Windows file locking issues with TemporaryDirectory - see test_factory_windows.py",
)
def test_file_based_size_rotating_logger(self):
"""Test file-based size rotating logger example."""
with tempfile.TemporaryDirectory() as temp_dir:
logger = SizeRotatingLog(
name="app_logger",
directory=temp_dir,
filenames=["app.log", "debug.log"],
maxmbytes=1,
# Small size for testing
daystokeep=7,
level=LogLevel.DEBUG,
streamhandler=False, # No console output for test
)
# Generate some log messages
for i in range(10):
logger.info(f"Log message {i}")
logger.error(f"Error message {i}")
# Verify log files were created
log_files = list(Path(temp_dir).glob("*.log"))
assert len(log_files) >= 1 # At least one log file should exist
@pytest.mark.skipif(
sys.platform == "win32",
reason="Windows file locking issues with TemporaryDirectory - see test_factory_windows.py",
)
def test_time_based_rotating_logger(self):
"""Test time-based rotating logger example."""
with tempfile.TemporaryDirectory() as temp_dir:
logger = TimedRotatingLog(
name="scheduled_app",
directory=temp_dir,
filenames=["scheduled.log"],
when=RotateWhen.DAILY,
level=LogLevel.WARNING,
streamhandler=False,
)
logger.warning("Scheduled task started")
logger.error("Task encountered an error")
logger.critical("Critical system failure")
# Verify log file was created
log_files = list(Path(temp_dir).glob("*.log"))
assert len(log_files) >= 1
@pytest.mark.skipif(
sys.platform == "win32",
reason="Windows file locking issues with TemporaryDirectory - see test_factory_windows.py",
)
def test_production_like_multi_logger_setup(self):
"""Test production-like setup with multiple loggers."""
with tempfile.TemporaryDirectory() as temp_dir:
# Application logger
app_logger = LoggerFactory.create_logger(
LoggerType.SIZE_ROTATING,
name="production_app",
directory=temp_dir,
filenames=["app.log"],
maxmbytes=50,
daystokeep=30,
level=LogLevel.INFO,
streamhandler=False,
showlocation=True,
timezone="UTC",
)
# Error logger
error_logger = LoggerFactory.create_logger(
LoggerType.SIZE_ROTATING,
name="production_errors",
directory=temp_dir,
filenames=["errors.log"],
maxmbytes=10,
daystokeep=90,
level=LogLevel.ERROR,
streamhandler=False,
)
# Audit logger
audit_logger = LoggerFactory.create_logger(
LoggerType.TIMED_ROTATING,
name="audit_log",
directory=temp_dir,
filenames=["audit.log"],
when=RotateWhen.MIDNIGHT,
level=LogLevel.INFO,
streamhandler=False,
)
# Test logging to different loggers
app_logger.info("Application started successfully")
error_logger.error("Database connection failed")
audit_logger.info("User login: admin")
# Verify all loggers are different instances
assert app_logger.name != error_logger.name != audit_logger.name
# Verify log files were created
log_files = list(Path(temp_dir).glob("*.log"))
assert len(log_files) >= 3
@pytest.mark.skipif(
sys.platform == "win32",
reason="Windows file locking issues with TemporaryDirectory - see test_factory_windows.py",
)
def test_logger_registry_in_production_scenario(self):
"""Test logger registry usage in production scenario."""
with tempfile.TemporaryDirectory() as temp_dir:
# First module gets logger
module1_logger = LoggerFactory.get_or_create_logger(
LoggerType.SIZE_ROTATING,
name="shared_app_logger",
directory=temp_dir,
level=LogLevel.INFO,
)
# The Second module gets the same logger (cached)
module2_logger = LoggerFactory.get_or_create_logger(
LoggerType.SIZE_ROTATING,
name="shared_app_logger",
directory=temp_dir, # Must provide same params
)
# Should be the same instance
assert module1_logger is module2_logger
# Both modules can log
module1_logger.info("Message from module 1")
module2_logger.info("Message from module 2")
@pytest.mark.skipif(
sys.platform == "win32",
reason="Windows file locking issues with TemporaryDirectory - see test_factory_windows.py",
)
def test_mixed_enum_string_usage_example(self):
"""Test realistic mixed usage of enums and strings."""
with tempfile.TemporaryDirectory() as temp_dir:
# Configuration from environment (strings)
config_level = "INFO"
config_when = "midnight"
# Create logger with mix of config and enums
logger = TimedRotatingLog(
name="config_driven_app",
directory=temp_dir,
level=config_level, # String from config
when=RotateWhen.MIDNIGHT, # Enum for type safety
streamhandler=True,
)
logger.info("Configuration loaded successfully")
assert logger.name == "config_driven_app"
def test_error_handling_scenarios(self):
"""Test various error handling scenarios."""
# Invalid logger type
with pytest.raises(ValueError, match="Invalid logger type"):
LoggerFactory.create_logger("nonexistent_type", name="error_test")
# Invalid directory (should raise PermissionError when trying to create)
# This test only works on Unix/Linux/macOS systems with chmod
if sys.platform != "win32":
with tempfile.TemporaryDirectory() as temp_dir:
readonly_parent = os.path.join(temp_dir, "readonly")
# Read-only parent
os.makedirs(readonly_parent, mode=0o555)
try:
invalid_dir = os.path.join(readonly_parent, "invalid")
with pytest.raises(PermissionError):
SizeRotatingLog(name="permission_test", directory=invalid_dir)
finally:
# Restore permissions for cleanup
os.chmod(readonly_parent, 0o755)
@pytest.mark.skipif(
sys.platform == "win32",
reason="Windows file locking issues with TemporaryDirectory - see test_factory_windows.py",
)
def test_logger_customization_example(self):
"""Test logger with extensive customization."""
with tempfile.TemporaryDirectory() as temp_dir:
logger = LoggerFactory.create_logger(
LoggerType.TIMED_ROTATING,
name="custom_app",
directory=temp_dir,
filenames=["custom.log", "custom_debug.log"],
level=LogLevel.DEBUG,
when=RotateWhen.HOURLY,
daystokeep=14,
encoding="utf-8",
datefmt="%Y-%m-%d %H:%M:%S",
timezone="UTC",
streamhandler=True,
showlocation=True,
)
# Test all log levels
logger.debug("Debug information")
logger.info("Informational message")
logger.warning("Warning message")
logger.error("Error occurred")
logger.critical("Critical failure")
assert logger.name == "custom_app"
assert logger.level == 10 # DEBUG level
@pytest.mark.skipif(
sys.platform == "win32",
reason="Windows file locking issues with TemporaryDirectory - see test_factory_windows.py",
)
def test_convenience_functions_examples(self):
"""Test all convenience functions with realistic scenarios."""
# Basic logger for console output
console_logger = BasicLog(name="console", level=LogLevel.WARNING)
console_logger.warning("Console warning message")
# Size rotating for application logs
with tempfile.TemporaryDirectory() as temp_dir:
app_logger = SizeRotatingLog(
name="application",
directory=temp_dir,
maxmbytes=5,
level=LogLevel.INFO,
)
app_logger.info("Application log message")
# Timed rotating for audit logs
audit_logger = TimedRotatingLog(
name="audit",
directory=temp_dir,
when=RotateWhen.DAILY,
level=LogLevel.INFO,
)
audit_logger.info("Audit log message")
# Verify all loggers have different names
names = {console_logger.name, app_logger.name, audit_logger.name}
assert len(names) == 3 # All unique names