| 1 |
# coding: utf-8 |
| 2 |
"""Tests for the IPython tab-completion machinery.""" |
| 3 |
# ----------------------------------------------------------------------------- |
| 4 |
# Module imports |
| 5 |
# ----------------------------------------------------------------------------- |
| 6 |
|
| 7 |
# stdlib |
| 8 |
import io |
| 9 |
import gc |
| 10 |
import os |
| 11 |
import sys |
| 12 |
import tempfile |
| 13 |
from datetime import datetime |
| 14 |
from pathlib import Path |
| 15 |
|
| 16 |
from tempfile import TemporaryDirectory |
| 17 |
|
| 18 |
# our own packages |
| 19 |
from traitlets.config.loader import Config |
| 20 |
|
| 21 |
from IPython.core.history import HistoryAccessor, HistoryManager, extract_hist_ranges |
| 22 |
|
| 23 |
import pytest |
| 24 |
|
| 25 |
|
| 26 |
def test_proper_default_encoding(): |
| 27 |
assert sys.getdefaultencoding() == "utf-8" |
| 28 |
|
| 29 |
|
| 30 |
def hmmax_instance_maker(N: int): |
| 31 |
if os.name == "nt": |
| 32 |
|
| 33 |
@pytest.fixture() |
| 34 |
def inner(): |
| 35 |
pass |
| 36 |
|
| 37 |
else: |
| 38 |
|
| 39 |
@pytest.fixture() |
| 40 |
def inner(): |
| 41 |
assert HistoryManager._max_inst == 1 |
| 42 |
HistoryManager._max_inst = N |
| 43 |
lh = len(HistoryManager._instances) |
| 44 |
try: |
| 45 |
yield |
| 46 |
gc.collect() |
| 47 |
assert len(HistoryManager._instances) == lh |
| 48 |
finally: |
| 49 |
HistoryManager._max_inst = 1 |
| 50 |
|
| 51 |
return inner |
| 52 |
|
| 53 |
|
| 54 |
hmmax2 = hmmax_instance_maker(2) |
| 55 |
hmmax3 = hmmax_instance_maker(3) |
| 56 |
|
| 57 |
|
| 58 |
def test_history(hmmax2): |
| 59 |
ip = get_ipython() |
| 60 |
with TemporaryDirectory() as tmpdir: |
| 61 |
tmp_path = Path(tmpdir) |
| 62 |
hist_manager_ori = ip.history_manager |
| 63 |
hist_file = tmp_path / "history_test_history1.sqlite" |
| 64 |
try: |
| 65 |
ip.history_manager = HistoryManager(shell=ip, hist_file=hist_file) |
| 66 |
hist = ["a=1", "def f():\n test = 1\n return test", "b='€Æ¾÷ß'"] |
| 67 |
for i, h in enumerate(hist, start=1): |
| 68 |
ip.history_manager.store_inputs(i, h) |
| 69 |
|
| 70 |
ip.history_manager.db_log_output = True |
| 71 |
# Doesn't match the input, but we'll just check it's stored. |
| 72 |
ip.history_manager.output_hist_reprs[3] = "spam" |
| 73 |
ip.history_manager.store_output(3) |
| 74 |
|
| 75 |
assert ip.history_manager.input_hist_raw == [""] + hist |
| 76 |
|
| 77 |
# Detailed tests for _get_range_session |
| 78 |
grs = ip.history_manager._get_range_session |
| 79 |
assert list(grs(start=2, stop=-1)) == list(zip([0], [2], hist[1:-1])) |
| 80 |
assert list(grs(start=-2)) == list(zip([0, 0], [2, 3], hist[-2:])) |
| 81 |
assert list(grs(output=True)) == list( |
| 82 |
zip([0, 0, 0], [1, 2, 3], zip(hist, [None, None, "spam"])) |
| 83 |
) |
| 84 |
|
| 85 |
# Check whether specifying a range beyond the end of the current |
| 86 |
# session results in an error (gh-804) |
| 87 |
ip.run_line_magic("hist", "2-500") |
| 88 |
|
| 89 |
# Check that we can write non-ascii characters to a file |
| 90 |
ip.run_line_magic("hist", "-f %s" % (tmp_path / "test1")) |
| 91 |
ip.run_line_magic("hist", "-pf %s" % (tmp_path / "test2")) |
| 92 |
ip.run_line_magic("hist", "-nf %s" % (tmp_path / "test3")) |
| 93 |
ip.run_line_magic("save", "%s 1-10" % (tmp_path / "test4")) |
| 94 |
|
| 95 |
# New session |
| 96 |
ip.history_manager.reset() |
| 97 |
newcmds = ["z=5", "class X(object):\n pass", "k='p'", "z=5"] |
| 98 |
for i, cmd in enumerate(newcmds, start=1): |
| 99 |
ip.history_manager.store_inputs(i, cmd) |
| 100 |
gothist = ip.history_manager.get_range(start=1, stop=4) |
| 101 |
assert list(gothist) == list(zip([0, 0, 0], [1, 2, 3], newcmds)) |
| 102 |
# Previous session: |
| 103 |
gothist = ip.history_manager.get_range(-1, 1, 4) |
| 104 |
assert list(gothist) == list(zip([1, 1, 1], [1, 2, 3], hist)) |
| 105 |
|
| 106 |
newhist = [(2, i, c) for (i, c) in enumerate(newcmds, 1)] |
| 107 |
|
| 108 |
# Check get_hist_tail |
| 109 |
gothist = ip.history_manager.get_tail(5, output=True, include_latest=True) |
| 110 |
expected = [(1, 3, (hist[-1], "spam"))] + [ |
| 111 |
(s, n, (c, None)) for (s, n, c) in newhist |
| 112 |
] |
| 113 |
assert list(gothist) == expected |
| 114 |
|
| 115 |
gothist = ip.history_manager.get_tail(2) |
| 116 |
expected = newhist[-3:-1] |
| 117 |
assert list(gothist) == expected |
| 118 |
|
| 119 |
# Check get_hist_search |
| 120 |
|
| 121 |
gothist = ip.history_manager.search("*test*") |
| 122 |
assert list(gothist) == [(1, 2, hist[1])] |
| 123 |
|
| 124 |
gothist = ip.history_manager.search("*=*") |
| 125 |
assert list(gothist) == [ |
| 126 |
(1, 1, hist[0]), |
| 127 |
(1, 2, hist[1]), |
| 128 |
(1, 3, hist[2]), |
| 129 |
newhist[0], |
| 130 |
newhist[2], |
| 131 |
newhist[3], |
| 132 |
] |
| 133 |
|
| 134 |
gothist = ip.history_manager.search("*=*", n=4) |
| 135 |
assert list(gothist) == [ |
| 136 |
(1, 3, hist[2]), |
| 137 |
newhist[0], |
| 138 |
newhist[2], |
| 139 |
newhist[3], |
| 140 |
] |
| 141 |
|
| 142 |
gothist = ip.history_manager.search("*=*", unique=True) |
| 143 |
assert list(gothist) == [ |
| 144 |
(1, 1, hist[0]), |
| 145 |
(1, 2, hist[1]), |
| 146 |
(1, 3, hist[2]), |
| 147 |
newhist[2], |
| 148 |
newhist[3], |
| 149 |
] |
| 150 |
|
| 151 |
gothist = ip.history_manager.search("*=*", unique=True, n=3) |
| 152 |
assert list(gothist) == [(1, 3, hist[2]), newhist[2], newhist[3]] |
| 153 |
|
| 154 |
gothist = ip.history_manager.search("b*", output=True) |
| 155 |
assert list(gothist) == [(1, 3, (hist[2], "spam"))] |
| 156 |
|
| 157 |
# Cross testing: check that magic %save can get previous session. |
| 158 |
testfilename = (tmp_path / "test.py").resolve() |
| 159 |
ip.run_line_magic("save", str(testfilename) + " ~1/1-3") |
| 160 |
with io.open(testfilename, encoding="utf-8") as testfile: |
| 161 |
assert testfile.read() == "# coding: utf-8\n" + "\n".join(hist) + "\n" |
| 162 |
|
| 163 |
# Duplicate line numbers - check that it doesn't crash, and |
| 164 |
# gets a new session |
| 165 |
ip.history_manager.store_inputs(1, "rogue") |
| 166 |
ip.history_manager.writeout_cache() |
| 167 |
assert ip.history_manager.session_number == 3 |
| 168 |
|
| 169 |
# Check that session and line values are not just max values |
| 170 |
sessid, lineno, entry = newhist[-1] |
| 171 |
assert lineno > 1 |
| 172 |
ip.history_manager.reset() |
| 173 |
lineno = 1 |
| 174 |
ip.history_manager.store_inputs(lineno, entry) |
| 175 |
gothist = ip.history_manager.search("*=*", unique=True) |
| 176 |
hist = list(gothist)[-1] |
| 177 |
assert sessid < hist[0] |
| 178 |
assert hist[1:] == (lineno, entry) |
| 179 |
finally: |
| 180 |
# Ensure saving thread is shut down before we try to clean up the files |
| 181 |
ip.history_manager.end_session() |
| 182 |
# Forcibly close database rather than relying on garbage collection |
| 183 |
ip.history_manager.save_thread.stop() |
| 184 |
ip.history_manager.db.close() |
| 185 |
# swap back |
| 186 |
ip.history_manager = hist_manager_ori |
| 187 |
|
| 188 |
|
| 189 |
def test_extract_hist_ranges(): |
| 190 |
instr = "1 2/3 ~4/5-6 ~4/7-~4/9 ~9/2-~7/5 ~10/" |
| 191 |
expected = [ |
| 192 |
(0, 1, 2), # 0 == current session |
| 193 |
(2, 3, 4), |
| 194 |
(-4, 5, 7), |
| 195 |
(-4, 7, 10), |
| 196 |
(-9, 2, None), # None == to end |
| 197 |
(-8, 1, None), |
| 198 |
(-7, 1, 6), |
| 199 |
(-10, 1, None), |
| 200 |
] |
| 201 |
actual = list(extract_hist_ranges(instr)) |
| 202 |
assert actual == expected |
| 203 |
|
| 204 |
|
| 205 |
def test_extract_hist_ranges_empty_str(): |
| 206 |
instr = "" |
| 207 |
expected = [(0, 1, None)] # 0 == current session, None == to end |
| 208 |
actual = list(extract_hist_ranges(instr)) |
| 209 |
assert actual == expected |
| 210 |
|
| 211 |
|
| 212 |
@pytest.mark.parametrize( |
| 213 |
"instr,expected,description", |
| 214 |
[ |
| 215 |
("21-23", [(0, 21, 24)], "Just line numbers"), |
| 216 |
("25-", [(0, 25, None)], "Line start, no end"), |
| 217 |
("~4/", [(-4, 1, None)], "with trailing slash"), |
| 218 |
# ("~4", [(-4, 1, None)], "without trailing slash"), |
| 219 |
("~4/1-5", [(-4, 1, 6)], "with line ranges and trailing slash"), |
| 220 |
( |
| 221 |
"~4/1- ~5/ ~6/1-3", |
| 222 |
[(-4, 1, None), (-5, 1, None), (-6, 1, 4)], |
| 223 |
"multiple sessions with mixed syntax", |
| 224 |
), |
| 225 |
("~10/ ~20/", [(-10, 1, None), (-20, 1, None)], "larger session numbers"), |
| 226 |
# ("~1", [(-1, 1, None)], "single digit session without slash"), |
| 227 |
("~1/", [(-1, 1, None)], "single digit session with slash"), |
| 228 |
# ("~2", [(-2, 1, None)], "backward compatibility without slash"), |
| 229 |
("~2/", [(-2, 1, None)], "backward compatibility with slash"), |
| 230 |
("4-", [(0, 4, None)], "from line 4 onward in current session"), |
| 231 |
("~4/4-", [(-4, 4, None)], "from line 4 onward in session 4"), |
| 232 |
("2/4-", [(2, 4, None)], "from line 4 onward in session 2"), |
| 233 |
("~5/10-", [(-5, 10, None)], "from line 10 onward in session 5"), |
| 234 |
], |
| 235 |
) |
| 236 |
def test_misc_extract_hist_ranges(instr, expected, description): |
| 237 |
actual = list(extract_hist_ranges(instr)) |
| 238 |
assert ( |
| 239 |
actual == expected |
| 240 |
), f"Failed for '{instr}' ({description}): expected {expected}, got {actual}" |
| 241 |
|
| 242 |
|
| 243 |
def test_magic_rerun(): |
| 244 |
"""Simple test for %rerun (no args -> rerun last line)""" |
| 245 |
ip = get_ipython() |
| 246 |
ip.run_cell("a = 10", store_history=True) |
| 247 |
ip.run_cell("a += 1", store_history=True) |
| 248 |
assert ip.user_ns["a"] == 11 |
| 249 |
ip.run_cell("%rerun", store_history=True) |
| 250 |
assert ip.user_ns["a"] == 12 |
| 251 |
|
| 252 |
|
| 253 |
def test_timestamp_type(): |
| 254 |
ip = get_ipython() |
| 255 |
info = ip.history_manager.get_session_info() |
| 256 |
assert isinstance(info[1], datetime) |
| 257 |
|
| 258 |
|
| 259 |
def test_hist_file_config(hmmax3): |
| 260 |
cfg = Config() |
| 261 |
tfile = tempfile.NamedTemporaryFile(delete=False) |
| 262 |
cfg.HistoryManager.hist_file = Path(tfile.name) |
| 263 |
try: |
| 264 |
hm = HistoryManager(shell=get_ipython(), config=cfg) |
| 265 |
assert hm.hist_file == cfg.HistoryManager.hist_file |
| 266 |
finally: |
| 267 |
try: |
| 268 |
Path(tfile.name).unlink() |
| 269 |
except OSError: |
| 270 |
# same catch as in testing.tools.TempFileMixin |
| 271 |
# On Windows, even though we close the file, we still can't |
| 272 |
# delete it. I have no clue why |
| 273 |
pass |
| 274 |
HistoryManager.__max_inst = 1 |
| 275 |
|
| 276 |
|
| 277 |
def test_histmanager_disabled(hmmax2): |
| 278 |
"""Ensure that disabling the history manager doesn't create a database.""" |
| 279 |
cfg = Config() |
| 280 |
cfg.HistoryAccessor.enabled = False |
| 281 |
|
| 282 |
ip = get_ipython() |
| 283 |
with TemporaryDirectory() as tmpdir: |
| 284 |
hist_manager_ori = ip.history_manager |
| 285 |
hist_file = Path(tmpdir) / "history.sqlite" |
| 286 |
cfg.HistoryManager.hist_file = hist_file |
| 287 |
try: |
| 288 |
ip.history_manager = HistoryManager(shell=ip, config=cfg) |
| 289 |
hist = ["a=1", "def f():\n test = 1\n return test", "b='€Æ¾÷ß'"] |
| 290 |
for i, h in enumerate(hist, start=1): |
| 291 |
ip.history_manager.store_inputs(i, h) |
| 292 |
assert ip.history_manager.input_hist_raw == [""] + hist |
| 293 |
ip.history_manager.reset() |
| 294 |
ip.history_manager.end_session() |
| 295 |
finally: |
| 296 |
ip.history_manager = hist_manager_ori |
| 297 |
|
| 298 |
# hist_file should not be created |
| 299 |
assert hist_file.exists() is False |
| 300 |
|
| 301 |
|
| 302 |
def test_get_tail_session_awareness(hmmax3): |
| 303 |
"""Test .get_tail() is: |
| 304 |
- session specific in HistoryManager |
| 305 |
- session agnostic in HistoryAccessor |
| 306 |
same for .get_last_session_id() |
| 307 |
""" |
| 308 |
with TemporaryDirectory() as tmpdir: |
| 309 |
ip = get_ipython() |
| 310 |
tmp_path = Path(tmpdir) |
| 311 |
hist_file = tmp_path / "history.sqlite" |
| 312 |
get_source = lambda x: x[2] |
| 313 |
hm1 = None |
| 314 |
hm2 = None |
| 315 |
ha = None |
| 316 |
try: |
| 317 |
# hm1 creates a new session and adds history entries, |
| 318 |
# ha catches up |
| 319 |
hm1 = HistoryManager(shell=ip, hist_file=hist_file) |
| 320 |
hm1_last_sid = hm1.get_last_session_id |
| 321 |
ha = HistoryAccessor(hist_file=hist_file) |
| 322 |
ha_last_sid = ha.get_last_session_id |
| 323 |
|
| 324 |
hist1 = ["a=1", "b=1", "c=1"] |
| 325 |
for i, h in enumerate(hist1 + [""], start=1): |
| 326 |
hm1.store_inputs(i, h) |
| 327 |
assert list(map(get_source, hm1.get_tail())) == hist1 |
| 328 |
assert list(map(get_source, ha.get_tail())) == hist1 |
| 329 |
sid1 = hm1_last_sid() |
| 330 |
assert sid1 is not None |
| 331 |
assert ha_last_sid() == sid1 |
| 332 |
|
| 333 |
# hm2 creates a new session and adds entries, |
| 334 |
# ha catches up |
| 335 |
hm2 = HistoryManager(shell=ip, hist_file=hist_file) |
| 336 |
hm2_last_sid = hm2.get_last_session_id |
| 337 |
|
| 338 |
hist2 = ["a=2", "b=2", "c=2"] |
| 339 |
for i, h in enumerate(hist2 + [""], start=1): |
| 340 |
hm2.store_inputs(i, h) |
| 341 |
tail = hm2.get_tail(n=3) |
| 342 |
assert list(map(get_source, tail)) == hist2 |
| 343 |
tail = ha.get_tail(n=3) |
| 344 |
assert list(map(get_source, tail)) == hist2 |
| 345 |
sid2 = hm2_last_sid() |
| 346 |
assert sid2 is not None |
| 347 |
assert ha_last_sid() == sid2 |
| 348 |
assert sid2 != sid1 |
| 349 |
|
| 350 |
# but hm1 still maintains its point of reference |
| 351 |
# and adding more entries to it doesn't change others |
| 352 |
# immediate perspective |
| 353 |
assert hm1_last_sid() == sid1 |
| 354 |
tail = hm1.get_tail(n=3) |
| 355 |
assert list(map(get_source, tail)) == hist1 |
| 356 |
|
| 357 |
hist3 = ["a=3", "b=3", "c=3"] |
| 358 |
for i, h in enumerate(hist3 + [""], start=5): |
| 359 |
hm1.store_inputs(i, h) |
| 360 |
tail = hm1.get_tail(n=7) |
| 361 |
assert list(map(get_source, tail)) == hist1 + [""] + hist3 |
| 362 |
tail = hm2.get_tail(n=3) |
| 363 |
assert list(map(get_source, tail)) == hist2 |
| 364 |
tail = ha.get_tail(n=3) |
| 365 |
assert list(map(get_source, tail)) == hist2 |
| 366 |
assert hm1_last_sid() == sid1 |
| 367 |
assert hm2_last_sid() == sid2 |
| 368 |
assert ha_last_sid() == sid2 |
| 369 |
finally: |
| 370 |
if hm1: |
| 371 |
hm1.save_thread.stop() |
| 372 |
hm1.db.close() |
| 373 |
if hm2: |
| 374 |
hm2.save_thread.stop() |
| 375 |
hm2.db.close() |
| 376 |
if ha: |
| 377 |
ha.db.close() |
| 378 |
|
| 379 |
|
| 380 |
def test_calling_run_cell(hmmax2): |
| 381 |
ip = get_ipython() |
| 382 |
with TemporaryDirectory() as tmpdir: |
| 383 |
tmp_path = Path(tmpdir) |
| 384 |
hist_manager_ori = ip.history_manager |
| 385 |
hist_file = tmp_path / "history_test_history1.sqlite" |
| 386 |
try: |
| 387 |
ip.history_manager = HistoryManager(shell=ip, hist_file=hist_file) |
| 388 |
import time |
| 389 |
|
| 390 |
session_number = ip.history_manager.session_number |
| 391 |
ip.run_cell(raw_cell="get_ipython().run_cell(raw_cell='1', store_history=True)", store_history=True) |
| 392 |
while ip.history_manager.db_input_cache: |
| 393 |
time.sleep(0) |
| 394 |
new_session_number = ip.history_manager.session_number |
| 395 |
finally: |
| 396 |
# Ensure saving thread is shut down before we try to clean up the files |
| 397 |
ip.history_manager.end_session() |
| 398 |
# Forcibly close database rather than relying on garbage collection |
| 399 |
ip.history_manager.save_thread.stop() |
| 400 |
ip.history_manager.db.close() |
| 401 |
|
| 402 |
ip.history_manager = hist_manager_ori |
| 403 |
assert session_number == new_session_number, ValueError(f"{session_number} != {new_session_number}") |