/tests/regressiontests/templates/smartif.py
Python | 53 lines | 32 code | 12 blank | 9 comment | 0 complexity | 84baada609cb49463ee6618737bc0d44 MD5 | raw file
1from django.template.smartif import IfParser, Literal 2from django.utils import unittest 3 4class SmartIfTests(unittest.TestCase): 5 6 def assertCalcEqual(self, expected, tokens): 7 self.assertEqual(expected, IfParser(tokens).parse().eval({})) 8 9 # We only test things here that are difficult to test elsewhere 10 # Many other tests are found in the main tests for builtin template tags 11 # Test parsing via the printed parse tree 12 def test_not(self): 13 var = IfParser(["not", False]).parse() 14 self.assertEqual("(not (literal False))", repr(var)) 15 self.assertTrue(var.eval({})) 16 17 self.assertFalse(IfParser(["not", True]).parse().eval({})) 18 19 def test_or(self): 20 var = IfParser([True, "or", False]).parse() 21 self.assertEqual("(or (literal True) (literal False))", repr(var)) 22 self.assertTrue(var.eval({})) 23 24 def test_in(self): 25 list_ = [1,2,3] 26 self.assertCalcEqual(True, [1, 'in', list_]) 27 self.assertCalcEqual(False, [1, 'in', None]) 28 self.assertCalcEqual(False, [None, 'in', list_]) 29 30 def test_not_in(self): 31 list_ = [1,2,3] 32 self.assertCalcEqual(False, [1, 'not', 'in', list_]) 33 self.assertCalcEqual(True, [4, 'not', 'in', list_]) 34 self.assertCalcEqual(False, [1, 'not', 'in', None]) 35 self.assertCalcEqual(True, [None, 'not', 'in', list_]) 36 37 def test_precedence(self): 38 # (False and False) or True == True <- we want this one, like Python 39 # False and (False or True) == False 40 self.assertCalcEqual(True, [False, 'and', False, 'or', True]) 41 42 # True or (False and False) == True <- we want this one, like Python 43 # (True or False) and False == False 44 self.assertCalcEqual(True, [True, 'or', False, 'and', False]) 45 46 # (1 or 1) == 2 -> False 47 # 1 or (1 == 2) -> True <- we want this one 48 self.assertCalcEqual(True, [1, 'or', 1, '==', 2]) 49 50 self.assertCalcEqual(True, [True, '==', True, 'or', True, '==', False]) 51 52 self.assertEqual("(or (and (== (literal 1) (literal 2)) (literal 3)) (literal 4))", 53 repr(IfParser([1, '==', 2, 'and', 3, 'or', 4]).parse()))