|
| 1 | +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. |
| 2 | +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. |
| 3 | +# |
| 4 | +# The Universal Permissive License (UPL), Version 1.0 |
| 5 | +# |
| 6 | +# Subject to the condition set forth below, permission is hereby granted to any |
| 7 | +# person obtaining a copy of this software, associated documentation and/or |
| 8 | +# data (collectively the "Software"), free of charge and under any and all |
| 9 | +# copyright rights in the Software, and any and all patent rights owned or |
| 10 | +# freely licensable by each licensor hereunder covering either (i) the |
| 11 | +# unmodified Software as contributed to or provided by such licensor, or (ii) |
| 12 | +# the Larger Works (as defined below), to deal in both |
| 13 | +# |
| 14 | +# (a) the Software, and |
| 15 | +# |
| 16 | +# (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if |
| 17 | +# one is included with the Software each a "Larger Work" to which the Software |
| 18 | +# is contributed by such licensors), |
| 19 | +# |
| 20 | +# without restriction, including without limitation the rights to copy, create |
| 21 | +# derivative works of, display, perform, and distribute the Software and make, |
| 22 | +# use, sell, offer for sale, import, export, have made, and have sold the |
| 23 | +# Software and the Larger Work(s), and to sublicense the foregoing rights on |
| 24 | +# either these or other terms. |
| 25 | +# |
| 26 | +# This license is subject to the following condition: |
| 27 | +# |
| 28 | +# The above copyright notice and either this complete permission notice or at a |
| 29 | +# minimum a reference to the UPL must be included in all copies or substantial |
| 30 | +# portions of the Software. |
| 31 | +# |
| 32 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 33 | +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 34 | +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 35 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 36 | +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 37 | +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 38 | +# SOFTWARE. |
| 39 | + |
| 40 | +import sys |
| 41 | + |
| 42 | +if sys.platform != 'win32' and (sys.implementation.name != 'graalpy' or not __graalpython__.is_managed_launcher()): |
| 43 | + import os |
| 44 | + import re |
| 45 | + import select |
| 46 | + import subprocess |
| 47 | + import tempfile |
| 48 | + import termios |
| 49 | + from textwrap import dedent |
| 50 | + |
| 51 | + |
| 52 | + def validate_repl(stdin, python_args=(), ignore_preamble=True): |
| 53 | + env = os.environ.copy() |
| 54 | + env['TERM'] = 'ansi' |
| 55 | + env['PYTHONIOENCODING'] = 'utf-8' |
| 56 | + pty_parent, pty_child = os.openpty() |
| 57 | + try: |
| 58 | + termios.tcsetwinsize(pty_parent, (60, 80)) |
| 59 | + proc = subprocess.Popen( |
| 60 | + [sys.executable, '-I', *python_args], |
| 61 | + env=env, |
| 62 | + stdin=pty_child, |
| 63 | + stdout=pty_child, |
| 64 | + stderr=pty_child, |
| 65 | + ) |
| 66 | + out = '' |
| 67 | + input_and_output = [] |
| 68 | + expected_preamble = '' |
| 69 | + in_matches = list(re.finditer(r'^(>>>|\.\.\.) (.*)', stdin, flags=re.MULTILINE)) |
| 70 | + for i, match in enumerate(in_matches): |
| 71 | + if i == 0: |
| 72 | + expected_preamble = stdin[:match.start() - 1] if match.start() else '' |
| 73 | + input_and_output.append(( |
| 74 | + match.group(1), |
| 75 | + match.group(2), |
| 76 | + stdin[match.end():in_matches[i + 1].start() - 1 if i + 1 < len(in_matches) else -1], |
| 77 | + )) |
| 78 | + index = -1 |
| 79 | + whole_out = '' |
| 80 | + while True: |
| 81 | + rlist, _, _ = select.select([pty_parent], [], [], 30) |
| 82 | + assert pty_parent in rlist, f"Timed out waiting for REPL output. Output: {whole_out}{out}" |
| 83 | + out += os.read(pty_parent, 1024).decode('utf-8') |
| 84 | + out = out.replace('\r\n', '\n') |
| 85 | + out = re.sub(r'\x1b\[(?:\?2004[hl]|\d+[A-G])', '', out) |
| 86 | + if out == '>>> ' or out.endswith(('\n>>> ', '\n... ')): |
| 87 | + prompt = out[:3] |
| 88 | + actual = out[:-5] |
| 89 | + if index >= 0: |
| 90 | + expected_prompt, current_in, expected_out = input_and_output[index] |
| 91 | + assert prompt == expected_prompt |
| 92 | + expected = f'{expected_prompt} {current_in}{expected_out}' |
| 93 | + else: |
| 94 | + expected = expected_preamble |
| 95 | + if index >= 0 or not ignore_preamble: |
| 96 | + assert actual == expected, f'Actual:\n{actual!r}\nExpected:\n{expected!r}' |
| 97 | + index += 1 |
| 98 | + whole_out += out[:-4] |
| 99 | + out = out[-4:] |
| 100 | + if index >= len(input_and_output): |
| 101 | + os.write(pty_parent, b'\x04') # CTRL-D |
| 102 | + proc.wait(timeout=30) |
| 103 | + out = os.read(pty_parent, 1024).decode('utf-8') |
| 104 | + out = re.sub(r'\x1b\[\?2004[hl]', '', out) |
| 105 | + assert not out.strip(), f"Garbage after EOF:\n{out!r}" |
| 106 | + return |
| 107 | + else: |
| 108 | + _, next_in, _ = input_and_output[index] |
| 109 | + os.write(pty_parent, next_in.encode('utf-8') + b'\r') |
| 110 | + finally: |
| 111 | + os.close(pty_child) |
| 112 | + os.close(pty_parent) |
| 113 | + |
| 114 | + |
| 115 | + def test_basic_repl(): |
| 116 | + validate_repl(dedent("""\ |
| 117 | + >>> 1023 + 1 |
| 118 | + 1024 |
| 119 | + >>> None |
| 120 | + >>> "hello" |
| 121 | + 'hello' |
| 122 | + >>> _ |
| 123 | + 'hello' |
| 124 | + """)) |
| 125 | + |
| 126 | + |
| 127 | + def test_continuation(): |
| 128 | + validate_repl(dedent(r'''\ |
| 129 | + >>> def foo(): |
| 130 | + ... a = 1 |
| 131 | + ... return a |
| 132 | + ... |
| 133 | + >>> class Foo: |
| 134 | + ... def meth(self): |
| 135 | + ... return 1 |
| 136 | + ... |
| 137 | + >>> from functools import wraps |
| 138 | + >>> @wraps |
| 139 | + ... def foo(fn): |
| 140 | + ... return fn |
| 141 | + ... |
| 142 | + >>> from contextlib import contextmanager |
| 143 | + >>> @contextmanager |
| 144 | + ... class Foo: |
| 145 | + ... pass |
| 146 | + ... |
| 147 | + >>> """ |
| 148 | + ... asdf |
| 149 | + ... """ |
| 150 | + '\nasdf\n' |
| 151 | + ''')) |
| 152 | + |
| 153 | + |
| 154 | + def test_exceptions(): |
| 155 | + validate_repl(dedent("""\ |
| 156 | + >>> 1 / 0 |
| 157 | + Traceback (most recent call last): |
| 158 | + File "<stdin>", line 1, in <module> |
| 159 | + ZeroDivisionError: division by zero |
| 160 | + >>> import sys |
| 161 | + >>> sys.last_value |
| 162 | + ZeroDivisionError('division by zero') |
| 163 | + >>> class BrokenRepr: |
| 164 | + ... def __repr__(self): |
| 165 | + ... asdf |
| 166 | + ... |
| 167 | + >>> BrokenRepr() |
| 168 | + Traceback (most recent call last): |
| 169 | + File "<stdin>", line 1, in <module> |
| 170 | + File "<stdin>", line 3, in __repr__ |
| 171 | + NameError: name 'asdf' is not defined |
| 172 | + """)) |
| 173 | + |
| 174 | + |
| 175 | + def test_inspect_flag(): |
| 176 | + with tempfile.NamedTemporaryFile('w') as f: |
| 177 | + f.write('a = 1\n') |
| 178 | + f.flush() |
| 179 | + validate_repl(dedent("""\ |
| 180 | + >>> a |
| 181 | + 1 |
| 182 | + """), python_args=['-i', f.name], ignore_preamble=False) |
| 183 | + |
| 184 | + |
| 185 | + def test_inspect_flag_exit(): |
| 186 | + with tempfile.NamedTemporaryFile('w') as f: |
| 187 | + f.write('a = 1\nimport sys\nsys.exit(1)\n') |
| 188 | + f.flush() |
| 189 | + validate_repl(dedent(f"""\ |
| 190 | + Traceback (most recent call last): |
| 191 | + File "{os.path.realpath(f.name)}", line 3, in <module> |
| 192 | + sys.exit(1) |
| 193 | + SystemExit: 1 |
| 194 | + >>> a |
| 195 | + 1 |
| 196 | + """), python_args=['-i', f.name], ignore_preamble=False) |
0 commit comments