-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproduction_tests.py
More file actions
359 lines (290 loc) · 10.4 KB
/
production_tests.py
File metadata and controls
359 lines (290 loc) · 10.4 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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
#!/usr/bin/env python3
"""
Production-grade tests for the enhanced template engine.
Tests error handling, missing variables, security, and edge cases.
"""
import sys
import logging
from template_engine import (
TemplateEngine,
MissingVariableError,
InvalidVariableError,
LoopRenderError,
TemplateRenderError
)
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
def test_missing_variables_strict_mode():
"""Test that missing variables raise errors in strict mode."""
print("=== Testing Missing Variables (Strict Mode) ===")
engine = TemplateEngine(strict_mode=True)
# Test missing simple variable
template = "Hello $name, welcome to $site!"
context = {'name': 'Alice'} # Missing 'site'
try:
result = engine.render(template, context)
print("❌ FAIL: Should have raised MissingVariableError")
return False
except MissingVariableError as e:
print(f"✅ PASS: Correctly caught missing variable: {e}")
# Test missing loop variable
loop_template = """
Welcome $name!
{% for item in items %}
- $item.title: $item.description
{% endfor %}
"""
loop_context = {'name': 'Bob'} # Missing 'items'
try:
result = engine.render(loop_template, loop_context)
print("❌ FAIL: Should have raised LoopRenderError")
return False
except LoopRenderError as e:
print(f"✅ PASS: Correctly caught missing loop variable: {e}")
# Test missing nested variable in loop
nested_template = """
{% for user in users %}
- $user.name ($user.missing_field)
{% endfor %}
"""
nested_context = {
'users': [
{'name': 'Alice', 'age': 30},
{'name': 'Bob', 'age': 25}
]
}
try:
result = engine.render(nested_template, nested_context)
print("❌ FAIL: Should have raised MissingVariableError")
return False
except (MissingVariableError, LoopRenderError) as e:
print(f"✅ PASS: Correctly caught missing nested variable: {e}")
return True
def test_missing_variables_lenient_mode():
"""Test that missing variables are preserved as placeholders in lenient mode."""
print("\n=== Testing Missing Variables (Lenient Mode) ===")
engine = TemplateEngine(strict_mode=False)
# Test missing simple variable
template = "Hello $name, welcome to $site!"
context = {'name': 'Alice'} # Missing 'site'
result = engine.render(template, context)
expected = "Hello Alice, welcome to ${site}!"
if result == expected:
print("✅ PASS: Missing variable preserved as placeholder")
else:
print(f"❌ FAIL: Expected '{expected}', got '{result}'")
return False
missing_vars = engine.get_missing_variables()
if 'site' in missing_vars:
print("✅ PASS: Missing variables tracked correctly")
else:
print(f"❌ FAIL: Missing variables not tracked: {missing_vars}")
return False
return True
def test_invalid_variable_names():
"""Test that invalid/dangerous variable names are rejected."""
print("\n=== Testing Invalid Variable Names ===")
# Use lenient mode to see filtering behavior
engine = TemplateEngine(strict_mode=False)
# Test dangerous context variables
dangerous_context = {
'__import__': 'dangerous',
'eval': 'also dangerous',
'__class__': 'very dangerous',
'safe_var': 'this is ok'
}
template = "$safe_var $__import__ $eval $__class__"
result = engine.render(template, dangerous_context)
# Should only render safe_var, others should be missing/ignored
if 'this is ok' in result and 'dangerous' not in result:
print("✅ PASS: Dangerous variables filtered out")
else:
print(f"❌ FAIL: Dangerous variables not filtered: {result}")
return False
return True
def test_template_syntax_validation():
"""Test template syntax validation."""
print("\n=== Testing Template Syntax Validation ===")
engine = TemplateEngine(strict_mode=True)
# Test unmatched loop tags
bad_template = """
{% for item in items %}
$item.name
<!-- Missing endfor -->
"""
try:
result = engine.render(bad_template, {'items': []})
print("❌ FAIL: Should have caught unmatched loop tags")
return False
except TemplateRenderError as e:
print(f"✅ PASS: Correctly caught syntax error: {e}")
return True
def test_xss_protection():
"""Test XSS protection through HTML escaping."""
print("\n=== Testing XSS Protection ===")
engine = TemplateEngine(auto_escape=True)
malicious_context = {
'user_input': '<script>alert("XSS")</script>',
'title': 'Safe & Sound',
'description': '<b>Bold</b> text'
}
template = """
<h1>$title</h1>
<p>User said: $user_input</p>
<div>$description</div>
"""
result = engine.render(template, malicious_context)
# Check that dangerous content is escaped
if '<script>' in result and '&' in result:
print("✅ PASS: XSS content properly escaped")
else:
print(f"❌ FAIL: XSS content not escaped properly: {result}")
return False
return True
def test_loop_error_handling():
"""Test comprehensive loop error handling."""
print("\n=== Testing Loop Error Handling ===")
engine = TemplateEngine(strict_mode=True)
# Test loop with non-list variable
template1 = """
{% for item in not_a_list %}
$item.name
{% endfor %}
"""
context1 = {'not_a_list': 'just a string'}
try:
result = engine.render(template1, context1)
print("❌ FAIL: Should have caught non-list error")
return False
except LoopRenderError as e:
print(f"✅ PASS: Correctly caught non-list error: {e}")
# Test loop with invalid variable names
template2 = """
{% for __dangerous__ in items %}
$__dangerous__.name
{% endfor %}
"""
context2 = {'items': [{'name': 'test'}]}
try:
result = engine.render(template2, context2)
print("❌ FAIL: Should have caught invalid loop variable")
return False
except (LoopRenderError, InvalidVariableError) as e:
print(f"✅ PASS: Correctly caught invalid loop variable: {e}")
return True
def test_performance_and_memory():
"""Test performance with large datasets."""
print("\n=== Testing Performance & Memory ===")
engine = TemplateEngine(strict_mode=False)
# Create large dataset
large_context = {
'title': 'Performance Test',
'items': [
{
'id': i,
'name': f'Item {i}',
'description': f'Description for item {i}',
'value': i * 1.5
}
for i in range(5000)
]
}
template = """
<h1>$title</h1>
<div>Total Items: ${len(items)}</div>
<ul>
{% for item in items %}
<li>ID: $item.id | Name: $item.name | Value: $item.value</li>
{% endfor %}
</ul>
"""
import time
start_time = time.time()
try:
result = engine.render(template, large_context)
end_time = time.time()
render_time = end_time - start_time
result_lines = result.count('\n')
print(f"✅ PASS: Rendered {result_lines} lines in {render_time:.3f} seconds")
# Check performance threshold (should be reasonable)
if render_time < 5.0: # 5 seconds threshold
print("✅ PASS: Performance within acceptable limits")
else:
print(f"⚠️ WARNING: Performance slow: {render_time:.3f}s")
return True
except Exception as e:
print(f"❌ FAIL: Performance test failed: {e}")
return False
def test_production_edge_cases():
"""Test various edge cases that might occur in production."""
print("\n=== Testing Production Edge Cases ===")
engine = TemplateEngine(strict_mode=False)
# Test empty templates
result = engine.render("", {})
if result == "":
print("✅ PASS: Empty template handled")
else:
print(f"❌ FAIL: Empty template not handled: '{result}'")
return False
# Test empty context
result = engine.render("Hello World!", {})
if result == "Hello World!":
print("✅ PASS: Empty context handled")
else:
print(f"❌ FAIL: Empty context not handled: '{result}'")
return False
# Test None values
context = {'name': None, 'age': 0, 'active': False}
template = "$name|$age|$active"
result = engine.render(template, context)
if "|0|False" in result: # None becomes empty string
print("✅ PASS: None values handled correctly")
else:
print(f"❌ FAIL: None values not handled: '{result}'")
return False
# Test Unicode content
unicode_context = {'message': 'Hello 世界! 🌍'}
unicode_template = "Message: $message"
result = engine.render(unicode_template, unicode_context)
if '世界' in result and '🌍' in result:
print("✅ PASS: Unicode content handled")
else:
print(f"❌ FAIL: Unicode content not handled: '{result}'")
return False
return True
def run_all_tests():
"""Run all production tests."""
print("🚀 Starting Production-Grade Template Engine Tests")
print("=" * 60)
tests = [
test_missing_variables_strict_mode,
test_missing_variables_lenient_mode,
test_invalid_variable_names,
test_template_syntax_validation,
test_xss_protection,
test_loop_error_handling,
test_performance_and_memory,
test_production_edge_cases
]
passed = 0
failed = 0
for test_func in tests:
try:
if test_func():
passed += 1
else:
failed += 1
except Exception as e:
print(f"❌ FAIL: {test_func.__name__} threw unexpected error: {e}")
failed += 1
print("\n" + "=" * 60)
print(f"📊 Test Results: {passed} passed, {failed} failed")
if failed == 0:
print("🎉 ALL TESTS PASSED! Template engine is production-ready.")
return True
else:
print("⚠️ Some tests failed. Please review the issues above.")
return False
if __name__ == "__main__":
success = run_all_tests()
sys.exit(0 if success else 1)