| 1 |
from django.test import SimpleTestCase |
| 2 |
|
| 3 |
from ..utils import setup |
| 4 |
|
| 5 |
|
| 6 |
class ListIndexTests(SimpleTestCase): |
| 7 |
@setup({"list-index01": "{{ var.1 }}"}) |
| 8 |
def test_list_index01(self): |
| 9 |
""" |
| 10 |
List-index syntax allows a template to access a certain item of a |
| 11 |
subscriptable object. |
| 12 |
""" |
| 13 |
output = self.engine.render_to_string( |
| 14 |
"list-index01", {"var": ["first item", "second item"]} |
| 15 |
) |
| 16 |
self.assertEqual(output, "second item") |
| 17 |
|
| 18 |
@setup({"list-index02": "{{ var.5 }}"}) |
| 19 |
def test_list_index02(self): |
| 20 |
""" |
| 21 |
Fail silently when the list index is out of range. |
| 22 |
""" |
| 23 |
output = self.engine.render_to_string( |
| 24 |
"list-index02", {"var": ["first item", "second item"]} |
| 25 |
) |
| 26 |
if self.engine.string_if_invalid: |
| 27 |
self.assertEqual(output, "INVALID") |
| 28 |
else: |
| 29 |
self.assertEqual(output, "") |
| 30 |
|
| 31 |
@setup({"list-index03": "{{ var.1 }}"}) |
| 32 |
def test_list_index03(self): |
| 33 |
""" |
| 34 |
Fail silently when the list index is out of range. |
| 35 |
""" |
| 36 |
output = self.engine.render_to_string("list-index03", {"var": None}) |
| 37 |
if self.engine.string_if_invalid: |
| 38 |
self.assertEqual(output, "INVALID") |
| 39 |
else: |
| 40 |
self.assertEqual(output, "") |
| 41 |
|
| 42 |
@setup({"list-index04": "{{ var.1 }}"}) |
| 43 |
def test_list_index04(self): |
| 44 |
""" |
| 45 |
Fail silently when variable is a dict without the specified key. |
| 46 |
""" |
| 47 |
output = self.engine.render_to_string("list-index04", {"var": {}}) |
| 48 |
if self.engine.string_if_invalid: |
| 49 |
self.assertEqual(output, "INVALID") |
| 50 |
else: |
| 51 |
self.assertEqual(output, "") |
| 52 |
|
| 53 |
@setup({"list-index05": "{{ var.1 }}"}) |
| 54 |
def test_list_index05(self): |
| 55 |
""" |
| 56 |
Dictionary lookup wins out when dict's key is a string. |
| 57 |
""" |
| 58 |
output = self.engine.render_to_string("list-index05", {"var": {"1": "hello"}}) |
| 59 |
self.assertEqual(output, "hello") |
| 60 |
|
| 61 |
@setup({"list-index06": "{{ var.1 }}"}) |
| 62 |
def test_list_index06(self): |
| 63 |
""" |
| 64 |
But list-index lookup wins out when dict's key is an int, which |
| 65 |
behind the scenes is really a dictionary lookup (for a dict) |
| 66 |
after converting the key to an int. |
| 67 |
""" |
| 68 |
output = self.engine.render_to_string("list-index06", {"var": {1: "hello"}}) |
| 69 |
self.assertEqual(output, "hello") |
| 70 |
|
| 71 |
@setup({"list-index07": "{{ var.1 }}"}) |
| 72 |
def test_list_index07(self): |
| 73 |
""" |
| 74 |
Dictionary lookup wins out when there is a string and int version |
| 75 |
of the key. |
| 76 |
""" |
| 77 |
output = self.engine.render_to_string( |
| 78 |
"list-index07", {"var": {"1": "hello", 1: "world"}} |
| 79 |
) |
| 80 |
self.assertEqual(output, "hello") |