first commit

This commit is contained in:
Ayxan
2022-05-23 00:16:32 +04:00
commit d660f2a4ca
24786 changed files with 4428337 additions and 0 deletions

View File

@ -0,0 +1,80 @@
"""Test embedding of IPython"""
#-----------------------------------------------------------------------------
# Copyright (C) 2013 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import os
import sys
from IPython.testing.decorators import skip_win32
from IPython.testing import IPYTHON_TESTING_TIMEOUT_SCALE
#-----------------------------------------------------------------------------
# Tests
#-----------------------------------------------------------------------------
@skip_win32
def test_debug_magic_passes_through_generators():
"""
This test that we can correctly pass through frames of a generator post-mortem.
"""
import pexpect
import re
in_prompt = re.compile(br'In ?\[\d+\]:')
ipdb_prompt = 'ipdb>'
env = os.environ.copy()
child = pexpect.spawn(sys.executable, ['-m', 'IPython', '--colors=nocolor', '--simple-prompt'],
env=env)
child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE
child.expect(in_prompt)
child.timeout = 2 * IPYTHON_TESTING_TIMEOUT_SCALE
child.sendline("def f(x):")
child.sendline(" raise Exception")
child.sendline("")
child.expect(in_prompt)
child.sendline("gen = (f(x) for x in [0])")
child.sendline("")
child.expect(in_prompt)
child.sendline("for x in gen:")
child.sendline(" pass")
child.sendline("")
child.timeout = 10 * IPYTHON_TESTING_TIMEOUT_SCALE
child.expect('Exception:')
child.expect(in_prompt)
child.sendline(r'%debug')
child.expect('----> 2 raise Exception')
child.expect(ipdb_prompt)
child.sendline('u')
child.expect_exact(r'----> 1 gen = (f(x) for x in [0])')
child.expect(ipdb_prompt)
child.sendline('u')
child.expect_exact('----> 1 for x in gen:')
child.expect(ipdb_prompt)
child.sendline('u')
child.expect_exact('*** Oldest frame')
child.expect(ipdb_prompt)
child.sendline('exit')
child.expect(in_prompt)
child.sendline('exit')
child.close()

View File

@ -0,0 +1,138 @@
"""Test embedding of IPython"""
#-----------------------------------------------------------------------------
# Copyright (C) 2013 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import os
import subprocess
import sys
from IPython.utils.tempdir import NamedFileInTemporaryDirectory
from IPython.testing.decorators import skip_win32
from IPython.testing import IPYTHON_TESTING_TIMEOUT_SCALE
#-----------------------------------------------------------------------------
# Tests
#-----------------------------------------------------------------------------
_sample_embed = b"""
import IPython
a = 3
b = 14
print(a, '.', b)
IPython.embed()
print('bye!')
"""
_exit = b"exit\r"
def test_ipython_embed():
"""test that `IPython.embed()` works"""
with NamedFileInTemporaryDirectory('file_with_embed.py') as f:
f.write(_sample_embed)
f.flush()
f.close() # otherwise msft won't be able to read the file
# run `python file_with_embed.py`
cmd = [sys.executable, f.name]
env = os.environ.copy()
env['IPY_TEST_SIMPLE_PROMPT'] = '1'
p = subprocess.Popen(cmd, env=env, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate(_exit)
std = out.decode('UTF-8')
assert p.returncode == 0
assert "3 . 14" in std
if os.name != "nt":
# TODO: Fix up our different stdout references, see issue gh-14
assert "IPython" in std
assert "bye!" in std
@skip_win32
def test_nest_embed():
"""test that `IPython.embed()` is nestable"""
import pexpect
ipy_prompt = r']:' #ansi color codes give problems matching beyond this
env = os.environ.copy()
env['IPY_TEST_SIMPLE_PROMPT'] = '1'
child = pexpect.spawn(sys.executable, ['-m', 'IPython', '--colors=nocolor'],
env=env)
child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE
child.expect(ipy_prompt)
child.timeout = 5 * IPYTHON_TESTING_TIMEOUT_SCALE
child.sendline("import IPython")
child.expect(ipy_prompt)
child.sendline("ip0 = get_ipython()")
#enter first nested embed
child.sendline("IPython.embed()")
#skip the banner until we get to a prompt
try:
prompted = -1
while prompted != 0:
prompted = child.expect([ipy_prompt, '\r\n'])
except pexpect.TIMEOUT as e:
print(e)
#child.interact()
child.sendline("embed1 = get_ipython()")
child.expect(ipy_prompt)
child.sendline("print('true' if embed1 is not ip0 else 'false')")
assert(child.expect(['true\r\n', 'false\r\n']) == 0)
child.expect(ipy_prompt)
child.sendline("print('true' if IPython.get_ipython() is embed1 else 'false')")
assert(child.expect(['true\r\n', 'false\r\n']) == 0)
child.expect(ipy_prompt)
#enter second nested embed
child.sendline("IPython.embed()")
#skip the banner until we get to a prompt
try:
prompted = -1
while prompted != 0:
prompted = child.expect([ipy_prompt, '\r\n'])
except pexpect.TIMEOUT as e:
print(e)
#child.interact()
child.sendline("embed2 = get_ipython()")
child.expect(ipy_prompt)
child.sendline("print('true' if embed2 is not embed1 else 'false')")
assert(child.expect(['true\r\n', 'false\r\n']) == 0)
child.expect(ipy_prompt)
child.sendline("print('true' if embed2 is IPython.get_ipython() else 'false')")
assert(child.expect(['true\r\n', 'false\r\n']) == 0)
child.expect(ipy_prompt)
child.sendline('exit')
#back at first embed
child.expect(ipy_prompt)
child.sendline("print('true' if get_ipython() is embed1 else 'false')")
assert(child.expect(['true\r\n', 'false\r\n']) == 0)
child.expect(ipy_prompt)
child.sendline("print('true' if IPython.get_ipython() is embed1 else 'false')")
assert(child.expect(['true\r\n', 'false\r\n']) == 0)
child.expect(ipy_prompt)
child.sendline('exit')
#back at launching scope
child.expect(ipy_prompt)
child.sendline("print('true' if get_ipython() is ip0 else 'false')")
assert(child.expect(['true\r\n', 'false\r\n']) == 0)
child.expect(ipy_prompt)
child.sendline("print('true' if IPython.get_ipython() is ip0 else 'false')")
assert(child.expect(['true\r\n', 'false\r\n']) == 0)
child.expect(ipy_prompt)
child.sendline('exit')
child.close()

View File

@ -0,0 +1,30 @@
"""Test help output of various IPython entry points"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import pytest
import IPython.testing.tools as tt
def test_ipython_help():
tt.help_all_output_test()
def test_profile_help():
tt.help_all_output_test("profile")
def test_profile_list_help():
tt.help_all_output_test("profile list")
def test_profile_create_help():
tt.help_all_output_test("profile create")
def test_locate_help():
tt.help_all_output_test("locate")
def test_locate_profile_help():
tt.help_all_output_test("locate profile")
def test_trust_help():
pytest.importorskip("nbformat")
tt.help_all_output_test("trust")

View File

@ -0,0 +1,242 @@
# -*- coding: utf-8 -*-
"""Tests for the TerminalInteractiveShell and related pieces."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import sys
import unittest
import os
from IPython.core.inputtransformer import InputTransformer
from IPython.testing import tools as tt
from IPython.utils.capture import capture_output
from IPython.terminal.ptutils import _elide, _adjust_completion_text_based_on_context
class TestElide(unittest.TestCase):
def test_elide(self):
_elide("concatenate((a1, a2, ...), axis", "") # do not raise
_elide("concatenate((a1, a2, ..), . axis", "") # do not raise
self.assertEqual(
_elide("aaaa.bbbb.ccccc.dddddd.eeeee.fffff.gggggg.hhhhhh", ""),
"aaaa.b…g.hhhhhh",
)
test_string = os.sep.join(["", 10 * "a", 10 * "b", 10 * "c", ""])
expect_stirng = (
os.sep + "a" + "\N{HORIZONTAL ELLIPSIS}" + "b" + os.sep + 10 * "c"
)
self.assertEqual(_elide(test_string, ""), expect_stirng)
def test_elide_typed_normal(self):
self.assertEqual(
_elide(
"the quick brown fox jumped over the lazy dog",
"the quick brown fox",
min_elide=10,
),
"the…fox jumped over the lazy dog",
)
def test_elide_typed_short_match(self):
"""
if the match is too short we don't elide.
avoid the "the...the"
"""
self.assertEqual(
_elide("the quick brown fox jumped over the lazy dog", "the", min_elide=10),
"the quick brown fox jumped over the lazy dog",
)
def test_elide_typed_no_match(self):
"""
if the match is too short we don't elide.
avoid the "the...the"
"""
# here we typed red instead of brown
self.assertEqual(
_elide(
"the quick brown fox jumped over the lazy dog",
"the quick red fox",
min_elide=10,
),
"the quick brown fox jumped over the lazy dog",
)
class TestContextAwareCompletion(unittest.TestCase):
def test_adjust_completion_text_based_on_context(self):
# Adjusted case
self.assertEqual(
_adjust_completion_text_based_on_context("arg1=", "func1(a=)", 7), "arg1"
)
# Untouched cases
self.assertEqual(
_adjust_completion_text_based_on_context("arg1=", "func1(a)", 7), "arg1="
)
self.assertEqual(
_adjust_completion_text_based_on_context("arg1=", "func1(a", 7), "arg1="
)
self.assertEqual(
_adjust_completion_text_based_on_context("%magic", "func1(a=)", 7), "%magic"
)
self.assertEqual(
_adjust_completion_text_based_on_context("func2", "func1(a=)", 7), "func2"
)
# Decorator for interaction loop tests -----------------------------------------
class mock_input_helper(object):
"""Machinery for tests of the main interact loop.
Used by the mock_input decorator.
"""
def __init__(self, testgen):
self.testgen = testgen
self.exception = None
self.ip = get_ipython()
def __enter__(self):
self.orig_prompt_for_code = self.ip.prompt_for_code
self.ip.prompt_for_code = self.fake_input
return self
def __exit__(self, etype, value, tb):
self.ip.prompt_for_code = self.orig_prompt_for_code
def fake_input(self):
try:
return next(self.testgen)
except StopIteration:
self.ip.keep_running = False
return u''
except:
self.exception = sys.exc_info()
self.ip.keep_running = False
return u''
def mock_input(testfunc):
"""Decorator for tests of the main interact loop.
Write the test as a generator, yield-ing the input strings, which IPython
will see as if they were typed in at the prompt.
"""
def test_method(self):
testgen = testfunc(self)
with mock_input_helper(testgen) as mih:
mih.ip.interact()
if mih.exception is not None:
# Re-raise captured exception
etype, value, tb = mih.exception
import traceback
traceback.print_tb(tb, file=sys.stdout)
del tb # Avoid reference loop
raise value
return test_method
# Test classes -----------------------------------------------------------------
class InteractiveShellTestCase(unittest.TestCase):
def rl_hist_entries(self, rl, n):
"""Get last n readline history entries as a list"""
return [rl.get_history_item(rl.get_current_history_length() - x)
for x in range(n - 1, -1, -1)]
@mock_input
def test_inputtransformer_syntaxerror(self):
ip = get_ipython()
ip.input_transformers_post.append(syntax_error_transformer)
try:
#raise Exception
with tt.AssertPrints('4', suppress=False):
yield u'print(2*2)'
with tt.AssertPrints('SyntaxError: input contains', suppress=False):
yield u'print(2345) # syntaxerror'
with tt.AssertPrints('16', suppress=False):
yield u'print(4*4)'
finally:
ip.input_transformers_post.remove(syntax_error_transformer)
def test_repl_not_plain_text(self):
ip = get_ipython()
formatter = ip.display_formatter
assert formatter.active_types == ['text/plain']
# terminal may have arbitrary mimetype handler to open external viewer
# or inline images.
assert formatter.ipython_display_formatter.enabled
class Test(object):
def __repr__(self):
return "<Test %i>" % id(self)
def _repr_html_(self):
return '<html>'
# verify that HTML repr isn't computed
obj = Test()
data, _ = formatter.format(obj)
self.assertEqual(data, {'text/plain': repr(obj)})
class Test2(Test):
def _ipython_display_(self):
from IPython.display import display, HTML
display(HTML("<custom>"))
# verify that mimehandlers are called
called = False
def handler(data, metadata):
print("Handler called")
nonlocal called
called = True
ip.display_formatter.active_types.append("text/html")
ip.display_formatter.formatters["text/html"].enabled = True
ip.mime_renderers["text/html"] = handler
try:
obj = Test()
display(obj)
finally:
ip.display_formatter.formatters["text/html"].enabled = False
del ip.mime_renderers["text/html"]
assert called == True
def syntax_error_transformer(lines):
"""Transformer that throws SyntaxError if 'syntaxerror' is in the code."""
for line in lines:
pos = line.find('syntaxerror')
if pos >= 0:
e = SyntaxError('input contains "syntaxerror"')
e.text = line
e.offset = pos + 1
raise e
return lines
class TerminalMagicsTestCase(unittest.TestCase):
def test_paste_magics_blankline(self):
"""Test that code with a blank line doesn't get split (gh-3246)."""
ip = get_ipython()
s = ('def pasted_func(a):\n'
' b = a+1\n'
'\n'
' return b')
tm = ip.magics_manager.registry['TerminalMagics']
tm.store_or_execute(s, name=None)
self.assertEqual(ip.user_ns['pasted_func'](54), 55)