summaryrefslogtreecommitdiff
path: root/src/zope/tales/tests/test_expressions.py
blob: 1653c29d0a77d92ecdb989d179b934afa2a5fd60 (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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Default TALES expression implementations tests.
"""
import six
import unittest

from zope.tales.engine import Engine
from zope.tales.interfaces import ITALESFunctionNamespace
from zope.tales.tales import Undefined
from zope.interface import implementer
import zope.tales.tests

text_type = str if str is not bytes else unicode  # noqa PY2


class Data(object):

    def __init__(self, **kw):
        self.__dict__.update(kw)

    def __getattr__(self, name):
        # Let linters (like pylint) know this is a dynamic class and they
        # shouldn't emit "Data has no attribute" errors
        return object.__getattribute__(self, name)

    def __repr__(self):
        return self.name

    __str__ = __repr__


class ErrorGenerator(object):

    def __getitem__(self, name):
        from six.moves import builtins
        if name == 'Undefined':
            e = Undefined
        else:
            e = getattr(builtins, name, None) or SystemError
        raise e('mess')


class Callable(object):

    def __call__(self):
        return 42


class OldStyleCallable:  # NOT object
    pass


class ExpressionTestBase(zope.tales.tests.TestCase):

    def setUp(self):
        # Test expression compilation
        d = Data(
            name='xander',
            y=Data(
                name='yikes',
                z=Data(name='zope')
            )
        )
        at = Data(
            name='yikes',
            _d=d
        )
        self.context = Data(
            vars=dict(
                x=d,
                y=Data(z=3),
                b='boot',
                B=2,
                adapterTest=at,
                dynamic='z',
                eightBits=u'déjà vu'.encode('utf-8'),
                ErrorGenerator=ErrorGenerator(),
                callable=Callable(),
                old_callable_class=OldStyleCallable,
            )
        )

        self.engine = Engine

        self.py3BrokenEightBits = "a b'd\\xc3\\xa9j\\xc3\\xa0 vu'"

    def _compiled_expr(self, expr):
        return self.engine.compile(expr) if isinstance(expr, str) else expr

    def _check_evals_to(self, expr, result):
        expr = self._compiled_expr(expr)
        self.assertEqual(expr(self.context), result)
        return expr

    def _check_evals_to_instance(self, expr, result_kind):
        expr = self._compiled_expr(expr)
        self.assertIsInstance(expr(self.context), result_kind)
        return expr

    def _check_raises_compiler_error(self, expr_str, regex=None):
        from zope.tales.tales import CompilerError
        meth = self.assertRaises if regex is None else self.assertRaisesRegex
        args = (regex,) if regex is not None else ()
        with meth(CompilerError, *args) as exc:
            self.engine.compile(expr_str)
        return exc.exception

    def _check_subexpr_raises_compiler_error(self, expr, regexp):
        from zope.tales.expressions import SubPathExpr
        from zope.tales.tales import CompilerError
        with self.assertRaisesRegex(CompilerError, regexp):
            SubPathExpr(expr, None, self.engine)


class TestParsedExpressions(ExpressionTestBase):
    # Whitebox tests of expressions that have been compiled by the engine

    def testSimple(self):
        expr = self.engine.compile('x')
        self._check_evals_to(expr, self.context.vars['x'])

    def testPath(self):
        expr = self.engine.compile('x/y')
        self._check_evals_to(expr, self.context.vars['x'].y)
        self.assertEqual("standard expression ('x/y')", str(expr))
        self.assertEqual("<PathExpr standard:'x/y'>", repr(expr))

    def test_path_nocall_call(self):
        self._check_evals_to('callable', 42)
        self._check_evals_to('nocall:callable', self.context.vars['callable'])

        self._check_evals_to_instance('old_callable_class', OldStyleCallable)
        self._check_evals_to('nocall:old_callable_class', OldStyleCallable)

    def test_path_exists(self):
        self._check_evals_to('exists:x', 1)
        self._check_evals_to('exists:' + 'i' + str(id(self)), 0)

    def testLongPath(self):
        expr = self.engine.compile('x/y/z')
        self._check_evals_to(expr, self.context.vars['x'].y.z)

    def testOrPath(self):
        expr = self.engine.compile('path:a|b|c/d/e')
        self._check_evals_to(expr, 'boot')

        for e in 'Undefined', 'AttributeError', 'LookupError', 'TypeError':
            expr = self.engine.compile('path:ErrorGenerator/%s|b|c/d/e' % e)
            self._check_evals_to(expr, 'boot')

    def testOrPathWithSpaces(self):
        expr = self.engine.compile('path:a | b | c/d/e')
        self._check_evals_to(expr, 'boot')

        for e in 'Undefined', 'AttributeError', 'LookupError', 'TypeError':
            expr = self.engine.compile(
                'path:ErrorGenerator/%s | b | c/d/e' % e)
            self._check_evals_to(expr, 'boot')

    def testNonAsciiPath(self):
        error = self.engine.getCompilerError()
        with self.assertRaises(error):
            self.engine.compile(u'path: ä')

    def test_path_CONTEXTS(self):
        self.context.contexts = 42
        self._check_evals_to('CONTEXTS', 42)

    def testDynamic(self):
        expr = self.engine.compile('x/y/?dynamic')
        self._check_evals_to(expr, self.context.vars['x'].y.z)

    def testBadInitalDynamic(self):
        from zope.tales.tales import CompilerError
        with self.assertRaises(CompilerError) as exc:
            self.engine.compile('?x')
        e = exc.exception
        self.assertEqual(e.args[0],
                         'Dynamic name specified in first subpath element')

    def test_dynamic_invalid_variable_name(self):
        from zope.tales.tales import CompilerError
        with self.assertRaisesRegex(CompilerError, "Invalid variable name"):
            self.engine.compile('path:a/?123')

    def testOldStyleClassIsCalled(self):
        class AnOldStyleClass:
            pass
        self.context.vars['oldstyleclass'] = AnOldStyleClass
        expr = self.engine.compile('oldstyleclass')
        self.assertTrue(isinstance(expr(self.context), AnOldStyleClass))

    def testString(self):
        expr = self.engine.compile('string:Fred')
        context = self.context
        result = expr(context)
        self.assertEqual(result, 'Fred')
        self.assertIsInstance(result, str)
        self.assertEqual("string expression ('Fred')", str(expr))
        self.assertEqual("<StringExpr 'Fred'>", repr(expr))

    def testStringSub(self):
        expr = self.engine.compile('string:A$B')
        self._check_evals_to(expr, 'A2')

    def testString_w_dollar_sign(self):
        expr = self.engine.compile('string:A$$$B')
        self._check_evals_to(expr, 'A$2')

    def testStringSub_w_python(self):
        CompilerError = self.engine.getCompilerError()
        self.assertRaises(CompilerError,
                          self.engine.compile,
                          'string:${python:1}')

    def testStringSubComplex(self):
        expr = self.engine.compile('string:a ${x/y} b ${y/z} c')
        self._check_evals_to(expr, 'a yikes b 3 c')

    def testStringSubComplex_w_miss_and_python(self):
        # See https://bugs.launchpad.net/zope.tales/+bug/1002242
        CompilerError = self.engine.getCompilerError()
        self.assertRaises(CompilerError,
                          self.engine.compile,
                          'string:${nothig/nothing|python:1}')

    def testString8Bits(self):
        # Simple eight bit string interpolation should just work.
        # Except on Py3, where we really mess it up.
        expr = self.engine.compile('string:a ${eightBits}')
        expected = ('a ' + self.context.vars['eightBits']
                    if not six.PY3 else self.py3BrokenEightBits)
        self._check_evals_to(expr, expected)

    def testStringUnicode(self):
        # Unicode string expressions should return unicode strings
        expr = self.engine.compile(u'string:Fred')
        context = self.context
        result = expr(context)
        self.assertEqual(result, u'Fred')
        self.assertIsInstance(result, text_type)

    def testStringFailureWhenMixed(self):
        # Mixed Unicode and 8bit string interpolation fails with a
        # UnicodeDecodeError, assuming there is no default encoding
        expr = self.engine.compile(u'string:a ${eightBits}')
        with self.assertRaises(UnicodeDecodeError):
            result = expr(self.context)
            # If we get here, we're on Python 3, which handles this
            # poorly.
            self.assertTrue(six.PY3)
            self.assertEqual(result, self.py3BrokenEightBits)
            # raise UnicodeDecodeError
            self.context.vars['eightBits'].decode('ascii')

    def test_string_escape_percent(self):
        self._check_evals_to('string:%', '%')

    def testPython(self):
        expr = self.engine.compile('python: 2 + 2')
        self._check_evals_to(expr, 4)

    def testPythonCallableIsntCalled(self):
        self.context.vars['acallable'] = lambda: 23
        expr = self.engine.compile('python: acallable')
        self.assertEqual(expr(self.context), self.context.vars['acallable'])

    def testPythonNewline(self):
        expr = self.engine.compile('python: 2 \n+\n 2\n')
        self._check_evals_to(expr, 4)

    def testPythonDosNewline(self):
        expr = self.engine.compile('python: 2 \r\n+\r\n 2\r\n')
        self._check_evals_to(expr, 4)

    def testPythonErrorRaisesCompilerError(self):
        self.assertRaises(self.engine.getCompilerError(),
                          self.engine.compile, 'python: splat.0')

    def testHybridPathExpressions(self):
        def eval(expr):
            e = self.engine.compile(expr)
            return e(self.context)
        self.context.vars['one'] = 1
        self.context.vars['acallable'] = lambda: 23

        self.assertEqual(eval('foo | python:1+1'), 2)
        self.assertEqual(eval('foo | python:acallable'),
                         self.context.vars['acallable'])
        self.assertEqual(eval('foo | string:x'), 'x')
        self.assertEqual(eval('foo | string:$one'), '1')
        self.assertTrue(eval('foo | exists:x'))

    def testEmptyPathSegmentRaisesCompilerError(self):
        CompilerError = self.engine.getCompilerError()

        def check(expr):
            self.assertRaises(CompilerError, self.engine.compile, expr)

        # path expressions on their own:
        check('/ab/cd | c/d | e/f')
        check('ab//cd | c/d | e/f')
        check('ab/cd/ | c/d | e/f')
        check('ab/cd | /c/d | e/f')
        check('ab/cd | c//d | e/f')
        check('ab/cd | c/d/ | e/f')
        check('ab/cd | c/d | /e/f')
        check('ab/cd | c/d | e//f')
        check('ab/cd | c/d | e/f/')

        # path expressions embedded in string: expressions:
        check('string:${/ab/cd}')
        check('string:${ab//cd}')
        check('string:${ab/cd/}')
        check('string:foo${/ab/cd | c/d | e/f}bar')
        check('string:foo${ab//cd | c/d | e/f}bar')
        check('string:foo${ab/cd/ | c/d | e/f}bar')
        check('string:foo${ab/cd | /c/d | e/f}bar')
        check('string:foo${ab/cd | c//d | e/f}bar')
        check('string:foo${ab/cd | c/d/ | e/f}bar')
        check('string:foo${ab/cd | c/d | /e/f}bar')
        check('string:foo${ab/cd | c/d | e//f}bar')
        check('string:foo${ab/cd | c/d | e/f/}bar')

    def test_defer_expression_returns_wrapper(self):
        from zope.tales.expressions import DeferWrapper
        from zope.tales.expressions import DeferExpr
        expr = self.engine.compile('defer: B')
        self.assertIsInstance(expr, DeferExpr)
        self.assertEqual(str(expr), "<DeferExpr 'B'>")
        self._check_evals_to_instance(expr, DeferWrapper)

        wrapper = expr(self.context)
        # It evaluates to what its underlying expression evaluates to
        self.assertEqual(wrapper(), self.context.vars['B'])
        # The str() of defer is the same as the str() of evaluating it
        self.assertEqual(str(wrapper), str(self.context.vars['B']))
        self.assertEqual(str(wrapper()), str(self.context.vars['B']))

    def test_eval_defer_wrapper(self):
        expr = self.engine.compile('defer: b')
        self.context.vars['deferred'] = expr(self.context)
        self._check_evals_to('deferred', self.context.vars['b'])

    def test_lazy_expression_returns_wrapper(self):
        from zope.tales.expressions import LazyWrapper
        from zope.tales.expressions import LazyExpr
        expr = self.engine.compile('lazy: b')
        self.assertIsInstance(expr, LazyExpr)
        self.assertEqual(repr(expr), "lazy:'b'")
        lazy = expr(self.context)
        self.assertIsInstance(lazy, LazyWrapper)

        first_result = lazy()
        second_result = lazy()
        self.assertIs(first_result, second_result)

    def test_not(self):
        # self.context is a Data object, not a real
        # zope.tales.tales.Context object, and as such
        # it doesn't define the evaluateBoolean function that
        # not expressions need. Add it locally to avoid disturbing
        # other tests.
        def evaluateBoolean(expr):
            return bool(expr(self.context))
        self.context.evaluateBoolean = evaluateBoolean
        self._check_evals_to('not:exists:x', 0)
        expr = self._check_evals_to('not:exists:v_42', 1)
        self.assertEqual("<NotExpr 'exists:v_42'>", repr(expr))

    def test_bad_initial_name_subexpr(self):
        self._check_subexpr_raises_compiler_error(
            '123',
            "Invalid variable name"
        )

    def test_builtins_in_path(self):
        from ..tales import ExpressionEngine
        from ..expressions import PathExpr, SubPathExpr

        class MySubPathExpr(SubPathExpr):
            ALLOWED_BUILTINS = {'True': True, 'False': False, 'x': None}

        class MyPathExpr(PathExpr):
            SUBEXPR_FACTORY = MySubPathExpr

        engine = ExpressionEngine()
        for pt in MyPathExpr._default_type_names:
            engine.registerType(pt, MyPathExpr)

        def eval(expr):
            return engine.compile(expr)(self.context)

        self.assertTrue(eval("True"))
        self.assertFalse(eval("False"))
        with self.assertRaises(KeyError):
            eval("None")
        self.assertIsNotNone(eval("x"))  # variable before builtin


class FunctionTests(ExpressionTestBase):

    def setUp(self):
        ExpressionTestBase.setUp(self)

        # a test namespace
        @implementer(ITALESFunctionNamespace)
        class TestNameSpace(object):

            def __init__(self, context):
                self.context = context

            def setEngine(self, engine):
                self._engine = engine

            def engine(self):
                return self._engine

            def upper(self):
                return str(self.context).upper()

            def __getitem__(self, key):
                if key == 'jump':
                    return self.context._d
                raise KeyError(key)

        self.TestNameSpace = TestNameSpace
        self.engine.registerFunctionNamespace('namespace', self.TestNameSpace)
        self.engine.registerFunctionNamespace('not_callable_ns', None)

    # framework-ish tests

    def testSetEngine(self):
        expr = self.engine.compile('adapterTest/namespace:engine')
        self.assertEqual(expr(self.context), self.context)

    def testGetFunctionNamespace(self):
        self.assertEqual(
            self.engine.getFunctionNamespace('namespace'),
            self.TestNameSpace
        )

    def testGetFunctionNamespaceBadNamespace(self):
        self.assertRaises(KeyError,
                          self.engine.getFunctionNamespace,
                          'badnamespace')

    # compile time tests

    def testBadNamespace(self):
        # namespace doesn't exist
        self._check_raises_compiler_error(
            'adapterTest/badnamespace:title',
            'Unknown namespace "badnamespace"')

    def testBadInitialNamespace(self):
        # first segment in a path must not have modifier
        self._check_raises_compiler_error(
            'namespace:title',
            'Unrecognized expression type "namespace"')

        # In an ideal world there would be another test here to test
        # that a nicer error was raised when you tried to use
        # something like:
        # standard:namespace:upper
        # ...as a path.
        # However, the compilation stage of PathExpr currently
        # allows any expression type to be nested, so something like:
        # standard:standard:context/attribute
        # ...will work fine.
        # When that is changed so that only expression types which
        # should be nested are nestable, then the additional test
        # should be added here.

    def test_bad_initial_namespace_subpath(self):
        self._check_subexpr_raises_compiler_error(
            'namespace:title',
            "Namespace function specified in first subpath element")

    def testInvalidNamespaceName(self):
        self._check_raises_compiler_error(
            'adapterTest/1foo:bar',
            'Invalid namespace name "1foo"')

    def testBadFunction(self):
        # namespace is fine, adapter is not defined
        expr = self.engine.compile('adapterTest/namespace:title')
        with self.assertRaises(KeyError) as exc:
            expr(self.context)

        e = exc.exception
        self.assertEqual(e.args[0], 'title')

    # runtime tests

    def testNormalFunction(self):
        expr = self.engine.compile('adapterTest/namespace:upper')
        self.assertEqual(expr(self.context), 'YIKES')

    def testFunctionOnFunction(self):
        expr = self.engine.compile(
            'adapterTest/namespace:jump/namespace:upper')
        self.assertEqual(expr(self.context), 'XANDER')

    def testPathOnFunction(self):
        expr = self.engine.compile('adapterTest/namespace:jump/y/z')
        self._check_evals_to(expr, self.context.vars['x'].y.z)

    def test_path_through_non_callable_nampspace(self):
        expr = self.engine.compile('adapterTest/not_callable_ns:nope')
        with self.assertRaisesRegex(ValueError, 'None'):
            expr(self.context)


class TestSimpleModuleImporter(unittest.TestCase):

    def _makeOne(self):
        from zope.tales.expressions import SimpleModuleImporter
        return SimpleModuleImporter()

    def test_simple(self):
        imp = self._makeOne()
        import os
        import os.path
        self.assertIs(os, imp['os'])
        self.assertIs(os.path, imp['os.path'])

    def test_no_such_toplevel_possible(self):
        with self.assertRaises(ImportError):
            self._makeOne()['this cannot exist']

    def test_no_such_submodule_not_package(self):
        with self.assertRaises(ImportError):
            self._makeOne()['zope.tales.tests.test_expressions.submodule']

    def test_no_such_submodule_package(self):
        with self.assertRaises(ImportError):
            self._makeOne()['zope.tales.tests.submodule']