2013-07-01 14:22:27 +02:00
|
|
|
import unittest
|
|
|
|
|
2011-07-13 11:35:51 +02:00
|
|
|
from django.template.smartif import IfParser
|
2009-12-09 23:40:36 +01:00
|
|
|
|
2013-11-02 22:34:05 +01:00
|
|
|
|
2009-12-09 23:40:36 +01:00
|
|
|
class SmartIfTests(unittest.TestCase):
|
|
|
|
def assertCalcEqual(self, expected, tokens):
|
|
|
|
self.assertEqual(expected, IfParser(tokens).parse().eval({}))
|
|
|
|
|
|
|
|
# We only test things here that are difficult to test elsewhere
|
|
|
|
# Many other tests are found in the main tests for builtin template tags
|
|
|
|
# Test parsing via the printed parse tree
|
|
|
|
def test_not(self):
|
|
|
|
var = IfParser(["not", False]).parse()
|
|
|
|
self.assertEqual("(not (literal False))", repr(var))
|
2011-03-03 16:04:39 +01:00
|
|
|
self.assertTrue(var.eval({}))
|
2009-12-09 23:40:36 +01:00
|
|
|
|
|
|
|
self.assertFalse(IfParser(["not", True]).parse().eval({}))
|
|
|
|
|
|
|
|
def test_or(self):
|
|
|
|
var = IfParser([True, "or", False]).parse()
|
|
|
|
self.assertEqual("(or (literal True) (literal False))", repr(var))
|
2011-03-03 16:04:39 +01:00
|
|
|
self.assertTrue(var.eval({}))
|
2009-12-09 23:40:36 +01:00
|
|
|
|
|
|
|
def test_in(self):
|
2013-10-26 21:15:03 +02:00
|
|
|
list_ = [1, 2, 3]
|
2009-12-09 23:40:36 +01:00
|
|
|
self.assertCalcEqual(True, [1, "in", list_])
|
|
|
|
self.assertCalcEqual(False, [1, "in", None])
|
|
|
|
self.assertCalcEqual(False, [None, "in", list_])
|
|
|
|
|
2010-03-09 00:25:37 +01:00
|
|
|
def test_not_in(self):
|
2013-10-26 21:15:03 +02:00
|
|
|
list_ = [1, 2, 3]
|
2010-03-09 00:25:37 +01:00
|
|
|
self.assertCalcEqual(False, [1, "not", "in", list_])
|
|
|
|
self.assertCalcEqual(True, [4, "not", "in", list_])
|
|
|
|
self.assertCalcEqual(False, [1, "not", "in", None])
|
|
|
|
self.assertCalcEqual(True, [None, "not", "in", list_])
|
|
|
|
|
2009-12-09 23:40:36 +01:00
|
|
|
def test_precedence(self):
|
|
|
|
# (False and False) or True == True <- we want this one, like Python
|
|
|
|
# False and (False or True) == False
|
|
|
|
self.assertCalcEqual(True, [False, "and", False, "or", True])
|
|
|
|
|
|
|
|
# True or (False and False) == True <- we want this one, like Python
|
|
|
|
# (True or False) and False == False
|
|
|
|
self.assertCalcEqual(True, [True, "or", False, "and", False])
|
|
|
|
|
|
|
|
# (1 or 1) == 2 -> False
|
|
|
|
# 1 or (1 == 2) -> True <- we want this one
|
|
|
|
self.assertCalcEqual(True, [1, "or", 1, "==", 2])
|
|
|
|
|
|
|
|
self.assertCalcEqual(True, [True, "==", True, "or", True, "==", False])
|
|
|
|
|
|
|
|
self.assertEqual(
|
|
|
|
"(or (and (== (literal 1) (literal 2)) (literal 3)) (literal 4))",
|
|
|
|
repr(IfParser([1, "==", 2, "and", 3, "or", 4]).parse()),
|
|
|
|
)
|