summaryrefslogtreecommitdiffstats
path: root/python/mozbuild/mozbuild/test/frontend/test_sandbox.py
blob: 017de1ce9ce18f03b5a3796fd87830dda0a09019 (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
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import unittest

import mozpack.path as mozpath
from mozunit import main

from mozbuild.frontend.context import (
    FUNCTIONS,
    SPECIAL_VARIABLES,
    VARIABLES,
    Context,
    SourcePath,
)
from mozbuild.frontend.reader import MozbuildSandbox, SandboxCalledError
from mozbuild.frontend.sandbox import Sandbox, SandboxExecutionError, SandboxLoadError
from mozbuild.test.common import MockConfig

test_data_path = mozpath.abspath(mozpath.dirname(__file__))
test_data_path = mozpath.join(test_data_path, "data")


class TestSandbox(unittest.TestCase):
    def sandbox(self):
        return Sandbox(
            Context(
                {
                    "DIRS": (list, list, None),
                }
            )
        )

    def test_exec_source_success(self):
        sandbox = self.sandbox()
        context = sandbox._context

        sandbox.exec_source("foo = True", mozpath.abspath("foo.py"))

        self.assertNotIn("foo", context)
        self.assertEqual(context.main_path, mozpath.abspath("foo.py"))
        self.assertEqual(context.all_paths, set([mozpath.abspath("foo.py")]))

    def test_exec_compile_error(self):
        sandbox = self.sandbox()

        with self.assertRaises(SandboxExecutionError) as se:
            sandbox.exec_source("2f23;k;asfj", mozpath.abspath("foo.py"))

        self.assertEqual(se.exception.file_stack, [mozpath.abspath("foo.py")])
        self.assertIsInstance(se.exception.exc_value, SyntaxError)
        self.assertEqual(sandbox._context.main_path, mozpath.abspath("foo.py"))

    def test_exec_import_denied(self):
        sandbox = self.sandbox()

        with self.assertRaises(SandboxExecutionError) as se:
            sandbox.exec_source("import sys")

        self.assertIsInstance(se.exception, SandboxExecutionError)
        self.assertEqual(se.exception.exc_type, ImportError)

    def test_exec_source_multiple(self):
        sandbox = self.sandbox()

        sandbox.exec_source('DIRS = ["foo"]')
        sandbox.exec_source('DIRS += ["bar"]')

        self.assertEqual(sandbox["DIRS"], ["foo", "bar"])

    def test_exec_source_illegal_key_set(self):
        sandbox = self.sandbox()

        with self.assertRaises(SandboxExecutionError) as se:
            sandbox.exec_source("ILLEGAL = True")

        e = se.exception
        self.assertIsInstance(e.exc_value, KeyError)

        e = se.exception.exc_value
        self.assertEqual(e.args[0], "global_ns")
        self.assertEqual(e.args[1], "set_unknown")

    def test_exec_source_reassign(self):
        sandbox = self.sandbox()

        sandbox.exec_source('DIRS = ["foo"]')
        with self.assertRaises(SandboxExecutionError) as se:
            sandbox.exec_source('DIRS = ["bar"]')

        self.assertEqual(sandbox["DIRS"], ["foo"])
        e = se.exception
        self.assertIsInstance(e.exc_value, KeyError)

        e = se.exception.exc_value
        self.assertEqual(e.args[0], "global_ns")
        self.assertEqual(e.args[1], "reassign")
        self.assertEqual(e.args[2], "DIRS")

    def test_exec_source_reassign_builtin(self):
        sandbox = self.sandbox()

        with self.assertRaises(SandboxExecutionError) as se:
            sandbox.exec_source("sorted = 1")

        e = se.exception
        self.assertIsInstance(e.exc_value, KeyError)

        e = se.exception.exc_value
        self.assertEqual(e.args[0], "Cannot reassign builtins")


class TestedSandbox(MozbuildSandbox):
    """Version of MozbuildSandbox with a little more convenience for testing.

    It automatically normalizes paths given to exec_file and exec_source. This
    helps simplify the test code.
    """

    def normalize_path(self, path):
        return mozpath.normpath(mozpath.join(self._context.config.topsrcdir, path))

    def source_path(self, path):
        return SourcePath(self._context, path)

    def exec_file(self, path):
        super(TestedSandbox, self).exec_file(self.normalize_path(path))

    def exec_source(self, source, path=""):
        super(TestedSandbox, self).exec_source(
            source, self.normalize_path(path) if path else ""
        )


class TestMozbuildSandbox(unittest.TestCase):
    def sandbox(self, data_path=None, metadata={}):
        config = None

        if data_path is not None:
            config = MockConfig(mozpath.join(test_data_path, data_path))
        else:
            config = MockConfig()

        return TestedSandbox(Context(VARIABLES, config), metadata)

    def test_default_state(self):
        sandbox = self.sandbox()
        sandbox._context.add_source(sandbox.normalize_path("moz.build"))
        config = sandbox._context.config

        self.assertEqual(sandbox["TOPSRCDIR"], config.topsrcdir)
        self.assertEqual(sandbox["TOPOBJDIR"], config.topobjdir)
        self.assertEqual(sandbox["RELATIVEDIR"], "")
        self.assertEqual(sandbox["SRCDIR"], config.topsrcdir)
        self.assertEqual(sandbox["OBJDIR"], config.topobjdir)

    def test_symbol_presence(self):
        # Ensure no discrepancies between the master symbol table and what's in
        # the sandbox.
        sandbox = self.sandbox()
        sandbox._context.add_source(sandbox.normalize_path("moz.build"))

        all_symbols = set()
        all_symbols |= set(FUNCTIONS.keys())
        all_symbols |= set(SPECIAL_VARIABLES.keys())

        for symbol in all_symbols:
            self.assertIsNotNone(sandbox[symbol])

    def test_path_calculation(self):
        sandbox = self.sandbox()
        sandbox._context.add_source(sandbox.normalize_path("foo/bar/moz.build"))
        config = sandbox._context.config

        self.assertEqual(sandbox["TOPSRCDIR"], config.topsrcdir)
        self.assertEqual(sandbox["TOPOBJDIR"], config.topobjdir)
        self.assertEqual(sandbox["RELATIVEDIR"], "foo/bar")
        self.assertEqual(sandbox["SRCDIR"], mozpath.join(config.topsrcdir, "foo/bar"))
        self.assertEqual(sandbox["OBJDIR"], mozpath.join(config.topobjdir, "foo/bar"))

    def test_config_access(self):
        sandbox = self.sandbox()
        config = sandbox._context.config

        self.assertEqual(sandbox["CONFIG"]["MOZ_TRUE"], "1")
        self.assertEqual(sandbox["CONFIG"]["MOZ_FOO"], config.substs["MOZ_FOO"])

        # Access to an undefined substitution should return None.
        self.assertNotIn("MISSING", sandbox["CONFIG"])
        self.assertIsNone(sandbox["CONFIG"]["MISSING"])

        # Should shouldn't be allowed to assign to the config.
        with self.assertRaises(Exception):
            sandbox["CONFIG"]["FOO"] = ""

    def test_special_variables(self):
        sandbox = self.sandbox()
        sandbox._context.add_source(sandbox.normalize_path("moz.build"))

        for k in SPECIAL_VARIABLES:
            with self.assertRaises(KeyError):
                sandbox[k] = 0

    def test_exec_source_reassign_exported(self):
        template_sandbox = self.sandbox(data_path="templates")

        # Templates need to be defined in actual files because of
        # inspect.getsourcelines.
        template_sandbox.exec_file("templates.mozbuild")

        config = MockConfig()

        exports = {"DIST_SUBDIR": "browser"}

        sandbox = TestedSandbox(
            Context(VARIABLES, config),
            metadata={
                "exports": exports,
                "templates": template_sandbox.templates,
            },
        )

        self.assertEqual(sandbox["DIST_SUBDIR"], "browser")

        # Templates should not interfere
        sandbox.exec_source("Template([])", "foo.mozbuild")

        sandbox.exec_source('DIST_SUBDIR = "foo"')
        with self.assertRaises(SandboxExecutionError) as se:
            sandbox.exec_source('DIST_SUBDIR = "bar"')

        self.assertEqual(sandbox["DIST_SUBDIR"], "foo")
        e = se.exception
        self.assertIsInstance(e.exc_value, KeyError)

        e = se.exception.exc_value
        self.assertEqual(e.args[0], "global_ns")
        self.assertEqual(e.args[1], "reassign")
        self.assertEqual(e.args[2], "DIST_SUBDIR")

    def test_include_basic(self):
        sandbox = self.sandbox(data_path="include-basic")

        sandbox.exec_file("moz.build")

        self.assertEqual(
            sandbox["DIRS"],
            [
                sandbox.source_path("foo"),
                sandbox.source_path("bar"),
            ],
        )
        self.assertEqual(
            sandbox._context.main_path, sandbox.normalize_path("moz.build")
        )
        self.assertEqual(len(sandbox._context.all_paths), 2)

    def test_include_outside_topsrcdir(self):
        sandbox = self.sandbox(data_path="include-outside-topsrcdir")

        with self.assertRaises(SandboxLoadError) as se:
            sandbox.exec_file("relative.build")

        self.assertEqual(
            se.exception.illegal_path, sandbox.normalize_path("../moz.build")
        )

    def test_include_error_stack(self):
        # Ensure the path stack is reported properly in exceptions.
        sandbox = self.sandbox(data_path="include-file-stack")

        with self.assertRaises(SandboxExecutionError) as se:
            sandbox.exec_file("moz.build")

        e = se.exception
        self.assertIsInstance(e.exc_value, KeyError)

        args = e.exc_value.args
        self.assertEqual(args[0], "global_ns")
        self.assertEqual(args[1], "set_unknown")
        self.assertEqual(args[2], "ILLEGAL")

        expected_stack = [
            mozpath.join(sandbox._context.config.topsrcdir, p)
            for p in ["moz.build", "included-1.build", "included-2.build"]
        ]

        self.assertEqual(e.file_stack, expected_stack)

    def test_include_missing(self):
        sandbox = self.sandbox(data_path="include-missing")

        with self.assertRaises(SandboxLoadError) as sle:
            sandbox.exec_file("moz.build")

        self.assertIsNotNone(sle.exception.read_error)

    def test_include_relative_from_child_dir(self):
        # A relative path from a subdirectory should be relative from that
        # child directory.
        sandbox = self.sandbox(data_path="include-relative-from-child")
        sandbox.exec_file("child/child.build")
        self.assertEqual(sandbox["DIRS"], [sandbox.source_path("../foo")])

        sandbox = self.sandbox(data_path="include-relative-from-child")
        sandbox.exec_file("child/child2.build")
        self.assertEqual(sandbox["DIRS"], [sandbox.source_path("../foo")])

    def test_include_topsrcdir_relative(self):
        # An absolute path for include() is relative to topsrcdir.

        sandbox = self.sandbox(data_path="include-topsrcdir-relative")
        sandbox.exec_file("moz.build")

        self.assertEqual(sandbox["DIRS"], [sandbox.source_path("foo")])

    def test_error(self):
        sandbox = self.sandbox()

        with self.assertRaises(SandboxCalledError) as sce:
            sandbox.exec_source('error("This is an error.")')

        e = sce.exception.message
        self.assertIn("This is an error.", str(e))

    def test_substitute_config_files(self):
        sandbox = self.sandbox()
        sandbox._context.add_source(sandbox.normalize_path("moz.build"))

        sandbox.exec_source('CONFIGURE_SUBST_FILES += ["bar", "foo"]')
        self.assertEqual(sandbox["CONFIGURE_SUBST_FILES"], ["bar", "foo"])
        for item in sandbox["CONFIGURE_SUBST_FILES"]:
            self.assertIsInstance(item, SourcePath)

    def test_invalid_exports_set_base(self):
        sandbox = self.sandbox()

        with self.assertRaises(SandboxExecutionError) as se:
            sandbox.exec_source('EXPORTS = "foo.h"')

        self.assertEqual(se.exception.exc_type, ValueError)

    def test_templates(self):
        sandbox = self.sandbox(data_path="templates")

        # Templates need to be defined in actual files because of
        # inspect.getsourcelines.
        sandbox.exec_file("templates.mozbuild")

        sandbox2 = self.sandbox(metadata={"templates": sandbox.templates})
        source = """
Template([
    'foo.cpp',
])
"""
        sandbox2.exec_source(source, "foo.mozbuild")

        self.assertEqual(
            sandbox2._context,
            {
                "SOURCES": ["foo.cpp"],
                "DIRS": [],
            },
        )

        sandbox2 = self.sandbox(metadata={"templates": sandbox.templates})
        source = """
SOURCES += ['qux.cpp']
Template([
    'bar.cpp',
    'foo.cpp',
],[
    'foo',
])
SOURCES += ['hoge.cpp']
"""
        sandbox2.exec_source(source, "foo.mozbuild")

        self.assertEqual(
            sandbox2._context,
            {
                "SOURCES": ["qux.cpp", "bar.cpp", "foo.cpp", "hoge.cpp"],
                "DIRS": [sandbox2.source_path("foo")],
            },
        )

        sandbox2 = self.sandbox(metadata={"templates": sandbox.templates})
        source = """
TemplateError([
    'foo.cpp',
])
"""
        with self.assertRaises(SandboxExecutionError) as se:
            sandbox2.exec_source(source, "foo.mozbuild")

        e = se.exception
        self.assertIsInstance(e.exc_value, KeyError)

        e = se.exception.exc_value
        self.assertEqual(e.args[0], "global_ns")
        self.assertEqual(e.args[1], "set_unknown")

        # TemplateGlobalVariable tries to access 'illegal' but that is expected
        # to throw.
        sandbox2 = self.sandbox(metadata={"templates": sandbox.templates})
        source = """
illegal = True
TemplateGlobalVariable()
"""
        with self.assertRaises(SandboxExecutionError) as se:
            sandbox2.exec_source(source, "foo.mozbuild")

        e = se.exception
        self.assertIsInstance(e.exc_value, NameError)

        # TemplateGlobalUPPERVariable sets SOURCES with DIRS, but the context
        # used when running the template is not expected to access variables
        # from the global context.
        sandbox2 = self.sandbox(metadata={"templates": sandbox.templates})
        source = """
DIRS += ['foo']
TemplateGlobalUPPERVariable()
"""
        sandbox2.exec_source(source, "foo.mozbuild")
        self.assertEqual(
            sandbox2._context,
            {
                "SOURCES": [],
                "DIRS": [sandbox2.source_path("foo")],
            },
        )

        # However, the result of the template is mixed with the global
        # context.
        sandbox2 = self.sandbox(metadata={"templates": sandbox.templates})
        source = """
SOURCES += ['qux.cpp']
TemplateInherit([
    'bar.cpp',
    'foo.cpp',
])
SOURCES += ['hoge.cpp']
"""
        sandbox2.exec_source(source, "foo.mozbuild")

        self.assertEqual(
            sandbox2._context,
            {
                "SOURCES": ["qux.cpp", "bar.cpp", "foo.cpp", "hoge.cpp"],
                "USE_LIBS": ["foo"],
                "DIRS": [],
            },
        )

        # Template names must be CamelCase. Here, we can define the template
        # inline because the error happens before inspect.getsourcelines.
        sandbox2 = self.sandbox(metadata={"templates": sandbox.templates})
        source = """
@template
def foo():
    pass
"""

        with self.assertRaises(SandboxExecutionError) as se:
            sandbox2.exec_source(source, "foo.mozbuild")

        e = se.exception
        self.assertIsInstance(e.exc_value, NameError)

        e = se.exception.exc_value
        self.assertIn("Template function names must be CamelCase.", str(e))

        # Template names must not already be registered.
        sandbox2 = self.sandbox(metadata={"templates": sandbox.templates})
        source = """
@template
def Template():
    pass
"""
        with self.assertRaises(SandboxExecutionError) as se:
            sandbox2.exec_source(source, "foo.mozbuild")

        e = se.exception
        self.assertIsInstance(e.exc_value, KeyError)

        e = se.exception.exc_value
        self.assertIn(
            'A template named "Template" was already declared in %s.'
            % sandbox.normalize_path("templates.mozbuild"),
            str(e),
        )

    def test_function_args(self):
        class Foo(int):
            pass

        def foo(a, b):
            return type(a), type(b)

        FUNCTIONS.update(
            {
                "foo": (lambda self: foo, (Foo, int), ""),
            }
        )

        try:
            sandbox = self.sandbox()
            source = 'foo("a", "b")'

            with self.assertRaises(SandboxExecutionError) as se:
                sandbox.exec_source(source, "foo.mozbuild")

            e = se.exception
            self.assertIsInstance(e.exc_value, ValueError)

            sandbox = self.sandbox()
            source = 'foo(1, "b")'

            with self.assertRaises(SandboxExecutionError) as se:
                sandbox.exec_source(source, "foo.mozbuild")

            e = se.exception
            self.assertIsInstance(e.exc_value, ValueError)

            sandbox = self.sandbox()
            source = "a = foo(1, 2)"
            sandbox.exec_source(source, "foo.mozbuild")

            self.assertEqual(sandbox["a"], (Foo, int))
        finally:
            del FUNCTIONS["foo"]


if __name__ == "__main__":
    main()