summaryrefslogtreecommitdiff
path: root/tests/test_context.py
blob: 41b77b45a3b9200ba10b463047ccce1f4cfee3f2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# coding: utf-8

"""
Unit tests of context.py.

"""

from datetime import datetime
import unittest

from pystache.context import _NOT_FOUND
from pystache.context import _get_value
from pystache.context import Context
from tests.common import AssertIsMixin

class SimpleObject(object):

    """A sample class that does not define __getitem__()."""

    def __init__(self):
        self.foo = "bar"

    def foo_callable(self):
        return "called..."


class DictLike(object):

    """A sample class that implements __getitem__() and __contains__()."""

    def __init__(self):
        self._dict = {'foo': 'bar'}
        self.fuzz = 'buzz'

    def __contains__(self, key):
        return key in self._dict

    def __getitem__(self, key):
        return self._dict[key]


class GetValueTests(unittest.TestCase, AssertIsMixin):

    """Test context._get_value()."""

    def assertNotFound(self, item, key):
        """
        Assert that a call to _get_value() returns _NOT_FOUND.

        """
        self.assertIs(_get_value(item, key), _NOT_FOUND)

    ### Case: the item is a dictionary.

    def test_dictionary__key_present(self):
        """
        Test getting a key from a dictionary.

        """
        item = {"foo": "bar"}
        self.assertEquals(_get_value(item, "foo"), "bar")

    def test_dictionary__callable_not_called(self):
        """
        Test that callable values are returned as-is (and in particular not called).

        """
        def foo_callable(self):
            return "bar"

        item = {"foo": foo_callable}
        self.assertNotEquals(_get_value(item, "foo"), "bar")
        self.assertTrue(_get_value(item, "foo") is foo_callable)

    def test_dictionary__key_missing(self):
        """
        Test getting a missing key from a dictionary.

        """
        item = {}
        self.assertNotFound(item, "missing")

    def test_dictionary__attributes_not_checked(self):
        """
        Test that dictionary attributes are not checked.

        """
        item = {}
        attr_name = "keys"
        self.assertEquals(getattr(item, attr_name)(), [])
        self.assertNotFound(item, attr_name)

    def test_dictionary__dict_subclass(self):
        """
        Test that subclasses of dict are treated as dictionaries.

        """
        class DictSubclass(dict): pass

        item = DictSubclass()
        item["foo"] = "bar"

        self.assertEquals(_get_value(item, "foo"), "bar")

    ### Case: the item is an object.

    def test_object__attribute_present(self):
        """
        Test getting an attribute from an object.

        """
        item = SimpleObject()
        self.assertEquals(_get_value(item, "foo"), "bar")

    def test_object__attribute_missing(self):
        """
        Test getting a missing attribute from an object.

        """
        item = SimpleObject()
        self.assertNotFound(item, "missing")

    def test_object__attribute_is_callable(self):
        """
        Test getting a callable attribute from an object.

        """
        item = SimpleObject()
        self.assertEquals(_get_value(item, "foo_callable"), "called...")

    def test_object__non_built_in_type(self):
        """
        Test getting an attribute from an instance of a type that isn't built-in.

        """
        item = datetime(2012, 1, 2)
        self.assertEquals(_get_value(item, "day"), 2)

    def test_object__dict_like(self):
        """
        Test getting a key from a dict-like object (an object that implements '__getitem__').

        """
        item = DictLike()
        self.assertEquals(item["foo"], "bar")
        self.assertNotFound(item, "foo")

    ### Case: the item is an instance of a built-in type.

    def test_built_in_type__integer(self):
        """
        Test getting from an integer.

        """
        class MyInt(int): pass

        item1 = MyInt(10)
        item2 = 10

        self.assertEquals(item1.real, 10)
        self.assertEquals(item2.real, 10)

        self.assertEquals(_get_value(item1, 'real'), 10)
        self.assertNotFound(item2, 'real')

    def test_built_in_type__string(self):
        """
        Test getting from a string.

        """
        class MyStr(str): pass

        item1 = MyStr('abc')
        item2 = 'abc'

        self.assertEquals(item1.upper(), 'ABC')
        self.assertEquals(item2.upper(), 'ABC')

        self.assertEquals(_get_value(item1, 'upper'), 'ABC')
        self.assertNotFound(item2, 'upper')

    def test_built_in_type__list(self):
        """
        Test getting from a list.

        """
        class MyList(list): pass

        item1 = MyList([1, 2, 3])
        item2 = [1, 2, 3]

        self.assertEquals(item1.pop(), 3)
        self.assertEquals(item2.pop(), 3)

        self.assertEquals(_get_value(item1, 'pop'), 2)
        self.assertNotFound(item2, 'pop')


class ContextTests(unittest.TestCase, AssertIsMixin):

    """
    Test the Context class.

    """

    def test_init__no_elements(self):
        """
        Check that passing nothing to __init__() raises no exception.

        """
        context = Context()

    def test_init__many_elements(self):
        """
        Check that passing more than two items to __init__() raises no exception.

        """
        context = Context({}, {}, {})

    def test__repr(self):
        context = Context()
        self.assertEquals(repr(context), 'Context()')

        context = Context({'foo': 'bar'})
        self.assertEquals(repr(context), "Context({'foo': 'bar'},)")

        context = Context({'foo': 'bar'}, {'abc': 123})
        self.assertEquals(repr(context), "Context({'foo': 'bar'}, {'abc': 123})")

    def test__str(self):
        context = Context()
        self.assertEquals(str(context), 'Context()')

        context = Context({'foo': 'bar'})
        self.assertEquals(str(context), "Context({'foo': 'bar'},)")

        context = Context({'foo': 'bar'}, {'abc': 123})
        self.assertEquals(str(context), "Context({'foo': 'bar'}, {'abc': 123})")

    ## Test the static create() method.

    def test_create__dictionary(self):
        """
        Test passing a dictionary.

        """
        context = Context.create({'foo': 'bar'})
        self.assertEquals(context.get('foo'), 'bar')

    def test_create__none(self):
        """
        Test passing None.

        """
        context = Context.create({'foo': 'bar'}, None)
        self.assertEquals(context.get('foo'), 'bar')

    def test_create__object(self):
        """
        Test passing an object.

        """
        class Foo(object):
            foo = 'bar'
        context = Context.create(Foo())
        self.assertEquals(context.get('foo'), 'bar')

    def test_create__context(self):
        """
        Test passing a Context instance.

        """
        obj = Context({'foo': 'bar'})
        context = Context.create(obj)
        self.assertEquals(context.get('foo'), 'bar')

    def test_create__kwarg(self):
        """
        Test passing a keyword argument.

        """
        context = Context.create(foo='bar')
        self.assertEquals(context.get('foo'), 'bar')

    def test_create__precedence_positional(self):
        """
        Test precedence of positional arguments.

        """
        context = Context.create({'foo': 'bar'}, {'foo': 'buzz'})
        self.assertEquals(context.get('foo'), 'buzz')

    def test_create__precedence_keyword(self):
        """
        Test precedence of keyword arguments.

        """
        context = Context.create({'foo': 'bar'}, foo='buzz')
        self.assertEquals(context.get('foo'), 'buzz')

    def test_get__key_present(self):
        """
        Test getting a key.

        """
        context = Context({"foo": "bar"})
        self.assertEquals(context.get("foo"), "bar")

    def test_get__key_missing(self):
        """
        Test getting a missing key.

        """
        context = Context()
        self.assertTrue(context.get("foo") is None)

    def test_get__default(self):
        """
        Test that get() respects the default value.

        """
        context = Context()
        self.assertEquals(context.get("foo", "bar"), "bar")

    def test_get__precedence(self):
        """
        Test that get() respects the order of precedence (later items first).

        """
        context = Context({"foo": "bar"}, {"foo": "buzz"})
        self.assertEquals(context.get("foo"), "buzz")

    def test_get__fallback(self):
        """
        Check that first-added stack items are queried on context misses.

        """
        context = Context({"fuzz": "buzz"}, {"foo": "bar"})
        self.assertEquals(context.get("fuzz"), "buzz")

    def test_push(self):
        """
        Test push().

        """
        key = "foo"
        context = Context({key: "bar"})
        self.assertEquals(context.get(key), "bar")

        context.push({key: "buzz"})
        self.assertEquals(context.get(key), "buzz")

    def test_pop(self):
        """
        Test pop().

        """
        key = "foo"
        context = Context({key: "bar"}, {key: "buzz"})
        self.assertEquals(context.get(key), "buzz")

        item = context.pop()
        self.assertEquals(item, {"foo": "buzz"})
        self.assertEquals(context.get(key), "bar")

    def test_top(self):
        key = "foo"
        context = Context({key: "bar"}, {key: "buzz"})
        self.assertEquals(context.get(key), "buzz")

        top = context.top()
        self.assertEquals(top, {"foo": "buzz"})
        # Make sure calling top() didn't remove the item from the stack.
        self.assertEquals(context.get(key), "buzz")

    def test_copy(self):
        key = "foo"
        original = Context({key: "bar"}, {key: "buzz"})
        self.assertEquals(original.get(key), "buzz")

        new = original.copy()
        # Confirm that the copy behaves the same.
        self.assertEquals(new.get(key), "buzz")
        # Change the copy, and confirm it is changed.
        new.pop()
        self.assertEquals(new.get(key), "bar")
        # Confirm the original is unchanged.
        self.assertEquals(original.get(key), "buzz")