65 lines
2.2 KiB
Python
65 lines
2.2 KiB
Python
#!/usr/bin/env python3.9
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
Test null coalescing operator ?? functionality
|
|
"""
|
|
|
|
from pyenjoy.template.Engine import Engine
|
|
from pyenjoy.kit.Kv import Kv
|
|
|
|
def test_null_coalescing():
|
|
"""Test null coalescing operator"""
|
|
print("Testing null coalescing operator...")
|
|
|
|
engine = Engine.use()
|
|
|
|
# Test cases
|
|
test_cases = [
|
|
# Template, data, expected result
|
|
("#(data??'未知')", {"data": None}, "未知"),
|
|
("#(data??'未知')", {"data": "测试"}, "测试"),
|
|
("#(data??'未知')", {}, "未知"),
|
|
("#(user.name??'匿名')", {"user": {"name": "张三"}}, "张三"),
|
|
("#(user.name??'匿名')", {"user": {}}, "匿名"),
|
|
("#(user.name??'匿名')", {}, "匿名"),
|
|
# Nested null coalescing
|
|
("#(data1??data2??'默认值')", {"data1": None, "data2": None}, "默认值"),
|
|
("#(data1??data2??'默认值')", {"data1": None, "data2": "中间值"}, "中间值"),
|
|
("#(data1??data2??'默认值')", {"data1": "第一个值", "data2": "中间值"}, "第一个值"),
|
|
]
|
|
|
|
passed = 0
|
|
failed = 0
|
|
|
|
for i, (template_str, data, expected) in enumerate(test_cases):
|
|
try:
|
|
template = engine.get_template_by_string(template_str)
|
|
result = template.render_to_string(Kv(data))
|
|
if result == expected:
|
|
print(f"✓ Test {i+1}: Passed")
|
|
print(f" Template: {template_str}")
|
|
print(f" Data: {data}")
|
|
print(f" Result: {result}")
|
|
passed += 1
|
|
else:
|
|
print(f"✗ Test {i+1}: Failed")
|
|
print(f" Template: {template_str}")
|
|
print(f" Data: {data}")
|
|
print(f" Expected: {expected}")
|
|
print(f" Got: {result}")
|
|
failed += 1
|
|
except Exception as e:
|
|
print(f"✗ Test {i+1}: Error")
|
|
print(f" Template: {template_str}")
|
|
print(f" Data: {data}")
|
|
print(f" Error: {e}")
|
|
failed += 1
|
|
print()
|
|
|
|
print(f"Summary: {passed} passed, {failed} failed")
|
|
return passed == len(test_cases)
|
|
|
|
if __name__ == "__main__":
|
|
success = test_null_coalescing()
|
|
exit(0 if success else 1)
|