调整版本并做测试

This commit is contained in:
2026-02-27 17:10:54 +08:00
parent fa673138f6
commit 31be9d0e97
77 changed files with 679 additions and 25 deletions

98
test_file_template.py Normal file
View File

@@ -0,0 +1,98 @@
#!/usr/bin/env python3.9
# -*- coding: utf-8 -*-
"""
Test template from file functionality
"""
import os
from pyenjoy.template.Engine import Engine
from pyenjoy.kit.Kv import Kv
def test_file_template():
"""Test template from file"""
print("Testing template from file...")
# Create a test template file
test_dir = "./test_templates"
os.makedirs(test_dir, exist_ok=True)
# Test case 1: Basic template
test_file1 = os.path.join(test_dir, "test1.txt")
with open(test_file1, "w", encoding="utf-8") as f:
f.write("Hello, #(name)!")
# Test case 2: Template with null coalescing
test_file2 = os.path.join(test_dir, "test2.txt")
with open(test_file2, "w", encoding="utf-8") as f:
f.write("Data: #(data??'未知')")
# Test case 3: Template with multiple expressions
test_file3 = os.path.join(test_dir, "test3.txt")
with open(test_file3, "w", encoding="utf-8") as f:
f.write("Name: #(name), Age: #(age??'未知'), City: #(city??'未知')")
# Create engine and configure base template path
engine = Engine.use()
engine.base_template_path = os.getcwd()
# Test cases
test_cases = [
# (file_path, data, expected_result, description)
(test_file1, {"name": "World"}, "Hello, World!", "Basic template"),
(test_file2, {"data": None}, "Data: 未知", "Null coalescing with None"),
(test_file2, {"data": "测试数据"}, "Data: 测试数据", "Null coalescing with value"),
(test_file2, {}, "Data: 未知", "Null coalescing with undefined variable"),
(test_file3, {"name": "张三", "age": 30}, "Name: 张三, Age: 30, City: 未知", "Multiple expressions"),
]
passed = 0
failed = 0
for i, (file_path, data, expected, description) in enumerate(test_cases):
try:
print(f"\nTest {i+1}: {description}")
print(f"File: {file_path}")
print(f"Data: {data}")
# Get template
template = engine.get_template(file_path)
# Render template
result = template.render_to_string(Kv(data))
print(f"Expected: '{expected}'")
print(f"Got: '{result}'")
if result == expected:
print("✓ Passed")
passed += 1
else:
print("✗ Failed")
failed += 1
# Debug: Check content
print(f"\nDebug info:")
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
print(f"File content: '{content}'")
print(f"Content length: {len(content)}")
print(f"Content repr: {repr(content)}")
except Exception as e:
print(f"✗ Error: {e}")
failed += 1
print(f"\nSummary: {passed} passed, {failed} failed")
# Clean up
for file_path in [test_file1, test_file2, test_file3]:
if os.path.exists(file_path):
os.remove(file_path)
if os.path.exists(test_dir):
os.rmdir(test_dir)
return passed == len(test_cases)
if __name__ == "__main__":
success = test_file_template()
exit(0 if success else 1)