File: test_imports.py

package info (click to toggle)
restrictedpython 8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,072 kB
  • sloc: python: 4,043; makefile: 193
file content (62 lines) | stat: -rw-r--r-- 1,536 bytes parent folder | download
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
"""
Tests about imports
"""

import pytest

from RestrictedPython import compile_restricted_exec
from RestrictedPython import safe_builtins
from tests.helper import restricted_exec


OS_IMPORT_EXAMPLE = """
import os

os.listdir('/')
"""


def test_os_import():
    """It does not allow to import anything by default.

    The `__import__` function is not provided as it is not safe.
    """
    # Caution: This test is broken on PyPy until the following issue is fixed:
    # https://bitbucket.org/pypy/pypy/issues/2653
    # PyPy currently ignores the restriction of the `__builtins__`.
    glb = {'__builtins__': safe_builtins}

    with pytest.raises(ImportError) as err:
        restricted_exec(OS_IMPORT_EXAMPLE, glb)
    assert '__import__ not found' == str(err.value)


BUILTINS_EXAMPLE = """
import builtins

mygetattr = builtins['getattr']
"""


def test_import_py3_builtins():
    """It should not be allowed to access global builtins in Python3."""
    result = compile_restricted_exec(BUILTINS_EXAMPLE)
    assert result.code is None
    assert result.errors == (
        'Line 2: "builtins" is a reserved name.',
        'Line 4: "builtins" is a reserved name.'
    )


BUILTINS_AS_EXAMPLE = """
import builtins as glb

mygetattr = glb['getattr']
"""


def test_import_py3_as_builtins():
    """It should not be allowed to access global builtins in Python3."""
    result = compile_restricted_exec(BUILTINS_AS_EXAMPLE)
    assert result.code is None
    assert result.errors == ('Line 2: "builtins" is a reserved name.',)