Show More
@@ -1,50 +1,59 b'' | |||||
1 | name: Run tests |
|
1 | name: Run tests | |
2 |
|
2 | |||
3 | on: |
|
3 | on: | |
4 | push: |
|
4 | push: | |
5 | pull_request: |
|
5 | pull_request: | |
6 | # Run weekly on Monday at 1:23 UTC |
|
6 | # Run weekly on Monday at 1:23 UTC | |
7 | schedule: |
|
7 | schedule: | |
8 | - cron: '23 1 * * 1' |
|
8 | - cron: '23 1 * * 1' | |
9 | workflow_dispatch: |
|
9 | workflow_dispatch: | |
10 |
|
10 | |||
11 |
|
11 | |||
12 | jobs: |
|
12 | jobs: | |
13 | test: |
|
13 | test: | |
14 | runs-on: ${{ matrix.os }} |
|
14 | runs-on: ${{ matrix.os }} | |
15 | strategy: |
|
15 | strategy: | |
16 | matrix: |
|
16 | matrix: | |
17 | os: [ubuntu-latest] |
|
17 | os: [ubuntu-latest] | |
18 | python-version: ["3.7", "3.8", "3.9", "3.10"] |
|
18 | python-version: ["3.7", "3.8", "3.9", "3.10"] | |
|
19 | deps: [test_extra] | |||
19 | # Test all on ubuntu, test ends on macos |
|
20 | # Test all on ubuntu, test ends on macos | |
20 | include: |
|
21 | include: | |
21 | - os: macos-latest |
|
22 | - os: macos-latest | |
22 | python-version: "3.7" |
|
23 | python-version: "3.7" | |
|
24 | deps: test_extra | |||
23 | - os: macos-latest |
|
25 | - os: macos-latest | |
24 | python-version: "3.10" |
|
26 | python-version: "3.10" | |
|
27 | deps: test_extra | |||
|
28 | # Tests minimal dependencies set | |||
|
29 | - os: ubuntu-latest | |||
|
30 | python-version: "3.10" | |||
|
31 | deps: test | |||
|
32 | # Tests latest development Python version | |||
|
33 | - os: ubuntu-latest | |||
|
34 | python-version: "3.11-dev" | |||
|
35 | deps: test | |||
25 |
|
36 | |||
26 | steps: |
|
37 | steps: | |
27 | - uses: actions/checkout@v2 |
|
38 | - uses: actions/checkout@v2 | |
28 | - name: Set up Python ${{ matrix.python-version }} |
|
39 | - name: Set up Python ${{ matrix.python-version }} | |
29 | uses: actions/setup-python@v2 |
|
40 | uses: actions/setup-python@v2 | |
30 | with: |
|
41 | with: | |
31 | python-version: ${{ matrix.python-version }} |
|
42 | python-version: ${{ matrix.python-version }} | |
32 | - name: Install latex |
|
43 | - name: Install latex | |
33 | if: runner.os == 'Linux' |
|
44 | if: runner.os == 'Linux' && matrix.deps == 'test_extra' | |
34 | run: sudo apt-get -yq -o Acquire::Retries=3 --no-install-suggests --no-install-recommends install texlive dvipng |
|
45 | run: sudo apt-get -yq -o Acquire::Retries=3 --no-install-suggests --no-install-recommends install texlive dvipng | |
35 | - name: Install and update Python dependencies |
|
46 | - name: Install and update Python dependencies | |
36 | run: | |
|
47 | run: | | |
37 | python -m pip install --upgrade pip setuptools wheel |
|
48 | python -m pip install --upgrade pip setuptools wheel | |
38 |
python -m pip install --upgrade -e |
|
49 | python -m pip install --upgrade -e .[${{ matrix.deps }}] | |
39 |
python -m pip install --upgrade |
|
50 | python -m pip install --upgrade check-manifest pytest-cov | |
40 | python -m pip install --upgrade pytest pytest-cov pytest-trio 'matplotlib!=3.2.0' pandas |
|
|||
41 | python -m pip install --upgrade check-manifest pytest-cov anyio |
|
|||
42 | - name: Check manifest |
|
51 | - name: Check manifest | |
43 | run: check-manifest |
|
52 | run: check-manifest | |
44 | - name: pytest |
|
53 | - name: pytest | |
45 | env: |
|
54 | env: | |
46 | COLUMNS: 120 |
|
55 | COLUMNS: 120 | |
47 | run: | |
|
56 | run: | | |
48 | pytest --color=yes -v --cov --cov-report=xml |
|
57 | pytest --color=yes -v --cov --cov-report=xml | |
49 | - name: Upload coverage to Codecov |
|
58 | - name: Upload coverage to Codecov | |
50 | uses: codecov/codecov-action@v2 |
|
59 | uses: codecov/codecov-action@v2 |
@@ -1,1284 +1,1289 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """Tests for the IPython tab-completion machinery.""" |
|
2 | """Tests for the IPython tab-completion machinery.""" | |
3 |
|
3 | |||
4 | # Copyright (c) IPython Development Team. |
|
4 | # Copyright (c) IPython Development Team. | |
5 | # Distributed under the terms of the Modified BSD License. |
|
5 | # Distributed under the terms of the Modified BSD License. | |
6 |
|
6 | |||
7 | import os |
|
7 | import os | |
8 | import pytest |
|
8 | import pytest | |
9 | import sys |
|
9 | import sys | |
10 | import textwrap |
|
10 | import textwrap | |
11 | import unittest |
|
11 | import unittest | |
12 |
|
12 | |||
13 | from contextlib import contextmanager |
|
13 | from contextlib import contextmanager | |
14 |
|
14 | |||
15 | from traitlets.config.loader import Config |
|
15 | from traitlets.config.loader import Config | |
16 | from IPython import get_ipython |
|
16 | from IPython import get_ipython | |
17 | from IPython.core import completer |
|
17 | from IPython.core import completer | |
18 | from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory |
|
18 | from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory | |
19 | from IPython.utils.generics import complete_object |
|
19 | from IPython.utils.generics import complete_object | |
20 | from IPython.testing import decorators as dec |
|
20 | from IPython.testing import decorators as dec | |
21 |
|
21 | |||
22 | from IPython.core.completer import ( |
|
22 | from IPython.core.completer import ( | |
23 | Completion, |
|
23 | Completion, | |
24 | provisionalcompleter, |
|
24 | provisionalcompleter, | |
25 | match_dict_keys, |
|
25 | match_dict_keys, | |
26 | _deduplicate_completions, |
|
26 | _deduplicate_completions, | |
27 | ) |
|
27 | ) | |
28 |
|
28 | |||
29 | if sys.version_info >= (3, 10): |
|
29 | if sys.version_info >= (3, 10): | |
30 | import jedi |
|
30 | import jedi | |
31 | from pkg_resources import parse_version |
|
31 | from pkg_resources import parse_version | |
32 |
|
32 | |||
33 | # Requires https://github.com/davidhalter/jedi/pull/1795 |
|
33 | # Requires https://github.com/davidhalter/jedi/pull/1795 | |
34 | jedi_issue = parse_version(jedi.__version__) <= parse_version("0.18.0") |
|
34 | jedi_issue = parse_version(jedi.__version__) <= parse_version("0.18.0") | |
35 | else: |
|
35 | else: | |
36 | jedi_issue = False |
|
36 | jedi_issue = False | |
37 |
|
37 | |||
38 | # ----------------------------------------------------------------------------- |
|
38 | # ----------------------------------------------------------------------------- | |
39 | # Test functions |
|
39 | # Test functions | |
40 | # ----------------------------------------------------------------------------- |
|
40 | # ----------------------------------------------------------------------------- | |
41 |
|
41 | |||
42 | def recompute_unicode_ranges(): |
|
42 | def recompute_unicode_ranges(): | |
43 | """ |
|
43 | """ | |
44 | utility to recompute the largest unicode range without any characters |
|
44 | utility to recompute the largest unicode range without any characters | |
45 |
|
45 | |||
46 | use to recompute the gap in the global _UNICODE_RANGES of completer.py |
|
46 | use to recompute the gap in the global _UNICODE_RANGES of completer.py | |
47 | """ |
|
47 | """ | |
48 | import itertools |
|
48 | import itertools | |
49 | import unicodedata |
|
49 | import unicodedata | |
50 | valid = [] |
|
50 | valid = [] | |
51 | for c in range(0,0x10FFFF + 1): |
|
51 | for c in range(0,0x10FFFF + 1): | |
52 | try: |
|
52 | try: | |
53 | unicodedata.name(chr(c)) |
|
53 | unicodedata.name(chr(c)) | |
54 | except ValueError: |
|
54 | except ValueError: | |
55 | continue |
|
55 | continue | |
56 | valid.append(c) |
|
56 | valid.append(c) | |
57 |
|
57 | |||
58 | def ranges(i): |
|
58 | def ranges(i): | |
59 | for a, b in itertools.groupby(enumerate(i), lambda pair: pair[1] - pair[0]): |
|
59 | for a, b in itertools.groupby(enumerate(i), lambda pair: pair[1] - pair[0]): | |
60 | b = list(b) |
|
60 | b = list(b) | |
61 | yield b[0][1], b[-1][1] |
|
61 | yield b[0][1], b[-1][1] | |
62 |
|
62 | |||
63 | rg = list(ranges(valid)) |
|
63 | rg = list(ranges(valid)) | |
64 | lens = [] |
|
64 | lens = [] | |
65 | gap_lens = [] |
|
65 | gap_lens = [] | |
66 | pstart, pstop = 0,0 |
|
66 | pstart, pstop = 0,0 | |
67 | for start, stop in rg: |
|
67 | for start, stop in rg: | |
68 | lens.append(stop-start) |
|
68 | lens.append(stop-start) | |
69 | gap_lens.append((start - pstop, hex(pstop), hex(start), f'{round((start - pstop)/0xe01f0*100)}%')) |
|
69 | gap_lens.append((start - pstop, hex(pstop), hex(start), f'{round((start - pstop)/0xe01f0*100)}%')) | |
70 | pstart, pstop = start, stop |
|
70 | pstart, pstop = start, stop | |
71 |
|
71 | |||
72 | return sorted(gap_lens)[-1] |
|
72 | return sorted(gap_lens)[-1] | |
73 |
|
73 | |||
74 |
|
74 | |||
75 |
|
75 | |||
76 | def test_unicode_range(): |
|
76 | def test_unicode_range(): | |
77 | """ |
|
77 | """ | |
78 | Test that the ranges we test for unicode names give the same number of |
|
78 | Test that the ranges we test for unicode names give the same number of | |
79 | results than testing the full length. |
|
79 | results than testing the full length. | |
80 | """ |
|
80 | """ | |
81 | from IPython.core.completer import _unicode_name_compute, _UNICODE_RANGES |
|
81 | from IPython.core.completer import _unicode_name_compute, _UNICODE_RANGES | |
82 |
|
82 | |||
83 | expected_list = _unicode_name_compute([(0, 0x110000)]) |
|
83 | expected_list = _unicode_name_compute([(0, 0x110000)]) | |
84 | test = _unicode_name_compute(_UNICODE_RANGES) |
|
84 | test = _unicode_name_compute(_UNICODE_RANGES) | |
85 | len_exp = len(expected_list) |
|
85 | len_exp = len(expected_list) | |
86 | len_test = len(test) |
|
86 | len_test = len(test) | |
87 |
|
87 | |||
88 | # do not inline the len() or on error pytest will try to print the 130 000 + |
|
88 | # do not inline the len() or on error pytest will try to print the 130 000 + | |
89 | # elements. |
|
89 | # elements. | |
90 | message = None |
|
90 | message = None | |
91 | if len_exp != len_test or len_exp > 131808: |
|
91 | if len_exp != len_test or len_exp > 131808: | |
92 | size, start, stop, prct = recompute_unicode_ranges() |
|
92 | size, start, stop, prct = recompute_unicode_ranges() | |
93 | message = f"""_UNICODE_RANGES likely wrong and need updating. This is |
|
93 | message = f"""_UNICODE_RANGES likely wrong and need updating. This is | |
94 | likely due to a new release of Python. We've find that the biggest gap |
|
94 | likely due to a new release of Python. We've find that the biggest gap | |
95 | in unicode characters has reduces in size to be {size} characters |
|
95 | in unicode characters has reduces in size to be {size} characters | |
96 | ({prct}), from {start}, to {stop}. In completer.py likely update to |
|
96 | ({prct}), from {start}, to {stop}. In completer.py likely update to | |
97 |
|
97 | |||
98 | _UNICODE_RANGES = [(32, {start}), ({stop}, 0xe01f0)] |
|
98 | _UNICODE_RANGES = [(32, {start}), ({stop}, 0xe01f0)] | |
99 |
|
99 | |||
100 | And update the assertion below to use |
|
100 | And update the assertion below to use | |
101 |
|
101 | |||
102 | len_exp <= {len_exp} |
|
102 | len_exp <= {len_exp} | |
103 | """ |
|
103 | """ | |
104 | assert len_exp == len_test, message |
|
104 | assert len_exp == len_test, message | |
105 |
|
105 | |||
106 | # fail if new unicode symbols have been added. |
|
106 | # fail if new unicode symbols have been added. | |
107 |
assert len_exp <= 13 |
|
107 | assert len_exp <= 138552, message | |
108 |
|
108 | |||
109 |
|
109 | |||
110 | @contextmanager |
|
110 | @contextmanager | |
111 | def greedy_completion(): |
|
111 | def greedy_completion(): | |
112 | ip = get_ipython() |
|
112 | ip = get_ipython() | |
113 | greedy_original = ip.Completer.greedy |
|
113 | greedy_original = ip.Completer.greedy | |
114 | try: |
|
114 | try: | |
115 | ip.Completer.greedy = True |
|
115 | ip.Completer.greedy = True | |
116 | yield |
|
116 | yield | |
117 | finally: |
|
117 | finally: | |
118 | ip.Completer.greedy = greedy_original |
|
118 | ip.Completer.greedy = greedy_original | |
119 |
|
119 | |||
120 |
|
120 | |||
121 | def test_protect_filename(): |
|
121 | def test_protect_filename(): | |
122 | if sys.platform == "win32": |
|
122 | if sys.platform == "win32": | |
123 | pairs = [ |
|
123 | pairs = [ | |
124 | ("abc", "abc"), |
|
124 | ("abc", "abc"), | |
125 | (" abc", '" abc"'), |
|
125 | (" abc", '" abc"'), | |
126 | ("a bc", '"a bc"'), |
|
126 | ("a bc", '"a bc"'), | |
127 | ("a bc", '"a bc"'), |
|
127 | ("a bc", '"a bc"'), | |
128 | (" bc", '" bc"'), |
|
128 | (" bc", '" bc"'), | |
129 | ] |
|
129 | ] | |
130 | else: |
|
130 | else: | |
131 | pairs = [ |
|
131 | pairs = [ | |
132 | ("abc", "abc"), |
|
132 | ("abc", "abc"), | |
133 | (" abc", r"\ abc"), |
|
133 | (" abc", r"\ abc"), | |
134 | ("a bc", r"a\ bc"), |
|
134 | ("a bc", r"a\ bc"), | |
135 | ("a bc", r"a\ \ bc"), |
|
135 | ("a bc", r"a\ \ bc"), | |
136 | (" bc", r"\ \ bc"), |
|
136 | (" bc", r"\ \ bc"), | |
137 | # On posix, we also protect parens and other special characters. |
|
137 | # On posix, we also protect parens and other special characters. | |
138 | ("a(bc", r"a\(bc"), |
|
138 | ("a(bc", r"a\(bc"), | |
139 | ("a)bc", r"a\)bc"), |
|
139 | ("a)bc", r"a\)bc"), | |
140 | ("a( )bc", r"a\(\ \)bc"), |
|
140 | ("a( )bc", r"a\(\ \)bc"), | |
141 | ("a[1]bc", r"a\[1\]bc"), |
|
141 | ("a[1]bc", r"a\[1\]bc"), | |
142 | ("a{1}bc", r"a\{1\}bc"), |
|
142 | ("a{1}bc", r"a\{1\}bc"), | |
143 | ("a#bc", r"a\#bc"), |
|
143 | ("a#bc", r"a\#bc"), | |
144 | ("a?bc", r"a\?bc"), |
|
144 | ("a?bc", r"a\?bc"), | |
145 | ("a=bc", r"a\=bc"), |
|
145 | ("a=bc", r"a\=bc"), | |
146 | ("a\\bc", r"a\\bc"), |
|
146 | ("a\\bc", r"a\\bc"), | |
147 | ("a|bc", r"a\|bc"), |
|
147 | ("a|bc", r"a\|bc"), | |
148 | ("a;bc", r"a\;bc"), |
|
148 | ("a;bc", r"a\;bc"), | |
149 | ("a:bc", r"a\:bc"), |
|
149 | ("a:bc", r"a\:bc"), | |
150 | ("a'bc", r"a\'bc"), |
|
150 | ("a'bc", r"a\'bc"), | |
151 | ("a*bc", r"a\*bc"), |
|
151 | ("a*bc", r"a\*bc"), | |
152 | ('a"bc', r"a\"bc"), |
|
152 | ('a"bc', r"a\"bc"), | |
153 | ("a^bc", r"a\^bc"), |
|
153 | ("a^bc", r"a\^bc"), | |
154 | ("a&bc", r"a\&bc"), |
|
154 | ("a&bc", r"a\&bc"), | |
155 | ] |
|
155 | ] | |
156 | # run the actual tests |
|
156 | # run the actual tests | |
157 | for s1, s2 in pairs: |
|
157 | for s1, s2 in pairs: | |
158 | s1p = completer.protect_filename(s1) |
|
158 | s1p = completer.protect_filename(s1) | |
159 | assert s1p == s2 |
|
159 | assert s1p == s2 | |
160 |
|
160 | |||
161 |
|
161 | |||
162 | def check_line_split(splitter, test_specs): |
|
162 | def check_line_split(splitter, test_specs): | |
163 | for part1, part2, split in test_specs: |
|
163 | for part1, part2, split in test_specs: | |
164 | cursor_pos = len(part1) |
|
164 | cursor_pos = len(part1) | |
165 | line = part1 + part2 |
|
165 | line = part1 + part2 | |
166 | out = splitter.split_line(line, cursor_pos) |
|
166 | out = splitter.split_line(line, cursor_pos) | |
167 | assert out == split |
|
167 | assert out == split | |
168 |
|
168 | |||
169 |
|
169 | |||
170 | def test_line_split(): |
|
170 | def test_line_split(): | |
171 | """Basic line splitter test with default specs.""" |
|
171 | """Basic line splitter test with default specs.""" | |
172 | sp = completer.CompletionSplitter() |
|
172 | sp = completer.CompletionSplitter() | |
173 | # The format of the test specs is: part1, part2, expected answer. Parts 1 |
|
173 | # The format of the test specs is: part1, part2, expected answer. Parts 1 | |
174 | # and 2 are joined into the 'line' sent to the splitter, as if the cursor |
|
174 | # and 2 are joined into the 'line' sent to the splitter, as if the cursor | |
175 | # was at the end of part1. So an empty part2 represents someone hitting |
|
175 | # was at the end of part1. So an empty part2 represents someone hitting | |
176 | # tab at the end of the line, the most common case. |
|
176 | # tab at the end of the line, the most common case. | |
177 | t = [ |
|
177 | t = [ | |
178 | ("run some/scrip", "", "some/scrip"), |
|
178 | ("run some/scrip", "", "some/scrip"), | |
179 | ("run scripts/er", "ror.py foo", "scripts/er"), |
|
179 | ("run scripts/er", "ror.py foo", "scripts/er"), | |
180 | ("echo $HOM", "", "HOM"), |
|
180 | ("echo $HOM", "", "HOM"), | |
181 | ("print sys.pa", "", "sys.pa"), |
|
181 | ("print sys.pa", "", "sys.pa"), | |
182 | ("print(sys.pa", "", "sys.pa"), |
|
182 | ("print(sys.pa", "", "sys.pa"), | |
183 | ("execfile('scripts/er", "", "scripts/er"), |
|
183 | ("execfile('scripts/er", "", "scripts/er"), | |
184 | ("a[x.", "", "x."), |
|
184 | ("a[x.", "", "x."), | |
185 | ("a[x.", "y", "x."), |
|
185 | ("a[x.", "y", "x."), | |
186 | ('cd "some_file/', "", "some_file/"), |
|
186 | ('cd "some_file/', "", "some_file/"), | |
187 | ] |
|
187 | ] | |
188 | check_line_split(sp, t) |
|
188 | check_line_split(sp, t) | |
189 | # Ensure splitting works OK with unicode by re-running the tests with |
|
189 | # Ensure splitting works OK with unicode by re-running the tests with | |
190 | # all inputs turned into unicode |
|
190 | # all inputs turned into unicode | |
191 | check_line_split(sp, [map(str, p) for p in t]) |
|
191 | check_line_split(sp, [map(str, p) for p in t]) | |
192 |
|
192 | |||
193 |
|
193 | |||
194 | class NamedInstanceMetaclass(type): |
|
194 | class NamedInstanceMetaclass(type): | |
195 | def __getitem__(cls, item): |
|
195 | def __getitem__(cls, item): | |
196 | return cls.get_instance(item) |
|
196 | return cls.get_instance(item) | |
197 |
|
197 | |||
198 |
|
198 | |||
199 | class NamedInstanceClass(metaclass=NamedInstanceMetaclass): |
|
199 | class NamedInstanceClass(metaclass=NamedInstanceMetaclass): | |
200 | def __init__(self, name): |
|
200 | def __init__(self, name): | |
201 | if not hasattr(self.__class__, "instances"): |
|
201 | if not hasattr(self.__class__, "instances"): | |
202 | self.__class__.instances = {} |
|
202 | self.__class__.instances = {} | |
203 | self.__class__.instances[name] = self |
|
203 | self.__class__.instances[name] = self | |
204 |
|
204 | |||
205 | @classmethod |
|
205 | @classmethod | |
206 | def _ipython_key_completions_(cls): |
|
206 | def _ipython_key_completions_(cls): | |
207 | return cls.instances.keys() |
|
207 | return cls.instances.keys() | |
208 |
|
208 | |||
209 | @classmethod |
|
209 | @classmethod | |
210 | def get_instance(cls, name): |
|
210 | def get_instance(cls, name): | |
211 | return cls.instances[name] |
|
211 | return cls.instances[name] | |
212 |
|
212 | |||
213 |
|
213 | |||
214 | class KeyCompletable: |
|
214 | class KeyCompletable: | |
215 | def __init__(self, things=()): |
|
215 | def __init__(self, things=()): | |
216 | self.things = things |
|
216 | self.things = things | |
217 |
|
217 | |||
218 | def _ipython_key_completions_(self): |
|
218 | def _ipython_key_completions_(self): | |
219 | return list(self.things) |
|
219 | return list(self.things) | |
220 |
|
220 | |||
221 |
|
221 | |||
|
222 | @pytest.mark.xfail( | |||
|
223 | sys.version_info >= (3, 11), | |||
|
224 | reason="parso does not support 3.11 yet", | |||
|
225 | raises=NotImplementedError, | |||
|
226 | ) | |||
222 | class TestCompleter(unittest.TestCase): |
|
227 | class TestCompleter(unittest.TestCase): | |
223 | def setUp(self): |
|
228 | def setUp(self): | |
224 | """ |
|
229 | """ | |
225 | We want to silence all PendingDeprecationWarning when testing the completer |
|
230 | We want to silence all PendingDeprecationWarning when testing the completer | |
226 | """ |
|
231 | """ | |
227 | self._assertwarns = self.assertWarns(PendingDeprecationWarning) |
|
232 | self._assertwarns = self.assertWarns(PendingDeprecationWarning) | |
228 | self._assertwarns.__enter__() |
|
233 | self._assertwarns.__enter__() | |
229 |
|
234 | |||
230 | def tearDown(self): |
|
235 | def tearDown(self): | |
231 | try: |
|
236 | try: | |
232 | self._assertwarns.__exit__(None, None, None) |
|
237 | self._assertwarns.__exit__(None, None, None) | |
233 | except AssertionError: |
|
238 | except AssertionError: | |
234 | pass |
|
239 | pass | |
235 |
|
240 | |||
236 | def test_custom_completion_error(self): |
|
241 | def test_custom_completion_error(self): | |
237 | """Test that errors from custom attribute completers are silenced.""" |
|
242 | """Test that errors from custom attribute completers are silenced.""" | |
238 | ip = get_ipython() |
|
243 | ip = get_ipython() | |
239 |
|
244 | |||
240 | class A: |
|
245 | class A: | |
241 | pass |
|
246 | pass | |
242 |
|
247 | |||
243 | ip.user_ns["x"] = A() |
|
248 | ip.user_ns["x"] = A() | |
244 |
|
249 | |||
245 | @complete_object.register(A) |
|
250 | @complete_object.register(A) | |
246 | def complete_A(a, existing_completions): |
|
251 | def complete_A(a, existing_completions): | |
247 | raise TypeError("this should be silenced") |
|
252 | raise TypeError("this should be silenced") | |
248 |
|
253 | |||
249 | ip.complete("x.") |
|
254 | ip.complete("x.") | |
250 |
|
255 | |||
251 | def test_custom_completion_ordering(self): |
|
256 | def test_custom_completion_ordering(self): | |
252 | """Test that errors from custom attribute completers are silenced.""" |
|
257 | """Test that errors from custom attribute completers are silenced.""" | |
253 | ip = get_ipython() |
|
258 | ip = get_ipython() | |
254 |
|
259 | |||
255 | _, matches = ip.complete('in') |
|
260 | _, matches = ip.complete('in') | |
256 | assert matches.index('input') < matches.index('int') |
|
261 | assert matches.index('input') < matches.index('int') | |
257 |
|
262 | |||
258 | def complete_example(a): |
|
263 | def complete_example(a): | |
259 | return ['example2', 'example1'] |
|
264 | return ['example2', 'example1'] | |
260 |
|
265 | |||
261 | ip.Completer.custom_completers.add_re('ex*', complete_example) |
|
266 | ip.Completer.custom_completers.add_re('ex*', complete_example) | |
262 | _, matches = ip.complete('ex') |
|
267 | _, matches = ip.complete('ex') | |
263 | assert matches.index('example2') < matches.index('example1') |
|
268 | assert matches.index('example2') < matches.index('example1') | |
264 |
|
269 | |||
265 | def test_unicode_completions(self): |
|
270 | def test_unicode_completions(self): | |
266 | ip = get_ipython() |
|
271 | ip = get_ipython() | |
267 | # Some strings that trigger different types of completion. Check them both |
|
272 | # Some strings that trigger different types of completion. Check them both | |
268 | # in str and unicode forms |
|
273 | # in str and unicode forms | |
269 | s = ["ru", "%ru", "cd /", "floa", "float(x)/"] |
|
274 | s = ["ru", "%ru", "cd /", "floa", "float(x)/"] | |
270 | for t in s + list(map(str, s)): |
|
275 | for t in s + list(map(str, s)): | |
271 | # We don't need to check exact completion values (they may change |
|
276 | # We don't need to check exact completion values (they may change | |
272 | # depending on the state of the namespace, but at least no exceptions |
|
277 | # depending on the state of the namespace, but at least no exceptions | |
273 | # should be thrown and the return value should be a pair of text, list |
|
278 | # should be thrown and the return value should be a pair of text, list | |
274 | # values. |
|
279 | # values. | |
275 | text, matches = ip.complete(t) |
|
280 | text, matches = ip.complete(t) | |
276 | self.assertIsInstance(text, str) |
|
281 | self.assertIsInstance(text, str) | |
277 | self.assertIsInstance(matches, list) |
|
282 | self.assertIsInstance(matches, list) | |
278 |
|
283 | |||
279 | def test_latex_completions(self): |
|
284 | def test_latex_completions(self): | |
280 | from IPython.core.latex_symbols import latex_symbols |
|
285 | from IPython.core.latex_symbols import latex_symbols | |
281 | import random |
|
286 | import random | |
282 |
|
287 | |||
283 | ip = get_ipython() |
|
288 | ip = get_ipython() | |
284 | # Test some random unicode symbols |
|
289 | # Test some random unicode symbols | |
285 |
keys = random.sample(latex_symbols |
|
290 | keys = random.sample(sorted(latex_symbols), 10) | |
286 | for k in keys: |
|
291 | for k in keys: | |
287 | text, matches = ip.complete(k) |
|
292 | text, matches = ip.complete(k) | |
288 | self.assertEqual(text, k) |
|
293 | self.assertEqual(text, k) | |
289 | self.assertEqual(matches, [latex_symbols[k]]) |
|
294 | self.assertEqual(matches, [latex_symbols[k]]) | |
290 | # Test a more complex line |
|
295 | # Test a more complex line | |
291 | text, matches = ip.complete("print(\\alpha") |
|
296 | text, matches = ip.complete("print(\\alpha") | |
292 | self.assertEqual(text, "\\alpha") |
|
297 | self.assertEqual(text, "\\alpha") | |
293 | self.assertEqual(matches[0], latex_symbols["\\alpha"]) |
|
298 | self.assertEqual(matches[0], latex_symbols["\\alpha"]) | |
294 | # Test multiple matching latex symbols |
|
299 | # Test multiple matching latex symbols | |
295 | text, matches = ip.complete("\\al") |
|
300 | text, matches = ip.complete("\\al") | |
296 | self.assertIn("\\alpha", matches) |
|
301 | self.assertIn("\\alpha", matches) | |
297 | self.assertIn("\\aleph", matches) |
|
302 | self.assertIn("\\aleph", matches) | |
298 |
|
303 | |||
299 | def test_latex_no_results(self): |
|
304 | def test_latex_no_results(self): | |
300 | """ |
|
305 | """ | |
301 | forward latex should really return nothing in either field if nothing is found. |
|
306 | forward latex should really return nothing in either field if nothing is found. | |
302 | """ |
|
307 | """ | |
303 | ip = get_ipython() |
|
308 | ip = get_ipython() | |
304 | text, matches = ip.Completer.latex_matches("\\really_i_should_match_nothing") |
|
309 | text, matches = ip.Completer.latex_matches("\\really_i_should_match_nothing") | |
305 | self.assertEqual(text, "") |
|
310 | self.assertEqual(text, "") | |
306 | self.assertEqual(matches, ()) |
|
311 | self.assertEqual(matches, ()) | |
307 |
|
312 | |||
308 | def test_back_latex_completion(self): |
|
313 | def test_back_latex_completion(self): | |
309 | ip = get_ipython() |
|
314 | ip = get_ipython() | |
310 |
|
315 | |||
311 | # do not return more than 1 matches for \beta, only the latex one. |
|
316 | # do not return more than 1 matches for \beta, only the latex one. | |
312 | name, matches = ip.complete("\\β") |
|
317 | name, matches = ip.complete("\\β") | |
313 | self.assertEqual(matches, ["\\beta"]) |
|
318 | self.assertEqual(matches, ["\\beta"]) | |
314 |
|
319 | |||
315 | def test_back_unicode_completion(self): |
|
320 | def test_back_unicode_completion(self): | |
316 | ip = get_ipython() |
|
321 | ip = get_ipython() | |
317 |
|
322 | |||
318 | name, matches = ip.complete("\\Ⅴ") |
|
323 | name, matches = ip.complete("\\Ⅴ") | |
319 | self.assertEqual(matches, ("\\ROMAN NUMERAL FIVE",)) |
|
324 | self.assertEqual(matches, ("\\ROMAN NUMERAL FIVE",)) | |
320 |
|
325 | |||
321 | def test_forward_unicode_completion(self): |
|
326 | def test_forward_unicode_completion(self): | |
322 | ip = get_ipython() |
|
327 | ip = get_ipython() | |
323 |
|
328 | |||
324 | name, matches = ip.complete("\\ROMAN NUMERAL FIVE") |
|
329 | name, matches = ip.complete("\\ROMAN NUMERAL FIVE") | |
325 | self.assertEqual(matches, ["Ⅴ"]) # This is not a V |
|
330 | self.assertEqual(matches, ["Ⅴ"]) # This is not a V | |
326 | self.assertEqual(matches, ["\u2164"]) # same as above but explicit. |
|
331 | self.assertEqual(matches, ["\u2164"]) # same as above but explicit. | |
327 |
|
332 | |||
328 | def test_delim_setting(self): |
|
333 | def test_delim_setting(self): | |
329 | sp = completer.CompletionSplitter() |
|
334 | sp = completer.CompletionSplitter() | |
330 | sp.delims = " " |
|
335 | sp.delims = " " | |
331 | self.assertEqual(sp.delims, " ") |
|
336 | self.assertEqual(sp.delims, " ") | |
332 | self.assertEqual(sp._delim_expr, r"[\ ]") |
|
337 | self.assertEqual(sp._delim_expr, r"[\ ]") | |
333 |
|
338 | |||
334 | def test_spaces(self): |
|
339 | def test_spaces(self): | |
335 | """Test with only spaces as split chars.""" |
|
340 | """Test with only spaces as split chars.""" | |
336 | sp = completer.CompletionSplitter() |
|
341 | sp = completer.CompletionSplitter() | |
337 | sp.delims = " " |
|
342 | sp.delims = " " | |
338 | t = [("foo", "", "foo"), ("run foo", "", "foo"), ("run foo", "bar", "foo")] |
|
343 | t = [("foo", "", "foo"), ("run foo", "", "foo"), ("run foo", "bar", "foo")] | |
339 | check_line_split(sp, t) |
|
344 | check_line_split(sp, t) | |
340 |
|
345 | |||
341 | def test_has_open_quotes1(self): |
|
346 | def test_has_open_quotes1(self): | |
342 | for s in ["'", "'''", "'hi' '"]: |
|
347 | for s in ["'", "'''", "'hi' '"]: | |
343 | self.assertEqual(completer.has_open_quotes(s), "'") |
|
348 | self.assertEqual(completer.has_open_quotes(s), "'") | |
344 |
|
349 | |||
345 | def test_has_open_quotes2(self): |
|
350 | def test_has_open_quotes2(self): | |
346 | for s in ['"', '"""', '"hi" "']: |
|
351 | for s in ['"', '"""', '"hi" "']: | |
347 | self.assertEqual(completer.has_open_quotes(s), '"') |
|
352 | self.assertEqual(completer.has_open_quotes(s), '"') | |
348 |
|
353 | |||
349 | def test_has_open_quotes3(self): |
|
354 | def test_has_open_quotes3(self): | |
350 | for s in ["''", "''' '''", "'hi' 'ipython'"]: |
|
355 | for s in ["''", "''' '''", "'hi' 'ipython'"]: | |
351 | self.assertFalse(completer.has_open_quotes(s)) |
|
356 | self.assertFalse(completer.has_open_quotes(s)) | |
352 |
|
357 | |||
353 | def test_has_open_quotes4(self): |
|
358 | def test_has_open_quotes4(self): | |
354 | for s in ['""', '""" """', '"hi" "ipython"']: |
|
359 | for s in ['""', '""" """', '"hi" "ipython"']: | |
355 | self.assertFalse(completer.has_open_quotes(s)) |
|
360 | self.assertFalse(completer.has_open_quotes(s)) | |
356 |
|
361 | |||
357 | @pytest.mark.xfail( |
|
362 | @pytest.mark.xfail( | |
358 | sys.platform == "win32", reason="abspath completions fail on Windows" |
|
363 | sys.platform == "win32", reason="abspath completions fail on Windows" | |
359 | ) |
|
364 | ) | |
360 | def test_abspath_file_completions(self): |
|
365 | def test_abspath_file_completions(self): | |
361 | ip = get_ipython() |
|
366 | ip = get_ipython() | |
362 | with TemporaryDirectory() as tmpdir: |
|
367 | with TemporaryDirectory() as tmpdir: | |
363 | prefix = os.path.join(tmpdir, "foo") |
|
368 | prefix = os.path.join(tmpdir, "foo") | |
364 | suffixes = ["1", "2"] |
|
369 | suffixes = ["1", "2"] | |
365 | names = [prefix + s for s in suffixes] |
|
370 | names = [prefix + s for s in suffixes] | |
366 | for n in names: |
|
371 | for n in names: | |
367 | open(n, "w").close() |
|
372 | open(n, "w").close() | |
368 |
|
373 | |||
369 | # Check simple completion |
|
374 | # Check simple completion | |
370 | c = ip.complete(prefix)[1] |
|
375 | c = ip.complete(prefix)[1] | |
371 | self.assertEqual(c, names) |
|
376 | self.assertEqual(c, names) | |
372 |
|
377 | |||
373 | # Now check with a function call |
|
378 | # Now check with a function call | |
374 | cmd = 'a = f("%s' % prefix |
|
379 | cmd = 'a = f("%s' % prefix | |
375 | c = ip.complete(prefix, cmd)[1] |
|
380 | c = ip.complete(prefix, cmd)[1] | |
376 | comp = [prefix + s for s in suffixes] |
|
381 | comp = [prefix + s for s in suffixes] | |
377 | self.assertEqual(c, comp) |
|
382 | self.assertEqual(c, comp) | |
378 |
|
383 | |||
379 | def test_local_file_completions(self): |
|
384 | def test_local_file_completions(self): | |
380 | ip = get_ipython() |
|
385 | ip = get_ipython() | |
381 | with TemporaryWorkingDirectory(): |
|
386 | with TemporaryWorkingDirectory(): | |
382 | prefix = "./foo" |
|
387 | prefix = "./foo" | |
383 | suffixes = ["1", "2"] |
|
388 | suffixes = ["1", "2"] | |
384 | names = [prefix + s for s in suffixes] |
|
389 | names = [prefix + s for s in suffixes] | |
385 | for n in names: |
|
390 | for n in names: | |
386 | open(n, "w").close() |
|
391 | open(n, "w").close() | |
387 |
|
392 | |||
388 | # Check simple completion |
|
393 | # Check simple completion | |
389 | c = ip.complete(prefix)[1] |
|
394 | c = ip.complete(prefix)[1] | |
390 | self.assertEqual(c, names) |
|
395 | self.assertEqual(c, names) | |
391 |
|
396 | |||
392 | # Now check with a function call |
|
397 | # Now check with a function call | |
393 | cmd = 'a = f("%s' % prefix |
|
398 | cmd = 'a = f("%s' % prefix | |
394 | c = ip.complete(prefix, cmd)[1] |
|
399 | c = ip.complete(prefix, cmd)[1] | |
395 | comp = {prefix + s for s in suffixes} |
|
400 | comp = {prefix + s for s in suffixes} | |
396 | self.assertTrue(comp.issubset(set(c))) |
|
401 | self.assertTrue(comp.issubset(set(c))) | |
397 |
|
402 | |||
398 | def test_quoted_file_completions(self): |
|
403 | def test_quoted_file_completions(self): | |
399 | ip = get_ipython() |
|
404 | ip = get_ipython() | |
400 | with TemporaryWorkingDirectory(): |
|
405 | with TemporaryWorkingDirectory(): | |
401 | name = "foo'bar" |
|
406 | name = "foo'bar" | |
402 | open(name, "w").close() |
|
407 | open(name, "w").close() | |
403 |
|
408 | |||
404 | # Don't escape Windows |
|
409 | # Don't escape Windows | |
405 | escaped = name if sys.platform == "win32" else "foo\\'bar" |
|
410 | escaped = name if sys.platform == "win32" else "foo\\'bar" | |
406 |
|
411 | |||
407 | # Single quote matches embedded single quote |
|
412 | # Single quote matches embedded single quote | |
408 | text = "open('foo" |
|
413 | text = "open('foo" | |
409 | c = ip.Completer._complete( |
|
414 | c = ip.Completer._complete( | |
410 | cursor_line=0, cursor_pos=len(text), full_text=text |
|
415 | cursor_line=0, cursor_pos=len(text), full_text=text | |
411 | )[1] |
|
416 | )[1] | |
412 | self.assertEqual(c, [escaped]) |
|
417 | self.assertEqual(c, [escaped]) | |
413 |
|
418 | |||
414 | # Double quote requires no escape |
|
419 | # Double quote requires no escape | |
415 | text = 'open("foo' |
|
420 | text = 'open("foo' | |
416 | c = ip.Completer._complete( |
|
421 | c = ip.Completer._complete( | |
417 | cursor_line=0, cursor_pos=len(text), full_text=text |
|
422 | cursor_line=0, cursor_pos=len(text), full_text=text | |
418 | )[1] |
|
423 | )[1] | |
419 | self.assertEqual(c, [name]) |
|
424 | self.assertEqual(c, [name]) | |
420 |
|
425 | |||
421 | # No quote requires an escape |
|
426 | # No quote requires an escape | |
422 | text = "%ls foo" |
|
427 | text = "%ls foo" | |
423 | c = ip.Completer._complete( |
|
428 | c = ip.Completer._complete( | |
424 | cursor_line=0, cursor_pos=len(text), full_text=text |
|
429 | cursor_line=0, cursor_pos=len(text), full_text=text | |
425 | )[1] |
|
430 | )[1] | |
426 | self.assertEqual(c, [escaped]) |
|
431 | self.assertEqual(c, [escaped]) | |
427 |
|
432 | |||
428 | def test_all_completions_dups(self): |
|
433 | def test_all_completions_dups(self): | |
429 | """ |
|
434 | """ | |
430 | Make sure the output of `IPCompleter.all_completions` does not have |
|
435 | Make sure the output of `IPCompleter.all_completions` does not have | |
431 | duplicated prefixes. |
|
436 | duplicated prefixes. | |
432 | """ |
|
437 | """ | |
433 | ip = get_ipython() |
|
438 | ip = get_ipython() | |
434 | c = ip.Completer |
|
439 | c = ip.Completer | |
435 | ip.ex("class TestClass():\n\ta=1\n\ta1=2") |
|
440 | ip.ex("class TestClass():\n\ta=1\n\ta1=2") | |
436 | for jedi_status in [True, False]: |
|
441 | for jedi_status in [True, False]: | |
437 | with provisionalcompleter(): |
|
442 | with provisionalcompleter(): | |
438 | ip.Completer.use_jedi = jedi_status |
|
443 | ip.Completer.use_jedi = jedi_status | |
439 | matches = c.all_completions("TestCl") |
|
444 | matches = c.all_completions("TestCl") | |
440 | assert matches == ['TestClass'], jedi_status |
|
445 | assert matches == ['TestClass'], jedi_status | |
441 | matches = c.all_completions("TestClass.") |
|
446 | matches = c.all_completions("TestClass.") | |
442 | if jedi_status and jedi_issue: |
|
447 | if jedi_status and jedi_issue: | |
443 | continue |
|
448 | continue | |
444 | assert len(matches) > 2, jedi_status |
|
449 | assert len(matches) > 2, jedi_status | |
445 | matches = c.all_completions("TestClass.a") |
|
450 | matches = c.all_completions("TestClass.a") | |
446 | assert matches == ['TestClass.a', 'TestClass.a1'], jedi_status |
|
451 | assert matches == ['TestClass.a', 'TestClass.a1'], jedi_status | |
447 |
|
452 | |||
448 | def test_jedi(self): |
|
453 | def test_jedi(self): | |
449 | """ |
|
454 | """ | |
450 | A couple of issue we had with Jedi |
|
455 | A couple of issue we had with Jedi | |
451 | """ |
|
456 | """ | |
452 | ip = get_ipython() |
|
457 | ip = get_ipython() | |
453 |
|
458 | |||
454 | def _test_complete(reason, s, comp, start=None, end=None): |
|
459 | def _test_complete(reason, s, comp, start=None, end=None): | |
455 | l = len(s) |
|
460 | l = len(s) | |
456 | start = start if start is not None else l |
|
461 | start = start if start is not None else l | |
457 | end = end if end is not None else l |
|
462 | end = end if end is not None else l | |
458 | with provisionalcompleter(): |
|
463 | with provisionalcompleter(): | |
459 | ip.Completer.use_jedi = True |
|
464 | ip.Completer.use_jedi = True | |
460 | completions = set(ip.Completer.completions(s, l)) |
|
465 | completions = set(ip.Completer.completions(s, l)) | |
461 | ip.Completer.use_jedi = False |
|
466 | ip.Completer.use_jedi = False | |
462 | assert Completion(start, end, comp) in completions, reason |
|
467 | assert Completion(start, end, comp) in completions, reason | |
463 |
|
468 | |||
464 | def _test_not_complete(reason, s, comp): |
|
469 | def _test_not_complete(reason, s, comp): | |
465 | l = len(s) |
|
470 | l = len(s) | |
466 | with provisionalcompleter(): |
|
471 | with provisionalcompleter(): | |
467 | ip.Completer.use_jedi = True |
|
472 | ip.Completer.use_jedi = True | |
468 | completions = set(ip.Completer.completions(s, l)) |
|
473 | completions = set(ip.Completer.completions(s, l)) | |
469 | ip.Completer.use_jedi = False |
|
474 | ip.Completer.use_jedi = False | |
470 | assert Completion(l, l, comp) not in completions, reason |
|
475 | assert Completion(l, l, comp) not in completions, reason | |
471 |
|
476 | |||
472 | import jedi |
|
477 | import jedi | |
473 |
|
478 | |||
474 | jedi_version = tuple(int(i) for i in jedi.__version__.split(".")[:3]) |
|
479 | jedi_version = tuple(int(i) for i in jedi.__version__.split(".")[:3]) | |
475 | if jedi_version > (0, 10): |
|
480 | if jedi_version > (0, 10): | |
476 | _test_complete("jedi >0.9 should complete and not crash", "a=1;a.", "real") |
|
481 | _test_complete("jedi >0.9 should complete and not crash", "a=1;a.", "real") | |
477 | _test_complete("can infer first argument", 'a=(1,"foo");a[0].', "real") |
|
482 | _test_complete("can infer first argument", 'a=(1,"foo");a[0].', "real") | |
478 | _test_complete("can infer second argument", 'a=(1,"foo");a[1].', "capitalize") |
|
483 | _test_complete("can infer second argument", 'a=(1,"foo");a[1].', "capitalize") | |
479 | _test_complete("cover duplicate completions", "im", "import", 0, 2) |
|
484 | _test_complete("cover duplicate completions", "im", "import", 0, 2) | |
480 |
|
485 | |||
481 | _test_not_complete("does not mix types", 'a=(1,"foo");a[0].', "capitalize") |
|
486 | _test_not_complete("does not mix types", 'a=(1,"foo");a[0].', "capitalize") | |
482 |
|
487 | |||
483 | def test_completion_have_signature(self): |
|
488 | def test_completion_have_signature(self): | |
484 | """ |
|
489 | """ | |
485 | Lets make sure jedi is capable of pulling out the signature of the function we are completing. |
|
490 | Lets make sure jedi is capable of pulling out the signature of the function we are completing. | |
486 | """ |
|
491 | """ | |
487 | ip = get_ipython() |
|
492 | ip = get_ipython() | |
488 | with provisionalcompleter(): |
|
493 | with provisionalcompleter(): | |
489 | ip.Completer.use_jedi = True |
|
494 | ip.Completer.use_jedi = True | |
490 | completions = ip.Completer.completions("ope", 3) |
|
495 | completions = ip.Completer.completions("ope", 3) | |
491 | c = next(completions) # should be `open` |
|
496 | c = next(completions) # should be `open` | |
492 | ip.Completer.use_jedi = False |
|
497 | ip.Completer.use_jedi = False | |
493 | assert "file" in c.signature, "Signature of function was not found by completer" |
|
498 | assert "file" in c.signature, "Signature of function was not found by completer" | |
494 | assert ( |
|
499 | assert ( | |
495 | "encoding" in c.signature |
|
500 | "encoding" in c.signature | |
496 | ), "Signature of function was not found by completer" |
|
501 | ), "Signature of function was not found by completer" | |
497 |
|
502 | |||
498 | @pytest.mark.xfail(jedi_issue, reason="Known failure on jedi<=0.18.0") |
|
503 | @pytest.mark.xfail(jedi_issue, reason="Known failure on jedi<=0.18.0") | |
499 | def test_deduplicate_completions(self): |
|
504 | def test_deduplicate_completions(self): | |
500 | """ |
|
505 | """ | |
501 | Test that completions are correctly deduplicated (even if ranges are not the same) |
|
506 | Test that completions are correctly deduplicated (even if ranges are not the same) | |
502 | """ |
|
507 | """ | |
503 | ip = get_ipython() |
|
508 | ip = get_ipython() | |
504 | ip.ex( |
|
509 | ip.ex( | |
505 | textwrap.dedent( |
|
510 | textwrap.dedent( | |
506 | """ |
|
511 | """ | |
507 | class Z: |
|
512 | class Z: | |
508 | zoo = 1 |
|
513 | zoo = 1 | |
509 | """ |
|
514 | """ | |
510 | ) |
|
515 | ) | |
511 | ) |
|
516 | ) | |
512 | with provisionalcompleter(): |
|
517 | with provisionalcompleter(): | |
513 | ip.Completer.use_jedi = True |
|
518 | ip.Completer.use_jedi = True | |
514 | l = list( |
|
519 | l = list( | |
515 | _deduplicate_completions("Z.z", ip.Completer.completions("Z.z", 3)) |
|
520 | _deduplicate_completions("Z.z", ip.Completer.completions("Z.z", 3)) | |
516 | ) |
|
521 | ) | |
517 | ip.Completer.use_jedi = False |
|
522 | ip.Completer.use_jedi = False | |
518 |
|
523 | |||
519 | assert len(l) == 1, "Completions (Z.z<tab>) correctly deduplicate: %s " % l |
|
524 | assert len(l) == 1, "Completions (Z.z<tab>) correctly deduplicate: %s " % l | |
520 | assert l[0].text == "zoo" # and not `it.accumulate` |
|
525 | assert l[0].text == "zoo" # and not `it.accumulate` | |
521 |
|
526 | |||
522 | def test_greedy_completions(self): |
|
527 | def test_greedy_completions(self): | |
523 | """ |
|
528 | """ | |
524 | Test the capability of the Greedy completer. |
|
529 | Test the capability of the Greedy completer. | |
525 |
|
530 | |||
526 | Most of the test here does not really show off the greedy completer, for proof |
|
531 | Most of the test here does not really show off the greedy completer, for proof | |
527 | each of the text below now pass with Jedi. The greedy completer is capable of more. |
|
532 | each of the text below now pass with Jedi. The greedy completer is capable of more. | |
528 |
|
533 | |||
529 | See the :any:`test_dict_key_completion_contexts` |
|
534 | See the :any:`test_dict_key_completion_contexts` | |
530 |
|
535 | |||
531 | """ |
|
536 | """ | |
532 | ip = get_ipython() |
|
537 | ip = get_ipython() | |
533 | ip.ex("a=list(range(5))") |
|
538 | ip.ex("a=list(range(5))") | |
534 | _, c = ip.complete(".", line="a[0].") |
|
539 | _, c = ip.complete(".", line="a[0].") | |
535 | self.assertFalse(".real" in c, "Shouldn't have completed on a[0]: %s" % c) |
|
540 | self.assertFalse(".real" in c, "Shouldn't have completed on a[0]: %s" % c) | |
536 |
|
541 | |||
537 | def _(line, cursor_pos, expect, message, completion): |
|
542 | def _(line, cursor_pos, expect, message, completion): | |
538 | with greedy_completion(), provisionalcompleter(): |
|
543 | with greedy_completion(), provisionalcompleter(): | |
539 | ip.Completer.use_jedi = False |
|
544 | ip.Completer.use_jedi = False | |
540 | _, c = ip.complete(".", line=line, cursor_pos=cursor_pos) |
|
545 | _, c = ip.complete(".", line=line, cursor_pos=cursor_pos) | |
541 | self.assertIn(expect, c, message % c) |
|
546 | self.assertIn(expect, c, message % c) | |
542 |
|
547 | |||
543 | ip.Completer.use_jedi = True |
|
548 | ip.Completer.use_jedi = True | |
544 | with provisionalcompleter(): |
|
549 | with provisionalcompleter(): | |
545 | completions = ip.Completer.completions(line, cursor_pos) |
|
550 | completions = ip.Completer.completions(line, cursor_pos) | |
546 | self.assertIn(completion, completions) |
|
551 | self.assertIn(completion, completions) | |
547 |
|
552 | |||
548 | with provisionalcompleter(): |
|
553 | with provisionalcompleter(): | |
549 | _( |
|
554 | _( | |
550 | "a[0].", |
|
555 | "a[0].", | |
551 | 5, |
|
556 | 5, | |
552 | "a[0].real", |
|
557 | "a[0].real", | |
553 | "Should have completed on a[0].: %s", |
|
558 | "Should have completed on a[0].: %s", | |
554 | Completion(5, 5, "real"), |
|
559 | Completion(5, 5, "real"), | |
555 | ) |
|
560 | ) | |
556 | _( |
|
561 | _( | |
557 | "a[0].r", |
|
562 | "a[0].r", | |
558 | 6, |
|
563 | 6, | |
559 | "a[0].real", |
|
564 | "a[0].real", | |
560 | "Should have completed on a[0].r: %s", |
|
565 | "Should have completed on a[0].r: %s", | |
561 | Completion(5, 6, "real"), |
|
566 | Completion(5, 6, "real"), | |
562 | ) |
|
567 | ) | |
563 |
|
568 | |||
564 | _( |
|
569 | _( | |
565 | "a[0].from_", |
|
570 | "a[0].from_", | |
566 | 10, |
|
571 | 10, | |
567 | "a[0].from_bytes", |
|
572 | "a[0].from_bytes", | |
568 | "Should have completed on a[0].from_: %s", |
|
573 | "Should have completed on a[0].from_: %s", | |
569 | Completion(5, 10, "from_bytes"), |
|
574 | Completion(5, 10, "from_bytes"), | |
570 | ) |
|
575 | ) | |
571 |
|
576 | |||
572 | def test_omit__names(self): |
|
577 | def test_omit__names(self): | |
573 | # also happens to test IPCompleter as a configurable |
|
578 | # also happens to test IPCompleter as a configurable | |
574 | ip = get_ipython() |
|
579 | ip = get_ipython() | |
575 | ip._hidden_attr = 1 |
|
580 | ip._hidden_attr = 1 | |
576 | ip._x = {} |
|
581 | ip._x = {} | |
577 | c = ip.Completer |
|
582 | c = ip.Completer | |
578 | ip.ex("ip=get_ipython()") |
|
583 | ip.ex("ip=get_ipython()") | |
579 | cfg = Config() |
|
584 | cfg = Config() | |
580 | cfg.IPCompleter.omit__names = 0 |
|
585 | cfg.IPCompleter.omit__names = 0 | |
581 | c.update_config(cfg) |
|
586 | c.update_config(cfg) | |
582 | with provisionalcompleter(): |
|
587 | with provisionalcompleter(): | |
583 | c.use_jedi = False |
|
588 | c.use_jedi = False | |
584 | s, matches = c.complete("ip.") |
|
589 | s, matches = c.complete("ip.") | |
585 | self.assertIn("ip.__str__", matches) |
|
590 | self.assertIn("ip.__str__", matches) | |
586 | self.assertIn("ip._hidden_attr", matches) |
|
591 | self.assertIn("ip._hidden_attr", matches) | |
587 |
|
592 | |||
588 | # c.use_jedi = True |
|
593 | # c.use_jedi = True | |
589 | # completions = set(c.completions('ip.', 3)) |
|
594 | # completions = set(c.completions('ip.', 3)) | |
590 | # self.assertIn(Completion(3, 3, '__str__'), completions) |
|
595 | # self.assertIn(Completion(3, 3, '__str__'), completions) | |
591 | # self.assertIn(Completion(3,3, "_hidden_attr"), completions) |
|
596 | # self.assertIn(Completion(3,3, "_hidden_attr"), completions) | |
592 |
|
597 | |||
593 | cfg = Config() |
|
598 | cfg = Config() | |
594 | cfg.IPCompleter.omit__names = 1 |
|
599 | cfg.IPCompleter.omit__names = 1 | |
595 | c.update_config(cfg) |
|
600 | c.update_config(cfg) | |
596 | with provisionalcompleter(): |
|
601 | with provisionalcompleter(): | |
597 | c.use_jedi = False |
|
602 | c.use_jedi = False | |
598 | s, matches = c.complete("ip.") |
|
603 | s, matches = c.complete("ip.") | |
599 | self.assertNotIn("ip.__str__", matches) |
|
604 | self.assertNotIn("ip.__str__", matches) | |
600 | # self.assertIn('ip._hidden_attr', matches) |
|
605 | # self.assertIn('ip._hidden_attr', matches) | |
601 |
|
606 | |||
602 | # c.use_jedi = True |
|
607 | # c.use_jedi = True | |
603 | # completions = set(c.completions('ip.', 3)) |
|
608 | # completions = set(c.completions('ip.', 3)) | |
604 | # self.assertNotIn(Completion(3,3,'__str__'), completions) |
|
609 | # self.assertNotIn(Completion(3,3,'__str__'), completions) | |
605 | # self.assertIn(Completion(3,3, "_hidden_attr"), completions) |
|
610 | # self.assertIn(Completion(3,3, "_hidden_attr"), completions) | |
606 |
|
611 | |||
607 | cfg = Config() |
|
612 | cfg = Config() | |
608 | cfg.IPCompleter.omit__names = 2 |
|
613 | cfg.IPCompleter.omit__names = 2 | |
609 | c.update_config(cfg) |
|
614 | c.update_config(cfg) | |
610 | with provisionalcompleter(): |
|
615 | with provisionalcompleter(): | |
611 | c.use_jedi = False |
|
616 | c.use_jedi = False | |
612 | s, matches = c.complete("ip.") |
|
617 | s, matches = c.complete("ip.") | |
613 | self.assertNotIn("ip.__str__", matches) |
|
618 | self.assertNotIn("ip.__str__", matches) | |
614 | self.assertNotIn("ip._hidden_attr", matches) |
|
619 | self.assertNotIn("ip._hidden_attr", matches) | |
615 |
|
620 | |||
616 | # c.use_jedi = True |
|
621 | # c.use_jedi = True | |
617 | # completions = set(c.completions('ip.', 3)) |
|
622 | # completions = set(c.completions('ip.', 3)) | |
618 | # self.assertNotIn(Completion(3,3,'__str__'), completions) |
|
623 | # self.assertNotIn(Completion(3,3,'__str__'), completions) | |
619 | # self.assertNotIn(Completion(3,3, "_hidden_attr"), completions) |
|
624 | # self.assertNotIn(Completion(3,3, "_hidden_attr"), completions) | |
620 |
|
625 | |||
621 | with provisionalcompleter(): |
|
626 | with provisionalcompleter(): | |
622 | c.use_jedi = False |
|
627 | c.use_jedi = False | |
623 | s, matches = c.complete("ip._x.") |
|
628 | s, matches = c.complete("ip._x.") | |
624 | self.assertIn("ip._x.keys", matches) |
|
629 | self.assertIn("ip._x.keys", matches) | |
625 |
|
630 | |||
626 | # c.use_jedi = True |
|
631 | # c.use_jedi = True | |
627 | # completions = set(c.completions('ip._x.', 6)) |
|
632 | # completions = set(c.completions('ip._x.', 6)) | |
628 | # self.assertIn(Completion(6,6, "keys"), completions) |
|
633 | # self.assertIn(Completion(6,6, "keys"), completions) | |
629 |
|
634 | |||
630 | del ip._hidden_attr |
|
635 | del ip._hidden_attr | |
631 | del ip._x |
|
636 | del ip._x | |
632 |
|
637 | |||
633 | def test_limit_to__all__False_ok(self): |
|
638 | def test_limit_to__all__False_ok(self): | |
634 | """ |
|
639 | """ | |
635 | Limit to all is deprecated, once we remove it this test can go away. |
|
640 | Limit to all is deprecated, once we remove it this test can go away. | |
636 | """ |
|
641 | """ | |
637 | ip = get_ipython() |
|
642 | ip = get_ipython() | |
638 | c = ip.Completer |
|
643 | c = ip.Completer | |
639 | c.use_jedi = False |
|
644 | c.use_jedi = False | |
640 | ip.ex("class D: x=24") |
|
645 | ip.ex("class D: x=24") | |
641 | ip.ex("d=D()") |
|
646 | ip.ex("d=D()") | |
642 | cfg = Config() |
|
647 | cfg = Config() | |
643 | cfg.IPCompleter.limit_to__all__ = False |
|
648 | cfg.IPCompleter.limit_to__all__ = False | |
644 | c.update_config(cfg) |
|
649 | c.update_config(cfg) | |
645 | s, matches = c.complete("d.") |
|
650 | s, matches = c.complete("d.") | |
646 | self.assertIn("d.x", matches) |
|
651 | self.assertIn("d.x", matches) | |
647 |
|
652 | |||
648 | def test_get__all__entries_ok(self): |
|
653 | def test_get__all__entries_ok(self): | |
649 | class A: |
|
654 | class A: | |
650 | __all__ = ["x", 1] |
|
655 | __all__ = ["x", 1] | |
651 |
|
656 | |||
652 | words = completer.get__all__entries(A()) |
|
657 | words = completer.get__all__entries(A()) | |
653 | self.assertEqual(words, ["x"]) |
|
658 | self.assertEqual(words, ["x"]) | |
654 |
|
659 | |||
655 | def test_get__all__entries_no__all__ok(self): |
|
660 | def test_get__all__entries_no__all__ok(self): | |
656 | class A: |
|
661 | class A: | |
657 | pass |
|
662 | pass | |
658 |
|
663 | |||
659 | words = completer.get__all__entries(A()) |
|
664 | words = completer.get__all__entries(A()) | |
660 | self.assertEqual(words, []) |
|
665 | self.assertEqual(words, []) | |
661 |
|
666 | |||
662 | def test_func_kw_completions(self): |
|
667 | def test_func_kw_completions(self): | |
663 | ip = get_ipython() |
|
668 | ip = get_ipython() | |
664 | c = ip.Completer |
|
669 | c = ip.Completer | |
665 | c.use_jedi = False |
|
670 | c.use_jedi = False | |
666 | ip.ex("def myfunc(a=1,b=2): return a+b") |
|
671 | ip.ex("def myfunc(a=1,b=2): return a+b") | |
667 | s, matches = c.complete(None, "myfunc(1,b") |
|
672 | s, matches = c.complete(None, "myfunc(1,b") | |
668 | self.assertIn("b=", matches) |
|
673 | self.assertIn("b=", matches) | |
669 | # Simulate completing with cursor right after b (pos==10): |
|
674 | # Simulate completing with cursor right after b (pos==10): | |
670 | s, matches = c.complete(None, "myfunc(1,b)", 10) |
|
675 | s, matches = c.complete(None, "myfunc(1,b)", 10) | |
671 | self.assertIn("b=", matches) |
|
676 | self.assertIn("b=", matches) | |
672 | s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b') |
|
677 | s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b') | |
673 | self.assertIn("b=", matches) |
|
678 | self.assertIn("b=", matches) | |
674 | # builtin function |
|
679 | # builtin function | |
675 | s, matches = c.complete(None, "min(k, k") |
|
680 | s, matches = c.complete(None, "min(k, k") | |
676 | self.assertIn("key=", matches) |
|
681 | self.assertIn("key=", matches) | |
677 |
|
682 | |||
678 | def test_default_arguments_from_docstring(self): |
|
683 | def test_default_arguments_from_docstring(self): | |
679 | ip = get_ipython() |
|
684 | ip = get_ipython() | |
680 | c = ip.Completer |
|
685 | c = ip.Completer | |
681 | kwd = c._default_arguments_from_docstring("min(iterable[, key=func]) -> value") |
|
686 | kwd = c._default_arguments_from_docstring("min(iterable[, key=func]) -> value") | |
682 | self.assertEqual(kwd, ["key"]) |
|
687 | self.assertEqual(kwd, ["key"]) | |
683 | # with cython type etc |
|
688 | # with cython type etc | |
684 | kwd = c._default_arguments_from_docstring( |
|
689 | kwd = c._default_arguments_from_docstring( | |
685 | "Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n" |
|
690 | "Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n" | |
686 | ) |
|
691 | ) | |
687 | self.assertEqual(kwd, ["ncall", "resume", "nsplit"]) |
|
692 | self.assertEqual(kwd, ["ncall", "resume", "nsplit"]) | |
688 | # white spaces |
|
693 | # white spaces | |
689 | kwd = c._default_arguments_from_docstring( |
|
694 | kwd = c._default_arguments_from_docstring( | |
690 | "\n Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n" |
|
695 | "\n Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n" | |
691 | ) |
|
696 | ) | |
692 | self.assertEqual(kwd, ["ncall", "resume", "nsplit"]) |
|
697 | self.assertEqual(kwd, ["ncall", "resume", "nsplit"]) | |
693 |
|
698 | |||
694 | def test_line_magics(self): |
|
699 | def test_line_magics(self): | |
695 | ip = get_ipython() |
|
700 | ip = get_ipython() | |
696 | c = ip.Completer |
|
701 | c = ip.Completer | |
697 | s, matches = c.complete(None, "lsmag") |
|
702 | s, matches = c.complete(None, "lsmag") | |
698 | self.assertIn("%lsmagic", matches) |
|
703 | self.assertIn("%lsmagic", matches) | |
699 | s, matches = c.complete(None, "%lsmag") |
|
704 | s, matches = c.complete(None, "%lsmag") | |
700 | self.assertIn("%lsmagic", matches) |
|
705 | self.assertIn("%lsmagic", matches) | |
701 |
|
706 | |||
702 | def test_cell_magics(self): |
|
707 | def test_cell_magics(self): | |
703 | from IPython.core.magic import register_cell_magic |
|
708 | from IPython.core.magic import register_cell_magic | |
704 |
|
709 | |||
705 | @register_cell_magic |
|
710 | @register_cell_magic | |
706 | def _foo_cellm(line, cell): |
|
711 | def _foo_cellm(line, cell): | |
707 | pass |
|
712 | pass | |
708 |
|
713 | |||
709 | ip = get_ipython() |
|
714 | ip = get_ipython() | |
710 | c = ip.Completer |
|
715 | c = ip.Completer | |
711 |
|
716 | |||
712 | s, matches = c.complete(None, "_foo_ce") |
|
717 | s, matches = c.complete(None, "_foo_ce") | |
713 | self.assertIn("%%_foo_cellm", matches) |
|
718 | self.assertIn("%%_foo_cellm", matches) | |
714 | s, matches = c.complete(None, "%%_foo_ce") |
|
719 | s, matches = c.complete(None, "%%_foo_ce") | |
715 | self.assertIn("%%_foo_cellm", matches) |
|
720 | self.assertIn("%%_foo_cellm", matches) | |
716 |
|
721 | |||
717 | def test_line_cell_magics(self): |
|
722 | def test_line_cell_magics(self): | |
718 | from IPython.core.magic import register_line_cell_magic |
|
723 | from IPython.core.magic import register_line_cell_magic | |
719 |
|
724 | |||
720 | @register_line_cell_magic |
|
725 | @register_line_cell_magic | |
721 | def _bar_cellm(line, cell): |
|
726 | def _bar_cellm(line, cell): | |
722 | pass |
|
727 | pass | |
723 |
|
728 | |||
724 | ip = get_ipython() |
|
729 | ip = get_ipython() | |
725 | c = ip.Completer |
|
730 | c = ip.Completer | |
726 |
|
731 | |||
727 | # The policy here is trickier, see comments in completion code. The |
|
732 | # The policy here is trickier, see comments in completion code. The | |
728 | # returned values depend on whether the user passes %% or not explicitly, |
|
733 | # returned values depend on whether the user passes %% or not explicitly, | |
729 | # and this will show a difference if the same name is both a line and cell |
|
734 | # and this will show a difference if the same name is both a line and cell | |
730 | # magic. |
|
735 | # magic. | |
731 | s, matches = c.complete(None, "_bar_ce") |
|
736 | s, matches = c.complete(None, "_bar_ce") | |
732 | self.assertIn("%_bar_cellm", matches) |
|
737 | self.assertIn("%_bar_cellm", matches) | |
733 | self.assertIn("%%_bar_cellm", matches) |
|
738 | self.assertIn("%%_bar_cellm", matches) | |
734 | s, matches = c.complete(None, "%_bar_ce") |
|
739 | s, matches = c.complete(None, "%_bar_ce") | |
735 | self.assertIn("%_bar_cellm", matches) |
|
740 | self.assertIn("%_bar_cellm", matches) | |
736 | self.assertIn("%%_bar_cellm", matches) |
|
741 | self.assertIn("%%_bar_cellm", matches) | |
737 | s, matches = c.complete(None, "%%_bar_ce") |
|
742 | s, matches = c.complete(None, "%%_bar_ce") | |
738 | self.assertNotIn("%_bar_cellm", matches) |
|
743 | self.assertNotIn("%_bar_cellm", matches) | |
739 | self.assertIn("%%_bar_cellm", matches) |
|
744 | self.assertIn("%%_bar_cellm", matches) | |
740 |
|
745 | |||
741 | def test_magic_completion_order(self): |
|
746 | def test_magic_completion_order(self): | |
742 | ip = get_ipython() |
|
747 | ip = get_ipython() | |
743 | c = ip.Completer |
|
748 | c = ip.Completer | |
744 |
|
749 | |||
745 | # Test ordering of line and cell magics. |
|
750 | # Test ordering of line and cell magics. | |
746 | text, matches = c.complete("timeit") |
|
751 | text, matches = c.complete("timeit") | |
747 | self.assertEqual(matches, ["%timeit", "%%timeit"]) |
|
752 | self.assertEqual(matches, ["%timeit", "%%timeit"]) | |
748 |
|
753 | |||
749 | def test_magic_completion_shadowing(self): |
|
754 | def test_magic_completion_shadowing(self): | |
750 | ip = get_ipython() |
|
755 | ip = get_ipython() | |
751 | c = ip.Completer |
|
756 | c = ip.Completer | |
752 | c.use_jedi = False |
|
757 | c.use_jedi = False | |
753 |
|
758 | |||
754 | # Before importing matplotlib, %matplotlib magic should be the only option. |
|
759 | # Before importing matplotlib, %matplotlib magic should be the only option. | |
755 | text, matches = c.complete("mat") |
|
760 | text, matches = c.complete("mat") | |
756 | self.assertEqual(matches, ["%matplotlib"]) |
|
761 | self.assertEqual(matches, ["%matplotlib"]) | |
757 |
|
762 | |||
758 | # The newly introduced name should shadow the magic. |
|
763 | # The newly introduced name should shadow the magic. | |
759 | ip.run_cell("matplotlib = 1") |
|
764 | ip.run_cell("matplotlib = 1") | |
760 | text, matches = c.complete("mat") |
|
765 | text, matches = c.complete("mat") | |
761 | self.assertEqual(matches, ["matplotlib"]) |
|
766 | self.assertEqual(matches, ["matplotlib"]) | |
762 |
|
767 | |||
763 | # After removing matplotlib from namespace, the magic should again be |
|
768 | # After removing matplotlib from namespace, the magic should again be | |
764 | # the only option. |
|
769 | # the only option. | |
765 | del ip.user_ns["matplotlib"] |
|
770 | del ip.user_ns["matplotlib"] | |
766 | text, matches = c.complete("mat") |
|
771 | text, matches = c.complete("mat") | |
767 | self.assertEqual(matches, ["%matplotlib"]) |
|
772 | self.assertEqual(matches, ["%matplotlib"]) | |
768 |
|
773 | |||
769 | def test_magic_completion_shadowing_explicit(self): |
|
774 | def test_magic_completion_shadowing_explicit(self): | |
770 | """ |
|
775 | """ | |
771 | If the user try to complete a shadowed magic, and explicit % start should |
|
776 | If the user try to complete a shadowed magic, and explicit % start should | |
772 | still return the completions. |
|
777 | still return the completions. | |
773 | """ |
|
778 | """ | |
774 | ip = get_ipython() |
|
779 | ip = get_ipython() | |
775 | c = ip.Completer |
|
780 | c = ip.Completer | |
776 |
|
781 | |||
777 | # Before importing matplotlib, %matplotlib magic should be the only option. |
|
782 | # Before importing matplotlib, %matplotlib magic should be the only option. | |
778 | text, matches = c.complete("%mat") |
|
783 | text, matches = c.complete("%mat") | |
779 | self.assertEqual(matches, ["%matplotlib"]) |
|
784 | self.assertEqual(matches, ["%matplotlib"]) | |
780 |
|
785 | |||
781 | ip.run_cell("matplotlib = 1") |
|
786 | ip.run_cell("matplotlib = 1") | |
782 |
|
787 | |||
783 | # After removing matplotlib from namespace, the magic should still be |
|
788 | # After removing matplotlib from namespace, the magic should still be | |
784 | # the only option. |
|
789 | # the only option. | |
785 | text, matches = c.complete("%mat") |
|
790 | text, matches = c.complete("%mat") | |
786 | self.assertEqual(matches, ["%matplotlib"]) |
|
791 | self.assertEqual(matches, ["%matplotlib"]) | |
787 |
|
792 | |||
788 | def test_magic_config(self): |
|
793 | def test_magic_config(self): | |
789 | ip = get_ipython() |
|
794 | ip = get_ipython() | |
790 | c = ip.Completer |
|
795 | c = ip.Completer | |
791 |
|
796 | |||
792 | s, matches = c.complete(None, "conf") |
|
797 | s, matches = c.complete(None, "conf") | |
793 | self.assertIn("%config", matches) |
|
798 | self.assertIn("%config", matches) | |
794 | s, matches = c.complete(None, "conf") |
|
799 | s, matches = c.complete(None, "conf") | |
795 | self.assertNotIn("AliasManager", matches) |
|
800 | self.assertNotIn("AliasManager", matches) | |
796 | s, matches = c.complete(None, "config ") |
|
801 | s, matches = c.complete(None, "config ") | |
797 | self.assertIn("AliasManager", matches) |
|
802 | self.assertIn("AliasManager", matches) | |
798 | s, matches = c.complete(None, "%config ") |
|
803 | s, matches = c.complete(None, "%config ") | |
799 | self.assertIn("AliasManager", matches) |
|
804 | self.assertIn("AliasManager", matches) | |
800 | s, matches = c.complete(None, "config Ali") |
|
805 | s, matches = c.complete(None, "config Ali") | |
801 | self.assertListEqual(["AliasManager"], matches) |
|
806 | self.assertListEqual(["AliasManager"], matches) | |
802 | s, matches = c.complete(None, "%config Ali") |
|
807 | s, matches = c.complete(None, "%config Ali") | |
803 | self.assertListEqual(["AliasManager"], matches) |
|
808 | self.assertListEqual(["AliasManager"], matches) | |
804 | s, matches = c.complete(None, "config AliasManager") |
|
809 | s, matches = c.complete(None, "config AliasManager") | |
805 | self.assertListEqual(["AliasManager"], matches) |
|
810 | self.assertListEqual(["AliasManager"], matches) | |
806 | s, matches = c.complete(None, "%config AliasManager") |
|
811 | s, matches = c.complete(None, "%config AliasManager") | |
807 | self.assertListEqual(["AliasManager"], matches) |
|
812 | self.assertListEqual(["AliasManager"], matches) | |
808 | s, matches = c.complete(None, "config AliasManager.") |
|
813 | s, matches = c.complete(None, "config AliasManager.") | |
809 | self.assertIn("AliasManager.default_aliases", matches) |
|
814 | self.assertIn("AliasManager.default_aliases", matches) | |
810 | s, matches = c.complete(None, "%config AliasManager.") |
|
815 | s, matches = c.complete(None, "%config AliasManager.") | |
811 | self.assertIn("AliasManager.default_aliases", matches) |
|
816 | self.assertIn("AliasManager.default_aliases", matches) | |
812 | s, matches = c.complete(None, "config AliasManager.de") |
|
817 | s, matches = c.complete(None, "config AliasManager.de") | |
813 | self.assertListEqual(["AliasManager.default_aliases"], matches) |
|
818 | self.assertListEqual(["AliasManager.default_aliases"], matches) | |
814 | s, matches = c.complete(None, "config AliasManager.de") |
|
819 | s, matches = c.complete(None, "config AliasManager.de") | |
815 | self.assertListEqual(["AliasManager.default_aliases"], matches) |
|
820 | self.assertListEqual(["AliasManager.default_aliases"], matches) | |
816 |
|
821 | |||
817 | def test_magic_color(self): |
|
822 | def test_magic_color(self): | |
818 | ip = get_ipython() |
|
823 | ip = get_ipython() | |
819 | c = ip.Completer |
|
824 | c = ip.Completer | |
820 |
|
825 | |||
821 | s, matches = c.complete(None, "colo") |
|
826 | s, matches = c.complete(None, "colo") | |
822 | self.assertIn("%colors", matches) |
|
827 | self.assertIn("%colors", matches) | |
823 | s, matches = c.complete(None, "colo") |
|
828 | s, matches = c.complete(None, "colo") | |
824 | self.assertNotIn("NoColor", matches) |
|
829 | self.assertNotIn("NoColor", matches) | |
825 | s, matches = c.complete(None, "%colors") # No trailing space |
|
830 | s, matches = c.complete(None, "%colors") # No trailing space | |
826 | self.assertNotIn("NoColor", matches) |
|
831 | self.assertNotIn("NoColor", matches) | |
827 | s, matches = c.complete(None, "colors ") |
|
832 | s, matches = c.complete(None, "colors ") | |
828 | self.assertIn("NoColor", matches) |
|
833 | self.assertIn("NoColor", matches) | |
829 | s, matches = c.complete(None, "%colors ") |
|
834 | s, matches = c.complete(None, "%colors ") | |
830 | self.assertIn("NoColor", matches) |
|
835 | self.assertIn("NoColor", matches) | |
831 | s, matches = c.complete(None, "colors NoCo") |
|
836 | s, matches = c.complete(None, "colors NoCo") | |
832 | self.assertListEqual(["NoColor"], matches) |
|
837 | self.assertListEqual(["NoColor"], matches) | |
833 | s, matches = c.complete(None, "%colors NoCo") |
|
838 | s, matches = c.complete(None, "%colors NoCo") | |
834 | self.assertListEqual(["NoColor"], matches) |
|
839 | self.assertListEqual(["NoColor"], matches) | |
835 |
|
840 | |||
836 | def test_match_dict_keys(self): |
|
841 | def test_match_dict_keys(self): | |
837 | """ |
|
842 | """ | |
838 | Test that match_dict_keys works on a couple of use case does return what |
|
843 | Test that match_dict_keys works on a couple of use case does return what | |
839 | expected, and does not crash |
|
844 | expected, and does not crash | |
840 | """ |
|
845 | """ | |
841 | delims = " \t\n`!@#$^&*()=+[{]}\\|;:'\",<>?" |
|
846 | delims = " \t\n`!@#$^&*()=+[{]}\\|;:'\",<>?" | |
842 |
|
847 | |||
843 | keys = ["foo", b"far"] |
|
848 | keys = ["foo", b"far"] | |
844 | assert match_dict_keys(keys, "b'", delims=delims) == ("'", 2, ["far"]) |
|
849 | assert match_dict_keys(keys, "b'", delims=delims) == ("'", 2, ["far"]) | |
845 | assert match_dict_keys(keys, "b'f", delims=delims) == ("'", 2, ["far"]) |
|
850 | assert match_dict_keys(keys, "b'f", delims=delims) == ("'", 2, ["far"]) | |
846 | assert match_dict_keys(keys, 'b"', delims=delims) == ('"', 2, ["far"]) |
|
851 | assert match_dict_keys(keys, 'b"', delims=delims) == ('"', 2, ["far"]) | |
847 | assert match_dict_keys(keys, 'b"f', delims=delims) == ('"', 2, ["far"]) |
|
852 | assert match_dict_keys(keys, 'b"f', delims=delims) == ('"', 2, ["far"]) | |
848 |
|
853 | |||
849 | assert match_dict_keys(keys, "'", delims=delims) == ("'", 1, ["foo"]) |
|
854 | assert match_dict_keys(keys, "'", delims=delims) == ("'", 1, ["foo"]) | |
850 | assert match_dict_keys(keys, "'f", delims=delims) == ("'", 1, ["foo"]) |
|
855 | assert match_dict_keys(keys, "'f", delims=delims) == ("'", 1, ["foo"]) | |
851 | assert match_dict_keys(keys, '"', delims=delims) == ('"', 1, ["foo"]) |
|
856 | assert match_dict_keys(keys, '"', delims=delims) == ('"', 1, ["foo"]) | |
852 | assert match_dict_keys(keys, '"f', delims=delims) == ('"', 1, ["foo"]) |
|
857 | assert match_dict_keys(keys, '"f', delims=delims) == ('"', 1, ["foo"]) | |
853 |
|
858 | |||
854 | match_dict_keys |
|
859 | match_dict_keys | |
855 |
|
860 | |||
856 | def test_match_dict_keys_tuple(self): |
|
861 | def test_match_dict_keys_tuple(self): | |
857 | """ |
|
862 | """ | |
858 | Test that match_dict_keys called with extra prefix works on a couple of use case, |
|
863 | Test that match_dict_keys called with extra prefix works on a couple of use case, | |
859 | does return what expected, and does not crash. |
|
864 | does return what expected, and does not crash. | |
860 | """ |
|
865 | """ | |
861 | delims = " \t\n`!@#$^&*()=+[{]}\\|;:'\",<>?" |
|
866 | delims = " \t\n`!@#$^&*()=+[{]}\\|;:'\",<>?" | |
862 |
|
867 | |||
863 | keys = [("foo", "bar"), ("foo", "oof"), ("foo", b"bar"), ('other', 'test')] |
|
868 | keys = [("foo", "bar"), ("foo", "oof"), ("foo", b"bar"), ('other', 'test')] | |
864 |
|
869 | |||
865 | # Completion on first key == "foo" |
|
870 | # Completion on first key == "foo" | |
866 | assert match_dict_keys(keys, "'", delims=delims, extra_prefix=("foo",)) == ("'", 1, ["bar", "oof"]) |
|
871 | assert match_dict_keys(keys, "'", delims=delims, extra_prefix=("foo",)) == ("'", 1, ["bar", "oof"]) | |
867 | assert match_dict_keys(keys, "\"", delims=delims, extra_prefix=("foo",)) == ("\"", 1, ["bar", "oof"]) |
|
872 | assert match_dict_keys(keys, "\"", delims=delims, extra_prefix=("foo",)) == ("\"", 1, ["bar", "oof"]) | |
868 | assert match_dict_keys(keys, "'o", delims=delims, extra_prefix=("foo",)) == ("'", 1, ["oof"]) |
|
873 | assert match_dict_keys(keys, "'o", delims=delims, extra_prefix=("foo",)) == ("'", 1, ["oof"]) | |
869 | assert match_dict_keys(keys, "\"o", delims=delims, extra_prefix=("foo",)) == ("\"", 1, ["oof"]) |
|
874 | assert match_dict_keys(keys, "\"o", delims=delims, extra_prefix=("foo",)) == ("\"", 1, ["oof"]) | |
870 | assert match_dict_keys(keys, "b'", delims=delims, extra_prefix=("foo",)) == ("'", 2, ["bar"]) |
|
875 | assert match_dict_keys(keys, "b'", delims=delims, extra_prefix=("foo",)) == ("'", 2, ["bar"]) | |
871 | assert match_dict_keys(keys, "b\"", delims=delims, extra_prefix=("foo",)) == ("\"", 2, ["bar"]) |
|
876 | assert match_dict_keys(keys, "b\"", delims=delims, extra_prefix=("foo",)) == ("\"", 2, ["bar"]) | |
872 | assert match_dict_keys(keys, "b'b", delims=delims, extra_prefix=("foo",)) == ("'", 2, ["bar"]) |
|
877 | assert match_dict_keys(keys, "b'b", delims=delims, extra_prefix=("foo",)) == ("'", 2, ["bar"]) | |
873 | assert match_dict_keys(keys, "b\"b", delims=delims, extra_prefix=("foo",)) == ("\"", 2, ["bar"]) |
|
878 | assert match_dict_keys(keys, "b\"b", delims=delims, extra_prefix=("foo",)) == ("\"", 2, ["bar"]) | |
874 |
|
879 | |||
875 | # No Completion |
|
880 | # No Completion | |
876 | assert match_dict_keys(keys, "'", delims=delims, extra_prefix=("no_foo",)) == ("'", 1, []) |
|
881 | assert match_dict_keys(keys, "'", delims=delims, extra_prefix=("no_foo",)) == ("'", 1, []) | |
877 | assert match_dict_keys(keys, "'", delims=delims, extra_prefix=("fo",)) == ("'", 1, []) |
|
882 | assert match_dict_keys(keys, "'", delims=delims, extra_prefix=("fo",)) == ("'", 1, []) | |
878 |
|
883 | |||
879 | keys = [('foo1', 'foo2', 'foo3', 'foo4'), ('foo1', 'foo2', 'bar', 'foo4')] |
|
884 | keys = [('foo1', 'foo2', 'foo3', 'foo4'), ('foo1', 'foo2', 'bar', 'foo4')] | |
880 | assert match_dict_keys(keys, "'foo", delims=delims, extra_prefix=('foo1',)) == ("'", 1, ["foo2", "foo2"]) |
|
885 | assert match_dict_keys(keys, "'foo", delims=delims, extra_prefix=('foo1',)) == ("'", 1, ["foo2", "foo2"]) | |
881 | assert match_dict_keys(keys, "'foo", delims=delims, extra_prefix=('foo1', 'foo2')) == ("'", 1, ["foo3"]) |
|
886 | assert match_dict_keys(keys, "'foo", delims=delims, extra_prefix=('foo1', 'foo2')) == ("'", 1, ["foo3"]) | |
882 | assert match_dict_keys(keys, "'foo", delims=delims, extra_prefix=('foo1', 'foo2', 'foo3')) == ("'", 1, ["foo4"]) |
|
887 | assert match_dict_keys(keys, "'foo", delims=delims, extra_prefix=('foo1', 'foo2', 'foo3')) == ("'", 1, ["foo4"]) | |
883 | assert match_dict_keys(keys, "'foo", delims=delims, extra_prefix=('foo1', 'foo2', 'foo3', 'foo4')) == ("'", 1, []) |
|
888 | assert match_dict_keys(keys, "'foo", delims=delims, extra_prefix=('foo1', 'foo2', 'foo3', 'foo4')) == ("'", 1, []) | |
884 |
|
889 | |||
885 | def test_dict_key_completion_string(self): |
|
890 | def test_dict_key_completion_string(self): | |
886 | """Test dictionary key completion for string keys""" |
|
891 | """Test dictionary key completion for string keys""" | |
887 | ip = get_ipython() |
|
892 | ip = get_ipython() | |
888 | complete = ip.Completer.complete |
|
893 | complete = ip.Completer.complete | |
889 |
|
894 | |||
890 | ip.user_ns["d"] = {"abc": None} |
|
895 | ip.user_ns["d"] = {"abc": None} | |
891 |
|
896 | |||
892 | # check completion at different stages |
|
897 | # check completion at different stages | |
893 | _, matches = complete(line_buffer="d[") |
|
898 | _, matches = complete(line_buffer="d[") | |
894 | self.assertIn("'abc'", matches) |
|
899 | self.assertIn("'abc'", matches) | |
895 | self.assertNotIn("'abc']", matches) |
|
900 | self.assertNotIn("'abc']", matches) | |
896 |
|
901 | |||
897 | _, matches = complete(line_buffer="d['") |
|
902 | _, matches = complete(line_buffer="d['") | |
898 | self.assertIn("abc", matches) |
|
903 | self.assertIn("abc", matches) | |
899 | self.assertNotIn("abc']", matches) |
|
904 | self.assertNotIn("abc']", matches) | |
900 |
|
905 | |||
901 | _, matches = complete(line_buffer="d['a") |
|
906 | _, matches = complete(line_buffer="d['a") | |
902 | self.assertIn("abc", matches) |
|
907 | self.assertIn("abc", matches) | |
903 | self.assertNotIn("abc']", matches) |
|
908 | self.assertNotIn("abc']", matches) | |
904 |
|
909 | |||
905 | # check use of different quoting |
|
910 | # check use of different quoting | |
906 | _, matches = complete(line_buffer='d["') |
|
911 | _, matches = complete(line_buffer='d["') | |
907 | self.assertIn("abc", matches) |
|
912 | self.assertIn("abc", matches) | |
908 | self.assertNotIn('abc"]', matches) |
|
913 | self.assertNotIn('abc"]', matches) | |
909 |
|
914 | |||
910 | _, matches = complete(line_buffer='d["a') |
|
915 | _, matches = complete(line_buffer='d["a') | |
911 | self.assertIn("abc", matches) |
|
916 | self.assertIn("abc", matches) | |
912 | self.assertNotIn('abc"]', matches) |
|
917 | self.assertNotIn('abc"]', matches) | |
913 |
|
918 | |||
914 | # check sensitivity to following context |
|
919 | # check sensitivity to following context | |
915 | _, matches = complete(line_buffer="d[]", cursor_pos=2) |
|
920 | _, matches = complete(line_buffer="d[]", cursor_pos=2) | |
916 | self.assertIn("'abc'", matches) |
|
921 | self.assertIn("'abc'", matches) | |
917 |
|
922 | |||
918 | _, matches = complete(line_buffer="d['']", cursor_pos=3) |
|
923 | _, matches = complete(line_buffer="d['']", cursor_pos=3) | |
919 | self.assertIn("abc", matches) |
|
924 | self.assertIn("abc", matches) | |
920 | self.assertNotIn("abc'", matches) |
|
925 | self.assertNotIn("abc'", matches) | |
921 | self.assertNotIn("abc']", matches) |
|
926 | self.assertNotIn("abc']", matches) | |
922 |
|
927 | |||
923 | # check multiple solutions are correctly returned and that noise is not |
|
928 | # check multiple solutions are correctly returned and that noise is not | |
924 | ip.user_ns["d"] = { |
|
929 | ip.user_ns["d"] = { | |
925 | "abc": None, |
|
930 | "abc": None, | |
926 | "abd": None, |
|
931 | "abd": None, | |
927 | "bad": None, |
|
932 | "bad": None, | |
928 | object(): None, |
|
933 | object(): None, | |
929 | 5: None, |
|
934 | 5: None, | |
930 | ("abe", None): None, |
|
935 | ("abe", None): None, | |
931 | (None, "abf"): None |
|
936 | (None, "abf"): None | |
932 | } |
|
937 | } | |
933 |
|
938 | |||
934 | _, matches = complete(line_buffer="d['a") |
|
939 | _, matches = complete(line_buffer="d['a") | |
935 | self.assertIn("abc", matches) |
|
940 | self.assertIn("abc", matches) | |
936 | self.assertIn("abd", matches) |
|
941 | self.assertIn("abd", matches) | |
937 | self.assertNotIn("bad", matches) |
|
942 | self.assertNotIn("bad", matches) | |
938 | self.assertNotIn("abe", matches) |
|
943 | self.assertNotIn("abe", matches) | |
939 | self.assertNotIn("abf", matches) |
|
944 | self.assertNotIn("abf", matches) | |
940 | assert not any(m.endswith(("]", '"', "'")) for m in matches), matches |
|
945 | assert not any(m.endswith(("]", '"', "'")) for m in matches), matches | |
941 |
|
946 | |||
942 | # check escaping and whitespace |
|
947 | # check escaping and whitespace | |
943 | ip.user_ns["d"] = {"a\nb": None, "a'b": None, 'a"b': None, "a word": None} |
|
948 | ip.user_ns["d"] = {"a\nb": None, "a'b": None, 'a"b': None, "a word": None} | |
944 | _, matches = complete(line_buffer="d['a") |
|
949 | _, matches = complete(line_buffer="d['a") | |
945 | self.assertIn("a\\nb", matches) |
|
950 | self.assertIn("a\\nb", matches) | |
946 | self.assertIn("a\\'b", matches) |
|
951 | self.assertIn("a\\'b", matches) | |
947 | self.assertIn('a"b', matches) |
|
952 | self.assertIn('a"b', matches) | |
948 | self.assertIn("a word", matches) |
|
953 | self.assertIn("a word", matches) | |
949 | assert not any(m.endswith(("]", '"', "'")) for m in matches), matches |
|
954 | assert not any(m.endswith(("]", '"', "'")) for m in matches), matches | |
950 |
|
955 | |||
951 | # - can complete on non-initial word of the string |
|
956 | # - can complete on non-initial word of the string | |
952 | _, matches = complete(line_buffer="d['a w") |
|
957 | _, matches = complete(line_buffer="d['a w") | |
953 | self.assertIn("word", matches) |
|
958 | self.assertIn("word", matches) | |
954 |
|
959 | |||
955 | # - understands quote escaping |
|
960 | # - understands quote escaping | |
956 | _, matches = complete(line_buffer="d['a\\'") |
|
961 | _, matches = complete(line_buffer="d['a\\'") | |
957 | self.assertIn("b", matches) |
|
962 | self.assertIn("b", matches) | |
958 |
|
963 | |||
959 | # - default quoting should work like repr |
|
964 | # - default quoting should work like repr | |
960 | _, matches = complete(line_buffer="d[") |
|
965 | _, matches = complete(line_buffer="d[") | |
961 | self.assertIn('"a\'b"', matches) |
|
966 | self.assertIn('"a\'b"', matches) | |
962 |
|
967 | |||
963 | # - when opening quote with ", possible to match with unescaped apostrophe |
|
968 | # - when opening quote with ", possible to match with unescaped apostrophe | |
964 | _, matches = complete(line_buffer="d[\"a'") |
|
969 | _, matches = complete(line_buffer="d[\"a'") | |
965 | self.assertIn("b", matches) |
|
970 | self.assertIn("b", matches) | |
966 |
|
971 | |||
967 | # need to not split at delims that readline won't split at |
|
972 | # need to not split at delims that readline won't split at | |
968 | if "-" not in ip.Completer.splitter.delims: |
|
973 | if "-" not in ip.Completer.splitter.delims: | |
969 | ip.user_ns["d"] = {"before-after": None} |
|
974 | ip.user_ns["d"] = {"before-after": None} | |
970 | _, matches = complete(line_buffer="d['before-af") |
|
975 | _, matches = complete(line_buffer="d['before-af") | |
971 | self.assertIn("before-after", matches) |
|
976 | self.assertIn("before-after", matches) | |
972 |
|
977 | |||
973 | # check completion on tuple-of-string keys at different stage - on first key |
|
978 | # check completion on tuple-of-string keys at different stage - on first key | |
974 | ip.user_ns["d"] = {('foo', 'bar'): None} |
|
979 | ip.user_ns["d"] = {('foo', 'bar'): None} | |
975 | _, matches = complete(line_buffer="d[") |
|
980 | _, matches = complete(line_buffer="d[") | |
976 | self.assertIn("'foo'", matches) |
|
981 | self.assertIn("'foo'", matches) | |
977 | self.assertNotIn("'foo']", matches) |
|
982 | self.assertNotIn("'foo']", matches) | |
978 | self.assertNotIn("'bar'", matches) |
|
983 | self.assertNotIn("'bar'", matches) | |
979 | self.assertNotIn("foo", matches) |
|
984 | self.assertNotIn("foo", matches) | |
980 | self.assertNotIn("bar", matches) |
|
985 | self.assertNotIn("bar", matches) | |
981 |
|
986 | |||
982 | # - match the prefix |
|
987 | # - match the prefix | |
983 | _, matches = complete(line_buffer="d['f") |
|
988 | _, matches = complete(line_buffer="d['f") | |
984 | self.assertIn("foo", matches) |
|
989 | self.assertIn("foo", matches) | |
985 | self.assertNotIn("foo']", matches) |
|
990 | self.assertNotIn("foo']", matches) | |
986 | self.assertNotIn('foo"]', matches) |
|
991 | self.assertNotIn('foo"]', matches) | |
987 | _, matches = complete(line_buffer="d['foo") |
|
992 | _, matches = complete(line_buffer="d['foo") | |
988 | self.assertIn("foo", matches) |
|
993 | self.assertIn("foo", matches) | |
989 |
|
994 | |||
990 | # - can complete on second key |
|
995 | # - can complete on second key | |
991 | _, matches = complete(line_buffer="d['foo', ") |
|
996 | _, matches = complete(line_buffer="d['foo', ") | |
992 | self.assertIn("'bar'", matches) |
|
997 | self.assertIn("'bar'", matches) | |
993 | _, matches = complete(line_buffer="d['foo', 'b") |
|
998 | _, matches = complete(line_buffer="d['foo', 'b") | |
994 | self.assertIn("bar", matches) |
|
999 | self.assertIn("bar", matches) | |
995 | self.assertNotIn("foo", matches) |
|
1000 | self.assertNotIn("foo", matches) | |
996 |
|
1001 | |||
997 | # - does not propose missing keys |
|
1002 | # - does not propose missing keys | |
998 | _, matches = complete(line_buffer="d['foo', 'f") |
|
1003 | _, matches = complete(line_buffer="d['foo', 'f") | |
999 | self.assertNotIn("bar", matches) |
|
1004 | self.assertNotIn("bar", matches) | |
1000 | self.assertNotIn("foo", matches) |
|
1005 | self.assertNotIn("foo", matches) | |
1001 |
|
1006 | |||
1002 | # check sensitivity to following context |
|
1007 | # check sensitivity to following context | |
1003 | _, matches = complete(line_buffer="d['foo',]", cursor_pos=8) |
|
1008 | _, matches = complete(line_buffer="d['foo',]", cursor_pos=8) | |
1004 | self.assertIn("'bar'", matches) |
|
1009 | self.assertIn("'bar'", matches) | |
1005 | self.assertNotIn("bar", matches) |
|
1010 | self.assertNotIn("bar", matches) | |
1006 | self.assertNotIn("'foo'", matches) |
|
1011 | self.assertNotIn("'foo'", matches) | |
1007 | self.assertNotIn("foo", matches) |
|
1012 | self.assertNotIn("foo", matches) | |
1008 |
|
1013 | |||
1009 | _, matches = complete(line_buffer="d['']", cursor_pos=3) |
|
1014 | _, matches = complete(line_buffer="d['']", cursor_pos=3) | |
1010 | self.assertIn("foo", matches) |
|
1015 | self.assertIn("foo", matches) | |
1011 | assert not any(m.endswith(("]", '"', "'")) for m in matches), matches |
|
1016 | assert not any(m.endswith(("]", '"', "'")) for m in matches), matches | |
1012 |
|
1017 | |||
1013 | _, matches = complete(line_buffer='d[""]', cursor_pos=3) |
|
1018 | _, matches = complete(line_buffer='d[""]', cursor_pos=3) | |
1014 | self.assertIn("foo", matches) |
|
1019 | self.assertIn("foo", matches) | |
1015 | assert not any(m.endswith(("]", '"', "'")) for m in matches), matches |
|
1020 | assert not any(m.endswith(("]", '"', "'")) for m in matches), matches | |
1016 |
|
1021 | |||
1017 | _, matches = complete(line_buffer='d["foo","]', cursor_pos=9) |
|
1022 | _, matches = complete(line_buffer='d["foo","]', cursor_pos=9) | |
1018 | self.assertIn("bar", matches) |
|
1023 | self.assertIn("bar", matches) | |
1019 | assert not any(m.endswith(("]", '"', "'")) for m in matches), matches |
|
1024 | assert not any(m.endswith(("]", '"', "'")) for m in matches), matches | |
1020 |
|
1025 | |||
1021 | _, matches = complete(line_buffer='d["foo",]', cursor_pos=8) |
|
1026 | _, matches = complete(line_buffer='d["foo",]', cursor_pos=8) | |
1022 | self.assertIn("'bar'", matches) |
|
1027 | self.assertIn("'bar'", matches) | |
1023 | self.assertNotIn("bar", matches) |
|
1028 | self.assertNotIn("bar", matches) | |
1024 |
|
1029 | |||
1025 | # Can complete with longer tuple keys |
|
1030 | # Can complete with longer tuple keys | |
1026 | ip.user_ns["d"] = {('foo', 'bar', 'foobar'): None} |
|
1031 | ip.user_ns["d"] = {('foo', 'bar', 'foobar'): None} | |
1027 |
|
1032 | |||
1028 | # - can complete second key |
|
1033 | # - can complete second key | |
1029 | _, matches = complete(line_buffer="d['foo', 'b") |
|
1034 | _, matches = complete(line_buffer="d['foo', 'b") | |
1030 | self.assertIn("bar", matches) |
|
1035 | self.assertIn("bar", matches) | |
1031 | self.assertNotIn("foo", matches) |
|
1036 | self.assertNotIn("foo", matches) | |
1032 | self.assertNotIn("foobar", matches) |
|
1037 | self.assertNotIn("foobar", matches) | |
1033 |
|
1038 | |||
1034 | # - can complete third key |
|
1039 | # - can complete third key | |
1035 | _, matches = complete(line_buffer="d['foo', 'bar', 'fo") |
|
1040 | _, matches = complete(line_buffer="d['foo', 'bar', 'fo") | |
1036 | self.assertIn("foobar", matches) |
|
1041 | self.assertIn("foobar", matches) | |
1037 | self.assertNotIn("foo", matches) |
|
1042 | self.assertNotIn("foo", matches) | |
1038 | self.assertNotIn("bar", matches) |
|
1043 | self.assertNotIn("bar", matches) | |
1039 |
|
1044 | |||
1040 | def test_dict_key_completion_contexts(self): |
|
1045 | def test_dict_key_completion_contexts(self): | |
1041 | """Test expression contexts in which dict key completion occurs""" |
|
1046 | """Test expression contexts in which dict key completion occurs""" | |
1042 | ip = get_ipython() |
|
1047 | ip = get_ipython() | |
1043 | complete = ip.Completer.complete |
|
1048 | complete = ip.Completer.complete | |
1044 | d = {"abc": None} |
|
1049 | d = {"abc": None} | |
1045 | ip.user_ns["d"] = d |
|
1050 | ip.user_ns["d"] = d | |
1046 |
|
1051 | |||
1047 | class C: |
|
1052 | class C: | |
1048 | data = d |
|
1053 | data = d | |
1049 |
|
1054 | |||
1050 | ip.user_ns["C"] = C |
|
1055 | ip.user_ns["C"] = C | |
1051 | ip.user_ns["get"] = lambda: d |
|
1056 | ip.user_ns["get"] = lambda: d | |
1052 |
|
1057 | |||
1053 | def assert_no_completion(**kwargs): |
|
1058 | def assert_no_completion(**kwargs): | |
1054 | _, matches = complete(**kwargs) |
|
1059 | _, matches = complete(**kwargs) | |
1055 | self.assertNotIn("abc", matches) |
|
1060 | self.assertNotIn("abc", matches) | |
1056 | self.assertNotIn("abc'", matches) |
|
1061 | self.assertNotIn("abc'", matches) | |
1057 | self.assertNotIn("abc']", matches) |
|
1062 | self.assertNotIn("abc']", matches) | |
1058 | self.assertNotIn("'abc'", matches) |
|
1063 | self.assertNotIn("'abc'", matches) | |
1059 | self.assertNotIn("'abc']", matches) |
|
1064 | self.assertNotIn("'abc']", matches) | |
1060 |
|
1065 | |||
1061 | def assert_completion(**kwargs): |
|
1066 | def assert_completion(**kwargs): | |
1062 | _, matches = complete(**kwargs) |
|
1067 | _, matches = complete(**kwargs) | |
1063 | self.assertIn("'abc'", matches) |
|
1068 | self.assertIn("'abc'", matches) | |
1064 | self.assertNotIn("'abc']", matches) |
|
1069 | self.assertNotIn("'abc']", matches) | |
1065 |
|
1070 | |||
1066 | # no completion after string closed, even if reopened |
|
1071 | # no completion after string closed, even if reopened | |
1067 | assert_no_completion(line_buffer="d['a'") |
|
1072 | assert_no_completion(line_buffer="d['a'") | |
1068 | assert_no_completion(line_buffer='d["a"') |
|
1073 | assert_no_completion(line_buffer='d["a"') | |
1069 | assert_no_completion(line_buffer="d['a' + ") |
|
1074 | assert_no_completion(line_buffer="d['a' + ") | |
1070 | assert_no_completion(line_buffer="d['a' + '") |
|
1075 | assert_no_completion(line_buffer="d['a' + '") | |
1071 |
|
1076 | |||
1072 | # completion in non-trivial expressions |
|
1077 | # completion in non-trivial expressions | |
1073 | assert_completion(line_buffer="+ d[") |
|
1078 | assert_completion(line_buffer="+ d[") | |
1074 | assert_completion(line_buffer="(d[") |
|
1079 | assert_completion(line_buffer="(d[") | |
1075 | assert_completion(line_buffer="C.data[") |
|
1080 | assert_completion(line_buffer="C.data[") | |
1076 |
|
1081 | |||
1077 | # greedy flag |
|
1082 | # greedy flag | |
1078 | def assert_completion(**kwargs): |
|
1083 | def assert_completion(**kwargs): | |
1079 | _, matches = complete(**kwargs) |
|
1084 | _, matches = complete(**kwargs) | |
1080 | self.assertIn("get()['abc']", matches) |
|
1085 | self.assertIn("get()['abc']", matches) | |
1081 |
|
1086 | |||
1082 | assert_no_completion(line_buffer="get()[") |
|
1087 | assert_no_completion(line_buffer="get()[") | |
1083 | with greedy_completion(): |
|
1088 | with greedy_completion(): | |
1084 | assert_completion(line_buffer="get()[") |
|
1089 | assert_completion(line_buffer="get()[") | |
1085 | assert_completion(line_buffer="get()['") |
|
1090 | assert_completion(line_buffer="get()['") | |
1086 | assert_completion(line_buffer="get()['a") |
|
1091 | assert_completion(line_buffer="get()['a") | |
1087 | assert_completion(line_buffer="get()['ab") |
|
1092 | assert_completion(line_buffer="get()['ab") | |
1088 | assert_completion(line_buffer="get()['abc") |
|
1093 | assert_completion(line_buffer="get()['abc") | |
1089 |
|
1094 | |||
1090 | def test_dict_key_completion_bytes(self): |
|
1095 | def test_dict_key_completion_bytes(self): | |
1091 | """Test handling of bytes in dict key completion""" |
|
1096 | """Test handling of bytes in dict key completion""" | |
1092 | ip = get_ipython() |
|
1097 | ip = get_ipython() | |
1093 | complete = ip.Completer.complete |
|
1098 | complete = ip.Completer.complete | |
1094 |
|
1099 | |||
1095 | ip.user_ns["d"] = {"abc": None, b"abd": None} |
|
1100 | ip.user_ns["d"] = {"abc": None, b"abd": None} | |
1096 |
|
1101 | |||
1097 | _, matches = complete(line_buffer="d[") |
|
1102 | _, matches = complete(line_buffer="d[") | |
1098 | self.assertIn("'abc'", matches) |
|
1103 | self.assertIn("'abc'", matches) | |
1099 | self.assertIn("b'abd'", matches) |
|
1104 | self.assertIn("b'abd'", matches) | |
1100 |
|
1105 | |||
1101 | if False: # not currently implemented |
|
1106 | if False: # not currently implemented | |
1102 | _, matches = complete(line_buffer="d[b") |
|
1107 | _, matches = complete(line_buffer="d[b") | |
1103 | self.assertIn("b'abd'", matches) |
|
1108 | self.assertIn("b'abd'", matches) | |
1104 | self.assertNotIn("b'abc'", matches) |
|
1109 | self.assertNotIn("b'abc'", matches) | |
1105 |
|
1110 | |||
1106 | _, matches = complete(line_buffer="d[b'") |
|
1111 | _, matches = complete(line_buffer="d[b'") | |
1107 | self.assertIn("abd", matches) |
|
1112 | self.assertIn("abd", matches) | |
1108 | self.assertNotIn("abc", matches) |
|
1113 | self.assertNotIn("abc", matches) | |
1109 |
|
1114 | |||
1110 | _, matches = complete(line_buffer="d[B'") |
|
1115 | _, matches = complete(line_buffer="d[B'") | |
1111 | self.assertIn("abd", matches) |
|
1116 | self.assertIn("abd", matches) | |
1112 | self.assertNotIn("abc", matches) |
|
1117 | self.assertNotIn("abc", matches) | |
1113 |
|
1118 | |||
1114 | _, matches = complete(line_buffer="d['") |
|
1119 | _, matches = complete(line_buffer="d['") | |
1115 | self.assertIn("abc", matches) |
|
1120 | self.assertIn("abc", matches) | |
1116 | self.assertNotIn("abd", matches) |
|
1121 | self.assertNotIn("abd", matches) | |
1117 |
|
1122 | |||
1118 | def test_dict_key_completion_unicode_py3(self): |
|
1123 | def test_dict_key_completion_unicode_py3(self): | |
1119 | """Test handling of unicode in dict key completion""" |
|
1124 | """Test handling of unicode in dict key completion""" | |
1120 | ip = get_ipython() |
|
1125 | ip = get_ipython() | |
1121 | complete = ip.Completer.complete |
|
1126 | complete = ip.Completer.complete | |
1122 |
|
1127 | |||
1123 | ip.user_ns["d"] = {"a\u05d0": None} |
|
1128 | ip.user_ns["d"] = {"a\u05d0": None} | |
1124 |
|
1129 | |||
1125 | # query using escape |
|
1130 | # query using escape | |
1126 | if sys.platform != "win32": |
|
1131 | if sys.platform != "win32": | |
1127 | # Known failure on Windows |
|
1132 | # Known failure on Windows | |
1128 | _, matches = complete(line_buffer="d['a\\u05d0") |
|
1133 | _, matches = complete(line_buffer="d['a\\u05d0") | |
1129 | self.assertIn("u05d0", matches) # tokenized after \\ |
|
1134 | self.assertIn("u05d0", matches) # tokenized after \\ | |
1130 |
|
1135 | |||
1131 | # query using character |
|
1136 | # query using character | |
1132 | _, matches = complete(line_buffer="d['a\u05d0") |
|
1137 | _, matches = complete(line_buffer="d['a\u05d0") | |
1133 | self.assertIn("a\u05d0", matches) |
|
1138 | self.assertIn("a\u05d0", matches) | |
1134 |
|
1139 | |||
1135 | with greedy_completion(): |
|
1140 | with greedy_completion(): | |
1136 | # query using escape |
|
1141 | # query using escape | |
1137 | _, matches = complete(line_buffer="d['a\\u05d0") |
|
1142 | _, matches = complete(line_buffer="d['a\\u05d0") | |
1138 | self.assertIn("d['a\\u05d0']", matches) # tokenized after \\ |
|
1143 | self.assertIn("d['a\\u05d0']", matches) # tokenized after \\ | |
1139 |
|
1144 | |||
1140 | # query using character |
|
1145 | # query using character | |
1141 | _, matches = complete(line_buffer="d['a\u05d0") |
|
1146 | _, matches = complete(line_buffer="d['a\u05d0") | |
1142 | self.assertIn("d['a\u05d0']", matches) |
|
1147 | self.assertIn("d['a\u05d0']", matches) | |
1143 |
|
1148 | |||
1144 | @dec.skip_without("numpy") |
|
1149 | @dec.skip_without("numpy") | |
1145 | def test_struct_array_key_completion(self): |
|
1150 | def test_struct_array_key_completion(self): | |
1146 | """Test dict key completion applies to numpy struct arrays""" |
|
1151 | """Test dict key completion applies to numpy struct arrays""" | |
1147 | import numpy |
|
1152 | import numpy | |
1148 |
|
1153 | |||
1149 | ip = get_ipython() |
|
1154 | ip = get_ipython() | |
1150 | complete = ip.Completer.complete |
|
1155 | complete = ip.Completer.complete | |
1151 | ip.user_ns["d"] = numpy.array([], dtype=[("hello", "f"), ("world", "f")]) |
|
1156 | ip.user_ns["d"] = numpy.array([], dtype=[("hello", "f"), ("world", "f")]) | |
1152 | _, matches = complete(line_buffer="d['") |
|
1157 | _, matches = complete(line_buffer="d['") | |
1153 | self.assertIn("hello", matches) |
|
1158 | self.assertIn("hello", matches) | |
1154 | self.assertIn("world", matches) |
|
1159 | self.assertIn("world", matches) | |
1155 | # complete on the numpy struct itself |
|
1160 | # complete on the numpy struct itself | |
1156 | dt = numpy.dtype( |
|
1161 | dt = numpy.dtype( | |
1157 | [("my_head", [("my_dt", ">u4"), ("my_df", ">u4")]), ("my_data", ">f4", 5)] |
|
1162 | [("my_head", [("my_dt", ">u4"), ("my_df", ">u4")]), ("my_data", ">f4", 5)] | |
1158 | ) |
|
1163 | ) | |
1159 | x = numpy.zeros(2, dtype=dt) |
|
1164 | x = numpy.zeros(2, dtype=dt) | |
1160 | ip.user_ns["d"] = x[1] |
|
1165 | ip.user_ns["d"] = x[1] | |
1161 | _, matches = complete(line_buffer="d['") |
|
1166 | _, matches = complete(line_buffer="d['") | |
1162 | self.assertIn("my_head", matches) |
|
1167 | self.assertIn("my_head", matches) | |
1163 | self.assertIn("my_data", matches) |
|
1168 | self.assertIn("my_data", matches) | |
1164 | # complete on a nested level |
|
1169 | # complete on a nested level | |
1165 | with greedy_completion(): |
|
1170 | with greedy_completion(): | |
1166 | ip.user_ns["d"] = numpy.zeros(2, dtype=dt) |
|
1171 | ip.user_ns["d"] = numpy.zeros(2, dtype=dt) | |
1167 | _, matches = complete(line_buffer="d[1]['my_head']['") |
|
1172 | _, matches = complete(line_buffer="d[1]['my_head']['") | |
1168 | self.assertTrue(any(["my_dt" in m for m in matches])) |
|
1173 | self.assertTrue(any(["my_dt" in m for m in matches])) | |
1169 | self.assertTrue(any(["my_df" in m for m in matches])) |
|
1174 | self.assertTrue(any(["my_df" in m for m in matches])) | |
1170 |
|
1175 | |||
1171 | @dec.skip_without("pandas") |
|
1176 | @dec.skip_without("pandas") | |
1172 | def test_dataframe_key_completion(self): |
|
1177 | def test_dataframe_key_completion(self): | |
1173 | """Test dict key completion applies to pandas DataFrames""" |
|
1178 | """Test dict key completion applies to pandas DataFrames""" | |
1174 | import pandas |
|
1179 | import pandas | |
1175 |
|
1180 | |||
1176 | ip = get_ipython() |
|
1181 | ip = get_ipython() | |
1177 | complete = ip.Completer.complete |
|
1182 | complete = ip.Completer.complete | |
1178 | ip.user_ns["d"] = pandas.DataFrame({"hello": [1], "world": [2]}) |
|
1183 | ip.user_ns["d"] = pandas.DataFrame({"hello": [1], "world": [2]}) | |
1179 | _, matches = complete(line_buffer="d['") |
|
1184 | _, matches = complete(line_buffer="d['") | |
1180 | self.assertIn("hello", matches) |
|
1185 | self.assertIn("hello", matches) | |
1181 | self.assertIn("world", matches) |
|
1186 | self.assertIn("world", matches) | |
1182 |
|
1187 | |||
1183 | def test_dict_key_completion_invalids(self): |
|
1188 | def test_dict_key_completion_invalids(self): | |
1184 | """Smoke test cases dict key completion can't handle""" |
|
1189 | """Smoke test cases dict key completion can't handle""" | |
1185 | ip = get_ipython() |
|
1190 | ip = get_ipython() | |
1186 | complete = ip.Completer.complete |
|
1191 | complete = ip.Completer.complete | |
1187 |
|
1192 | |||
1188 | ip.user_ns["no_getitem"] = None |
|
1193 | ip.user_ns["no_getitem"] = None | |
1189 | ip.user_ns["no_keys"] = [] |
|
1194 | ip.user_ns["no_keys"] = [] | |
1190 | ip.user_ns["cant_call_keys"] = dict |
|
1195 | ip.user_ns["cant_call_keys"] = dict | |
1191 | ip.user_ns["empty"] = {} |
|
1196 | ip.user_ns["empty"] = {} | |
1192 | ip.user_ns["d"] = {"abc": 5} |
|
1197 | ip.user_ns["d"] = {"abc": 5} | |
1193 |
|
1198 | |||
1194 | _, matches = complete(line_buffer="no_getitem['") |
|
1199 | _, matches = complete(line_buffer="no_getitem['") | |
1195 | _, matches = complete(line_buffer="no_keys['") |
|
1200 | _, matches = complete(line_buffer="no_keys['") | |
1196 | _, matches = complete(line_buffer="cant_call_keys['") |
|
1201 | _, matches = complete(line_buffer="cant_call_keys['") | |
1197 | _, matches = complete(line_buffer="empty['") |
|
1202 | _, matches = complete(line_buffer="empty['") | |
1198 | _, matches = complete(line_buffer="name_error['") |
|
1203 | _, matches = complete(line_buffer="name_error['") | |
1199 | _, matches = complete(line_buffer="d['\\") # incomplete escape |
|
1204 | _, matches = complete(line_buffer="d['\\") # incomplete escape | |
1200 |
|
1205 | |||
1201 | def test_object_key_completion(self): |
|
1206 | def test_object_key_completion(self): | |
1202 | ip = get_ipython() |
|
1207 | ip = get_ipython() | |
1203 | ip.user_ns["key_completable"] = KeyCompletable(["qwerty", "qwick"]) |
|
1208 | ip.user_ns["key_completable"] = KeyCompletable(["qwerty", "qwick"]) | |
1204 |
|
1209 | |||
1205 | _, matches = ip.Completer.complete(line_buffer="key_completable['qw") |
|
1210 | _, matches = ip.Completer.complete(line_buffer="key_completable['qw") | |
1206 | self.assertIn("qwerty", matches) |
|
1211 | self.assertIn("qwerty", matches) | |
1207 | self.assertIn("qwick", matches) |
|
1212 | self.assertIn("qwick", matches) | |
1208 |
|
1213 | |||
1209 | def test_class_key_completion(self): |
|
1214 | def test_class_key_completion(self): | |
1210 | ip = get_ipython() |
|
1215 | ip = get_ipython() | |
1211 | NamedInstanceClass("qwerty") |
|
1216 | NamedInstanceClass("qwerty") | |
1212 | NamedInstanceClass("qwick") |
|
1217 | NamedInstanceClass("qwick") | |
1213 | ip.user_ns["named_instance_class"] = NamedInstanceClass |
|
1218 | ip.user_ns["named_instance_class"] = NamedInstanceClass | |
1214 |
|
1219 | |||
1215 | _, matches = ip.Completer.complete(line_buffer="named_instance_class['qw") |
|
1220 | _, matches = ip.Completer.complete(line_buffer="named_instance_class['qw") | |
1216 | self.assertIn("qwerty", matches) |
|
1221 | self.assertIn("qwerty", matches) | |
1217 | self.assertIn("qwick", matches) |
|
1222 | self.assertIn("qwick", matches) | |
1218 |
|
1223 | |||
1219 | def test_tryimport(self): |
|
1224 | def test_tryimport(self): | |
1220 | """ |
|
1225 | """ | |
1221 | Test that try-import don't crash on trailing dot, and import modules before |
|
1226 | Test that try-import don't crash on trailing dot, and import modules before | |
1222 | """ |
|
1227 | """ | |
1223 | from IPython.core.completerlib import try_import |
|
1228 | from IPython.core.completerlib import try_import | |
1224 |
|
1229 | |||
1225 | assert try_import("IPython.") |
|
1230 | assert try_import("IPython.") | |
1226 |
|
1231 | |||
1227 | def test_aimport_module_completer(self): |
|
1232 | def test_aimport_module_completer(self): | |
1228 | ip = get_ipython() |
|
1233 | ip = get_ipython() | |
1229 | _, matches = ip.complete("i", "%aimport i") |
|
1234 | _, matches = ip.complete("i", "%aimport i") | |
1230 | self.assertIn("io", matches) |
|
1235 | self.assertIn("io", matches) | |
1231 | self.assertNotIn("int", matches) |
|
1236 | self.assertNotIn("int", matches) | |
1232 |
|
1237 | |||
1233 | def test_nested_import_module_completer(self): |
|
1238 | def test_nested_import_module_completer(self): | |
1234 | ip = get_ipython() |
|
1239 | ip = get_ipython() | |
1235 | _, matches = ip.complete(None, "import IPython.co", 17) |
|
1240 | _, matches = ip.complete(None, "import IPython.co", 17) | |
1236 | self.assertIn("IPython.core", matches) |
|
1241 | self.assertIn("IPython.core", matches) | |
1237 | self.assertNotIn("import IPython.core", matches) |
|
1242 | self.assertNotIn("import IPython.core", matches) | |
1238 | self.assertNotIn("IPython.display", matches) |
|
1243 | self.assertNotIn("IPython.display", matches) | |
1239 |
|
1244 | |||
1240 | def test_import_module_completer(self): |
|
1245 | def test_import_module_completer(self): | |
1241 | ip = get_ipython() |
|
1246 | ip = get_ipython() | |
1242 | _, matches = ip.complete("i", "import i") |
|
1247 | _, matches = ip.complete("i", "import i") | |
1243 | self.assertIn("io", matches) |
|
1248 | self.assertIn("io", matches) | |
1244 | self.assertNotIn("int", matches) |
|
1249 | self.assertNotIn("int", matches) | |
1245 |
|
1250 | |||
1246 | def test_from_module_completer(self): |
|
1251 | def test_from_module_completer(self): | |
1247 | ip = get_ipython() |
|
1252 | ip = get_ipython() | |
1248 | _, matches = ip.complete("B", "from io import B", 16) |
|
1253 | _, matches = ip.complete("B", "from io import B", 16) | |
1249 | self.assertIn("BytesIO", matches) |
|
1254 | self.assertIn("BytesIO", matches) | |
1250 | self.assertNotIn("BaseException", matches) |
|
1255 | self.assertNotIn("BaseException", matches) | |
1251 |
|
1256 | |||
1252 | def test_snake_case_completion(self): |
|
1257 | def test_snake_case_completion(self): | |
1253 | ip = get_ipython() |
|
1258 | ip = get_ipython() | |
1254 | ip.Completer.use_jedi = False |
|
1259 | ip.Completer.use_jedi = False | |
1255 | ip.user_ns["some_three"] = 3 |
|
1260 | ip.user_ns["some_three"] = 3 | |
1256 | ip.user_ns["some_four"] = 4 |
|
1261 | ip.user_ns["some_four"] = 4 | |
1257 | _, matches = ip.complete("s_", "print(s_f") |
|
1262 | _, matches = ip.complete("s_", "print(s_f") | |
1258 | self.assertIn("some_three", matches) |
|
1263 | self.assertIn("some_three", matches) | |
1259 | self.assertIn("some_four", matches) |
|
1264 | self.assertIn("some_four", matches) | |
1260 |
|
1265 | |||
1261 | def test_mix_terms(self): |
|
1266 | def test_mix_terms(self): | |
1262 | ip = get_ipython() |
|
1267 | ip = get_ipython() | |
1263 | from textwrap import dedent |
|
1268 | from textwrap import dedent | |
1264 |
|
1269 | |||
1265 | ip.Completer.use_jedi = False |
|
1270 | ip.Completer.use_jedi = False | |
1266 | ip.ex( |
|
1271 | ip.ex( | |
1267 | dedent( |
|
1272 | dedent( | |
1268 | """ |
|
1273 | """ | |
1269 | class Test: |
|
1274 | class Test: | |
1270 | def meth(self, meth_arg1): |
|
1275 | def meth(self, meth_arg1): | |
1271 | print("meth") |
|
1276 | print("meth") | |
1272 |
|
1277 | |||
1273 | def meth_1(self, meth1_arg1, meth1_arg2): |
|
1278 | def meth_1(self, meth1_arg1, meth1_arg2): | |
1274 | print("meth1") |
|
1279 | print("meth1") | |
1275 |
|
1280 | |||
1276 | def meth_2(self, meth2_arg1, meth2_arg2): |
|
1281 | def meth_2(self, meth2_arg1, meth2_arg2): | |
1277 | print("meth2") |
|
1282 | print("meth2") | |
1278 | test = Test() |
|
1283 | test = Test() | |
1279 | """ |
|
1284 | """ | |
1280 | ) |
|
1285 | ) | |
1281 | ) |
|
1286 | ) | |
1282 | _, matches = ip.complete(None, "test.meth(") |
|
1287 | _, matches = ip.complete(None, "test.meth(") | |
1283 | self.assertIn("meth_arg1=", matches) |
|
1288 | self.assertIn("meth_arg1=", matches) | |
1284 | self.assertNotIn("meth2_arg1=", matches) |
|
1289 | self.assertNotIn("meth2_arg1=", matches) |
@@ -1,515 +1,513 b'' | |||||
1 | # Copyright (c) IPython Development Team. |
|
1 | # Copyright (c) IPython Development Team. | |
2 | # Distributed under the terms of the Modified BSD License. |
|
2 | # Distributed under the terms of the Modified BSD License. | |
3 |
|
3 | |||
4 | import json |
|
4 | import json | |
5 | import os |
|
5 | import os | |
6 | import warnings |
|
6 | import warnings | |
7 |
|
7 | |||
8 | from unittest import mock |
|
8 | from unittest import mock | |
9 |
|
9 | |||
10 | import pytest |
|
10 | import pytest | |
11 |
|
11 | |||
12 | from IPython import display |
|
12 | from IPython import display | |
13 | from IPython.core.getipython import get_ipython |
|
13 | from IPython.core.getipython import get_ipython | |
14 | from IPython.utils.io import capture_output |
|
14 | from IPython.utils.io import capture_output | |
15 | from IPython.utils.tempdir import NamedFileInTemporaryDirectory |
|
15 | from IPython.utils.tempdir import NamedFileInTemporaryDirectory | |
16 | from IPython import paths as ipath |
|
16 | from IPython import paths as ipath | |
17 | from IPython.testing.tools import AssertNotPrints |
|
17 | from IPython.testing.tools import AssertNotPrints | |
18 |
|
18 | |||
19 | import IPython.testing.decorators as dec |
|
19 | import IPython.testing.decorators as dec | |
20 |
|
20 | |||
21 | def test_image_size(): |
|
21 | def test_image_size(): | |
22 | """Simple test for display.Image(args, width=x,height=y)""" |
|
22 | """Simple test for display.Image(args, width=x,height=y)""" | |
23 | thisurl = 'http://www.google.fr/images/srpr/logo3w.png' |
|
23 | thisurl = 'http://www.google.fr/images/srpr/logo3w.png' | |
24 | img = display.Image(url=thisurl, width=200, height=200) |
|
24 | img = display.Image(url=thisurl, width=200, height=200) | |
25 | assert '<img src="%s" width="200" height="200"/>' % (thisurl) == img._repr_html_() |
|
25 | assert '<img src="%s" width="200" height="200"/>' % (thisurl) == img._repr_html_() | |
26 | img = display.Image(url=thisurl, metadata={'width':200, 'height':200}) |
|
26 | img = display.Image(url=thisurl, metadata={'width':200, 'height':200}) | |
27 | assert '<img src="%s" width="200" height="200"/>' % (thisurl) == img._repr_html_() |
|
27 | assert '<img src="%s" width="200" height="200"/>' % (thisurl) == img._repr_html_() | |
28 | img = display.Image(url=thisurl, width=200) |
|
28 | img = display.Image(url=thisurl, width=200) | |
29 | assert '<img src="%s" width="200"/>' % (thisurl) == img._repr_html_() |
|
29 | assert '<img src="%s" width="200"/>' % (thisurl) == img._repr_html_() | |
30 | img = display.Image(url=thisurl) |
|
30 | img = display.Image(url=thisurl) | |
31 | assert '<img src="%s"/>' % (thisurl) == img._repr_html_() |
|
31 | assert '<img src="%s"/>' % (thisurl) == img._repr_html_() | |
32 | img = display.Image(url=thisurl, unconfined=True) |
|
32 | img = display.Image(url=thisurl, unconfined=True) | |
33 | assert '<img src="%s" class="unconfined"/>' % (thisurl) == img._repr_html_() |
|
33 | assert '<img src="%s" class="unconfined"/>' % (thisurl) == img._repr_html_() | |
34 |
|
34 | |||
35 |
|
35 | |||
36 | def test_image_mimes(): |
|
36 | def test_image_mimes(): | |
37 | fmt = get_ipython().display_formatter.format |
|
37 | fmt = get_ipython().display_formatter.format | |
38 | for format in display.Image._ACCEPTABLE_EMBEDDINGS: |
|
38 | for format in display.Image._ACCEPTABLE_EMBEDDINGS: | |
39 | mime = display.Image._MIMETYPES[format] |
|
39 | mime = display.Image._MIMETYPES[format] | |
40 | img = display.Image(b'garbage', format=format) |
|
40 | img = display.Image(b'garbage', format=format) | |
41 | data, metadata = fmt(img) |
|
41 | data, metadata = fmt(img) | |
42 | assert sorted(data) == sorted([mime, "text/plain"]) |
|
42 | assert sorted(data) == sorted([mime, "text/plain"]) | |
43 |
|
43 | |||
44 |
|
44 | |||
45 | def test_geojson(): |
|
45 | def test_geojson(): | |
46 |
|
46 | |||
47 | gj = display.GeoJSON(data={ |
|
47 | gj = display.GeoJSON(data={ | |
48 | "type": "Feature", |
|
48 | "type": "Feature", | |
49 | "geometry": { |
|
49 | "geometry": { | |
50 | "type": "Point", |
|
50 | "type": "Point", | |
51 | "coordinates": [-81.327, 296.038] |
|
51 | "coordinates": [-81.327, 296.038] | |
52 | }, |
|
52 | }, | |
53 | "properties": { |
|
53 | "properties": { | |
54 | "name": "Inca City" |
|
54 | "name": "Inca City" | |
55 | } |
|
55 | } | |
56 | }, |
|
56 | }, | |
57 | url_template="http://s3-eu-west-1.amazonaws.com/whereonmars.cartodb.net/{basemap_id}/{z}/{x}/{y}.png", |
|
57 | url_template="http://s3-eu-west-1.amazonaws.com/whereonmars.cartodb.net/{basemap_id}/{z}/{x}/{y}.png", | |
58 | layer_options={ |
|
58 | layer_options={ | |
59 | "basemap_id": "celestia_mars-shaded-16k_global", |
|
59 | "basemap_id": "celestia_mars-shaded-16k_global", | |
60 | "attribution": "Celestia/praesepe", |
|
60 | "attribution": "Celestia/praesepe", | |
61 | "minZoom": 0, |
|
61 | "minZoom": 0, | |
62 | "maxZoom": 18, |
|
62 | "maxZoom": 18, | |
63 | }, |
|
63 | }, | |
64 | ) |
|
64 | ) | |
65 | assert "<IPython.core.display.GeoJSON object>" == str(gj) |
|
65 | assert "<IPython.core.display.GeoJSON object>" == str(gj) | |
66 |
|
66 | |||
67 |
|
67 | |||
68 | def test_retina_png(): |
|
68 | def test_retina_png(): | |
69 | here = os.path.dirname(__file__) |
|
69 | here = os.path.dirname(__file__) | |
70 | img = display.Image(os.path.join(here, "2x2.png"), retina=True) |
|
70 | img = display.Image(os.path.join(here, "2x2.png"), retina=True) | |
71 | assert img.height == 1 |
|
71 | assert img.height == 1 | |
72 | assert img.width == 1 |
|
72 | assert img.width == 1 | |
73 | data, md = img._repr_png_() |
|
73 | data, md = img._repr_png_() | |
74 | assert md["width"] == 1 |
|
74 | assert md["width"] == 1 | |
75 | assert md["height"] == 1 |
|
75 | assert md["height"] == 1 | |
76 |
|
76 | |||
77 |
|
77 | |||
78 | def test_embed_svg_url(): |
|
78 | def test_embed_svg_url(): | |
79 | import gzip |
|
79 | import gzip | |
80 | from io import BytesIO |
|
80 | from io import BytesIO | |
81 | svg_data = b'<svg><circle x="0" y="0" r="1"/></svg>' |
|
81 | svg_data = b'<svg><circle x="0" y="0" r="1"/></svg>' | |
82 | url = 'http://test.com/circle.svg' |
|
82 | url = 'http://test.com/circle.svg' | |
83 |
|
83 | |||
84 | gzip_svg = BytesIO() |
|
84 | gzip_svg = BytesIO() | |
85 | with gzip.open(gzip_svg, 'wb') as fp: |
|
85 | with gzip.open(gzip_svg, 'wb') as fp: | |
86 | fp.write(svg_data) |
|
86 | fp.write(svg_data) | |
87 | gzip_svg = gzip_svg.getvalue() |
|
87 | gzip_svg = gzip_svg.getvalue() | |
88 |
|
88 | |||
89 | def mocked_urlopen(*args, **kwargs): |
|
89 | def mocked_urlopen(*args, **kwargs): | |
90 | class MockResponse: |
|
90 | class MockResponse: | |
91 | def __init__(self, svg): |
|
91 | def __init__(self, svg): | |
92 | self._svg_data = svg |
|
92 | self._svg_data = svg | |
93 | self.headers = {'content-type': 'image/svg+xml'} |
|
93 | self.headers = {'content-type': 'image/svg+xml'} | |
94 |
|
94 | |||
95 | def read(self): |
|
95 | def read(self): | |
96 | return self._svg_data |
|
96 | return self._svg_data | |
97 |
|
97 | |||
98 | if args[0] == url: |
|
98 | if args[0] == url: | |
99 | return MockResponse(svg_data) |
|
99 | return MockResponse(svg_data) | |
100 | elif args[0] == url + "z": |
|
100 | elif args[0] == url + "z": | |
101 | ret = MockResponse(gzip_svg) |
|
101 | ret = MockResponse(gzip_svg) | |
102 | ret.headers["content-encoding"] = "gzip" |
|
102 | ret.headers["content-encoding"] = "gzip" | |
103 | return ret |
|
103 | return ret | |
104 | return MockResponse(None) |
|
104 | return MockResponse(None) | |
105 |
|
105 | |||
106 | with mock.patch('urllib.request.urlopen', side_effect=mocked_urlopen): |
|
106 | with mock.patch('urllib.request.urlopen', side_effect=mocked_urlopen): | |
107 | svg = display.SVG(url=url) |
|
107 | svg = display.SVG(url=url) | |
108 | assert svg._repr_svg_().startswith("<svg") is True |
|
108 | assert svg._repr_svg_().startswith("<svg") is True | |
109 | svg = display.SVG(url=url + "z") |
|
109 | svg = display.SVG(url=url + "z") | |
110 | assert svg._repr_svg_().startswith("<svg") is True |
|
110 | assert svg._repr_svg_().startswith("<svg") is True | |
111 |
|
111 | |||
112 |
|
112 | |||
113 | def test_retina_jpeg(): |
|
113 | def test_retina_jpeg(): | |
114 | here = os.path.dirname(__file__) |
|
114 | here = os.path.dirname(__file__) | |
115 | img = display.Image(os.path.join(here, "2x2.jpg"), retina=True) |
|
115 | img = display.Image(os.path.join(here, "2x2.jpg"), retina=True) | |
116 | assert img.height == 1 |
|
116 | assert img.height == 1 | |
117 | assert img.width == 1 |
|
117 | assert img.width == 1 | |
118 | data, md = img._repr_jpeg_() |
|
118 | data, md = img._repr_jpeg_() | |
119 | assert md["width"] == 1 |
|
119 | assert md["width"] == 1 | |
120 | assert md["height"] == 1 |
|
120 | assert md["height"] == 1 | |
121 |
|
121 | |||
122 |
|
122 | |||
123 | def test_base64image(): |
|
123 | def test_base64image(): | |
124 | display.Image("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB94BCRQnOqNu0b4AAAAKSURBVAjXY2AAAAACAAHiIbwzAAAAAElFTkSuQmCC") |
|
124 | display.Image("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB94BCRQnOqNu0b4AAAAKSURBVAjXY2AAAAACAAHiIbwzAAAAAElFTkSuQmCC") | |
125 |
|
125 | |||
126 | def test_image_filename_defaults(): |
|
126 | def test_image_filename_defaults(): | |
127 | '''test format constraint, and validity of jpeg and png''' |
|
127 | '''test format constraint, and validity of jpeg and png''' | |
128 | tpath = ipath.get_ipython_package_dir() |
|
128 | tpath = ipath.get_ipython_package_dir() | |
129 | pytest.raises( |
|
129 | pytest.raises( | |
130 | ValueError, |
|
130 | ValueError, | |
131 | display.Image, |
|
131 | display.Image, | |
132 | filename=os.path.join(tpath, "testing/tests/badformat.zip"), |
|
132 | filename=os.path.join(tpath, "testing/tests/badformat.zip"), | |
133 | embed=True, |
|
133 | embed=True, | |
134 | ) |
|
134 | ) | |
135 | pytest.raises(ValueError, display.Image) |
|
135 | pytest.raises(ValueError, display.Image) | |
136 | pytest.raises( |
|
136 | pytest.raises( | |
137 | ValueError, |
|
137 | ValueError, | |
138 | display.Image, |
|
138 | display.Image, | |
139 | data="this is not an image", |
|
139 | data="this is not an image", | |
140 | format="badformat", |
|
140 | format="badformat", | |
141 | embed=True, |
|
141 | embed=True, | |
142 | ) |
|
142 | ) | |
143 | # check boths paths to allow packages to test at build and install time |
|
143 | # check boths paths to allow packages to test at build and install time | |
144 | imgfile = os.path.join(tpath, 'core/tests/2x2.png') |
|
144 | imgfile = os.path.join(tpath, 'core/tests/2x2.png') | |
145 | img = display.Image(filename=imgfile) |
|
145 | img = display.Image(filename=imgfile) | |
146 | assert "png" == img.format |
|
146 | assert "png" == img.format | |
147 | assert img._repr_png_() is not None |
|
147 | assert img._repr_png_() is not None | |
148 | img = display.Image( |
|
148 | img = display.Image( | |
149 | filename=os.path.join(tpath, "testing/tests/logo.jpg"), embed=False |
|
149 | filename=os.path.join(tpath, "testing/tests/logo.jpg"), embed=False | |
150 | ) |
|
150 | ) | |
151 | assert "jpeg" == img.format |
|
151 | assert "jpeg" == img.format | |
152 | assert img._repr_jpeg_() is None |
|
152 | assert img._repr_jpeg_() is None | |
153 |
|
153 | |||
154 | def _get_inline_config(): |
|
154 | def _get_inline_config(): | |
155 | from matplotlib_inline.config import InlineBackend |
|
155 | from matplotlib_inline.config import InlineBackend | |
156 | return InlineBackend.instance() |
|
156 | return InlineBackend.instance() | |
157 |
|
157 | |||
158 |
|
158 | |||
159 | @dec.skip_without("ipykernel") |
|
|||
160 | @dec.skip_without("matplotlib") |
|
159 | @dec.skip_without("matplotlib") | |
161 | def test_set_matplotlib_close(): |
|
160 | def test_set_matplotlib_close(): | |
162 | cfg = _get_inline_config() |
|
161 | cfg = _get_inline_config() | |
163 | cfg.close_figures = False |
|
162 | cfg.close_figures = False | |
164 | with pytest.deprecated_call(): |
|
163 | with pytest.deprecated_call(): | |
165 | display.set_matplotlib_close() |
|
164 | display.set_matplotlib_close() | |
166 | assert cfg.close_figures |
|
165 | assert cfg.close_figures | |
167 | with pytest.deprecated_call(): |
|
166 | with pytest.deprecated_call(): | |
168 | display.set_matplotlib_close(False) |
|
167 | display.set_matplotlib_close(False) | |
169 | assert not cfg.close_figures |
|
168 | assert not cfg.close_figures | |
170 |
|
169 | |||
171 | _fmt_mime_map = { |
|
170 | _fmt_mime_map = { | |
172 | 'png': 'image/png', |
|
171 | 'png': 'image/png', | |
173 | 'jpeg': 'image/jpeg', |
|
172 | 'jpeg': 'image/jpeg', | |
174 | 'pdf': 'application/pdf', |
|
173 | 'pdf': 'application/pdf', | |
175 | 'retina': 'image/png', |
|
174 | 'retina': 'image/png', | |
176 | 'svg': 'image/svg+xml', |
|
175 | 'svg': 'image/svg+xml', | |
177 | } |
|
176 | } | |
178 |
|
177 | |||
179 | @dec.skip_without('matplotlib') |
|
178 | @dec.skip_without('matplotlib') | |
180 | def test_set_matplotlib_formats(): |
|
179 | def test_set_matplotlib_formats(): | |
181 | from matplotlib.figure import Figure |
|
180 | from matplotlib.figure import Figure | |
182 | formatters = get_ipython().display_formatter.formatters |
|
181 | formatters = get_ipython().display_formatter.formatters | |
183 | for formats in [ |
|
182 | for formats in [ | |
184 | ('png',), |
|
183 | ('png',), | |
185 | ('pdf', 'svg'), |
|
184 | ('pdf', 'svg'), | |
186 | ('jpeg', 'retina', 'png'), |
|
185 | ('jpeg', 'retina', 'png'), | |
187 | (), |
|
186 | (), | |
188 | ]: |
|
187 | ]: | |
189 | active_mimes = {_fmt_mime_map[fmt] for fmt in formats} |
|
188 | active_mimes = {_fmt_mime_map[fmt] for fmt in formats} | |
190 | with pytest.deprecated_call(): |
|
189 | with pytest.deprecated_call(): | |
191 | display.set_matplotlib_formats(*formats) |
|
190 | display.set_matplotlib_formats(*formats) | |
192 | for mime, f in formatters.items(): |
|
191 | for mime, f in formatters.items(): | |
193 | if mime in active_mimes: |
|
192 | if mime in active_mimes: | |
194 | assert Figure in f |
|
193 | assert Figure in f | |
195 | else: |
|
194 | else: | |
196 | assert Figure not in f |
|
195 | assert Figure not in f | |
197 |
|
196 | |||
198 |
|
197 | |||
199 | @dec.skip_without("ipykernel") |
|
|||
200 | @dec.skip_without("matplotlib") |
|
198 | @dec.skip_without("matplotlib") | |
201 | def test_set_matplotlib_formats_kwargs(): |
|
199 | def test_set_matplotlib_formats_kwargs(): | |
202 | from matplotlib.figure import Figure |
|
200 | from matplotlib.figure import Figure | |
203 | ip = get_ipython() |
|
201 | ip = get_ipython() | |
204 | cfg = _get_inline_config() |
|
202 | cfg = _get_inline_config() | |
205 | cfg.print_figure_kwargs.update(dict(foo='bar')) |
|
203 | cfg.print_figure_kwargs.update(dict(foo='bar')) | |
206 | kwargs = dict(dpi=150) |
|
204 | kwargs = dict(dpi=150) | |
207 | with pytest.deprecated_call(): |
|
205 | with pytest.deprecated_call(): | |
208 | display.set_matplotlib_formats("png", **kwargs) |
|
206 | display.set_matplotlib_formats("png", **kwargs) | |
209 | formatter = ip.display_formatter.formatters["image/png"] |
|
207 | formatter = ip.display_formatter.formatters["image/png"] | |
210 | f = formatter.lookup_by_type(Figure) |
|
208 | f = formatter.lookup_by_type(Figure) | |
211 | formatter_kwargs = f.keywords |
|
209 | formatter_kwargs = f.keywords | |
212 | expected = kwargs |
|
210 | expected = kwargs | |
213 | expected["base64"] = True |
|
211 | expected["base64"] = True | |
214 | expected["fmt"] = "png" |
|
212 | expected["fmt"] = "png" | |
215 | expected.update(cfg.print_figure_kwargs) |
|
213 | expected.update(cfg.print_figure_kwargs) | |
216 | assert formatter_kwargs == expected |
|
214 | assert formatter_kwargs == expected | |
217 |
|
215 | |||
218 | def test_display_available(): |
|
216 | def test_display_available(): | |
219 | """ |
|
217 | """ | |
220 | Test that display is available without import |
|
218 | Test that display is available without import | |
221 |
|
219 | |||
222 | We don't really care if it's in builtin or anything else, but it should |
|
220 | We don't really care if it's in builtin or anything else, but it should | |
223 | always be available. |
|
221 | always be available. | |
224 | """ |
|
222 | """ | |
225 | ip = get_ipython() |
|
223 | ip = get_ipython() | |
226 | with AssertNotPrints('NameError'): |
|
224 | with AssertNotPrints('NameError'): | |
227 | ip.run_cell('display') |
|
225 | ip.run_cell('display') | |
228 | try: |
|
226 | try: | |
229 | ip.run_cell('del display') |
|
227 | ip.run_cell('del display') | |
230 | except NameError: |
|
228 | except NameError: | |
231 | pass # it's ok, it might be in builtins |
|
229 | pass # it's ok, it might be in builtins | |
232 | # even if deleted it should be back |
|
230 | # even if deleted it should be back | |
233 | with AssertNotPrints('NameError'): |
|
231 | with AssertNotPrints('NameError'): | |
234 | ip.run_cell('display') |
|
232 | ip.run_cell('display') | |
235 |
|
233 | |||
236 | def test_textdisplayobj_pretty_repr(): |
|
234 | def test_textdisplayobj_pretty_repr(): | |
237 | p = display.Pretty("This is a simple test") |
|
235 | p = display.Pretty("This is a simple test") | |
238 | assert repr(p) == "<IPython.core.display.Pretty object>" |
|
236 | assert repr(p) == "<IPython.core.display.Pretty object>" | |
239 | assert p.data == "This is a simple test" |
|
237 | assert p.data == "This is a simple test" | |
240 |
|
238 | |||
241 | p._show_mem_addr = True |
|
239 | p._show_mem_addr = True | |
242 | assert repr(p) == object.__repr__(p) |
|
240 | assert repr(p) == object.__repr__(p) | |
243 |
|
241 | |||
244 |
|
242 | |||
245 | def test_displayobject_repr(): |
|
243 | def test_displayobject_repr(): | |
246 | h = display.HTML("<br />") |
|
244 | h = display.HTML("<br />") | |
247 | assert repr(h) == "<IPython.core.display.HTML object>" |
|
245 | assert repr(h) == "<IPython.core.display.HTML object>" | |
248 | h._show_mem_addr = True |
|
246 | h._show_mem_addr = True | |
249 | assert repr(h) == object.__repr__(h) |
|
247 | assert repr(h) == object.__repr__(h) | |
250 | h._show_mem_addr = False |
|
248 | h._show_mem_addr = False | |
251 | assert repr(h) == "<IPython.core.display.HTML object>" |
|
249 | assert repr(h) == "<IPython.core.display.HTML object>" | |
252 |
|
250 | |||
253 | j = display.Javascript("") |
|
251 | j = display.Javascript("") | |
254 | assert repr(j) == "<IPython.core.display.Javascript object>" |
|
252 | assert repr(j) == "<IPython.core.display.Javascript object>" | |
255 | j._show_mem_addr = True |
|
253 | j._show_mem_addr = True | |
256 | assert repr(j) == object.__repr__(j) |
|
254 | assert repr(j) == object.__repr__(j) | |
257 | j._show_mem_addr = False |
|
255 | j._show_mem_addr = False | |
258 | assert repr(j) == "<IPython.core.display.Javascript object>" |
|
256 | assert repr(j) == "<IPython.core.display.Javascript object>" | |
259 |
|
257 | |||
260 | @mock.patch('warnings.warn') |
|
258 | @mock.patch('warnings.warn') | |
261 | def test_encourage_iframe_over_html(m_warn): |
|
259 | def test_encourage_iframe_over_html(m_warn): | |
262 | display.HTML() |
|
260 | display.HTML() | |
263 | m_warn.assert_not_called() |
|
261 | m_warn.assert_not_called() | |
264 |
|
262 | |||
265 | display.HTML('<br />') |
|
263 | display.HTML('<br />') | |
266 | m_warn.assert_not_called() |
|
264 | m_warn.assert_not_called() | |
267 |
|
265 | |||
268 | display.HTML('<html><p>Lots of content here</p><iframe src="http://a.com"></iframe>') |
|
266 | display.HTML('<html><p>Lots of content here</p><iframe src="http://a.com"></iframe>') | |
269 | m_warn.assert_not_called() |
|
267 | m_warn.assert_not_called() | |
270 |
|
268 | |||
271 | display.HTML('<iframe src="http://a.com"></iframe>') |
|
269 | display.HTML('<iframe src="http://a.com"></iframe>') | |
272 | m_warn.assert_called_with('Consider using IPython.display.IFrame instead') |
|
270 | m_warn.assert_called_with('Consider using IPython.display.IFrame instead') | |
273 |
|
271 | |||
274 | m_warn.reset_mock() |
|
272 | m_warn.reset_mock() | |
275 | display.HTML('<IFRAME SRC="http://a.com"></IFRAME>') |
|
273 | display.HTML('<IFRAME SRC="http://a.com"></IFRAME>') | |
276 | m_warn.assert_called_with('Consider using IPython.display.IFrame instead') |
|
274 | m_warn.assert_called_with('Consider using IPython.display.IFrame instead') | |
277 |
|
275 | |||
278 | def test_progress(): |
|
276 | def test_progress(): | |
279 | p = display.ProgressBar(10) |
|
277 | p = display.ProgressBar(10) | |
280 | assert "0/10" in repr(p) |
|
278 | assert "0/10" in repr(p) | |
281 | p.html_width = "100%" |
|
279 | p.html_width = "100%" | |
282 | p.progress = 5 |
|
280 | p.progress = 5 | |
283 | assert ( |
|
281 | assert ( | |
284 | p._repr_html_() == "<progress style='width:100%' max='10' value='5'></progress>" |
|
282 | p._repr_html_() == "<progress style='width:100%' max='10' value='5'></progress>" | |
285 | ) |
|
283 | ) | |
286 |
|
284 | |||
287 |
|
285 | |||
288 | def test_progress_iter(): |
|
286 | def test_progress_iter(): | |
289 | with capture_output(display=False) as captured: |
|
287 | with capture_output(display=False) as captured: | |
290 | for i in display.ProgressBar(5): |
|
288 | for i in display.ProgressBar(5): | |
291 | out = captured.stdout |
|
289 | out = captured.stdout | |
292 | assert "{0}/5".format(i) in out |
|
290 | assert "{0}/5".format(i) in out | |
293 | out = captured.stdout |
|
291 | out = captured.stdout | |
294 | assert "5/5" in out |
|
292 | assert "5/5" in out | |
295 |
|
293 | |||
296 |
|
294 | |||
297 | def test_json(): |
|
295 | def test_json(): | |
298 | d = {'a': 5} |
|
296 | d = {'a': 5} | |
299 | lis = [d] |
|
297 | lis = [d] | |
300 | metadata = [ |
|
298 | metadata = [ | |
301 | {'expanded': False, 'root': 'root'}, |
|
299 | {'expanded': False, 'root': 'root'}, | |
302 | {'expanded': True, 'root': 'root'}, |
|
300 | {'expanded': True, 'root': 'root'}, | |
303 | {'expanded': False, 'root': 'custom'}, |
|
301 | {'expanded': False, 'root': 'custom'}, | |
304 | {'expanded': True, 'root': 'custom'}, |
|
302 | {'expanded': True, 'root': 'custom'}, | |
305 | ] |
|
303 | ] | |
306 | json_objs = [ |
|
304 | json_objs = [ | |
307 | display.JSON(d), |
|
305 | display.JSON(d), | |
308 | display.JSON(d, expanded=True), |
|
306 | display.JSON(d, expanded=True), | |
309 | display.JSON(d, root='custom'), |
|
307 | display.JSON(d, root='custom'), | |
310 | display.JSON(d, expanded=True, root='custom'), |
|
308 | display.JSON(d, expanded=True, root='custom'), | |
311 | ] |
|
309 | ] | |
312 | for j, md in zip(json_objs, metadata): |
|
310 | for j, md in zip(json_objs, metadata): | |
313 | assert j._repr_json_() == (d, md) |
|
311 | assert j._repr_json_() == (d, md) | |
314 |
|
312 | |||
315 | with warnings.catch_warnings(record=True) as w: |
|
313 | with warnings.catch_warnings(record=True) as w: | |
316 | warnings.simplefilter("always") |
|
314 | warnings.simplefilter("always") | |
317 | j = display.JSON(json.dumps(d)) |
|
315 | j = display.JSON(json.dumps(d)) | |
318 | assert len(w) == 1 |
|
316 | assert len(w) == 1 | |
319 | assert j._repr_json_() == (d, metadata[0]) |
|
317 | assert j._repr_json_() == (d, metadata[0]) | |
320 |
|
318 | |||
321 | json_objs = [ |
|
319 | json_objs = [ | |
322 | display.JSON(lis), |
|
320 | display.JSON(lis), | |
323 | display.JSON(lis, expanded=True), |
|
321 | display.JSON(lis, expanded=True), | |
324 | display.JSON(lis, root='custom'), |
|
322 | display.JSON(lis, root='custom'), | |
325 | display.JSON(lis, expanded=True, root='custom'), |
|
323 | display.JSON(lis, expanded=True, root='custom'), | |
326 | ] |
|
324 | ] | |
327 | for j, md in zip(json_objs, metadata): |
|
325 | for j, md in zip(json_objs, metadata): | |
328 | assert j._repr_json_() == (lis, md) |
|
326 | assert j._repr_json_() == (lis, md) | |
329 |
|
327 | |||
330 | with warnings.catch_warnings(record=True) as w: |
|
328 | with warnings.catch_warnings(record=True) as w: | |
331 | warnings.simplefilter("always") |
|
329 | warnings.simplefilter("always") | |
332 | j = display.JSON(json.dumps(lis)) |
|
330 | j = display.JSON(json.dumps(lis)) | |
333 | assert len(w) == 1 |
|
331 | assert len(w) == 1 | |
334 | assert j._repr_json_() == (lis, metadata[0]) |
|
332 | assert j._repr_json_() == (lis, metadata[0]) | |
335 |
|
333 | |||
336 |
|
334 | |||
337 | def test_video_embedding(): |
|
335 | def test_video_embedding(): | |
338 | """use a tempfile, with dummy-data, to ensure that video embedding doesn't crash""" |
|
336 | """use a tempfile, with dummy-data, to ensure that video embedding doesn't crash""" | |
339 | v = display.Video("http://ignored") |
|
337 | v = display.Video("http://ignored") | |
340 | assert not v.embed |
|
338 | assert not v.embed | |
341 | html = v._repr_html_() |
|
339 | html = v._repr_html_() | |
342 | assert 'src="data:' not in html |
|
340 | assert 'src="data:' not in html | |
343 | assert 'src="http://ignored"' in html |
|
341 | assert 'src="http://ignored"' in html | |
344 |
|
342 | |||
345 | with pytest.raises(ValueError): |
|
343 | with pytest.raises(ValueError): | |
346 | v = display.Video(b'abc') |
|
344 | v = display.Video(b'abc') | |
347 |
|
345 | |||
348 | with NamedFileInTemporaryDirectory('test.mp4') as f: |
|
346 | with NamedFileInTemporaryDirectory('test.mp4') as f: | |
349 | f.write(b'abc') |
|
347 | f.write(b'abc') | |
350 | f.close() |
|
348 | f.close() | |
351 |
|
349 | |||
352 | v = display.Video(f.name) |
|
350 | v = display.Video(f.name) | |
353 | assert not v.embed |
|
351 | assert not v.embed | |
354 | html = v._repr_html_() |
|
352 | html = v._repr_html_() | |
355 | assert 'src="data:' not in html |
|
353 | assert 'src="data:' not in html | |
356 |
|
354 | |||
357 | v = display.Video(f.name, embed=True) |
|
355 | v = display.Video(f.name, embed=True) | |
358 | html = v._repr_html_() |
|
356 | html = v._repr_html_() | |
359 | assert 'src="data:video/mp4;base64,YWJj"' in html |
|
357 | assert 'src="data:video/mp4;base64,YWJj"' in html | |
360 |
|
358 | |||
361 | v = display.Video(f.name, embed=True, mimetype='video/other') |
|
359 | v = display.Video(f.name, embed=True, mimetype='video/other') | |
362 | html = v._repr_html_() |
|
360 | html = v._repr_html_() | |
363 | assert 'src="data:video/other;base64,YWJj"' in html |
|
361 | assert 'src="data:video/other;base64,YWJj"' in html | |
364 |
|
362 | |||
365 | v = display.Video(b'abc', embed=True, mimetype='video/mp4') |
|
363 | v = display.Video(b'abc', embed=True, mimetype='video/mp4') | |
366 | html = v._repr_html_() |
|
364 | html = v._repr_html_() | |
367 | assert 'src="data:video/mp4;base64,YWJj"' in html |
|
365 | assert 'src="data:video/mp4;base64,YWJj"' in html | |
368 |
|
366 | |||
369 | v = display.Video(u'YWJj', embed=True, mimetype='video/xyz') |
|
367 | v = display.Video(u'YWJj', embed=True, mimetype='video/xyz') | |
370 | html = v._repr_html_() |
|
368 | html = v._repr_html_() | |
371 | assert 'src="data:video/xyz;base64,YWJj"' in html |
|
369 | assert 'src="data:video/xyz;base64,YWJj"' in html | |
372 |
|
370 | |||
373 | def test_html_metadata(): |
|
371 | def test_html_metadata(): | |
374 | s = "<h1>Test</h1>" |
|
372 | s = "<h1>Test</h1>" | |
375 | h = display.HTML(s, metadata={"isolated": True}) |
|
373 | h = display.HTML(s, metadata={"isolated": True}) | |
376 | assert h._repr_html_() == (s, {"isolated": True}) |
|
374 | assert h._repr_html_() == (s, {"isolated": True}) | |
377 |
|
375 | |||
378 |
|
376 | |||
379 | def test_display_id(): |
|
377 | def test_display_id(): | |
380 | ip = get_ipython() |
|
378 | ip = get_ipython() | |
381 | with mock.patch.object(ip.display_pub, 'publish') as pub: |
|
379 | with mock.patch.object(ip.display_pub, 'publish') as pub: | |
382 | handle = display.display('x') |
|
380 | handle = display.display('x') | |
383 | assert handle is None |
|
381 | assert handle is None | |
384 | handle = display.display('y', display_id='secret') |
|
382 | handle = display.display('y', display_id='secret') | |
385 | assert isinstance(handle, display.DisplayHandle) |
|
383 | assert isinstance(handle, display.DisplayHandle) | |
386 | handle2 = display.display('z', display_id=True) |
|
384 | handle2 = display.display('z', display_id=True) | |
387 | assert isinstance(handle2, display.DisplayHandle) |
|
385 | assert isinstance(handle2, display.DisplayHandle) | |
388 | assert handle.display_id != handle2.display_id |
|
386 | assert handle.display_id != handle2.display_id | |
389 |
|
387 | |||
390 | assert pub.call_count == 3 |
|
388 | assert pub.call_count == 3 | |
391 | args, kwargs = pub.call_args_list[0] |
|
389 | args, kwargs = pub.call_args_list[0] | |
392 | assert args == () |
|
390 | assert args == () | |
393 | assert kwargs == { |
|
391 | assert kwargs == { | |
394 | 'data': { |
|
392 | 'data': { | |
395 | 'text/plain': repr('x') |
|
393 | 'text/plain': repr('x') | |
396 | }, |
|
394 | }, | |
397 | 'metadata': {}, |
|
395 | 'metadata': {}, | |
398 | } |
|
396 | } | |
399 | args, kwargs = pub.call_args_list[1] |
|
397 | args, kwargs = pub.call_args_list[1] | |
400 | assert args == () |
|
398 | assert args == () | |
401 | assert kwargs == { |
|
399 | assert kwargs == { | |
402 | 'data': { |
|
400 | 'data': { | |
403 | 'text/plain': repr('y') |
|
401 | 'text/plain': repr('y') | |
404 | }, |
|
402 | }, | |
405 | 'metadata': {}, |
|
403 | 'metadata': {}, | |
406 | 'transient': { |
|
404 | 'transient': { | |
407 | 'display_id': handle.display_id, |
|
405 | 'display_id': handle.display_id, | |
408 | }, |
|
406 | }, | |
409 | } |
|
407 | } | |
410 | args, kwargs = pub.call_args_list[2] |
|
408 | args, kwargs = pub.call_args_list[2] | |
411 | assert args == () |
|
409 | assert args == () | |
412 | assert kwargs == { |
|
410 | assert kwargs == { | |
413 | 'data': { |
|
411 | 'data': { | |
414 | 'text/plain': repr('z') |
|
412 | 'text/plain': repr('z') | |
415 | }, |
|
413 | }, | |
416 | 'metadata': {}, |
|
414 | 'metadata': {}, | |
417 | 'transient': { |
|
415 | 'transient': { | |
418 | 'display_id': handle2.display_id, |
|
416 | 'display_id': handle2.display_id, | |
419 | }, |
|
417 | }, | |
420 | } |
|
418 | } | |
421 |
|
419 | |||
422 |
|
420 | |||
423 | def test_update_display(): |
|
421 | def test_update_display(): | |
424 | ip = get_ipython() |
|
422 | ip = get_ipython() | |
425 | with mock.patch.object(ip.display_pub, 'publish') as pub: |
|
423 | with mock.patch.object(ip.display_pub, 'publish') as pub: | |
426 | with pytest.raises(TypeError): |
|
424 | with pytest.raises(TypeError): | |
427 | display.update_display('x') |
|
425 | display.update_display('x') | |
428 | display.update_display('x', display_id='1') |
|
426 | display.update_display('x', display_id='1') | |
429 | display.update_display('y', display_id='2') |
|
427 | display.update_display('y', display_id='2') | |
430 | args, kwargs = pub.call_args_list[0] |
|
428 | args, kwargs = pub.call_args_list[0] | |
431 | assert args == () |
|
429 | assert args == () | |
432 | assert kwargs == { |
|
430 | assert kwargs == { | |
433 | 'data': { |
|
431 | 'data': { | |
434 | 'text/plain': repr('x') |
|
432 | 'text/plain': repr('x') | |
435 | }, |
|
433 | }, | |
436 | 'metadata': {}, |
|
434 | 'metadata': {}, | |
437 | 'transient': { |
|
435 | 'transient': { | |
438 | 'display_id': '1', |
|
436 | 'display_id': '1', | |
439 | }, |
|
437 | }, | |
440 | 'update': True, |
|
438 | 'update': True, | |
441 | } |
|
439 | } | |
442 | args, kwargs = pub.call_args_list[1] |
|
440 | args, kwargs = pub.call_args_list[1] | |
443 | assert args == () |
|
441 | assert args == () | |
444 | assert kwargs == { |
|
442 | assert kwargs == { | |
445 | 'data': { |
|
443 | 'data': { | |
446 | 'text/plain': repr('y') |
|
444 | 'text/plain': repr('y') | |
447 | }, |
|
445 | }, | |
448 | 'metadata': {}, |
|
446 | 'metadata': {}, | |
449 | 'transient': { |
|
447 | 'transient': { | |
450 | 'display_id': '2', |
|
448 | 'display_id': '2', | |
451 | }, |
|
449 | }, | |
452 | 'update': True, |
|
450 | 'update': True, | |
453 | } |
|
451 | } | |
454 |
|
452 | |||
455 |
|
453 | |||
456 | def test_display_handle(): |
|
454 | def test_display_handle(): | |
457 | ip = get_ipython() |
|
455 | ip = get_ipython() | |
458 | handle = display.DisplayHandle() |
|
456 | handle = display.DisplayHandle() | |
459 | assert isinstance(handle.display_id, str) |
|
457 | assert isinstance(handle.display_id, str) | |
460 | handle = display.DisplayHandle("my-id") |
|
458 | handle = display.DisplayHandle("my-id") | |
461 | assert handle.display_id == "my-id" |
|
459 | assert handle.display_id == "my-id" | |
462 | with mock.patch.object(ip.display_pub, "publish") as pub: |
|
460 | with mock.patch.object(ip.display_pub, "publish") as pub: | |
463 | handle.display("x") |
|
461 | handle.display("x") | |
464 | handle.update("y") |
|
462 | handle.update("y") | |
465 |
|
463 | |||
466 | args, kwargs = pub.call_args_list[0] |
|
464 | args, kwargs = pub.call_args_list[0] | |
467 | assert args == () |
|
465 | assert args == () | |
468 | assert kwargs == { |
|
466 | assert kwargs == { | |
469 | 'data': { |
|
467 | 'data': { | |
470 | 'text/plain': repr('x') |
|
468 | 'text/plain': repr('x') | |
471 | }, |
|
469 | }, | |
472 | 'metadata': {}, |
|
470 | 'metadata': {}, | |
473 | 'transient': { |
|
471 | 'transient': { | |
474 | 'display_id': handle.display_id, |
|
472 | 'display_id': handle.display_id, | |
475 | } |
|
473 | } | |
476 | } |
|
474 | } | |
477 | args, kwargs = pub.call_args_list[1] |
|
475 | args, kwargs = pub.call_args_list[1] | |
478 | assert args == () |
|
476 | assert args == () | |
479 | assert kwargs == { |
|
477 | assert kwargs == { | |
480 | 'data': { |
|
478 | 'data': { | |
481 | 'text/plain': repr('y') |
|
479 | 'text/plain': repr('y') | |
482 | }, |
|
480 | }, | |
483 | 'metadata': {}, |
|
481 | 'metadata': {}, | |
484 | 'transient': { |
|
482 | 'transient': { | |
485 | 'display_id': handle.display_id, |
|
483 | 'display_id': handle.display_id, | |
486 | }, |
|
484 | }, | |
487 | 'update': True, |
|
485 | 'update': True, | |
488 | } |
|
486 | } | |
489 |
|
487 | |||
490 |
|
488 | |||
491 | def test_image_alt_tag(): |
|
489 | def test_image_alt_tag(): | |
492 | """Simple test for display.Image(args, alt=x,)""" |
|
490 | """Simple test for display.Image(args, alt=x,)""" | |
493 | thisurl = "http://example.com/image.png" |
|
491 | thisurl = "http://example.com/image.png" | |
494 | img = display.Image(url=thisurl, alt="an image") |
|
492 | img = display.Image(url=thisurl, alt="an image") | |
495 | assert '<img src="%s" alt="an image"/>' % (thisurl) == img._repr_html_() |
|
493 | assert '<img src="%s" alt="an image"/>' % (thisurl) == img._repr_html_() | |
496 | img = display.Image(url=thisurl, unconfined=True, alt="an image") |
|
494 | img = display.Image(url=thisurl, unconfined=True, alt="an image") | |
497 | assert ( |
|
495 | assert ( | |
498 | '<img src="%s" class="unconfined" alt="an image"/>' % (thisurl) |
|
496 | '<img src="%s" class="unconfined" alt="an image"/>' % (thisurl) | |
499 | == img._repr_html_() |
|
497 | == img._repr_html_() | |
500 | ) |
|
498 | ) | |
501 | img = display.Image(url=thisurl, alt='>"& <') |
|
499 | img = display.Image(url=thisurl, alt='>"& <') | |
502 | assert '<img src="%s" alt=">"& <"/>' % (thisurl) == img._repr_html_() |
|
500 | assert '<img src="%s" alt=">"& <"/>' % (thisurl) == img._repr_html_() | |
503 |
|
501 | |||
504 | img = display.Image(url=thisurl, metadata={"alt": "an image"}) |
|
502 | img = display.Image(url=thisurl, metadata={"alt": "an image"}) | |
505 | assert img.alt == "an image" |
|
503 | assert img.alt == "an image" | |
506 | here = os.path.dirname(__file__) |
|
504 | here = os.path.dirname(__file__) | |
507 | img = display.Image(os.path.join(here, "2x2.png"), alt="an image") |
|
505 | img = display.Image(os.path.join(here, "2x2.png"), alt="an image") | |
508 | assert img.alt == "an image" |
|
506 | assert img.alt == "an image" | |
509 | _, md = img._repr_png_() |
|
507 | _, md = img._repr_png_() | |
510 | assert md["alt"] == "an image" |
|
508 | assert md["alt"] == "an image" | |
511 |
|
509 | |||
512 |
|
510 | |||
513 | def test_image_bad_filename_raises_proper_exception(): |
|
511 | def test_image_bad_filename_raises_proper_exception(): | |
514 | with pytest.raises(FileNotFoundError): |
|
512 | with pytest.raises(FileNotFoundError): | |
515 | display.Image("/this/file/does/not/exist/")._repr_png_() |
|
513 | display.Image("/this/file/does/not/exist/")._repr_png_() |
@@ -1,636 +1,641 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Tests for the inputsplitter module.""" |
|
2 | """Tests for the inputsplitter module.""" | |
3 |
|
3 | |||
4 |
|
4 | |||
5 | # Copyright (c) IPython Development Team. |
|
5 | # Copyright (c) IPython Development Team. | |
6 | # Distributed under the terms of the Modified BSD License. |
|
6 | # Distributed under the terms of the Modified BSD License. | |
7 |
|
7 | |||
8 | import unittest |
|
8 | import unittest | |
|
9 | import pytest | |||
9 | import sys |
|
10 | import sys | |
10 |
|
11 | |||
11 | from IPython.core import inputsplitter as isp |
|
12 | from IPython.core import inputsplitter as isp | |
12 | from IPython.core.inputtransformer import InputTransformer |
|
13 | from IPython.core.inputtransformer import InputTransformer | |
13 | from IPython.core.tests.test_inputtransformer import syntax, syntax_ml |
|
14 | from IPython.core.tests.test_inputtransformer import syntax, syntax_ml | |
14 | from IPython.testing import tools as tt |
|
15 | from IPython.testing import tools as tt | |
15 | from IPython.testing.decorators import skipif |
|
|||
16 |
|
16 | |||
17 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
18 | # Semi-complete examples (also used as tests) |
|
18 | # Semi-complete examples (also used as tests) | |
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 |
|
20 | |||
21 | # Note: at the bottom, there's a slightly more complete version of this that |
|
21 | # Note: at the bottom, there's a slightly more complete version of this that | |
22 | # can be useful during development of code here. |
|
22 | # can be useful during development of code here. | |
23 |
|
23 | |||
24 | def mini_interactive_loop(input_func): |
|
24 | def mini_interactive_loop(input_func): | |
25 | """Minimal example of the logic of an interactive interpreter loop. |
|
25 | """Minimal example of the logic of an interactive interpreter loop. | |
26 |
|
26 | |||
27 | This serves as an example, and it is used by the test system with a fake |
|
27 | This serves as an example, and it is used by the test system with a fake | |
28 | raw_input that simulates interactive input.""" |
|
28 | raw_input that simulates interactive input.""" | |
29 |
|
29 | |||
30 | from IPython.core.inputsplitter import InputSplitter |
|
30 | from IPython.core.inputsplitter import InputSplitter | |
31 |
|
31 | |||
32 | isp = InputSplitter() |
|
32 | isp = InputSplitter() | |
33 | # In practice, this input loop would be wrapped in an outside loop to read |
|
33 | # In practice, this input loop would be wrapped in an outside loop to read | |
34 | # input indefinitely, until some exit/quit command was issued. Here we |
|
34 | # input indefinitely, until some exit/quit command was issued. Here we | |
35 | # only illustrate the basic inner loop. |
|
35 | # only illustrate the basic inner loop. | |
36 | while isp.push_accepts_more(): |
|
36 | while isp.push_accepts_more(): | |
37 | indent = ' '*isp.get_indent_spaces() |
|
37 | indent = ' '*isp.get_indent_spaces() | |
38 | prompt = '>>> ' + indent |
|
38 | prompt = '>>> ' + indent | |
39 | line = indent + input_func(prompt) |
|
39 | line = indent + input_func(prompt) | |
40 | isp.push(line) |
|
40 | isp.push(line) | |
41 |
|
41 | |||
42 | # Here we just return input so we can use it in a test suite, but a real |
|
42 | # Here we just return input so we can use it in a test suite, but a real | |
43 | # interpreter would instead send it for execution somewhere. |
|
43 | # interpreter would instead send it for execution somewhere. | |
44 | src = isp.source_reset() |
|
44 | src = isp.source_reset() | |
45 | #print 'Input source was:\n', src # dbg |
|
45 | #print 'Input source was:\n', src # dbg | |
46 | return src |
|
46 | return src | |
47 |
|
47 | |||
48 | #----------------------------------------------------------------------------- |
|
48 | #----------------------------------------------------------------------------- | |
49 | # Test utilities, just for local use |
|
49 | # Test utilities, just for local use | |
50 | #----------------------------------------------------------------------------- |
|
50 | #----------------------------------------------------------------------------- | |
51 |
|
51 | |||
52 |
|
52 | |||
53 | def pseudo_input(lines): |
|
53 | def pseudo_input(lines): | |
54 | """Return a function that acts like raw_input but feeds the input list.""" |
|
54 | """Return a function that acts like raw_input but feeds the input list.""" | |
55 | ilines = iter(lines) |
|
55 | ilines = iter(lines) | |
56 | def raw_in(prompt): |
|
56 | def raw_in(prompt): | |
57 | try: |
|
57 | try: | |
58 | return next(ilines) |
|
58 | return next(ilines) | |
59 | except StopIteration: |
|
59 | except StopIteration: | |
60 | return '' |
|
60 | return '' | |
61 | return raw_in |
|
61 | return raw_in | |
62 |
|
62 | |||
63 | #----------------------------------------------------------------------------- |
|
63 | #----------------------------------------------------------------------------- | |
64 | # Tests |
|
64 | # Tests | |
65 | #----------------------------------------------------------------------------- |
|
65 | #----------------------------------------------------------------------------- | |
66 | def test_spaces(): |
|
66 | def test_spaces(): | |
67 | tests = [('', 0), |
|
67 | tests = [('', 0), | |
68 | (' ', 1), |
|
68 | (' ', 1), | |
69 | ('\n', 0), |
|
69 | ('\n', 0), | |
70 | (' \n', 1), |
|
70 | (' \n', 1), | |
71 | ('x', 0), |
|
71 | ('x', 0), | |
72 | (' x', 1), |
|
72 | (' x', 1), | |
73 | (' x',2), |
|
73 | (' x',2), | |
74 | (' x',4), |
|
74 | (' x',4), | |
75 | # Note: tabs are counted as a single whitespace! |
|
75 | # Note: tabs are counted as a single whitespace! | |
76 | ('\tx', 1), |
|
76 | ('\tx', 1), | |
77 | ('\t x', 2), |
|
77 | ('\t x', 2), | |
78 | ] |
|
78 | ] | |
79 | tt.check_pairs(isp.num_ini_spaces, tests) |
|
79 | tt.check_pairs(isp.num_ini_spaces, tests) | |
80 |
|
80 | |||
81 |
|
81 | |||
82 | def test_remove_comments(): |
|
82 | def test_remove_comments(): | |
83 | tests = [('text', 'text'), |
|
83 | tests = [('text', 'text'), | |
84 | ('text # comment', 'text '), |
|
84 | ('text # comment', 'text '), | |
85 | ('text # comment\n', 'text \n'), |
|
85 | ('text # comment\n', 'text \n'), | |
86 | ('text # comment \n', 'text \n'), |
|
86 | ('text # comment \n', 'text \n'), | |
87 | ('line # c \nline\n','line \nline\n'), |
|
87 | ('line # c \nline\n','line \nline\n'), | |
88 | ('line # c \nline#c2 \nline\nline #c\n\n', |
|
88 | ('line # c \nline#c2 \nline\nline #c\n\n', | |
89 | 'line \nline\nline\nline \n\n'), |
|
89 | 'line \nline\nline\nline \n\n'), | |
90 | ] |
|
90 | ] | |
91 | tt.check_pairs(isp.remove_comments, tests) |
|
91 | tt.check_pairs(isp.remove_comments, tests) | |
92 |
|
92 | |||
93 |
|
93 | |||
94 | def test_get_input_encoding(): |
|
94 | def test_get_input_encoding(): | |
95 | encoding = isp.get_input_encoding() |
|
95 | encoding = isp.get_input_encoding() | |
96 | assert isinstance(encoding, str) |
|
96 | assert isinstance(encoding, str) | |
97 | # simple-minded check that at least encoding a simple string works with the |
|
97 | # simple-minded check that at least encoding a simple string works with the | |
98 | # encoding we got. |
|
98 | # encoding we got. | |
99 | assert "test".encode(encoding) == b"test" |
|
99 | assert "test".encode(encoding) == b"test" | |
100 |
|
100 | |||
101 |
|
101 | |||
102 | class NoInputEncodingTestCase(unittest.TestCase): |
|
102 | class NoInputEncodingTestCase(unittest.TestCase): | |
103 | def setUp(self): |
|
103 | def setUp(self): | |
104 | self.old_stdin = sys.stdin |
|
104 | self.old_stdin = sys.stdin | |
105 | class X: pass |
|
105 | class X: pass | |
106 | fake_stdin = X() |
|
106 | fake_stdin = X() | |
107 | sys.stdin = fake_stdin |
|
107 | sys.stdin = fake_stdin | |
108 |
|
108 | |||
109 | def test(self): |
|
109 | def test(self): | |
110 | # Verify that if sys.stdin has no 'encoding' attribute we do the right |
|
110 | # Verify that if sys.stdin has no 'encoding' attribute we do the right | |
111 | # thing |
|
111 | # thing | |
112 | enc = isp.get_input_encoding() |
|
112 | enc = isp.get_input_encoding() | |
113 | self.assertEqual(enc, 'ascii') |
|
113 | self.assertEqual(enc, 'ascii') | |
114 |
|
114 | |||
115 | def tearDown(self): |
|
115 | def tearDown(self): | |
116 | sys.stdin = self.old_stdin |
|
116 | sys.stdin = self.old_stdin | |
117 |
|
117 | |||
118 |
|
118 | |||
119 | class InputSplitterTestCase(unittest.TestCase): |
|
119 | class InputSplitterTestCase(unittest.TestCase): | |
120 | def setUp(self): |
|
120 | def setUp(self): | |
121 | self.isp = isp.InputSplitter() |
|
121 | self.isp = isp.InputSplitter() | |
122 |
|
122 | |||
123 | def test_reset(self): |
|
123 | def test_reset(self): | |
124 | isp = self.isp |
|
124 | isp = self.isp | |
125 | isp.push('x=1') |
|
125 | isp.push('x=1') | |
126 | isp.reset() |
|
126 | isp.reset() | |
127 | self.assertEqual(isp._buffer, []) |
|
127 | self.assertEqual(isp._buffer, []) | |
128 | self.assertEqual(isp.get_indent_spaces(), 0) |
|
128 | self.assertEqual(isp.get_indent_spaces(), 0) | |
129 | self.assertEqual(isp.source, '') |
|
129 | self.assertEqual(isp.source, '') | |
130 | self.assertEqual(isp.code, None) |
|
130 | self.assertEqual(isp.code, None) | |
131 | self.assertEqual(isp._is_complete, False) |
|
131 | self.assertEqual(isp._is_complete, False) | |
132 |
|
132 | |||
133 | def test_source(self): |
|
133 | def test_source(self): | |
134 | self.isp._store('1') |
|
134 | self.isp._store('1') | |
135 | self.isp._store('2') |
|
135 | self.isp._store('2') | |
136 | self.assertEqual(self.isp.source, '1\n2\n') |
|
136 | self.assertEqual(self.isp.source, '1\n2\n') | |
137 | self.assertEqual(len(self.isp._buffer)>0, True) |
|
137 | self.assertEqual(len(self.isp._buffer)>0, True) | |
138 | self.assertEqual(self.isp.source_reset(), '1\n2\n') |
|
138 | self.assertEqual(self.isp.source_reset(), '1\n2\n') | |
139 | self.assertEqual(self.isp._buffer, []) |
|
139 | self.assertEqual(self.isp._buffer, []) | |
140 | self.assertEqual(self.isp.source, '') |
|
140 | self.assertEqual(self.isp.source, '') | |
141 |
|
141 | |||
142 | def test_indent(self): |
|
142 | def test_indent(self): | |
143 | isp = self.isp # shorthand |
|
143 | isp = self.isp # shorthand | |
144 | isp.push('x=1') |
|
144 | isp.push('x=1') | |
145 | self.assertEqual(isp.get_indent_spaces(), 0) |
|
145 | self.assertEqual(isp.get_indent_spaces(), 0) | |
146 | isp.push('if 1:\n x=1') |
|
146 | isp.push('if 1:\n x=1') | |
147 | self.assertEqual(isp.get_indent_spaces(), 4) |
|
147 | self.assertEqual(isp.get_indent_spaces(), 4) | |
148 | isp.push('y=2\n') |
|
148 | isp.push('y=2\n') | |
149 | self.assertEqual(isp.get_indent_spaces(), 0) |
|
149 | self.assertEqual(isp.get_indent_spaces(), 0) | |
150 |
|
150 | |||
151 | def test_indent2(self): |
|
151 | def test_indent2(self): | |
152 | isp = self.isp |
|
152 | isp = self.isp | |
153 | isp.push('if 1:') |
|
153 | isp.push('if 1:') | |
154 | self.assertEqual(isp.get_indent_spaces(), 4) |
|
154 | self.assertEqual(isp.get_indent_spaces(), 4) | |
155 | isp.push(' x=1') |
|
155 | isp.push(' x=1') | |
156 | self.assertEqual(isp.get_indent_spaces(), 4) |
|
156 | self.assertEqual(isp.get_indent_spaces(), 4) | |
157 | # Blank lines shouldn't change the indent level |
|
157 | # Blank lines shouldn't change the indent level | |
158 | isp.push(' '*2) |
|
158 | isp.push(' '*2) | |
159 | self.assertEqual(isp.get_indent_spaces(), 4) |
|
159 | self.assertEqual(isp.get_indent_spaces(), 4) | |
160 |
|
160 | |||
161 | def test_indent3(self): |
|
161 | def test_indent3(self): | |
162 | isp = self.isp |
|
162 | isp = self.isp | |
163 | # When a multiline statement contains parens or multiline strings, we |
|
163 | # When a multiline statement contains parens or multiline strings, we | |
164 | # shouldn't get confused. |
|
164 | # shouldn't get confused. | |
165 | isp.push("if 1:") |
|
165 | isp.push("if 1:") | |
166 | isp.push(" x = (1+\n 2)") |
|
166 | isp.push(" x = (1+\n 2)") | |
167 | self.assertEqual(isp.get_indent_spaces(), 4) |
|
167 | self.assertEqual(isp.get_indent_spaces(), 4) | |
168 |
|
168 | |||
169 | def test_indent4(self): |
|
169 | def test_indent4(self): | |
170 | isp = self.isp |
|
170 | isp = self.isp | |
171 | # whitespace after ':' should not screw up indent level |
|
171 | # whitespace after ':' should not screw up indent level | |
172 | isp.push('if 1: \n x=1') |
|
172 | isp.push('if 1: \n x=1') | |
173 | self.assertEqual(isp.get_indent_spaces(), 4) |
|
173 | self.assertEqual(isp.get_indent_spaces(), 4) | |
174 | isp.push('y=2\n') |
|
174 | isp.push('y=2\n') | |
175 | self.assertEqual(isp.get_indent_spaces(), 0) |
|
175 | self.assertEqual(isp.get_indent_spaces(), 0) | |
176 | isp.push('if 1:\t\n x=1') |
|
176 | isp.push('if 1:\t\n x=1') | |
177 | self.assertEqual(isp.get_indent_spaces(), 4) |
|
177 | self.assertEqual(isp.get_indent_spaces(), 4) | |
178 | isp.push('y=2\n') |
|
178 | isp.push('y=2\n') | |
179 | self.assertEqual(isp.get_indent_spaces(), 0) |
|
179 | self.assertEqual(isp.get_indent_spaces(), 0) | |
180 |
|
180 | |||
181 | def test_dedent_pass(self): |
|
181 | def test_dedent_pass(self): | |
182 | isp = self.isp # shorthand |
|
182 | isp = self.isp # shorthand | |
183 | # should NOT cause dedent |
|
183 | # should NOT cause dedent | |
184 | isp.push('if 1:\n passes = 5') |
|
184 | isp.push('if 1:\n passes = 5') | |
185 | self.assertEqual(isp.get_indent_spaces(), 4) |
|
185 | self.assertEqual(isp.get_indent_spaces(), 4) | |
186 | isp.push('if 1:\n pass') |
|
186 | isp.push('if 1:\n pass') | |
187 | self.assertEqual(isp.get_indent_spaces(), 0) |
|
187 | self.assertEqual(isp.get_indent_spaces(), 0) | |
188 | isp.push('if 1:\n pass ') |
|
188 | isp.push('if 1:\n pass ') | |
189 | self.assertEqual(isp.get_indent_spaces(), 0) |
|
189 | self.assertEqual(isp.get_indent_spaces(), 0) | |
190 |
|
190 | |||
191 | def test_dedent_break(self): |
|
191 | def test_dedent_break(self): | |
192 | isp = self.isp # shorthand |
|
192 | isp = self.isp # shorthand | |
193 | # should NOT cause dedent |
|
193 | # should NOT cause dedent | |
194 | isp.push('while 1:\n breaks = 5') |
|
194 | isp.push('while 1:\n breaks = 5') | |
195 | self.assertEqual(isp.get_indent_spaces(), 4) |
|
195 | self.assertEqual(isp.get_indent_spaces(), 4) | |
196 | isp.push('while 1:\n break') |
|
196 | isp.push('while 1:\n break') | |
197 | self.assertEqual(isp.get_indent_spaces(), 0) |
|
197 | self.assertEqual(isp.get_indent_spaces(), 0) | |
198 | isp.push('while 1:\n break ') |
|
198 | isp.push('while 1:\n break ') | |
199 | self.assertEqual(isp.get_indent_spaces(), 0) |
|
199 | self.assertEqual(isp.get_indent_spaces(), 0) | |
200 |
|
200 | |||
201 | def test_dedent_continue(self): |
|
201 | def test_dedent_continue(self): | |
202 | isp = self.isp # shorthand |
|
202 | isp = self.isp # shorthand | |
203 | # should NOT cause dedent |
|
203 | # should NOT cause dedent | |
204 | isp.push('while 1:\n continues = 5') |
|
204 | isp.push('while 1:\n continues = 5') | |
205 | self.assertEqual(isp.get_indent_spaces(), 4) |
|
205 | self.assertEqual(isp.get_indent_spaces(), 4) | |
206 | isp.push('while 1:\n continue') |
|
206 | isp.push('while 1:\n continue') | |
207 | self.assertEqual(isp.get_indent_spaces(), 0) |
|
207 | self.assertEqual(isp.get_indent_spaces(), 0) | |
208 | isp.push('while 1:\n continue ') |
|
208 | isp.push('while 1:\n continue ') | |
209 | self.assertEqual(isp.get_indent_spaces(), 0) |
|
209 | self.assertEqual(isp.get_indent_spaces(), 0) | |
210 |
|
210 | |||
211 | def test_dedent_raise(self): |
|
211 | def test_dedent_raise(self): | |
212 | isp = self.isp # shorthand |
|
212 | isp = self.isp # shorthand | |
213 | # should NOT cause dedent |
|
213 | # should NOT cause dedent | |
214 | isp.push('if 1:\n raised = 4') |
|
214 | isp.push('if 1:\n raised = 4') | |
215 | self.assertEqual(isp.get_indent_spaces(), 4) |
|
215 | self.assertEqual(isp.get_indent_spaces(), 4) | |
216 | isp.push('if 1:\n raise TypeError()') |
|
216 | isp.push('if 1:\n raise TypeError()') | |
217 | self.assertEqual(isp.get_indent_spaces(), 0) |
|
217 | self.assertEqual(isp.get_indent_spaces(), 0) | |
218 | isp.push('if 1:\n raise') |
|
218 | isp.push('if 1:\n raise') | |
219 | self.assertEqual(isp.get_indent_spaces(), 0) |
|
219 | self.assertEqual(isp.get_indent_spaces(), 0) | |
220 | isp.push('if 1:\n raise ') |
|
220 | isp.push('if 1:\n raise ') | |
221 | self.assertEqual(isp.get_indent_spaces(), 0) |
|
221 | self.assertEqual(isp.get_indent_spaces(), 0) | |
222 |
|
222 | |||
223 | def test_dedent_return(self): |
|
223 | def test_dedent_return(self): | |
224 | isp = self.isp # shorthand |
|
224 | isp = self.isp # shorthand | |
225 | # should NOT cause dedent |
|
225 | # should NOT cause dedent | |
226 | isp.push('if 1:\n returning = 4') |
|
226 | isp.push('if 1:\n returning = 4') | |
227 | self.assertEqual(isp.get_indent_spaces(), 4) |
|
227 | self.assertEqual(isp.get_indent_spaces(), 4) | |
228 | isp.push('if 1:\n return 5 + 493') |
|
228 | isp.push('if 1:\n return 5 + 493') | |
229 | self.assertEqual(isp.get_indent_spaces(), 0) |
|
229 | self.assertEqual(isp.get_indent_spaces(), 0) | |
230 | isp.push('if 1:\n return') |
|
230 | isp.push('if 1:\n return') | |
231 | self.assertEqual(isp.get_indent_spaces(), 0) |
|
231 | self.assertEqual(isp.get_indent_spaces(), 0) | |
232 | isp.push('if 1:\n return ') |
|
232 | isp.push('if 1:\n return ') | |
233 | self.assertEqual(isp.get_indent_spaces(), 0) |
|
233 | self.assertEqual(isp.get_indent_spaces(), 0) | |
234 | isp.push('if 1:\n return(0)') |
|
234 | isp.push('if 1:\n return(0)') | |
235 | self.assertEqual(isp.get_indent_spaces(), 0) |
|
235 | self.assertEqual(isp.get_indent_spaces(), 0) | |
236 |
|
236 | |||
237 | def test_push(self): |
|
237 | def test_push(self): | |
238 | isp = self.isp |
|
238 | isp = self.isp | |
239 | self.assertEqual(isp.push('x=1'), True) |
|
239 | self.assertEqual(isp.push('x=1'), True) | |
240 |
|
240 | |||
241 | def test_push2(self): |
|
241 | def test_push2(self): | |
242 | isp = self.isp |
|
242 | isp = self.isp | |
243 | self.assertEqual(isp.push('if 1:'), False) |
|
243 | self.assertEqual(isp.push('if 1:'), False) | |
244 | for line in [' x=1', '# a comment', ' y=2']: |
|
244 | for line in [' x=1', '# a comment', ' y=2']: | |
245 | print(line) |
|
245 | print(line) | |
246 | self.assertEqual(isp.push(line), True) |
|
246 | self.assertEqual(isp.push(line), True) | |
247 |
|
247 | |||
248 | def test_push3(self): |
|
248 | def test_push3(self): | |
249 | isp = self.isp |
|
249 | isp = self.isp | |
250 | isp.push('if True:') |
|
250 | isp.push('if True:') | |
251 | isp.push(' a = 1') |
|
251 | isp.push(' a = 1') | |
252 | self.assertEqual(isp.push('b = [1,'), False) |
|
252 | self.assertEqual(isp.push('b = [1,'), False) | |
253 |
|
253 | |||
254 | def test_push_accepts_more(self): |
|
254 | def test_push_accepts_more(self): | |
255 | isp = self.isp |
|
255 | isp = self.isp | |
256 | isp.push('x=1') |
|
256 | isp.push('x=1') | |
257 | self.assertEqual(isp.push_accepts_more(), False) |
|
257 | self.assertEqual(isp.push_accepts_more(), False) | |
258 |
|
258 | |||
259 | def test_push_accepts_more2(self): |
|
259 | def test_push_accepts_more2(self): | |
260 | isp = self.isp |
|
260 | isp = self.isp | |
261 | isp.push('if 1:') |
|
261 | isp.push('if 1:') | |
262 | self.assertEqual(isp.push_accepts_more(), True) |
|
262 | self.assertEqual(isp.push_accepts_more(), True) | |
263 | isp.push(' x=1') |
|
263 | isp.push(' x=1') | |
264 | self.assertEqual(isp.push_accepts_more(), True) |
|
264 | self.assertEqual(isp.push_accepts_more(), True) | |
265 | isp.push('') |
|
265 | isp.push('') | |
266 | self.assertEqual(isp.push_accepts_more(), False) |
|
266 | self.assertEqual(isp.push_accepts_more(), False) | |
267 |
|
267 | |||
268 | def test_push_accepts_more3(self): |
|
268 | def test_push_accepts_more3(self): | |
269 | isp = self.isp |
|
269 | isp = self.isp | |
270 | isp.push("x = (2+\n3)") |
|
270 | isp.push("x = (2+\n3)") | |
271 | self.assertEqual(isp.push_accepts_more(), False) |
|
271 | self.assertEqual(isp.push_accepts_more(), False) | |
272 |
|
272 | |||
273 | def test_push_accepts_more4(self): |
|
273 | def test_push_accepts_more4(self): | |
274 | isp = self.isp |
|
274 | isp = self.isp | |
275 | # When a multiline statement contains parens or multiline strings, we |
|
275 | # When a multiline statement contains parens or multiline strings, we | |
276 | # shouldn't get confused. |
|
276 | # shouldn't get confused. | |
277 | # FIXME: we should be able to better handle de-dents in statements like |
|
277 | # FIXME: we should be able to better handle de-dents in statements like | |
278 | # multiline strings and multiline expressions (continued with \ or |
|
278 | # multiline strings and multiline expressions (continued with \ or | |
279 | # parens). Right now we aren't handling the indentation tracking quite |
|
279 | # parens). Right now we aren't handling the indentation tracking quite | |
280 | # correctly with this, though in practice it may not be too much of a |
|
280 | # correctly with this, though in practice it may not be too much of a | |
281 | # problem. We'll need to see. |
|
281 | # problem. We'll need to see. | |
282 | isp.push("if 1:") |
|
282 | isp.push("if 1:") | |
283 | isp.push(" x = (2+") |
|
283 | isp.push(" x = (2+") | |
284 | isp.push(" 3)") |
|
284 | isp.push(" 3)") | |
285 | self.assertEqual(isp.push_accepts_more(), True) |
|
285 | self.assertEqual(isp.push_accepts_more(), True) | |
286 | isp.push(" y = 3") |
|
286 | isp.push(" y = 3") | |
287 | self.assertEqual(isp.push_accepts_more(), True) |
|
287 | self.assertEqual(isp.push_accepts_more(), True) | |
288 | isp.push('') |
|
288 | isp.push('') | |
289 | self.assertEqual(isp.push_accepts_more(), False) |
|
289 | self.assertEqual(isp.push_accepts_more(), False) | |
290 |
|
290 | |||
291 | def test_push_accepts_more5(self): |
|
291 | def test_push_accepts_more5(self): | |
292 | isp = self.isp |
|
292 | isp = self.isp | |
293 | isp.push('try:') |
|
293 | isp.push('try:') | |
294 | isp.push(' a = 5') |
|
294 | isp.push(' a = 5') | |
295 | isp.push('except:') |
|
295 | isp.push('except:') | |
296 | isp.push(' raise') |
|
296 | isp.push(' raise') | |
297 | # We want to be able to add an else: block at this point, so it should |
|
297 | # We want to be able to add an else: block at this point, so it should | |
298 | # wait for a blank line. |
|
298 | # wait for a blank line. | |
299 | self.assertEqual(isp.push_accepts_more(), True) |
|
299 | self.assertEqual(isp.push_accepts_more(), True) | |
300 |
|
300 | |||
301 | def test_continuation(self): |
|
301 | def test_continuation(self): | |
302 | isp = self.isp |
|
302 | isp = self.isp | |
303 | isp.push("import os, \\") |
|
303 | isp.push("import os, \\") | |
304 | self.assertEqual(isp.push_accepts_more(), True) |
|
304 | self.assertEqual(isp.push_accepts_more(), True) | |
305 | isp.push("sys") |
|
305 | isp.push("sys") | |
306 | self.assertEqual(isp.push_accepts_more(), False) |
|
306 | self.assertEqual(isp.push_accepts_more(), False) | |
307 |
|
307 | |||
308 | def test_syntax_error(self): |
|
308 | def test_syntax_error(self): | |
309 | isp = self.isp |
|
309 | isp = self.isp | |
310 | # Syntax errors immediately produce a 'ready' block, so the invalid |
|
310 | # Syntax errors immediately produce a 'ready' block, so the invalid | |
311 | # Python can be sent to the kernel for evaluation with possible ipython |
|
311 | # Python can be sent to the kernel for evaluation with possible ipython | |
312 | # special-syntax conversion. |
|
312 | # special-syntax conversion. | |
313 | isp.push('run foo') |
|
313 | isp.push('run foo') | |
314 | self.assertEqual(isp.push_accepts_more(), False) |
|
314 | self.assertEqual(isp.push_accepts_more(), False) | |
315 |
|
315 | |||
316 | def test_unicode(self): |
|
316 | def test_unicode(self): | |
317 | self.isp.push(u"Pérez") |
|
317 | self.isp.push(u"Pérez") | |
318 | self.isp.push(u'\xc3\xa9') |
|
318 | self.isp.push(u'\xc3\xa9') | |
319 | self.isp.push(u"u'\xc3\xa9'") |
|
319 | self.isp.push(u"u'\xc3\xa9'") | |
320 |
|
320 | |||
321 | @skipif(sys.version_info[:3] == (3, 9, 8)) |
|
321 | @pytest.mark.xfail( | |
|
322 | reason="Bug in python 3.9.8 – bpo 45738", | |||
|
323 | condition=sys.version_info in [(3, 9, 8, "final", 0), (3, 11, 0, "alpha", 2)], | |||
|
324 | raises=SystemError, | |||
|
325 | strict=True, | |||
|
326 | ) | |||
322 | def test_line_continuation(self): |
|
327 | def test_line_continuation(self): | |
323 | """ Test issue #2108.""" |
|
328 | """ Test issue #2108.""" | |
324 | isp = self.isp |
|
329 | isp = self.isp | |
325 | # A blank line after a line continuation should not accept more |
|
330 | # A blank line after a line continuation should not accept more | |
326 | isp.push("1 \\\n\n") |
|
331 | isp.push("1 \\\n\n") | |
327 | self.assertEqual(isp.push_accepts_more(), False) |
|
332 | self.assertEqual(isp.push_accepts_more(), False) | |
328 | # Whitespace after a \ is a SyntaxError. The only way to test that |
|
333 | # Whitespace after a \ is a SyntaxError. The only way to test that | |
329 | # here is to test that push doesn't accept more (as with |
|
334 | # here is to test that push doesn't accept more (as with | |
330 | # test_syntax_error() above). |
|
335 | # test_syntax_error() above). | |
331 | isp.push(r"1 \ ") |
|
336 | isp.push(r"1 \ ") | |
332 | self.assertEqual(isp.push_accepts_more(), False) |
|
337 | self.assertEqual(isp.push_accepts_more(), False) | |
333 | # Even if the line is continuable (c.f. the regular Python |
|
338 | # Even if the line is continuable (c.f. the regular Python | |
334 | # interpreter) |
|
339 | # interpreter) | |
335 | isp.push(r"(1 \ ") |
|
340 | isp.push(r"(1 \ ") | |
336 | self.assertEqual(isp.push_accepts_more(), False) |
|
341 | self.assertEqual(isp.push_accepts_more(), False) | |
337 |
|
342 | |||
338 | def test_check_complete(self): |
|
343 | def test_check_complete(self): | |
339 | isp = self.isp |
|
344 | isp = self.isp | |
340 | self.assertEqual(isp.check_complete("a = 1"), ('complete', None)) |
|
345 | self.assertEqual(isp.check_complete("a = 1"), ('complete', None)) | |
341 | self.assertEqual(isp.check_complete("for a in range(5):"), ('incomplete', 4)) |
|
346 | self.assertEqual(isp.check_complete("for a in range(5):"), ('incomplete', 4)) | |
342 | self.assertEqual(isp.check_complete("raise = 2"), ('invalid', None)) |
|
347 | self.assertEqual(isp.check_complete("raise = 2"), ('invalid', None)) | |
343 | self.assertEqual(isp.check_complete("a = [1,\n2,"), ('incomplete', 0)) |
|
348 | self.assertEqual(isp.check_complete("a = [1,\n2,"), ('incomplete', 0)) | |
344 | self.assertEqual(isp.check_complete("def a():\n x=1\n global x"), ('invalid', None)) |
|
349 | self.assertEqual(isp.check_complete("def a():\n x=1\n global x"), ('invalid', None)) | |
345 |
|
350 | |||
346 | class InteractiveLoopTestCase(unittest.TestCase): |
|
351 | class InteractiveLoopTestCase(unittest.TestCase): | |
347 | """Tests for an interactive loop like a python shell. |
|
352 | """Tests for an interactive loop like a python shell. | |
348 | """ |
|
353 | """ | |
349 | def check_ns(self, lines, ns): |
|
354 | def check_ns(self, lines, ns): | |
350 | """Validate that the given input lines produce the resulting namespace. |
|
355 | """Validate that the given input lines produce the resulting namespace. | |
351 |
|
356 | |||
352 | Note: the input lines are given exactly as they would be typed in an |
|
357 | Note: the input lines are given exactly as they would be typed in an | |
353 | auto-indenting environment, as mini_interactive_loop above already does |
|
358 | auto-indenting environment, as mini_interactive_loop above already does | |
354 | auto-indenting and prepends spaces to the input. |
|
359 | auto-indenting and prepends spaces to the input. | |
355 | """ |
|
360 | """ | |
356 | src = mini_interactive_loop(pseudo_input(lines)) |
|
361 | src = mini_interactive_loop(pseudo_input(lines)) | |
357 | test_ns = {} |
|
362 | test_ns = {} | |
358 | exec(src, test_ns) |
|
363 | exec(src, test_ns) | |
359 | # We can't check that the provided ns is identical to the test_ns, |
|
364 | # We can't check that the provided ns is identical to the test_ns, | |
360 | # because Python fills test_ns with extra keys (copyright, etc). But |
|
365 | # because Python fills test_ns with extra keys (copyright, etc). But | |
361 | # we can check that the given dict is *contained* in test_ns |
|
366 | # we can check that the given dict is *contained* in test_ns | |
362 | for k,v in ns.items(): |
|
367 | for k,v in ns.items(): | |
363 | self.assertEqual(test_ns[k], v) |
|
368 | self.assertEqual(test_ns[k], v) | |
364 |
|
369 | |||
365 | def test_simple(self): |
|
370 | def test_simple(self): | |
366 | self.check_ns(['x=1'], dict(x=1)) |
|
371 | self.check_ns(['x=1'], dict(x=1)) | |
367 |
|
372 | |||
368 | def test_simple2(self): |
|
373 | def test_simple2(self): | |
369 | self.check_ns(['if 1:', 'x=2'], dict(x=2)) |
|
374 | self.check_ns(['if 1:', 'x=2'], dict(x=2)) | |
370 |
|
375 | |||
371 | def test_xy(self): |
|
376 | def test_xy(self): | |
372 | self.check_ns(['x=1; y=2'], dict(x=1, y=2)) |
|
377 | self.check_ns(['x=1; y=2'], dict(x=1, y=2)) | |
373 |
|
378 | |||
374 | def test_abc(self): |
|
379 | def test_abc(self): | |
375 | self.check_ns(['if 1:','a=1','b=2','c=3'], dict(a=1, b=2, c=3)) |
|
380 | self.check_ns(['if 1:','a=1','b=2','c=3'], dict(a=1, b=2, c=3)) | |
376 |
|
381 | |||
377 | def test_multi(self): |
|
382 | def test_multi(self): | |
378 | self.check_ns(['x =(1+','1+','2)'], dict(x=4)) |
|
383 | self.check_ns(['x =(1+','1+','2)'], dict(x=4)) | |
379 |
|
384 | |||
380 |
|
385 | |||
381 | class IPythonInputTestCase(InputSplitterTestCase): |
|
386 | class IPythonInputTestCase(InputSplitterTestCase): | |
382 | """By just creating a new class whose .isp is a different instance, we |
|
387 | """By just creating a new class whose .isp is a different instance, we | |
383 | re-run the same test battery on the new input splitter. |
|
388 | re-run the same test battery on the new input splitter. | |
384 |
|
389 | |||
385 | In addition, this runs the tests over the syntax and syntax_ml dicts that |
|
390 | In addition, this runs the tests over the syntax and syntax_ml dicts that | |
386 | were tested by individual functions, as part of the OO interface. |
|
391 | were tested by individual functions, as part of the OO interface. | |
387 |
|
392 | |||
388 | It also makes some checks on the raw buffer storage. |
|
393 | It also makes some checks on the raw buffer storage. | |
389 | """ |
|
394 | """ | |
390 |
|
395 | |||
391 | def setUp(self): |
|
396 | def setUp(self): | |
392 | self.isp = isp.IPythonInputSplitter() |
|
397 | self.isp = isp.IPythonInputSplitter() | |
393 |
|
398 | |||
394 | def test_syntax(self): |
|
399 | def test_syntax(self): | |
395 | """Call all single-line syntax tests from the main object""" |
|
400 | """Call all single-line syntax tests from the main object""" | |
396 | isp = self.isp |
|
401 | isp = self.isp | |
397 | for example in syntax.values(): |
|
402 | for example in syntax.values(): | |
398 | for raw, out_t in example: |
|
403 | for raw, out_t in example: | |
399 | if raw.startswith(' '): |
|
404 | if raw.startswith(' '): | |
400 | continue |
|
405 | continue | |
401 |
|
406 | |||
402 | isp.push(raw+'\n') |
|
407 | isp.push(raw+'\n') | |
403 | out_raw = isp.source_raw |
|
408 | out_raw = isp.source_raw | |
404 | out = isp.source_reset() |
|
409 | out = isp.source_reset() | |
405 | self.assertEqual(out.rstrip(), out_t, |
|
410 | self.assertEqual(out.rstrip(), out_t, | |
406 | tt.pair_fail_msg.format("inputsplitter",raw, out_t, out)) |
|
411 | tt.pair_fail_msg.format("inputsplitter",raw, out_t, out)) | |
407 | self.assertEqual(out_raw.rstrip(), raw.rstrip()) |
|
412 | self.assertEqual(out_raw.rstrip(), raw.rstrip()) | |
408 |
|
413 | |||
409 | def test_syntax_multiline(self): |
|
414 | def test_syntax_multiline(self): | |
410 | isp = self.isp |
|
415 | isp = self.isp | |
411 | for example in syntax_ml.values(): |
|
416 | for example in syntax_ml.values(): | |
412 | for line_pairs in example: |
|
417 | for line_pairs in example: | |
413 | out_t_parts = [] |
|
418 | out_t_parts = [] | |
414 | raw_parts = [] |
|
419 | raw_parts = [] | |
415 | for lraw, out_t_part in line_pairs: |
|
420 | for lraw, out_t_part in line_pairs: | |
416 | if out_t_part is not None: |
|
421 | if out_t_part is not None: | |
417 | out_t_parts.append(out_t_part) |
|
422 | out_t_parts.append(out_t_part) | |
418 |
|
423 | |||
419 | if lraw is not None: |
|
424 | if lraw is not None: | |
420 | isp.push(lraw) |
|
425 | isp.push(lraw) | |
421 | raw_parts.append(lraw) |
|
426 | raw_parts.append(lraw) | |
422 |
|
427 | |||
423 | out_raw = isp.source_raw |
|
428 | out_raw = isp.source_raw | |
424 | out = isp.source_reset() |
|
429 | out = isp.source_reset() | |
425 | out_t = '\n'.join(out_t_parts).rstrip() |
|
430 | out_t = '\n'.join(out_t_parts).rstrip() | |
426 | raw = '\n'.join(raw_parts).rstrip() |
|
431 | raw = '\n'.join(raw_parts).rstrip() | |
427 | self.assertEqual(out.rstrip(), out_t) |
|
432 | self.assertEqual(out.rstrip(), out_t) | |
428 | self.assertEqual(out_raw.rstrip(), raw) |
|
433 | self.assertEqual(out_raw.rstrip(), raw) | |
429 |
|
434 | |||
430 | def test_syntax_multiline_cell(self): |
|
435 | def test_syntax_multiline_cell(self): | |
431 | isp = self.isp |
|
436 | isp = self.isp | |
432 | for example in syntax_ml.values(): |
|
437 | for example in syntax_ml.values(): | |
433 |
|
438 | |||
434 | out_t_parts = [] |
|
439 | out_t_parts = [] | |
435 | for line_pairs in example: |
|
440 | for line_pairs in example: | |
436 | raw = '\n'.join(r for r, _ in line_pairs if r is not None) |
|
441 | raw = '\n'.join(r for r, _ in line_pairs if r is not None) | |
437 | out_t = '\n'.join(t for _,t in line_pairs if t is not None) |
|
442 | out_t = '\n'.join(t for _,t in line_pairs if t is not None) | |
438 | out = isp.transform_cell(raw) |
|
443 | out = isp.transform_cell(raw) | |
439 | # Match ignoring trailing whitespace |
|
444 | # Match ignoring trailing whitespace | |
440 | self.assertEqual(out.rstrip(), out_t.rstrip()) |
|
445 | self.assertEqual(out.rstrip(), out_t.rstrip()) | |
441 |
|
446 | |||
442 | def test_cellmagic_preempt(self): |
|
447 | def test_cellmagic_preempt(self): | |
443 | isp = self.isp |
|
448 | isp = self.isp | |
444 | for raw, name, line, cell in [ |
|
449 | for raw, name, line, cell in [ | |
445 | ("%%cellm a\nIn[1]:", u'cellm', u'a', u'In[1]:'), |
|
450 | ("%%cellm a\nIn[1]:", u'cellm', u'a', u'In[1]:'), | |
446 | ("%%cellm \nline\n>>> hi", u'cellm', u'', u'line\n>>> hi'), |
|
451 | ("%%cellm \nline\n>>> hi", u'cellm', u'', u'line\n>>> hi'), | |
447 | (">>> %%cellm \nline\n>>> hi", u'cellm', u'', u'line\nhi'), |
|
452 | (">>> %%cellm \nline\n>>> hi", u'cellm', u'', u'line\nhi'), | |
448 | ("%%cellm \n>>> hi", u'cellm', u'', u'>>> hi'), |
|
453 | ("%%cellm \n>>> hi", u'cellm', u'', u'>>> hi'), | |
449 | ("%%cellm \nline1\nline2", u'cellm', u'', u'line1\nline2'), |
|
454 | ("%%cellm \nline1\nline2", u'cellm', u'', u'line1\nline2'), | |
450 | ("%%cellm \nline1\\\\\nline2", u'cellm', u'', u'line1\\\\\nline2'), |
|
455 | ("%%cellm \nline1\\\\\nline2", u'cellm', u'', u'line1\\\\\nline2'), | |
451 | ]: |
|
456 | ]: | |
452 | expected = "get_ipython().run_cell_magic(%r, %r, %r)" % ( |
|
457 | expected = "get_ipython().run_cell_magic(%r, %r, %r)" % ( | |
453 | name, line, cell |
|
458 | name, line, cell | |
454 | ) |
|
459 | ) | |
455 | out = isp.transform_cell(raw) |
|
460 | out = isp.transform_cell(raw) | |
456 | self.assertEqual(out.rstrip(), expected.rstrip()) |
|
461 | self.assertEqual(out.rstrip(), expected.rstrip()) | |
457 |
|
462 | |||
458 | def test_multiline_passthrough(self): |
|
463 | def test_multiline_passthrough(self): | |
459 | isp = self.isp |
|
464 | isp = self.isp | |
460 | class CommentTransformer(InputTransformer): |
|
465 | class CommentTransformer(InputTransformer): | |
461 | def __init__(self): |
|
466 | def __init__(self): | |
462 | self._lines = [] |
|
467 | self._lines = [] | |
463 |
|
468 | |||
464 | def push(self, line): |
|
469 | def push(self, line): | |
465 | self._lines.append(line + '#') |
|
470 | self._lines.append(line + '#') | |
466 |
|
471 | |||
467 | def reset(self): |
|
472 | def reset(self): | |
468 | text = '\n'.join(self._lines) |
|
473 | text = '\n'.join(self._lines) | |
469 | self._lines = [] |
|
474 | self._lines = [] | |
470 | return text |
|
475 | return text | |
471 |
|
476 | |||
472 | isp.physical_line_transforms.insert(0, CommentTransformer()) |
|
477 | isp.physical_line_transforms.insert(0, CommentTransformer()) | |
473 |
|
478 | |||
474 | for raw, expected in [ |
|
479 | for raw, expected in [ | |
475 | ("a=5", "a=5#"), |
|
480 | ("a=5", "a=5#"), | |
476 | ("%ls foo", "get_ipython().run_line_magic(%r, %r)" % (u'ls', u'foo#')), |
|
481 | ("%ls foo", "get_ipython().run_line_magic(%r, %r)" % (u'ls', u'foo#')), | |
477 | ("!ls foo\n%ls bar", "get_ipython().system(%r)\nget_ipython().run_line_magic(%r, %r)" % ( |
|
482 | ("!ls foo\n%ls bar", "get_ipython().system(%r)\nget_ipython().run_line_magic(%r, %r)" % ( | |
478 | u'ls foo#', u'ls', u'bar#' |
|
483 | u'ls foo#', u'ls', u'bar#' | |
479 | )), |
|
484 | )), | |
480 | ("1\n2\n3\n%ls foo\n4\n5", "1#\n2#\n3#\nget_ipython().run_line_magic(%r, %r)\n4#\n5#" % (u'ls', u'foo#')), |
|
485 | ("1\n2\n3\n%ls foo\n4\n5", "1#\n2#\n3#\nget_ipython().run_line_magic(%r, %r)\n4#\n5#" % (u'ls', u'foo#')), | |
481 | ]: |
|
486 | ]: | |
482 | out = isp.transform_cell(raw) |
|
487 | out = isp.transform_cell(raw) | |
483 | self.assertEqual(out.rstrip(), expected.rstrip()) |
|
488 | self.assertEqual(out.rstrip(), expected.rstrip()) | |
484 |
|
489 | |||
485 | #----------------------------------------------------------------------------- |
|
490 | #----------------------------------------------------------------------------- | |
486 | # Main - use as a script, mostly for developer experiments |
|
491 | # Main - use as a script, mostly for developer experiments | |
487 | #----------------------------------------------------------------------------- |
|
492 | #----------------------------------------------------------------------------- | |
488 |
|
493 | |||
489 | if __name__ == '__main__': |
|
494 | if __name__ == '__main__': | |
490 | # A simple demo for interactive experimentation. This code will not get |
|
495 | # A simple demo for interactive experimentation. This code will not get | |
491 | # picked up by any test suite. |
|
496 | # picked up by any test suite. | |
492 | from IPython.core.inputsplitter import IPythonInputSplitter |
|
497 | from IPython.core.inputsplitter import IPythonInputSplitter | |
493 |
|
498 | |||
494 | # configure here the syntax to use, prompt and whether to autoindent |
|
499 | # configure here the syntax to use, prompt and whether to autoindent | |
495 | #isp, start_prompt = InputSplitter(), '>>> ' |
|
500 | #isp, start_prompt = InputSplitter(), '>>> ' | |
496 | isp, start_prompt = IPythonInputSplitter(), 'In> ' |
|
501 | isp, start_prompt = IPythonInputSplitter(), 'In> ' | |
497 |
|
502 | |||
498 | autoindent = True |
|
503 | autoindent = True | |
499 | #autoindent = False |
|
504 | #autoindent = False | |
500 |
|
505 | |||
501 | try: |
|
506 | try: | |
502 | while True: |
|
507 | while True: | |
503 | prompt = start_prompt |
|
508 | prompt = start_prompt | |
504 | while isp.push_accepts_more(): |
|
509 | while isp.push_accepts_more(): | |
505 | indent = ' '*isp.get_indent_spaces() |
|
510 | indent = ' '*isp.get_indent_spaces() | |
506 | if autoindent: |
|
511 | if autoindent: | |
507 | line = indent + input(prompt+indent) |
|
512 | line = indent + input(prompt+indent) | |
508 | else: |
|
513 | else: | |
509 | line = input(prompt) |
|
514 | line = input(prompt) | |
510 | isp.push(line) |
|
515 | isp.push(line) | |
511 | prompt = '... ' |
|
516 | prompt = '... ' | |
512 |
|
517 | |||
513 | # Here we just return input so we can use it in a test suite, but a |
|
518 | # Here we just return input so we can use it in a test suite, but a | |
514 | # real interpreter would instead send it for execution somewhere. |
|
519 | # real interpreter would instead send it for execution somewhere. | |
515 | #src = isp.source; raise EOFError # dbg |
|
520 | #src = isp.source; raise EOFError # dbg | |
516 | raw = isp.source_raw |
|
521 | raw = isp.source_raw | |
517 | src = isp.source_reset() |
|
522 | src = isp.source_reset() | |
518 | print('Input source was:\n', src) |
|
523 | print('Input source was:\n', src) | |
519 | print('Raw source was:\n', raw) |
|
524 | print('Raw source was:\n', raw) | |
520 | except EOFError: |
|
525 | except EOFError: | |
521 | print('Bye') |
|
526 | print('Bye') | |
522 |
|
527 | |||
523 | # Tests for cell magics support |
|
528 | # Tests for cell magics support | |
524 |
|
529 | |||
525 | def test_last_blank(): |
|
530 | def test_last_blank(): | |
526 | assert isp.last_blank("") is False |
|
531 | assert isp.last_blank("") is False | |
527 | assert isp.last_blank("abc") is False |
|
532 | assert isp.last_blank("abc") is False | |
528 | assert isp.last_blank("abc\n") is False |
|
533 | assert isp.last_blank("abc\n") is False | |
529 | assert isp.last_blank("abc\na") is False |
|
534 | assert isp.last_blank("abc\na") is False | |
530 |
|
535 | |||
531 | assert isp.last_blank("\n") is True |
|
536 | assert isp.last_blank("\n") is True | |
532 | assert isp.last_blank("\n ") is True |
|
537 | assert isp.last_blank("\n ") is True | |
533 | assert isp.last_blank("abc\n ") is True |
|
538 | assert isp.last_blank("abc\n ") is True | |
534 | assert isp.last_blank("abc\n\n") is True |
|
539 | assert isp.last_blank("abc\n\n") is True | |
535 | assert isp.last_blank("abc\nd\n\n") is True |
|
540 | assert isp.last_blank("abc\nd\n\n") is True | |
536 | assert isp.last_blank("abc\nd\ne\n\n") is True |
|
541 | assert isp.last_blank("abc\nd\ne\n\n") is True | |
537 | assert isp.last_blank("abc \n \n \n\n") is True |
|
542 | assert isp.last_blank("abc \n \n \n\n") is True | |
538 |
|
543 | |||
539 |
|
544 | |||
540 | def test_last_two_blanks(): |
|
545 | def test_last_two_blanks(): | |
541 | assert isp.last_two_blanks("") is False |
|
546 | assert isp.last_two_blanks("") is False | |
542 | assert isp.last_two_blanks("abc") is False |
|
547 | assert isp.last_two_blanks("abc") is False | |
543 | assert isp.last_two_blanks("abc\n") is False |
|
548 | assert isp.last_two_blanks("abc\n") is False | |
544 | assert isp.last_two_blanks("abc\n\na") is False |
|
549 | assert isp.last_two_blanks("abc\n\na") is False | |
545 | assert isp.last_two_blanks("abc\n \n") is False |
|
550 | assert isp.last_two_blanks("abc\n \n") is False | |
546 | assert isp.last_two_blanks("abc\n\n") is False |
|
551 | assert isp.last_two_blanks("abc\n\n") is False | |
547 |
|
552 | |||
548 | assert isp.last_two_blanks("\n\n") is True |
|
553 | assert isp.last_two_blanks("\n\n") is True | |
549 | assert isp.last_two_blanks("\n\n ") is True |
|
554 | assert isp.last_two_blanks("\n\n ") is True | |
550 | assert isp.last_two_blanks("\n \n") is True |
|
555 | assert isp.last_two_blanks("\n \n") is True | |
551 | assert isp.last_two_blanks("abc\n\n ") is True |
|
556 | assert isp.last_two_blanks("abc\n\n ") is True | |
552 | assert isp.last_two_blanks("abc\n\n\n") is True |
|
557 | assert isp.last_two_blanks("abc\n\n\n") is True | |
553 | assert isp.last_two_blanks("abc\n\n \n") is True |
|
558 | assert isp.last_two_blanks("abc\n\n \n") is True | |
554 | assert isp.last_two_blanks("abc\n\n \n ") is True |
|
559 | assert isp.last_two_blanks("abc\n\n \n ") is True | |
555 | assert isp.last_two_blanks("abc\n\n \n \n") is True |
|
560 | assert isp.last_two_blanks("abc\n\n \n \n") is True | |
556 | assert isp.last_two_blanks("abc\nd\n\n\n") is True |
|
561 | assert isp.last_two_blanks("abc\nd\n\n\n") is True | |
557 | assert isp.last_two_blanks("abc\nd\ne\nf\n\n\n") is True |
|
562 | assert isp.last_two_blanks("abc\nd\ne\nf\n\n\n") is True | |
558 |
|
563 | |||
559 |
|
564 | |||
560 | class CellMagicsCommon(object): |
|
565 | class CellMagicsCommon(object): | |
561 |
|
566 | |||
562 | def test_whole_cell(self): |
|
567 | def test_whole_cell(self): | |
563 | src = "%%cellm line\nbody\n" |
|
568 | src = "%%cellm line\nbody\n" | |
564 | out = self.sp.transform_cell(src) |
|
569 | out = self.sp.transform_cell(src) | |
565 | ref = "get_ipython().run_cell_magic('cellm', 'line', 'body')\n" |
|
570 | ref = "get_ipython().run_cell_magic('cellm', 'line', 'body')\n" | |
566 | assert out == ref |
|
571 | assert out == ref | |
567 |
|
572 | |||
568 | def test_cellmagic_help(self): |
|
573 | def test_cellmagic_help(self): | |
569 | self.sp.push('%%cellm?') |
|
574 | self.sp.push('%%cellm?') | |
570 | assert self.sp.push_accepts_more() is False |
|
575 | assert self.sp.push_accepts_more() is False | |
571 |
|
576 | |||
572 | def tearDown(self): |
|
577 | def tearDown(self): | |
573 | self.sp.reset() |
|
578 | self.sp.reset() | |
574 |
|
579 | |||
575 |
|
580 | |||
576 | class CellModeCellMagics(CellMagicsCommon, unittest.TestCase): |
|
581 | class CellModeCellMagics(CellMagicsCommon, unittest.TestCase): | |
577 | sp = isp.IPythonInputSplitter(line_input_checker=False) |
|
582 | sp = isp.IPythonInputSplitter(line_input_checker=False) | |
578 |
|
583 | |||
579 | def test_incremental(self): |
|
584 | def test_incremental(self): | |
580 | sp = self.sp |
|
585 | sp = self.sp | |
581 | sp.push("%%cellm firstline\n") |
|
586 | sp.push("%%cellm firstline\n") | |
582 | assert sp.push_accepts_more() is True # 1 |
|
587 | assert sp.push_accepts_more() is True # 1 | |
583 | sp.push("line2\n") |
|
588 | sp.push("line2\n") | |
584 | assert sp.push_accepts_more() is True # 2 |
|
589 | assert sp.push_accepts_more() is True # 2 | |
585 | sp.push("\n") |
|
590 | sp.push("\n") | |
586 | # This should accept a blank line and carry on until the cell is reset |
|
591 | # This should accept a blank line and carry on until the cell is reset | |
587 | assert sp.push_accepts_more() is True # 3 |
|
592 | assert sp.push_accepts_more() is True # 3 | |
588 |
|
593 | |||
589 | def test_no_strip_coding(self): |
|
594 | def test_no_strip_coding(self): | |
590 | src = '\n'.join([ |
|
595 | src = '\n'.join([ | |
591 | '%%writefile foo.py', |
|
596 | '%%writefile foo.py', | |
592 | '# coding: utf-8', |
|
597 | '# coding: utf-8', | |
593 | 'print(u"üñîçø∂é")', |
|
598 | 'print(u"üñîçø∂é")', | |
594 | ]) |
|
599 | ]) | |
595 | out = self.sp.transform_cell(src) |
|
600 | out = self.sp.transform_cell(src) | |
596 | assert "# coding: utf-8" in out |
|
601 | assert "# coding: utf-8" in out | |
597 |
|
602 | |||
598 |
|
603 | |||
599 | class LineModeCellMagics(CellMagicsCommon, unittest.TestCase): |
|
604 | class LineModeCellMagics(CellMagicsCommon, unittest.TestCase): | |
600 | sp = isp.IPythonInputSplitter(line_input_checker=True) |
|
605 | sp = isp.IPythonInputSplitter(line_input_checker=True) | |
601 |
|
606 | |||
602 | def test_incremental(self): |
|
607 | def test_incremental(self): | |
603 | sp = self.sp |
|
608 | sp = self.sp | |
604 | sp.push("%%cellm line2\n") |
|
609 | sp.push("%%cellm line2\n") | |
605 | assert sp.push_accepts_more() is True # 1 |
|
610 | assert sp.push_accepts_more() is True # 1 | |
606 | sp.push("\n") |
|
611 | sp.push("\n") | |
607 | # In this case, a blank line should end the cell magic |
|
612 | # In this case, a blank line should end the cell magic | |
608 | assert sp.push_accepts_more() is False # 2 |
|
613 | assert sp.push_accepts_more() is False # 2 | |
609 |
|
614 | |||
610 |
|
615 | |||
611 | indentation_samples = [ |
|
616 | indentation_samples = [ | |
612 | ('a = 1', 0), |
|
617 | ('a = 1', 0), | |
613 | ('for a in b:', 4), |
|
618 | ('for a in b:', 4), | |
614 | ('def f():', 4), |
|
619 | ('def f():', 4), | |
615 | ('def f(): #comment', 4), |
|
620 | ('def f(): #comment', 4), | |
616 | ('a = ":#not a comment"', 0), |
|
621 | ('a = ":#not a comment"', 0), | |
617 | ('def f():\n a = 1', 4), |
|
622 | ('def f():\n a = 1', 4), | |
618 | ('def f():\n return 1', 0), |
|
623 | ('def f():\n return 1', 0), | |
619 | ('for a in b:\n' |
|
624 | ('for a in b:\n' | |
620 | ' if a < 0:' |
|
625 | ' if a < 0:' | |
621 | ' continue', 3), |
|
626 | ' continue', 3), | |
622 | ('a = {', 4), |
|
627 | ('a = {', 4), | |
623 | ('a = {\n' |
|
628 | ('a = {\n' | |
624 | ' 1,', 5), |
|
629 | ' 1,', 5), | |
625 | ('b = """123', 0), |
|
630 | ('b = """123', 0), | |
626 | ('', 0), |
|
631 | ('', 0), | |
627 | ('def f():\n pass', 0), |
|
632 | ('def f():\n pass', 0), | |
628 | ('class Bar:\n def f():\n pass', 4), |
|
633 | ('class Bar:\n def f():\n pass', 4), | |
629 | ('class Bar:\n def f():\n raise', 4), |
|
634 | ('class Bar:\n def f():\n raise', 4), | |
630 | ] |
|
635 | ] | |
631 |
|
636 | |||
632 | def test_find_next_indent(): |
|
637 | def test_find_next_indent(): | |
633 | for code, exp in indentation_samples: |
|
638 | for code, exp in indentation_samples: | |
634 | res = isp.find_next_indent(code) |
|
639 | res = isp.find_next_indent(code) | |
635 | msg = "{!r} != {!r} (expected)\n Code: {!r}".format(res, exp, code) |
|
640 | msg = "{!r} != {!r} (expected)\n Code: {!r}".format(res, exp, code) | |
636 | assert res == exp, msg |
|
641 | assert res == exp, msg |
@@ -1,385 +1,388 b'' | |||||
1 | """Tests for the token-based transformers in IPython.core.inputtransformer2 |
|
1 | """Tests for the token-based transformers in IPython.core.inputtransformer2 | |
2 |
|
2 | |||
3 | Line-based transformers are the simpler ones; token-based transformers are |
|
3 | Line-based transformers are the simpler ones; token-based transformers are | |
4 | more complex. See test_inputtransformer2_line for tests for line-based |
|
4 | more complex. See test_inputtransformer2_line for tests for line-based | |
5 | transformations. |
|
5 | transformations. | |
6 | """ |
|
6 | """ | |
7 | import string |
|
7 | import string | |
8 | import sys |
|
8 | import sys | |
9 | from textwrap import dedent |
|
9 | from textwrap import dedent | |
10 |
|
10 | |||
11 | import pytest |
|
11 | import pytest | |
12 |
|
12 | |||
13 | from IPython.core import inputtransformer2 as ipt2 |
|
13 | from IPython.core import inputtransformer2 as ipt2 | |
14 | from IPython.core.inputtransformer2 import _find_assign_op, make_tokens_by_line |
|
14 | from IPython.core.inputtransformer2 import _find_assign_op, make_tokens_by_line | |
15 |
|
15 | |||
16 | MULTILINE_MAGIC = ("""\ |
|
16 | MULTILINE_MAGIC = ("""\ | |
17 | a = f() |
|
17 | a = f() | |
18 | %foo \\ |
|
18 | %foo \\ | |
19 | bar |
|
19 | bar | |
20 | g() |
|
20 | g() | |
21 | """.splitlines(keepends=True), (2, 0), """\ |
|
21 | """.splitlines(keepends=True), (2, 0), """\ | |
22 | a = f() |
|
22 | a = f() | |
23 | get_ipython().run_line_magic('foo', ' bar') |
|
23 | get_ipython().run_line_magic('foo', ' bar') | |
24 | g() |
|
24 | g() | |
25 | """.splitlines(keepends=True)) |
|
25 | """.splitlines(keepends=True)) | |
26 |
|
26 | |||
27 | INDENTED_MAGIC = ("""\ |
|
27 | INDENTED_MAGIC = ("""\ | |
28 | for a in range(5): |
|
28 | for a in range(5): | |
29 | %ls |
|
29 | %ls | |
30 | """.splitlines(keepends=True), (2, 4), """\ |
|
30 | """.splitlines(keepends=True), (2, 4), """\ | |
31 | for a in range(5): |
|
31 | for a in range(5): | |
32 | get_ipython().run_line_magic('ls', '') |
|
32 | get_ipython().run_line_magic('ls', '') | |
33 | """.splitlines(keepends=True)) |
|
33 | """.splitlines(keepends=True)) | |
34 |
|
34 | |||
35 | CRLF_MAGIC = ([ |
|
35 | CRLF_MAGIC = ([ | |
36 | "a = f()\n", |
|
36 | "a = f()\n", | |
37 | "%ls\r\n", |
|
37 | "%ls\r\n", | |
38 | "g()\n" |
|
38 | "g()\n" | |
39 | ], (2, 0), [ |
|
39 | ], (2, 0), [ | |
40 | "a = f()\n", |
|
40 | "a = f()\n", | |
41 | "get_ipython().run_line_magic('ls', '')\n", |
|
41 | "get_ipython().run_line_magic('ls', '')\n", | |
42 | "g()\n" |
|
42 | "g()\n" | |
43 | ]) |
|
43 | ]) | |
44 |
|
44 | |||
45 | MULTILINE_MAGIC_ASSIGN = ("""\ |
|
45 | MULTILINE_MAGIC_ASSIGN = ("""\ | |
46 | a = f() |
|
46 | a = f() | |
47 | b = %foo \\ |
|
47 | b = %foo \\ | |
48 | bar |
|
48 | bar | |
49 | g() |
|
49 | g() | |
50 | """.splitlines(keepends=True), (2, 4), """\ |
|
50 | """.splitlines(keepends=True), (2, 4), """\ | |
51 | a = f() |
|
51 | a = f() | |
52 | b = get_ipython().run_line_magic('foo', ' bar') |
|
52 | b = get_ipython().run_line_magic('foo', ' bar') | |
53 | g() |
|
53 | g() | |
54 | """.splitlines(keepends=True)) |
|
54 | """.splitlines(keepends=True)) | |
55 |
|
55 | |||
56 | MULTILINE_SYSTEM_ASSIGN = ("""\ |
|
56 | MULTILINE_SYSTEM_ASSIGN = ("""\ | |
57 | a = f() |
|
57 | a = f() | |
58 | b = !foo \\ |
|
58 | b = !foo \\ | |
59 | bar |
|
59 | bar | |
60 | g() |
|
60 | g() | |
61 | """.splitlines(keepends=True), (2, 4), """\ |
|
61 | """.splitlines(keepends=True), (2, 4), """\ | |
62 | a = f() |
|
62 | a = f() | |
63 | b = get_ipython().getoutput('foo bar') |
|
63 | b = get_ipython().getoutput('foo bar') | |
64 | g() |
|
64 | g() | |
65 | """.splitlines(keepends=True)) |
|
65 | """.splitlines(keepends=True)) | |
66 |
|
66 | |||
67 | ##### |
|
67 | ##### | |
68 |
|
68 | |||
69 | MULTILINE_SYSTEM_ASSIGN_AFTER_DEDENT = ("""\ |
|
69 | MULTILINE_SYSTEM_ASSIGN_AFTER_DEDENT = ("""\ | |
70 | def test(): |
|
70 | def test(): | |
71 | for i in range(1): |
|
71 | for i in range(1): | |
72 | print(i) |
|
72 | print(i) | |
73 | res =! ls |
|
73 | res =! ls | |
74 | """.splitlines(keepends=True), (4, 7), '''\ |
|
74 | """.splitlines(keepends=True), (4, 7), '''\ | |
75 | def test(): |
|
75 | def test(): | |
76 | for i in range(1): |
|
76 | for i in range(1): | |
77 | print(i) |
|
77 | print(i) | |
78 | res =get_ipython().getoutput(\' ls\') |
|
78 | res =get_ipython().getoutput(\' ls\') | |
79 | '''.splitlines(keepends=True)) |
|
79 | '''.splitlines(keepends=True)) | |
80 |
|
80 | |||
81 | ###### |
|
81 | ###### | |
82 |
|
82 | |||
83 | AUTOCALL_QUOTE = ( |
|
83 | AUTOCALL_QUOTE = ( | |
84 | [",f 1 2 3\n"], (1, 0), |
|
84 | [",f 1 2 3\n"], (1, 0), | |
85 | ['f("1", "2", "3")\n'] |
|
85 | ['f("1", "2", "3")\n'] | |
86 | ) |
|
86 | ) | |
87 |
|
87 | |||
88 | AUTOCALL_QUOTE2 = ( |
|
88 | AUTOCALL_QUOTE2 = ( | |
89 | [";f 1 2 3\n"], (1, 0), |
|
89 | [";f 1 2 3\n"], (1, 0), | |
90 | ['f("1 2 3")\n'] |
|
90 | ['f("1 2 3")\n'] | |
91 | ) |
|
91 | ) | |
92 |
|
92 | |||
93 | AUTOCALL_PAREN = ( |
|
93 | AUTOCALL_PAREN = ( | |
94 | ["/f 1 2 3\n"], (1, 0), |
|
94 | ["/f 1 2 3\n"], (1, 0), | |
95 | ['f(1, 2, 3)\n'] |
|
95 | ['f(1, 2, 3)\n'] | |
96 | ) |
|
96 | ) | |
97 |
|
97 | |||
98 | SIMPLE_HELP = ( |
|
98 | SIMPLE_HELP = ( | |
99 | ["foo?\n"], (1, 0), |
|
99 | ["foo?\n"], (1, 0), | |
100 | ["get_ipython().run_line_magic('pinfo', 'foo')\n"] |
|
100 | ["get_ipython().run_line_magic('pinfo', 'foo')\n"] | |
101 | ) |
|
101 | ) | |
102 |
|
102 | |||
103 | DETAILED_HELP = ( |
|
103 | DETAILED_HELP = ( | |
104 | ["foo??\n"], (1, 0), |
|
104 | ["foo??\n"], (1, 0), | |
105 | ["get_ipython().run_line_magic('pinfo2', 'foo')\n"] |
|
105 | ["get_ipython().run_line_magic('pinfo2', 'foo')\n"] | |
106 | ) |
|
106 | ) | |
107 |
|
107 | |||
108 | MAGIC_HELP = ( |
|
108 | MAGIC_HELP = ( | |
109 | ["%foo?\n"], (1, 0), |
|
109 | ["%foo?\n"], (1, 0), | |
110 | ["get_ipython().run_line_magic('pinfo', '%foo')\n"] |
|
110 | ["get_ipython().run_line_magic('pinfo', '%foo')\n"] | |
111 | ) |
|
111 | ) | |
112 |
|
112 | |||
113 | HELP_IN_EXPR = ( |
|
113 | HELP_IN_EXPR = ( | |
114 | ["a = b + c?\n"], (1, 0), |
|
114 | ["a = b + c?\n"], (1, 0), | |
115 | ["get_ipython().set_next_input('a = b + c');" |
|
115 | ["get_ipython().set_next_input('a = b + c');" | |
116 | "get_ipython().run_line_magic('pinfo', 'c')\n"] |
|
116 | "get_ipython().run_line_magic('pinfo', 'c')\n"] | |
117 | ) |
|
117 | ) | |
118 |
|
118 | |||
119 | HELP_CONTINUED_LINE = ("""\ |
|
119 | HELP_CONTINUED_LINE = ("""\ | |
120 | a = \\ |
|
120 | a = \\ | |
121 | zip? |
|
121 | zip? | |
122 | """.splitlines(keepends=True), (1, 0), |
|
122 | """.splitlines(keepends=True), (1, 0), | |
123 | [r"get_ipython().set_next_input('a = \\\nzip');get_ipython().run_line_magic('pinfo', 'zip')" + "\n"] |
|
123 | [r"get_ipython().set_next_input('a = \\\nzip');get_ipython().run_line_magic('pinfo', 'zip')" + "\n"] | |
124 | ) |
|
124 | ) | |
125 |
|
125 | |||
126 | HELP_MULTILINE = ("""\ |
|
126 | HELP_MULTILINE = ("""\ | |
127 | (a, |
|
127 | (a, | |
128 | b) = zip? |
|
128 | b) = zip? | |
129 | """.splitlines(keepends=True), (1, 0), |
|
129 | """.splitlines(keepends=True), (1, 0), | |
130 | [r"get_ipython().set_next_input('(a,\nb) = zip');get_ipython().run_line_magic('pinfo', 'zip')" + "\n"] |
|
130 | [r"get_ipython().set_next_input('(a,\nb) = zip');get_ipython().run_line_magic('pinfo', 'zip')" + "\n"] | |
131 | ) |
|
131 | ) | |
132 |
|
132 | |||
133 | HELP_UNICODE = ( |
|
133 | HELP_UNICODE = ( | |
134 | ["π.foo?\n"], (1, 0), |
|
134 | ["π.foo?\n"], (1, 0), | |
135 | ["get_ipython().run_line_magic('pinfo', 'π.foo')\n"] |
|
135 | ["get_ipython().run_line_magic('pinfo', 'π.foo')\n"] | |
136 | ) |
|
136 | ) | |
137 |
|
137 | |||
138 |
|
138 | |||
139 | def null_cleanup_transformer(lines): |
|
139 | def null_cleanup_transformer(lines): | |
140 | """ |
|
140 | """ | |
141 | A cleanup transform that returns an empty list. |
|
141 | A cleanup transform that returns an empty list. | |
142 | """ |
|
142 | """ | |
143 | return [] |
|
143 | return [] | |
144 |
|
144 | |||
145 |
|
145 | |||
146 | def test_check_make_token_by_line_never_ends_empty(): |
|
146 | def test_check_make_token_by_line_never_ends_empty(): | |
147 | """ |
|
147 | """ | |
148 | Check that not sequence of single or double characters ends up leading to en empty list of tokens |
|
148 | Check that not sequence of single or double characters ends up leading to en empty list of tokens | |
149 | """ |
|
149 | """ | |
150 | from string import printable |
|
150 | from string import printable | |
151 | for c in printable: |
|
151 | for c in printable: | |
152 | assert make_tokens_by_line(c)[-1] != [] |
|
152 | assert make_tokens_by_line(c)[-1] != [] | |
153 | for k in printable: |
|
153 | for k in printable: | |
154 | assert make_tokens_by_line(c + k)[-1] != [] |
|
154 | assert make_tokens_by_line(c + k)[-1] != [] | |
155 |
|
155 | |||
156 |
|
156 | |||
157 | def check_find(transformer, case, match=True): |
|
157 | def check_find(transformer, case, match=True): | |
158 | sample, expected_start, _ = case |
|
158 | sample, expected_start, _ = case | |
159 | tbl = make_tokens_by_line(sample) |
|
159 | tbl = make_tokens_by_line(sample) | |
160 | res = transformer.find(tbl) |
|
160 | res = transformer.find(tbl) | |
161 | if match: |
|
161 | if match: | |
162 | # start_line is stored 0-indexed, expected values are 1-indexed |
|
162 | # start_line is stored 0-indexed, expected values are 1-indexed | |
163 | assert (res.start_line + 1, res.start_col) == expected_start |
|
163 | assert (res.start_line + 1, res.start_col) == expected_start | |
164 | return res |
|
164 | return res | |
165 | else: |
|
165 | else: | |
166 | assert res is None |
|
166 | assert res is None | |
167 |
|
167 | |||
168 | def check_transform(transformer_cls, case): |
|
168 | def check_transform(transformer_cls, case): | |
169 | lines, start, expected = case |
|
169 | lines, start, expected = case | |
170 | transformer = transformer_cls(start) |
|
170 | transformer = transformer_cls(start) | |
171 | assert transformer.transform(lines) == expected |
|
171 | assert transformer.transform(lines) == expected | |
172 |
|
172 | |||
173 | def test_continued_line(): |
|
173 | def test_continued_line(): | |
174 | lines = MULTILINE_MAGIC_ASSIGN[0] |
|
174 | lines = MULTILINE_MAGIC_ASSIGN[0] | |
175 | assert ipt2.find_end_of_continued_line(lines, 1) == 2 |
|
175 | assert ipt2.find_end_of_continued_line(lines, 1) == 2 | |
176 |
|
176 | |||
177 | assert ipt2.assemble_continued_line(lines, (1, 5), 2) == "foo bar" |
|
177 | assert ipt2.assemble_continued_line(lines, (1, 5), 2) == "foo bar" | |
178 |
|
178 | |||
179 | def test_find_assign_magic(): |
|
179 | def test_find_assign_magic(): | |
180 | check_find(ipt2.MagicAssign, MULTILINE_MAGIC_ASSIGN) |
|
180 | check_find(ipt2.MagicAssign, MULTILINE_MAGIC_ASSIGN) | |
181 | check_find(ipt2.MagicAssign, MULTILINE_SYSTEM_ASSIGN, match=False) |
|
181 | check_find(ipt2.MagicAssign, MULTILINE_SYSTEM_ASSIGN, match=False) | |
182 | check_find(ipt2.MagicAssign, MULTILINE_SYSTEM_ASSIGN_AFTER_DEDENT, match=False) |
|
182 | check_find(ipt2.MagicAssign, MULTILINE_SYSTEM_ASSIGN_AFTER_DEDENT, match=False) | |
183 |
|
183 | |||
184 | def test_transform_assign_magic(): |
|
184 | def test_transform_assign_magic(): | |
185 | check_transform(ipt2.MagicAssign, MULTILINE_MAGIC_ASSIGN) |
|
185 | check_transform(ipt2.MagicAssign, MULTILINE_MAGIC_ASSIGN) | |
186 |
|
186 | |||
187 | def test_find_assign_system(): |
|
187 | def test_find_assign_system(): | |
188 | check_find(ipt2.SystemAssign, MULTILINE_SYSTEM_ASSIGN) |
|
188 | check_find(ipt2.SystemAssign, MULTILINE_SYSTEM_ASSIGN) | |
189 | check_find(ipt2.SystemAssign, MULTILINE_SYSTEM_ASSIGN_AFTER_DEDENT) |
|
189 | check_find(ipt2.SystemAssign, MULTILINE_SYSTEM_ASSIGN_AFTER_DEDENT) | |
190 | check_find(ipt2.SystemAssign, (["a = !ls\n"], (1, 5), None)) |
|
190 | check_find(ipt2.SystemAssign, (["a = !ls\n"], (1, 5), None)) | |
191 | check_find(ipt2.SystemAssign, (["a=!ls\n"], (1, 2), None)) |
|
191 | check_find(ipt2.SystemAssign, (["a=!ls\n"], (1, 2), None)) | |
192 | check_find(ipt2.SystemAssign, MULTILINE_MAGIC_ASSIGN, match=False) |
|
192 | check_find(ipt2.SystemAssign, MULTILINE_MAGIC_ASSIGN, match=False) | |
193 |
|
193 | |||
194 | def test_transform_assign_system(): |
|
194 | def test_transform_assign_system(): | |
195 | check_transform(ipt2.SystemAssign, MULTILINE_SYSTEM_ASSIGN) |
|
195 | check_transform(ipt2.SystemAssign, MULTILINE_SYSTEM_ASSIGN) | |
196 | check_transform(ipt2.SystemAssign, MULTILINE_SYSTEM_ASSIGN_AFTER_DEDENT) |
|
196 | check_transform(ipt2.SystemAssign, MULTILINE_SYSTEM_ASSIGN_AFTER_DEDENT) | |
197 |
|
197 | |||
198 | def test_find_magic_escape(): |
|
198 | def test_find_magic_escape(): | |
199 | check_find(ipt2.EscapedCommand, MULTILINE_MAGIC) |
|
199 | check_find(ipt2.EscapedCommand, MULTILINE_MAGIC) | |
200 | check_find(ipt2.EscapedCommand, INDENTED_MAGIC) |
|
200 | check_find(ipt2.EscapedCommand, INDENTED_MAGIC) | |
201 | check_find(ipt2.EscapedCommand, MULTILINE_MAGIC_ASSIGN, match=False) |
|
201 | check_find(ipt2.EscapedCommand, MULTILINE_MAGIC_ASSIGN, match=False) | |
202 |
|
202 | |||
203 | def test_transform_magic_escape(): |
|
203 | def test_transform_magic_escape(): | |
204 | check_transform(ipt2.EscapedCommand, MULTILINE_MAGIC) |
|
204 | check_transform(ipt2.EscapedCommand, MULTILINE_MAGIC) | |
205 | check_transform(ipt2.EscapedCommand, INDENTED_MAGIC) |
|
205 | check_transform(ipt2.EscapedCommand, INDENTED_MAGIC) | |
206 | check_transform(ipt2.EscapedCommand, CRLF_MAGIC) |
|
206 | check_transform(ipt2.EscapedCommand, CRLF_MAGIC) | |
207 |
|
207 | |||
208 | def test_find_autocalls(): |
|
208 | def test_find_autocalls(): | |
209 | for case in [AUTOCALL_QUOTE, AUTOCALL_QUOTE2, AUTOCALL_PAREN]: |
|
209 | for case in [AUTOCALL_QUOTE, AUTOCALL_QUOTE2, AUTOCALL_PAREN]: | |
210 | print("Testing %r" % case[0]) |
|
210 | print("Testing %r" % case[0]) | |
211 | check_find(ipt2.EscapedCommand, case) |
|
211 | check_find(ipt2.EscapedCommand, case) | |
212 |
|
212 | |||
213 | def test_transform_autocall(): |
|
213 | def test_transform_autocall(): | |
214 | for case in [AUTOCALL_QUOTE, AUTOCALL_QUOTE2, AUTOCALL_PAREN]: |
|
214 | for case in [AUTOCALL_QUOTE, AUTOCALL_QUOTE2, AUTOCALL_PAREN]: | |
215 | print("Testing %r" % case[0]) |
|
215 | print("Testing %r" % case[0]) | |
216 | check_transform(ipt2.EscapedCommand, case) |
|
216 | check_transform(ipt2.EscapedCommand, case) | |
217 |
|
217 | |||
218 | def test_find_help(): |
|
218 | def test_find_help(): | |
219 | for case in [SIMPLE_HELP, DETAILED_HELP, MAGIC_HELP, HELP_IN_EXPR]: |
|
219 | for case in [SIMPLE_HELP, DETAILED_HELP, MAGIC_HELP, HELP_IN_EXPR]: | |
220 | check_find(ipt2.HelpEnd, case) |
|
220 | check_find(ipt2.HelpEnd, case) | |
221 |
|
221 | |||
222 | tf = check_find(ipt2.HelpEnd, HELP_CONTINUED_LINE) |
|
222 | tf = check_find(ipt2.HelpEnd, HELP_CONTINUED_LINE) | |
223 | assert tf.q_line == 1 |
|
223 | assert tf.q_line == 1 | |
224 | assert tf.q_col == 3 |
|
224 | assert tf.q_col == 3 | |
225 |
|
225 | |||
226 | tf = check_find(ipt2.HelpEnd, HELP_MULTILINE) |
|
226 | tf = check_find(ipt2.HelpEnd, HELP_MULTILINE) | |
227 | assert tf.q_line == 1 |
|
227 | assert tf.q_line == 1 | |
228 | assert tf.q_col == 8 |
|
228 | assert tf.q_col == 8 | |
229 |
|
229 | |||
230 | # ? in a comment does not trigger help |
|
230 | # ? in a comment does not trigger help | |
231 | check_find(ipt2.HelpEnd, (["foo # bar?\n"], None, None), match=False) |
|
231 | check_find(ipt2.HelpEnd, (["foo # bar?\n"], None, None), match=False) | |
232 | # Nor in a string |
|
232 | # Nor in a string | |
233 | check_find(ipt2.HelpEnd, (["foo = '''bar?\n"], None, None), match=False) |
|
233 | check_find(ipt2.HelpEnd, (["foo = '''bar?\n"], None, None), match=False) | |
234 |
|
234 | |||
235 | def test_transform_help(): |
|
235 | def test_transform_help(): | |
236 | tf = ipt2.HelpEnd((1, 0), (1, 9)) |
|
236 | tf = ipt2.HelpEnd((1, 0), (1, 9)) | |
237 | assert tf.transform(HELP_IN_EXPR[0]) == HELP_IN_EXPR[2] |
|
237 | assert tf.transform(HELP_IN_EXPR[0]) == HELP_IN_EXPR[2] | |
238 |
|
238 | |||
239 | tf = ipt2.HelpEnd((1, 0), (2, 3)) |
|
239 | tf = ipt2.HelpEnd((1, 0), (2, 3)) | |
240 | assert tf.transform(HELP_CONTINUED_LINE[0]) == HELP_CONTINUED_LINE[2] |
|
240 | assert tf.transform(HELP_CONTINUED_LINE[0]) == HELP_CONTINUED_LINE[2] | |
241 |
|
241 | |||
242 | tf = ipt2.HelpEnd((1, 0), (2, 8)) |
|
242 | tf = ipt2.HelpEnd((1, 0), (2, 8)) | |
243 | assert tf.transform(HELP_MULTILINE[0]) == HELP_MULTILINE[2] |
|
243 | assert tf.transform(HELP_MULTILINE[0]) == HELP_MULTILINE[2] | |
244 |
|
244 | |||
245 | tf = ipt2.HelpEnd((1, 0), (1, 0)) |
|
245 | tf = ipt2.HelpEnd((1, 0), (1, 0)) | |
246 | assert tf.transform(HELP_UNICODE[0]) == HELP_UNICODE[2] |
|
246 | assert tf.transform(HELP_UNICODE[0]) == HELP_UNICODE[2] | |
247 |
|
247 | |||
248 | def test_find_assign_op_dedent(): |
|
248 | def test_find_assign_op_dedent(): | |
249 | """ |
|
249 | """ | |
250 | be careful that empty token like dedent are not counted as parens |
|
250 | be careful that empty token like dedent are not counted as parens | |
251 | """ |
|
251 | """ | |
252 | class Tk: |
|
252 | class Tk: | |
253 | def __init__(self, s): |
|
253 | def __init__(self, s): | |
254 | self.string = s |
|
254 | self.string = s | |
255 |
|
255 | |||
256 | assert _find_assign_op([Tk(s) for s in ("", "a", "=", "b")]) == 2 |
|
256 | assert _find_assign_op([Tk(s) for s in ("", "a", "=", "b")]) == 2 | |
257 | assert ( |
|
257 | assert ( | |
258 | _find_assign_op([Tk(s) for s in ("", "(", "a", "=", "b", ")", "=", "5")]) == 6 |
|
258 | _find_assign_op([Tk(s) for s in ("", "(", "a", "=", "b", ")", "=", "5")]) == 6 | |
259 | ) |
|
259 | ) | |
260 |
|
260 | |||
261 |
|
261 | |||
262 | examples = [ |
|
262 | examples = [ | |
263 | pytest.param("a = 1", "complete", None), |
|
263 | pytest.param("a = 1", "complete", None), | |
264 | pytest.param("for a in range(5):", "incomplete", 4), |
|
264 | pytest.param("for a in range(5):", "incomplete", 4), | |
265 | pytest.param("for a in range(5):\n if a > 0:", "incomplete", 8), |
|
265 | pytest.param("for a in range(5):\n if a > 0:", "incomplete", 8), | |
266 | pytest.param("raise = 2", "invalid", None), |
|
266 | pytest.param("raise = 2", "invalid", None), | |
267 | pytest.param("a = [1,\n2,", "incomplete", 0), |
|
267 | pytest.param("a = [1,\n2,", "incomplete", 0), | |
268 | pytest.param("(\n))", "incomplete", 0), |
|
268 | pytest.param("(\n))", "incomplete", 0), | |
269 | pytest.param("\\\r\n", "incomplete", 0), |
|
269 | pytest.param("\\\r\n", "incomplete", 0), | |
270 | pytest.param("a = '''\n hi", "incomplete", 3), |
|
270 | pytest.param("a = '''\n hi", "incomplete", 3), | |
271 | pytest.param("def a():\n x=1\n global x", "invalid", None), |
|
271 | pytest.param("def a():\n x=1\n global x", "invalid", None), | |
272 | pytest.param( |
|
272 | pytest.param( | |
273 | "a \\ ", |
|
273 | "a \\ ", | |
274 | "invalid", |
|
274 | "invalid", | |
275 | None, |
|
275 | None, | |
276 | marks=pytest.mark.xfail( |
|
276 | marks=pytest.mark.xfail( | |
277 | reason="Bug in python 3.9.8 – bpo 45738", |
|
277 | reason="Bug in python 3.9.8 – bpo 45738", | |
278 |
condition=sys.version_info |
|
278 | condition=sys.version_info | |
|
279 | in [(3, 9, 8, "final", 0), (3, 11, 0, "alpha", 2)], | |||
279 | raises=SystemError, |
|
280 | raises=SystemError, | |
280 | strict=True, |
|
281 | strict=True, | |
281 | ), |
|
282 | ), | |
282 | ), # Nothing allowed after backslash, |
|
283 | ), # Nothing allowed after backslash, | |
283 | pytest.param("1\\\n+2", "complete", None), |
|
284 | pytest.param("1\\\n+2", "complete", None), | |
284 | ] |
|
285 | ] | |
285 |
|
286 | |||
286 |
|
287 | |||
287 | @pytest.mark.parametrize("code, expected, number", examples) |
|
288 | @pytest.mark.parametrize("code, expected, number", examples) | |
288 | def test_check_complete_param(code, expected, number): |
|
289 | def test_check_complete_param(code, expected, number): | |
289 | cc = ipt2.TransformerManager().check_complete |
|
290 | cc = ipt2.TransformerManager().check_complete | |
290 | assert cc(code) == (expected, number) |
|
291 | assert cc(code) == (expected, number) | |
291 |
|
292 | |||
292 |
|
293 | |||
293 | @pytest.mark.xfail( |
|
294 | @pytest.mark.xfail( | |
294 | reason="Bug in python 3.9.8 – bpo 45738", |
|
295 | reason="Bug in python 3.9.8 – bpo 45738", | |
295 |
condition=sys.version_info[ |
|
296 | condition=sys.version_info in [(3, 9, 8, "final", 0), (3, 11, 0, "alpha", 2)], | |
|
297 | raises=SystemError, | |||
|
298 | strict=True, | |||
296 | ) |
|
299 | ) | |
297 | def test_check_complete(): |
|
300 | def test_check_complete(): | |
298 | cc = ipt2.TransformerManager().check_complete |
|
301 | cc = ipt2.TransformerManager().check_complete | |
299 |
|
302 | |||
300 | example = dedent(""" |
|
303 | example = dedent(""" | |
301 | if True: |
|
304 | if True: | |
302 | a=1""" ) |
|
305 | a=1""" ) | |
303 |
|
306 | |||
304 | assert cc(example) == ("incomplete", 4) |
|
307 | assert cc(example) == ("incomplete", 4) | |
305 | assert cc(example + "\n") == ("complete", None) |
|
308 | assert cc(example + "\n") == ("complete", None) | |
306 | assert cc(example + "\n ") == ("complete", None) |
|
309 | assert cc(example + "\n ") == ("complete", None) | |
307 |
|
310 | |||
308 | # no need to loop on all the letters/numbers. |
|
311 | # no need to loop on all the letters/numbers. | |
309 | short = '12abAB'+string.printable[62:] |
|
312 | short = '12abAB'+string.printable[62:] | |
310 | for c in short: |
|
313 | for c in short: | |
311 | # test does not raise: |
|
314 | # test does not raise: | |
312 | cc(c) |
|
315 | cc(c) | |
313 | for k in short: |
|
316 | for k in short: | |
314 | cc(c+k) |
|
317 | cc(c+k) | |
315 |
|
318 | |||
316 | assert cc("def f():\n x=0\n \\\n ") == ("incomplete", 2) |
|
319 | assert cc("def f():\n x=0\n \\\n ") == ("incomplete", 2) | |
317 |
|
320 | |||
318 |
|
321 | |||
319 | def test_check_complete_II(): |
|
322 | def test_check_complete_II(): | |
320 | """ |
|
323 | """ | |
321 | Test that multiple line strings are properly handled. |
|
324 | Test that multiple line strings are properly handled. | |
322 |
|
325 | |||
323 | Separate test function for convenience |
|
326 | Separate test function for convenience | |
324 |
|
327 | |||
325 | """ |
|
328 | """ | |
326 | cc = ipt2.TransformerManager().check_complete |
|
329 | cc = ipt2.TransformerManager().check_complete | |
327 | assert cc('''def foo():\n """''') == ("incomplete", 4) |
|
330 | assert cc('''def foo():\n """''') == ("incomplete", 4) | |
328 |
|
331 | |||
329 |
|
332 | |||
330 | def test_check_complete_invalidates_sunken_brackets(): |
|
333 | def test_check_complete_invalidates_sunken_brackets(): | |
331 | """ |
|
334 | """ | |
332 | Test that a single line with more closing brackets than the opening ones is |
|
335 | Test that a single line with more closing brackets than the opening ones is | |
333 | interpreted as invalid |
|
336 | interpreted as invalid | |
334 | """ |
|
337 | """ | |
335 | cc = ipt2.TransformerManager().check_complete |
|
338 | cc = ipt2.TransformerManager().check_complete | |
336 | assert cc(")") == ("invalid", None) |
|
339 | assert cc(")") == ("invalid", None) | |
337 | assert cc("]") == ("invalid", None) |
|
340 | assert cc("]") == ("invalid", None) | |
338 | assert cc("}") == ("invalid", None) |
|
341 | assert cc("}") == ("invalid", None) | |
339 | assert cc(")(") == ("invalid", None) |
|
342 | assert cc(")(") == ("invalid", None) | |
340 | assert cc("][") == ("invalid", None) |
|
343 | assert cc("][") == ("invalid", None) | |
341 | assert cc("}{") == ("invalid", None) |
|
344 | assert cc("}{") == ("invalid", None) | |
342 | assert cc("]()(") == ("invalid", None) |
|
345 | assert cc("]()(") == ("invalid", None) | |
343 | assert cc("())(") == ("invalid", None) |
|
346 | assert cc("())(") == ("invalid", None) | |
344 | assert cc(")[](") == ("invalid", None) |
|
347 | assert cc(")[](") == ("invalid", None) | |
345 | assert cc("()](") == ("invalid", None) |
|
348 | assert cc("()](") == ("invalid", None) | |
346 |
|
349 | |||
347 |
|
350 | |||
348 | def test_null_cleanup_transformer(): |
|
351 | def test_null_cleanup_transformer(): | |
349 | manager = ipt2.TransformerManager() |
|
352 | manager = ipt2.TransformerManager() | |
350 | manager.cleanup_transforms.insert(0, null_cleanup_transformer) |
|
353 | manager.cleanup_transforms.insert(0, null_cleanup_transformer) | |
351 | assert manager.transform_cell("") == "" |
|
354 | assert manager.transform_cell("") == "" | |
352 |
|
355 | |||
353 |
|
356 | |||
354 |
|
357 | |||
355 |
|
358 | |||
356 | def test_side_effects_I(): |
|
359 | def test_side_effects_I(): | |
357 | count = 0 |
|
360 | count = 0 | |
358 | def counter(lines): |
|
361 | def counter(lines): | |
359 | nonlocal count |
|
362 | nonlocal count | |
360 | count += 1 |
|
363 | count += 1 | |
361 | return lines |
|
364 | return lines | |
362 |
|
365 | |||
363 | counter.has_side_effects = True |
|
366 | counter.has_side_effects = True | |
364 |
|
367 | |||
365 | manager = ipt2.TransformerManager() |
|
368 | manager = ipt2.TransformerManager() | |
366 | manager.cleanup_transforms.insert(0, counter) |
|
369 | manager.cleanup_transforms.insert(0, counter) | |
367 | assert manager.check_complete("a=1\n") == ('complete', None) |
|
370 | assert manager.check_complete("a=1\n") == ('complete', None) | |
368 | assert count == 0 |
|
371 | assert count == 0 | |
369 |
|
372 | |||
370 |
|
373 | |||
371 |
|
374 | |||
372 |
|
375 | |||
373 | def test_side_effects_II(): |
|
376 | def test_side_effects_II(): | |
374 | count = 0 |
|
377 | count = 0 | |
375 | def counter(lines): |
|
378 | def counter(lines): | |
376 | nonlocal count |
|
379 | nonlocal count | |
377 | count += 1 |
|
380 | count += 1 | |
378 | return lines |
|
381 | return lines | |
379 |
|
382 | |||
380 | counter.has_side_effects = True |
|
383 | counter.has_side_effects = True | |
381 |
|
384 | |||
382 | manager = ipt2.TransformerManager() |
|
385 | manager = ipt2.TransformerManager() | |
383 | manager.line_transforms.insert(0, counter) |
|
386 | manager.line_transforms.insert(0, counter) | |
384 | assert manager.check_complete("b=1\n") == ('complete', None) |
|
387 | assert manager.check_complete("b=1\n") == ('complete', None) | |
385 | assert count == 0 |
|
388 | assert count == 0 |
@@ -1,1358 +1,1359 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Tests for various magic functions.""" |
|
2 | """Tests for various magic functions.""" | |
3 |
|
3 | |||
4 | import asyncio |
|
4 | import asyncio | |
5 | import io |
|
5 | import io | |
6 | import os |
|
6 | import os | |
7 | import re |
|
7 | import re | |
8 | import shlex |
|
8 | import shlex | |
9 | import sys |
|
9 | import sys | |
10 | import warnings |
|
10 | import warnings | |
11 | from importlib import invalidate_caches |
|
11 | from importlib import invalidate_caches | |
12 | from io import StringIO |
|
12 | from io import StringIO | |
13 | from pathlib import Path |
|
13 | from pathlib import Path | |
14 | from textwrap import dedent |
|
14 | from textwrap import dedent | |
15 | from unittest import TestCase, mock |
|
15 | from unittest import TestCase, mock | |
16 |
|
16 | |||
17 | import pytest |
|
17 | import pytest | |
18 |
|
18 | |||
19 | from IPython import get_ipython |
|
19 | from IPython import get_ipython | |
20 | from IPython.core import magic |
|
20 | from IPython.core import magic | |
21 | from IPython.core.error import UsageError |
|
21 | from IPython.core.error import UsageError | |
22 | from IPython.core.magic import ( |
|
22 | from IPython.core.magic import ( | |
23 | Magics, |
|
23 | Magics, | |
24 | cell_magic, |
|
24 | cell_magic, | |
25 | line_magic, |
|
25 | line_magic, | |
26 | magics_class, |
|
26 | magics_class, | |
27 | register_cell_magic, |
|
27 | register_cell_magic, | |
28 | register_line_magic, |
|
28 | register_line_magic, | |
29 | ) |
|
29 | ) | |
30 | from IPython.core.magics import code, execution, logging, osm, script |
|
30 | from IPython.core.magics import code, execution, logging, osm, script | |
31 | from IPython.testing import decorators as dec |
|
31 | from IPython.testing import decorators as dec | |
32 | from IPython.testing import tools as tt |
|
32 | from IPython.testing import tools as tt | |
33 | from IPython.utils.io import capture_output |
|
33 | from IPython.utils.io import capture_output | |
34 | from IPython.utils.process import find_cmd |
|
34 | from IPython.utils.process import find_cmd | |
35 | from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory |
|
35 | from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory | |
36 |
|
36 | |||
37 | from .test_debugger import PdbTestInput |
|
37 | from .test_debugger import PdbTestInput | |
38 |
|
38 | |||
39 |
|
39 | |||
40 | @magic.magics_class |
|
40 | @magic.magics_class | |
41 | class DummyMagics(magic.Magics): pass |
|
41 | class DummyMagics(magic.Magics): pass | |
42 |
|
42 | |||
43 | def test_extract_code_ranges(): |
|
43 | def test_extract_code_ranges(): | |
44 | instr = "1 3 5-6 7-9 10:15 17: :10 10- -13 :" |
|
44 | instr = "1 3 5-6 7-9 10:15 17: :10 10- -13 :" | |
45 | expected = [ |
|
45 | expected = [ | |
46 | (0, 1), |
|
46 | (0, 1), | |
47 | (2, 3), |
|
47 | (2, 3), | |
48 | (4, 6), |
|
48 | (4, 6), | |
49 | (6, 9), |
|
49 | (6, 9), | |
50 | (9, 14), |
|
50 | (9, 14), | |
51 | (16, None), |
|
51 | (16, None), | |
52 | (None, 9), |
|
52 | (None, 9), | |
53 | (9, None), |
|
53 | (9, None), | |
54 | (None, 13), |
|
54 | (None, 13), | |
55 | (None, None), |
|
55 | (None, None), | |
56 | ] |
|
56 | ] | |
57 | actual = list(code.extract_code_ranges(instr)) |
|
57 | actual = list(code.extract_code_ranges(instr)) | |
58 | assert actual == expected |
|
58 | assert actual == expected | |
59 |
|
59 | |||
60 | def test_extract_symbols(): |
|
60 | def test_extract_symbols(): | |
61 | source = """import foo\na = 10\ndef b():\n return 42\n\n\nclass A: pass\n\n\n""" |
|
61 | source = """import foo\na = 10\ndef b():\n return 42\n\n\nclass A: pass\n\n\n""" | |
62 | symbols_args = ["a", "b", "A", "A,b", "A,a", "z"] |
|
62 | symbols_args = ["a", "b", "A", "A,b", "A,a", "z"] | |
63 | expected = [([], ['a']), |
|
63 | expected = [([], ['a']), | |
64 | (["def b():\n return 42\n"], []), |
|
64 | (["def b():\n return 42\n"], []), | |
65 | (["class A: pass\n"], []), |
|
65 | (["class A: pass\n"], []), | |
66 | (["class A: pass\n", "def b():\n return 42\n"], []), |
|
66 | (["class A: pass\n", "def b():\n return 42\n"], []), | |
67 | (["class A: pass\n"], ['a']), |
|
67 | (["class A: pass\n"], ['a']), | |
68 | ([], ['z'])] |
|
68 | ([], ['z'])] | |
69 | for symbols, exp in zip(symbols_args, expected): |
|
69 | for symbols, exp in zip(symbols_args, expected): | |
70 | assert code.extract_symbols(source, symbols) == exp |
|
70 | assert code.extract_symbols(source, symbols) == exp | |
71 |
|
71 | |||
72 |
|
72 | |||
73 | def test_extract_symbols_raises_exception_with_non_python_code(): |
|
73 | def test_extract_symbols_raises_exception_with_non_python_code(): | |
74 | source = ("=begin A Ruby program :)=end\n" |
|
74 | source = ("=begin A Ruby program :)=end\n" | |
75 | "def hello\n" |
|
75 | "def hello\n" | |
76 | "puts 'Hello world'\n" |
|
76 | "puts 'Hello world'\n" | |
77 | "end") |
|
77 | "end") | |
78 | with pytest.raises(SyntaxError): |
|
78 | with pytest.raises(SyntaxError): | |
79 | code.extract_symbols(source, "hello") |
|
79 | code.extract_symbols(source, "hello") | |
80 |
|
80 | |||
81 |
|
81 | |||
82 | def test_magic_not_found(): |
|
82 | def test_magic_not_found(): | |
83 | # magic not found raises UsageError |
|
83 | # magic not found raises UsageError | |
84 | with pytest.raises(UsageError): |
|
84 | with pytest.raises(UsageError): | |
85 | _ip.magic('doesntexist') |
|
85 | _ip.magic('doesntexist') | |
86 |
|
86 | |||
87 | # ensure result isn't success when a magic isn't found |
|
87 | # ensure result isn't success when a magic isn't found | |
88 | result = _ip.run_cell('%doesntexist') |
|
88 | result = _ip.run_cell('%doesntexist') | |
89 | assert isinstance(result.error_in_exec, UsageError) |
|
89 | assert isinstance(result.error_in_exec, UsageError) | |
90 |
|
90 | |||
91 |
|
91 | |||
92 | def test_cell_magic_not_found(): |
|
92 | def test_cell_magic_not_found(): | |
93 | # magic not found raises UsageError |
|
93 | # magic not found raises UsageError | |
94 | with pytest.raises(UsageError): |
|
94 | with pytest.raises(UsageError): | |
95 | _ip.run_cell_magic('doesntexist', 'line', 'cell') |
|
95 | _ip.run_cell_magic('doesntexist', 'line', 'cell') | |
96 |
|
96 | |||
97 | # ensure result isn't success when a magic isn't found |
|
97 | # ensure result isn't success when a magic isn't found | |
98 | result = _ip.run_cell('%%doesntexist') |
|
98 | result = _ip.run_cell('%%doesntexist') | |
99 | assert isinstance(result.error_in_exec, UsageError) |
|
99 | assert isinstance(result.error_in_exec, UsageError) | |
100 |
|
100 | |||
101 |
|
101 | |||
102 | def test_magic_error_status(): |
|
102 | def test_magic_error_status(): | |
103 | def fail(shell): |
|
103 | def fail(shell): | |
104 | 1/0 |
|
104 | 1/0 | |
105 | _ip.register_magic_function(fail) |
|
105 | _ip.register_magic_function(fail) | |
106 | result = _ip.run_cell('%fail') |
|
106 | result = _ip.run_cell('%fail') | |
107 | assert isinstance(result.error_in_exec, ZeroDivisionError) |
|
107 | assert isinstance(result.error_in_exec, ZeroDivisionError) | |
108 |
|
108 | |||
109 |
|
109 | |||
110 | def test_config(): |
|
110 | def test_config(): | |
111 | """ test that config magic does not raise |
|
111 | """ test that config magic does not raise | |
112 | can happen if Configurable init is moved too early into |
|
112 | can happen if Configurable init is moved too early into | |
113 | Magics.__init__ as then a Config object will be registered as a |
|
113 | Magics.__init__ as then a Config object will be registered as a | |
114 | magic. |
|
114 | magic. | |
115 | """ |
|
115 | """ | |
116 | ## should not raise. |
|
116 | ## should not raise. | |
117 | _ip.magic('config') |
|
117 | _ip.magic('config') | |
118 |
|
118 | |||
119 | def test_config_available_configs(): |
|
119 | def test_config_available_configs(): | |
120 | """ test that config magic prints available configs in unique and |
|
120 | """ test that config magic prints available configs in unique and | |
121 | sorted order. """ |
|
121 | sorted order. """ | |
122 | with capture_output() as captured: |
|
122 | with capture_output() as captured: | |
123 | _ip.magic('config') |
|
123 | _ip.magic('config') | |
124 |
|
124 | |||
125 | stdout = captured.stdout |
|
125 | stdout = captured.stdout | |
126 | config_classes = stdout.strip().split('\n')[1:] |
|
126 | config_classes = stdout.strip().split('\n')[1:] | |
127 | assert config_classes == sorted(set(config_classes)) |
|
127 | assert config_classes == sorted(set(config_classes)) | |
128 |
|
128 | |||
129 | def test_config_print_class(): |
|
129 | def test_config_print_class(): | |
130 | """ test that config with a classname prints the class's options. """ |
|
130 | """ test that config with a classname prints the class's options. """ | |
131 | with capture_output() as captured: |
|
131 | with capture_output() as captured: | |
132 | _ip.magic('config TerminalInteractiveShell') |
|
132 | _ip.magic('config TerminalInteractiveShell') | |
133 |
|
133 | |||
134 | stdout = captured.stdout |
|
134 | stdout = captured.stdout | |
135 | assert re.match( |
|
135 | assert re.match( | |
136 | "TerminalInteractiveShell.* options", stdout.splitlines()[0] |
|
136 | "TerminalInteractiveShell.* options", stdout.splitlines()[0] | |
137 | ), f"{stdout}\n\n1st line of stdout not like 'TerminalInteractiveShell.* options'" |
|
137 | ), f"{stdout}\n\n1st line of stdout not like 'TerminalInteractiveShell.* options'" | |
138 |
|
138 | |||
139 |
|
139 | |||
140 | def test_rehashx(): |
|
140 | def test_rehashx(): | |
141 | # clear up everything |
|
141 | # clear up everything | |
142 | _ip.alias_manager.clear_aliases() |
|
142 | _ip.alias_manager.clear_aliases() | |
143 | del _ip.db['syscmdlist'] |
|
143 | del _ip.db['syscmdlist'] | |
144 |
|
144 | |||
145 | _ip.magic('rehashx') |
|
145 | _ip.magic('rehashx') | |
146 | # Practically ALL ipython development systems will have more than 10 aliases |
|
146 | # Practically ALL ipython development systems will have more than 10 aliases | |
147 |
|
147 | |||
148 | assert len(_ip.alias_manager.aliases) > 10 |
|
148 | assert len(_ip.alias_manager.aliases) > 10 | |
149 | for name, cmd in _ip.alias_manager.aliases: |
|
149 | for name, cmd in _ip.alias_manager.aliases: | |
150 | # we must strip dots from alias names |
|
150 | # we must strip dots from alias names | |
151 | assert "." not in name |
|
151 | assert "." not in name | |
152 |
|
152 | |||
153 | # rehashx must fill up syscmdlist |
|
153 | # rehashx must fill up syscmdlist | |
154 | scoms = _ip.db['syscmdlist'] |
|
154 | scoms = _ip.db['syscmdlist'] | |
155 | assert len(scoms) > 10 |
|
155 | assert len(scoms) > 10 | |
156 |
|
156 | |||
157 |
|
157 | |||
158 | def test_magic_parse_options(): |
|
158 | def test_magic_parse_options(): | |
159 | """Test that we don't mangle paths when parsing magic options.""" |
|
159 | """Test that we don't mangle paths when parsing magic options.""" | |
160 | ip = get_ipython() |
|
160 | ip = get_ipython() | |
161 | path = 'c:\\x' |
|
161 | path = 'c:\\x' | |
162 | m = DummyMagics(ip) |
|
162 | m = DummyMagics(ip) | |
163 | opts = m.parse_options('-f %s' % path,'f:')[0] |
|
163 | opts = m.parse_options('-f %s' % path,'f:')[0] | |
164 | # argv splitting is os-dependent |
|
164 | # argv splitting is os-dependent | |
165 | if os.name == 'posix': |
|
165 | if os.name == 'posix': | |
166 | expected = 'c:x' |
|
166 | expected = 'c:x' | |
167 | else: |
|
167 | else: | |
168 | expected = path |
|
168 | expected = path | |
169 | assert opts["f"] == expected |
|
169 | assert opts["f"] == expected | |
170 |
|
170 | |||
171 |
|
171 | |||
172 | def test_magic_parse_long_options(): |
|
172 | def test_magic_parse_long_options(): | |
173 | """Magic.parse_options can handle --foo=bar long options""" |
|
173 | """Magic.parse_options can handle --foo=bar long options""" | |
174 | ip = get_ipython() |
|
174 | ip = get_ipython() | |
175 | m = DummyMagics(ip) |
|
175 | m = DummyMagics(ip) | |
176 | opts, _ = m.parse_options("--foo --bar=bubble", "a", "foo", "bar=") |
|
176 | opts, _ = m.parse_options("--foo --bar=bubble", "a", "foo", "bar=") | |
177 | assert "foo" in opts |
|
177 | assert "foo" in opts | |
178 | assert "bar" in opts |
|
178 | assert "bar" in opts | |
179 | assert opts["bar"] == "bubble" |
|
179 | assert opts["bar"] == "bubble" | |
180 |
|
180 | |||
181 |
|
181 | |||
182 | def doctest_hist_f(): |
|
182 | def doctest_hist_f(): | |
183 | """Test %hist -f with temporary filename. |
|
183 | """Test %hist -f with temporary filename. | |
184 |
|
184 | |||
185 | In [9]: import tempfile |
|
185 | In [9]: import tempfile | |
186 |
|
186 | |||
187 | In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-') |
|
187 | In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-') | |
188 |
|
188 | |||
189 | In [11]: %hist -nl -f $tfile 3 |
|
189 | In [11]: %hist -nl -f $tfile 3 | |
190 |
|
190 | |||
191 | In [13]: import os; os.unlink(tfile) |
|
191 | In [13]: import os; os.unlink(tfile) | |
192 | """ |
|
192 | """ | |
193 |
|
193 | |||
194 |
|
194 | |||
195 | def doctest_hist_op(): |
|
195 | def doctest_hist_op(): | |
196 | """Test %hist -op |
|
196 | """Test %hist -op | |
197 |
|
197 | |||
198 | In [1]: class b(float): |
|
198 | In [1]: class b(float): | |
199 | ...: pass |
|
199 | ...: pass | |
200 | ...: |
|
200 | ...: | |
201 |
|
201 | |||
202 | In [2]: class s(object): |
|
202 | In [2]: class s(object): | |
203 | ...: def __str__(self): |
|
203 | ...: def __str__(self): | |
204 | ...: return 's' |
|
204 | ...: return 's' | |
205 | ...: |
|
205 | ...: | |
206 |
|
206 | |||
207 | In [3]: |
|
207 | In [3]: | |
208 |
|
208 | |||
209 | In [4]: class r(b): |
|
209 | In [4]: class r(b): | |
210 | ...: def __repr__(self): |
|
210 | ...: def __repr__(self): | |
211 | ...: return 'r' |
|
211 | ...: return 'r' | |
212 | ...: |
|
212 | ...: | |
213 |
|
213 | |||
214 | In [5]: class sr(s,r): pass |
|
214 | In [5]: class sr(s,r): pass | |
215 | ...: |
|
215 | ...: | |
216 |
|
216 | |||
217 | In [6]: |
|
217 | In [6]: | |
218 |
|
218 | |||
219 | In [7]: bb=b() |
|
219 | In [7]: bb=b() | |
220 |
|
220 | |||
221 | In [8]: ss=s() |
|
221 | In [8]: ss=s() | |
222 |
|
222 | |||
223 | In [9]: rr=r() |
|
223 | In [9]: rr=r() | |
224 |
|
224 | |||
225 | In [10]: ssrr=sr() |
|
225 | In [10]: ssrr=sr() | |
226 |
|
226 | |||
227 | In [11]: 4.5 |
|
227 | In [11]: 4.5 | |
228 | Out[11]: 4.5 |
|
228 | Out[11]: 4.5 | |
229 |
|
229 | |||
230 | In [12]: str(ss) |
|
230 | In [12]: str(ss) | |
231 | Out[12]: 's' |
|
231 | Out[12]: 's' | |
232 |
|
232 | |||
233 | In [13]: |
|
233 | In [13]: | |
234 |
|
234 | |||
235 | In [14]: %hist -op |
|
235 | In [14]: %hist -op | |
236 | >>> class b: |
|
236 | >>> class b: | |
237 | ... pass |
|
237 | ... pass | |
238 | ... |
|
238 | ... | |
239 | >>> class s(b): |
|
239 | >>> class s(b): | |
240 | ... def __str__(self): |
|
240 | ... def __str__(self): | |
241 | ... return 's' |
|
241 | ... return 's' | |
242 | ... |
|
242 | ... | |
243 | >>> |
|
243 | >>> | |
244 | >>> class r(b): |
|
244 | >>> class r(b): | |
245 | ... def __repr__(self): |
|
245 | ... def __repr__(self): | |
246 | ... return 'r' |
|
246 | ... return 'r' | |
247 | ... |
|
247 | ... | |
248 | >>> class sr(s,r): pass |
|
248 | >>> class sr(s,r): pass | |
249 | >>> |
|
249 | >>> | |
250 | >>> bb=b() |
|
250 | >>> bb=b() | |
251 | >>> ss=s() |
|
251 | >>> ss=s() | |
252 | >>> rr=r() |
|
252 | >>> rr=r() | |
253 | >>> ssrr=sr() |
|
253 | >>> ssrr=sr() | |
254 | >>> 4.5 |
|
254 | >>> 4.5 | |
255 | 4.5 |
|
255 | 4.5 | |
256 | >>> str(ss) |
|
256 | >>> str(ss) | |
257 | 's' |
|
257 | 's' | |
258 | >>> |
|
258 | >>> | |
259 | """ |
|
259 | """ | |
260 |
|
260 | |||
261 | def test_hist_pof(): |
|
261 | def test_hist_pof(): | |
262 | ip = get_ipython() |
|
262 | ip = get_ipython() | |
263 | ip.run_cell("1+2", store_history=True) |
|
263 | ip.run_cell("1+2", store_history=True) | |
264 | #raise Exception(ip.history_manager.session_number) |
|
264 | #raise Exception(ip.history_manager.session_number) | |
265 | #raise Exception(list(ip.history_manager._get_range_session())) |
|
265 | #raise Exception(list(ip.history_manager._get_range_session())) | |
266 | with TemporaryDirectory() as td: |
|
266 | with TemporaryDirectory() as td: | |
267 | tf = os.path.join(td, 'hist.py') |
|
267 | tf = os.path.join(td, 'hist.py') | |
268 | ip.run_line_magic('history', '-pof %s' % tf) |
|
268 | ip.run_line_magic('history', '-pof %s' % tf) | |
269 | assert os.path.isfile(tf) |
|
269 | assert os.path.isfile(tf) | |
270 |
|
270 | |||
271 |
|
271 | |||
272 | def test_macro(): |
|
272 | def test_macro(): | |
273 | ip = get_ipython() |
|
273 | ip = get_ipython() | |
274 | ip.history_manager.reset() # Clear any existing history. |
|
274 | ip.history_manager.reset() # Clear any existing history. | |
275 | cmds = ["a=1", "def b():\n return a**2", "print(a,b())"] |
|
275 | cmds = ["a=1", "def b():\n return a**2", "print(a,b())"] | |
276 | for i, cmd in enumerate(cmds, start=1): |
|
276 | for i, cmd in enumerate(cmds, start=1): | |
277 | ip.history_manager.store_inputs(i, cmd) |
|
277 | ip.history_manager.store_inputs(i, cmd) | |
278 | ip.magic("macro test 1-3") |
|
278 | ip.magic("macro test 1-3") | |
279 | assert ip.user_ns["test"].value == "\n".join(cmds) + "\n" |
|
279 | assert ip.user_ns["test"].value == "\n".join(cmds) + "\n" | |
280 |
|
280 | |||
281 | # List macros |
|
281 | # List macros | |
282 | assert "test" in ip.magic("macro") |
|
282 | assert "test" in ip.magic("macro") | |
283 |
|
283 | |||
284 |
|
284 | |||
285 | def test_macro_run(): |
|
285 | def test_macro_run(): | |
286 | """Test that we can run a multi-line macro successfully.""" |
|
286 | """Test that we can run a multi-line macro successfully.""" | |
287 | ip = get_ipython() |
|
287 | ip = get_ipython() | |
288 | ip.history_manager.reset() |
|
288 | ip.history_manager.reset() | |
289 | cmds = ["a=10", "a+=1", "print(a)", "%macro test 2-3"] |
|
289 | cmds = ["a=10", "a+=1", "print(a)", "%macro test 2-3"] | |
290 | for cmd in cmds: |
|
290 | for cmd in cmds: | |
291 | ip.run_cell(cmd, store_history=True) |
|
291 | ip.run_cell(cmd, store_history=True) | |
292 | assert ip.user_ns["test"].value == "a+=1\nprint(a)\n" |
|
292 | assert ip.user_ns["test"].value == "a+=1\nprint(a)\n" | |
293 | with tt.AssertPrints("12"): |
|
293 | with tt.AssertPrints("12"): | |
294 | ip.run_cell("test") |
|
294 | ip.run_cell("test") | |
295 | with tt.AssertPrints("13"): |
|
295 | with tt.AssertPrints("13"): | |
296 | ip.run_cell("test") |
|
296 | ip.run_cell("test") | |
297 |
|
297 | |||
298 |
|
298 | |||
299 | def test_magic_magic(): |
|
299 | def test_magic_magic(): | |
300 | """Test %magic""" |
|
300 | """Test %magic""" | |
301 | ip = get_ipython() |
|
301 | ip = get_ipython() | |
302 | with capture_output() as captured: |
|
302 | with capture_output() as captured: | |
303 | ip.magic("magic") |
|
303 | ip.magic("magic") | |
304 |
|
304 | |||
305 | stdout = captured.stdout |
|
305 | stdout = captured.stdout | |
306 | assert "%magic" in stdout |
|
306 | assert "%magic" in stdout | |
307 | assert "IPython" in stdout |
|
307 | assert "IPython" in stdout | |
308 | assert "Available" in stdout |
|
308 | assert "Available" in stdout | |
309 |
|
309 | |||
310 |
|
310 | |||
311 | @dec.skipif_not_numpy |
|
311 | @dec.skipif_not_numpy | |
312 | def test_numpy_reset_array_undec(): |
|
312 | def test_numpy_reset_array_undec(): | |
313 | "Test '%reset array' functionality" |
|
313 | "Test '%reset array' functionality" | |
314 | _ip.ex("import numpy as np") |
|
314 | _ip.ex("import numpy as np") | |
315 | _ip.ex("a = np.empty(2)") |
|
315 | _ip.ex("a = np.empty(2)") | |
316 | assert "a" in _ip.user_ns |
|
316 | assert "a" in _ip.user_ns | |
317 | _ip.magic("reset -f array") |
|
317 | _ip.magic("reset -f array") | |
318 | assert "a" not in _ip.user_ns |
|
318 | assert "a" not in _ip.user_ns | |
319 |
|
319 | |||
320 |
|
320 | |||
321 | def test_reset_out(): |
|
321 | def test_reset_out(): | |
322 | "Test '%reset out' magic" |
|
322 | "Test '%reset out' magic" | |
323 | _ip.run_cell("parrot = 'dead'", store_history=True) |
|
323 | _ip.run_cell("parrot = 'dead'", store_history=True) | |
324 | # test '%reset -f out', make an Out prompt |
|
324 | # test '%reset -f out', make an Out prompt | |
325 | _ip.run_cell("parrot", store_history=True) |
|
325 | _ip.run_cell("parrot", store_history=True) | |
326 | assert "dead" in [_ip.user_ns[x] for x in ("_", "__", "___")] |
|
326 | assert "dead" in [_ip.user_ns[x] for x in ("_", "__", "___")] | |
327 | _ip.magic("reset -f out") |
|
327 | _ip.magic("reset -f out") | |
328 | assert "dead" not in [_ip.user_ns[x] for x in ("_", "__", "___")] |
|
328 | assert "dead" not in [_ip.user_ns[x] for x in ("_", "__", "___")] | |
329 | assert len(_ip.user_ns["Out"]) == 0 |
|
329 | assert len(_ip.user_ns["Out"]) == 0 | |
330 |
|
330 | |||
331 |
|
331 | |||
332 | def test_reset_in(): |
|
332 | def test_reset_in(): | |
333 | "Test '%reset in' magic" |
|
333 | "Test '%reset in' magic" | |
334 | # test '%reset -f in' |
|
334 | # test '%reset -f in' | |
335 | _ip.run_cell("parrot", store_history=True) |
|
335 | _ip.run_cell("parrot", store_history=True) | |
336 | assert "parrot" in [_ip.user_ns[x] for x in ("_i", "_ii", "_iii")] |
|
336 | assert "parrot" in [_ip.user_ns[x] for x in ("_i", "_ii", "_iii")] | |
337 | _ip.magic("%reset -f in") |
|
337 | _ip.magic("%reset -f in") | |
338 | assert "parrot" not in [_ip.user_ns[x] for x in ("_i", "_ii", "_iii")] |
|
338 | assert "parrot" not in [_ip.user_ns[x] for x in ("_i", "_ii", "_iii")] | |
339 | assert len(set(_ip.user_ns["In"])) == 1 |
|
339 | assert len(set(_ip.user_ns["In"])) == 1 | |
340 |
|
340 | |||
341 |
|
341 | |||
342 | def test_reset_dhist(): |
|
342 | def test_reset_dhist(): | |
343 | "Test '%reset dhist' magic" |
|
343 | "Test '%reset dhist' magic" | |
344 | _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing |
|
344 | _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing | |
345 | _ip.magic("cd " + os.path.dirname(pytest.__file__)) |
|
345 | _ip.magic("cd " + os.path.dirname(pytest.__file__)) | |
346 | _ip.magic("cd -") |
|
346 | _ip.magic("cd -") | |
347 | assert len(_ip.user_ns["_dh"]) > 0 |
|
347 | assert len(_ip.user_ns["_dh"]) > 0 | |
348 | _ip.magic("reset -f dhist") |
|
348 | _ip.magic("reset -f dhist") | |
349 | assert len(_ip.user_ns["_dh"]) == 0 |
|
349 | assert len(_ip.user_ns["_dh"]) == 0 | |
350 | _ip.run_cell("_dh = [d for d in tmp]") # restore |
|
350 | _ip.run_cell("_dh = [d for d in tmp]") # restore | |
351 |
|
351 | |||
352 |
|
352 | |||
353 | def test_reset_in_length(): |
|
353 | def test_reset_in_length(): | |
354 | "Test that '%reset in' preserves In[] length" |
|
354 | "Test that '%reset in' preserves In[] length" | |
355 | _ip.run_cell("print 'foo'") |
|
355 | _ip.run_cell("print 'foo'") | |
356 | _ip.run_cell("reset -f in") |
|
356 | _ip.run_cell("reset -f in") | |
357 | assert len(_ip.user_ns["In"]) == _ip.displayhook.prompt_count + 1 |
|
357 | assert len(_ip.user_ns["In"]) == _ip.displayhook.prompt_count + 1 | |
358 |
|
358 | |||
359 |
|
359 | |||
360 | class TestResetErrors(TestCase): |
|
360 | class TestResetErrors(TestCase): | |
361 |
|
361 | |||
362 | def test_reset_redefine(self): |
|
362 | def test_reset_redefine(self): | |
363 |
|
363 | |||
364 | @magics_class |
|
364 | @magics_class | |
365 | class KernelMagics(Magics): |
|
365 | class KernelMagics(Magics): | |
366 | @line_magic |
|
366 | @line_magic | |
367 | def less(self, shell): pass |
|
367 | def less(self, shell): pass | |
368 |
|
368 | |||
369 | _ip.register_magics(KernelMagics) |
|
369 | _ip.register_magics(KernelMagics) | |
370 |
|
370 | |||
371 | with self.assertLogs() as cm: |
|
371 | with self.assertLogs() as cm: | |
372 | # hack, we want to just capture logs, but assertLogs fails if not |
|
372 | # hack, we want to just capture logs, but assertLogs fails if not | |
373 | # logs get produce. |
|
373 | # logs get produce. | |
374 | # so log one things we ignore. |
|
374 | # so log one things we ignore. | |
375 | import logging as log_mod |
|
375 | import logging as log_mod | |
376 | log = log_mod.getLogger() |
|
376 | log = log_mod.getLogger() | |
377 | log.info('Nothing') |
|
377 | log.info('Nothing') | |
378 | # end hack. |
|
378 | # end hack. | |
379 | _ip.run_cell("reset -f") |
|
379 | _ip.run_cell("reset -f") | |
380 |
|
380 | |||
381 | assert len(cm.output) == 1 |
|
381 | assert len(cm.output) == 1 | |
382 | for out in cm.output: |
|
382 | for out in cm.output: | |
383 | assert "Invalid alias" not in out |
|
383 | assert "Invalid alias" not in out | |
384 |
|
384 | |||
385 | def test_tb_syntaxerror(): |
|
385 | def test_tb_syntaxerror(): | |
386 | """test %tb after a SyntaxError""" |
|
386 | """test %tb after a SyntaxError""" | |
387 | ip = get_ipython() |
|
387 | ip = get_ipython() | |
388 | ip.run_cell("for") |
|
388 | ip.run_cell("for") | |
389 |
|
389 | |||
390 | # trap and validate stdout |
|
390 | # trap and validate stdout | |
391 | save_stdout = sys.stdout |
|
391 | save_stdout = sys.stdout | |
392 | try: |
|
392 | try: | |
393 | sys.stdout = StringIO() |
|
393 | sys.stdout = StringIO() | |
394 | ip.run_cell("%tb") |
|
394 | ip.run_cell("%tb") | |
395 | out = sys.stdout.getvalue() |
|
395 | out = sys.stdout.getvalue() | |
396 | finally: |
|
396 | finally: | |
397 | sys.stdout = save_stdout |
|
397 | sys.stdout = save_stdout | |
398 | # trim output, and only check the last line |
|
398 | # trim output, and only check the last line | |
399 | last_line = out.rstrip().splitlines()[-1].strip() |
|
399 | last_line = out.rstrip().splitlines()[-1].strip() | |
400 | assert last_line == "SyntaxError: invalid syntax" |
|
400 | assert last_line == "SyntaxError: invalid syntax" | |
401 |
|
401 | |||
402 |
|
402 | |||
403 | def test_time(): |
|
403 | def test_time(): | |
404 | ip = get_ipython() |
|
404 | ip = get_ipython() | |
405 |
|
405 | |||
406 | with tt.AssertPrints("Wall time: "): |
|
406 | with tt.AssertPrints("Wall time: "): | |
407 | ip.run_cell("%time None") |
|
407 | ip.run_cell("%time None") | |
408 |
|
408 | |||
409 | ip.run_cell("def f(kmjy):\n" |
|
409 | ip.run_cell("def f(kmjy):\n" | |
410 | " %time print (2*kmjy)") |
|
410 | " %time print (2*kmjy)") | |
411 |
|
411 | |||
412 | with tt.AssertPrints("Wall time: "): |
|
412 | with tt.AssertPrints("Wall time: "): | |
413 | with tt.AssertPrints("hihi", suppress=False): |
|
413 | with tt.AssertPrints("hihi", suppress=False): | |
414 | ip.run_cell("f('hi')") |
|
414 | ip.run_cell("f('hi')") | |
415 |
|
415 | |||
416 | def test_time_last_not_expression(): |
|
416 | def test_time_last_not_expression(): | |
417 | ip.run_cell("%%time\n" |
|
417 | ip.run_cell("%%time\n" | |
418 | "var_1 = 1\n" |
|
418 | "var_1 = 1\n" | |
419 | "var_2 = 2\n") |
|
419 | "var_2 = 2\n") | |
420 | assert ip.user_ns['var_1'] == 1 |
|
420 | assert ip.user_ns['var_1'] == 1 | |
421 | del ip.user_ns['var_1'] |
|
421 | del ip.user_ns['var_1'] | |
422 | assert ip.user_ns['var_2'] == 2 |
|
422 | assert ip.user_ns['var_2'] == 2 | |
423 | del ip.user_ns['var_2'] |
|
423 | del ip.user_ns['var_2'] | |
424 |
|
424 | |||
425 |
|
425 | |||
426 | @dec.skip_win32 |
|
426 | @dec.skip_win32 | |
427 | def test_time2(): |
|
427 | def test_time2(): | |
428 | ip = get_ipython() |
|
428 | ip = get_ipython() | |
429 |
|
429 | |||
430 | with tt.AssertPrints("CPU times: user "): |
|
430 | with tt.AssertPrints("CPU times: user "): | |
431 | ip.run_cell("%time None") |
|
431 | ip.run_cell("%time None") | |
432 |
|
432 | |||
433 | def test_time3(): |
|
433 | def test_time3(): | |
434 | """Erroneous magic function calls, issue gh-3334""" |
|
434 | """Erroneous magic function calls, issue gh-3334""" | |
435 | ip = get_ipython() |
|
435 | ip = get_ipython() | |
436 | ip.user_ns.pop('run', None) |
|
436 | ip.user_ns.pop('run', None) | |
437 |
|
437 | |||
438 | with tt.AssertNotPrints("not found", channel='stderr'): |
|
438 | with tt.AssertNotPrints("not found", channel='stderr'): | |
439 | ip.run_cell("%%time\n" |
|
439 | ip.run_cell("%%time\n" | |
440 | "run = 0\n" |
|
440 | "run = 0\n" | |
441 | "run += 1") |
|
441 | "run += 1") | |
442 |
|
442 | |||
443 | def test_multiline_time(): |
|
443 | def test_multiline_time(): | |
444 | """Make sure last statement from time return a value.""" |
|
444 | """Make sure last statement from time return a value.""" | |
445 | ip = get_ipython() |
|
445 | ip = get_ipython() | |
446 | ip.user_ns.pop('run', None) |
|
446 | ip.user_ns.pop('run', None) | |
447 |
|
447 | |||
448 | ip.run_cell(dedent("""\ |
|
448 | ip.run_cell(dedent("""\ | |
449 | %%time |
|
449 | %%time | |
450 | a = "ho" |
|
450 | a = "ho" | |
451 | b = "hey" |
|
451 | b = "hey" | |
452 | a+b |
|
452 | a+b | |
453 | """ |
|
453 | """ | |
454 | ) |
|
454 | ) | |
455 | ) |
|
455 | ) | |
456 | assert ip.user_ns_hidden["_"] == "hohey" |
|
456 | assert ip.user_ns_hidden["_"] == "hohey" | |
457 |
|
457 | |||
458 |
|
458 | |||
459 | def test_time_local_ns(): |
|
459 | def test_time_local_ns(): | |
460 | """ |
|
460 | """ | |
461 | Test that local_ns is actually global_ns when running a cell magic |
|
461 | Test that local_ns is actually global_ns when running a cell magic | |
462 | """ |
|
462 | """ | |
463 | ip = get_ipython() |
|
463 | ip = get_ipython() | |
464 | ip.run_cell("%%time\n" "myvar = 1") |
|
464 | ip.run_cell("%%time\n" "myvar = 1") | |
465 | assert ip.user_ns["myvar"] == 1 |
|
465 | assert ip.user_ns["myvar"] == 1 | |
466 | del ip.user_ns["myvar"] |
|
466 | del ip.user_ns["myvar"] | |
467 |
|
467 | |||
468 |
|
468 | |||
469 | def test_doctest_mode(): |
|
469 | def test_doctest_mode(): | |
470 | "Toggle doctest_mode twice, it should be a no-op and run without error" |
|
470 | "Toggle doctest_mode twice, it should be a no-op and run without error" | |
471 | _ip.magic('doctest_mode') |
|
471 | _ip.magic('doctest_mode') | |
472 | _ip.magic('doctest_mode') |
|
472 | _ip.magic('doctest_mode') | |
473 |
|
473 | |||
474 |
|
474 | |||
475 | def test_parse_options(): |
|
475 | def test_parse_options(): | |
476 | """Tests for basic options parsing in magics.""" |
|
476 | """Tests for basic options parsing in magics.""" | |
477 | # These are only the most minimal of tests, more should be added later. At |
|
477 | # These are only the most minimal of tests, more should be added later. At | |
478 | # the very least we check that basic text/unicode calls work OK. |
|
478 | # the very least we check that basic text/unicode calls work OK. | |
479 | m = DummyMagics(_ip) |
|
479 | m = DummyMagics(_ip) | |
480 | assert m.parse_options("foo", "")[1] == "foo" |
|
480 | assert m.parse_options("foo", "")[1] == "foo" | |
481 | assert m.parse_options("foo", "")[1] == "foo" |
|
481 | assert m.parse_options("foo", "")[1] == "foo" | |
482 |
|
482 | |||
483 |
|
483 | |||
484 | def test_parse_options_preserve_non_option_string(): |
|
484 | def test_parse_options_preserve_non_option_string(): | |
485 | """Test to assert preservation of non-option part of magic-block, while parsing magic options.""" |
|
485 | """Test to assert preservation of non-option part of magic-block, while parsing magic options.""" | |
486 | m = DummyMagics(_ip) |
|
486 | m = DummyMagics(_ip) | |
487 | opts, stmt = m.parse_options( |
|
487 | opts, stmt = m.parse_options( | |
488 | " -n1 -r 13 _ = 314 + foo", "n:r:", preserve_non_opts=True |
|
488 | " -n1 -r 13 _ = 314 + foo", "n:r:", preserve_non_opts=True | |
489 | ) |
|
489 | ) | |
490 | assert opts == {"n": "1", "r": "13"} |
|
490 | assert opts == {"n": "1", "r": "13"} | |
491 | assert stmt == "_ = 314 + foo" |
|
491 | assert stmt == "_ = 314 + foo" | |
492 |
|
492 | |||
493 |
|
493 | |||
494 | def test_run_magic_preserve_code_block(): |
|
494 | def test_run_magic_preserve_code_block(): | |
495 | """Test to assert preservation of non-option part of magic-block, while running magic.""" |
|
495 | """Test to assert preservation of non-option part of magic-block, while running magic.""" | |
496 | _ip.user_ns["spaces"] = [] |
|
496 | _ip.user_ns["spaces"] = [] | |
497 | _ip.magic("timeit -n1 -r1 spaces.append([s.count(' ') for s in ['document']])") |
|
497 | _ip.magic("timeit -n1 -r1 spaces.append([s.count(' ') for s in ['document']])") | |
498 | assert _ip.user_ns["spaces"] == [[0]] |
|
498 | assert _ip.user_ns["spaces"] == [[0]] | |
499 |
|
499 | |||
500 |
|
500 | |||
501 | def test_dirops(): |
|
501 | def test_dirops(): | |
502 | """Test various directory handling operations.""" |
|
502 | """Test various directory handling operations.""" | |
503 | # curpath = lambda :os.path.splitdrive(os.getcwd())[1].replace('\\','/') |
|
503 | # curpath = lambda :os.path.splitdrive(os.getcwd())[1].replace('\\','/') | |
504 | curpath = os.getcwd |
|
504 | curpath = os.getcwd | |
505 | startdir = os.getcwd() |
|
505 | startdir = os.getcwd() | |
506 | ipdir = os.path.realpath(_ip.ipython_dir) |
|
506 | ipdir = os.path.realpath(_ip.ipython_dir) | |
507 | try: |
|
507 | try: | |
508 | _ip.magic('cd "%s"' % ipdir) |
|
508 | _ip.magic('cd "%s"' % ipdir) | |
509 | assert curpath() == ipdir |
|
509 | assert curpath() == ipdir | |
510 | _ip.magic('cd -') |
|
510 | _ip.magic('cd -') | |
511 | assert curpath() == startdir |
|
511 | assert curpath() == startdir | |
512 | _ip.magic('pushd "%s"' % ipdir) |
|
512 | _ip.magic('pushd "%s"' % ipdir) | |
513 | assert curpath() == ipdir |
|
513 | assert curpath() == ipdir | |
514 | _ip.magic('popd') |
|
514 | _ip.magic('popd') | |
515 | assert curpath() == startdir |
|
515 | assert curpath() == startdir | |
516 | finally: |
|
516 | finally: | |
517 | os.chdir(startdir) |
|
517 | os.chdir(startdir) | |
518 |
|
518 | |||
519 |
|
519 | |||
520 | def test_cd_force_quiet(): |
|
520 | def test_cd_force_quiet(): | |
521 | """Test OSMagics.cd_force_quiet option""" |
|
521 | """Test OSMagics.cd_force_quiet option""" | |
522 | _ip.config.OSMagics.cd_force_quiet = True |
|
522 | _ip.config.OSMagics.cd_force_quiet = True | |
523 | osmagics = osm.OSMagics(shell=_ip) |
|
523 | osmagics = osm.OSMagics(shell=_ip) | |
524 |
|
524 | |||
525 | startdir = os.getcwd() |
|
525 | startdir = os.getcwd() | |
526 | ipdir = os.path.realpath(_ip.ipython_dir) |
|
526 | ipdir = os.path.realpath(_ip.ipython_dir) | |
527 |
|
527 | |||
528 | try: |
|
528 | try: | |
529 | with tt.AssertNotPrints(ipdir): |
|
529 | with tt.AssertNotPrints(ipdir): | |
530 | osmagics.cd('"%s"' % ipdir) |
|
530 | osmagics.cd('"%s"' % ipdir) | |
531 | with tt.AssertNotPrints(startdir): |
|
531 | with tt.AssertNotPrints(startdir): | |
532 | osmagics.cd('-') |
|
532 | osmagics.cd('-') | |
533 | finally: |
|
533 | finally: | |
534 | os.chdir(startdir) |
|
534 | os.chdir(startdir) | |
535 |
|
535 | |||
536 |
|
536 | |||
537 | def test_xmode(): |
|
537 | def test_xmode(): | |
538 | # Calling xmode three times should be a no-op |
|
538 | # Calling xmode three times should be a no-op | |
539 | xmode = _ip.InteractiveTB.mode |
|
539 | xmode = _ip.InteractiveTB.mode | |
540 | for i in range(4): |
|
540 | for i in range(4): | |
541 | _ip.magic("xmode") |
|
541 | _ip.magic("xmode") | |
542 | assert _ip.InteractiveTB.mode == xmode |
|
542 | assert _ip.InteractiveTB.mode == xmode | |
543 |
|
543 | |||
544 | def test_reset_hard(): |
|
544 | def test_reset_hard(): | |
545 | monitor = [] |
|
545 | monitor = [] | |
546 | class A(object): |
|
546 | class A(object): | |
547 | def __del__(self): |
|
547 | def __del__(self): | |
548 | monitor.append(1) |
|
548 | monitor.append(1) | |
549 | def __repr__(self): |
|
549 | def __repr__(self): | |
550 | return "<A instance>" |
|
550 | return "<A instance>" | |
551 |
|
551 | |||
552 | _ip.user_ns["a"] = A() |
|
552 | _ip.user_ns["a"] = A() | |
553 | _ip.run_cell("a") |
|
553 | _ip.run_cell("a") | |
554 |
|
554 | |||
555 | assert monitor == [] |
|
555 | assert monitor == [] | |
556 | _ip.magic("reset -f") |
|
556 | _ip.magic("reset -f") | |
557 | assert monitor == [1] |
|
557 | assert monitor == [1] | |
558 |
|
558 | |||
559 | class TestXdel(tt.TempFileMixin): |
|
559 | class TestXdel(tt.TempFileMixin): | |
560 | def test_xdel(self): |
|
560 | def test_xdel(self): | |
561 | """Test that references from %run are cleared by xdel.""" |
|
561 | """Test that references from %run are cleared by xdel.""" | |
562 | src = ("class A(object):\n" |
|
562 | src = ("class A(object):\n" | |
563 | " monitor = []\n" |
|
563 | " monitor = []\n" | |
564 | " def __del__(self):\n" |
|
564 | " def __del__(self):\n" | |
565 | " self.monitor.append(1)\n" |
|
565 | " self.monitor.append(1)\n" | |
566 | "a = A()\n") |
|
566 | "a = A()\n") | |
567 | self.mktmp(src) |
|
567 | self.mktmp(src) | |
568 | # %run creates some hidden references... |
|
568 | # %run creates some hidden references... | |
569 | _ip.magic("run %s" % self.fname) |
|
569 | _ip.magic("run %s" % self.fname) | |
570 | # ... as does the displayhook. |
|
570 | # ... as does the displayhook. | |
571 | _ip.run_cell("a") |
|
571 | _ip.run_cell("a") | |
572 |
|
572 | |||
573 | monitor = _ip.user_ns["A"].monitor |
|
573 | monitor = _ip.user_ns["A"].monitor | |
574 | assert monitor == [] |
|
574 | assert monitor == [] | |
575 |
|
575 | |||
576 | _ip.magic("xdel a") |
|
576 | _ip.magic("xdel a") | |
577 |
|
577 | |||
578 | # Check that a's __del__ method has been called. |
|
578 | # Check that a's __del__ method has been called. | |
579 | assert monitor == [1] |
|
579 | assert monitor == [1] | |
580 |
|
580 | |||
581 | def doctest_who(): |
|
581 | def doctest_who(): | |
582 | """doctest for %who |
|
582 | """doctest for %who | |
583 |
|
583 | |||
584 | In [1]: %reset -sf |
|
584 | In [1]: %reset -sf | |
585 |
|
585 | |||
586 | In [2]: alpha = 123 |
|
586 | In [2]: alpha = 123 | |
587 |
|
587 | |||
588 | In [3]: beta = 'beta' |
|
588 | In [3]: beta = 'beta' | |
589 |
|
589 | |||
590 | In [4]: %who int |
|
590 | In [4]: %who int | |
591 | alpha |
|
591 | alpha | |
592 |
|
592 | |||
593 | In [5]: %who str |
|
593 | In [5]: %who str | |
594 | beta |
|
594 | beta | |
595 |
|
595 | |||
596 | In [6]: %whos |
|
596 | In [6]: %whos | |
597 | Variable Type Data/Info |
|
597 | Variable Type Data/Info | |
598 | ---------------------------- |
|
598 | ---------------------------- | |
599 | alpha int 123 |
|
599 | alpha int 123 | |
600 | beta str beta |
|
600 | beta str beta | |
601 |
|
601 | |||
602 | In [7]: %who_ls |
|
602 | In [7]: %who_ls | |
603 | Out[7]: ['alpha', 'beta'] |
|
603 | Out[7]: ['alpha', 'beta'] | |
604 | """ |
|
604 | """ | |
605 |
|
605 | |||
606 | def test_whos(): |
|
606 | def test_whos(): | |
607 | """Check that whos is protected against objects where repr() fails.""" |
|
607 | """Check that whos is protected against objects where repr() fails.""" | |
608 | class A(object): |
|
608 | class A(object): | |
609 | def __repr__(self): |
|
609 | def __repr__(self): | |
610 | raise Exception() |
|
610 | raise Exception() | |
611 | _ip.user_ns['a'] = A() |
|
611 | _ip.user_ns['a'] = A() | |
612 | _ip.magic("whos") |
|
612 | _ip.magic("whos") | |
613 |
|
613 | |||
614 | def doctest_precision(): |
|
614 | def doctest_precision(): | |
615 | """doctest for %precision |
|
615 | """doctest for %precision | |
616 |
|
616 | |||
617 | In [1]: f = get_ipython().display_formatter.formatters['text/plain'] |
|
617 | In [1]: f = get_ipython().display_formatter.formatters['text/plain'] | |
618 |
|
618 | |||
619 | In [2]: %precision 5 |
|
619 | In [2]: %precision 5 | |
620 | Out[2]: '%.5f' |
|
620 | Out[2]: '%.5f' | |
621 |
|
621 | |||
622 | In [3]: f.float_format |
|
622 | In [3]: f.float_format | |
623 | Out[3]: '%.5f' |
|
623 | Out[3]: '%.5f' | |
624 |
|
624 | |||
625 | In [4]: %precision %e |
|
625 | In [4]: %precision %e | |
626 | Out[4]: '%e' |
|
626 | Out[4]: '%e' | |
627 |
|
627 | |||
628 | In [5]: f(3.1415927) |
|
628 | In [5]: f(3.1415927) | |
629 | Out[5]: '3.141593e+00' |
|
629 | Out[5]: '3.141593e+00' | |
630 | """ |
|
630 | """ | |
631 |
|
631 | |||
632 | def test_debug_magic(): |
|
632 | def test_debug_magic(): | |
633 | """Test debugging a small code with %debug |
|
633 | """Test debugging a small code with %debug | |
634 |
|
634 | |||
635 | In [1]: with PdbTestInput(['c']): |
|
635 | In [1]: with PdbTestInput(['c']): | |
636 | ...: %debug print("a b") #doctest: +ELLIPSIS |
|
636 | ...: %debug print("a b") #doctest: +ELLIPSIS | |
637 | ...: |
|
637 | ...: | |
638 | ... |
|
638 | ... | |
639 | ipdb> c |
|
639 | ipdb> c | |
640 | a b |
|
640 | a b | |
641 | In [2]: |
|
641 | In [2]: | |
642 | """ |
|
642 | """ | |
643 |
|
643 | |||
644 | def test_psearch(): |
|
644 | def test_psearch(): | |
645 | with tt.AssertPrints("dict.fromkeys"): |
|
645 | with tt.AssertPrints("dict.fromkeys"): | |
646 | _ip.run_cell("dict.fr*?") |
|
646 | _ip.run_cell("dict.fr*?") | |
647 | with tt.AssertPrints("π.is_integer"): |
|
647 | with tt.AssertPrints("π.is_integer"): | |
648 | _ip.run_cell("π = 3.14;\nπ.is_integ*?") |
|
648 | _ip.run_cell("π = 3.14;\nπ.is_integ*?") | |
649 |
|
649 | |||
650 | def test_timeit_shlex(): |
|
650 | def test_timeit_shlex(): | |
651 | """test shlex issues with timeit (#1109)""" |
|
651 | """test shlex issues with timeit (#1109)""" | |
652 | _ip.ex("def f(*a,**kw): pass") |
|
652 | _ip.ex("def f(*a,**kw): pass") | |
653 | _ip.magic('timeit -n1 "this is a bug".count(" ")') |
|
653 | _ip.magic('timeit -n1 "this is a bug".count(" ")') | |
654 | _ip.magic('timeit -r1 -n1 f(" ", 1)') |
|
654 | _ip.magic('timeit -r1 -n1 f(" ", 1)') | |
655 | _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")') |
|
655 | _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")') | |
656 | _ip.magic('timeit -r1 -n1 ("a " + "b")') |
|
656 | _ip.magic('timeit -r1 -n1 ("a " + "b")') | |
657 | _ip.magic('timeit -r1 -n1 f("a " + "b")') |
|
657 | _ip.magic('timeit -r1 -n1 f("a " + "b")') | |
658 | _ip.magic('timeit -r1 -n1 f("a " + "b ")') |
|
658 | _ip.magic('timeit -r1 -n1 f("a " + "b ")') | |
659 |
|
659 | |||
660 |
|
660 | |||
661 | def test_timeit_special_syntax(): |
|
661 | def test_timeit_special_syntax(): | |
662 | "Test %%timeit with IPython special syntax" |
|
662 | "Test %%timeit with IPython special syntax" | |
663 | @register_line_magic |
|
663 | @register_line_magic | |
664 | def lmagic(line): |
|
664 | def lmagic(line): | |
665 | ip = get_ipython() |
|
665 | ip = get_ipython() | |
666 | ip.user_ns['lmagic_out'] = line |
|
666 | ip.user_ns['lmagic_out'] = line | |
667 |
|
667 | |||
668 | # line mode test |
|
668 | # line mode test | |
669 | _ip.run_line_magic("timeit", "-n1 -r1 %lmagic my line") |
|
669 | _ip.run_line_magic("timeit", "-n1 -r1 %lmagic my line") | |
670 | assert _ip.user_ns["lmagic_out"] == "my line" |
|
670 | assert _ip.user_ns["lmagic_out"] == "my line" | |
671 | # cell mode test |
|
671 | # cell mode test | |
672 | _ip.run_cell_magic("timeit", "-n1 -r1", "%lmagic my line2") |
|
672 | _ip.run_cell_magic("timeit", "-n1 -r1", "%lmagic my line2") | |
673 | assert _ip.user_ns["lmagic_out"] == "my line2" |
|
673 | assert _ip.user_ns["lmagic_out"] == "my line2" | |
674 |
|
674 | |||
675 |
|
675 | |||
676 | def test_timeit_return(): |
|
676 | def test_timeit_return(): | |
677 | """ |
|
677 | """ | |
678 | test whether timeit -o return object |
|
678 | test whether timeit -o return object | |
679 | """ |
|
679 | """ | |
680 |
|
680 | |||
681 | res = _ip.run_line_magic('timeit','-n10 -r10 -o 1') |
|
681 | res = _ip.run_line_magic('timeit','-n10 -r10 -o 1') | |
682 | assert(res is not None) |
|
682 | assert(res is not None) | |
683 |
|
683 | |||
684 | def test_timeit_quiet(): |
|
684 | def test_timeit_quiet(): | |
685 | """ |
|
685 | """ | |
686 | test quiet option of timeit magic |
|
686 | test quiet option of timeit magic | |
687 | """ |
|
687 | """ | |
688 | with tt.AssertNotPrints("loops"): |
|
688 | with tt.AssertNotPrints("loops"): | |
689 | _ip.run_cell("%timeit -n1 -r1 -q 1") |
|
689 | _ip.run_cell("%timeit -n1 -r1 -q 1") | |
690 |
|
690 | |||
691 | def test_timeit_return_quiet(): |
|
691 | def test_timeit_return_quiet(): | |
692 | with tt.AssertNotPrints("loops"): |
|
692 | with tt.AssertNotPrints("loops"): | |
693 | res = _ip.run_line_magic('timeit', '-n1 -r1 -q -o 1') |
|
693 | res = _ip.run_line_magic('timeit', '-n1 -r1 -q -o 1') | |
694 | assert (res is not None) |
|
694 | assert (res is not None) | |
695 |
|
695 | |||
696 | def test_timeit_invalid_return(): |
|
696 | def test_timeit_invalid_return(): | |
697 | with pytest.raises(SyntaxError): |
|
697 | with pytest.raises(SyntaxError): | |
698 | _ip.run_line_magic('timeit', 'return') |
|
698 | _ip.run_line_magic('timeit', 'return') | |
699 |
|
699 | |||
700 | @dec.skipif(execution.profile is None) |
|
700 | @dec.skipif(execution.profile is None) | |
701 | def test_prun_special_syntax(): |
|
701 | def test_prun_special_syntax(): | |
702 | "Test %%prun with IPython special syntax" |
|
702 | "Test %%prun with IPython special syntax" | |
703 | @register_line_magic |
|
703 | @register_line_magic | |
704 | def lmagic(line): |
|
704 | def lmagic(line): | |
705 | ip = get_ipython() |
|
705 | ip = get_ipython() | |
706 | ip.user_ns['lmagic_out'] = line |
|
706 | ip.user_ns['lmagic_out'] = line | |
707 |
|
707 | |||
708 | # line mode test |
|
708 | # line mode test | |
709 | _ip.run_line_magic("prun", "-q %lmagic my line") |
|
709 | _ip.run_line_magic("prun", "-q %lmagic my line") | |
710 | assert _ip.user_ns["lmagic_out"] == "my line" |
|
710 | assert _ip.user_ns["lmagic_out"] == "my line" | |
711 | # cell mode test |
|
711 | # cell mode test | |
712 | _ip.run_cell_magic("prun", "-q", "%lmagic my line2") |
|
712 | _ip.run_cell_magic("prun", "-q", "%lmagic my line2") | |
713 | assert _ip.user_ns["lmagic_out"] == "my line2" |
|
713 | assert _ip.user_ns["lmagic_out"] == "my line2" | |
714 |
|
714 | |||
715 |
|
715 | |||
716 | @dec.skipif(execution.profile is None) |
|
716 | @dec.skipif(execution.profile is None) | |
717 | def test_prun_quotes(): |
|
717 | def test_prun_quotes(): | |
718 | "Test that prun does not clobber string escapes (GH #1302)" |
|
718 | "Test that prun does not clobber string escapes (GH #1302)" | |
719 | _ip.magic(r"prun -q x = '\t'") |
|
719 | _ip.magic(r"prun -q x = '\t'") | |
720 | assert _ip.user_ns["x"] == "\t" |
|
720 | assert _ip.user_ns["x"] == "\t" | |
721 |
|
721 | |||
722 |
|
722 | |||
723 | def test_extension(): |
|
723 | def test_extension(): | |
724 | # Debugging information for failures of this test |
|
724 | # Debugging information for failures of this test | |
725 | print('sys.path:') |
|
725 | print('sys.path:') | |
726 | for p in sys.path: |
|
726 | for p in sys.path: | |
727 | print(' ', p) |
|
727 | print(' ', p) | |
728 | print('CWD', os.getcwd()) |
|
728 | print('CWD', os.getcwd()) | |
729 |
|
729 | |||
730 | pytest.raises(ImportError, _ip.magic, "load_ext daft_extension") |
|
730 | pytest.raises(ImportError, _ip.magic, "load_ext daft_extension") | |
731 | daft_path = os.path.join(os.path.dirname(__file__), "daft_extension") |
|
731 | daft_path = os.path.join(os.path.dirname(__file__), "daft_extension") | |
732 | sys.path.insert(0, daft_path) |
|
732 | sys.path.insert(0, daft_path) | |
733 | try: |
|
733 | try: | |
734 | _ip.user_ns.pop('arq', None) |
|
734 | _ip.user_ns.pop('arq', None) | |
735 | invalidate_caches() # Clear import caches |
|
735 | invalidate_caches() # Clear import caches | |
736 | _ip.magic("load_ext daft_extension") |
|
736 | _ip.magic("load_ext daft_extension") | |
737 | assert _ip.user_ns["arq"] == 185 |
|
737 | assert _ip.user_ns["arq"] == 185 | |
738 | _ip.magic("unload_ext daft_extension") |
|
738 | _ip.magic("unload_ext daft_extension") | |
739 | assert 'arq' not in _ip.user_ns |
|
739 | assert 'arq' not in _ip.user_ns | |
740 | finally: |
|
740 | finally: | |
741 | sys.path.remove(daft_path) |
|
741 | sys.path.remove(daft_path) | |
742 |
|
742 | |||
743 |
|
743 | |||
744 | def test_notebook_export_json(): |
|
744 | def test_notebook_export_json(): | |
|
745 | pytest.importorskip("nbformat") | |||
745 | _ip = get_ipython() |
|
746 | _ip = get_ipython() | |
746 | _ip.history_manager.reset() # Clear any existing history. |
|
747 | _ip.history_manager.reset() # Clear any existing history. | |
747 | cmds = ["a=1", "def b():\n return a**2", "print('noël, été', b())"] |
|
748 | cmds = ["a=1", "def b():\n return a**2", "print('noël, été', b())"] | |
748 | for i, cmd in enumerate(cmds, start=1): |
|
749 | for i, cmd in enumerate(cmds, start=1): | |
749 | _ip.history_manager.store_inputs(i, cmd) |
|
750 | _ip.history_manager.store_inputs(i, cmd) | |
750 | with TemporaryDirectory() as td: |
|
751 | with TemporaryDirectory() as td: | |
751 | outfile = os.path.join(td, "nb.ipynb") |
|
752 | outfile = os.path.join(td, "nb.ipynb") | |
752 | _ip.magic("notebook -e %s" % outfile) |
|
753 | _ip.magic("notebook -e %s" % outfile) | |
753 |
|
754 | |||
754 |
|
755 | |||
755 | class TestEnv(TestCase): |
|
756 | class TestEnv(TestCase): | |
756 |
|
757 | |||
757 | def test_env(self): |
|
758 | def test_env(self): | |
758 | env = _ip.magic("env") |
|
759 | env = _ip.magic("env") | |
759 | self.assertTrue(isinstance(env, dict)) |
|
760 | self.assertTrue(isinstance(env, dict)) | |
760 |
|
761 | |||
761 | def test_env_secret(self): |
|
762 | def test_env_secret(self): | |
762 | env = _ip.magic("env") |
|
763 | env = _ip.magic("env") | |
763 | hidden = "<hidden>" |
|
764 | hidden = "<hidden>" | |
764 | with mock.patch.dict( |
|
765 | with mock.patch.dict( | |
765 | os.environ, |
|
766 | os.environ, | |
766 | { |
|
767 | { | |
767 | "API_KEY": "abc123", |
|
768 | "API_KEY": "abc123", | |
768 | "SECRET_THING": "ssshhh", |
|
769 | "SECRET_THING": "ssshhh", | |
769 | "JUPYTER_TOKEN": "", |
|
770 | "JUPYTER_TOKEN": "", | |
770 | "VAR": "abc" |
|
771 | "VAR": "abc" | |
771 | } |
|
772 | } | |
772 | ): |
|
773 | ): | |
773 | env = _ip.magic("env") |
|
774 | env = _ip.magic("env") | |
774 | assert env["API_KEY"] == hidden |
|
775 | assert env["API_KEY"] == hidden | |
775 | assert env["SECRET_THING"] == hidden |
|
776 | assert env["SECRET_THING"] == hidden | |
776 | assert env["JUPYTER_TOKEN"] == hidden |
|
777 | assert env["JUPYTER_TOKEN"] == hidden | |
777 | assert env["VAR"] == "abc" |
|
778 | assert env["VAR"] == "abc" | |
778 |
|
779 | |||
779 | def test_env_get_set_simple(self): |
|
780 | def test_env_get_set_simple(self): | |
780 | env = _ip.magic("env var val1") |
|
781 | env = _ip.magic("env var val1") | |
781 | self.assertEqual(env, None) |
|
782 | self.assertEqual(env, None) | |
782 | self.assertEqual(os.environ['var'], 'val1') |
|
783 | self.assertEqual(os.environ['var'], 'val1') | |
783 | self.assertEqual(_ip.magic("env var"), 'val1') |
|
784 | self.assertEqual(_ip.magic("env var"), 'val1') | |
784 | env = _ip.magic("env var=val2") |
|
785 | env = _ip.magic("env var=val2") | |
785 | self.assertEqual(env, None) |
|
786 | self.assertEqual(env, None) | |
786 | self.assertEqual(os.environ['var'], 'val2') |
|
787 | self.assertEqual(os.environ['var'], 'val2') | |
787 |
|
788 | |||
788 | def test_env_get_set_complex(self): |
|
789 | def test_env_get_set_complex(self): | |
789 | env = _ip.magic("env var 'val1 '' 'val2") |
|
790 | env = _ip.magic("env var 'val1 '' 'val2") | |
790 | self.assertEqual(env, None) |
|
791 | self.assertEqual(env, None) | |
791 | self.assertEqual(os.environ['var'], "'val1 '' 'val2") |
|
792 | self.assertEqual(os.environ['var'], "'val1 '' 'val2") | |
792 | self.assertEqual(_ip.magic("env var"), "'val1 '' 'val2") |
|
793 | self.assertEqual(_ip.magic("env var"), "'val1 '' 'val2") | |
793 | env = _ip.magic('env var=val2 val3="val4') |
|
794 | env = _ip.magic('env var=val2 val3="val4') | |
794 | self.assertEqual(env, None) |
|
795 | self.assertEqual(env, None) | |
795 | self.assertEqual(os.environ['var'], 'val2 val3="val4') |
|
796 | self.assertEqual(os.environ['var'], 'val2 val3="val4') | |
796 |
|
797 | |||
797 | def test_env_set_bad_input(self): |
|
798 | def test_env_set_bad_input(self): | |
798 | self.assertRaises(UsageError, lambda: _ip.magic("set_env var")) |
|
799 | self.assertRaises(UsageError, lambda: _ip.magic("set_env var")) | |
799 |
|
800 | |||
800 | def test_env_set_whitespace(self): |
|
801 | def test_env_set_whitespace(self): | |
801 | self.assertRaises(UsageError, lambda: _ip.magic("env var A=B")) |
|
802 | self.assertRaises(UsageError, lambda: _ip.magic("env var A=B")) | |
802 |
|
803 | |||
803 |
|
804 | |||
804 | class CellMagicTestCase(TestCase): |
|
805 | class CellMagicTestCase(TestCase): | |
805 |
|
806 | |||
806 | def check_ident(self, magic): |
|
807 | def check_ident(self, magic): | |
807 | # Manually called, we get the result |
|
808 | # Manually called, we get the result | |
808 | out = _ip.run_cell_magic(magic, "a", "b") |
|
809 | out = _ip.run_cell_magic(magic, "a", "b") | |
809 | assert out == ("a", "b") |
|
810 | assert out == ("a", "b") | |
810 | # Via run_cell, it goes into the user's namespace via displayhook |
|
811 | # Via run_cell, it goes into the user's namespace via displayhook | |
811 | _ip.run_cell("%%" + magic + " c\nd\n") |
|
812 | _ip.run_cell("%%" + magic + " c\nd\n") | |
812 | assert _ip.user_ns["_"] == ("c", "d\n") |
|
813 | assert _ip.user_ns["_"] == ("c", "d\n") | |
813 |
|
814 | |||
814 | def test_cell_magic_func_deco(self): |
|
815 | def test_cell_magic_func_deco(self): | |
815 | "Cell magic using simple decorator" |
|
816 | "Cell magic using simple decorator" | |
816 | @register_cell_magic |
|
817 | @register_cell_magic | |
817 | def cellm(line, cell): |
|
818 | def cellm(line, cell): | |
818 | return line, cell |
|
819 | return line, cell | |
819 |
|
820 | |||
820 | self.check_ident('cellm') |
|
821 | self.check_ident('cellm') | |
821 |
|
822 | |||
822 | def test_cell_magic_reg(self): |
|
823 | def test_cell_magic_reg(self): | |
823 | "Cell magic manually registered" |
|
824 | "Cell magic manually registered" | |
824 | def cellm(line, cell): |
|
825 | def cellm(line, cell): | |
825 | return line, cell |
|
826 | return line, cell | |
826 |
|
827 | |||
827 | _ip.register_magic_function(cellm, 'cell', 'cellm2') |
|
828 | _ip.register_magic_function(cellm, 'cell', 'cellm2') | |
828 | self.check_ident('cellm2') |
|
829 | self.check_ident('cellm2') | |
829 |
|
830 | |||
830 | def test_cell_magic_class(self): |
|
831 | def test_cell_magic_class(self): | |
831 | "Cell magics declared via a class" |
|
832 | "Cell magics declared via a class" | |
832 | @magics_class |
|
833 | @magics_class | |
833 | class MyMagics(Magics): |
|
834 | class MyMagics(Magics): | |
834 |
|
835 | |||
835 | @cell_magic |
|
836 | @cell_magic | |
836 | def cellm3(self, line, cell): |
|
837 | def cellm3(self, line, cell): | |
837 | return line, cell |
|
838 | return line, cell | |
838 |
|
839 | |||
839 | _ip.register_magics(MyMagics) |
|
840 | _ip.register_magics(MyMagics) | |
840 | self.check_ident('cellm3') |
|
841 | self.check_ident('cellm3') | |
841 |
|
842 | |||
842 | def test_cell_magic_class2(self): |
|
843 | def test_cell_magic_class2(self): | |
843 | "Cell magics declared via a class, #2" |
|
844 | "Cell magics declared via a class, #2" | |
844 | @magics_class |
|
845 | @magics_class | |
845 | class MyMagics2(Magics): |
|
846 | class MyMagics2(Magics): | |
846 |
|
847 | |||
847 | @cell_magic('cellm4') |
|
848 | @cell_magic('cellm4') | |
848 | def cellm33(self, line, cell): |
|
849 | def cellm33(self, line, cell): | |
849 | return line, cell |
|
850 | return line, cell | |
850 |
|
851 | |||
851 | _ip.register_magics(MyMagics2) |
|
852 | _ip.register_magics(MyMagics2) | |
852 | self.check_ident('cellm4') |
|
853 | self.check_ident('cellm4') | |
853 | # Check that nothing is registered as 'cellm33' |
|
854 | # Check that nothing is registered as 'cellm33' | |
854 | c33 = _ip.find_cell_magic('cellm33') |
|
855 | c33 = _ip.find_cell_magic('cellm33') | |
855 | assert c33 == None |
|
856 | assert c33 == None | |
856 |
|
857 | |||
857 | def test_file(): |
|
858 | def test_file(): | |
858 | """Basic %%writefile""" |
|
859 | """Basic %%writefile""" | |
859 | ip = get_ipython() |
|
860 | ip = get_ipython() | |
860 | with TemporaryDirectory() as td: |
|
861 | with TemporaryDirectory() as td: | |
861 | fname = os.path.join(td, 'file1') |
|
862 | fname = os.path.join(td, 'file1') | |
862 | ip.run_cell_magic("writefile", fname, u'\n'.join([ |
|
863 | ip.run_cell_magic("writefile", fname, u'\n'.join([ | |
863 | 'line1', |
|
864 | 'line1', | |
864 | 'line2', |
|
865 | 'line2', | |
865 | ])) |
|
866 | ])) | |
866 | s = Path(fname).read_text() |
|
867 | s = Path(fname).read_text() | |
867 | assert "line1\n" in s |
|
868 | assert "line1\n" in s | |
868 | assert "line2" in s |
|
869 | assert "line2" in s | |
869 |
|
870 | |||
870 |
|
871 | |||
871 | @dec.skip_win32 |
|
872 | @dec.skip_win32 | |
872 | def test_file_single_quote(): |
|
873 | def test_file_single_quote(): | |
873 | """Basic %%writefile with embedded single quotes""" |
|
874 | """Basic %%writefile with embedded single quotes""" | |
874 | ip = get_ipython() |
|
875 | ip = get_ipython() | |
875 | with TemporaryDirectory() as td: |
|
876 | with TemporaryDirectory() as td: | |
876 | fname = os.path.join(td, '\'file1\'') |
|
877 | fname = os.path.join(td, '\'file1\'') | |
877 | ip.run_cell_magic("writefile", fname, u'\n'.join([ |
|
878 | ip.run_cell_magic("writefile", fname, u'\n'.join([ | |
878 | 'line1', |
|
879 | 'line1', | |
879 | 'line2', |
|
880 | 'line2', | |
880 | ])) |
|
881 | ])) | |
881 | s = Path(fname).read_text() |
|
882 | s = Path(fname).read_text() | |
882 | assert "line1\n" in s |
|
883 | assert "line1\n" in s | |
883 | assert "line2" in s |
|
884 | assert "line2" in s | |
884 |
|
885 | |||
885 |
|
886 | |||
886 | @dec.skip_win32 |
|
887 | @dec.skip_win32 | |
887 | def test_file_double_quote(): |
|
888 | def test_file_double_quote(): | |
888 | """Basic %%writefile with embedded double quotes""" |
|
889 | """Basic %%writefile with embedded double quotes""" | |
889 | ip = get_ipython() |
|
890 | ip = get_ipython() | |
890 | with TemporaryDirectory() as td: |
|
891 | with TemporaryDirectory() as td: | |
891 | fname = os.path.join(td, '"file1"') |
|
892 | fname = os.path.join(td, '"file1"') | |
892 | ip.run_cell_magic("writefile", fname, u'\n'.join([ |
|
893 | ip.run_cell_magic("writefile", fname, u'\n'.join([ | |
893 | 'line1', |
|
894 | 'line1', | |
894 | 'line2', |
|
895 | 'line2', | |
895 | ])) |
|
896 | ])) | |
896 | s = Path(fname).read_text() |
|
897 | s = Path(fname).read_text() | |
897 | assert "line1\n" in s |
|
898 | assert "line1\n" in s | |
898 | assert "line2" in s |
|
899 | assert "line2" in s | |
899 |
|
900 | |||
900 |
|
901 | |||
901 | def test_file_var_expand(): |
|
902 | def test_file_var_expand(): | |
902 | """%%writefile $filename""" |
|
903 | """%%writefile $filename""" | |
903 | ip = get_ipython() |
|
904 | ip = get_ipython() | |
904 | with TemporaryDirectory() as td: |
|
905 | with TemporaryDirectory() as td: | |
905 | fname = os.path.join(td, 'file1') |
|
906 | fname = os.path.join(td, 'file1') | |
906 | ip.user_ns['filename'] = fname |
|
907 | ip.user_ns['filename'] = fname | |
907 | ip.run_cell_magic("writefile", '$filename', u'\n'.join([ |
|
908 | ip.run_cell_magic("writefile", '$filename', u'\n'.join([ | |
908 | 'line1', |
|
909 | 'line1', | |
909 | 'line2', |
|
910 | 'line2', | |
910 | ])) |
|
911 | ])) | |
911 | s = Path(fname).read_text() |
|
912 | s = Path(fname).read_text() | |
912 | assert "line1\n" in s |
|
913 | assert "line1\n" in s | |
913 | assert "line2" in s |
|
914 | assert "line2" in s | |
914 |
|
915 | |||
915 |
|
916 | |||
916 | def test_file_unicode(): |
|
917 | def test_file_unicode(): | |
917 | """%%writefile with unicode cell""" |
|
918 | """%%writefile with unicode cell""" | |
918 | ip = get_ipython() |
|
919 | ip = get_ipython() | |
919 | with TemporaryDirectory() as td: |
|
920 | with TemporaryDirectory() as td: | |
920 | fname = os.path.join(td, 'file1') |
|
921 | fname = os.path.join(td, 'file1') | |
921 | ip.run_cell_magic("writefile", fname, u'\n'.join([ |
|
922 | ip.run_cell_magic("writefile", fname, u'\n'.join([ | |
922 | u'liné1', |
|
923 | u'liné1', | |
923 | u'liné2', |
|
924 | u'liné2', | |
924 | ])) |
|
925 | ])) | |
925 | with io.open(fname, encoding='utf-8') as f: |
|
926 | with io.open(fname, encoding='utf-8') as f: | |
926 | s = f.read() |
|
927 | s = f.read() | |
927 | assert "liné1\n" in s |
|
928 | assert "liné1\n" in s | |
928 | assert "liné2" in s |
|
929 | assert "liné2" in s | |
929 |
|
930 | |||
930 |
|
931 | |||
931 | def test_file_amend(): |
|
932 | def test_file_amend(): | |
932 | """%%writefile -a amends files""" |
|
933 | """%%writefile -a amends files""" | |
933 | ip = get_ipython() |
|
934 | ip = get_ipython() | |
934 | with TemporaryDirectory() as td: |
|
935 | with TemporaryDirectory() as td: | |
935 | fname = os.path.join(td, 'file2') |
|
936 | fname = os.path.join(td, 'file2') | |
936 | ip.run_cell_magic("writefile", fname, u'\n'.join([ |
|
937 | ip.run_cell_magic("writefile", fname, u'\n'.join([ | |
937 | 'line1', |
|
938 | 'line1', | |
938 | 'line2', |
|
939 | 'line2', | |
939 | ])) |
|
940 | ])) | |
940 | ip.run_cell_magic("writefile", "-a %s" % fname, u'\n'.join([ |
|
941 | ip.run_cell_magic("writefile", "-a %s" % fname, u'\n'.join([ | |
941 | 'line3', |
|
942 | 'line3', | |
942 | 'line4', |
|
943 | 'line4', | |
943 | ])) |
|
944 | ])) | |
944 | s = Path(fname).read_text() |
|
945 | s = Path(fname).read_text() | |
945 | assert "line1\n" in s |
|
946 | assert "line1\n" in s | |
946 | assert "line3\n" in s |
|
947 | assert "line3\n" in s | |
947 |
|
948 | |||
948 |
|
949 | |||
949 | def test_file_spaces(): |
|
950 | def test_file_spaces(): | |
950 | """%%file with spaces in filename""" |
|
951 | """%%file with spaces in filename""" | |
951 | ip = get_ipython() |
|
952 | ip = get_ipython() | |
952 | with TemporaryWorkingDirectory() as td: |
|
953 | with TemporaryWorkingDirectory() as td: | |
953 | fname = "file name" |
|
954 | fname = "file name" | |
954 | ip.run_cell_magic("file", '"%s"'%fname, u'\n'.join([ |
|
955 | ip.run_cell_magic("file", '"%s"'%fname, u'\n'.join([ | |
955 | 'line1', |
|
956 | 'line1', | |
956 | 'line2', |
|
957 | 'line2', | |
957 | ])) |
|
958 | ])) | |
958 | s = Path(fname).read_text() |
|
959 | s = Path(fname).read_text() | |
959 | assert "line1\n" in s |
|
960 | assert "line1\n" in s | |
960 | assert "line2" in s |
|
961 | assert "line2" in s | |
961 |
|
962 | |||
962 |
|
963 | |||
963 | def test_script_config(): |
|
964 | def test_script_config(): | |
964 | ip = get_ipython() |
|
965 | ip = get_ipython() | |
965 | ip.config.ScriptMagics.script_magics = ['whoda'] |
|
966 | ip.config.ScriptMagics.script_magics = ['whoda'] | |
966 | sm = script.ScriptMagics(shell=ip) |
|
967 | sm = script.ScriptMagics(shell=ip) | |
967 | assert "whoda" in sm.magics["cell"] |
|
968 | assert "whoda" in sm.magics["cell"] | |
968 |
|
969 | |||
969 |
|
970 | |||
970 | @pytest.fixture |
|
971 | @pytest.fixture | |
971 | def event_loop(): |
|
972 | def event_loop(): | |
972 | yield asyncio.get_event_loop_policy().get_event_loop() |
|
973 | yield asyncio.get_event_loop_policy().get_event_loop() | |
973 |
|
974 | |||
974 |
|
975 | |||
975 | @dec.skip_win32 |
|
976 | @dec.skip_win32 | |
976 | @pytest.mark.skipif( |
|
977 | @pytest.mark.skipif( | |
977 | sys.platform == "win32", reason="This test does not run under Windows" |
|
978 | sys.platform == "win32", reason="This test does not run under Windows" | |
978 | ) |
|
979 | ) | |
979 | def test_script_out(event_loop): |
|
980 | def test_script_out(event_loop): | |
980 | assert event_loop.is_running() is False |
|
981 | assert event_loop.is_running() is False | |
981 |
|
982 | |||
982 | ip = get_ipython() |
|
983 | ip = get_ipython() | |
983 | ip.run_cell_magic("script", "--out output sh", "echo 'hi'") |
|
984 | ip.run_cell_magic("script", "--out output sh", "echo 'hi'") | |
984 | assert event_loop.is_running() is False |
|
985 | assert event_loop.is_running() is False | |
985 | assert ip.user_ns["output"] == "hi\n" |
|
986 | assert ip.user_ns["output"] == "hi\n" | |
986 |
|
987 | |||
987 |
|
988 | |||
988 | @dec.skip_win32 |
|
989 | @dec.skip_win32 | |
989 | @pytest.mark.skipif( |
|
990 | @pytest.mark.skipif( | |
990 | sys.platform == "win32", reason="This test does not run under Windows" |
|
991 | sys.platform == "win32", reason="This test does not run under Windows" | |
991 | ) |
|
992 | ) | |
992 | def test_script_err(event_loop): |
|
993 | def test_script_err(event_loop): | |
993 | ip = get_ipython() |
|
994 | ip = get_ipython() | |
994 | assert event_loop.is_running() is False |
|
995 | assert event_loop.is_running() is False | |
995 | ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2") |
|
996 | ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2") | |
996 | assert event_loop.is_running() is False |
|
997 | assert event_loop.is_running() is False | |
997 | assert ip.user_ns["error"] == "hello\n" |
|
998 | assert ip.user_ns["error"] == "hello\n" | |
998 |
|
999 | |||
999 |
|
1000 | |||
1000 | @dec.skip_win32 |
|
1001 | @dec.skip_win32 | |
1001 | @pytest.mark.skipif( |
|
1002 | @pytest.mark.skipif( | |
1002 | sys.platform == "win32", reason="This test does not run under Windows" |
|
1003 | sys.platform == "win32", reason="This test does not run under Windows" | |
1003 | ) |
|
1004 | ) | |
1004 | def test_script_out_err(): |
|
1005 | def test_script_out_err(): | |
1005 |
|
1006 | |||
1006 | ip = get_ipython() |
|
1007 | ip = get_ipython() | |
1007 | ip.run_cell_magic( |
|
1008 | ip.run_cell_magic( | |
1008 | "script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2" |
|
1009 | "script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2" | |
1009 | ) |
|
1010 | ) | |
1010 | assert ip.user_ns["output"] == "hi\n" |
|
1011 | assert ip.user_ns["output"] == "hi\n" | |
1011 | assert ip.user_ns["error"] == "hello\n" |
|
1012 | assert ip.user_ns["error"] == "hello\n" | |
1012 |
|
1013 | |||
1013 |
|
1014 | |||
1014 | @dec.skip_win32 |
|
1015 | @dec.skip_win32 | |
1015 | @pytest.mark.skipif( |
|
1016 | @pytest.mark.skipif( | |
1016 | sys.platform == "win32", reason="This test does not run under Windows" |
|
1017 | sys.platform == "win32", reason="This test does not run under Windows" | |
1017 | ) |
|
1018 | ) | |
1018 | async def test_script_bg_out(event_loop): |
|
1019 | async def test_script_bg_out(event_loop): | |
1019 | ip = get_ipython() |
|
1020 | ip = get_ipython() | |
1020 | ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'") |
|
1021 | ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'") | |
1021 | assert (await ip.user_ns["output"].read()) == b"hi\n" |
|
1022 | assert (await ip.user_ns["output"].read()) == b"hi\n" | |
1022 | ip.user_ns["output"].close() |
|
1023 | ip.user_ns["output"].close() | |
1023 | event_loop.stop() |
|
1024 | event_loop.stop() | |
1024 |
|
1025 | |||
1025 |
|
1026 | |||
1026 | @dec.skip_win32 |
|
1027 | @dec.skip_win32 | |
1027 | @pytest.mark.skipif( |
|
1028 | @pytest.mark.skipif( | |
1028 | sys.platform == "win32", reason="This test does not run under Windows" |
|
1029 | sys.platform == "win32", reason="This test does not run under Windows" | |
1029 | ) |
|
1030 | ) | |
1030 | async def test_script_bg_err(): |
|
1031 | async def test_script_bg_err(): | |
1031 | ip = get_ipython() |
|
1032 | ip = get_ipython() | |
1032 | ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2") |
|
1033 | ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2") | |
1033 | assert (await ip.user_ns["error"].read()) == b"hello\n" |
|
1034 | assert (await ip.user_ns["error"].read()) == b"hello\n" | |
1034 | ip.user_ns["error"].close() |
|
1035 | ip.user_ns["error"].close() | |
1035 |
|
1036 | |||
1036 |
|
1037 | |||
1037 | @dec.skip_win32 |
|
1038 | @dec.skip_win32 | |
1038 | @pytest.mark.skipif( |
|
1039 | @pytest.mark.skipif( | |
1039 | sys.platform == "win32", reason="This test does not run under Windows" |
|
1040 | sys.platform == "win32", reason="This test does not run under Windows" | |
1040 | ) |
|
1041 | ) | |
1041 | async def test_script_bg_out_err(): |
|
1042 | async def test_script_bg_out_err(): | |
1042 | ip = get_ipython() |
|
1043 | ip = get_ipython() | |
1043 | ip.run_cell_magic( |
|
1044 | ip.run_cell_magic( | |
1044 | "script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2" |
|
1045 | "script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2" | |
1045 | ) |
|
1046 | ) | |
1046 | assert (await ip.user_ns["output"].read()) == b"hi\n" |
|
1047 | assert (await ip.user_ns["output"].read()) == b"hi\n" | |
1047 | assert (await ip.user_ns["error"].read()) == b"hello\n" |
|
1048 | assert (await ip.user_ns["error"].read()) == b"hello\n" | |
1048 | ip.user_ns["output"].close() |
|
1049 | ip.user_ns["output"].close() | |
1049 | ip.user_ns["error"].close() |
|
1050 | ip.user_ns["error"].close() | |
1050 |
|
1051 | |||
1051 |
|
1052 | |||
1052 | def test_script_defaults(): |
|
1053 | def test_script_defaults(): | |
1053 | ip = get_ipython() |
|
1054 | ip = get_ipython() | |
1054 | for cmd in ['sh', 'bash', 'perl', 'ruby']: |
|
1055 | for cmd in ['sh', 'bash', 'perl', 'ruby']: | |
1055 | try: |
|
1056 | try: | |
1056 | find_cmd(cmd) |
|
1057 | find_cmd(cmd) | |
1057 | except Exception: |
|
1058 | except Exception: | |
1058 | pass |
|
1059 | pass | |
1059 | else: |
|
1060 | else: | |
1060 | assert cmd in ip.magics_manager.magics["cell"] |
|
1061 | assert cmd in ip.magics_manager.magics["cell"] | |
1061 |
|
1062 | |||
1062 |
|
1063 | |||
1063 | @magics_class |
|
1064 | @magics_class | |
1064 | class FooFoo(Magics): |
|
1065 | class FooFoo(Magics): | |
1065 | """class with both %foo and %%foo magics""" |
|
1066 | """class with both %foo and %%foo magics""" | |
1066 | @line_magic('foo') |
|
1067 | @line_magic('foo') | |
1067 | def line_foo(self, line): |
|
1068 | def line_foo(self, line): | |
1068 | "I am line foo" |
|
1069 | "I am line foo" | |
1069 | pass |
|
1070 | pass | |
1070 |
|
1071 | |||
1071 | @cell_magic("foo") |
|
1072 | @cell_magic("foo") | |
1072 | def cell_foo(self, line, cell): |
|
1073 | def cell_foo(self, line, cell): | |
1073 | "I am cell foo, not line foo" |
|
1074 | "I am cell foo, not line foo" | |
1074 | pass |
|
1075 | pass | |
1075 |
|
1076 | |||
1076 | def test_line_cell_info(): |
|
1077 | def test_line_cell_info(): | |
1077 | """%%foo and %foo magics are distinguishable to inspect""" |
|
1078 | """%%foo and %foo magics are distinguishable to inspect""" | |
1078 | ip = get_ipython() |
|
1079 | ip = get_ipython() | |
1079 | ip.magics_manager.register(FooFoo) |
|
1080 | ip.magics_manager.register(FooFoo) | |
1080 | oinfo = ip.object_inspect("foo") |
|
1081 | oinfo = ip.object_inspect("foo") | |
1081 | assert oinfo["found"] is True |
|
1082 | assert oinfo["found"] is True | |
1082 | assert oinfo["ismagic"] is True |
|
1083 | assert oinfo["ismagic"] is True | |
1083 |
|
1084 | |||
1084 | oinfo = ip.object_inspect("%%foo") |
|
1085 | oinfo = ip.object_inspect("%%foo") | |
1085 | assert oinfo["found"] is True |
|
1086 | assert oinfo["found"] is True | |
1086 | assert oinfo["ismagic"] is True |
|
1087 | assert oinfo["ismagic"] is True | |
1087 | assert oinfo["docstring"] == FooFoo.cell_foo.__doc__ |
|
1088 | assert oinfo["docstring"] == FooFoo.cell_foo.__doc__ | |
1088 |
|
1089 | |||
1089 | oinfo = ip.object_inspect("%foo") |
|
1090 | oinfo = ip.object_inspect("%foo") | |
1090 | assert oinfo["found"] is True |
|
1091 | assert oinfo["found"] is True | |
1091 | assert oinfo["ismagic"] is True |
|
1092 | assert oinfo["ismagic"] is True | |
1092 | assert oinfo["docstring"] == FooFoo.line_foo.__doc__ |
|
1093 | assert oinfo["docstring"] == FooFoo.line_foo.__doc__ | |
1093 |
|
1094 | |||
1094 |
|
1095 | |||
1095 | def test_multiple_magics(): |
|
1096 | def test_multiple_magics(): | |
1096 | ip = get_ipython() |
|
1097 | ip = get_ipython() | |
1097 | foo1 = FooFoo(ip) |
|
1098 | foo1 = FooFoo(ip) | |
1098 | foo2 = FooFoo(ip) |
|
1099 | foo2 = FooFoo(ip) | |
1099 | mm = ip.magics_manager |
|
1100 | mm = ip.magics_manager | |
1100 | mm.register(foo1) |
|
1101 | mm.register(foo1) | |
1101 | assert mm.magics["line"]["foo"].__self__ is foo1 |
|
1102 | assert mm.magics["line"]["foo"].__self__ is foo1 | |
1102 | mm.register(foo2) |
|
1103 | mm.register(foo2) | |
1103 | assert mm.magics["line"]["foo"].__self__ is foo2 |
|
1104 | assert mm.magics["line"]["foo"].__self__ is foo2 | |
1104 |
|
1105 | |||
1105 |
|
1106 | |||
1106 | def test_alias_magic(): |
|
1107 | def test_alias_magic(): | |
1107 | """Test %alias_magic.""" |
|
1108 | """Test %alias_magic.""" | |
1108 | ip = get_ipython() |
|
1109 | ip = get_ipython() | |
1109 | mm = ip.magics_manager |
|
1110 | mm = ip.magics_manager | |
1110 |
|
1111 | |||
1111 | # Basic operation: both cell and line magics are created, if possible. |
|
1112 | # Basic operation: both cell and line magics are created, if possible. | |
1112 | ip.run_line_magic("alias_magic", "timeit_alias timeit") |
|
1113 | ip.run_line_magic("alias_magic", "timeit_alias timeit") | |
1113 | assert "timeit_alias" in mm.magics["line"] |
|
1114 | assert "timeit_alias" in mm.magics["line"] | |
1114 | assert "timeit_alias" in mm.magics["cell"] |
|
1115 | assert "timeit_alias" in mm.magics["cell"] | |
1115 |
|
1116 | |||
1116 | # --cell is specified, line magic not created. |
|
1117 | # --cell is specified, line magic not created. | |
1117 | ip.run_line_magic("alias_magic", "--cell timeit_cell_alias timeit") |
|
1118 | ip.run_line_magic("alias_magic", "--cell timeit_cell_alias timeit") | |
1118 | assert "timeit_cell_alias" not in mm.magics["line"] |
|
1119 | assert "timeit_cell_alias" not in mm.magics["line"] | |
1119 | assert "timeit_cell_alias" in mm.magics["cell"] |
|
1120 | assert "timeit_cell_alias" in mm.magics["cell"] | |
1120 |
|
1121 | |||
1121 | # Test that line alias is created successfully. |
|
1122 | # Test that line alias is created successfully. | |
1122 | ip.run_line_magic("alias_magic", "--line env_alias env") |
|
1123 | ip.run_line_magic("alias_magic", "--line env_alias env") | |
1123 | assert ip.run_line_magic("env", "") == ip.run_line_magic("env_alias", "") |
|
1124 | assert ip.run_line_magic("env", "") == ip.run_line_magic("env_alias", "") | |
1124 |
|
1125 | |||
1125 | # Test that line alias with parameters passed in is created successfully. |
|
1126 | # Test that line alias with parameters passed in is created successfully. | |
1126 | ip.run_line_magic( |
|
1127 | ip.run_line_magic( | |
1127 | "alias_magic", "--line history_alias history --params " + shlex.quote("3") |
|
1128 | "alias_magic", "--line history_alias history --params " + shlex.quote("3") | |
1128 | ) |
|
1129 | ) | |
1129 | assert "history_alias" in mm.magics["line"] |
|
1130 | assert "history_alias" in mm.magics["line"] | |
1130 |
|
1131 | |||
1131 |
|
1132 | |||
1132 | def test_save(): |
|
1133 | def test_save(): | |
1133 | """Test %save.""" |
|
1134 | """Test %save.""" | |
1134 | ip = get_ipython() |
|
1135 | ip = get_ipython() | |
1135 | ip.history_manager.reset() # Clear any existing history. |
|
1136 | ip.history_manager.reset() # Clear any existing history. | |
1136 | cmds = ["a=1", "def b():\n return a**2", "print(a, b())"] |
|
1137 | cmds = ["a=1", "def b():\n return a**2", "print(a, b())"] | |
1137 | for i, cmd in enumerate(cmds, start=1): |
|
1138 | for i, cmd in enumerate(cmds, start=1): | |
1138 | ip.history_manager.store_inputs(i, cmd) |
|
1139 | ip.history_manager.store_inputs(i, cmd) | |
1139 | with TemporaryDirectory() as tmpdir: |
|
1140 | with TemporaryDirectory() as tmpdir: | |
1140 | file = os.path.join(tmpdir, "testsave.py") |
|
1141 | file = os.path.join(tmpdir, "testsave.py") | |
1141 | ip.run_line_magic("save", "%s 1-10" % file) |
|
1142 | ip.run_line_magic("save", "%s 1-10" % file) | |
1142 | content = Path(file).read_text() |
|
1143 | content = Path(file).read_text() | |
1143 | assert content.count(cmds[0]) == 1 |
|
1144 | assert content.count(cmds[0]) == 1 | |
1144 | assert "coding: utf-8" in content |
|
1145 | assert "coding: utf-8" in content | |
1145 | ip.run_line_magic("save", "-a %s 1-10" % file) |
|
1146 | ip.run_line_magic("save", "-a %s 1-10" % file) | |
1146 | content = Path(file).read_text() |
|
1147 | content = Path(file).read_text() | |
1147 | assert content.count(cmds[0]) == 2 |
|
1148 | assert content.count(cmds[0]) == 2 | |
1148 | assert "coding: utf-8" in content |
|
1149 | assert "coding: utf-8" in content | |
1149 |
|
1150 | |||
1150 |
|
1151 | |||
1151 | def test_save_with_no_args(): |
|
1152 | def test_save_with_no_args(): | |
1152 | ip = get_ipython() |
|
1153 | ip = get_ipython() | |
1153 | ip.history_manager.reset() # Clear any existing history. |
|
1154 | ip.history_manager.reset() # Clear any existing history. | |
1154 | cmds = ["a=1", "def b():\n return a**2", "print(a, b())", "%save"] |
|
1155 | cmds = ["a=1", "def b():\n return a**2", "print(a, b())", "%save"] | |
1155 | for i, cmd in enumerate(cmds, start=1): |
|
1156 | for i, cmd in enumerate(cmds, start=1): | |
1156 | ip.history_manager.store_inputs(i, cmd) |
|
1157 | ip.history_manager.store_inputs(i, cmd) | |
1157 |
|
1158 | |||
1158 | with TemporaryDirectory() as tmpdir: |
|
1159 | with TemporaryDirectory() as tmpdir: | |
1159 | path = os.path.join(tmpdir, "testsave.py") |
|
1160 | path = os.path.join(tmpdir, "testsave.py") | |
1160 | ip.run_line_magic("save", path) |
|
1161 | ip.run_line_magic("save", path) | |
1161 | content = Path(path).read_text() |
|
1162 | content = Path(path).read_text() | |
1162 | expected_content = dedent( |
|
1163 | expected_content = dedent( | |
1163 | """\ |
|
1164 | """\ | |
1164 | # coding: utf-8 |
|
1165 | # coding: utf-8 | |
1165 | a=1 |
|
1166 | a=1 | |
1166 | def b(): |
|
1167 | def b(): | |
1167 | return a**2 |
|
1168 | return a**2 | |
1168 | print(a, b()) |
|
1169 | print(a, b()) | |
1169 | """ |
|
1170 | """ | |
1170 | ) |
|
1171 | ) | |
1171 | assert content == expected_content |
|
1172 | assert content == expected_content | |
1172 |
|
1173 | |||
1173 |
|
1174 | |||
1174 | def test_store(): |
|
1175 | def test_store(): | |
1175 | """Test %store.""" |
|
1176 | """Test %store.""" | |
1176 | ip = get_ipython() |
|
1177 | ip = get_ipython() | |
1177 | ip.run_line_magic('load_ext', 'storemagic') |
|
1178 | ip.run_line_magic('load_ext', 'storemagic') | |
1178 |
|
1179 | |||
1179 | # make sure the storage is empty |
|
1180 | # make sure the storage is empty | |
1180 | ip.run_line_magic("store", "-z") |
|
1181 | ip.run_line_magic("store", "-z") | |
1181 | ip.user_ns["var"] = 42 |
|
1182 | ip.user_ns["var"] = 42 | |
1182 | ip.run_line_magic("store", "var") |
|
1183 | ip.run_line_magic("store", "var") | |
1183 | ip.user_ns["var"] = 39 |
|
1184 | ip.user_ns["var"] = 39 | |
1184 | ip.run_line_magic("store", "-r") |
|
1185 | ip.run_line_magic("store", "-r") | |
1185 | assert ip.user_ns["var"] == 42 |
|
1186 | assert ip.user_ns["var"] == 42 | |
1186 |
|
1187 | |||
1187 | ip.run_line_magic("store", "-d var") |
|
1188 | ip.run_line_magic("store", "-d var") | |
1188 | ip.user_ns["var"] = 39 |
|
1189 | ip.user_ns["var"] = 39 | |
1189 | ip.run_line_magic("store", "-r") |
|
1190 | ip.run_line_magic("store", "-r") | |
1190 | assert ip.user_ns["var"] == 39 |
|
1191 | assert ip.user_ns["var"] == 39 | |
1191 |
|
1192 | |||
1192 |
|
1193 | |||
1193 | def _run_edit_test(arg_s, exp_filename=None, |
|
1194 | def _run_edit_test(arg_s, exp_filename=None, | |
1194 | exp_lineno=-1, |
|
1195 | exp_lineno=-1, | |
1195 | exp_contents=None, |
|
1196 | exp_contents=None, | |
1196 | exp_is_temp=None): |
|
1197 | exp_is_temp=None): | |
1197 | ip = get_ipython() |
|
1198 | ip = get_ipython() | |
1198 | M = code.CodeMagics(ip) |
|
1199 | M = code.CodeMagics(ip) | |
1199 | last_call = ['',''] |
|
1200 | last_call = ['',''] | |
1200 | opts,args = M.parse_options(arg_s,'prxn:') |
|
1201 | opts,args = M.parse_options(arg_s,'prxn:') | |
1201 | filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call) |
|
1202 | filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call) | |
1202 |
|
1203 | |||
1203 | if exp_filename is not None: |
|
1204 | if exp_filename is not None: | |
1204 | assert exp_filename == filename |
|
1205 | assert exp_filename == filename | |
1205 | if exp_contents is not None: |
|
1206 | if exp_contents is not None: | |
1206 | with io.open(filename, 'r', encoding='utf-8') as f: |
|
1207 | with io.open(filename, 'r', encoding='utf-8') as f: | |
1207 | contents = f.read() |
|
1208 | contents = f.read() | |
1208 | assert exp_contents == contents |
|
1209 | assert exp_contents == contents | |
1209 | if exp_lineno != -1: |
|
1210 | if exp_lineno != -1: | |
1210 | assert exp_lineno == lineno |
|
1211 | assert exp_lineno == lineno | |
1211 | if exp_is_temp is not None: |
|
1212 | if exp_is_temp is not None: | |
1212 | assert exp_is_temp == is_temp |
|
1213 | assert exp_is_temp == is_temp | |
1213 |
|
1214 | |||
1214 |
|
1215 | |||
1215 | def test_edit_interactive(): |
|
1216 | def test_edit_interactive(): | |
1216 | """%edit on interactively defined objects""" |
|
1217 | """%edit on interactively defined objects""" | |
1217 | ip = get_ipython() |
|
1218 | ip = get_ipython() | |
1218 | n = ip.execution_count |
|
1219 | n = ip.execution_count | |
1219 | ip.run_cell("def foo(): return 1", store_history=True) |
|
1220 | ip.run_cell("def foo(): return 1", store_history=True) | |
1220 |
|
1221 | |||
1221 | with pytest.raises(code.InteractivelyDefined) as e: |
|
1222 | with pytest.raises(code.InteractivelyDefined) as e: | |
1222 | _run_edit_test("foo") |
|
1223 | _run_edit_test("foo") | |
1223 | assert e.value.index == n |
|
1224 | assert e.value.index == n | |
1224 |
|
1225 | |||
1225 |
|
1226 | |||
1226 | def test_edit_cell(): |
|
1227 | def test_edit_cell(): | |
1227 | """%edit [cell id]""" |
|
1228 | """%edit [cell id]""" | |
1228 | ip = get_ipython() |
|
1229 | ip = get_ipython() | |
1229 |
|
1230 | |||
1230 | ip.run_cell("def foo(): return 1", store_history=True) |
|
1231 | ip.run_cell("def foo(): return 1", store_history=True) | |
1231 |
|
1232 | |||
1232 | # test |
|
1233 | # test | |
1233 | _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True) |
|
1234 | _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True) | |
1234 |
|
1235 | |||
1235 | def test_edit_fname(): |
|
1236 | def test_edit_fname(): | |
1236 | """%edit file""" |
|
1237 | """%edit file""" | |
1237 | # test |
|
1238 | # test | |
1238 | _run_edit_test("test file.py", exp_filename="test file.py") |
|
1239 | _run_edit_test("test file.py", exp_filename="test file.py") | |
1239 |
|
1240 | |||
1240 | def test_bookmark(): |
|
1241 | def test_bookmark(): | |
1241 | ip = get_ipython() |
|
1242 | ip = get_ipython() | |
1242 | ip.run_line_magic('bookmark', 'bmname') |
|
1243 | ip.run_line_magic('bookmark', 'bmname') | |
1243 | with tt.AssertPrints('bmname'): |
|
1244 | with tt.AssertPrints('bmname'): | |
1244 | ip.run_line_magic('bookmark', '-l') |
|
1245 | ip.run_line_magic('bookmark', '-l') | |
1245 | ip.run_line_magic('bookmark', '-d bmname') |
|
1246 | ip.run_line_magic('bookmark', '-d bmname') | |
1246 |
|
1247 | |||
1247 | def test_ls_magic(): |
|
1248 | def test_ls_magic(): | |
1248 | ip = get_ipython() |
|
1249 | ip = get_ipython() | |
1249 | json_formatter = ip.display_formatter.formatters['application/json'] |
|
1250 | json_formatter = ip.display_formatter.formatters['application/json'] | |
1250 | json_formatter.enabled = True |
|
1251 | json_formatter.enabled = True | |
1251 | lsmagic = ip.magic('lsmagic') |
|
1252 | lsmagic = ip.magic('lsmagic') | |
1252 | with warnings.catch_warnings(record=True) as w: |
|
1253 | with warnings.catch_warnings(record=True) as w: | |
1253 | j = json_formatter(lsmagic) |
|
1254 | j = json_formatter(lsmagic) | |
1254 | assert sorted(j) == ["cell", "line"] |
|
1255 | assert sorted(j) == ["cell", "line"] | |
1255 | assert w == [] # no warnings |
|
1256 | assert w == [] # no warnings | |
1256 |
|
1257 | |||
1257 |
|
1258 | |||
1258 | def test_strip_initial_indent(): |
|
1259 | def test_strip_initial_indent(): | |
1259 | def sii(s): |
|
1260 | def sii(s): | |
1260 | lines = s.splitlines() |
|
1261 | lines = s.splitlines() | |
1261 | return '\n'.join(code.strip_initial_indent(lines)) |
|
1262 | return '\n'.join(code.strip_initial_indent(lines)) | |
1262 |
|
1263 | |||
1263 | assert sii(" a = 1\nb = 2") == "a = 1\nb = 2" |
|
1264 | assert sii(" a = 1\nb = 2") == "a = 1\nb = 2" | |
1264 | assert sii(" a\n b\nc") == "a\n b\nc" |
|
1265 | assert sii(" a\n b\nc") == "a\n b\nc" | |
1265 | assert sii("a\n b") == "a\n b" |
|
1266 | assert sii("a\n b") == "a\n b" | |
1266 |
|
1267 | |||
1267 | def test_logging_magic_quiet_from_arg(): |
|
1268 | def test_logging_magic_quiet_from_arg(): | |
1268 | _ip.config.LoggingMagics.quiet = False |
|
1269 | _ip.config.LoggingMagics.quiet = False | |
1269 | lm = logging.LoggingMagics(shell=_ip) |
|
1270 | lm = logging.LoggingMagics(shell=_ip) | |
1270 | with TemporaryDirectory() as td: |
|
1271 | with TemporaryDirectory() as td: | |
1271 | try: |
|
1272 | try: | |
1272 | with tt.AssertNotPrints(re.compile("Activating.*")): |
|
1273 | with tt.AssertNotPrints(re.compile("Activating.*")): | |
1273 | lm.logstart('-q {}'.format( |
|
1274 | lm.logstart('-q {}'.format( | |
1274 | os.path.join(td, "quiet_from_arg.log"))) |
|
1275 | os.path.join(td, "quiet_from_arg.log"))) | |
1275 | finally: |
|
1276 | finally: | |
1276 | _ip.logger.logstop() |
|
1277 | _ip.logger.logstop() | |
1277 |
|
1278 | |||
1278 | def test_logging_magic_quiet_from_config(): |
|
1279 | def test_logging_magic_quiet_from_config(): | |
1279 | _ip.config.LoggingMagics.quiet = True |
|
1280 | _ip.config.LoggingMagics.quiet = True | |
1280 | lm = logging.LoggingMagics(shell=_ip) |
|
1281 | lm = logging.LoggingMagics(shell=_ip) | |
1281 | with TemporaryDirectory() as td: |
|
1282 | with TemporaryDirectory() as td: | |
1282 | try: |
|
1283 | try: | |
1283 | with tt.AssertNotPrints(re.compile("Activating.*")): |
|
1284 | with tt.AssertNotPrints(re.compile("Activating.*")): | |
1284 | lm.logstart(os.path.join(td, "quiet_from_config.log")) |
|
1285 | lm.logstart(os.path.join(td, "quiet_from_config.log")) | |
1285 | finally: |
|
1286 | finally: | |
1286 | _ip.logger.logstop() |
|
1287 | _ip.logger.logstop() | |
1287 |
|
1288 | |||
1288 |
|
1289 | |||
1289 | def test_logging_magic_not_quiet(): |
|
1290 | def test_logging_magic_not_quiet(): | |
1290 | _ip.config.LoggingMagics.quiet = False |
|
1291 | _ip.config.LoggingMagics.quiet = False | |
1291 | lm = logging.LoggingMagics(shell=_ip) |
|
1292 | lm = logging.LoggingMagics(shell=_ip) | |
1292 | with TemporaryDirectory() as td: |
|
1293 | with TemporaryDirectory() as td: | |
1293 | try: |
|
1294 | try: | |
1294 | with tt.AssertPrints(re.compile("Activating.*")): |
|
1295 | with tt.AssertPrints(re.compile("Activating.*")): | |
1295 | lm.logstart(os.path.join(td, "not_quiet.log")) |
|
1296 | lm.logstart(os.path.join(td, "not_quiet.log")) | |
1296 | finally: |
|
1297 | finally: | |
1297 | _ip.logger.logstop() |
|
1298 | _ip.logger.logstop() | |
1298 |
|
1299 | |||
1299 |
|
1300 | |||
1300 | def test_time_no_var_expand(): |
|
1301 | def test_time_no_var_expand(): | |
1301 | _ip.user_ns['a'] = 5 |
|
1302 | _ip.user_ns['a'] = 5 | |
1302 | _ip.user_ns['b'] = [] |
|
1303 | _ip.user_ns['b'] = [] | |
1303 | _ip.magic('time b.append("{a}")') |
|
1304 | _ip.magic('time b.append("{a}")') | |
1304 | assert _ip.user_ns['b'] == ['{a}'] |
|
1305 | assert _ip.user_ns['b'] == ['{a}'] | |
1305 |
|
1306 | |||
1306 |
|
1307 | |||
1307 | # this is slow, put at the end for local testing. |
|
1308 | # this is slow, put at the end for local testing. | |
1308 | def test_timeit_arguments(): |
|
1309 | def test_timeit_arguments(): | |
1309 | "Test valid timeit arguments, should not cause SyntaxError (GH #1269)" |
|
1310 | "Test valid timeit arguments, should not cause SyntaxError (GH #1269)" | |
1310 | if sys.version_info < (3,7): |
|
1311 | if sys.version_info < (3,7): | |
1311 | _ip.magic("timeit -n1 -r1 ('#')") |
|
1312 | _ip.magic("timeit -n1 -r1 ('#')") | |
1312 | else: |
|
1313 | else: | |
1313 | # 3.7 optimize no-op statement like above out, and complain there is |
|
1314 | # 3.7 optimize no-op statement like above out, and complain there is | |
1314 | # nothing in the for loop. |
|
1315 | # nothing in the for loop. | |
1315 | _ip.magic("timeit -n1 -r1 a=('#')") |
|
1316 | _ip.magic("timeit -n1 -r1 a=('#')") | |
1316 |
|
1317 | |||
1317 |
|
1318 | |||
1318 | TEST_MODULE = """ |
|
1319 | TEST_MODULE = """ | |
1319 | print('Loaded my_tmp') |
|
1320 | print('Loaded my_tmp') | |
1320 | if __name__ == "__main__": |
|
1321 | if __name__ == "__main__": | |
1321 | print('I just ran a script') |
|
1322 | print('I just ran a script') | |
1322 | """ |
|
1323 | """ | |
1323 |
|
1324 | |||
1324 |
|
1325 | |||
1325 | def test_run_module_from_import_hook(): |
|
1326 | def test_run_module_from_import_hook(): | |
1326 | "Test that a module can be loaded via an import hook" |
|
1327 | "Test that a module can be loaded via an import hook" | |
1327 | with TemporaryDirectory() as tmpdir: |
|
1328 | with TemporaryDirectory() as tmpdir: | |
1328 | fullpath = os.path.join(tmpdir, 'my_tmp.py') |
|
1329 | fullpath = os.path.join(tmpdir, 'my_tmp.py') | |
1329 | Path(fullpath).write_text(TEST_MODULE) |
|
1330 | Path(fullpath).write_text(TEST_MODULE) | |
1330 |
|
1331 | |||
1331 | import importlib.abc |
|
1332 | import importlib.abc | |
1332 | import importlib.util |
|
1333 | import importlib.util | |
1333 |
|
1334 | |||
1334 | class MyTempImporter(importlib.abc.MetaPathFinder, importlib.abc.SourceLoader): |
|
1335 | class MyTempImporter(importlib.abc.MetaPathFinder, importlib.abc.SourceLoader): | |
1335 | def find_spec(self, fullname, path, target=None): |
|
1336 | def find_spec(self, fullname, path, target=None): | |
1336 | if fullname == "my_tmp": |
|
1337 | if fullname == "my_tmp": | |
1337 | return importlib.util.spec_from_loader(fullname, self) |
|
1338 | return importlib.util.spec_from_loader(fullname, self) | |
1338 |
|
1339 | |||
1339 | def get_filename(self, fullname): |
|
1340 | def get_filename(self, fullname): | |
1340 | if fullname != "my_tmp": |
|
1341 | if fullname != "my_tmp": | |
1341 | raise ImportError(f"unexpected module name '{fullname}'") |
|
1342 | raise ImportError(f"unexpected module name '{fullname}'") | |
1342 | return fullpath |
|
1343 | return fullpath | |
1343 |
|
1344 | |||
1344 | def get_data(self, path): |
|
1345 | def get_data(self, path): | |
1345 | if not Path(path).samefile(fullpath): |
|
1346 | if not Path(path).samefile(fullpath): | |
1346 | raise OSError(f"expected path '{fullpath}', got '{path}'") |
|
1347 | raise OSError(f"expected path '{fullpath}', got '{path}'") | |
1347 | return Path(fullpath).read_text() |
|
1348 | return Path(fullpath).read_text() | |
1348 |
|
1349 | |||
1349 | sys.meta_path.insert(0, MyTempImporter()) |
|
1350 | sys.meta_path.insert(0, MyTempImporter()) | |
1350 |
|
1351 | |||
1351 | with capture_output() as captured: |
|
1352 | with capture_output() as captured: | |
1352 | _ip.magic("run -m my_tmp") |
|
1353 | _ip.magic("run -m my_tmp") | |
1353 | _ip.run_cell("import my_tmp") |
|
1354 | _ip.run_cell("import my_tmp") | |
1354 |
|
1355 | |||
1355 | output = "Loaded my_tmp\nI just ran a script\nLoaded my_tmp\n" |
|
1356 | output = "Loaded my_tmp\nI just ran a script\nLoaded my_tmp\n" | |
1356 | assert output == captured.stdout |
|
1357 | assert output == captured.stdout | |
1357 |
|
1358 | |||
1358 | sys.meta_path.pop(0) |
|
1359 | sys.meta_path.pop(0) |
@@ -1,454 +1,453 b'' | |||||
1 | """Tests for the object inspection functionality. |
|
1 | """Tests for the object inspection functionality. | |
2 | """ |
|
2 | """ | |
3 |
|
3 | |||
4 | # Copyright (c) IPython Development Team. |
|
4 | # Copyright (c) IPython Development Team. | |
5 | # Distributed under the terms of the Modified BSD License. |
|
5 | # Distributed under the terms of the Modified BSD License. | |
6 |
|
6 | |||
7 |
|
7 | |||
8 | from inspect import signature, Signature, Parameter |
|
8 | from inspect import signature, Signature, Parameter | |
9 | import os |
|
9 | import os | |
10 | import re |
|
10 | import re | |
11 |
|
11 | |||
12 | from .. import oinspect |
|
12 | from .. import oinspect | |
13 |
|
13 | |||
14 | from decorator import decorator |
|
14 | from decorator import decorator | |
15 |
|
15 | |||
16 | from IPython.testing.tools import AssertPrints, AssertNotPrints |
|
16 | from IPython.testing.tools import AssertPrints, AssertNotPrints | |
17 | from IPython.utils.path import compress_user |
|
17 | from IPython.utils.path import compress_user | |
18 |
|
18 | |||
19 |
|
19 | |||
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 | # Globals and constants |
|
21 | # Globals and constants | |
22 | #----------------------------------------------------------------------------- |
|
22 | #----------------------------------------------------------------------------- | |
23 |
|
23 | |||
24 | inspector = None |
|
24 | inspector = None | |
25 |
|
25 | |||
26 | def setup_module(): |
|
26 | def setup_module(): | |
27 | global inspector |
|
27 | global inspector | |
28 | inspector = oinspect.Inspector() |
|
28 | inspector = oinspect.Inspector() | |
29 |
|
29 | |||
30 |
|
30 | |||
31 | #----------------------------------------------------------------------------- |
|
31 | #----------------------------------------------------------------------------- | |
32 | # Local utilities |
|
32 | # Local utilities | |
33 | #----------------------------------------------------------------------------- |
|
33 | #----------------------------------------------------------------------------- | |
34 |
|
34 | |||
35 | # WARNING: since this test checks the line number where a function is |
|
35 | # WARNING: since this test checks the line number where a function is | |
36 | # defined, if any code is inserted above, the following line will need to be |
|
36 | # defined, if any code is inserted above, the following line will need to be | |
37 | # updated. Do NOT insert any whitespace between the next line and the function |
|
37 | # updated. Do NOT insert any whitespace between the next line and the function | |
38 | # definition below. |
|
38 | # definition below. | |
39 | THIS_LINE_NUMBER = 39 # Put here the actual number of this line |
|
39 | THIS_LINE_NUMBER = 39 # Put here the actual number of this line | |
40 |
|
40 | |||
41 | from unittest import TestCase |
|
41 | from unittest import TestCase | |
42 |
|
42 | |||
43 | class Test(TestCase): |
|
43 | class Test(TestCase): | |
44 |
|
44 | |||
45 | def test_find_source_lines(self): |
|
45 | def test_find_source_lines(self): | |
46 | self.assertEqual(oinspect.find_source_lines(Test.test_find_source_lines), |
|
46 | self.assertEqual(oinspect.find_source_lines(Test.test_find_source_lines), | |
47 | THIS_LINE_NUMBER+6) |
|
47 | THIS_LINE_NUMBER+6) | |
48 |
|
48 | |||
49 |
|
49 | |||
50 | # A couple of utilities to ensure these tests work the same from a source or a |
|
50 | # A couple of utilities to ensure these tests work the same from a source or a | |
51 | # binary install |
|
51 | # binary install | |
52 | def pyfile(fname): |
|
52 | def pyfile(fname): | |
53 | return os.path.normcase(re.sub('.py[co]$', '.py', fname)) |
|
53 | return os.path.normcase(re.sub('.py[co]$', '.py', fname)) | |
54 |
|
54 | |||
55 |
|
55 | |||
56 | def match_pyfiles(f1, f2): |
|
56 | def match_pyfiles(f1, f2): | |
57 | assert pyfile(f1) == pyfile(f2) |
|
57 | assert pyfile(f1) == pyfile(f2) | |
58 |
|
58 | |||
59 |
|
59 | |||
60 | def test_find_file(): |
|
60 | def test_find_file(): | |
61 | match_pyfiles(oinspect.find_file(test_find_file), os.path.abspath(__file__)) |
|
61 | match_pyfiles(oinspect.find_file(test_find_file), os.path.abspath(__file__)) | |
62 |
|
62 | |||
63 |
|
63 | |||
64 | def test_find_file_decorated1(): |
|
64 | def test_find_file_decorated1(): | |
65 |
|
65 | |||
66 | @decorator |
|
66 | @decorator | |
67 | def noop1(f): |
|
67 | def noop1(f): | |
68 | def wrapper(*a, **kw): |
|
68 | def wrapper(*a, **kw): | |
69 | return f(*a, **kw) |
|
69 | return f(*a, **kw) | |
70 | return wrapper |
|
70 | return wrapper | |
71 |
|
71 | |||
72 | @noop1 |
|
72 | @noop1 | |
73 | def f(x): |
|
73 | def f(x): | |
74 | "My docstring" |
|
74 | "My docstring" | |
75 |
|
75 | |||
76 | match_pyfiles(oinspect.find_file(f), os.path.abspath(__file__)) |
|
76 | match_pyfiles(oinspect.find_file(f), os.path.abspath(__file__)) | |
77 | assert f.__doc__ == "My docstring" |
|
77 | assert f.__doc__ == "My docstring" | |
78 |
|
78 | |||
79 |
|
79 | |||
80 | def test_find_file_decorated2(): |
|
80 | def test_find_file_decorated2(): | |
81 |
|
81 | |||
82 | @decorator |
|
82 | @decorator | |
83 | def noop2(f, *a, **kw): |
|
83 | def noop2(f, *a, **kw): | |
84 | return f(*a, **kw) |
|
84 | return f(*a, **kw) | |
85 |
|
85 | |||
86 | @noop2 |
|
86 | @noop2 | |
87 | @noop2 |
|
87 | @noop2 | |
88 | @noop2 |
|
88 | @noop2 | |
89 | def f(x): |
|
89 | def f(x): | |
90 | "My docstring 2" |
|
90 | "My docstring 2" | |
91 |
|
91 | |||
92 | match_pyfiles(oinspect.find_file(f), os.path.abspath(__file__)) |
|
92 | match_pyfiles(oinspect.find_file(f), os.path.abspath(__file__)) | |
93 | assert f.__doc__ == "My docstring 2" |
|
93 | assert f.__doc__ == "My docstring 2" | |
94 |
|
94 | |||
95 |
|
95 | |||
96 | def test_find_file_magic(): |
|
96 | def test_find_file_magic(): | |
97 | run = ip.find_line_magic('run') |
|
97 | run = ip.find_line_magic('run') | |
98 | assert oinspect.find_file(run) is not None |
|
98 | assert oinspect.find_file(run) is not None | |
99 |
|
99 | |||
100 |
|
100 | |||
101 | # A few generic objects we can then inspect in the tests below |
|
101 | # A few generic objects we can then inspect in the tests below | |
102 |
|
102 | |||
103 | class Call(object): |
|
103 | class Call(object): | |
104 | """This is the class docstring.""" |
|
104 | """This is the class docstring.""" | |
105 |
|
105 | |||
106 | def __init__(self, x, y=1): |
|
106 | def __init__(self, x, y=1): | |
107 | """This is the constructor docstring.""" |
|
107 | """This is the constructor docstring.""" | |
108 |
|
108 | |||
109 | def __call__(self, *a, **kw): |
|
109 | def __call__(self, *a, **kw): | |
110 | """This is the call docstring.""" |
|
110 | """This is the call docstring.""" | |
111 |
|
111 | |||
112 | def method(self, x, z=2): |
|
112 | def method(self, x, z=2): | |
113 | """Some method's docstring""" |
|
113 | """Some method's docstring""" | |
114 |
|
114 | |||
115 | class HasSignature(object): |
|
115 | class HasSignature(object): | |
116 | """This is the class docstring.""" |
|
116 | """This is the class docstring.""" | |
117 | __signature__ = Signature([Parameter('test', Parameter.POSITIONAL_OR_KEYWORD)]) |
|
117 | __signature__ = Signature([Parameter('test', Parameter.POSITIONAL_OR_KEYWORD)]) | |
118 |
|
118 | |||
119 | def __init__(self, *args): |
|
119 | def __init__(self, *args): | |
120 | """This is the init docstring""" |
|
120 | """This is the init docstring""" | |
121 |
|
121 | |||
122 |
|
122 | |||
123 | class SimpleClass(object): |
|
123 | class SimpleClass(object): | |
124 | def method(self, x, z=2): |
|
124 | def method(self, x, z=2): | |
125 | """Some method's docstring""" |
|
125 | """Some method's docstring""" | |
126 |
|
126 | |||
127 |
|
127 | |||
128 | class Awkward(object): |
|
128 | class Awkward(object): | |
129 | def __getattr__(self, name): |
|
129 | def __getattr__(self, name): | |
130 | raise Exception(name) |
|
130 | raise Exception(name) | |
131 |
|
131 | |||
132 | class NoBoolCall: |
|
132 | class NoBoolCall: | |
133 | """ |
|
133 | """ | |
134 | callable with `__bool__` raising should still be inspect-able. |
|
134 | callable with `__bool__` raising should still be inspect-able. | |
135 | """ |
|
135 | """ | |
136 |
|
136 | |||
137 | def __call__(self): |
|
137 | def __call__(self): | |
138 | """does nothing""" |
|
138 | """does nothing""" | |
139 | pass |
|
139 | pass | |
140 |
|
140 | |||
141 | def __bool__(self): |
|
141 | def __bool__(self): | |
142 | """just raise NotImplemented""" |
|
142 | """just raise NotImplemented""" | |
143 | raise NotImplementedError('Must be implemented') |
|
143 | raise NotImplementedError('Must be implemented') | |
144 |
|
144 | |||
145 |
|
145 | |||
146 | class SerialLiar(object): |
|
146 | class SerialLiar(object): | |
147 | """Attribute accesses always get another copy of the same class. |
|
147 | """Attribute accesses always get another copy of the same class. | |
148 |
|
148 | |||
149 | unittest.mock.call does something similar, but it's not ideal for testing |
|
149 | unittest.mock.call does something similar, but it's not ideal for testing | |
150 | as the failure mode is to eat all your RAM. This gives up after 10k levels. |
|
150 | as the failure mode is to eat all your RAM. This gives up after 10k levels. | |
151 | """ |
|
151 | """ | |
152 | def __init__(self, max_fibbing_twig, lies_told=0): |
|
152 | def __init__(self, max_fibbing_twig, lies_told=0): | |
153 | if lies_told > 10000: |
|
153 | if lies_told > 10000: | |
154 | raise RuntimeError('Nose too long, honesty is the best policy') |
|
154 | raise RuntimeError('Nose too long, honesty is the best policy') | |
155 | self.max_fibbing_twig = max_fibbing_twig |
|
155 | self.max_fibbing_twig = max_fibbing_twig | |
156 | self.lies_told = lies_told |
|
156 | self.lies_told = lies_told | |
157 | max_fibbing_twig[0] = max(max_fibbing_twig[0], lies_told) |
|
157 | max_fibbing_twig[0] = max(max_fibbing_twig[0], lies_told) | |
158 |
|
158 | |||
159 | def __getattr__(self, item): |
|
159 | def __getattr__(self, item): | |
160 | return SerialLiar(self.max_fibbing_twig, self.lies_told + 1) |
|
160 | return SerialLiar(self.max_fibbing_twig, self.lies_told + 1) | |
161 |
|
161 | |||
162 | #----------------------------------------------------------------------------- |
|
162 | #----------------------------------------------------------------------------- | |
163 | # Tests |
|
163 | # Tests | |
164 | #----------------------------------------------------------------------------- |
|
164 | #----------------------------------------------------------------------------- | |
165 |
|
165 | |||
166 | def test_info(): |
|
166 | def test_info(): | |
167 | "Check that Inspector.info fills out various fields as expected." |
|
167 | "Check that Inspector.info fills out various fields as expected." | |
168 | i = inspector.info(Call, oname="Call") |
|
168 | i = inspector.info(Call, oname="Call") | |
169 | assert i["type_name"] == "type" |
|
169 | assert i["type_name"] == "type" | |
170 | expected_class = str(type(type)) # <class 'type'> (Python 3) or <type 'type'> |
|
170 | expected_class = str(type(type)) # <class 'type'> (Python 3) or <type 'type'> | |
171 | assert i["base_class"] == expected_class |
|
171 | assert i["base_class"] == expected_class | |
172 | assert re.search( |
|
172 | assert re.search( | |
173 | "<class 'IPython.core.tests.test_oinspect.Call'( at 0x[0-9a-f]{1,9})?>", |
|
173 | "<class 'IPython.core.tests.test_oinspect.Call'( at 0x[0-9a-f]{1,9})?>", | |
174 | i["string_form"], |
|
174 | i["string_form"], | |
175 | ) |
|
175 | ) | |
176 | fname = __file__ |
|
176 | fname = __file__ | |
177 | if fname.endswith(".pyc"): |
|
177 | if fname.endswith(".pyc"): | |
178 | fname = fname[:-1] |
|
178 | fname = fname[:-1] | |
179 | # case-insensitive comparison needed on some filesystems |
|
179 | # case-insensitive comparison needed on some filesystems | |
180 | # e.g. Windows: |
|
180 | # e.g. Windows: | |
181 | assert i["file"].lower() == compress_user(fname).lower() |
|
181 | assert i["file"].lower() == compress_user(fname).lower() | |
182 | assert i["definition"] == None |
|
182 | assert i["definition"] == None | |
183 | assert i["docstring"] == Call.__doc__ |
|
183 | assert i["docstring"] == Call.__doc__ | |
184 | assert i["source"] == None |
|
184 | assert i["source"] == None | |
185 | assert i["isclass"] is True |
|
185 | assert i["isclass"] is True | |
186 | assert i["init_definition"] == "Call(x, y=1)" |
|
186 | assert i["init_definition"] == "Call(x, y=1)" | |
187 | assert i["init_docstring"] == Call.__init__.__doc__ |
|
187 | assert i["init_docstring"] == Call.__init__.__doc__ | |
188 |
|
188 | |||
189 | i = inspector.info(Call, detail_level=1) |
|
189 | i = inspector.info(Call, detail_level=1) | |
190 | assert i["source"] is not None |
|
190 | assert i["source"] is not None | |
191 | assert i["docstring"] == None |
|
191 | assert i["docstring"] == None | |
192 |
|
192 | |||
193 | c = Call(1) |
|
193 | c = Call(1) | |
194 | c.__doc__ = "Modified instance docstring" |
|
194 | c.__doc__ = "Modified instance docstring" | |
195 | i = inspector.info(c) |
|
195 | i = inspector.info(c) | |
196 | assert i["type_name"] == "Call" |
|
196 | assert i["type_name"] == "Call" | |
197 | assert i["docstring"] == "Modified instance docstring" |
|
197 | assert i["docstring"] == "Modified instance docstring" | |
198 | assert i["class_docstring"] == Call.__doc__ |
|
198 | assert i["class_docstring"] == Call.__doc__ | |
199 | assert i["init_docstring"] == Call.__init__.__doc__ |
|
199 | assert i["init_docstring"] == Call.__init__.__doc__ | |
200 | assert i["call_docstring"] == Call.__call__.__doc__ |
|
200 | assert i["call_docstring"] == Call.__call__.__doc__ | |
201 |
|
201 | |||
202 |
|
202 | |||
203 | def test_class_signature(): |
|
203 | def test_class_signature(): | |
204 | info = inspector.info(HasSignature, "HasSignature") |
|
204 | info = inspector.info(HasSignature, "HasSignature") | |
205 | assert info["init_definition"] == "HasSignature(test)" |
|
205 | assert info["init_definition"] == "HasSignature(test)" | |
206 | assert info["init_docstring"] == HasSignature.__init__.__doc__ |
|
206 | assert info["init_docstring"] == HasSignature.__init__.__doc__ | |
207 |
|
207 | |||
208 |
|
208 | |||
209 | def test_info_awkward(): |
|
209 | def test_info_awkward(): | |
210 | # Just test that this doesn't throw an error. |
|
210 | # Just test that this doesn't throw an error. | |
211 | inspector.info(Awkward()) |
|
211 | inspector.info(Awkward()) | |
212 |
|
212 | |||
213 | def test_bool_raise(): |
|
213 | def test_bool_raise(): | |
214 | inspector.info(NoBoolCall()) |
|
214 | inspector.info(NoBoolCall()) | |
215 |
|
215 | |||
216 | def test_info_serialliar(): |
|
216 | def test_info_serialliar(): | |
217 | fib_tracker = [0] |
|
217 | fib_tracker = [0] | |
218 | inspector.info(SerialLiar(fib_tracker)) |
|
218 | inspector.info(SerialLiar(fib_tracker)) | |
219 |
|
219 | |||
220 | # Nested attribute access should be cut off at 100 levels deep to avoid |
|
220 | # Nested attribute access should be cut off at 100 levels deep to avoid | |
221 | # infinite loops: https://github.com/ipython/ipython/issues/9122 |
|
221 | # infinite loops: https://github.com/ipython/ipython/issues/9122 | |
222 | assert fib_tracker[0] < 9000 |
|
222 | assert fib_tracker[0] < 9000 | |
223 |
|
223 | |||
224 | def support_function_one(x, y=2, *a, **kw): |
|
224 | def support_function_one(x, y=2, *a, **kw): | |
225 | """A simple function.""" |
|
225 | """A simple function.""" | |
226 |
|
226 | |||
227 | def test_calldef_none(): |
|
227 | def test_calldef_none(): | |
228 | # We should ignore __call__ for all of these. |
|
228 | # We should ignore __call__ for all of these. | |
229 | for obj in [support_function_one, SimpleClass().method, any, str.upper]: |
|
229 | for obj in [support_function_one, SimpleClass().method, any, str.upper]: | |
230 | i = inspector.info(obj) |
|
230 | i = inspector.info(obj) | |
231 | assert i["call_def"] is None |
|
231 | assert i["call_def"] is None | |
232 |
|
232 | |||
233 |
|
233 | |||
234 | def f_kwarg(pos, *, kwonly): |
|
234 | def f_kwarg(pos, *, kwonly): | |
235 | pass |
|
235 | pass | |
236 |
|
236 | |||
237 | def test_definition_kwonlyargs(): |
|
237 | def test_definition_kwonlyargs(): | |
238 | i = inspector.info(f_kwarg, oname="f_kwarg") # analysis:ignore |
|
238 | i = inspector.info(f_kwarg, oname="f_kwarg") # analysis:ignore | |
239 | assert i["definition"] == "f_kwarg(pos, *, kwonly)" |
|
239 | assert i["definition"] == "f_kwarg(pos, *, kwonly)" | |
240 |
|
240 | |||
241 |
|
241 | |||
242 | def test_getdoc(): |
|
242 | def test_getdoc(): | |
243 | class A(object): |
|
243 | class A(object): | |
244 | """standard docstring""" |
|
244 | """standard docstring""" | |
245 | pass |
|
245 | pass | |
246 |
|
246 | |||
247 | class B(object): |
|
247 | class B(object): | |
248 | """standard docstring""" |
|
248 | """standard docstring""" | |
249 | def getdoc(self): |
|
249 | def getdoc(self): | |
250 | return "custom docstring" |
|
250 | return "custom docstring" | |
251 |
|
251 | |||
252 | class C(object): |
|
252 | class C(object): | |
253 | """standard docstring""" |
|
253 | """standard docstring""" | |
254 | def getdoc(self): |
|
254 | def getdoc(self): | |
255 | return None |
|
255 | return None | |
256 |
|
256 | |||
257 | a = A() |
|
257 | a = A() | |
258 | b = B() |
|
258 | b = B() | |
259 | c = C() |
|
259 | c = C() | |
260 |
|
260 | |||
261 | assert oinspect.getdoc(a) == "standard docstring" |
|
261 | assert oinspect.getdoc(a) == "standard docstring" | |
262 | assert oinspect.getdoc(b) == "custom docstring" |
|
262 | assert oinspect.getdoc(b) == "custom docstring" | |
263 | assert oinspect.getdoc(c) == "standard docstring" |
|
263 | assert oinspect.getdoc(c) == "standard docstring" | |
264 |
|
264 | |||
265 |
|
265 | |||
266 | def test_empty_property_has_no_source(): |
|
266 | def test_empty_property_has_no_source(): | |
267 | i = inspector.info(property(), detail_level=1) |
|
267 | i = inspector.info(property(), detail_level=1) | |
268 | assert i["source"] is None |
|
268 | assert i["source"] is None | |
269 |
|
269 | |||
270 |
|
270 | |||
271 | def test_property_sources(): |
|
271 | def test_property_sources(): | |
272 | import posixpath |
|
|||
273 | # A simple adder whose source and signature stays |
|
272 | # A simple adder whose source and signature stays | |
274 | # the same across Python distributions |
|
273 | # the same across Python distributions | |
275 | def simple_add(a, b): |
|
274 | def simple_add(a, b): | |
276 | "Adds two numbers" |
|
275 | "Adds two numbers" | |
277 | return a + b |
|
276 | return a + b | |
278 |
|
277 | |||
279 | class A(object): |
|
278 | class A(object): | |
280 | @property |
|
279 | @property | |
281 | def foo(self): |
|
280 | def foo(self): | |
282 | return 'bar' |
|
281 | return 'bar' | |
283 |
|
282 | |||
284 | foo = foo.setter(lambda self, v: setattr(self, 'bar', v)) |
|
283 | foo = foo.setter(lambda self, v: setattr(self, 'bar', v)) | |
285 |
|
284 | |||
286 |
dname = property( |
|
285 | dname = property(oinspect.getdoc) | |
287 | adder = property(simple_add) |
|
286 | adder = property(simple_add) | |
288 |
|
287 | |||
289 | i = inspector.info(A.foo, detail_level=1) |
|
288 | i = inspector.info(A.foo, detail_level=1) | |
290 | assert "def foo(self):" in i["source"] |
|
289 | assert "def foo(self):" in i["source"] | |
291 | assert "lambda self, v:" in i["source"] |
|
290 | assert "lambda self, v:" in i["source"] | |
292 |
|
291 | |||
293 | i = inspector.info(A.dname, detail_level=1) |
|
292 | i = inspector.info(A.dname, detail_level=1) | |
294 |
assert "def |
|
293 | assert "def getdoc(obj)" in i["source"] | |
295 |
|
294 | |||
296 | i = inspector.info(A.adder, detail_level=1) |
|
295 | i = inspector.info(A.adder, detail_level=1) | |
297 | assert "def simple_add(a, b)" in i["source"] |
|
296 | assert "def simple_add(a, b)" in i["source"] | |
298 |
|
297 | |||
299 |
|
298 | |||
300 | def test_property_docstring_is_in_info_for_detail_level_0(): |
|
299 | def test_property_docstring_is_in_info_for_detail_level_0(): | |
301 | class A(object): |
|
300 | class A(object): | |
302 | @property |
|
301 | @property | |
303 | def foobar(self): |
|
302 | def foobar(self): | |
304 | """This is `foobar` property.""" |
|
303 | """This is `foobar` property.""" | |
305 | pass |
|
304 | pass | |
306 |
|
305 | |||
307 | ip.user_ns["a_obj"] = A() |
|
306 | ip.user_ns["a_obj"] = A() | |
308 | assert ( |
|
307 | assert ( | |
309 | "This is `foobar` property." |
|
308 | "This is `foobar` property." | |
310 | == ip.object_inspect("a_obj.foobar", detail_level=0)["docstring"] |
|
309 | == ip.object_inspect("a_obj.foobar", detail_level=0)["docstring"] | |
311 | ) |
|
310 | ) | |
312 |
|
311 | |||
313 | ip.user_ns["a_cls"] = A |
|
312 | ip.user_ns["a_cls"] = A | |
314 | assert ( |
|
313 | assert ( | |
315 | "This is `foobar` property." |
|
314 | "This is `foobar` property." | |
316 | == ip.object_inspect("a_cls.foobar", detail_level=0)["docstring"] |
|
315 | == ip.object_inspect("a_cls.foobar", detail_level=0)["docstring"] | |
317 | ) |
|
316 | ) | |
318 |
|
317 | |||
319 |
|
318 | |||
320 | def test_pdef(): |
|
319 | def test_pdef(): | |
321 | # See gh-1914 |
|
320 | # See gh-1914 | |
322 | def foo(): pass |
|
321 | def foo(): pass | |
323 | inspector.pdef(foo, 'foo') |
|
322 | inspector.pdef(foo, 'foo') | |
324 |
|
323 | |||
325 |
|
324 | |||
326 | def test_pinfo_nonascii(): |
|
325 | def test_pinfo_nonascii(): | |
327 | # See gh-1177 |
|
326 | # See gh-1177 | |
328 | from . import nonascii2 |
|
327 | from . import nonascii2 | |
329 | ip.user_ns['nonascii2'] = nonascii2 |
|
328 | ip.user_ns['nonascii2'] = nonascii2 | |
330 | ip._inspect('pinfo', 'nonascii2', detail_level=1) |
|
329 | ip._inspect('pinfo', 'nonascii2', detail_level=1) | |
331 |
|
330 | |||
332 | def test_pinfo_type(): |
|
331 | def test_pinfo_type(): | |
333 | """ |
|
332 | """ | |
334 | type can fail in various edge case, for example `type.__subclass__()` |
|
333 | type can fail in various edge case, for example `type.__subclass__()` | |
335 | """ |
|
334 | """ | |
336 | ip._inspect('pinfo', 'type') |
|
335 | ip._inspect('pinfo', 'type') | |
337 |
|
336 | |||
338 |
|
337 | |||
339 | def test_pinfo_docstring_no_source(): |
|
338 | def test_pinfo_docstring_no_source(): | |
340 | """Docstring should be included with detail_level=1 if there is no source""" |
|
339 | """Docstring should be included with detail_level=1 if there is no source""" | |
341 | with AssertPrints('Docstring:'): |
|
340 | with AssertPrints('Docstring:'): | |
342 | ip._inspect('pinfo', 'str.format', detail_level=0) |
|
341 | ip._inspect('pinfo', 'str.format', detail_level=0) | |
343 | with AssertPrints('Docstring:'): |
|
342 | with AssertPrints('Docstring:'): | |
344 | ip._inspect('pinfo', 'str.format', detail_level=1) |
|
343 | ip._inspect('pinfo', 'str.format', detail_level=1) | |
345 |
|
344 | |||
346 |
|
345 | |||
347 | def test_pinfo_no_docstring_if_source(): |
|
346 | def test_pinfo_no_docstring_if_source(): | |
348 | """Docstring should not be included with detail_level=1 if source is found""" |
|
347 | """Docstring should not be included with detail_level=1 if source is found""" | |
349 | def foo(): |
|
348 | def foo(): | |
350 | """foo has a docstring""" |
|
349 | """foo has a docstring""" | |
351 |
|
350 | |||
352 | ip.user_ns['foo'] = foo |
|
351 | ip.user_ns['foo'] = foo | |
353 |
|
352 | |||
354 | with AssertPrints('Docstring:'): |
|
353 | with AssertPrints('Docstring:'): | |
355 | ip._inspect('pinfo', 'foo', detail_level=0) |
|
354 | ip._inspect('pinfo', 'foo', detail_level=0) | |
356 | with AssertPrints('Source:'): |
|
355 | with AssertPrints('Source:'): | |
357 | ip._inspect('pinfo', 'foo', detail_level=1) |
|
356 | ip._inspect('pinfo', 'foo', detail_level=1) | |
358 | with AssertNotPrints('Docstring:'): |
|
357 | with AssertNotPrints('Docstring:'): | |
359 | ip._inspect('pinfo', 'foo', detail_level=1) |
|
358 | ip._inspect('pinfo', 'foo', detail_level=1) | |
360 |
|
359 | |||
361 |
|
360 | |||
362 | def test_pinfo_docstring_if_detail_and_no_source(): |
|
361 | def test_pinfo_docstring_if_detail_and_no_source(): | |
363 | """ Docstring should be displayed if source info not available """ |
|
362 | """ Docstring should be displayed if source info not available """ | |
364 | obj_def = '''class Foo(object): |
|
363 | obj_def = '''class Foo(object): | |
365 | """ This is a docstring for Foo """ |
|
364 | """ This is a docstring for Foo """ | |
366 | def bar(self): |
|
365 | def bar(self): | |
367 | """ This is a docstring for Foo.bar """ |
|
366 | """ This is a docstring for Foo.bar """ | |
368 | pass |
|
367 | pass | |
369 | ''' |
|
368 | ''' | |
370 |
|
369 | |||
371 | ip.run_cell(obj_def) |
|
370 | ip.run_cell(obj_def) | |
372 | ip.run_cell('foo = Foo()') |
|
371 | ip.run_cell('foo = Foo()') | |
373 |
|
372 | |||
374 | with AssertNotPrints("Source:"): |
|
373 | with AssertNotPrints("Source:"): | |
375 | with AssertPrints('Docstring:'): |
|
374 | with AssertPrints('Docstring:'): | |
376 | ip._inspect('pinfo', 'foo', detail_level=0) |
|
375 | ip._inspect('pinfo', 'foo', detail_level=0) | |
377 | with AssertPrints('Docstring:'): |
|
376 | with AssertPrints('Docstring:'): | |
378 | ip._inspect('pinfo', 'foo', detail_level=1) |
|
377 | ip._inspect('pinfo', 'foo', detail_level=1) | |
379 | with AssertPrints('Docstring:'): |
|
378 | with AssertPrints('Docstring:'): | |
380 | ip._inspect('pinfo', 'foo.bar', detail_level=0) |
|
379 | ip._inspect('pinfo', 'foo.bar', detail_level=0) | |
381 |
|
380 | |||
382 | with AssertNotPrints('Docstring:'): |
|
381 | with AssertNotPrints('Docstring:'): | |
383 | with AssertPrints('Source:'): |
|
382 | with AssertPrints('Source:'): | |
384 | ip._inspect('pinfo', 'foo.bar', detail_level=1) |
|
383 | ip._inspect('pinfo', 'foo.bar', detail_level=1) | |
385 |
|
384 | |||
386 |
|
385 | |||
387 | def test_pinfo_magic(): |
|
386 | def test_pinfo_magic(): | |
388 | with AssertPrints('Docstring:'): |
|
387 | with AssertPrints('Docstring:'): | |
389 | ip._inspect('pinfo', 'lsmagic', detail_level=0) |
|
388 | ip._inspect('pinfo', 'lsmagic', detail_level=0) | |
390 |
|
389 | |||
391 | with AssertPrints('Source:'): |
|
390 | with AssertPrints('Source:'): | |
392 | ip._inspect('pinfo', 'lsmagic', detail_level=1) |
|
391 | ip._inspect('pinfo', 'lsmagic', detail_level=1) | |
393 |
|
392 | |||
394 |
|
393 | |||
395 | def test_init_colors(): |
|
394 | def test_init_colors(): | |
396 | # ensure colors are not present in signature info |
|
395 | # ensure colors are not present in signature info | |
397 | info = inspector.info(HasSignature) |
|
396 | info = inspector.info(HasSignature) | |
398 | init_def = info["init_definition"] |
|
397 | init_def = info["init_definition"] | |
399 | assert "[0m" not in init_def |
|
398 | assert "[0m" not in init_def | |
400 |
|
399 | |||
401 |
|
400 | |||
402 | def test_builtin_init(): |
|
401 | def test_builtin_init(): | |
403 | info = inspector.info(list) |
|
402 | info = inspector.info(list) | |
404 | init_def = info['init_definition'] |
|
403 | init_def = info['init_definition'] | |
405 | assert init_def is not None |
|
404 | assert init_def is not None | |
406 |
|
405 | |||
407 |
|
406 | |||
408 | def test_render_signature_short(): |
|
407 | def test_render_signature_short(): | |
409 | def short_fun(a=1): pass |
|
408 | def short_fun(a=1): pass | |
410 | sig = oinspect._render_signature( |
|
409 | sig = oinspect._render_signature( | |
411 | signature(short_fun), |
|
410 | signature(short_fun), | |
412 | short_fun.__name__, |
|
411 | short_fun.__name__, | |
413 | ) |
|
412 | ) | |
414 | assert sig == "short_fun(a=1)" |
|
413 | assert sig == "short_fun(a=1)" | |
415 |
|
414 | |||
416 |
|
415 | |||
417 | def test_render_signature_long(): |
|
416 | def test_render_signature_long(): | |
418 | from typing import Optional |
|
417 | from typing import Optional | |
419 |
|
418 | |||
420 | def long_function( |
|
419 | def long_function( | |
421 | a_really_long_parameter: int, |
|
420 | a_really_long_parameter: int, | |
422 | and_another_long_one: bool = False, |
|
421 | and_another_long_one: bool = False, | |
423 | let_us_make_sure_this_is_looong: Optional[str] = None, |
|
422 | let_us_make_sure_this_is_looong: Optional[str] = None, | |
424 | ) -> bool: pass |
|
423 | ) -> bool: pass | |
425 |
|
424 | |||
426 | sig = oinspect._render_signature( |
|
425 | sig = oinspect._render_signature( | |
427 | signature(long_function), |
|
426 | signature(long_function), | |
428 | long_function.__name__, |
|
427 | long_function.__name__, | |
429 | ) |
|
428 | ) | |
430 | assert sig in [ |
|
429 | assert sig in [ | |
431 | # Python >=3.9 |
|
430 | # Python >=3.9 | |
432 | '''\ |
|
431 | '''\ | |
433 | long_function( |
|
432 | long_function( | |
434 | a_really_long_parameter: int, |
|
433 | a_really_long_parameter: int, | |
435 | and_another_long_one: bool = False, |
|
434 | and_another_long_one: bool = False, | |
436 | let_us_make_sure_this_is_looong: Optional[str] = None, |
|
435 | let_us_make_sure_this_is_looong: Optional[str] = None, | |
437 | ) -> bool\ |
|
436 | ) -> bool\ | |
438 | ''', |
|
437 | ''', | |
439 | # Python >=3.7 |
|
438 | # Python >=3.7 | |
440 | '''\ |
|
439 | '''\ | |
441 | long_function( |
|
440 | long_function( | |
442 | a_really_long_parameter: int, |
|
441 | a_really_long_parameter: int, | |
443 | and_another_long_one: bool = False, |
|
442 | and_another_long_one: bool = False, | |
444 | let_us_make_sure_this_is_looong: Union[str, NoneType] = None, |
|
443 | let_us_make_sure_this_is_looong: Union[str, NoneType] = None, | |
445 | ) -> bool\ |
|
444 | ) -> bool\ | |
446 | ''', # Python <=3.6 |
|
445 | ''', # Python <=3.6 | |
447 | '''\ |
|
446 | '''\ | |
448 | long_function( |
|
447 | long_function( | |
449 | a_really_long_parameter:int, |
|
448 | a_really_long_parameter:int, | |
450 | and_another_long_one:bool=False, |
|
449 | and_another_long_one:bool=False, | |
451 | let_us_make_sure_this_is_looong:Union[str, NoneType]=None, |
|
450 | let_us_make_sure_this_is_looong:Union[str, NoneType]=None, | |
452 | ) -> bool\ |
|
451 | ) -> bool\ | |
453 | ''', |
|
452 | ''', | |
454 | ] |
|
453 | ] |
@@ -1,599 +1,601 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """Tests for code execution (%run and related), which is particularly tricky. |
|
2 | """Tests for code execution (%run and related), which is particularly tricky. | |
3 |
|
3 | |||
4 | Because of how %run manages namespaces, and the fact that we are trying here to |
|
4 | Because of how %run manages namespaces, and the fact that we are trying here to | |
5 | verify subtle object deletion and reference counting issues, the %run tests |
|
5 | verify subtle object deletion and reference counting issues, the %run tests | |
6 | will be kept in this separate file. This makes it easier to aggregate in one |
|
6 | will be kept in this separate file. This makes it easier to aggregate in one | |
7 | place the tricks needed to handle it; most other magics are much easier to test |
|
7 | place the tricks needed to handle it; most other magics are much easier to test | |
8 | and we do so in a common test_magic file. |
|
8 | and we do so in a common test_magic file. | |
9 |
|
9 | |||
10 | Note that any test using `run -i` should make sure to do a `reset` afterwards, |
|
10 | Note that any test using `run -i` should make sure to do a `reset` afterwards, | |
11 | as otherwise it may influence later tests. |
|
11 | as otherwise it may influence later tests. | |
12 | """ |
|
12 | """ | |
13 |
|
13 | |||
14 | # Copyright (c) IPython Development Team. |
|
14 | # Copyright (c) IPython Development Team. | |
15 | # Distributed under the terms of the Modified BSD License. |
|
15 | # Distributed under the terms of the Modified BSD License. | |
16 |
|
16 | |||
17 |
|
17 | |||
18 |
|
18 | |||
19 | import functools |
|
19 | import functools | |
20 | import os |
|
20 | import os | |
21 | from os.path import join as pjoin |
|
21 | from os.path import join as pjoin | |
22 | import random |
|
22 | import random | |
23 | import string |
|
23 | import string | |
24 | import sys |
|
24 | import sys | |
25 | import textwrap |
|
25 | import textwrap | |
26 | import unittest |
|
26 | import unittest | |
27 | from unittest.mock import patch |
|
27 | from unittest.mock import patch | |
28 |
|
28 | |||
29 | import pytest |
|
29 | import pytest | |
30 |
|
30 | |||
31 | from IPython.testing import decorators as dec |
|
31 | from IPython.testing import decorators as dec | |
32 | from IPython.testing import tools as tt |
|
32 | from IPython.testing import tools as tt | |
33 | from IPython.utils.io import capture_output |
|
33 | from IPython.utils.io import capture_output | |
34 | from IPython.utils.tempdir import TemporaryDirectory |
|
34 | from IPython.utils.tempdir import TemporaryDirectory | |
35 | from IPython.core import debugger |
|
35 | from IPython.core import debugger | |
36 |
|
36 | |||
37 | def doctest_refbug(): |
|
37 | def doctest_refbug(): | |
38 | """Very nasty problem with references held by multiple runs of a script. |
|
38 | """Very nasty problem with references held by multiple runs of a script. | |
39 | See: https://github.com/ipython/ipython/issues/141 |
|
39 | See: https://github.com/ipython/ipython/issues/141 | |
40 |
|
40 | |||
41 | In [1]: _ip.clear_main_mod_cache() |
|
41 | In [1]: _ip.clear_main_mod_cache() | |
42 | # random |
|
42 | # random | |
43 |
|
43 | |||
44 | In [2]: %run refbug |
|
44 | In [2]: %run refbug | |
45 |
|
45 | |||
46 | In [3]: call_f() |
|
46 | In [3]: call_f() | |
47 | lowercased: hello |
|
47 | lowercased: hello | |
48 |
|
48 | |||
49 | In [4]: %run refbug |
|
49 | In [4]: %run refbug | |
50 |
|
50 | |||
51 | In [5]: call_f() |
|
51 | In [5]: call_f() | |
52 | lowercased: hello |
|
52 | lowercased: hello | |
53 | lowercased: hello |
|
53 | lowercased: hello | |
54 | """ |
|
54 | """ | |
55 |
|
55 | |||
56 |
|
56 | |||
57 | def doctest_run_builtins(): |
|
57 | def doctest_run_builtins(): | |
58 | r"""Check that %run doesn't damage __builtins__. |
|
58 | r"""Check that %run doesn't damage __builtins__. | |
59 |
|
59 | |||
60 | In [1]: import tempfile |
|
60 | In [1]: import tempfile | |
61 |
|
61 | |||
62 | In [2]: bid1 = id(__builtins__) |
|
62 | In [2]: bid1 = id(__builtins__) | |
63 |
|
63 | |||
64 | In [3]: fname = tempfile.mkstemp('.py')[1] |
|
64 | In [3]: fname = tempfile.mkstemp('.py')[1] | |
65 |
|
65 | |||
66 | In [3]: f = open(fname,'w') |
|
66 | In [3]: f = open(fname,'w') | |
67 |
|
67 | |||
68 | In [4]: dummy= f.write('pass\n') |
|
68 | In [4]: dummy= f.write('pass\n') | |
69 |
|
69 | |||
70 | In [5]: f.flush() |
|
70 | In [5]: f.flush() | |
71 |
|
71 | |||
72 | In [6]: t1 = type(__builtins__) |
|
72 | In [6]: t1 = type(__builtins__) | |
73 |
|
73 | |||
74 | In [7]: %run $fname |
|
74 | In [7]: %run $fname | |
75 |
|
75 | |||
76 | In [7]: f.close() |
|
76 | In [7]: f.close() | |
77 |
|
77 | |||
78 | In [8]: bid2 = id(__builtins__) |
|
78 | In [8]: bid2 = id(__builtins__) | |
79 |
|
79 | |||
80 | In [9]: t2 = type(__builtins__) |
|
80 | In [9]: t2 = type(__builtins__) | |
81 |
|
81 | |||
82 | In [10]: t1 == t2 |
|
82 | In [10]: t1 == t2 | |
83 | Out[10]: True |
|
83 | Out[10]: True | |
84 |
|
84 | |||
85 | In [10]: bid1 == bid2 |
|
85 | In [10]: bid1 == bid2 | |
86 | Out[10]: True |
|
86 | Out[10]: True | |
87 |
|
87 | |||
88 | In [12]: try: |
|
88 | In [12]: try: | |
89 | ....: os.unlink(fname) |
|
89 | ....: os.unlink(fname) | |
90 | ....: except: |
|
90 | ....: except: | |
91 | ....: pass |
|
91 | ....: pass | |
92 | ....: |
|
92 | ....: | |
93 | """ |
|
93 | """ | |
94 |
|
94 | |||
95 |
|
95 | |||
96 | def doctest_run_option_parser(): |
|
96 | def doctest_run_option_parser(): | |
97 | r"""Test option parser in %run. |
|
97 | r"""Test option parser in %run. | |
98 |
|
98 | |||
99 | In [1]: %run print_argv.py |
|
99 | In [1]: %run print_argv.py | |
100 | [] |
|
100 | [] | |
101 |
|
101 | |||
102 | In [2]: %run print_argv.py print*.py |
|
102 | In [2]: %run print_argv.py print*.py | |
103 | ['print_argv.py'] |
|
103 | ['print_argv.py'] | |
104 |
|
104 | |||
105 | In [3]: %run -G print_argv.py print*.py |
|
105 | In [3]: %run -G print_argv.py print*.py | |
106 | ['print*.py'] |
|
106 | ['print*.py'] | |
107 |
|
107 | |||
108 | """ |
|
108 | """ | |
109 |
|
109 | |||
110 |
|
110 | |||
111 | @dec.skip_win32 |
|
111 | @dec.skip_win32 | |
112 | def doctest_run_option_parser_for_posix(): |
|
112 | def doctest_run_option_parser_for_posix(): | |
113 | r"""Test option parser in %run (Linux/OSX specific). |
|
113 | r"""Test option parser in %run (Linux/OSX specific). | |
114 |
|
114 | |||
115 | You need double quote to escape glob in POSIX systems: |
|
115 | You need double quote to escape glob in POSIX systems: | |
116 |
|
116 | |||
117 | In [1]: %run print_argv.py print\\*.py |
|
117 | In [1]: %run print_argv.py print\\*.py | |
118 | ['print*.py'] |
|
118 | ['print*.py'] | |
119 |
|
119 | |||
120 | You can't use quote to escape glob in POSIX systems: |
|
120 | You can't use quote to escape glob in POSIX systems: | |
121 |
|
121 | |||
122 | In [2]: %run print_argv.py 'print*.py' |
|
122 | In [2]: %run print_argv.py 'print*.py' | |
123 | ['print_argv.py'] |
|
123 | ['print_argv.py'] | |
124 |
|
124 | |||
125 | """ |
|
125 | """ | |
126 |
|
126 | |||
127 |
|
127 | |||
128 | doctest_run_option_parser_for_posix.__skip_doctest__ = sys.platform == "win32" |
|
128 | doctest_run_option_parser_for_posix.__skip_doctest__ = sys.platform == "win32" | |
129 |
|
129 | |||
130 |
|
130 | |||
131 | @dec.skip_if_not_win32 |
|
131 | @dec.skip_if_not_win32 | |
132 | def doctest_run_option_parser_for_windows(): |
|
132 | def doctest_run_option_parser_for_windows(): | |
133 | r"""Test option parser in %run (Windows specific). |
|
133 | r"""Test option parser in %run (Windows specific). | |
134 |
|
134 | |||
135 | In Windows, you can't escape ``*` `by backslash: |
|
135 | In Windows, you can't escape ``*` `by backslash: | |
136 |
|
136 | |||
137 | In [1]: %run print_argv.py print\\*.py |
|
137 | In [1]: %run print_argv.py print\\*.py | |
138 | ['print\\\\*.py'] |
|
138 | ['print\\\\*.py'] | |
139 |
|
139 | |||
140 | You can use quote to escape glob: |
|
140 | You can use quote to escape glob: | |
141 |
|
141 | |||
142 | In [2]: %run print_argv.py 'print*.py' |
|
142 | In [2]: %run print_argv.py 'print*.py' | |
143 | ["'print*.py'"] |
|
143 | ["'print*.py'"] | |
144 |
|
144 | |||
145 | """ |
|
145 | """ | |
146 |
|
146 | |||
147 |
|
147 | |||
148 | doctest_run_option_parser_for_windows.__skip_doctest__ = sys.platform != "win32" |
|
148 | doctest_run_option_parser_for_windows.__skip_doctest__ = sys.platform != "win32" | |
149 |
|
149 | |||
150 |
|
150 | |||
151 | def doctest_reset_del(): |
|
151 | def doctest_reset_del(): | |
152 | """Test that resetting doesn't cause errors in __del__ methods. |
|
152 | """Test that resetting doesn't cause errors in __del__ methods. | |
153 |
|
153 | |||
154 | In [2]: class A(object): |
|
154 | In [2]: class A(object): | |
155 | ...: def __del__(self): |
|
155 | ...: def __del__(self): | |
156 | ...: print(str("Hi")) |
|
156 | ...: print(str("Hi")) | |
157 | ...: |
|
157 | ...: | |
158 |
|
158 | |||
159 | In [3]: a = A() |
|
159 | In [3]: a = A() | |
160 |
|
160 | |||
161 | In [4]: get_ipython().reset() |
|
161 | In [4]: get_ipython().reset() | |
162 | Hi |
|
162 | Hi | |
163 |
|
163 | |||
164 | In [5]: 1+1 |
|
164 | In [5]: 1+1 | |
165 | Out[5]: 2 |
|
165 | Out[5]: 2 | |
166 | """ |
|
166 | """ | |
167 |
|
167 | |||
168 | # For some tests, it will be handy to organize them in a class with a common |
|
168 | # For some tests, it will be handy to organize them in a class with a common | |
169 | # setup that makes a temp file |
|
169 | # setup that makes a temp file | |
170 |
|
170 | |||
171 | class TestMagicRunPass(tt.TempFileMixin): |
|
171 | class TestMagicRunPass(tt.TempFileMixin): | |
172 |
|
172 | |||
173 | def setUp(self): |
|
173 | def setUp(self): | |
174 | content = "a = [1,2,3]\nb = 1" |
|
174 | content = "a = [1,2,3]\nb = 1" | |
175 | self.mktmp(content) |
|
175 | self.mktmp(content) | |
176 |
|
176 | |||
177 | def run_tmpfile(self): |
|
177 | def run_tmpfile(self): | |
178 | _ip = get_ipython() |
|
178 | _ip = get_ipython() | |
179 | # This fails on Windows if self.tmpfile.name has spaces or "~" in it. |
|
179 | # This fails on Windows if self.tmpfile.name has spaces or "~" in it. | |
180 | # See below and ticket https://bugs.launchpad.net/bugs/366353 |
|
180 | # See below and ticket https://bugs.launchpad.net/bugs/366353 | |
181 | _ip.magic('run %s' % self.fname) |
|
181 | _ip.magic('run %s' % self.fname) | |
182 |
|
182 | |||
183 | def run_tmpfile_p(self): |
|
183 | def run_tmpfile_p(self): | |
184 | _ip = get_ipython() |
|
184 | _ip = get_ipython() | |
185 | # This fails on Windows if self.tmpfile.name has spaces or "~" in it. |
|
185 | # This fails on Windows if self.tmpfile.name has spaces or "~" in it. | |
186 | # See below and ticket https://bugs.launchpad.net/bugs/366353 |
|
186 | # See below and ticket https://bugs.launchpad.net/bugs/366353 | |
187 | _ip.magic('run -p %s' % self.fname) |
|
187 | _ip.magic('run -p %s' % self.fname) | |
188 |
|
188 | |||
189 | def test_builtins_id(self): |
|
189 | def test_builtins_id(self): | |
190 | """Check that %run doesn't damage __builtins__ """ |
|
190 | """Check that %run doesn't damage __builtins__ """ | |
191 | _ip = get_ipython() |
|
191 | _ip = get_ipython() | |
192 | # Test that the id of __builtins__ is not modified by %run |
|
192 | # Test that the id of __builtins__ is not modified by %run | |
193 | bid1 = id(_ip.user_ns['__builtins__']) |
|
193 | bid1 = id(_ip.user_ns['__builtins__']) | |
194 | self.run_tmpfile() |
|
194 | self.run_tmpfile() | |
195 | bid2 = id(_ip.user_ns['__builtins__']) |
|
195 | bid2 = id(_ip.user_ns['__builtins__']) | |
196 | assert bid1 == bid2 |
|
196 | assert bid1 == bid2 | |
197 |
|
197 | |||
198 | def test_builtins_type(self): |
|
198 | def test_builtins_type(self): | |
199 | """Check that the type of __builtins__ doesn't change with %run. |
|
199 | """Check that the type of __builtins__ doesn't change with %run. | |
200 |
|
200 | |||
201 | However, the above could pass if __builtins__ was already modified to |
|
201 | However, the above could pass if __builtins__ was already modified to | |
202 | be a dict (it should be a module) by a previous use of %run. So we |
|
202 | be a dict (it should be a module) by a previous use of %run. So we | |
203 | also check explicitly that it really is a module: |
|
203 | also check explicitly that it really is a module: | |
204 | """ |
|
204 | """ | |
205 | _ip = get_ipython() |
|
205 | _ip = get_ipython() | |
206 | self.run_tmpfile() |
|
206 | self.run_tmpfile() | |
207 | assert type(_ip.user_ns["__builtins__"]) == type(sys) |
|
207 | assert type(_ip.user_ns["__builtins__"]) == type(sys) | |
208 |
|
208 | |||
209 | def test_run_profile(self): |
|
209 | def test_run_profile(self): | |
210 | """Test that the option -p, which invokes the profiler, do not |
|
210 | """Test that the option -p, which invokes the profiler, do not | |
211 | crash by invoking execfile""" |
|
211 | crash by invoking execfile""" | |
212 | self.run_tmpfile_p() |
|
212 | self.run_tmpfile_p() | |
213 |
|
213 | |||
214 | def test_run_debug_twice(self): |
|
214 | def test_run_debug_twice(self): | |
215 | # https://github.com/ipython/ipython/issues/10028 |
|
215 | # https://github.com/ipython/ipython/issues/10028 | |
216 | _ip = get_ipython() |
|
216 | _ip = get_ipython() | |
217 | with tt.fake_input(['c']): |
|
217 | with tt.fake_input(['c']): | |
218 | _ip.magic('run -d %s' % self.fname) |
|
218 | _ip.magic('run -d %s' % self.fname) | |
219 | with tt.fake_input(['c']): |
|
219 | with tt.fake_input(['c']): | |
220 | _ip.magic('run -d %s' % self.fname) |
|
220 | _ip.magic('run -d %s' % self.fname) | |
221 |
|
221 | |||
222 | def test_run_debug_twice_with_breakpoint(self): |
|
222 | def test_run_debug_twice_with_breakpoint(self): | |
223 | """Make a valid python temp file.""" |
|
223 | """Make a valid python temp file.""" | |
224 | _ip = get_ipython() |
|
224 | _ip = get_ipython() | |
225 | with tt.fake_input(['b 2', 'c', 'c']): |
|
225 | with tt.fake_input(['b 2', 'c', 'c']): | |
226 | _ip.magic('run -d %s' % self.fname) |
|
226 | _ip.magic('run -d %s' % self.fname) | |
227 |
|
227 | |||
228 | with tt.fake_input(['c']): |
|
228 | with tt.fake_input(['c']): | |
229 | with tt.AssertNotPrints('KeyError'): |
|
229 | with tt.AssertNotPrints('KeyError'): | |
230 | _ip.magic('run -d %s' % self.fname) |
|
230 | _ip.magic('run -d %s' % self.fname) | |
231 |
|
231 | |||
232 |
|
232 | |||
233 | class TestMagicRunSimple(tt.TempFileMixin): |
|
233 | class TestMagicRunSimple(tt.TempFileMixin): | |
234 |
|
234 | |||
235 | def test_simpledef(self): |
|
235 | def test_simpledef(self): | |
236 | """Test that simple class definitions work.""" |
|
236 | """Test that simple class definitions work.""" | |
237 | src = ("class foo: pass\n" |
|
237 | src = ("class foo: pass\n" | |
238 | "def f(): return foo()") |
|
238 | "def f(): return foo()") | |
239 | self.mktmp(src) |
|
239 | self.mktmp(src) | |
240 | _ip.magic("run %s" % self.fname) |
|
240 | _ip.magic("run %s" % self.fname) | |
241 | _ip.run_cell("t = isinstance(f(), foo)") |
|
241 | _ip.run_cell("t = isinstance(f(), foo)") | |
242 | assert _ip.user_ns["t"] is True |
|
242 | assert _ip.user_ns["t"] is True | |
243 |
|
243 | |||
244 | def test_obj_del(self): |
|
244 | def test_obj_del(self): | |
245 | """Test that object's __del__ methods are called on exit.""" |
|
245 | """Test that object's __del__ methods are called on exit.""" | |
246 | src = ("class A(object):\n" |
|
246 | src = ("class A(object):\n" | |
247 | " def __del__(self):\n" |
|
247 | " def __del__(self):\n" | |
248 | " print('object A deleted')\n" |
|
248 | " print('object A deleted')\n" | |
249 | "a = A()\n") |
|
249 | "a = A()\n") | |
250 | self.mktmp(src) |
|
250 | self.mktmp(src) | |
251 | err = None |
|
251 | err = None | |
252 | tt.ipexec_validate(self.fname, 'object A deleted', err) |
|
252 | tt.ipexec_validate(self.fname, 'object A deleted', err) | |
253 |
|
253 | |||
254 | def test_aggressive_namespace_cleanup(self): |
|
254 | def test_aggressive_namespace_cleanup(self): | |
255 | """Test that namespace cleanup is not too aggressive GH-238 |
|
255 | """Test that namespace cleanup is not too aggressive GH-238 | |
256 |
|
256 | |||
257 | Returning from another run magic deletes the namespace""" |
|
257 | Returning from another run magic deletes the namespace""" | |
258 | # see ticket https://github.com/ipython/ipython/issues/238 |
|
258 | # see ticket https://github.com/ipython/ipython/issues/238 | |
259 |
|
259 | |||
260 | with tt.TempFileMixin() as empty: |
|
260 | with tt.TempFileMixin() as empty: | |
261 | empty.mktmp("") |
|
261 | empty.mktmp("") | |
262 | # On Windows, the filename will have \users in it, so we need to use the |
|
262 | # On Windows, the filename will have \users in it, so we need to use the | |
263 | # repr so that the \u becomes \\u. |
|
263 | # repr so that the \u becomes \\u. | |
264 | src = ( |
|
264 | src = ( | |
265 | "ip = get_ipython()\n" |
|
265 | "ip = get_ipython()\n" | |
266 | "for i in range(5):\n" |
|
266 | "for i in range(5):\n" | |
267 | " try:\n" |
|
267 | " try:\n" | |
268 | " ip.magic(%r)\n" |
|
268 | " ip.magic(%r)\n" | |
269 | " except NameError as e:\n" |
|
269 | " except NameError as e:\n" | |
270 | " print(i)\n" |
|
270 | " print(i)\n" | |
271 | " break\n" % ("run " + empty.fname) |
|
271 | " break\n" % ("run " + empty.fname) | |
272 | ) |
|
272 | ) | |
273 | self.mktmp(src) |
|
273 | self.mktmp(src) | |
274 | _ip.magic("run %s" % self.fname) |
|
274 | _ip.magic("run %s" % self.fname) | |
275 | _ip.run_cell("ip == get_ipython()") |
|
275 | _ip.run_cell("ip == get_ipython()") | |
276 | assert _ip.user_ns["i"] == 4 |
|
276 | assert _ip.user_ns["i"] == 4 | |
277 |
|
277 | |||
278 | def test_run_second(self): |
|
278 | def test_run_second(self): | |
279 | """Test that running a second file doesn't clobber the first, gh-3547""" |
|
279 | """Test that running a second file doesn't clobber the first, gh-3547""" | |
280 | self.mktmp("avar = 1\n" "def afunc():\n" " return avar\n") |
|
280 | self.mktmp("avar = 1\n" "def afunc():\n" " return avar\n") | |
281 |
|
281 | |||
282 | with tt.TempFileMixin() as empty: |
|
282 | with tt.TempFileMixin() as empty: | |
283 | empty.mktmp("") |
|
283 | empty.mktmp("") | |
284 |
|
284 | |||
285 | _ip.magic("run %s" % self.fname) |
|
285 | _ip.magic("run %s" % self.fname) | |
286 | _ip.magic("run %s" % empty.fname) |
|
286 | _ip.magic("run %s" % empty.fname) | |
287 | assert _ip.user_ns["afunc"]() == 1 |
|
287 | assert _ip.user_ns["afunc"]() == 1 | |
288 |
|
288 | |||
289 | @dec.skip_win32 |
|
289 | @dec.skip_win32 | |
290 | def test_tclass(self): |
|
290 | def test_tclass(self): | |
291 | mydir = os.path.dirname(__file__) |
|
291 | mydir = os.path.dirname(__file__) | |
292 | tc = os.path.join(mydir, 'tclass') |
|
292 | tc = os.path.join(mydir, 'tclass') | |
293 | src = ("%%run '%s' C-first\n" |
|
293 | src = ("%%run '%s' C-first\n" | |
294 | "%%run '%s' C-second\n" |
|
294 | "%%run '%s' C-second\n" | |
295 | "%%run '%s' C-third\n") % (tc, tc, tc) |
|
295 | "%%run '%s' C-third\n") % (tc, tc, tc) | |
296 | self.mktmp(src, '.ipy') |
|
296 | self.mktmp(src, '.ipy') | |
297 | out = """\ |
|
297 | out = """\ | |
298 | ARGV 1-: ['C-first'] |
|
298 | ARGV 1-: ['C-first'] | |
299 | ARGV 1-: ['C-second'] |
|
299 | ARGV 1-: ['C-second'] | |
300 | tclass.py: deleting object: C-first |
|
300 | tclass.py: deleting object: C-first | |
301 | ARGV 1-: ['C-third'] |
|
301 | ARGV 1-: ['C-third'] | |
302 | tclass.py: deleting object: C-second |
|
302 | tclass.py: deleting object: C-second | |
303 | tclass.py: deleting object: C-third |
|
303 | tclass.py: deleting object: C-third | |
304 | """ |
|
304 | """ | |
305 | err = None |
|
305 | err = None | |
306 | tt.ipexec_validate(self.fname, out, err) |
|
306 | tt.ipexec_validate(self.fname, out, err) | |
307 |
|
307 | |||
308 | def test_run_i_after_reset(self): |
|
308 | def test_run_i_after_reset(self): | |
309 | """Check that %run -i still works after %reset (gh-693)""" |
|
309 | """Check that %run -i still works after %reset (gh-693)""" | |
310 | src = "yy = zz\n" |
|
310 | src = "yy = zz\n" | |
311 | self.mktmp(src) |
|
311 | self.mktmp(src) | |
312 | _ip.run_cell("zz = 23") |
|
312 | _ip.run_cell("zz = 23") | |
313 | try: |
|
313 | try: | |
314 | _ip.magic("run -i %s" % self.fname) |
|
314 | _ip.magic("run -i %s" % self.fname) | |
315 | assert _ip.user_ns["yy"] == 23 |
|
315 | assert _ip.user_ns["yy"] == 23 | |
316 | finally: |
|
316 | finally: | |
317 | _ip.magic('reset -f') |
|
317 | _ip.magic('reset -f') | |
318 |
|
318 | |||
319 | _ip.run_cell("zz = 23") |
|
319 | _ip.run_cell("zz = 23") | |
320 | try: |
|
320 | try: | |
321 | _ip.magic("run -i %s" % self.fname) |
|
321 | _ip.magic("run -i %s" % self.fname) | |
322 | assert _ip.user_ns["yy"] == 23 |
|
322 | assert _ip.user_ns["yy"] == 23 | |
323 | finally: |
|
323 | finally: | |
324 | _ip.magic('reset -f') |
|
324 | _ip.magic('reset -f') | |
325 |
|
325 | |||
326 | def test_unicode(self): |
|
326 | def test_unicode(self): | |
327 | """Check that files in odd encodings are accepted.""" |
|
327 | """Check that files in odd encodings are accepted.""" | |
328 | mydir = os.path.dirname(__file__) |
|
328 | mydir = os.path.dirname(__file__) | |
329 | na = os.path.join(mydir, 'nonascii.py') |
|
329 | na = os.path.join(mydir, 'nonascii.py') | |
330 | _ip.magic('run "%s"' % na) |
|
330 | _ip.magic('run "%s"' % na) | |
331 | assert _ip.user_ns["u"] == "Ўт№Ф" |
|
331 | assert _ip.user_ns["u"] == "Ўт№Ф" | |
332 |
|
332 | |||
333 | def test_run_py_file_attribute(self): |
|
333 | def test_run_py_file_attribute(self): | |
334 | """Test handling of `__file__` attribute in `%run <file>.py`.""" |
|
334 | """Test handling of `__file__` attribute in `%run <file>.py`.""" | |
335 | src = "t = __file__\n" |
|
335 | src = "t = __file__\n" | |
336 | self.mktmp(src) |
|
336 | self.mktmp(src) | |
337 | _missing = object() |
|
337 | _missing = object() | |
338 | file1 = _ip.user_ns.get('__file__', _missing) |
|
338 | file1 = _ip.user_ns.get('__file__', _missing) | |
339 | _ip.magic('run %s' % self.fname) |
|
339 | _ip.magic('run %s' % self.fname) | |
340 | file2 = _ip.user_ns.get('__file__', _missing) |
|
340 | file2 = _ip.user_ns.get('__file__', _missing) | |
341 |
|
341 | |||
342 | # Check that __file__ was equal to the filename in the script's |
|
342 | # Check that __file__ was equal to the filename in the script's | |
343 | # namespace. |
|
343 | # namespace. | |
344 | assert _ip.user_ns["t"] == self.fname |
|
344 | assert _ip.user_ns["t"] == self.fname | |
345 |
|
345 | |||
346 | # Check that __file__ was not leaked back into user_ns. |
|
346 | # Check that __file__ was not leaked back into user_ns. | |
347 | assert file1 == file2 |
|
347 | assert file1 == file2 | |
348 |
|
348 | |||
349 | def test_run_ipy_file_attribute(self): |
|
349 | def test_run_ipy_file_attribute(self): | |
350 | """Test handling of `__file__` attribute in `%run <file.ipy>`.""" |
|
350 | """Test handling of `__file__` attribute in `%run <file.ipy>`.""" | |
351 | src = "t = __file__\n" |
|
351 | src = "t = __file__\n" | |
352 | self.mktmp(src, ext='.ipy') |
|
352 | self.mktmp(src, ext='.ipy') | |
353 | _missing = object() |
|
353 | _missing = object() | |
354 | file1 = _ip.user_ns.get('__file__', _missing) |
|
354 | file1 = _ip.user_ns.get('__file__', _missing) | |
355 | _ip.magic('run %s' % self.fname) |
|
355 | _ip.magic('run %s' % self.fname) | |
356 | file2 = _ip.user_ns.get('__file__', _missing) |
|
356 | file2 = _ip.user_ns.get('__file__', _missing) | |
357 |
|
357 | |||
358 | # Check that __file__ was equal to the filename in the script's |
|
358 | # Check that __file__ was equal to the filename in the script's | |
359 | # namespace. |
|
359 | # namespace. | |
360 | assert _ip.user_ns["t"] == self.fname |
|
360 | assert _ip.user_ns["t"] == self.fname | |
361 |
|
361 | |||
362 | # Check that __file__ was not leaked back into user_ns. |
|
362 | # Check that __file__ was not leaked back into user_ns. | |
363 | assert file1 == file2 |
|
363 | assert file1 == file2 | |
364 |
|
364 | |||
365 | def test_run_formatting(self): |
|
365 | def test_run_formatting(self): | |
366 | """ Test that %run -t -N<N> does not raise a TypeError for N > 1.""" |
|
366 | """ Test that %run -t -N<N> does not raise a TypeError for N > 1.""" | |
367 | src = "pass" |
|
367 | src = "pass" | |
368 | self.mktmp(src) |
|
368 | self.mktmp(src) | |
369 | _ip.magic('run -t -N 1 %s' % self.fname) |
|
369 | _ip.magic('run -t -N 1 %s' % self.fname) | |
370 | _ip.magic('run -t -N 10 %s' % self.fname) |
|
370 | _ip.magic('run -t -N 10 %s' % self.fname) | |
371 |
|
371 | |||
372 | def test_ignore_sys_exit(self): |
|
372 | def test_ignore_sys_exit(self): | |
373 | """Test the -e option to ignore sys.exit()""" |
|
373 | """Test the -e option to ignore sys.exit()""" | |
374 | src = "import sys; sys.exit(1)" |
|
374 | src = "import sys; sys.exit(1)" | |
375 | self.mktmp(src) |
|
375 | self.mktmp(src) | |
376 | with tt.AssertPrints('SystemExit'): |
|
376 | with tt.AssertPrints('SystemExit'): | |
377 | _ip.magic('run %s' % self.fname) |
|
377 | _ip.magic('run %s' % self.fname) | |
378 |
|
378 | |||
379 | with tt.AssertNotPrints('SystemExit'): |
|
379 | with tt.AssertNotPrints('SystemExit'): | |
380 | _ip.magic('run -e %s' % self.fname) |
|
380 | _ip.magic('run -e %s' % self.fname) | |
381 |
|
381 | |||
382 | def test_run_nb(self): |
|
382 | def test_run_nb(self): | |
383 | """Test %run notebook.ipynb""" |
|
383 | """Test %run notebook.ipynb""" | |
|
384 | pytest.importorskip("nbformat") | |||
384 | from nbformat import v4, writes |
|
385 | from nbformat import v4, writes | |
385 | nb = v4.new_notebook( |
|
386 | nb = v4.new_notebook( | |
386 | cells=[ |
|
387 | cells=[ | |
387 | v4.new_markdown_cell("The Ultimate Question of Everything"), |
|
388 | v4.new_markdown_cell("The Ultimate Question of Everything"), | |
388 | v4.new_code_cell("answer=42") |
|
389 | v4.new_code_cell("answer=42") | |
389 | ] |
|
390 | ] | |
390 | ) |
|
391 | ) | |
391 | src = writes(nb, version=4) |
|
392 | src = writes(nb, version=4) | |
392 | self.mktmp(src, ext='.ipynb') |
|
393 | self.mktmp(src, ext='.ipynb') | |
393 |
|
394 | |||
394 | _ip.magic("run %s" % self.fname) |
|
395 | _ip.magic("run %s" % self.fname) | |
395 |
|
396 | |||
396 | assert _ip.user_ns["answer"] == 42 |
|
397 | assert _ip.user_ns["answer"] == 42 | |
397 |
|
398 | |||
398 | def test_run_nb_error(self): |
|
399 | def test_run_nb_error(self): | |
399 | """Test %run notebook.ipynb error""" |
|
400 | """Test %run notebook.ipynb error""" | |
|
401 | pytest.importorskip("nbformat") | |||
400 | from nbformat import v4, writes |
|
402 | from nbformat import v4, writes | |
401 | # %run when a file name isn't provided |
|
403 | # %run when a file name isn't provided | |
402 | pytest.raises(Exception, _ip.magic, "run") |
|
404 | pytest.raises(Exception, _ip.magic, "run") | |
403 |
|
405 | |||
404 | # %run when a file doesn't exist |
|
406 | # %run when a file doesn't exist | |
405 | pytest.raises(Exception, _ip.magic, "run foobar.ipynb") |
|
407 | pytest.raises(Exception, _ip.magic, "run foobar.ipynb") | |
406 |
|
408 | |||
407 | # %run on a notebook with an error |
|
409 | # %run on a notebook with an error | |
408 | nb = v4.new_notebook( |
|
410 | nb = v4.new_notebook( | |
409 | cells=[ |
|
411 | cells=[ | |
410 | v4.new_code_cell("0/0") |
|
412 | v4.new_code_cell("0/0") | |
411 | ] |
|
413 | ] | |
412 | ) |
|
414 | ) | |
413 | src = writes(nb, version=4) |
|
415 | src = writes(nb, version=4) | |
414 | self.mktmp(src, ext='.ipynb') |
|
416 | self.mktmp(src, ext='.ipynb') | |
415 | pytest.raises(Exception, _ip.magic, "run %s" % self.fname) |
|
417 | pytest.raises(Exception, _ip.magic, "run %s" % self.fname) | |
416 |
|
418 | |||
417 | def test_file_options(self): |
|
419 | def test_file_options(self): | |
418 | src = ('import sys\n' |
|
420 | src = ('import sys\n' | |
419 | 'a = " ".join(sys.argv[1:])\n') |
|
421 | 'a = " ".join(sys.argv[1:])\n') | |
420 | self.mktmp(src) |
|
422 | self.mktmp(src) | |
421 | test_opts = "-x 3 --verbose" |
|
423 | test_opts = "-x 3 --verbose" | |
422 | _ip.run_line_magic("run", "{0} {1}".format(self.fname, test_opts)) |
|
424 | _ip.run_line_magic("run", "{0} {1}".format(self.fname, test_opts)) | |
423 | assert _ip.user_ns["a"] == test_opts |
|
425 | assert _ip.user_ns["a"] == test_opts | |
424 |
|
426 | |||
425 |
|
427 | |||
426 | class TestMagicRunWithPackage(unittest.TestCase): |
|
428 | class TestMagicRunWithPackage(unittest.TestCase): | |
427 |
|
429 | |||
428 | def writefile(self, name, content): |
|
430 | def writefile(self, name, content): | |
429 | path = os.path.join(self.tempdir.name, name) |
|
431 | path = os.path.join(self.tempdir.name, name) | |
430 | d = os.path.dirname(path) |
|
432 | d = os.path.dirname(path) | |
431 | if not os.path.isdir(d): |
|
433 | if not os.path.isdir(d): | |
432 | os.makedirs(d) |
|
434 | os.makedirs(d) | |
433 | with open(path, 'w') as f: |
|
435 | with open(path, 'w') as f: | |
434 | f.write(textwrap.dedent(content)) |
|
436 | f.write(textwrap.dedent(content)) | |
435 |
|
437 | |||
436 | def setUp(self): |
|
438 | def setUp(self): | |
437 | self.package = package = 'tmp{0}'.format(''.join([random.choice(string.ascii_letters) for i in range(10)])) |
|
439 | self.package = package = 'tmp{0}'.format(''.join([random.choice(string.ascii_letters) for i in range(10)])) | |
438 | """Temporary (probably) valid python package name.""" |
|
440 | """Temporary (probably) valid python package name.""" | |
439 |
|
441 | |||
440 | self.value = int(random.random() * 10000) |
|
442 | self.value = int(random.random() * 10000) | |
441 |
|
443 | |||
442 | self.tempdir = TemporaryDirectory() |
|
444 | self.tempdir = TemporaryDirectory() | |
443 | self.__orig_cwd = os.getcwd() |
|
445 | self.__orig_cwd = os.getcwd() | |
444 | sys.path.insert(0, self.tempdir.name) |
|
446 | sys.path.insert(0, self.tempdir.name) | |
445 |
|
447 | |||
446 | self.writefile(os.path.join(package, '__init__.py'), '') |
|
448 | self.writefile(os.path.join(package, '__init__.py'), '') | |
447 | self.writefile(os.path.join(package, 'sub.py'), """ |
|
449 | self.writefile(os.path.join(package, 'sub.py'), """ | |
448 | x = {0!r} |
|
450 | x = {0!r} | |
449 | """.format(self.value)) |
|
451 | """.format(self.value)) | |
450 | self.writefile(os.path.join(package, 'relative.py'), """ |
|
452 | self.writefile(os.path.join(package, 'relative.py'), """ | |
451 | from .sub import x |
|
453 | from .sub import x | |
452 | """) |
|
454 | """) | |
453 | self.writefile(os.path.join(package, 'absolute.py'), """ |
|
455 | self.writefile(os.path.join(package, 'absolute.py'), """ | |
454 | from {0}.sub import x |
|
456 | from {0}.sub import x | |
455 | """.format(package)) |
|
457 | """.format(package)) | |
456 | self.writefile(os.path.join(package, 'args.py'), """ |
|
458 | self.writefile(os.path.join(package, 'args.py'), """ | |
457 | import sys |
|
459 | import sys | |
458 | a = " ".join(sys.argv[1:]) |
|
460 | a = " ".join(sys.argv[1:]) | |
459 | """.format(package)) |
|
461 | """.format(package)) | |
460 |
|
462 | |||
461 | def tearDown(self): |
|
463 | def tearDown(self): | |
462 | os.chdir(self.__orig_cwd) |
|
464 | os.chdir(self.__orig_cwd) | |
463 | sys.path[:] = [p for p in sys.path if p != self.tempdir.name] |
|
465 | sys.path[:] = [p for p in sys.path if p != self.tempdir.name] | |
464 | self.tempdir.cleanup() |
|
466 | self.tempdir.cleanup() | |
465 |
|
467 | |||
466 | def check_run_submodule(self, submodule, opts=''): |
|
468 | def check_run_submodule(self, submodule, opts=''): | |
467 | _ip.user_ns.pop('x', None) |
|
469 | _ip.user_ns.pop('x', None) | |
468 | _ip.magic('run {2} -m {0}.{1}'.format(self.package, submodule, opts)) |
|
470 | _ip.magic('run {2} -m {0}.{1}'.format(self.package, submodule, opts)) | |
469 | self.assertEqual(_ip.user_ns['x'], self.value, |
|
471 | self.assertEqual(_ip.user_ns['x'], self.value, | |
470 | 'Variable `x` is not loaded from module `{0}`.' |
|
472 | 'Variable `x` is not loaded from module `{0}`.' | |
471 | .format(submodule)) |
|
473 | .format(submodule)) | |
472 |
|
474 | |||
473 | def test_run_submodule_with_absolute_import(self): |
|
475 | def test_run_submodule_with_absolute_import(self): | |
474 | self.check_run_submodule('absolute') |
|
476 | self.check_run_submodule('absolute') | |
475 |
|
477 | |||
476 | def test_run_submodule_with_relative_import(self): |
|
478 | def test_run_submodule_with_relative_import(self): | |
477 | """Run submodule that has a relative import statement (#2727).""" |
|
479 | """Run submodule that has a relative import statement (#2727).""" | |
478 | self.check_run_submodule('relative') |
|
480 | self.check_run_submodule('relative') | |
479 |
|
481 | |||
480 | def test_prun_submodule_with_absolute_import(self): |
|
482 | def test_prun_submodule_with_absolute_import(self): | |
481 | self.check_run_submodule('absolute', '-p') |
|
483 | self.check_run_submodule('absolute', '-p') | |
482 |
|
484 | |||
483 | def test_prun_submodule_with_relative_import(self): |
|
485 | def test_prun_submodule_with_relative_import(self): | |
484 | self.check_run_submodule('relative', '-p') |
|
486 | self.check_run_submodule('relative', '-p') | |
485 |
|
487 | |||
486 | def with_fake_debugger(func): |
|
488 | def with_fake_debugger(func): | |
487 | @functools.wraps(func) |
|
489 | @functools.wraps(func) | |
488 | def wrapper(*args, **kwds): |
|
490 | def wrapper(*args, **kwds): | |
489 | with patch.object(debugger.Pdb, 'run', staticmethod(eval)): |
|
491 | with patch.object(debugger.Pdb, 'run', staticmethod(eval)): | |
490 | return func(*args, **kwds) |
|
492 | return func(*args, **kwds) | |
491 | return wrapper |
|
493 | return wrapper | |
492 |
|
494 | |||
493 | @with_fake_debugger |
|
495 | @with_fake_debugger | |
494 | def test_debug_run_submodule_with_absolute_import(self): |
|
496 | def test_debug_run_submodule_with_absolute_import(self): | |
495 | self.check_run_submodule('absolute', '-d') |
|
497 | self.check_run_submodule('absolute', '-d') | |
496 |
|
498 | |||
497 | @with_fake_debugger |
|
499 | @with_fake_debugger | |
498 | def test_debug_run_submodule_with_relative_import(self): |
|
500 | def test_debug_run_submodule_with_relative_import(self): | |
499 | self.check_run_submodule('relative', '-d') |
|
501 | self.check_run_submodule('relative', '-d') | |
500 |
|
502 | |||
501 | def test_module_options(self): |
|
503 | def test_module_options(self): | |
502 | _ip.user_ns.pop("a", None) |
|
504 | _ip.user_ns.pop("a", None) | |
503 | test_opts = "-x abc -m test" |
|
505 | test_opts = "-x abc -m test" | |
504 | _ip.run_line_magic("run", "-m {0}.args {1}".format(self.package, test_opts)) |
|
506 | _ip.run_line_magic("run", "-m {0}.args {1}".format(self.package, test_opts)) | |
505 | assert _ip.user_ns["a"] == test_opts |
|
507 | assert _ip.user_ns["a"] == test_opts | |
506 |
|
508 | |||
507 | def test_module_options_with_separator(self): |
|
509 | def test_module_options_with_separator(self): | |
508 | _ip.user_ns.pop("a", None) |
|
510 | _ip.user_ns.pop("a", None) | |
509 | test_opts = "-x abc -m test" |
|
511 | test_opts = "-x abc -m test" | |
510 | _ip.run_line_magic("run", "-m {0}.args -- {1}".format(self.package, test_opts)) |
|
512 | _ip.run_line_magic("run", "-m {0}.args -- {1}".format(self.package, test_opts)) | |
511 | assert _ip.user_ns["a"] == test_opts |
|
513 | assert _ip.user_ns["a"] == test_opts | |
512 |
|
514 | |||
513 |
|
515 | |||
514 | def test_run__name__(): |
|
516 | def test_run__name__(): | |
515 | with TemporaryDirectory() as td: |
|
517 | with TemporaryDirectory() as td: | |
516 | path = pjoin(td, 'foo.py') |
|
518 | path = pjoin(td, 'foo.py') | |
517 | with open(path, 'w') as f: |
|
519 | with open(path, 'w') as f: | |
518 | f.write("q = __name__") |
|
520 | f.write("q = __name__") | |
519 |
|
521 | |||
520 | _ip.user_ns.pop("q", None) |
|
522 | _ip.user_ns.pop("q", None) | |
521 | _ip.magic("run {}".format(path)) |
|
523 | _ip.magic("run {}".format(path)) | |
522 | assert _ip.user_ns.pop("q") == "__main__" |
|
524 | assert _ip.user_ns.pop("q") == "__main__" | |
523 |
|
525 | |||
524 | _ip.magic("run -n {}".format(path)) |
|
526 | _ip.magic("run -n {}".format(path)) | |
525 | assert _ip.user_ns.pop("q") == "foo" |
|
527 | assert _ip.user_ns.pop("q") == "foo" | |
526 |
|
528 | |||
527 | try: |
|
529 | try: | |
528 | _ip.magic("run -i -n {}".format(path)) |
|
530 | _ip.magic("run -i -n {}".format(path)) | |
529 | assert _ip.user_ns.pop("q") == "foo" |
|
531 | assert _ip.user_ns.pop("q") == "foo" | |
530 | finally: |
|
532 | finally: | |
531 | _ip.magic('reset -f') |
|
533 | _ip.magic('reset -f') | |
532 |
|
534 | |||
533 |
|
535 | |||
534 | def test_run_tb(): |
|
536 | def test_run_tb(): | |
535 | """Test traceback offset in %run""" |
|
537 | """Test traceback offset in %run""" | |
536 | with TemporaryDirectory() as td: |
|
538 | with TemporaryDirectory() as td: | |
537 | path = pjoin(td, 'foo.py') |
|
539 | path = pjoin(td, 'foo.py') | |
538 | with open(path, 'w') as f: |
|
540 | with open(path, 'w') as f: | |
539 | f.write('\n'.join([ |
|
541 | f.write('\n'.join([ | |
540 | "def foo():", |
|
542 | "def foo():", | |
541 | " return bar()", |
|
543 | " return bar()", | |
542 | "def bar():", |
|
544 | "def bar():", | |
543 | " raise RuntimeError('hello!')", |
|
545 | " raise RuntimeError('hello!')", | |
544 | "foo()", |
|
546 | "foo()", | |
545 | ])) |
|
547 | ])) | |
546 | with capture_output() as io: |
|
548 | with capture_output() as io: | |
547 | _ip.magic('run {}'.format(path)) |
|
549 | _ip.magic('run {}'.format(path)) | |
548 | out = io.stdout |
|
550 | out = io.stdout | |
549 | assert "execfile" not in out |
|
551 | assert "execfile" not in out | |
550 | assert "RuntimeError" in out |
|
552 | assert "RuntimeError" in out | |
551 | assert out.count("---->") == 3 |
|
553 | assert out.count("---->") == 3 | |
552 | del ip.user_ns['bar'] |
|
554 | del ip.user_ns['bar'] | |
553 | del ip.user_ns['foo'] |
|
555 | del ip.user_ns['foo'] | |
554 |
|
556 | |||
555 |
|
557 | |||
556 | def test_multiprocessing_run(): |
|
558 | def test_multiprocessing_run(): | |
557 | """Set we can run mutiprocesgin without messing up up main namespace |
|
559 | """Set we can run mutiprocesgin without messing up up main namespace | |
558 |
|
560 | |||
559 | Note that import `nose.tools as nt` mdify the value s |
|
561 | Note that import `nose.tools as nt` mdify the value s | |
560 | sys.module['__mp_main__'] so we need to temporarily set it to None to test |
|
562 | sys.module['__mp_main__'] so we need to temporarily set it to None to test | |
561 | the issue. |
|
563 | the issue. | |
562 | """ |
|
564 | """ | |
563 | with TemporaryDirectory() as td: |
|
565 | with TemporaryDirectory() as td: | |
564 | mpm = sys.modules.get('__mp_main__') |
|
566 | mpm = sys.modules.get('__mp_main__') | |
565 | sys.modules['__mp_main__'] = None |
|
567 | sys.modules['__mp_main__'] = None | |
566 | try: |
|
568 | try: | |
567 | path = pjoin(td, 'test.py') |
|
569 | path = pjoin(td, 'test.py') | |
568 | with open(path, 'w') as f: |
|
570 | with open(path, 'w') as f: | |
569 | f.write("import multiprocessing\nprint('hoy')") |
|
571 | f.write("import multiprocessing\nprint('hoy')") | |
570 | with capture_output() as io: |
|
572 | with capture_output() as io: | |
571 | _ip.run_line_magic('run', path) |
|
573 | _ip.run_line_magic('run', path) | |
572 | _ip.run_cell("i_m_undefined") |
|
574 | _ip.run_cell("i_m_undefined") | |
573 | out = io.stdout |
|
575 | out = io.stdout | |
574 | assert "hoy" in out |
|
576 | assert "hoy" in out | |
575 | assert "AttributeError" not in out |
|
577 | assert "AttributeError" not in out | |
576 | assert "NameError" in out |
|
578 | assert "NameError" in out | |
577 | assert out.count("---->") == 1 |
|
579 | assert out.count("---->") == 1 | |
578 | except: |
|
580 | except: | |
579 | raise |
|
581 | raise | |
580 | finally: |
|
582 | finally: | |
581 | sys.modules['__mp_main__'] = mpm |
|
583 | sys.modules['__mp_main__'] = mpm | |
582 |
|
584 | |||
583 |
|
585 | |||
584 | def test_script_tb(): |
|
586 | def test_script_tb(): | |
585 | """Test traceback offset in `ipython script.py`""" |
|
587 | """Test traceback offset in `ipython script.py`""" | |
586 | with TemporaryDirectory() as td: |
|
588 | with TemporaryDirectory() as td: | |
587 | path = pjoin(td, 'foo.py') |
|
589 | path = pjoin(td, 'foo.py') | |
588 | with open(path, 'w') as f: |
|
590 | with open(path, 'w') as f: | |
589 | f.write('\n'.join([ |
|
591 | f.write('\n'.join([ | |
590 | "def foo():", |
|
592 | "def foo():", | |
591 | " return bar()", |
|
593 | " return bar()", | |
592 | "def bar():", |
|
594 | "def bar():", | |
593 | " raise RuntimeError('hello!')", |
|
595 | " raise RuntimeError('hello!')", | |
594 | "foo()", |
|
596 | "foo()", | |
595 | ])) |
|
597 | ])) | |
596 | out, err = tt.ipexec(path) |
|
598 | out, err = tt.ipexec(path) | |
597 | assert "execfile" not in out |
|
599 | assert "execfile" not in out | |
598 | assert "RuntimeError" in out |
|
600 | assert "RuntimeError" in out | |
599 | assert out.count("---->") == 3 |
|
601 | assert out.count("---->") == 3 |
@@ -1,674 +1,677 b'' | |||||
1 | """Various display related classes. |
|
1 | """Various display related classes. | |
2 |
|
2 | |||
3 | Authors : MinRK, gregcaporaso, dannystaple |
|
3 | Authors : MinRK, gregcaporaso, dannystaple | |
4 | """ |
|
4 | """ | |
5 | from html import escape as html_escape |
|
5 | from html import escape as html_escape | |
6 | from os.path import exists, isfile, splitext, abspath, join, isdir |
|
6 | from os.path import exists, isfile, splitext, abspath, join, isdir | |
7 | from os import walk, sep, fsdecode |
|
7 | from os import walk, sep, fsdecode | |
8 |
|
8 | |||
9 | from IPython.core.display import DisplayObject, TextDisplayObject |
|
9 | from IPython.core.display import DisplayObject, TextDisplayObject | |
10 |
|
10 | |||
11 | from typing import Tuple, Iterable |
|
11 | from typing import Tuple, Iterable | |
12 |
|
12 | |||
13 | __all__ = ['Audio', 'IFrame', 'YouTubeVideo', 'VimeoVideo', 'ScribdDocument', |
|
13 | __all__ = ['Audio', 'IFrame', 'YouTubeVideo', 'VimeoVideo', 'ScribdDocument', | |
14 | 'FileLink', 'FileLinks', 'Code'] |
|
14 | 'FileLink', 'FileLinks', 'Code'] | |
15 |
|
15 | |||
16 |
|
16 | |||
17 | class Audio(DisplayObject): |
|
17 | class Audio(DisplayObject): | |
18 | """Create an audio object. |
|
18 | """Create an audio object. | |
19 |
|
19 | |||
20 | When this object is returned by an input cell or passed to the |
|
20 | When this object is returned by an input cell or passed to the | |
21 | display function, it will result in Audio controls being displayed |
|
21 | display function, it will result in Audio controls being displayed | |
22 | in the frontend (only works in the notebook). |
|
22 | in the frontend (only works in the notebook). | |
23 |
|
23 | |||
24 | Parameters |
|
24 | Parameters | |
25 | ---------- |
|
25 | ---------- | |
26 | data : numpy array, list, unicode, str or bytes |
|
26 | data : numpy array, list, unicode, str or bytes | |
27 | Can be one of |
|
27 | Can be one of | |
28 |
|
28 | |||
29 | * Numpy 1d array containing the desired waveform (mono) |
|
29 | * Numpy 1d array containing the desired waveform (mono) | |
30 | * Numpy 2d array containing waveforms for each channel. |
|
30 | * Numpy 2d array containing waveforms for each channel. | |
31 | Shape=(NCHAN, NSAMPLES). For the standard channel order, see |
|
31 | Shape=(NCHAN, NSAMPLES). For the standard channel order, see | |
32 | http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx |
|
32 | http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx | |
33 | * List of float or integer representing the waveform (mono) |
|
33 | * List of float or integer representing the waveform (mono) | |
34 | * String containing the filename |
|
34 | * String containing the filename | |
35 | * Bytestring containing raw PCM data or |
|
35 | * Bytestring containing raw PCM data or | |
36 | * URL pointing to a file on the web. |
|
36 | * URL pointing to a file on the web. | |
37 |
|
37 | |||
38 | If the array option is used, the waveform will be normalized. |
|
38 | If the array option is used, the waveform will be normalized. | |
39 |
|
39 | |||
40 | If a filename or url is used, the format support will be browser |
|
40 | If a filename or url is used, the format support will be browser | |
41 | dependent. |
|
41 | dependent. | |
42 | url : unicode |
|
42 | url : unicode | |
43 | A URL to download the data from. |
|
43 | A URL to download the data from. | |
44 | filename : unicode |
|
44 | filename : unicode | |
45 | Path to a local file to load the data from. |
|
45 | Path to a local file to load the data from. | |
46 | embed : boolean |
|
46 | embed : boolean | |
47 | Should the audio data be embedded using a data URI (True) or should |
|
47 | Should the audio data be embedded using a data URI (True) or should | |
48 | the original source be referenced. Set this to True if you want the |
|
48 | the original source be referenced. Set this to True if you want the | |
49 | audio to playable later with no internet connection in the notebook. |
|
49 | audio to playable later with no internet connection in the notebook. | |
50 |
|
50 | |||
51 | Default is `True`, unless the keyword argument `url` is set, then |
|
51 | Default is `True`, unless the keyword argument `url` is set, then | |
52 | default value is `False`. |
|
52 | default value is `False`. | |
53 | rate : integer |
|
53 | rate : integer | |
54 | The sampling rate of the raw data. |
|
54 | The sampling rate of the raw data. | |
55 | Only required when data parameter is being used as an array |
|
55 | Only required when data parameter is being used as an array | |
56 | autoplay : bool |
|
56 | autoplay : bool | |
57 | Set to True if the audio should immediately start playing. |
|
57 | Set to True if the audio should immediately start playing. | |
58 | Default is `False`. |
|
58 | Default is `False`. | |
59 | normalize : bool |
|
59 | normalize : bool | |
60 | Whether audio should be normalized (rescaled) to the maximum possible |
|
60 | Whether audio should be normalized (rescaled) to the maximum possible | |
61 | range. Default is `True`. When set to `False`, `data` must be between |
|
61 | range. Default is `True`. When set to `False`, `data` must be between | |
62 | -1 and 1 (inclusive), otherwise an error is raised. |
|
62 | -1 and 1 (inclusive), otherwise an error is raised. | |
63 | Applies only when `data` is a list or array of samples; other types of |
|
63 | Applies only when `data` is a list or array of samples; other types of | |
64 | audio are never normalized. |
|
64 | audio are never normalized. | |
65 |
|
65 | |||
66 | Examples |
|
66 | Examples | |
67 | -------- |
|
67 | -------- | |
68 |
|
68 | |||
|
69 | >>> import pytest | |||
|
70 | >>> np = pytest.importorskip("numpy") | |||
|
71 | ||||
69 | Generate a sound |
|
72 | Generate a sound | |
70 |
|
73 | |||
71 | >>> import numpy as np |
|
74 | >>> import numpy as np | |
72 | >>> framerate = 44100 |
|
75 | >>> framerate = 44100 | |
73 | >>> t = np.linspace(0,5,framerate*5) |
|
76 | >>> t = np.linspace(0,5,framerate*5) | |
74 | >>> data = np.sin(2*np.pi*220*t) + np.sin(2*np.pi*224*t) |
|
77 | >>> data = np.sin(2*np.pi*220*t) + np.sin(2*np.pi*224*t) | |
75 | >>> Audio(data, rate=framerate) |
|
78 | >>> Audio(data, rate=framerate) | |
76 | <IPython.lib.display.Audio object> |
|
79 | <IPython.lib.display.Audio object> | |
77 |
|
80 | |||
78 | Can also do stereo or more channels |
|
81 | Can also do stereo or more channels | |
79 |
|
82 | |||
80 | >>> dataleft = np.sin(2*np.pi*220*t) |
|
83 | >>> dataleft = np.sin(2*np.pi*220*t) | |
81 | >>> dataright = np.sin(2*np.pi*224*t) |
|
84 | >>> dataright = np.sin(2*np.pi*224*t) | |
82 | >>> Audio([dataleft, dataright], rate=framerate) |
|
85 | >>> Audio([dataleft, dataright], rate=framerate) | |
83 | <IPython.lib.display.Audio object> |
|
86 | <IPython.lib.display.Audio object> | |
84 |
|
87 | |||
85 | From URL: |
|
88 | From URL: | |
86 |
|
89 | |||
87 | >>> Audio("http://www.nch.com.au/acm/8k16bitpcm.wav") # doctest: +SKIP |
|
90 | >>> Audio("http://www.nch.com.au/acm/8k16bitpcm.wav") # doctest: +SKIP | |
88 | >>> Audio(url="http://www.w3schools.com/html/horse.ogg") # doctest: +SKIP |
|
91 | >>> Audio(url="http://www.w3schools.com/html/horse.ogg") # doctest: +SKIP | |
89 |
|
92 | |||
90 | From a File: |
|
93 | From a File: | |
91 |
|
94 | |||
92 | >>> Audio('/path/to/sound.wav') # doctest: +SKIP |
|
95 | >>> Audio('/path/to/sound.wav') # doctest: +SKIP | |
93 | >>> Audio(filename='/path/to/sound.ogg') # doctest: +SKIP |
|
96 | >>> Audio(filename='/path/to/sound.ogg') # doctest: +SKIP | |
94 |
|
97 | |||
95 | From Bytes: |
|
98 | From Bytes: | |
96 |
|
99 | |||
97 | >>> Audio(b'RAW_WAV_DATA..') # doctest: +SKIP |
|
100 | >>> Audio(b'RAW_WAV_DATA..') # doctest: +SKIP | |
98 | >>> Audio(data=b'RAW_WAV_DATA..') # doctest: +SKIP |
|
101 | >>> Audio(data=b'RAW_WAV_DATA..') # doctest: +SKIP | |
99 |
|
102 | |||
100 | See Also |
|
103 | See Also | |
101 | -------- |
|
104 | -------- | |
102 | ipywidgets.Audio |
|
105 | ipywidgets.Audio | |
103 |
|
106 | |||
104 | AUdio widget with more more flexibility and options. |
|
107 | AUdio widget with more more flexibility and options. | |
105 |
|
108 | |||
106 | """ |
|
109 | """ | |
107 | _read_flags = 'rb' |
|
110 | _read_flags = 'rb' | |
108 |
|
111 | |||
109 | def __init__(self, data=None, filename=None, url=None, embed=None, rate=None, autoplay=False, normalize=True, *, |
|
112 | def __init__(self, data=None, filename=None, url=None, embed=None, rate=None, autoplay=False, normalize=True, *, | |
110 | element_id=None): |
|
113 | element_id=None): | |
111 | if filename is None and url is None and data is None: |
|
114 | if filename is None and url is None and data is None: | |
112 | raise ValueError("No audio data found. Expecting filename, url, or data.") |
|
115 | raise ValueError("No audio data found. Expecting filename, url, or data.") | |
113 | if embed is False and url is None: |
|
116 | if embed is False and url is None: | |
114 | raise ValueError("No url found. Expecting url when embed=False") |
|
117 | raise ValueError("No url found. Expecting url when embed=False") | |
115 |
|
118 | |||
116 | if url is not None and embed is not True: |
|
119 | if url is not None and embed is not True: | |
117 | self.embed = False |
|
120 | self.embed = False | |
118 | else: |
|
121 | else: | |
119 | self.embed = True |
|
122 | self.embed = True | |
120 | self.autoplay = autoplay |
|
123 | self.autoplay = autoplay | |
121 | self.element_id = element_id |
|
124 | self.element_id = element_id | |
122 | super(Audio, self).__init__(data=data, url=url, filename=filename) |
|
125 | super(Audio, self).__init__(data=data, url=url, filename=filename) | |
123 |
|
126 | |||
124 | if self.data is not None and not isinstance(self.data, bytes): |
|
127 | if self.data is not None and not isinstance(self.data, bytes): | |
125 | if rate is None: |
|
128 | if rate is None: | |
126 | raise ValueError("rate must be specified when data is a numpy array or list of audio samples.") |
|
129 | raise ValueError("rate must be specified when data is a numpy array or list of audio samples.") | |
127 | self.data = Audio._make_wav(data, rate, normalize) |
|
130 | self.data = Audio._make_wav(data, rate, normalize) | |
128 |
|
131 | |||
129 | def reload(self): |
|
132 | def reload(self): | |
130 | """Reload the raw data from file or URL.""" |
|
133 | """Reload the raw data from file or URL.""" | |
131 | import mimetypes |
|
134 | import mimetypes | |
132 | if self.embed: |
|
135 | if self.embed: | |
133 | super(Audio, self).reload() |
|
136 | super(Audio, self).reload() | |
134 |
|
137 | |||
135 | if self.filename is not None: |
|
138 | if self.filename is not None: | |
136 | self.mimetype = mimetypes.guess_type(self.filename)[0] |
|
139 | self.mimetype = mimetypes.guess_type(self.filename)[0] | |
137 | elif self.url is not None: |
|
140 | elif self.url is not None: | |
138 | self.mimetype = mimetypes.guess_type(self.url)[0] |
|
141 | self.mimetype = mimetypes.guess_type(self.url)[0] | |
139 | else: |
|
142 | else: | |
140 | self.mimetype = "audio/wav" |
|
143 | self.mimetype = "audio/wav" | |
141 |
|
144 | |||
142 | @staticmethod |
|
145 | @staticmethod | |
143 | def _make_wav(data, rate, normalize): |
|
146 | def _make_wav(data, rate, normalize): | |
144 | """ Transform a numpy array to a PCM bytestring """ |
|
147 | """ Transform a numpy array to a PCM bytestring """ | |
145 | from io import BytesIO |
|
148 | from io import BytesIO | |
146 | import wave |
|
149 | import wave | |
147 |
|
150 | |||
148 | try: |
|
151 | try: | |
149 | scaled, nchan = Audio._validate_and_normalize_with_numpy(data, normalize) |
|
152 | scaled, nchan = Audio._validate_and_normalize_with_numpy(data, normalize) | |
150 | except ImportError: |
|
153 | except ImportError: | |
151 | scaled, nchan = Audio._validate_and_normalize_without_numpy(data, normalize) |
|
154 | scaled, nchan = Audio._validate_and_normalize_without_numpy(data, normalize) | |
152 |
|
155 | |||
153 | fp = BytesIO() |
|
156 | fp = BytesIO() | |
154 | waveobj = wave.open(fp,mode='wb') |
|
157 | waveobj = wave.open(fp,mode='wb') | |
155 | waveobj.setnchannels(nchan) |
|
158 | waveobj.setnchannels(nchan) | |
156 | waveobj.setframerate(rate) |
|
159 | waveobj.setframerate(rate) | |
157 | waveobj.setsampwidth(2) |
|
160 | waveobj.setsampwidth(2) | |
158 | waveobj.setcomptype('NONE','NONE') |
|
161 | waveobj.setcomptype('NONE','NONE') | |
159 | waveobj.writeframes(scaled) |
|
162 | waveobj.writeframes(scaled) | |
160 | val = fp.getvalue() |
|
163 | val = fp.getvalue() | |
161 | waveobj.close() |
|
164 | waveobj.close() | |
162 |
|
165 | |||
163 | return val |
|
166 | return val | |
164 |
|
167 | |||
165 | @staticmethod |
|
168 | @staticmethod | |
166 | def _validate_and_normalize_with_numpy(data, normalize) -> Tuple[bytes, int]: |
|
169 | def _validate_and_normalize_with_numpy(data, normalize) -> Tuple[bytes, int]: | |
167 | import numpy as np |
|
170 | import numpy as np | |
168 |
|
171 | |||
169 | data = np.array(data, dtype=float) |
|
172 | data = np.array(data, dtype=float) | |
170 | if len(data.shape) == 1: |
|
173 | if len(data.shape) == 1: | |
171 | nchan = 1 |
|
174 | nchan = 1 | |
172 | elif len(data.shape) == 2: |
|
175 | elif len(data.shape) == 2: | |
173 | # In wave files,channels are interleaved. E.g., |
|
176 | # In wave files,channels are interleaved. E.g., | |
174 | # "L1R1L2R2..." for stereo. See |
|
177 | # "L1R1L2R2..." for stereo. See | |
175 | # http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx |
|
178 | # http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx | |
176 | # for channel ordering |
|
179 | # for channel ordering | |
177 | nchan = data.shape[0] |
|
180 | nchan = data.shape[0] | |
178 | data = data.T.ravel() |
|
181 | data = data.T.ravel() | |
179 | else: |
|
182 | else: | |
180 | raise ValueError('Array audio input must be a 1D or 2D array') |
|
183 | raise ValueError('Array audio input must be a 1D or 2D array') | |
181 |
|
184 | |||
182 | max_abs_value = np.max(np.abs(data)) |
|
185 | max_abs_value = np.max(np.abs(data)) | |
183 | normalization_factor = Audio._get_normalization_factor(max_abs_value, normalize) |
|
186 | normalization_factor = Audio._get_normalization_factor(max_abs_value, normalize) | |
184 | scaled = data / normalization_factor * 32767 |
|
187 | scaled = data / normalization_factor * 32767 | |
185 | return scaled.astype("<h").tobytes(), nchan |
|
188 | return scaled.astype("<h").tobytes(), nchan | |
186 |
|
189 | |||
187 | @staticmethod |
|
190 | @staticmethod | |
188 | def _validate_and_normalize_without_numpy(data, normalize): |
|
191 | def _validate_and_normalize_without_numpy(data, normalize): | |
189 | import array |
|
192 | import array | |
190 | import sys |
|
193 | import sys | |
191 |
|
194 | |||
192 | data = array.array('f', data) |
|
195 | data = array.array('f', data) | |
193 |
|
196 | |||
194 | try: |
|
197 | try: | |
195 | max_abs_value = float(max([abs(x) for x in data])) |
|
198 | max_abs_value = float(max([abs(x) for x in data])) | |
196 | except TypeError as e: |
|
199 | except TypeError as e: | |
197 | raise TypeError('Only lists of mono audio are ' |
|
200 | raise TypeError('Only lists of mono audio are ' | |
198 | 'supported if numpy is not installed') from e |
|
201 | 'supported if numpy is not installed') from e | |
199 |
|
202 | |||
200 | normalization_factor = Audio._get_normalization_factor(max_abs_value, normalize) |
|
203 | normalization_factor = Audio._get_normalization_factor(max_abs_value, normalize) | |
201 | scaled = array.array('h', [int(x / normalization_factor * 32767) for x in data]) |
|
204 | scaled = array.array('h', [int(x / normalization_factor * 32767) for x in data]) | |
202 | if sys.byteorder == 'big': |
|
205 | if sys.byteorder == 'big': | |
203 | scaled.byteswap() |
|
206 | scaled.byteswap() | |
204 | nchan = 1 |
|
207 | nchan = 1 | |
205 | return scaled.tobytes(), nchan |
|
208 | return scaled.tobytes(), nchan | |
206 |
|
209 | |||
207 | @staticmethod |
|
210 | @staticmethod | |
208 | def _get_normalization_factor(max_abs_value, normalize): |
|
211 | def _get_normalization_factor(max_abs_value, normalize): | |
209 | if not normalize and max_abs_value > 1: |
|
212 | if not normalize and max_abs_value > 1: | |
210 | raise ValueError('Audio data must be between -1 and 1 when normalize=False.') |
|
213 | raise ValueError('Audio data must be between -1 and 1 when normalize=False.') | |
211 | return max_abs_value if normalize else 1 |
|
214 | return max_abs_value if normalize else 1 | |
212 |
|
215 | |||
213 | def _data_and_metadata(self): |
|
216 | def _data_and_metadata(self): | |
214 | """shortcut for returning metadata with url information, if defined""" |
|
217 | """shortcut for returning metadata with url information, if defined""" | |
215 | md = {} |
|
218 | md = {} | |
216 | if self.url: |
|
219 | if self.url: | |
217 | md['url'] = self.url |
|
220 | md['url'] = self.url | |
218 | if md: |
|
221 | if md: | |
219 | return self.data, md |
|
222 | return self.data, md | |
220 | else: |
|
223 | else: | |
221 | return self.data |
|
224 | return self.data | |
222 |
|
225 | |||
223 | def _repr_html_(self): |
|
226 | def _repr_html_(self): | |
224 | src = """ |
|
227 | src = """ | |
225 | <audio {element_id} controls="controls" {autoplay}> |
|
228 | <audio {element_id} controls="controls" {autoplay}> | |
226 | <source src="{src}" type="{type}" /> |
|
229 | <source src="{src}" type="{type}" /> | |
227 | Your browser does not support the audio element. |
|
230 | Your browser does not support the audio element. | |
228 | </audio> |
|
231 | </audio> | |
229 | """ |
|
232 | """ | |
230 | return src.format(src=self.src_attr(), type=self.mimetype, autoplay=self.autoplay_attr(), |
|
233 | return src.format(src=self.src_attr(), type=self.mimetype, autoplay=self.autoplay_attr(), | |
231 | element_id=self.element_id_attr()) |
|
234 | element_id=self.element_id_attr()) | |
232 |
|
235 | |||
233 | def src_attr(self): |
|
236 | def src_attr(self): | |
234 | import base64 |
|
237 | import base64 | |
235 | if self.embed and (self.data is not None): |
|
238 | if self.embed and (self.data is not None): | |
236 | data = base64=base64.b64encode(self.data).decode('ascii') |
|
239 | data = base64=base64.b64encode(self.data).decode('ascii') | |
237 | return """data:{type};base64,{base64}""".format(type=self.mimetype, |
|
240 | return """data:{type};base64,{base64}""".format(type=self.mimetype, | |
238 | base64=data) |
|
241 | base64=data) | |
239 | elif self.url is not None: |
|
242 | elif self.url is not None: | |
240 | return self.url |
|
243 | return self.url | |
241 | else: |
|
244 | else: | |
242 | return "" |
|
245 | return "" | |
243 |
|
246 | |||
244 | def autoplay_attr(self): |
|
247 | def autoplay_attr(self): | |
245 | if(self.autoplay): |
|
248 | if(self.autoplay): | |
246 | return 'autoplay="autoplay"' |
|
249 | return 'autoplay="autoplay"' | |
247 | else: |
|
250 | else: | |
248 | return '' |
|
251 | return '' | |
249 |
|
252 | |||
250 | def element_id_attr(self): |
|
253 | def element_id_attr(self): | |
251 | if (self.element_id): |
|
254 | if (self.element_id): | |
252 | return 'id="{element_id}"'.format(element_id=self.element_id) |
|
255 | return 'id="{element_id}"'.format(element_id=self.element_id) | |
253 | else: |
|
256 | else: | |
254 | return '' |
|
257 | return '' | |
255 |
|
258 | |||
256 | class IFrame(object): |
|
259 | class IFrame(object): | |
257 | """ |
|
260 | """ | |
258 | Generic class to embed an iframe in an IPython notebook |
|
261 | Generic class to embed an iframe in an IPython notebook | |
259 | """ |
|
262 | """ | |
260 |
|
263 | |||
261 | iframe = """ |
|
264 | iframe = """ | |
262 | <iframe |
|
265 | <iframe | |
263 | width="{width}" |
|
266 | width="{width}" | |
264 | height="{height}" |
|
267 | height="{height}" | |
265 | src="{src}{params}" |
|
268 | src="{src}{params}" | |
266 | frameborder="0" |
|
269 | frameborder="0" | |
267 | allowfullscreen |
|
270 | allowfullscreen | |
268 | {extras} |
|
271 | {extras} | |
269 | ></iframe> |
|
272 | ></iframe> | |
270 | """ |
|
273 | """ | |
271 |
|
274 | |||
272 | def __init__(self, src, width, height, extras: Iterable[str] = None, **kwargs): |
|
275 | def __init__(self, src, width, height, extras: Iterable[str] = None, **kwargs): | |
273 | if extras is None: |
|
276 | if extras is None: | |
274 | extras = [] |
|
277 | extras = [] | |
275 |
|
278 | |||
276 | self.src = src |
|
279 | self.src = src | |
277 | self.width = width |
|
280 | self.width = width | |
278 | self.height = height |
|
281 | self.height = height | |
279 | self.extras = extras |
|
282 | self.extras = extras | |
280 | self.params = kwargs |
|
283 | self.params = kwargs | |
281 |
|
284 | |||
282 | def _repr_html_(self): |
|
285 | def _repr_html_(self): | |
283 | """return the embed iframe""" |
|
286 | """return the embed iframe""" | |
284 | if self.params: |
|
287 | if self.params: | |
285 | from urllib.parse import urlencode |
|
288 | from urllib.parse import urlencode | |
286 | params = "?" + urlencode(self.params) |
|
289 | params = "?" + urlencode(self.params) | |
287 | else: |
|
290 | else: | |
288 | params = "" |
|
291 | params = "" | |
289 | return self.iframe.format( |
|
292 | return self.iframe.format( | |
290 | src=self.src, |
|
293 | src=self.src, | |
291 | width=self.width, |
|
294 | width=self.width, | |
292 | height=self.height, |
|
295 | height=self.height, | |
293 | params=params, |
|
296 | params=params, | |
294 | extras=" ".join(self.extras), |
|
297 | extras=" ".join(self.extras), | |
295 | ) |
|
298 | ) | |
296 |
|
299 | |||
297 |
|
300 | |||
298 | class YouTubeVideo(IFrame): |
|
301 | class YouTubeVideo(IFrame): | |
299 | """Class for embedding a YouTube Video in an IPython session, based on its video id. |
|
302 | """Class for embedding a YouTube Video in an IPython session, based on its video id. | |
300 |
|
303 | |||
301 | e.g. to embed the video from https://www.youtube.com/watch?v=foo , you would |
|
304 | e.g. to embed the video from https://www.youtube.com/watch?v=foo , you would | |
302 | do:: |
|
305 | do:: | |
303 |
|
306 | |||
304 | vid = YouTubeVideo("foo") |
|
307 | vid = YouTubeVideo("foo") | |
305 | display(vid) |
|
308 | display(vid) | |
306 |
|
309 | |||
307 | To start from 30 seconds:: |
|
310 | To start from 30 seconds:: | |
308 |
|
311 | |||
309 | vid = YouTubeVideo("abc", start=30) |
|
312 | vid = YouTubeVideo("abc", start=30) | |
310 | display(vid) |
|
313 | display(vid) | |
311 |
|
314 | |||
312 | To calculate seconds from time as hours, minutes, seconds use |
|
315 | To calculate seconds from time as hours, minutes, seconds use | |
313 | :class:`datetime.timedelta`:: |
|
316 | :class:`datetime.timedelta`:: | |
314 |
|
317 | |||
315 | start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds()) |
|
318 | start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds()) | |
316 |
|
319 | |||
317 | Other parameters can be provided as documented at |
|
320 | Other parameters can be provided as documented at | |
318 | https://developers.google.com/youtube/player_parameters#Parameters |
|
321 | https://developers.google.com/youtube/player_parameters#Parameters | |
319 |
|
322 | |||
320 | When converting the notebook using nbconvert, a jpeg representation of the video |
|
323 | When converting the notebook using nbconvert, a jpeg representation of the video | |
321 | will be inserted in the document. |
|
324 | will be inserted in the document. | |
322 | """ |
|
325 | """ | |
323 |
|
326 | |||
324 | def __init__(self, id, width=400, height=300, allow_autoplay=False, **kwargs): |
|
327 | def __init__(self, id, width=400, height=300, allow_autoplay=False, **kwargs): | |
325 | self.id=id |
|
328 | self.id=id | |
326 | src = "https://www.youtube.com/embed/{0}".format(id) |
|
329 | src = "https://www.youtube.com/embed/{0}".format(id) | |
327 | if allow_autoplay: |
|
330 | if allow_autoplay: | |
328 | extras = list(kwargs.get("extras", [])) + ['allow="autoplay"'] |
|
331 | extras = list(kwargs.get("extras", [])) + ['allow="autoplay"'] | |
329 | kwargs.update(autoplay=1, extras=extras) |
|
332 | kwargs.update(autoplay=1, extras=extras) | |
330 | super(YouTubeVideo, self).__init__(src, width, height, **kwargs) |
|
333 | super(YouTubeVideo, self).__init__(src, width, height, **kwargs) | |
331 |
|
334 | |||
332 | def _repr_jpeg_(self): |
|
335 | def _repr_jpeg_(self): | |
333 | # Deferred import |
|
336 | # Deferred import | |
334 | from urllib.request import urlopen |
|
337 | from urllib.request import urlopen | |
335 |
|
338 | |||
336 | try: |
|
339 | try: | |
337 | return urlopen("https://img.youtube.com/vi/{id}/hqdefault.jpg".format(id=self.id)).read() |
|
340 | return urlopen("https://img.youtube.com/vi/{id}/hqdefault.jpg".format(id=self.id)).read() | |
338 | except IOError: |
|
341 | except IOError: | |
339 | return None |
|
342 | return None | |
340 |
|
343 | |||
341 | class VimeoVideo(IFrame): |
|
344 | class VimeoVideo(IFrame): | |
342 | """ |
|
345 | """ | |
343 | Class for embedding a Vimeo video in an IPython session, based on its video id. |
|
346 | Class for embedding a Vimeo video in an IPython session, based on its video id. | |
344 | """ |
|
347 | """ | |
345 |
|
348 | |||
346 | def __init__(self, id, width=400, height=300, **kwargs): |
|
349 | def __init__(self, id, width=400, height=300, **kwargs): | |
347 | src="https://player.vimeo.com/video/{0}".format(id) |
|
350 | src="https://player.vimeo.com/video/{0}".format(id) | |
348 | super(VimeoVideo, self).__init__(src, width, height, **kwargs) |
|
351 | super(VimeoVideo, self).__init__(src, width, height, **kwargs) | |
349 |
|
352 | |||
350 | class ScribdDocument(IFrame): |
|
353 | class ScribdDocument(IFrame): | |
351 | """ |
|
354 | """ | |
352 | Class for embedding a Scribd document in an IPython session |
|
355 | Class for embedding a Scribd document in an IPython session | |
353 |
|
356 | |||
354 | Use the start_page params to specify a starting point in the document |
|
357 | Use the start_page params to specify a starting point in the document | |
355 | Use the view_mode params to specify display type one off scroll | slideshow | book |
|
358 | Use the view_mode params to specify display type one off scroll | slideshow | book | |
356 |
|
359 | |||
357 | e.g to Display Wes' foundational paper about PANDAS in book mode from page 3 |
|
360 | e.g to Display Wes' foundational paper about PANDAS in book mode from page 3 | |
358 |
|
361 | |||
359 | ScribdDocument(71048089, width=800, height=400, start_page=3, view_mode="book") |
|
362 | ScribdDocument(71048089, width=800, height=400, start_page=3, view_mode="book") | |
360 | """ |
|
363 | """ | |
361 |
|
364 | |||
362 | def __init__(self, id, width=400, height=300, **kwargs): |
|
365 | def __init__(self, id, width=400, height=300, **kwargs): | |
363 | src="https://www.scribd.com/embeds/{0}/content".format(id) |
|
366 | src="https://www.scribd.com/embeds/{0}/content".format(id) | |
364 | super(ScribdDocument, self).__init__(src, width, height, **kwargs) |
|
367 | super(ScribdDocument, self).__init__(src, width, height, **kwargs) | |
365 |
|
368 | |||
366 | class FileLink(object): |
|
369 | class FileLink(object): | |
367 | """Class for embedding a local file link in an IPython session, based on path |
|
370 | """Class for embedding a local file link in an IPython session, based on path | |
368 |
|
371 | |||
369 | e.g. to embed a link that was generated in the IPython notebook as my/data.txt |
|
372 | e.g. to embed a link that was generated in the IPython notebook as my/data.txt | |
370 |
|
373 | |||
371 | you would do:: |
|
374 | you would do:: | |
372 |
|
375 | |||
373 | local_file = FileLink("my/data.txt") |
|
376 | local_file = FileLink("my/data.txt") | |
374 | display(local_file) |
|
377 | display(local_file) | |
375 |
|
378 | |||
376 | or in the HTML notebook, just:: |
|
379 | or in the HTML notebook, just:: | |
377 |
|
380 | |||
378 | FileLink("my/data.txt") |
|
381 | FileLink("my/data.txt") | |
379 | """ |
|
382 | """ | |
380 |
|
383 | |||
381 | html_link_str = "<a href='%s' target='_blank'>%s</a>" |
|
384 | html_link_str = "<a href='%s' target='_blank'>%s</a>" | |
382 |
|
385 | |||
383 | def __init__(self, |
|
386 | def __init__(self, | |
384 | path, |
|
387 | path, | |
385 | url_prefix='', |
|
388 | url_prefix='', | |
386 | result_html_prefix='', |
|
389 | result_html_prefix='', | |
387 | result_html_suffix='<br>'): |
|
390 | result_html_suffix='<br>'): | |
388 | """ |
|
391 | """ | |
389 | Parameters |
|
392 | Parameters | |
390 | ---------- |
|
393 | ---------- | |
391 | path : str |
|
394 | path : str | |
392 | path to the file or directory that should be formatted |
|
395 | path to the file or directory that should be formatted | |
393 | url_prefix : str |
|
396 | url_prefix : str | |
394 | prefix to be prepended to all files to form a working link [default: |
|
397 | prefix to be prepended to all files to form a working link [default: | |
395 | ''] |
|
398 | ''] | |
396 | result_html_prefix : str |
|
399 | result_html_prefix : str | |
397 | text to append to beginning to link [default: ''] |
|
400 | text to append to beginning to link [default: ''] | |
398 | result_html_suffix : str |
|
401 | result_html_suffix : str | |
399 | text to append at the end of link [default: '<br>'] |
|
402 | text to append at the end of link [default: '<br>'] | |
400 | """ |
|
403 | """ | |
401 | if isdir(path): |
|
404 | if isdir(path): | |
402 | raise ValueError("Cannot display a directory using FileLink. " |
|
405 | raise ValueError("Cannot display a directory using FileLink. " | |
403 | "Use FileLinks to display '%s'." % path) |
|
406 | "Use FileLinks to display '%s'." % path) | |
404 | self.path = fsdecode(path) |
|
407 | self.path = fsdecode(path) | |
405 | self.url_prefix = url_prefix |
|
408 | self.url_prefix = url_prefix | |
406 | self.result_html_prefix = result_html_prefix |
|
409 | self.result_html_prefix = result_html_prefix | |
407 | self.result_html_suffix = result_html_suffix |
|
410 | self.result_html_suffix = result_html_suffix | |
408 |
|
411 | |||
409 | def _format_path(self): |
|
412 | def _format_path(self): | |
410 | fp = ''.join([self.url_prefix, html_escape(self.path)]) |
|
413 | fp = ''.join([self.url_prefix, html_escape(self.path)]) | |
411 | return ''.join([self.result_html_prefix, |
|
414 | return ''.join([self.result_html_prefix, | |
412 | self.html_link_str % \ |
|
415 | self.html_link_str % \ | |
413 | (fp, html_escape(self.path, quote=False)), |
|
416 | (fp, html_escape(self.path, quote=False)), | |
414 | self.result_html_suffix]) |
|
417 | self.result_html_suffix]) | |
415 |
|
418 | |||
416 | def _repr_html_(self): |
|
419 | def _repr_html_(self): | |
417 | """return html link to file |
|
420 | """return html link to file | |
418 | """ |
|
421 | """ | |
419 | if not exists(self.path): |
|
422 | if not exists(self.path): | |
420 | return ("Path (<tt>%s</tt>) doesn't exist. " |
|
423 | return ("Path (<tt>%s</tt>) doesn't exist. " | |
421 | "It may still be in the process of " |
|
424 | "It may still be in the process of " | |
422 | "being generated, or you may have the " |
|
425 | "being generated, or you may have the " | |
423 | "incorrect path." % self.path) |
|
426 | "incorrect path." % self.path) | |
424 |
|
427 | |||
425 | return self._format_path() |
|
428 | return self._format_path() | |
426 |
|
429 | |||
427 | def __repr__(self): |
|
430 | def __repr__(self): | |
428 | """return absolute path to file |
|
431 | """return absolute path to file | |
429 | """ |
|
432 | """ | |
430 | return abspath(self.path) |
|
433 | return abspath(self.path) | |
431 |
|
434 | |||
432 | class FileLinks(FileLink): |
|
435 | class FileLinks(FileLink): | |
433 | """Class for embedding local file links in an IPython session, based on path |
|
436 | """Class for embedding local file links in an IPython session, based on path | |
434 |
|
437 | |||
435 | e.g. to embed links to files that were generated in the IPython notebook |
|
438 | e.g. to embed links to files that were generated in the IPython notebook | |
436 | under ``my/data``, you would do:: |
|
439 | under ``my/data``, you would do:: | |
437 |
|
440 | |||
438 | local_files = FileLinks("my/data") |
|
441 | local_files = FileLinks("my/data") | |
439 | display(local_files) |
|
442 | display(local_files) | |
440 |
|
443 | |||
441 | or in the HTML notebook, just:: |
|
444 | or in the HTML notebook, just:: | |
442 |
|
445 | |||
443 | FileLinks("my/data") |
|
446 | FileLinks("my/data") | |
444 | """ |
|
447 | """ | |
445 | def __init__(self, |
|
448 | def __init__(self, | |
446 | path, |
|
449 | path, | |
447 | url_prefix='', |
|
450 | url_prefix='', | |
448 | included_suffixes=None, |
|
451 | included_suffixes=None, | |
449 | result_html_prefix='', |
|
452 | result_html_prefix='', | |
450 | result_html_suffix='<br>', |
|
453 | result_html_suffix='<br>', | |
451 | notebook_display_formatter=None, |
|
454 | notebook_display_formatter=None, | |
452 | terminal_display_formatter=None, |
|
455 | terminal_display_formatter=None, | |
453 | recursive=True): |
|
456 | recursive=True): | |
454 | """ |
|
457 | """ | |
455 | See :class:`FileLink` for the ``path``, ``url_prefix``, |
|
458 | See :class:`FileLink` for the ``path``, ``url_prefix``, | |
456 | ``result_html_prefix`` and ``result_html_suffix`` parameters. |
|
459 | ``result_html_prefix`` and ``result_html_suffix`` parameters. | |
457 |
|
460 | |||
458 | included_suffixes : list |
|
461 | included_suffixes : list | |
459 | Filename suffixes to include when formatting output [default: include |
|
462 | Filename suffixes to include when formatting output [default: include | |
460 | all files] |
|
463 | all files] | |
461 |
|
464 | |||
462 | notebook_display_formatter : function |
|
465 | notebook_display_formatter : function | |
463 | Used to format links for display in the notebook. See discussion of |
|
466 | Used to format links for display in the notebook. See discussion of | |
464 | formatter functions below. |
|
467 | formatter functions below. | |
465 |
|
468 | |||
466 | terminal_display_formatter : function |
|
469 | terminal_display_formatter : function | |
467 | Used to format links for display in the terminal. See discussion of |
|
470 | Used to format links for display in the terminal. See discussion of | |
468 | formatter functions below. |
|
471 | formatter functions below. | |
469 |
|
472 | |||
470 | Formatter functions must be of the form:: |
|
473 | Formatter functions must be of the form:: | |
471 |
|
474 | |||
472 | f(dirname, fnames, included_suffixes) |
|
475 | f(dirname, fnames, included_suffixes) | |
473 |
|
476 | |||
474 | dirname : str |
|
477 | dirname : str | |
475 | The name of a directory |
|
478 | The name of a directory | |
476 | fnames : list |
|
479 | fnames : list | |
477 | The files in that directory |
|
480 | The files in that directory | |
478 | included_suffixes : list |
|
481 | included_suffixes : list | |
479 | The file suffixes that should be included in the output (passing None |
|
482 | The file suffixes that should be included in the output (passing None | |
480 | meansto include all suffixes in the output in the built-in formatters) |
|
483 | meansto include all suffixes in the output in the built-in formatters) | |
481 | recursive : boolean |
|
484 | recursive : boolean | |
482 | Whether to recurse into subdirectories. Default is True. |
|
485 | Whether to recurse into subdirectories. Default is True. | |
483 |
|
486 | |||
484 | The function should return a list of lines that will be printed in the |
|
487 | The function should return a list of lines that will be printed in the | |
485 | notebook (if passing notebook_display_formatter) or the terminal (if |
|
488 | notebook (if passing notebook_display_formatter) or the terminal (if | |
486 | passing terminal_display_formatter). This function is iterated over for |
|
489 | passing terminal_display_formatter). This function is iterated over for | |
487 | each directory in self.path. Default formatters are in place, can be |
|
490 | each directory in self.path. Default formatters are in place, can be | |
488 | passed here to support alternative formatting. |
|
491 | passed here to support alternative formatting. | |
489 |
|
492 | |||
490 | """ |
|
493 | """ | |
491 | if isfile(path): |
|
494 | if isfile(path): | |
492 | raise ValueError("Cannot display a file using FileLinks. " |
|
495 | raise ValueError("Cannot display a file using FileLinks. " | |
493 | "Use FileLink to display '%s'." % path) |
|
496 | "Use FileLink to display '%s'." % path) | |
494 | self.included_suffixes = included_suffixes |
|
497 | self.included_suffixes = included_suffixes | |
495 | # remove trailing slashes for more consistent output formatting |
|
498 | # remove trailing slashes for more consistent output formatting | |
496 | path = path.rstrip('/') |
|
499 | path = path.rstrip('/') | |
497 |
|
500 | |||
498 | self.path = path |
|
501 | self.path = path | |
499 | self.url_prefix = url_prefix |
|
502 | self.url_prefix = url_prefix | |
500 | self.result_html_prefix = result_html_prefix |
|
503 | self.result_html_prefix = result_html_prefix | |
501 | self.result_html_suffix = result_html_suffix |
|
504 | self.result_html_suffix = result_html_suffix | |
502 |
|
505 | |||
503 | self.notebook_display_formatter = \ |
|
506 | self.notebook_display_formatter = \ | |
504 | notebook_display_formatter or self._get_notebook_display_formatter() |
|
507 | notebook_display_formatter or self._get_notebook_display_formatter() | |
505 | self.terminal_display_formatter = \ |
|
508 | self.terminal_display_formatter = \ | |
506 | terminal_display_formatter or self._get_terminal_display_formatter() |
|
509 | terminal_display_formatter or self._get_terminal_display_formatter() | |
507 |
|
510 | |||
508 | self.recursive = recursive |
|
511 | self.recursive = recursive | |
509 |
|
512 | |||
510 | def _get_display_formatter(self, |
|
513 | def _get_display_formatter(self, | |
511 | dirname_output_format, |
|
514 | dirname_output_format, | |
512 | fname_output_format, |
|
515 | fname_output_format, | |
513 | fp_format, |
|
516 | fp_format, | |
514 | fp_cleaner=None): |
|
517 | fp_cleaner=None): | |
515 | """ generate built-in formatter function |
|
518 | """ generate built-in formatter function | |
516 |
|
519 | |||
517 | this is used to define both the notebook and terminal built-in |
|
520 | this is used to define both the notebook and terminal built-in | |
518 | formatters as they only differ by some wrapper text for each entry |
|
521 | formatters as they only differ by some wrapper text for each entry | |
519 |
|
522 | |||
520 | dirname_output_format: string to use for formatting directory |
|
523 | dirname_output_format: string to use for formatting directory | |
521 | names, dirname will be substituted for a single "%s" which |
|
524 | names, dirname will be substituted for a single "%s" which | |
522 | must appear in this string |
|
525 | must appear in this string | |
523 | fname_output_format: string to use for formatting file names, |
|
526 | fname_output_format: string to use for formatting file names, | |
524 | if a single "%s" appears in the string, fname will be substituted |
|
527 | if a single "%s" appears in the string, fname will be substituted | |
525 | if two "%s" appear in the string, the path to fname will be |
|
528 | if two "%s" appear in the string, the path to fname will be | |
526 | substituted for the first and fname will be substituted for the |
|
529 | substituted for the first and fname will be substituted for the | |
527 | second |
|
530 | second | |
528 | fp_format: string to use for formatting filepaths, must contain |
|
531 | fp_format: string to use for formatting filepaths, must contain | |
529 | exactly two "%s" and the dirname will be substituted for the first |
|
532 | exactly two "%s" and the dirname will be substituted for the first | |
530 | and fname will be substituted for the second |
|
533 | and fname will be substituted for the second | |
531 | """ |
|
534 | """ | |
532 | def f(dirname, fnames, included_suffixes=None): |
|
535 | def f(dirname, fnames, included_suffixes=None): | |
533 | result = [] |
|
536 | result = [] | |
534 | # begin by figuring out which filenames, if any, |
|
537 | # begin by figuring out which filenames, if any, | |
535 | # are going to be displayed |
|
538 | # are going to be displayed | |
536 | display_fnames = [] |
|
539 | display_fnames = [] | |
537 | for fname in fnames: |
|
540 | for fname in fnames: | |
538 | if (isfile(join(dirname,fname)) and |
|
541 | if (isfile(join(dirname,fname)) and | |
539 | (included_suffixes is None or |
|
542 | (included_suffixes is None or | |
540 | splitext(fname)[1] in included_suffixes)): |
|
543 | splitext(fname)[1] in included_suffixes)): | |
541 | display_fnames.append(fname) |
|
544 | display_fnames.append(fname) | |
542 |
|
545 | |||
543 | if len(display_fnames) == 0: |
|
546 | if len(display_fnames) == 0: | |
544 | # if there are no filenames to display, don't print anything |
|
547 | # if there are no filenames to display, don't print anything | |
545 | # (not even the directory name) |
|
548 | # (not even the directory name) | |
546 | pass |
|
549 | pass | |
547 | else: |
|
550 | else: | |
548 | # otherwise print the formatted directory name followed by |
|
551 | # otherwise print the formatted directory name followed by | |
549 | # the formatted filenames |
|
552 | # the formatted filenames | |
550 | dirname_output_line = dirname_output_format % dirname |
|
553 | dirname_output_line = dirname_output_format % dirname | |
551 | result.append(dirname_output_line) |
|
554 | result.append(dirname_output_line) | |
552 | for fname in display_fnames: |
|
555 | for fname in display_fnames: | |
553 | fp = fp_format % (dirname,fname) |
|
556 | fp = fp_format % (dirname,fname) | |
554 | if fp_cleaner is not None: |
|
557 | if fp_cleaner is not None: | |
555 | fp = fp_cleaner(fp) |
|
558 | fp = fp_cleaner(fp) | |
556 | try: |
|
559 | try: | |
557 | # output can include both a filepath and a filename... |
|
560 | # output can include both a filepath and a filename... | |
558 | fname_output_line = fname_output_format % (fp, fname) |
|
561 | fname_output_line = fname_output_format % (fp, fname) | |
559 | except TypeError: |
|
562 | except TypeError: | |
560 | # ... or just a single filepath |
|
563 | # ... or just a single filepath | |
561 | fname_output_line = fname_output_format % fname |
|
564 | fname_output_line = fname_output_format % fname | |
562 | result.append(fname_output_line) |
|
565 | result.append(fname_output_line) | |
563 | return result |
|
566 | return result | |
564 | return f |
|
567 | return f | |
565 |
|
568 | |||
566 | def _get_notebook_display_formatter(self, |
|
569 | def _get_notebook_display_formatter(self, | |
567 | spacer=" "): |
|
570 | spacer=" "): | |
568 | """ generate function to use for notebook formatting |
|
571 | """ generate function to use for notebook formatting | |
569 | """ |
|
572 | """ | |
570 | dirname_output_format = \ |
|
573 | dirname_output_format = \ | |
571 | self.result_html_prefix + "%s/" + self.result_html_suffix |
|
574 | self.result_html_prefix + "%s/" + self.result_html_suffix | |
572 | fname_output_format = \ |
|
575 | fname_output_format = \ | |
573 | self.result_html_prefix + spacer + self.html_link_str + self.result_html_suffix |
|
576 | self.result_html_prefix + spacer + self.html_link_str + self.result_html_suffix | |
574 | fp_format = self.url_prefix + '%s/%s' |
|
577 | fp_format = self.url_prefix + '%s/%s' | |
575 | if sep == "\\": |
|
578 | if sep == "\\": | |
576 | # Working on a platform where the path separator is "\", so |
|
579 | # Working on a platform where the path separator is "\", so | |
577 | # must convert these to "/" for generating a URI |
|
580 | # must convert these to "/" for generating a URI | |
578 | def fp_cleaner(fp): |
|
581 | def fp_cleaner(fp): | |
579 | # Replace all occurrences of backslash ("\") with a forward |
|
582 | # Replace all occurrences of backslash ("\") with a forward | |
580 | # slash ("/") - this is necessary on windows when a path is |
|
583 | # slash ("/") - this is necessary on windows when a path is | |
581 | # provided as input, but we must link to a URI |
|
584 | # provided as input, but we must link to a URI | |
582 | return fp.replace('\\','/') |
|
585 | return fp.replace('\\','/') | |
583 | else: |
|
586 | else: | |
584 | fp_cleaner = None |
|
587 | fp_cleaner = None | |
585 |
|
588 | |||
586 | return self._get_display_formatter(dirname_output_format, |
|
589 | return self._get_display_formatter(dirname_output_format, | |
587 | fname_output_format, |
|
590 | fname_output_format, | |
588 | fp_format, |
|
591 | fp_format, | |
589 | fp_cleaner) |
|
592 | fp_cleaner) | |
590 |
|
593 | |||
591 | def _get_terminal_display_formatter(self, |
|
594 | def _get_terminal_display_formatter(self, | |
592 | spacer=" "): |
|
595 | spacer=" "): | |
593 | """ generate function to use for terminal formatting |
|
596 | """ generate function to use for terminal formatting | |
594 | """ |
|
597 | """ | |
595 | dirname_output_format = "%s/" |
|
598 | dirname_output_format = "%s/" | |
596 | fname_output_format = spacer + "%s" |
|
599 | fname_output_format = spacer + "%s" | |
597 | fp_format = '%s/%s' |
|
600 | fp_format = '%s/%s' | |
598 |
|
601 | |||
599 | return self._get_display_formatter(dirname_output_format, |
|
602 | return self._get_display_formatter(dirname_output_format, | |
600 | fname_output_format, |
|
603 | fname_output_format, | |
601 | fp_format) |
|
604 | fp_format) | |
602 |
|
605 | |||
603 | def _format_path(self): |
|
606 | def _format_path(self): | |
604 | result_lines = [] |
|
607 | result_lines = [] | |
605 | if self.recursive: |
|
608 | if self.recursive: | |
606 | walked_dir = list(walk(self.path)) |
|
609 | walked_dir = list(walk(self.path)) | |
607 | else: |
|
610 | else: | |
608 | walked_dir = [next(walk(self.path))] |
|
611 | walked_dir = [next(walk(self.path))] | |
609 | walked_dir.sort() |
|
612 | walked_dir.sort() | |
610 | for dirname, subdirs, fnames in walked_dir: |
|
613 | for dirname, subdirs, fnames in walked_dir: | |
611 | result_lines += self.notebook_display_formatter(dirname, fnames, self.included_suffixes) |
|
614 | result_lines += self.notebook_display_formatter(dirname, fnames, self.included_suffixes) | |
612 | return '\n'.join(result_lines) |
|
615 | return '\n'.join(result_lines) | |
613 |
|
616 | |||
614 | def __repr__(self): |
|
617 | def __repr__(self): | |
615 | """return newline-separated absolute paths |
|
618 | """return newline-separated absolute paths | |
616 | """ |
|
619 | """ | |
617 | result_lines = [] |
|
620 | result_lines = [] | |
618 | if self.recursive: |
|
621 | if self.recursive: | |
619 | walked_dir = list(walk(self.path)) |
|
622 | walked_dir = list(walk(self.path)) | |
620 | else: |
|
623 | else: | |
621 | walked_dir = [next(walk(self.path))] |
|
624 | walked_dir = [next(walk(self.path))] | |
622 | walked_dir.sort() |
|
625 | walked_dir.sort() | |
623 | for dirname, subdirs, fnames in walked_dir: |
|
626 | for dirname, subdirs, fnames in walked_dir: | |
624 | result_lines += self.terminal_display_formatter(dirname, fnames, self.included_suffixes) |
|
627 | result_lines += self.terminal_display_formatter(dirname, fnames, self.included_suffixes) | |
625 | return '\n'.join(result_lines) |
|
628 | return '\n'.join(result_lines) | |
626 |
|
629 | |||
627 |
|
630 | |||
628 | class Code(TextDisplayObject): |
|
631 | class Code(TextDisplayObject): | |
629 | """Display syntax-highlighted source code. |
|
632 | """Display syntax-highlighted source code. | |
630 |
|
633 | |||
631 | This uses Pygments to highlight the code for HTML and Latex output. |
|
634 | This uses Pygments to highlight the code for HTML and Latex output. | |
632 |
|
635 | |||
633 | Parameters |
|
636 | Parameters | |
634 | ---------- |
|
637 | ---------- | |
635 | data : str |
|
638 | data : str | |
636 | The code as a string |
|
639 | The code as a string | |
637 | url : str |
|
640 | url : str | |
638 | A URL to fetch the code from |
|
641 | A URL to fetch the code from | |
639 | filename : str |
|
642 | filename : str | |
640 | A local filename to load the code from |
|
643 | A local filename to load the code from | |
641 | language : str |
|
644 | language : str | |
642 | The short name of a Pygments lexer to use for highlighting. |
|
645 | The short name of a Pygments lexer to use for highlighting. | |
643 | If not specified, it will guess the lexer based on the filename |
|
646 | If not specified, it will guess the lexer based on the filename | |
644 | or the code. Available lexers: http://pygments.org/docs/lexers/ |
|
647 | or the code. Available lexers: http://pygments.org/docs/lexers/ | |
645 | """ |
|
648 | """ | |
646 | def __init__(self, data=None, url=None, filename=None, language=None): |
|
649 | def __init__(self, data=None, url=None, filename=None, language=None): | |
647 | self.language = language |
|
650 | self.language = language | |
648 | super().__init__(data=data, url=url, filename=filename) |
|
651 | super().__init__(data=data, url=url, filename=filename) | |
649 |
|
652 | |||
650 | def _get_lexer(self): |
|
653 | def _get_lexer(self): | |
651 | if self.language: |
|
654 | if self.language: | |
652 | from pygments.lexers import get_lexer_by_name |
|
655 | from pygments.lexers import get_lexer_by_name | |
653 | return get_lexer_by_name(self.language) |
|
656 | return get_lexer_by_name(self.language) | |
654 | elif self.filename: |
|
657 | elif self.filename: | |
655 | from pygments.lexers import get_lexer_for_filename |
|
658 | from pygments.lexers import get_lexer_for_filename | |
656 | return get_lexer_for_filename(self.filename) |
|
659 | return get_lexer_for_filename(self.filename) | |
657 | else: |
|
660 | else: | |
658 | from pygments.lexers import guess_lexer |
|
661 | from pygments.lexers import guess_lexer | |
659 | return guess_lexer(self.data) |
|
662 | return guess_lexer(self.data) | |
660 |
|
663 | |||
661 | def __repr__(self): |
|
664 | def __repr__(self): | |
662 | return self.data |
|
665 | return self.data | |
663 |
|
666 | |||
664 | def _repr_html_(self): |
|
667 | def _repr_html_(self): | |
665 | from pygments import highlight |
|
668 | from pygments import highlight | |
666 | from pygments.formatters import HtmlFormatter |
|
669 | from pygments.formatters import HtmlFormatter | |
667 | fmt = HtmlFormatter() |
|
670 | fmt = HtmlFormatter() | |
668 | style = '<style>{}</style>'.format(fmt.get_style_defs('.output_html')) |
|
671 | style = '<style>{}</style>'.format(fmt.get_style_defs('.output_html')) | |
669 | return style + highlight(self.data, self._get_lexer(), fmt) |
|
672 | return style + highlight(self.data, self._get_lexer(), fmt) | |
670 |
|
673 | |||
671 | def _repr_latex_(self): |
|
674 | def _repr_latex_(self): | |
672 | from pygments import highlight |
|
675 | from pygments import highlight | |
673 | from pygments.formatters import LatexFormatter |
|
676 | from pygments.formatters import LatexFormatter | |
674 | return highlight(self.data, self._get_lexer(), LatexFormatter()) |
|
677 | return highlight(self.data, self._get_lexer(), LatexFormatter()) |
@@ -1,28 +1,30 b'' | |||||
1 | """Test help output of various IPython entry points""" |
|
1 | """Test help output of various IPython entry points""" | |
2 |
|
2 | |||
3 | # Copyright (c) IPython Development Team. |
|
3 | # Copyright (c) IPython Development Team. | |
4 | # Distributed under the terms of the Modified BSD License. |
|
4 | # Distributed under the terms of the Modified BSD License. | |
5 |
|
5 | |||
|
6 | import pytest | |||
6 | import IPython.testing.tools as tt |
|
7 | import IPython.testing.tools as tt | |
7 |
|
8 | |||
8 |
|
9 | |||
9 | def test_ipython_help(): |
|
10 | def test_ipython_help(): | |
10 | tt.help_all_output_test() |
|
11 | tt.help_all_output_test() | |
11 |
|
12 | |||
12 | def test_profile_help(): |
|
13 | def test_profile_help(): | |
13 | tt.help_all_output_test("profile") |
|
14 | tt.help_all_output_test("profile") | |
14 |
|
15 | |||
15 | def test_profile_list_help(): |
|
16 | def test_profile_list_help(): | |
16 | tt.help_all_output_test("profile list") |
|
17 | tt.help_all_output_test("profile list") | |
17 |
|
18 | |||
18 | def test_profile_create_help(): |
|
19 | def test_profile_create_help(): | |
19 | tt.help_all_output_test("profile create") |
|
20 | tt.help_all_output_test("profile create") | |
20 |
|
21 | |||
21 | def test_locate_help(): |
|
22 | def test_locate_help(): | |
22 | tt.help_all_output_test("locate") |
|
23 | tt.help_all_output_test("locate") | |
23 |
|
24 | |||
24 | def test_locate_profile_help(): |
|
25 | def test_locate_profile_help(): | |
25 | tt.help_all_output_test("locate profile") |
|
26 | tt.help_all_output_test("locate profile") | |
26 |
|
27 | |||
27 | def test_trust_help(): |
|
28 | def test_trust_help(): | |
|
29 | pytest.importorskip("nbformat") | |||
28 | tt.help_all_output_test("trust") |
|
30 | tt.help_all_output_test("trust") |
@@ -1,40 +1,40 b'' | |||||
1 | build: false |
|
1 | build: false | |
2 | matrix: |
|
2 | matrix: | |
3 | fast_finish: true # immediately finish build once one of the jobs fails. |
|
3 | fast_finish: true # immediately finish build once one of the jobs fails. | |
4 |
|
4 | |||
5 | environment: |
|
5 | environment: | |
6 | global: |
|
6 | global: | |
7 | APPVEYOR_BUILD_WORKER_IMAGE: 'Visual Studio 2022' |
|
7 | APPVEYOR_BUILD_WORKER_IMAGE: 'Visual Studio 2022' | |
8 | COLUMNS: 120 # Appveyor web viwer window width is 130 chars |
|
8 | COLUMNS: 120 # Appveyor web viwer window width is 130 chars | |
9 |
|
9 | |||
10 | matrix: |
|
10 | matrix: | |
11 |
|
11 | |||
12 | - PYTHON: "C:\\Python310-x64" |
|
12 | - PYTHON: "C:\\Python310-x64" | |
13 | PYTHON_VERSION: "3.10.x" |
|
13 | PYTHON_VERSION: "3.10.x" | |
14 | PYTHON_ARCH: "64" |
|
14 | PYTHON_ARCH: "64" | |
15 |
|
15 | |||
16 | - PYTHON: "C:\\Python37-x64" |
|
16 | - PYTHON: "C:\\Python37-x64" | |
17 | PYTHON_VERSION: "3.7.x" |
|
17 | PYTHON_VERSION: "3.7.x" | |
18 | PYTHON_ARCH: "64" |
|
18 | PYTHON_ARCH: "64" | |
19 |
|
19 | |||
20 | - PYTHON: "C:\\Python38" |
|
20 | - PYTHON: "C:\\Python38" | |
21 | PYTHON_VERSION: "3.8.x" |
|
21 | PYTHON_VERSION: "3.8.x" | |
22 | PYTHON_ARCH: "32" |
|
22 | PYTHON_ARCH: "32" | |
23 |
|
23 | |||
24 | - PYTHON: "C:\\Python38-x64" |
|
24 | - PYTHON: "C:\\Python38-x64" | |
25 | PYTHON_VERSION: "3.8.x" |
|
25 | PYTHON_VERSION: "3.8.x" | |
26 | PYTHON_ARCH: "64" |
|
26 | PYTHON_ARCH: "64" | |
27 |
|
27 | |||
28 | init: |
|
28 | init: | |
29 | - "ECHO %PYTHON% %PYTHON_VERSION% %PYTHON_ARCH%" |
|
29 | - "ECHO %PYTHON% %PYTHON_VERSION% %PYTHON_ARCH%" | |
30 |
|
30 | |||
31 | install: |
|
31 | install: | |
32 | - "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%" |
|
32 | - "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%" | |
33 | - python -m pip install --upgrade setuptools pip |
|
33 | - python -m pip install --upgrade setuptools pip | |
34 | - pip install pytest pytest-cov pytest-trio matplotlib pandas |
|
34 | - pip install pytest-cov | |
35 | - pip install -e .[test] |
|
35 | - pip install -e .[test_extra] | |
36 | test_script: |
|
36 | test_script: | |
37 | - pytest --color=yes -ra --cov --cov-report=xml |
|
37 | - pytest --color=yes -ra --cov --cov-report=xml | |
38 | on_finish: |
|
38 | on_finish: | |
39 | - curl -Os https://uploader.codecov.io/latest/windows/codecov.exe |
|
39 | - curl -Os https://uploader.codecov.io/latest/windows/codecov.exe | |
40 | - codecov -e PYTHON_VERSION,PYTHON_ARCH |
|
40 | - codecov -e PYTHON_VERSION,PYTHON_ARCH |
@@ -1,272 +1,279 b'' | |||||
1 | #!/usr/bin/env python3 |
|
1 | #!/usr/bin/env python3 | |
2 | # -*- coding: utf-8 -*- |
|
2 | # -*- coding: utf-8 -*- | |
3 | """Setup script for IPython. |
|
3 | """Setup script for IPython. | |
4 |
|
4 | |||
5 | Under Posix environments it works like a typical setup.py script. |
|
5 | Under Posix environments it works like a typical setup.py script. | |
6 | Under Windows, the command sdist is not supported, since IPython |
|
6 | Under Windows, the command sdist is not supported, since IPython | |
7 | requires utilities which are not available under Windows.""" |
|
7 | requires utilities which are not available under Windows.""" | |
8 |
|
8 | |||
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 | # Copyright (c) 2008-2011, IPython Development Team. |
|
10 | # Copyright (c) 2008-2011, IPython Development Team. | |
11 | # Copyright (c) 2001-2007, Fernando Perez <fernando.perez@colorado.edu> |
|
11 | # Copyright (c) 2001-2007, Fernando Perez <fernando.perez@colorado.edu> | |
12 | # Copyright (c) 2001, Janko Hauser <jhauser@zscout.de> |
|
12 | # Copyright (c) 2001, Janko Hauser <jhauser@zscout.de> | |
13 | # Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu> |
|
13 | # Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu> | |
14 | # |
|
14 | # | |
15 | # Distributed under the terms of the Modified BSD License. |
|
15 | # Distributed under the terms of the Modified BSD License. | |
16 | # |
|
16 | # | |
17 | # The full license is in the file COPYING.rst, distributed with this software. |
|
17 | # The full license is in the file COPYING.rst, distributed with this software. | |
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 |
|
19 | |||
20 | import os |
|
20 | import os | |
21 | import sys |
|
21 | import sys | |
22 | from pathlib import Path |
|
22 | from pathlib import Path | |
23 |
|
23 | |||
24 | # **Python version check** |
|
24 | # **Python version check** | |
25 | # |
|
25 | # | |
26 | # This check is also made in IPython/__init__, don't forget to update both when |
|
26 | # This check is also made in IPython/__init__, don't forget to update both when | |
27 | # changing Python version requirements. |
|
27 | # changing Python version requirements. | |
28 | if sys.version_info < (3, 7): |
|
28 | if sys.version_info < (3, 7): | |
29 | pip_message = 'This may be due to an out of date pip. Make sure you have pip >= 9.0.1.' |
|
29 | pip_message = 'This may be due to an out of date pip. Make sure you have pip >= 9.0.1.' | |
30 | try: |
|
30 | try: | |
31 | import pip |
|
31 | import pip | |
32 | pip_version = tuple([int(x) for x in pip.__version__.split('.')[:3]]) |
|
32 | pip_version = tuple([int(x) for x in pip.__version__.split('.')[:3]]) | |
33 | if pip_version < (9, 0, 1) : |
|
33 | if pip_version < (9, 0, 1) : | |
34 | pip_message = 'Your pip version is out of date, please install pip >= 9.0.1. '\ |
|
34 | pip_message = 'Your pip version is out of date, please install pip >= 9.0.1. '\ | |
35 | 'pip {} detected.'.format(pip.__version__) |
|
35 | 'pip {} detected.'.format(pip.__version__) | |
36 | else: |
|
36 | else: | |
37 | # pip is new enough - it must be something else |
|
37 | # pip is new enough - it must be something else | |
38 | pip_message = '' |
|
38 | pip_message = '' | |
39 | except Exception: |
|
39 | except Exception: | |
40 | pass |
|
40 | pass | |
41 |
|
41 | |||
42 |
|
42 | |||
43 | error = """ |
|
43 | error = """ | |
44 | IPython 7.17+ supports Python 3.7 and above, following NEP 29. |
|
44 | IPython 7.17+ supports Python 3.7 and above, following NEP 29. | |
45 | When using Python 2.7, please install IPython 5.x LTS Long Term Support version. |
|
45 | When using Python 2.7, please install IPython 5.x LTS Long Term Support version. | |
46 | Python 3.3 and 3.4 were supported up to IPython 6.x. |
|
46 | Python 3.3 and 3.4 were supported up to IPython 6.x. | |
47 | Python 3.5 was supported with IPython 7.0 to 7.9. |
|
47 | Python 3.5 was supported with IPython 7.0 to 7.9. | |
48 | Python 3.6 was supported with IPython up to 7.16. |
|
48 | Python 3.6 was supported with IPython up to 7.16. | |
49 |
|
49 | |||
50 | See IPython `README.rst` file for more information: |
|
50 | See IPython `README.rst` file for more information: | |
51 |
|
51 | |||
52 | https://github.com/ipython/ipython/blob/master/README.rst |
|
52 | https://github.com/ipython/ipython/blob/master/README.rst | |
53 |
|
53 | |||
54 | Python {py} detected. |
|
54 | Python {py} detected. | |
55 | {pip} |
|
55 | {pip} | |
56 | """.format(py=sys.version_info, pip=pip_message ) |
|
56 | """.format(py=sys.version_info, pip=pip_message ) | |
57 |
|
57 | |||
58 | print(error, file=sys.stderr) |
|
58 | print(error, file=sys.stderr) | |
59 | sys.exit(1) |
|
59 | sys.exit(1) | |
60 |
|
60 | |||
61 | # At least we're on the python version we need, move on. |
|
61 | # At least we're on the python version we need, move on. | |
62 |
|
62 | |||
63 | # BEFORE importing distutils, remove MANIFEST. distutils doesn't properly |
|
63 | # BEFORE importing distutils, remove MANIFEST. distutils doesn't properly | |
64 | # update it when the contents of directories change. |
|
64 | # update it when the contents of directories change. | |
65 | if Path("MANIFEST").exists(): |
|
65 | if Path("MANIFEST").exists(): | |
66 | Path("MANIFEST").unlink() |
|
66 | Path("MANIFEST").unlink() | |
67 |
|
67 | |||
68 | from distutils.core import setup |
|
68 | from distutils.core import setup | |
69 |
|
69 | |||
70 | # Our own imports |
|
70 | # Our own imports | |
71 | from setupbase import target_update |
|
71 | from setupbase import target_update | |
72 |
|
72 | |||
73 | from setupbase import ( |
|
73 | from setupbase import ( | |
74 | setup_args, |
|
74 | setup_args, | |
75 | find_packages, |
|
75 | find_packages, | |
76 | find_package_data, |
|
76 | find_package_data, | |
77 | check_package_data_first, |
|
77 | check_package_data_first, | |
78 | find_entry_points, |
|
78 | find_entry_points, | |
79 | build_scripts_entrypt, |
|
79 | build_scripts_entrypt, | |
80 | find_data_files, |
|
80 | find_data_files, | |
81 | git_prebuild, |
|
81 | git_prebuild, | |
82 | install_symlinked, |
|
82 | install_symlinked, | |
83 | install_lib_symlink, |
|
83 | install_lib_symlink, | |
84 | install_scripts_for_symlink, |
|
84 | install_scripts_for_symlink, | |
85 | unsymlink, |
|
85 | unsymlink, | |
86 | ) |
|
86 | ) | |
87 |
|
87 | |||
88 | #------------------------------------------------------------------------------- |
|
88 | #------------------------------------------------------------------------------- | |
89 | # Handle OS specific things |
|
89 | # Handle OS specific things | |
90 | #------------------------------------------------------------------------------- |
|
90 | #------------------------------------------------------------------------------- | |
91 |
|
91 | |||
92 | if os.name in ('nt','dos'): |
|
92 | if os.name in ('nt','dos'): | |
93 | os_name = 'windows' |
|
93 | os_name = 'windows' | |
94 | else: |
|
94 | else: | |
95 | os_name = os.name |
|
95 | os_name = os.name | |
96 |
|
96 | |||
97 | # Under Windows, 'sdist' has not been supported. Now that the docs build with |
|
97 | # Under Windows, 'sdist' has not been supported. Now that the docs build with | |
98 | # Sphinx it might work, but let's not turn it on until someone confirms that it |
|
98 | # Sphinx it might work, but let's not turn it on until someone confirms that it | |
99 | # actually works. |
|
99 | # actually works. | |
100 | if os_name == 'windows' and 'sdist' in sys.argv: |
|
100 | if os_name == 'windows' and 'sdist' in sys.argv: | |
101 | print('The sdist command is not available under Windows. Exiting.') |
|
101 | print('The sdist command is not available under Windows. Exiting.') | |
102 | sys.exit(1) |
|
102 | sys.exit(1) | |
103 |
|
103 | |||
104 |
|
104 | |||
105 | #------------------------------------------------------------------------------- |
|
105 | #------------------------------------------------------------------------------- | |
106 | # Things related to the IPython documentation |
|
106 | # Things related to the IPython documentation | |
107 | #------------------------------------------------------------------------------- |
|
107 | #------------------------------------------------------------------------------- | |
108 |
|
108 | |||
109 | # update the manuals when building a source dist |
|
109 | # update the manuals when building a source dist | |
110 | if len(sys.argv) >= 2 and sys.argv[1] in ('sdist','bdist_rpm'): |
|
110 | if len(sys.argv) >= 2 and sys.argv[1] in ('sdist','bdist_rpm'): | |
111 |
|
111 | |||
112 | # List of things to be updated. Each entry is a triplet of args for |
|
112 | # List of things to be updated. Each entry is a triplet of args for | |
113 | # target_update() |
|
113 | # target_update() | |
114 | to_update = [ |
|
114 | to_update = [ | |
115 | ('docs/man/ipython.1.gz', |
|
115 | ('docs/man/ipython.1.gz', | |
116 | ['docs/man/ipython.1'], |
|
116 | ['docs/man/ipython.1'], | |
117 | 'cd docs/man && gzip -9c ipython.1 > ipython.1.gz'), |
|
117 | 'cd docs/man && gzip -9c ipython.1 > ipython.1.gz'), | |
118 | ] |
|
118 | ] | |
119 |
|
119 | |||
120 |
|
120 | |||
121 | [ target_update(*t) for t in to_update ] |
|
121 | [ target_update(*t) for t in to_update ] | |
122 |
|
122 | |||
123 | #--------------------------------------------------------------------------- |
|
123 | #--------------------------------------------------------------------------- | |
124 | # Find all the packages, package data, and data_files |
|
124 | # Find all the packages, package data, and data_files | |
125 | #--------------------------------------------------------------------------- |
|
125 | #--------------------------------------------------------------------------- | |
126 |
|
126 | |||
127 | packages = find_packages() |
|
127 | packages = find_packages() | |
128 | package_data = find_package_data() |
|
128 | package_data = find_package_data() | |
129 |
|
129 | |||
130 | data_files = find_data_files() |
|
130 | data_files = find_data_files() | |
131 |
|
131 | |||
132 | setup_args['packages'] = packages |
|
132 | setup_args['packages'] = packages | |
133 | setup_args['package_data'] = package_data |
|
133 | setup_args['package_data'] = package_data | |
134 | setup_args['data_files'] = data_files |
|
134 | setup_args['data_files'] = data_files | |
135 |
|
135 | |||
136 | #--------------------------------------------------------------------------- |
|
136 | #--------------------------------------------------------------------------- | |
137 | # custom distutils commands |
|
137 | # custom distutils commands | |
138 | #--------------------------------------------------------------------------- |
|
138 | #--------------------------------------------------------------------------- | |
139 | # imports here, so they are after setuptools import if there was one |
|
139 | # imports here, so they are after setuptools import if there was one | |
140 | from distutils.command.sdist import sdist |
|
140 | from distutils.command.sdist import sdist | |
141 |
|
141 | |||
142 | setup_args['cmdclass'] = { |
|
142 | setup_args['cmdclass'] = { | |
143 | 'build_py': \ |
|
143 | 'build_py': \ | |
144 | check_package_data_first(git_prebuild('IPython')), |
|
144 | check_package_data_first(git_prebuild('IPython')), | |
145 | 'sdist' : git_prebuild('IPython', sdist), |
|
145 | 'sdist' : git_prebuild('IPython', sdist), | |
146 | 'symlink': install_symlinked, |
|
146 | 'symlink': install_symlinked, | |
147 | 'install_lib_symlink': install_lib_symlink, |
|
147 | 'install_lib_symlink': install_lib_symlink, | |
148 | 'install_scripts_sym': install_scripts_for_symlink, |
|
148 | 'install_scripts_sym': install_scripts_for_symlink, | |
149 | 'unsymlink': unsymlink, |
|
149 | 'unsymlink': unsymlink, | |
150 | } |
|
150 | } | |
151 |
|
151 | |||
152 |
|
152 | |||
153 | #--------------------------------------------------------------------------- |
|
153 | #--------------------------------------------------------------------------- | |
154 | # Handle scripts, dependencies, and setuptools specific things |
|
154 | # Handle scripts, dependencies, and setuptools specific things | |
155 | #--------------------------------------------------------------------------- |
|
155 | #--------------------------------------------------------------------------- | |
156 |
|
156 | |||
157 | # For some commands, use setuptools. Note that we do NOT list install here! |
|
157 | # For some commands, use setuptools. Note that we do NOT list install here! | |
158 | # If you want a setuptools-enhanced install, just run 'setupegg.py install' |
|
158 | # If you want a setuptools-enhanced install, just run 'setupegg.py install' | |
159 | needs_setuptools = {'develop', 'release', 'bdist_egg', 'bdist_rpm', |
|
159 | needs_setuptools = {'develop', 'release', 'bdist_egg', 'bdist_rpm', | |
160 | 'bdist', 'bdist_dumb', 'bdist_wininst', 'bdist_wheel', |
|
160 | 'bdist', 'bdist_dumb', 'bdist_wininst', 'bdist_wheel', | |
161 | 'egg_info', 'easy_install', 'upload', 'install_egg_info', |
|
161 | 'egg_info', 'easy_install', 'upload', 'install_egg_info', | |
162 | } |
|
162 | } | |
163 |
|
163 | |||
164 | if len(needs_setuptools.intersection(sys.argv)) > 0: |
|
164 | if len(needs_setuptools.intersection(sys.argv)) > 0: | |
165 | import setuptools |
|
165 | import setuptools | |
166 |
|
166 | |||
167 | # This dict is used for passing extra arguments that are setuptools |
|
167 | # This dict is used for passing extra arguments that are setuptools | |
168 | # specific to setup |
|
168 | # specific to setup | |
169 | setuptools_extra_args = {} |
|
169 | setuptools_extra_args = {} | |
170 |
|
170 | |||
171 | # setuptools requirements |
|
171 | # setuptools requirements | |
172 |
|
172 | |||
173 | extras_require = dict( |
|
173 | extras_require = dict( | |
174 | parallel=["ipyparallel"], |
|
174 | parallel=["ipyparallel"], | |
175 | qtconsole=["qtconsole"], |
|
175 | qtconsole=["qtconsole"], | |
176 | doc=["Sphinx>=1.3"], |
|
176 | doc=["Sphinx>=1.3"], | |
177 | test=[ |
|
177 | test=[ | |
178 | "pytest", |
|
178 | "pytest", | |
179 | "requests", |
|
|||
180 | "testpath", |
|
179 | "testpath", | |
181 | "pygments", |
|
180 | "pygments", | |
|
181 | ], | |||
|
182 | test_extra=[ | |||
|
183 | "pytest", | |||
|
184 | "testpath", | |||
|
185 | "curio", | |||
|
186 | "matplotlib!=3.2.0", | |||
182 | "nbformat", |
|
187 | "nbformat", | |
183 | "ipykernel", |
|
|||
184 | "numpy>=1.17", |
|
188 | "numpy>=1.17", | |
|
189 | "pandas", | |||
|
190 | "pygments", | |||
|
191 | "trio", | |||
185 | ], |
|
192 | ], | |
186 | terminal=[], |
|
193 | terminal=[], | |
187 | kernel=["ipykernel"], |
|
194 | kernel=["ipykernel"], | |
188 | nbformat=["nbformat"], |
|
195 | nbformat=["nbformat"], | |
189 | notebook=["notebook", "ipywidgets"], |
|
196 | notebook=["notebook", "ipywidgets"], | |
190 | nbconvert=["nbconvert"], |
|
197 | nbconvert=["nbconvert"], | |
191 | ) |
|
198 | ) | |
192 |
|
199 | |||
193 | install_requires = [ |
|
200 | install_requires = [ | |
194 | "setuptools>=18.5", |
|
201 | "setuptools>=18.5", | |
195 | "jedi>=0.16", |
|
202 | "jedi>=0.16", | |
196 | "decorator", |
|
203 | "decorator", | |
197 | "pickleshare", |
|
204 | "pickleshare", | |
198 | "traitlets>=4.2", |
|
205 | "traitlets>=4.2", | |
199 | "prompt_toolkit>=2.0.0,<3.1.0,!=3.0.0,!=3.0.1", |
|
206 | "prompt_toolkit>=2.0.0,<3.1.0,!=3.0.0,!=3.0.1", | |
200 | "pygments", |
|
207 | "pygments", | |
201 | "backcall", |
|
208 | "backcall", | |
202 | "stack_data", |
|
209 | "stack_data", | |
203 | "matplotlib-inline", |
|
210 | "matplotlib-inline", | |
204 | ] |
|
211 | ] | |
205 |
|
212 | |||
206 | # Platform-specific dependencies: |
|
213 | # Platform-specific dependencies: | |
207 | # This is the correct way to specify these, |
|
214 | # This is the correct way to specify these, | |
208 | # but requires pip >= 6. pip < 6 ignores these. |
|
215 | # but requires pip >= 6. pip < 6 ignores these. | |
209 |
|
216 | |||
210 | extras_require.update( |
|
217 | extras_require.update( | |
211 | { |
|
218 | { | |
212 | ':sys_platform != "win32"': ["pexpect>4.3"], |
|
219 | ':sys_platform != "win32"': ["pexpect>4.3"], | |
213 | ':sys_platform == "darwin"': ["appnope"], |
|
220 | ':sys_platform == "darwin"': ["appnope"], | |
214 | ':sys_platform == "win32"': ["colorama"], |
|
221 | ':sys_platform == "win32"': ["colorama"], | |
215 | } |
|
222 | } | |
216 | ) |
|
223 | ) | |
217 | # FIXME: re-specify above platform dependencies for pip < 6 |
|
224 | # FIXME: re-specify above platform dependencies for pip < 6 | |
218 | # These would result in non-portable bdists. |
|
225 | # These would result in non-portable bdists. | |
219 | if not any(arg.startswith('bdist') for arg in sys.argv): |
|
226 | if not any(arg.startswith('bdist') for arg in sys.argv): | |
220 | if sys.platform == 'darwin': |
|
227 | if sys.platform == 'darwin': | |
221 | install_requires.extend(['appnope']) |
|
228 | install_requires.extend(['appnope']) | |
222 |
|
229 | |||
223 | if not sys.platform.startswith("win"): |
|
230 | if not sys.platform.startswith("win"): | |
224 | install_requires.append("pexpect>4.3") |
|
231 | install_requires.append("pexpect>4.3") | |
225 |
|
232 | |||
226 | # workaround pypa/setuptools#147, where setuptools misspells |
|
233 | # workaround pypa/setuptools#147, where setuptools misspells | |
227 | # platform_python_implementation as python_implementation |
|
234 | # platform_python_implementation as python_implementation | |
228 | if 'setuptools' in sys.modules: |
|
235 | if 'setuptools' in sys.modules: | |
229 | for key in list(extras_require): |
|
236 | for key in list(extras_require): | |
230 | if 'platform_python_implementation' in key: |
|
237 | if 'platform_python_implementation' in key: | |
231 | new_key = key.replace('platform_python_implementation', 'python_implementation') |
|
238 | new_key = key.replace('platform_python_implementation', 'python_implementation') | |
232 | extras_require[new_key] = extras_require.pop(key) |
|
239 | extras_require[new_key] = extras_require.pop(key) | |
233 |
|
240 | |||
234 | everything = set() |
|
241 | everything = set() | |
235 | for key, deps in extras_require.items(): |
|
242 | for key, deps in extras_require.items(): | |
236 | if ':' not in key: |
|
243 | if ':' not in key: | |
237 | everything.update(deps) |
|
244 | everything.update(deps) | |
238 | extras_require['all'] = list(sorted(everything)) |
|
245 | extras_require['all'] = list(sorted(everything)) | |
239 |
|
246 | |||
240 | if 'setuptools' in sys.modules: |
|
247 | if 'setuptools' in sys.modules: | |
241 | setuptools_extra_args['python_requires'] = '>=3.7' |
|
248 | setuptools_extra_args['python_requires'] = '>=3.7' | |
242 | setuptools_extra_args['zip_safe'] = False |
|
249 | setuptools_extra_args['zip_safe'] = False | |
243 | setuptools_extra_args['entry_points'] = { |
|
250 | setuptools_extra_args['entry_points'] = { | |
244 | 'console_scripts': find_entry_points(), |
|
251 | 'console_scripts': find_entry_points(), | |
245 | 'pygments.lexers': [ |
|
252 | 'pygments.lexers': [ | |
246 | 'ipythonconsole = IPython.lib.lexers:IPythonConsoleLexer', |
|
253 | 'ipythonconsole = IPython.lib.lexers:IPythonConsoleLexer', | |
247 | 'ipython = IPython.lib.lexers:IPythonLexer', |
|
254 | 'ipython = IPython.lib.lexers:IPythonLexer', | |
248 | 'ipython3 = IPython.lib.lexers:IPython3Lexer', |
|
255 | 'ipython3 = IPython.lib.lexers:IPython3Lexer', | |
249 | ], |
|
256 | ], | |
250 | } |
|
257 | } | |
251 | setup_args['extras_require'] = extras_require |
|
258 | setup_args['extras_require'] = extras_require | |
252 | setup_args['install_requires'] = install_requires |
|
259 | setup_args['install_requires'] = install_requires | |
253 |
|
260 | |||
254 | else: |
|
261 | else: | |
255 | # scripts has to be a non-empty list, or install_scripts isn't called |
|
262 | # scripts has to be a non-empty list, or install_scripts isn't called | |
256 | setup_args['scripts'] = [e.split('=')[0].strip() for e in find_entry_points()] |
|
263 | setup_args['scripts'] = [e.split('=')[0].strip() for e in find_entry_points()] | |
257 |
|
264 | |||
258 | setup_args['cmdclass']['build_scripts'] = build_scripts_entrypt |
|
265 | setup_args['cmdclass']['build_scripts'] = build_scripts_entrypt | |
259 |
|
266 | |||
260 | #--------------------------------------------------------------------------- |
|
267 | #--------------------------------------------------------------------------- | |
261 | # Do the actual setup now |
|
268 | # Do the actual setup now | |
262 | #--------------------------------------------------------------------------- |
|
269 | #--------------------------------------------------------------------------- | |
263 |
|
270 | |||
264 | setup_args.update(setuptools_extra_args) |
|
271 | setup_args.update(setuptools_extra_args) | |
265 |
|
272 | |||
266 |
|
273 | |||
267 |
|
274 | |||
268 | def main(): |
|
275 | def main(): | |
269 | setup(**setup_args) |
|
276 | setup(**setup_args) | |
270 |
|
277 | |||
271 | if __name__ == '__main__': |
|
278 | if __name__ == '__main__': | |
272 | main() |
|
279 | main() |
General Comments 0
You need to be logged in to leave comments.
Login now