ipython / ipython
Showing 46 of 49 files from the diff.
Other files ignored by Codecov
MANIFEST.in has changed.
setup.py has changed.

@@ -1,5 +1,3 @@
Loading
1 -
import nose.tools as nt
2 -
3 1
from IPython.core.error import TryNext
4 2
from IPython.lib.clipboard import ClipboardEmpty
5 3
from IPython.testing.decorators import skip_if_no_x11
@@ -18,4 +16,4 @@
Loading
18 16
        # No clipboard access API available
19 17
        pass
20 18
    else:
21 -
        nt.assert_is_instance(a, str)
19 +
        assert isinstance(a, str)

@@ -22,8 +22,6 @@
Loading
22 22
23 23
import IPython.utils.module_paths as mp
24 24
25 -
import nose.tools as nt
26 -
27 25
TEST_FILE_PATH = Path(__file__).resolve().parent
28 26
29 27
TMP_TEST_DIR = Path(tempfile.mkdtemp(suffix="with.dot"))
@@ -67,7 +65,7 @@
Loading
67 65
    """
68 66
    Ensure the test are done with a temporary file that have a dot somewhere.
69 67
    """
70 -
    nt.assert_in(".", str(TMP_TEST_DIR))
68 +
    assert "." in str(TMP_TEST_DIR)
71 69
72 70
73 71
def test_find_mod_1():
@@ -76,7 +74,7 @@
Loading
76 74
    Expected output: a path to that directory's __init__.py file.
77 75
    """
78 76
    modpath = TMP_TEST_DIR / "xmod" / "__init__.py"
79 -
    nt.assert_equal(Path(mp.find_mod("xmod")), modpath)
77 +
    assert Path(mp.find_mod("xmod")) == modpath
80 78
81 79
def test_find_mod_2():
82 80
    """
@@ -85,7 +83,7 @@
Loading
85 83
    TODO: Confirm why this is a duplicate test.
86 84
    """
87 85
    modpath = TMP_TEST_DIR / "xmod" / "__init__.py"
88 -
    nt.assert_equal(Path(mp.find_mod("xmod")), modpath)
86 +
    assert Path(mp.find_mod("xmod")) == modpath
89 87
90 88
def test_find_mod_3():
91 89
    """
@@ -93,7 +91,7 @@
Loading
93 91
    Expected output: full path with .py extension.
94 92
    """
95 93
    modpath = TMP_TEST_DIR / "xmod" / "sub.py"
96 -
    nt.assert_equal(Path(mp.find_mod("xmod.sub")), modpath)
94 +
    assert Path(mp.find_mod("xmod.sub")) == modpath
97 95
98 96
def test_find_mod_4():
99 97
    """
@@ -101,11 +99,11 @@
Loading
101 99
    Expected output: full path with .py extension
102 100
    """
103 101
    modpath = TMP_TEST_DIR / "pack.py"
104 -
    nt.assert_equal(Path(mp.find_mod("pack")), modpath)
102 +
    assert Path(mp.find_mod("pack")) == modpath
105 103
106 104
def test_find_mod_5():
107 105
    """
108 106
    Search for a filename with a .pyc extension
109 107
    Expected output: TODO: do we exclude or include .pyc files?
110 108
    """
111 -
    nt.assert_equal(mp.find_mod("packpyc"), None)
109 +
    assert mp.find_mod("packpyc") == None

@@ -27,8 +27,6 @@
Loading
27 27
from pathlib import Path
28 28
from unittest import TestCase
29 29
30 -
import nose.tools as nt
31 -
32 30
from IPython.core.profileapp import list_profiles_in, list_bundled_profiles
33 31
from IPython.core.profiledir import ProfileDir
34 32
@@ -79,7 +77,7 @@
Loading
79 77
        except ImportError:
80 78
            return True
81 79
    return False
82 -
    
80 +
83 81
84 82
class ProfileStartupTest(TestCase):
85 83
    def setUp(self):
@@ -114,7 +112,7 @@
Loading
114 112
        self.init('00-start.ipy', '%xmode plain\n', '')
115 113
        self.validate('Exception reporting mode: Plain')
116 114
117 -
    
115 +
118 116
def test_list_profiles_in():
119 117
    # No need to remove these directories and files, as they will get nuked in
120 118
    # the module-level teardown.
@@ -127,7 +125,7 @@
Loading
127 125
    with open(td / "profile_file", "w") as f:
128 126
        f.write("I am not a profile directory")
129 127
    profiles = list_profiles_in(td)
130 -
    
128 +
131 129
    # unicode normalization can turn u'ünicode' into u'u\0308nicode',
132 130
    # so only check for *nicode, and that creating a ProfileDir from the
133 131
    # name remains valid
@@ -139,14 +137,14 @@
Loading
139 137
            found_unicode = True
140 138
            break
141 139
    if dec.unicode_paths:
142 -
        nt.assert_true(found_unicode)
143 -
    nt.assert_equal(set(profiles), {'foo', 'hello'})
140 +
        assert found_unicode is True
141 +
    assert set(profiles) == {"foo", "hello"}
144 142
145 143
146 144
def test_list_bundled_profiles():
147 145
    # This variable will need to be updated when a new profile gets bundled
148 146
    bundled = sorted(list_bundled_profiles())
149 -
    nt.assert_equal(bundled, [])
147 +
    assert bundled == []
150 148
151 149
152 150
def test_profile_create_ipython_dir():
@@ -167,4 +165,3 @@
Loading
167 165
        assert Path(profile_dir).exists()
168 166
        ipython_config = profile_dir / "ipython_config.py"
169 167
        assert Path(ipython_config).exists()
170 -
        

@@ -5,7 +5,6 @@
Loading
5 5
from contextlib import contextmanager
6 6
from unittest.mock import patch
7 7
8 -
import nose.tools as nt
9 8
import pytest
10 9
11 10
from IPython.lib import latextools
@@ -185,7 +184,13 @@
Loading
185 184
    Test that invalid hex colors provided to dvipng gives an exception.
186 185
    """
187 186
    latex_string = "$x^2$"
188 -
    nt.assert_raises(ValueError, lambda: latextools.latex_to_png(latex_string,
189 -
                                        backend='dvipng', color="#f00bar"))
190 -
    nt.assert_raises(ValueError, lambda: latextools.latex_to_png(latex_string,
191 -
                                        backend='dvipng', color="#f00"))
187 +
    pytest.raises(
188 +
        ValueError,
189 +
        lambda: latextools.latex_to_png(
190 +
            latex_string, backend="dvipng", color="#f00bar"
191 +
        ),
192 +
    )
193 +
    pytest.raises(
194 +
        ValueError,
195 +
        lambda: latextools.latex_to_png(latex_string, backend="dvipng", color="#f00"),
196 +
    )

@@ -12,29 +12,42 @@
Loading
12 12
from IPython.utils.capture import capture_output
13 13
14 14
from IPython.terminal.ptutils import _elide, _adjust_completion_text_based_on_context
15 -
import nose.tools as nt
16 15
17 -
class TestElide(unittest.TestCase):
18 16
17 +
class TestElide(unittest.TestCase):
19 18
    def test_elide(self):
20 -
        _elide('concatenate((a1, a2, ...), axis', '') # do not raise
21 -
        _elide('concatenate((a1, a2, ..), . axis', '') # do not raise
22 -
        nt.assert_equal(_elide('aaaa.bbbb.ccccc.dddddd.eeeee.fffff.gggggg.hhhhhh',''), 'aaaa.b…g.hhhhhh')
23 -
24 -
        test_string = os.sep.join(['', 10*'a', 10*'b', 10*'c', ''])
25 -
        expect_stirng = os.sep + 'a' + '\N{HORIZONTAL ELLIPSIS}' + 'b' + os.sep + 10*'c'
26 -
        nt.assert_equal(_elide(test_string, ''), expect_stirng)
19 +
        _elide("concatenate((a1, a2, ...), axis", "")  # do not raise
20 +
        _elide("concatenate((a1, a2, ..), . axis", "")  # do not raise
21 +
        self.assertEqual(
22 +
            _elide("aaaa.bbbb.ccccc.dddddd.eeeee.fffff.gggggg.hhhhhh", ""),
23 +
            "aaaa.b…g.hhhhhh",
24 +
        )
25 +
26 +
        test_string = os.sep.join(["", 10 * "a", 10 * "b", 10 * "c", ""])
27 +
        expect_stirng = (
28 +
            os.sep + "a" + "\N{HORIZONTAL ELLIPSIS}" + "b" + os.sep + 10 * "c"
29 +
        )
30 +
        self.assertEqual(_elide(test_string, ""), expect_stirng)
27 31
28 32
    def test_elide_typed_normal(self):
29 -
        nt.assert_equal(_elide('the quick brown fox jumped over the lazy dog', 'the quick brown fox', min_elide=10), 'the…fox jumped over the lazy dog')
30 -
33 +
        self.assertEqual(
34 +
            _elide(
35 +
                "the quick brown fox jumped over the lazy dog",
36 +
                "the quick brown fox",
37 +
                min_elide=10,
38 +
            ),
39 +
            "the…fox jumped over the lazy dog",
40 +
        )
31 41
32 42
    def test_elide_typed_short_match(self):
33 43
        """
34 44
        if the match is too short we don't elide.
35 45
        avoid the "the...the"
36 46
        """
37 -
        nt.assert_equal(_elide('the quick brown fox jumped over the lazy dog', 'the', min_elide=10), 'the quick brown fox jumped over the lazy dog')
47 +
        self.assertEqual(
48 +
            _elide("the quick brown fox jumped over the lazy dog", "the", min_elide=10),
49 +
            "the quick brown fox jumped over the lazy dog",
50 +
        )
38 51
39 52
    def test_elide_typed_no_match(self):
40 53
        """
@@ -42,22 +55,41 @@
Loading
42 55
        avoid the "the...the"
43 56
        """
44 57
        # here we typed red instead of brown
45 -
        nt.assert_equal(_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')
58 +
        self.assertEqual(
59 +
            _elide(
60 +
                "the quick brown fox jumped over the lazy dog",
61 +
                "the quick red fox",
62 +
                min_elide=10,
63 +
            ),
64 +
            "the quick brown fox jumped over the lazy dog",
65 +
        )
46 66
47 -
class TestContextAwareCompletion(unittest.TestCase):
48 67
68 +
class TestContextAwareCompletion(unittest.TestCase):
49 69
    def test_adjust_completion_text_based_on_context(self):
50 70
        # Adjusted case
51 -
        nt.assert_equal(_adjust_completion_text_based_on_context('arg1=', 'func1(a=)', 7), 'arg1')
71 +
        self.assertEqual(
72 +
            _adjust_completion_text_based_on_context("arg1=", "func1(a=)", 7), "arg1"
73 +
        )
52 74
53 75
        # Untouched cases
54 -
        nt.assert_equal(_adjust_completion_text_based_on_context('arg1=', 'func1(a)', 7), 'arg1=')
55 -
        nt.assert_equal(_adjust_completion_text_based_on_context('arg1=', 'func1(a', 7), 'arg1=')
56 -
        nt.assert_equal(_adjust_completion_text_based_on_context('%magic', 'func1(a=)', 7), '%magic')
57 -
        nt.assert_equal(_adjust_completion_text_based_on_context('func2', 'func1(a=)', 7), 'func2')
76 +
        self.assertEqual(
77 +
            _adjust_completion_text_based_on_context("arg1=", "func1(a)", 7), "arg1="
78 +
        )
79 +
        self.assertEqual(
80 +
            _adjust_completion_text_based_on_context("arg1=", "func1(a", 7), "arg1="
81 +
        )
82 +
        self.assertEqual(
83 +
            _adjust_completion_text_based_on_context("%magic", "func1(a=)", 7), "%magic"
84 +
        )
85 +
        self.assertEqual(
86 +
            _adjust_completion_text_based_on_context("func2", "func1(a=)", 7), "func2"
87 +
        )
88 +
58 89
59 90
# Decorator for interaction loop tests -----------------------------------------
60 91
92 +
61 93
class mock_input_helper(object):
62 94
    """Machinery for tests of the main interact loop.
63 95

@@ -6,9 +6,6 @@
Loading
6 6
import inspect
7 7
import sys
8 8
9 -
# Third party
10 -
import nose.tools as nt
11 -
12 9
# Our own
13 10
from IPython.testing import decorators as dec
14 11
from IPython.testing.skipdoctest import skip_doctest
@@ -95,7 +92,7 @@
Loading
95 92
    # Fetch the docstring from doctest_bad after decoration.
96 93
    val = doctest_bad.__doc__
97 94
    
98 -
    nt.assert_equal(check,val,"doctest_bad docstrings don't match")
95 +
    assert check == val, "doctest_bad docstrings don't match"
99 96
100 97
101 98
# Doctest skipping should work for class methods too
@@ -156,13 +153,14 @@
Loading
156 153
157 154
@dec.skip_linux
158 155
def test_linux():
159 -
    nt.assert_false(sys.platform.startswith('linux'),"This test can't run under linux")
156 +
    assert sys.platform.startswith("linux") is False, "This test can't run under linux"
157 +
160 158
161 159
@dec.skip_win32
162 160
def test_win32():
163 -
    nt.assert_not_equal(sys.platform,'win32',"This test can't run under windows")
161 +
    assert sys.platform != "win32", "This test can't run under windows"
162 +
164 163
165 164
@dec.skip_osx
166 165
def test_osx():
167 -
    nt.assert_not_equal(sys.platform,'darwin',"This test can't run under osx")
168 -
166 +
    assert sys.platform != "darwin", "This test can't run under osx"

@@ -6,7 +6,6 @@
Loading
6 6
import warnings
7 7
from unittest.mock import patch
8 8
9 -
import nose.tools as nt
10 9
from testpath import modified_env, assert_isdir, assert_isfile
11 10
12 11
from IPython import paths
@@ -52,7 +51,7 @@
Loading
52 51
            modified_env({'IPYTHONDIR': env_ipdir}):
53 52
        ipdir = paths.get_ipython_dir()
54 53
55 -
    nt.assert_equal(ipdir, env_ipdir)
54 +
    assert ipdir == env_ipdir
56 55
57 56
def test_get_ipython_dir_2():
58 57
    """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions."""
@@ -66,7 +65,7 @@
Loading
66 65
                         }):
67 66
        ipdir = paths.get_ipython_dir()
68 67
69 -
    nt.assert_equal(ipdir, os.path.join("someplace", ".ipython"))
68 +
    assert ipdir == os.path.join("someplace", ".ipython")
70 69
71 70
def test_get_ipython_dir_3():
72 71
    """test_get_ipython_dir_3, move XDG if defined, and .ipython doesn't exist."""
@@ -81,10 +80,10 @@
Loading
81 80
                }), warnings.catch_warnings(record=True) as w:
82 81
            ipdir = paths.get_ipython_dir()
83 82
84 -
        nt.assert_equal(ipdir, os.path.join(tmphome.name, ".ipython"))
83 +
        assert ipdir == os.path.join(tmphome.name, ".ipython")
85 84
        if sys.platform != 'darwin':
86 -
            nt.assert_equal(len(w), 1)
87 -
            nt.assert_in('Moving', str(w[0]))
85 +
            assert len(w) == 1
86 +
            assert "Moving" in str(w[0])
88 87
    finally:
89 88
        tmphome.cleanup()
90 89
@@ -106,10 +105,11 @@
Loading
106 105
        }), warnings.catch_warnings(record=True) as w:
107 106
            ipdir = paths.get_ipython_dir()
108 107
109 -
        nt.assert_equal(ipdir, os.path.join(HOME_TEST_DIR, ".ipython"))
108 +
        assert ipdir == os.path.join(HOME_TEST_DIR, ".ipython")
110 109
        if sys.platform != 'darwin':
111 -
            nt.assert_equal(len(w), 1)
112 -
            nt.assert_in('Ignoring', str(w[0]))
110 +
            assert len(w) == 1
111 +
            assert "Ignoring" in str(w[0])
112 +
113 113
114 114
def test_get_ipython_dir_5():
115 115
    """test_get_ipython_dir_5, use .ipython if exists and XDG defined, but doesn't exist."""
@@ -128,7 +128,7 @@
Loading
128 128
        }):
129 129
            ipdir = paths.get_ipython_dir()
130 130
131 -
        nt.assert_equal(ipdir, IP_TEST_DIR)
131 +
        assert ipdir == IP_TEST_DIR
132 132
133 133
def test_get_ipython_dir_6():
134 134
    """test_get_ipython_dir_6, use home over XDG if defined and neither exist."""
@@ -146,8 +146,8 @@
Loading
146 146
            }), warnings.catch_warnings(record=True) as w:
147 147
        ipdir = paths.get_ipython_dir()
148 148
149 -
    nt.assert_equal(ipdir, os.path.join(HOME_TEST_DIR, '.ipython'))
150 -
    nt.assert_equal(len(w), 0)
149 +
    assert ipdir == os.path.join(HOME_TEST_DIR, ".ipython")
150 +
    assert len(w) == 0
151 151
152 152
def test_get_ipython_dir_7():
153 153
    """test_get_ipython_dir_7, test home directory expansion on IPYTHONDIR"""
@@ -155,7 +155,8 @@
Loading
155 155
    with modified_env({'IPYTHONDIR': os.path.join('~', 'somewhere')}), \
156 156
            patch.object(paths, '_writable_dir', return_value=True):
157 157
        ipdir = paths.get_ipython_dir()
158 -
    nt.assert_equal(ipdir, os.path.join(home_dir, 'somewhere'))
158 +
    assert ipdir == os.path.join(home_dir, "somewhere")
159 +
159 160
160 161
@skip_win32
161 162
def test_get_ipython_dir_8():
@@ -164,14 +165,16 @@
Loading
164 165
        # test only when HOME directory actually writable
165 166
        return
166 167
167 -
    with patch.object(paths, '_writable_dir', lambda path: bool(path)), \
168 -
            patch.object(paths, 'get_xdg_dir', return_value=None), \
169 -
            modified_env({
170 -
                'IPYTHON_DIR': None,
171 -
                'IPYTHONDIR': None,
172 -
                'HOME': '/',
173 -
            }):
174 -
        nt.assert_equal(paths.get_ipython_dir(), '/.ipython')
168 +
    with patch.object(paths, "_writable_dir", lambda path: bool(path)), patch.object(
169 +
        paths, "get_xdg_dir", return_value=None
170 +
    ), modified_env(
171 +
        {
172 +
            "IPYTHON_DIR": None,
173 +
            "IPYTHONDIR": None,
174 +
            "HOME": "/",
175 +
        }
176 +
    ):
177 +
        assert paths.get_ipython_dir() == "/.ipython"
175 178
176 179
177 180
def test_get_ipython_cache_dir():
@@ -181,18 +184,16 @@
Loading
181 184
            os.makedirs(os.path.join(HOME_TEST_DIR, ".cache"))
182 185
            with modified_env({'XDG_CACHE_HOME': None}):
183 186
                ipdir = paths.get_ipython_cache_dir()
184 -
            nt.assert_equal(os.path.join(HOME_TEST_DIR, ".cache", "ipython"),
185 -
                            ipdir)
187 +
            assert os.path.join(HOME_TEST_DIR, ".cache", "ipython") == ipdir
186 188
            assert_isdir(ipdir)
187 189
188 190
            # test env override
189 191
            with modified_env({"XDG_CACHE_HOME": XDG_CACHE_DIR}):
190 192
                ipdir = paths.get_ipython_cache_dir()
191 193
            assert_isdir(ipdir)
192 -
            nt.assert_equal(ipdir, os.path.join(XDG_CACHE_DIR, "ipython"))
194 +
            assert ipdir == os.path.join(XDG_CACHE_DIR, "ipython")
193 195
        else:
194 -
            nt.assert_equal(paths.get_ipython_cache_dir(),
195 -
                            paths.get_ipython_dir())
196 +
            assert paths.get_ipython_cache_dir() == paths.get_ipython_dir()
196 197
197 198
def test_get_ipython_package_dir():
198 199
    ipdir = paths.get_ipython_package_dir()

@@ -5,7 +5,6 @@
Loading
5 5
# Distributed under the terms of the Modified BSD License.
6 6
7 7
import json
8 -
import nose.tools as nt
9 8
10 9
from IPython.utils import sysinfo
11 10

@@ -1,6 +1,5 @@
Loading
1 1
import unittest
2 2
from unittest.mock import Mock
3 -
import nose.tools as nt
4 3
5 4
from IPython.core import events
6 5
import IPython.testing.tools as tt
@@ -40,9 +39,9 @@
Loading
40 39
        def cb2():
41 40
            ...
42 41
43 -
        self.em.register('ping_received', cb1)
44 -
        nt.assert_raises(ValueError, self.em.unregister, 'ping_received', cb2)
45 -
        self.em.unregister('ping_received', cb1)
42 +
        self.em.register("ping_received", cb1)
43 +
        self.assertRaises(ValueError, self.em.unregister, "ping_received", cb2)
44 +
        self.em.unregister("ping_received", cb1)
46 45
47 46
    def test_cb_error(self):
48 47
        cb = Mock(side_effect=ValueError)

@@ -1,6 +1,5 @@
Loading
1 1
import io
2 2
import os.path
3 -
import nose.tools as nt
4 3
5 4
from IPython.utils import openpy
6 5
@@ -11,14 +10,14 @@
Loading
11 10
def test_detect_encoding():
12 11
    with open(nonascii_path, "rb") as f:
13 12
        enc, lines = openpy.detect_encoding(f.readline)
14 -
    nt.assert_equal(enc, "iso-8859-5")
13 +
    assert enc == "iso-8859-5"
15 14
16 15
17 16
def test_read_file():
18 17
    with io.open(nonascii_path, encoding="iso-8859-5") as f:
19 18
        read_specified_enc = f.read()
20 19
    read_detected_enc = openpy.read_py_file(nonascii_path, skip_encoding_cookie=False)
21 -
    nt.assert_equal(read_detected_enc, read_specified_enc)
20 +
    assert read_detected_enc == read_specified_enc
22 21
    assert "coding: iso-8859-5" in read_detected_enc
23 22
24 23
    read_strip_enc_cookie = openpy.read_py_file(
@@ -30,10 +29,10 @@
Loading
30 29
def test_source_to_unicode():
31 30
    with io.open(nonascii_path, "rb") as f:
32 31
        source_bytes = f.read()
33 -
    nt.assert_equal(
34 -
        openpy.source_to_unicode(source_bytes, skip_encoding_cookie=False).splitlines(),
35 -
        source_bytes.decode("iso-8859-5").splitlines(),
32 +
    assert (
33 +
        openpy.source_to_unicode(source_bytes, skip_encoding_cookie=False).splitlines()
34 +
        == source_bytes.decode("iso-8859-5").splitlines()
36 35
    )
37 36
38 37
    source_no_cookie = openpy.source_to_unicode(source_bytes, skip_encoding_cookie=True)
39 -
    nt.assert_not_in("coding: iso-8859-5", source_no_cookie)
38 +
    assert "coding: iso-8859-5" not in source_no_cookie

@@ -4,8 +4,6 @@
Loading
4 4
import os
5 5
import tempfile
6 6
7 -
import nose.tools as nt
8 -
9 7
from traitlets import Unicode
10 8
11 9
from IPython.core.application import BaseIPythonApplication
@@ -65,9 +63,8 @@
Loading
65 63
            f.write("c.TestApp.test = 'config file'")
66 64
67 65
        app = TestApp()
68 -
        app.initialize(['--profile-dir', td])
69 -
        nt.assert_equal(app.test, 'config file')
66 +
        app.initialize(["--profile-dir", td])
67 +
        assert app.test == "config file"
70 68
        app = TestApp()
71 -
        app.initialize(['--profile-dir', td, '--TestApp.test=cli'])
72 -
        nt.assert_equal(app.test, 'cli')
73 -
69 +
        app.initialize(["--profile-dir", td, "--TestApp.test=cli"])
70 +
        assert app.test == "cli"

@@ -15,7 +15,7 @@
Loading
15 15
from imp import reload
16 16
17 17
from nose import SkipTest, with_setup
18 -
import nose.tools as nt
18 +
import pytest
19 19
20 20
import IPython
21 21
from IPython import paths
@@ -155,7 +155,7 @@
Loading
155 155
    env['HOME'] = abspath(HOME_TEST_DIR+'garbage')
156 156
    # set os.name = posix, to prevent My Documents fallback on Windows
157 157
    os.name = 'posix'
158 -
    nt.assert_raises(path.HomeDirError, path.get_home_dir, True)
158 +
    pytest.raises(path.HomeDirError, path.get_home_dir, True)
159 159
160 160
# Should we stub wreg fully so we can run the test on all platforms?
161 161
@skip_if_not_win32
@@ -237,8 +237,7 @@
Loading
237 237
    env.pop('IPYTHONDIR', None)
238 238
    env.pop('XDG_CONFIG_HOME', None)
239 239
    cfgdir=os.path.join(path.get_home_dir(), '.config')
240 -
    if not os.path.exists(cfgdir):
241 -
        os.makedirs(cfgdir)
240 +
    os.makedirs(cfgdir, exist_ok=True)
242 241
243 242
    assert path.get_xdg_dir() is None
244 243
@@ -305,15 +304,15 @@
Loading
305 304
        assert path.get_py_filename("foo") == "foo.py"
306 305
    with make_tempfile("foo"):
307 306
        assert path.get_py_filename("foo") == "foo"
308 -
        nt.assert_raises(IOError, path.get_py_filename, "foo.py")
309 -
    nt.assert_raises(IOError, path.get_py_filename, "foo")
310 -
    nt.assert_raises(IOError, path.get_py_filename, "foo.py")
307 +
        pytest.raises(IOError, path.get_py_filename, "foo.py")
308 +
    pytest.raises(IOError, path.get_py_filename, "foo")
309 +
    pytest.raises(IOError, path.get_py_filename, "foo.py")
311 310
    true_fn = "foo with spaces.py"
312 311
    with make_tempfile(true_fn):
313 312
        assert path.get_py_filename("foo with spaces") == true_fn
314 313
        assert path.get_py_filename("foo with spaces.py") == true_fn
315 -
        nt.assert_raises(IOError, path.get_py_filename, '"foo with spaces.py"')
316 -
        nt.assert_raises(IOError, path.get_py_filename, "'foo with spaces.py'")
314 +
        pytest.raises(IOError, path.get_py_filename, '"foo with spaces.py"')
315 +
        pytest.raises(IOError, path.get_py_filename, "'foo with spaces.py'")
317 316
318 317
@onlyif_unicode_paths
319 318
def test_unicode_in_filename():
@@ -414,7 +413,7 @@
Loading
414 413
        path.ensure_dir_exists(d) # no-op
415 414
        f = os.path.join(td, 'ƒile')
416 415
        open(f, 'w').close() # touch
417 -
        with nt.assert_raises(IOError):
416 +
        with pytest.raises(IOError):
418 417
            path.ensure_dir_exists(f)
419 418
420 419
class TestLinkOrCopy(unittest.TestCase):

@@ -11,8 +11,6 @@
Loading
11 11
from subprocess import Popen, PIPE
12 12
import unittest
13 13
14 -
import nose.tools as nt
15 -
16 14
from IPython.utils.io import IOStream, Tee, capture_output
17 15
18 16
@@ -22,7 +20,7 @@
Loading
22 20
    text = 'Hello'
23 21
    tee = Tee(chan, channel='stdout')
24 22
    print(text, file=chan)
25 -
    nt.assert_equal(chan.getvalue(), text+"\n")
23 +
    assert chan.getvalue() == text + "\n"
26 24
27 25
28 26
class TeeTestCase(unittest.TestCase):
@@ -39,7 +37,7 @@
Loading
39 37
40 38
        print(text, end='', file=chan)
41 39
        trap_val = trap.getvalue()
42 -
        nt.assert_equal(chan.getvalue(), text)
40 +
        self.assertEqual(chan.getvalue(), text)
43 41
44 42
        tee.close()
45 43
@@ -82,8 +80,8 @@
Loading
82 80
        """capture_output() context works"""
83 81
        
84 82
        with capture_output() as io:
85 -
            print('hi, stdout')
86 -
            print('hi, stderr', file=sys.stderr)
87 -
        
88 -
        nt.assert_equal(io.stdout, 'hi, stdout\n')
89 -
        nt.assert_equal(io.stderr, 'hi, stderr\n')
83 +
            print("hi, stdout")
84 +
            print("hi, stderr", file=sys.stderr)
85 +
86 +
        self.assertEqual(io.stdout, "hi, stdout\n")
87 +
        self.assertEqual(io.stderr, "hi, stderr\n")

@@ -11,7 +11,7 @@
Loading
11 11
# Imports
12 12
#-----------------------------------------------------------------------------
13 13
14 -
import nose.tools as nt
14 +
import pytest
15 15
16 16
from IPython.utils.importstring import import_item
17 17
@@ -22,18 +22,19 @@
Loading
22 22
def test_import_plain():
23 23
    "Test simple imports"
24 24
    import os
25 -
    os2 = import_item('os')
26 -
    nt.assert_true(os is os2)
25 +
26 +
    os2 = import_item("os")
27 +
    assert os is os2
27 28
28 29
29 30
def test_import_nested():
30 31
    "Test nested imports from the stdlib"
31 32
    from os import path
32 -
    path2 = import_item('os.path')
33 -
    nt.assert_true(path is path2)
33 +
34 +
    path2 = import_item("os.path")
35 +
    assert path is path2
34 36
35 37
36 38
def test_import_raises():
37 39
    "Test that failing imports raise the right exception"
38 -
    nt.assert_raises(ImportError, import_item, 'IPython.foobar')
39 -
    
40 +
    pytest.raises(ImportError, import_item, "IPython.foobar")

@@ -18,8 +18,6 @@
Loading
18 18
from textwrap import dedent
19 19
from unittest.mock import patch
20 20
21 -
import nose.tools as nt
22 -
23 21
from IPython.core import debugger
24 22
from IPython.testing import IPYTHON_TESTING_TIMEOUT_SCALE
25 23
from IPython.testing.decorators import skip_win32
@@ -66,13 +64,13 @@
Loading
66 64
    a = '1234567890'* 7
67 65
    ar = "'1234567890123456789012345678901234567890123456789012345678901234567890'"
68 66
    a_trunc = "'123456789012...8901234567890'"
69 -
    nt.assert_equal(trepr(a), a_trunc)
67 +
    assert trepr(a) == a_trunc
70 68
    # The creation of our tracer modifies the repr module's repr function
71 69
    # in-place, since that global is used directly by the stdlib's pdb module.
72 70
    with warnings.catch_warnings():
73 71
        warnings.simplefilter('ignore', DeprecationWarning)
74 72
        debugger.Tracer()
75 -
    nt.assert_equal(trepr(a), ar)
73 +
    assert trepr(a) == ar
76 74
77 75
def test_ipdb_magics():
78 76
    '''Test calling some IPython magics from ipdb.

@@ -17,8 +17,6 @@
Loading
17 17
from textwrap import dedent
18 18
from unittest import TestCase, mock
19 19
20 -
import nose.tools as nt
21 -
22 20
import pytest
23 21
24 22
from IPython import get_ipython
@@ -47,18 +45,20 @@
Loading
47 45
48 46
def test_extract_code_ranges():
49 47
    instr = "1 3 5-6 7-9 10:15 17: :10 10- -13 :"
50 -
    expected = [(0, 1), 
51 -
                (2, 3),
52 -
                (4, 6),
53 -
                (6, 9),
54 -
                (9, 14),
55 -
                (16, None),
56 -
                (None, 9),
57 -
                (9, None),
58 -
                (None, 13),
59 -
                (None, None)]
48 +
    expected = [
49 +
        (0, 1),
50 +
        (2, 3),
51 +
        (4, 6),
52 +
        (6, 9),
53 +
        (9, 14),
54 +
        (16, None),
55 +
        (None, 9),
56 +
        (9, None),
57 +
        (None, 13),
58 +
        (None, None),
59 +
    ]
60 60
    actual = list(code.extract_code_ranges(instr))
61 -
    nt.assert_equal(actual, expected)
61 +
    assert actual == expected
62 62
63 63
def test_extract_symbols():
64 64
    source = """import foo\na = 10\ndef b():\n    return 42\n\n\nclass A: pass\n\n\n"""
@@ -70,7 +70,7 @@
Loading
70 70
                (["class A: pass\n"], ['a']),
71 71
                ([], ['z'])]
72 72
    for symbols, exp in zip(symbols_args, expected):
73 -
        nt.assert_equal(code.extract_symbols(source, symbols), exp)
73 +
        assert code.extract_symbols(source, symbols) == exp
74 74
75 75
76 76
def test_extract_symbols_raises_exception_with_non_python_code():
@@ -78,13 +78,13 @@
Loading
78 78
              "def hello\n"
79 79
              "puts 'Hello world'\n"
80 80
              "end")
81 -
    with nt.assert_raises(SyntaxError):
81 +
    with pytest.raises(SyntaxError):
82 82
        code.extract_symbols(source, "hello")
83 83
84 84
85 85
def test_magic_not_found():
86 86
    # magic not found raises UsageError
87 -
    with nt.assert_raises(UsageError):
87 +
    with pytest.raises(UsageError):
88 88
        _ip.magic('doesntexist')
89 89
90 90
    # ensure result isn't success when a magic isn't found
@@ -94,7 +94,7 @@
Loading
94 94
95 95
def test_cell_magic_not_found():
96 96
    # magic not found raises UsageError
97 -
    with nt.assert_raises(UsageError):
97 +
    with pytest.raises(UsageError):
98 98
        _ip.run_cell_magic('doesntexist', 'line', 'cell')
99 99
100 100
    # ensure result isn't success when a magic isn't found
@@ -127,7 +127,7 @@
Loading
127 127
128 128
    stdout = captured.stdout
129 129
    config_classes = stdout.strip().split('\n')[1:]
130 -
    nt.assert_list_equal(config_classes, sorted(set(config_classes)))
130 +
    assert config_classes == sorted(set(config_classes))
131 131
132 132
def test_config_print_class():
133 133
    """ test that config with a classname prints the class's options. """
@@ -144,19 +144,18 @@
Loading
144 144
    # clear up everything
145 145
    _ip.alias_manager.clear_aliases()
146 146
    del _ip.db['syscmdlist']
147 -
    
147 +
148 148
    _ip.magic('rehashx')
149 149
    # Practically ALL ipython development systems will have more than 10 aliases
150 150
151 -
    nt.assert_true(len(_ip.alias_manager.aliases) > 10)
151 +
    assert len(_ip.alias_manager.aliases) > 10
152 152
    for name, cmd in _ip.alias_manager.aliases:
153 153
        # we must strip dots from alias names
154 -
        nt.assert_not_in('.', name)
154 +
        assert "." not in name
155 155
156 156
    # rehashx must fill up syscmdlist
157 157
    scoms = _ip.db['syscmdlist']
158 -
    nt.assert_true(len(scoms) > 10)
159 -
            
158 +
    assert len(scoms) > 10
160 159
161 160
162 161
def test_magic_parse_options():
@@ -170,16 +169,17 @@
Loading
170 169
        expected = 'c:x'
171 170
    else:
172 171
        expected = path
173 -
    nt.assert_equal(opts['f'], expected)
172 +
    assert opts["f"] == expected
173 +
174 174
175 175
def test_magic_parse_long_options():
176 176
    """Magic.parse_options can handle --foo=bar long options"""
177 177
    ip = get_ipython()
178 178
    m = DummyMagics(ip)
179 -
    opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
180 -
    nt.assert_in('foo', opts)
181 -
    nt.assert_in('bar', opts)
182 -
    nt.assert_equal(opts['bar'], "bubble")
179 +
    opts, _ = m.parse_options("--foo --bar=bubble", "a", "foo", "bar=")
180 +
    assert "foo" in opts
181 +
    assert "bar" in opts
182 +
    assert opts["bar"] == "bubble"
183 183
184 184
185 185
def doctest_hist_f():
@@ -200,24 +200,24 @@
Loading
200 200
201 201
    In [1]: class b(float):
202 202
       ...:     pass
203 -
       ...: 
203 +
       ...:
204 204
205 205
    In [2]: class s(object):
206 206
       ...:     def __str__(self):
207 207
       ...:         return 's'
208 -
       ...: 
208 +
       ...:
209 209
210 -
    In [3]: 
210 +
    In [3]:
211 211
212 212
    In [4]: class r(b):
213 213
       ...:     def __repr__(self):
214 214
       ...:         return 'r'
215 -
       ...: 
215 +
       ...:
216 216
217 217
    In [5]: class sr(s,r): pass
218 -
       ...: 
218 +
       ...:
219 219
220 -
    In [6]: 
220 +
    In [6]:
221 221
222 222
    In [7]: bb=b()
223 223
@@ -233,23 +233,23 @@
Loading
233 233
    In [12]: str(ss)
234 234
    Out[12]: 's'
235 235
236 -
    In [13]: 
236 +
    In [13]:
237 237
238 238
    In [14]: %hist -op
239 239
    >>> class b:
240 240
    ...     pass
241 -
    ... 
241 +
    ...
242 242
    >>> class s(b):
243 243
    ...     def __str__(self):
244 244
    ...         return 's'
245 -
    ... 
246 -
    >>> 
245 +
    ...
246 +
    >>>
247 247
    >>> class r(b):
248 248
    ...     def __repr__(self):
249 249
    ...         return 'r'
250 -
    ... 
250 +
    ...
251 251
    >>> class sr(s,r): pass
252 -
    >>> 
252 +
    >>>
253 253
    >>> bb=b()
254 254
    >>> ss=s()
255 255
    >>> rr=r()
@@ -258,12 +258,12 @@
Loading
258 258
    4.5
259 259
    >>> str(ss)
260 260
    's'
261 -
    >>> 
261 +
    >>>
262 262
    """
263 263
264 264
def test_hist_pof():
265 265
    ip = get_ipython()
266 -
    ip.run_cell(u"1+2", store_history=True)
266 +
    ip.run_cell("1+2", store_history=True)
267 267
    #raise Exception(ip.history_manager.session_number)
268 268
    #raise Exception(list(ip.history_manager._get_range_session()))
269 269
    with TemporaryDirectory() as td:
@@ -279,10 +279,10 @@
Loading
279 279
    for i, cmd in enumerate(cmds, start=1):
280 280
        ip.history_manager.store_inputs(i, cmd)
281 281
    ip.magic("macro test 1-3")
282 -
    nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
283 -
    
282 +
    assert ip.user_ns["test"].value == "\n".join(cmds) + "\n"
283 +
284 284
    # List macros
285 -
    nt.assert_in("test", ip.magic("macro"))
285 +
    assert "test" in ip.magic("macro")
286 286
287 287
288 288
def test_macro_run():
@@ -292,7 +292,7 @@
Loading
292 292
    cmds = ["a=10", "a+=1", "print(a)", "%macro test 2-3"]
293 293
    for cmd in cmds:
294 294
        ip.run_cell(cmd, store_history=True)
295 -
    nt.assert_equal(ip.user_ns["test"].value, "a+=1\nprint(a)\n")
295 +
    assert ip.user_ns["test"].value == "a+=1\nprint(a)\n"
296 296
    with tt.AssertPrints("12"):
297 297
        ip.run_cell("test")
298 298
    with tt.AssertPrints("13"):
@@ -304,56 +304,61 @@
Loading
304 304
    ip = get_ipython()
305 305
    with capture_output() as captured:
306 306
        ip.magic("magic")
307 -
    
307 +
308 308
    stdout = captured.stdout
309 -
    nt.assert_in('%magic', stdout)
310 -
    nt.assert_in('IPython', stdout)
311 -
    nt.assert_in('Available', stdout)
309 +
    assert "%magic" in stdout
310 +
    assert "IPython" in stdout
311 +
    assert "Available" in stdout
312 312
313 313
314 314
@dec.skipif_not_numpy
315 315
def test_numpy_reset_array_undec():
316 316
    "Test '%reset array' functionality"
317 -
    _ip.ex('import numpy as np')
318 -
    _ip.ex('a = np.empty(2)')
319 -
    nt.assert_in('a', _ip.user_ns)
320 -
    _ip.magic('reset -f array')
321 -
    nt.assert_not_in('a', _ip.user_ns)
317 +
    _ip.ex("import numpy as np")
318 +
    _ip.ex("a = np.empty(2)")
319 +
    assert "a" in _ip.user_ns
320 +
    _ip.magic("reset -f array")
321 +
    assert "a" not in _ip.user_ns
322 +
322 323
323 324
def test_reset_out():
324 325
    "Test '%reset out' magic"
325 326
    _ip.run_cell("parrot = 'dead'", store_history=True)
326 327
    # test '%reset -f out', make an Out prompt
327 328
    _ip.run_cell("parrot", store_history=True)
328 -
    nt.assert_true('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
329 -
    _ip.magic('reset -f out')
330 -
    nt.assert_false('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
331 -
    nt.assert_equal(len(_ip.user_ns['Out']), 0)
329 +
    assert "dead" in [_ip.user_ns[x] for x in ("_", "__", "___")]
330 +
    _ip.magic("reset -f out")
331 +
    assert "dead" not in [_ip.user_ns[x] for x in ("_", "__", "___")]
332 +
    assert len(_ip.user_ns["Out"]) == 0
333 +
332 334
333 335
def test_reset_in():
334 336
    "Test '%reset in' magic"
335 337
    # test '%reset -f in'
336 338
    _ip.run_cell("parrot", store_history=True)
337 -
    nt.assert_true('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
338 -
    _ip.magic('%reset -f in')
339 -
    nt.assert_false('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
340 -
    nt.assert_equal(len(set(_ip.user_ns['In'])), 1)
339 +
    assert "parrot" in [_ip.user_ns[x] for x in ("_i", "_ii", "_iii")]
340 +
    _ip.magic("%reset -f in")
341 +
    assert "parrot" not in [_ip.user_ns[x] for x in ("_i", "_ii", "_iii")]
342 +
    assert len(set(_ip.user_ns["In"])) == 1
343 +
341 344
342 345
def test_reset_dhist():
343 346
    "Test '%reset dhist' magic"
344 -
    _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
345 -
    _ip.magic('cd ' + os.path.dirname(nt.__file__))
346 -
    _ip.magic('cd -')
347 -
    nt.assert_true(len(_ip.user_ns['_dh']) > 0)
348 -
    _ip.magic('reset -f dhist')
349 -
    nt.assert_equal(len(_ip.user_ns['_dh']), 0)
350 -
    _ip.run_cell("_dh = [d for d in tmp]") #restore
347 +
    _ip.run_cell("tmp = [d for d in _dh]")  # copy before clearing
348 +
    _ip.magic("cd " + os.path.dirname(pytest.__file__))
349 +
    _ip.magic("cd -")
350 +
    assert len(_ip.user_ns["_dh"]) > 0
351 +
    _ip.magic("reset -f dhist")
352 +
    assert len(_ip.user_ns["_dh"]) == 0
353 +
    _ip.run_cell("_dh = [d for d in tmp]")  # restore
354 +
351 355
352 356
def test_reset_in_length():
353 357
    "Test that '%reset in' preserves In[] length"
354 358
    _ip.run_cell("print 'foo'")
355 359
    _ip.run_cell("reset -f in")
356 -
    nt.assert_equal(len(_ip.user_ns['In']), _ip.displayhook.prompt_count+1)
360 +
    assert len(_ip.user_ns["In"]) == _ip.displayhook.prompt_count + 1
361 +
357 362
358 363
class TestResetErrors(TestCase):
359 364
@@ -384,7 +389,7 @@
Loading
384 389
    """test %tb after a SyntaxError"""
385 390
    ip = get_ipython()
386 391
    ip.run_cell("for")
387 -
    
392 +
388 393
    # trap and validate stdout
389 394
    save_stdout = sys.stdout
390 395
    try:
@@ -395,18 +400,18 @@
Loading
395 400
        sys.stdout = save_stdout
396 401
    # trim output, and only check the last line
397 402
    last_line = out.rstrip().splitlines()[-1].strip()
398 -
    nt.assert_equal(last_line, "SyntaxError: invalid syntax")
403 +
    assert last_line == "SyntaxError: invalid syntax"
399 404
400 405
401 406
def test_time():
402 407
    ip = get_ipython()
403 -
    
408 +
404 409
    with tt.AssertPrints("Wall time: "):
405 410
        ip.run_cell("%time None")
406 -
    
411 +
407 412
    ip.run_cell("def f(kmjy):\n"
408 413
                "    %time print (2*kmjy)")
409 -
    
414 +
410 415
    with tt.AssertPrints("Wall time: "):
411 416
        with tt.AssertPrints("hihi", suppress=False):
412 417
            ip.run_cell("f('hi')")
@@ -419,12 +424,12 @@
Loading
419 424
    del ip.user_ns['var_1']
420 425
    assert ip.user_ns['var_2'] == 2
421 426
    del ip.user_ns['var_2']
422 -
    
427 +
423 428
424 429
@dec.skip_win32
425 430
def test_time2():
426 431
    ip = get_ipython()
427 -
    
432 +
428 433
    with tt.AssertPrints("CPU times: user "):
429 434
        ip.run_cell("%time None")
430 435
@@ -432,7 +437,7 @@
Loading
432 437
    """Erroneous magic function calls, issue gh-3334"""
433 438
    ip = get_ipython()
434 439
    ip.user_ns.pop('run', None)
435 -
    
440 +
436 441
    with tt.AssertNotPrints("not found", channel='stderr'):
437 442
        ip.run_cell("%%time\n"
438 443
                    "run = 0\n"
@@ -448,18 +453,21 @@
Loading
448 453
        a = "ho"
449 454
        b = "hey"
450 455
        a+b
451 -
        """))
452 -
    nt.assert_equal(ip.user_ns_hidden['_'], 'hohey')
456 +
        """
457 +
        )
458 +
    )
459 +
    assert ip.user_ns_hidden["_"] == "hohey"
460 +
453 461
454 462
def test_time_local_ns():
455 463
    """
456 464
    Test that local_ns is actually global_ns when running a cell magic
457 465
    """
458 466
    ip = get_ipython()
459 -
    ip.run_cell("%%time\n"
460 -
                "myvar = 1")
461 -
    nt.assert_equal(ip.user_ns['myvar'], 1)
462 -
    del ip.user_ns['myvar']
467 +
    ip.run_cell("%%time\n" "myvar = 1")
468 +
    assert ip.user_ns["myvar"] == 1
469 +
    del ip.user_ns["myvar"]
470 +
463 471
464 472
def test_doctest_mode():
465 473
    "Toggle doctest_mode twice, it should be a no-op and run without error"
@@ -472,8 +480,8 @@
Loading
472 480
    # These are only the most minimal of tests, more should be added later.  At
473 481
    # the very least we check that basic text/unicode calls work OK.
474 482
    m = DummyMagics(_ip)
475 -
    nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
476 -
    nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
483 +
    assert m.parse_options("foo", "")[1] == "foo"
484 +
    assert m.parse_options("foo", "")[1] == "foo"
477 485
478 486
479 487
def test_parse_options_preserve_non_option_string():
@@ -482,8 +490,8 @@
Loading
482 490
    opts, stmt = m.parse_options(
483 491
        " -n1  -r 13 _ = 314 + foo", "n:r:", preserve_non_opts=True
484 492
    )
485 -
    nt.assert_equal(opts, {"n": "1", "r": "13"})
486 -
    nt.assert_equal(stmt, "_ = 314 + foo")
493 +
    assert opts == {"n": "1", "r": "13"}
494 +
    assert stmt == "_ = 314 + foo"
487 495
488 496
489 497
def test_run_magic_preserve_code_block():
@@ -501,13 +509,13 @@
Loading
501 509
    ipdir = os.path.realpath(_ip.ipython_dir)
502 510
    try:
503 511
        _ip.magic('cd "%s"' % ipdir)
504 -
        nt.assert_equal(curpath(), ipdir)
512 +
        assert curpath() == ipdir
505 513
        _ip.magic('cd -')
506 -
        nt.assert_equal(curpath(), startdir)
514 +
        assert curpath() == startdir
507 515
        _ip.magic('pushd "%s"' % ipdir)
508 -
        nt.assert_equal(curpath(), ipdir)
516 +
        assert curpath() == ipdir
509 517
        _ip.magic('popd')
510 -
        nt.assert_equal(curpath(), startdir)
518 +
        assert curpath() == startdir
511 519
    finally:
512 520
        os.chdir(startdir)
513 521
@@ -534,8 +542,8 @@
Loading
534 542
    xmode = _ip.InteractiveTB.mode
535 543
    for i in range(4):
536 544
        _ip.magic("xmode")
537 -
    nt.assert_equal(_ip.InteractiveTB.mode, xmode)
538 -
    
545 +
    assert _ip.InteractiveTB.mode == xmode
546 +
539 547
def test_reset_hard():
540 548
    monitor = []
541 549
    class A(object):
@@ -543,14 +551,14 @@
Loading
543 551
            monitor.append(1)
544 552
        def __repr__(self):
545 553
            return "<A instance>"
546 -
            
554 +
547 555
    _ip.user_ns["a"] = A()
548 556
    _ip.run_cell("a")
549 -
    
550 -
    nt.assert_equal(monitor, [])
557 +
558 +
    assert monitor == []
551 559
    _ip.magic("reset -f")
552 -
    nt.assert_equal(monitor, [1])
553 -
    
560 +
    assert monitor == [1]
561 +
554 562
class TestXdel(tt.TempFileMixin):
555 563
    def test_xdel(self):
556 564
        """Test that references from %run are cleared by xdel."""
@@ -564,36 +572,36 @@
Loading
564 572
        _ip.magic("run %s" % self.fname)
565 573
        # ... as does the displayhook.
566 574
        _ip.run_cell("a")
567 -
        
575 +
568 576
        monitor = _ip.user_ns["A"].monitor
569 -
        nt.assert_equal(monitor, [])
570 -
        
577 +
        assert monitor == []
578 +
571 579
        _ip.magic("xdel a")
572 -
        
580 +
573 581
        # Check that a's __del__ method has been called.
574 -
        nt.assert_equal(monitor, [1])
582 +
        assert monitor == [1]
575 583
576 584
def doctest_who():
577 585
    """doctest for %who
578 -
    
586 +
579 587
    In [1]: %reset -f
580 -
    
588 +
581 589
    In [2]: alpha = 123
582 -
    
590 +
583 591
    In [3]: beta = 'beta'
584 -
    
592 +
585 593
    In [4]: %who int
586 594
    alpha
587 -
    
595 +
588 596
    In [5]: %who str
589 597
    beta
590 -
    
598 +
591 599
    In [6]: %whos
592 600
    Variable   Type    Data/Info
593 601
    ----------------------------
594 602
    alpha      int     123
595 603
    beta       str     beta
596 -
    
604 +
597 605
    In [7]: %who_ls
598 606
    Out[7]: ['alpha', 'beta']
599 607
    """
@@ -608,25 +616,25 @@
Loading
608 616
609 617
def doctest_precision():
610 618
    """doctest for %precision
611 -
    
619 +
612 620
    In [1]: f = get_ipython().display_formatter.formatters['text/plain']
613 -
    
621 +
614 622
    In [2]: %precision 5
615 623
    Out[2]: '%.5f'
616 -
    
624 +
617 625
    In [3]: f.float_format
618 626
    Out[3]: '%.5f'
619 -
    
627 +
620 628
    In [4]: %precision %e
621 629
    Out[4]: '%e'
622 -
    
630 +
623 631
    In [5]: f(3.1415927)
624 632
    Out[5]: '3.141593e+00'
625 633
    """
626 634
627 635
def test_debug_magic():
628 636
    """Test debugging a small code with %debug
629 -
    
637 +
630 638
    In [1]: with PdbTestInput(['c']):
631 639
       ...:     %debug print("a b") #doctest: +ELLIPSIS
632 640
       ...:
@@ -661,11 +669,12 @@
Loading
661 669
        ip.user_ns['lmagic_out'] = line
662 670
663 671
    # line mode test
664 -
    _ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line')
665 -
    nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
672 +
    _ip.run_line_magic("timeit", "-n1 -r1 %lmagic my line")
673 +
    assert _ip.user_ns["lmagic_out"] == "my line"
666 674
    # cell mode test
667 -
    _ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2')
668 -
    nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
675 +
    _ip.run_cell_magic("timeit", "-n1 -r1", "%lmagic my line2")
676 +
    assert _ip.user_ns["lmagic_out"] == "my line2"
677 +
669 678
670 679
def test_timeit_return():
671 680
    """
@@ -688,7 +697,7 @@
Loading
688 697
    assert (res is not None)
689 698
690 699
def test_timeit_invalid_return():
691 -
    with nt.assert_raises_regex(SyntaxError, "outside function"):
700 +
    with pytest.raises(SyntaxError):
692 701
        _ip.run_line_magic('timeit', 'return')
693 702
694 703
@dec.skipif(execution.profile is None)
@@ -700,17 +709,19 @@
Loading
700 709
        ip.user_ns['lmagic_out'] = line
701 710
702 711
    # line mode test
703 -
    _ip.run_line_magic('prun', '-q %lmagic my line')
704 -
    nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
712 +
    _ip.run_line_magic("prun", "-q %lmagic my line")
713 +
    assert _ip.user_ns["lmagic_out"] == "my line"
705 714
    # cell mode test
706 -
    _ip.run_cell_magic('prun', '-q', '%lmagic my line2')
707 -
    nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
715 +
    _ip.run_cell_magic("prun", "-q", "%lmagic my line2")
716 +
    assert _ip.user_ns["lmagic_out"] == "my line2"
717 +
708 718
709 719
@dec.skipif(execution.profile is None)
710 720
def test_prun_quotes():
711 721
    "Test that prun does not clobber string escapes (GH #1302)"
712 722
    _ip.magic(r"prun -q x = '\t'")
713 -
    nt.assert_equal(_ip.user_ns['x'], '\t')
723 +
    assert _ip.user_ns["x"] == "\t"
724 +
714 725
715 726
def test_extension():
716 727
    # Debugging information for failures of this test
@@ -719,14 +730,14 @@
Loading
719 730
        print(' ', p)
720 731
    print('CWD', os.getcwd())
721 732
722 -
    nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
733 +
    pytest.raises(ImportError, _ip.magic, "load_ext daft_extension")
723 734
    daft_path = os.path.join(os.path.dirname(__file__), "daft_extension")
724 735
    sys.path.insert(0, daft_path)
725 736
    try:
726 737
        _ip.user_ns.pop('arq', None)
727 738
        invalidate_caches()   # Clear import caches
728 739
        _ip.magic("load_ext daft_extension")
729 -
        nt.assert_equal(_ip.user_ns['arq'], 185)
740 +
        assert _ip.user_ns["arq"] == 185
730 741
        _ip.magic("unload_ext daft_extension")
731 742
        assert 'arq' not in _ip.user_ns
732 743
    finally:
@@ -736,7 +747,7 @@
Loading
736 747
def test_notebook_export_json():
737 748
    _ip = get_ipython()
738 749
    _ip.history_manager.reset()   # Clear any existing history.
739 -
    cmds = [u"a=1", u"def b():\n  return a**2", u"print('noël, été', b())"]
750 +
    cmds = ["a=1", "def b():\n  return a**2", "print('noël, été', b())"]
740 751
    for i, cmd in enumerate(cmds, start=1):
741 752
        _ip.history_manager.store_inputs(i, cmd)
742 753
    with TemporaryDirectory() as td:
@@ -797,11 +808,11 @@
Loading
797 808
798 809
    def check_ident(self, magic):
799 810
        # Manually called, we get the result
800 -
        out = _ip.run_cell_magic(magic, 'a', 'b')
801 -
        nt.assert_equal(out, ('a','b'))
811 +
        out = _ip.run_cell_magic(magic, "a", "b")
812 +
        assert out == ("a", "b")
802 813
        # Via run_cell, it goes into the user's namespace via displayhook
803 -
        _ip.run_cell('%%' + magic +' c\nd\n')
804 -
        nt.assert_equal(_ip.user_ns['_'], ('c','d\n'))
814 +
        _ip.run_cell("%%" + magic + " c\nd\n")
815 +
        assert _ip.user_ns["_"] == ("c", "d\n")
805 816
806 817
    def test_cell_magic_func_deco(self):
807 818
        "Cell magic using simple decorator"
@@ -839,12 +850,12 @@
Loading
839 850
            @cell_magic('cellm4')
840 851
            def cellm33(self, line, cell):
841 852
                return line, cell
842 -
            
853 +
843 854
        _ip.register_magics(MyMagics2)
844 855
        self.check_ident('cellm4')
845 856
        # Check that nothing is registered as 'cellm33'
846 857
        c33 = _ip.find_cell_magic('cellm33')
847 -
        nt.assert_equal(c33, None)
858 +
        assert c33 == None
848 859
849 860
def test_file():
850 861
    """Basic %%writefile"""
@@ -856,8 +867,9 @@
Loading
856 867
            'line2',
857 868
        ]))
858 869
        s = Path(fname).read_text()
859 -
        nt.assert_in('line1\n', s)
860 -
        nt.assert_in('line2', s)
870 +
        assert "line1\n" in s
871 +
        assert "line2" in s
872 +
861 873
862 874
@dec.skip_win32
863 875
def test_file_single_quote():
@@ -870,8 +882,9 @@
Loading
870 882
            'line2',
871 883
        ]))
872 884
        s = Path(fname).read_text()
873 -
        nt.assert_in('line1\n', s)
874 -
        nt.assert_in('line2', s)
885 +
        assert "line1\n" in s
886 +
        assert "line2" in s
887 +
875 888
876 889
@dec.skip_win32
877 890
def test_file_double_quote():
@@ -884,8 +897,9 @@
Loading
884 897
            'line2',
885 898
        ]))
886 899
        s = Path(fname).read_text()
887 -
        nt.assert_in('line1\n', s)
888 -
        nt.assert_in('line2', s)
900 +
        assert "line1\n" in s
901 +
        assert "line2" in s
902 +
889 903
890 904
def test_file_var_expand():
891 905
    """%%writefile $filename"""
@@ -898,8 +912,9 @@
Loading
898 912
            'line2',
899 913
        ]))
900 914
        s = Path(fname).read_text()
901 -
        nt.assert_in('line1\n', s)
902 -
        nt.assert_in('line2', s)
915 +
        assert "line1\n" in s
916 +
        assert "line2" in s
917 +
903 918
904 919
def test_file_unicode():
905 920
    """%%writefile with unicode cell"""
@@ -912,8 +927,9 @@
Loading
912 927
        ]))
913 928
        with io.open(fname, encoding='utf-8') as f:
914 929
            s = f.read()
915 -
        nt.assert_in(u'liné1\n', s)
916 -
        nt.assert_in(u'liné2', s)
930 +
        assert "liné1\n" in s
931 +
        assert "liné2" in s
932 +
917 933
918 934
def test_file_amend():
919 935
    """%%writefile -a amends files"""
@@ -929,8 +945,9 @@
Loading
929 945
            'line4',
930 946
        ]))
931 947
        s = Path(fname).read_text()
932 -
        nt.assert_in('line1\n', s)
933 -
        nt.assert_in('line3\n', s)
948 +
        assert "line1\n" in s
949 +
        assert "line3\n" in s
950 +
934 951
935 952
def test_file_spaces():
936 953
    """%%file with spaces in filename"""
@@ -942,14 +959,16 @@
Loading
942 959
            'line2',
943 960
        ]))
944 961
        s = Path(fname).read_text()
945 -
        nt.assert_in('line1\n', s)
946 -
        nt.assert_in('line2', s)
947 -
    
962 +
        assert "line1\n" in s
963 +
        assert "line2" in s
964 +
965 +
948 966
def test_script_config():
949 967
    ip = get_ipython()
950 968
    ip.config.ScriptMagics.script_magics = ['whoda']
951 969
    sm = script.ScriptMagics(shell=ip)
952 -
    nt.assert_in('whoda', sm.magics['cell'])
970 +
    assert "whoda" in sm.magics["cell"]
971 +
953 972
954 973
@dec.skip_iptest_but_not_pytest
955 974
@dec.skip_win32
@@ -962,7 +981,8 @@
Loading
962 981
    ip = get_ipython()
963 982
    ip.run_cell_magic("script", "--out output sh", "echo 'hi'")
964 983
    assert asyncio.get_event_loop().is_running() is False
965 -
    nt.assert_equal(ip.user_ns['output'], 'hi\n')
984 +
    assert ip.user_ns["output"] == "hi\n"
985 +
966 986
967 987
@dec.skip_iptest_but_not_pytest
968 988
@dec.skip_win32
@@ -974,7 +994,7 @@
Loading
974 994
    assert asyncio.get_event_loop().is_running() is False
975 995
    ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2")
976 996
    assert asyncio.get_event_loop().is_running() is False
977 -
    nt.assert_equal(ip.user_ns['error'], 'hello\n')
997 +
    assert ip.user_ns["error"] == "hello\n"
978 998
979 999
980 1000
@dec.skip_iptest_but_not_pytest
@@ -988,8 +1008,8 @@
Loading
988 1008
    ip.run_cell_magic(
989 1009
        "script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2"
990 1010
    )
991 -
    nt.assert_equal(ip.user_ns["output"], "hi\n")
992 -
    nt.assert_equal(ip.user_ns["error"], "hello\n")
1011 +
    assert ip.user_ns["output"] == "hi\n"
1012 +
    assert ip.user_ns["error"] == "hello\n"
993 1013
994 1014
995 1015
@dec.skip_iptest_but_not_pytest
@@ -1000,10 +1020,11 @@
Loading
1000 1020
async def test_script_bg_out():
1001 1021
    ip = get_ipython()
1002 1022
    ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'")
1003 -
    nt.assert_equal((await ip.user_ns["output"].read()), b"hi\n")
1023 +
    assert (await ip.user_ns["output"].read()) == b"hi\n"
1004 1024
    ip.user_ns["output"].close()
1005 1025
    asyncio.get_event_loop().stop()
1006 1026
1027 +
1007 1028
@dec.skip_iptest_but_not_pytest
1008 1029
@dec.skip_win32
1009 1030
@pytest.mark.skipif(
@@ -1012,7 +1033,7 @@
Loading
1012 1033
async def test_script_bg_err():
1013 1034
    ip = get_ipython()
1014 1035
    ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2")
1015 -
    nt.assert_equal((await ip.user_ns["error"].read()), b"hello\n")
1036 +
    assert (await ip.user_ns["error"].read()) == b"hello\n"
1016 1037
    ip.user_ns["error"].close()
1017 1038
1018 1039
@@ -1026,8 +1047,8 @@
Loading
1026 1047
    ip.run_cell_magic(
1027 1048
        "script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2"
1028 1049
    )
1029 -
    nt.assert_equal((await ip.user_ns["output"].read()), b"hi\n")
1030 -
    nt.assert_equal((await ip.user_ns["error"].read()), b"hello\n")
1050 +
    assert (await ip.user_ns["output"].read()) == b"hi\n"
1051 +
    assert (await ip.user_ns["error"].read()) == b"hello\n"
1031 1052
    ip.user_ns["output"].close()
1032 1053
    ip.user_ns["error"].close()
1033 1054
@@ -1040,7 +1061,7 @@
Loading
1040 1061
        except Exception:
1041 1062
            pass
1042 1063
        else:
1043 -
            nt.assert_in(cmd, ip.magics_manager.magics['cell'])
1064 +
            assert cmd in ip.magics_manager.magics["cell"]
1044 1065
1045 1066
1046 1067
@magics_class
@@ -1060,19 +1081,20 @@
Loading
1060 1081
    """%%foo and %foo magics are distinguishable to inspect"""
1061 1082
    ip = get_ipython()
1062 1083
    ip.magics_manager.register(FooFoo)
1063 -
    oinfo = ip.object_inspect('foo')
1064 -
    nt.assert_true(oinfo['found'])
1065 -
    nt.assert_true(oinfo['ismagic'])
1066 -
    
1067 -
    oinfo = ip.object_inspect('%%foo')
1068 -
    nt.assert_true(oinfo['found'])
1069 -
    nt.assert_true(oinfo['ismagic'])
1070 -
    nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__)
1071 -
1072 -
    oinfo = ip.object_inspect('%foo')
1073 -
    nt.assert_true(oinfo['found'])
1074 -
    nt.assert_true(oinfo['ismagic'])
1075 -
    nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__)
1084 +
    oinfo = ip.object_inspect("foo")
1085 +
    assert oinfo["found"] is True
1086 +
    assert oinfo["ismagic"] is True
1087 +
1088 +
    oinfo = ip.object_inspect("%%foo")
1089 +
    assert oinfo["found"] is True
1090 +
    assert oinfo["ismagic"] is True
1091 +
    assert oinfo["docstring"] == FooFoo.cell_foo.__doc__
1092 +
1093 +
    oinfo = ip.object_inspect("%foo")
1094 +
    assert oinfo["found"] is True
1095 +
    assert oinfo["ismagic"] is True
1096 +
    assert oinfo["docstring"] == FooFoo.line_foo.__doc__
1097 +
1076 1098
1077 1099
def test_multiple_magics():
1078 1100
    ip = get_ipython()
@@ -1080,9 +1102,10 @@
Loading
1080 1102
    foo2 = FooFoo(ip)
1081 1103
    mm = ip.magics_manager
1082 1104
    mm.register(foo1)
1083 -
    nt.assert_true(mm.magics['line']['foo'].__self__ is foo1)
1105 +
    assert mm.magics["line"]["foo"].__self__ is foo1
1084 1106
    mm.register(foo2)
1085 -
    nt.assert_true(mm.magics['line']['foo'].__self__ is foo2)
1107 +
    assert mm.magics["line"]["foo"].__self__ is foo2
1108 +
1086 1109
1087 1110
def test_alias_magic():
1088 1111
    """Test %alias_magic."""
@@ -1090,48 +1113,49 @@
Loading
1090 1113
    mm = ip.magics_manager
1091 1114
1092 1115
    # Basic operation: both cell and line magics are created, if possible.
1093 -
    ip.run_line_magic('alias_magic', 'timeit_alias timeit')
1094 -
    nt.assert_in('timeit_alias', mm.magics['line'])
1095 -
    nt.assert_in('timeit_alias', mm.magics['cell'])
1116 +
    ip.run_line_magic("alias_magic", "timeit_alias timeit")
1117 +
    assert "timeit_alias" in mm.magics["line"]
1118 +
    assert "timeit_alias" in mm.magics["cell"]
1096 1119
1097 1120
    # --cell is specified, line magic not created.
1098 -
    ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
1099 -
    nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
1100 -
    nt.assert_in('timeit_cell_alias', mm.magics['cell'])
1121 +
    ip.run_line_magic("alias_magic", "--cell timeit_cell_alias timeit")
1122 +
    assert "timeit_cell_alias" not in mm.magics["line"]
1123 +
    assert "timeit_cell_alias" in mm.magics["cell"]
1101 1124
1102 1125
    # Test that line alias is created successfully.
1103 -
    ip.run_line_magic('alias_magic', '--line env_alias env')
1104 -
    nt.assert_equal(ip.run_line_magic('env', ''),
1105 -
                    ip.run_line_magic('env_alias', ''))
1126 +
    ip.run_line_magic("alias_magic", "--line env_alias env")
1127 +
    assert ip.run_line_magic("env", "") == ip.run_line_magic("env_alias", "")
1106 1128
1107 1129
    # Test that line alias with parameters passed in is created successfully.
1108 -
    ip.run_line_magic('alias_magic', '--line history_alias history --params ' + shlex.quote('3'))
1109 -
    nt.assert_in('history_alias', mm.magics['line'])
1130 +
    ip.run_line_magic(
1131 +
        "alias_magic", "--line history_alias history --params " + shlex.quote("3")
1132 +
    )
1133 +
    assert "history_alias" in mm.magics["line"]
1110 1134
1111 1135
1112 1136
def test_save():
1113 1137
    """Test %save."""
1114 1138
    ip = get_ipython()
1115 1139
    ip.history_manager.reset()   # Clear any existing history.
1116 -
    cmds = [u"a=1", u"def b():\n  return a**2", u"print(a, b())"]
1140 +
    cmds = ["a=1", "def b():\n  return a**2", "print(a, b())"]
1117 1141
    for i, cmd in enumerate(cmds, start=1):
1118 1142
        ip.history_manager.store_inputs(i, cmd)
1119 1143
    with TemporaryDirectory() as tmpdir:
1120 1144
        file = os.path.join(tmpdir, "testsave.py")
1121 1145
        ip.run_line_magic("save", "%s 1-10" % file)
1122 1146
        content = Path(file).read_text()
1123 -
        nt.assert_equal(content.count(cmds[0]), 1)
1124 -
        nt.assert_in("coding: utf-8", content)
1147 +
        assert content.count(cmds[0]) == 1
1148 +
        assert "coding: utf-8" in content
1125 1149
        ip.run_line_magic("save", "-a %s 1-10" % file)
1126 1150
        content = Path(file).read_text()
1127 -
        nt.assert_equal(content.count(cmds[0]), 2)
1128 -
        nt.assert_in("coding: utf-8", content)
1151 +
        assert content.count(cmds[0]) == 2
1152 +
        assert "coding: utf-8" in content
1129 1153
1130 1154
1131 1155
def test_save_with_no_args():
1132 1156
    ip = get_ipython()
1133 1157
    ip.history_manager.reset()  # Clear any existing history.
1134 -
    cmds = [u"a=1", u"def b():\n    return a**2", u"print(a, b())", "%save"]
1158 +
    cmds = ["a=1", "def b():\n    return a**2", "print(a, b())", "%save"]
1135 1159
    for i, cmd in enumerate(cmds, start=1):
1136 1160
        ip.history_manager.store_inputs(i, cmd)
1137 1161
@@ -1148,26 +1172,26 @@
Loading
1148 1172
            print(a, b())
1149 1173
            """
1150 1174
        )
1151 -
        nt.assert_equal(content, expected_content)
1175 +
        assert content == expected_content
1152 1176
1153 1177
1154 1178
def test_store():
1155 1179
    """Test %store."""
1156 1180
    ip = get_ipython()
1157 1181
    ip.run_line_magic('load_ext', 'storemagic')
1158 -
    
1182 +
1159 1183
    # make sure the storage is empty
1160 -
    ip.run_line_magic('store', '-z')
1161 -
    ip.user_ns['var'] = 42
1162 -
    ip.run_line_magic('store', 'var')
1163 -
    ip.user_ns['var'] = 39
1164 -
    ip.run_line_magic('store', '-r')
1165 -
    nt.assert_equal(ip.user_ns['var'], 42)
1184 +
    ip.run_line_magic("store", "-z")
1185 +
    ip.user_ns["var"] = 42
1186 +
    ip.run_line_magic("store", "var")
1187 +
    ip.user_ns["var"] = 39
1188 +
    ip.run_line_magic("store", "-r")
1189 +
    assert ip.user_ns["var"] == 42
1166 1190
1167 -
    ip.run_line_magic('store', '-d var')
1168 -
    ip.user_ns['var'] = 39
1169 -
    ip.run_line_magic('store' , '-r')
1170 -
    nt.assert_equal(ip.user_ns['var'], 39)
1191 +
    ip.run_line_magic("store", "-d var")
1192 +
    ip.user_ns["var"] = 39
1193 +
    ip.run_line_magic("store", "-r")
1194 +
    assert ip.user_ns["var"] == 39
1171 1195
1172 1196
1173 1197
def _run_edit_test(arg_s, exp_filename=None,
@@ -1179,29 +1203,29 @@
Loading
1179 1203
    last_call = ['','']
1180 1204
    opts,args = M.parse_options(arg_s,'prxn:')
1181 1205
    filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call)
1182 -
        
1206 +
1183 1207
    if exp_filename is not None:
1184 -
        nt.assert_equal(exp_filename, filename)
1208 +
        assert exp_filename == filename
1185 1209
    if exp_contents is not None:
1186 1210
        with io.open(filename, 'r', encoding='utf-8') as f:
1187 1211
            contents = f.read()
1188 -
        nt.assert_equal(exp_contents, contents)
1212 +
        assert exp_contents == contents
1189 1213
    if exp_lineno != -1:
1190 -
        nt.assert_equal(exp_lineno, lineno)
1214 +
        assert exp_lineno == lineno
1191 1215
    if exp_is_temp is not None:
1192 -
        nt.assert_equal(exp_is_temp, is_temp)
1216 +
        assert exp_is_temp == is_temp
1193 1217
1194 1218
1195 1219
def test_edit_interactive():
1196 1220
    """%edit on interactively defined objects"""
1197 1221
    ip = get_ipython()
1198 1222
    n = ip.execution_count
1199 -
    ip.run_cell(u"def foo(): return 1", store_history=True)
1200 -
    
1223 +
    ip.run_cell("def foo(): return 1", store_history=True)
1224 +
1201 1225
    try:
1202 1226
        _run_edit_test("foo")
1203 1227
    except code.InteractivelyDefined as e:
1204 -
        nt.assert_equal(e.index, n)
1228 +
        assert e.index == n
1205 1229
    else:
1206 1230
        raise AssertionError("Should have raised InteractivelyDefined")
1207 1231
@@ -1209,9 +1233,9 @@
Loading
1209 1233
def test_edit_cell():
1210 1234
    """%edit [cell id]"""
1211 1235
    ip = get_ipython()
1212 -
    
1213 -
    ip.run_cell(u"def foo(): return 1", store_history=True)
1214 -
    
1236 +
1237 +
    ip.run_cell("def foo(): return 1", store_history=True)
1238 +
1215 1239
    # test
1216 1240
    _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True)
1217 1241
@@ -1234,17 +1258,18 @@
Loading
1234 1258
    lsmagic = ip.magic('lsmagic')
1235 1259
    with warnings.catch_warnings(record=True) as w:
1236 1260
        j = json_formatter(lsmagic)
1237 -
    nt.assert_equal(sorted(j), ['cell', 'line'])
1238 -
    nt.assert_equal(w, []) # no warnings
1261 +
    assert sorted(j) == ["cell", "line"]
1262 +
    assert w == []  # no warnings
1263 +
1239 1264
1240 1265
def test_strip_initial_indent():
1241 1266
    def sii(s):
1242 1267
        lines = s.splitlines()
1243 1268
        return '\n'.join(code.strip_initial_indent(lines))
1244 1269
1245 -
    nt.assert_equal(sii("  a = 1\nb = 2"), "a = 1\nb = 2")
1246 -
    nt.assert_equal(sii("  a\n    b\nc"), "a\n  b\nc")
1247 -
    nt.assert_equal(sii("a\n  b"), "a\n  b")
1270 +
    assert sii("  a = 1\nb = 2") == "a = 1\nb = 2"
1271 +
    assert sii("  a\n    b\nc") == "a\n  b\nc"
1272 +
    assert sii("a\n  b") == "a\n  b"
1248 1273
1249 1274
def test_logging_magic_quiet_from_arg():
1250 1275
    _ip.config.LoggingMagics.quiet = False
@@ -1336,6 +1361,6 @@
Loading
1336 1361
            _ip.run_cell("import my_tmp")
1337 1362
1338 1363
        output = "Loaded my_tmp\nI just ran a script\nLoaded my_tmp\n"
1339 -
        nt.assert_equal(output, captured.stdout)
1364 +
        assert output == captured.stdout
1340 1365
1341 1366
        sys.meta_path.pop(0)

@@ -26,8 +26,7 @@
Loading
26 26
import unittest
27 27
from unittest.mock import patch
28 28
29 -
import nose.tools as nt
30 -
from nose import SkipTest
29 +
import pytest
31 30
32 31
from IPython.testing import decorators as dec
33 32
from IPython.testing import tools as tt
@@ -168,13 +167,13 @@
Loading
168 167
    def setUp(self):
169 168
        content = "a = [1,2,3]\nb = 1"
170 169
        self.mktmp(content)
171 -
        
170 +
172 171
    def run_tmpfile(self):
173 172
        _ip = get_ipython()
174 173
        # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
175 174
        # See below and ticket https://bugs.launchpad.net/bugs/366353
176 175
        _ip.magic('run %s' % self.fname)
177 -
        
176 +
178 177
    def run_tmpfile_p(self):
179 178
        _ip = get_ipython()
180 179
        # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
@@ -188,7 +187,7 @@
Loading
188 187
        bid1 = id(_ip.user_ns['__builtins__'])
189 188
        self.run_tmpfile()
190 189
        bid2 = id(_ip.user_ns['__builtins__'])
191 -
        nt.assert_equal(bid1, bid2)
190 +
        assert bid1 == bid2
192 191
193 192
    def test_builtins_type(self):
194 193
        """Check that the type of __builtins__ doesn't change with %run.
@@ -199,9 +198,9 @@
Loading
199 198
        """
200 199
        _ip = get_ipython()
201 200
        self.run_tmpfile()
202 -
        nt.assert_equal(type(_ip.user_ns['__builtins__']),type(sys))
203 -
        
204 -
    def test_run_profile( self ):
201 +
        assert type(_ip.user_ns["__builtins__"]) == type(sys)
202 +
203 +
    def test_run_profile(self):
205 204
        """Test that the option -p, which invokes the profiler, do not
206 205
        crash by invoking execfile"""
207 206
        self.run_tmpfile_p()
@@ -232,9 +231,9 @@
Loading
232 231
        src = ("class foo: pass\n"
233 232
               "def f(): return foo()")
234 233
        self.mktmp(src)
235 -
        _ip.magic('run %s' % self.fname)
236 -
        _ip.run_cell('t = isinstance(f(), foo)')
237 -
        nt.assert_true(_ip.user_ns['t'])
234 +
        _ip.magic("run %s" % self.fname)
235 +
        _ip.run_cell("t = isinstance(f(), foo)")
236 +
        assert _ip.user_ns["t"] is True
238 237
239 238
    def test_obj_del(self):
240 239
        """Test that object's __del__ methods are called on exit."""
@@ -242,7 +241,7 @@
Loading
242 241
            try:
243 242
                import win32api
244 243
            except ImportError as e:
245 -
                raise SkipTest("Test requires pywin32") from e
244 +
                raise unittest.SkipTest("Test requires pywin32") from e
246 245
        src = ("class A(object):\n"
247 246
               "    def __del__(self):\n"
248 247
               "        print('object A deleted')\n"
@@ -250,42 +249,41 @@
Loading
250 249
        self.mktmp(src)
251 250
        err = None
252 251
        tt.ipexec_validate(self.fname, 'object A deleted', err)
253 -
    
252 +
254 253
    def test_aggressive_namespace_cleanup(self):
255 254
        """Test that namespace cleanup is not too aggressive GH-238
256 255
257 256
        Returning from another run magic deletes the namespace"""
258 257
        # see ticket https://github.com/ipython/ipython/issues/238
259 -
        
258 +
260 259
        with tt.TempFileMixin() as empty:
261 -
            empty.mktmp('')
260 +
            empty.mktmp("")
262 261
            # On Windows, the filename will have \users in it, so we need to use the
263 262
            # repr so that the \u becomes \\u.
264 -
            src = ("ip = get_ipython()\n"
265 -
                   "for i in range(5):\n"
266 -
                   "   try:\n"
267 -
                   "       ip.magic(%r)\n"
268 -
                   "   except NameError as e:\n"
269 -
                   "       print(i)\n"
270 -
                   "       break\n" % ('run ' + empty.fname))
263 +
            src = (
264 +
                "ip = get_ipython()\n"
265 +
                "for i in range(5):\n"
266 +
                "   try:\n"
267 +
                "       ip.magic(%r)\n"
268 +
                "   except NameError as e:\n"
269 +
                "       print(i)\n"
270 +
                "       break\n" % ("run " + empty.fname)
271 +
            )
271 272
            self.mktmp(src)
272 -
            _ip.magic('run %s' % self.fname)
273 -
            _ip.run_cell('ip == get_ipython()')
274 -
            nt.assert_equal(_ip.user_ns['i'], 4)
275 -
    
273 +
            _ip.magic("run %s" % self.fname)
274 +
            _ip.run_cell("ip == get_ipython()")
275 +
            assert _ip.user_ns["i"] == 4
276 +
276 277
    def test_run_second(self):
277 -
        """Test that running a second file doesn't clobber the first, gh-3547
278 -
        """
279 -
        self.mktmp("avar = 1\n"
280 -
                   "def afunc():\n"
281 -
                   "  return avar\n")
278 +
        """Test that running a second file doesn't clobber the first, gh-3547"""
279 +
        self.mktmp("avar = 1\n" "def afunc():\n" "  return avar\n")
282 280
283 281
        with tt.TempFileMixin() as empty:
284 282
            empty.mktmp("")
285 -
            
286 -
            _ip.magic('run %s' % self.fname)
287 -
            _ip.magic('run %s' % empty.fname)
288 -
            nt.assert_equal(_ip.user_ns['afunc'](), 1)
283 +
284 +
            _ip.magic("run %s" % self.fname)
285 +
            _ip.magic("run %s" % empty.fname)
286 +
            assert _ip.user_ns["afunc"]() == 1
289 287
290 288
    @dec.skip_win32
291 289
    def test_tclass(self):
@@ -312,24 +310,24 @@
Loading
312 310
        self.mktmp(src)
313 311
        _ip.run_cell("zz = 23")
314 312
        try:
315 -
            _ip.magic('run -i %s' % self.fname)
316 -
            nt.assert_equal(_ip.user_ns['yy'], 23)
313 +
            _ip.magic("run -i %s" % self.fname)
314 +
            assert _ip.user_ns["yy"] == 23
317 315
        finally:
318 316
            _ip.magic('reset -f')
319 -
            
317 +
320 318
        _ip.run_cell("zz = 23")
321 319
        try:
322 -
            _ip.magic('run -i %s' % self.fname)
323 -
            nt.assert_equal(_ip.user_ns['yy'], 23)
320 +
            _ip.magic("run -i %s" % self.fname)
321 +
            assert _ip.user_ns["yy"] == 23
324 322
        finally:
325 323
            _ip.magic('reset -f')
326 -
            
324 +
327 325
    def test_unicode(self):
328 326
        """Check that files in odd encodings are accepted."""
329 327
        mydir = os.path.dirname(__file__)
330 328
        na = os.path.join(mydir, 'nonascii.py')
331 329
        _ip.magic('run "%s"' % na)
332 -
        nt.assert_equal(_ip.user_ns['u'], u'Ўт№Ф')
330 +
        assert _ip.user_ns["u"] == "Ўт№Ф"
333 331
334 332
    def test_run_py_file_attribute(self):
335 333
        """Test handling of `__file__` attribute in `%run <file>.py`."""
@@ -342,10 +340,10 @@
Loading
342 340
343 341
        # Check that __file__ was equal to the filename in the script's
344 342
        # namespace.
345 -
        nt.assert_equal(_ip.user_ns['t'], self.fname)
343 +
        assert _ip.user_ns["t"] == self.fname
346 344
347 345
        # Check that __file__ was not leaked back into user_ns.
348 -
        nt.assert_equal(file1, file2)
346 +
        assert file1 == file2
349 347
350 348
    def test_run_ipy_file_attribute(self):
351 349
        """Test handling of `__file__` attribute in `%run <file.ipy>`."""
@@ -358,10 +356,10 @@
Loading
358 356
359 357
        # Check that __file__ was equal to the filename in the script's
360 358
        # namespace.
361 -
        nt.assert_equal(_ip.user_ns['t'], self.fname)
359 +
        assert _ip.user_ns["t"] == self.fname
362 360
363 361
        # Check that __file__ was not leaked back into user_ns.
364 -
        nt.assert_equal(file1, file2)
362 +
        assert file1 == file2
365 363
366 364
    def test_run_formatting(self):
367 365
        """ Test that %run -t -N<N> does not raise a TypeError for N > 1."""
@@ -369,14 +367,14 @@
Loading
369 367
        self.mktmp(src)
370 368
        _ip.magic('run -t -N 1 %s' % self.fname)
371 369
        _ip.magic('run -t -N 10 %s' % self.fname)
372 -
    
370 +
373 371
    def test_ignore_sys_exit(self):
374 372
        """Test the -e option to ignore sys.exit()"""
375 373
        src = "import sys; sys.exit(1)"
376 374
        self.mktmp(src)
377 375
        with tt.AssertPrints('SystemExit'):
378 376
            _ip.magic('run %s' % self.fname)
379 -
        
377 +
380 378
        with tt.AssertNotPrints('SystemExit'):
381 379
            _ip.magic('run -e %s' % self.fname)
382 380
@@ -391,19 +389,19 @@
Loading
391 389
        )
392 390
        src = writes(nb, version=4)
393 391
        self.mktmp(src, ext='.ipynb')
394 -
        
392 +
395 393
        _ip.magic("run %s" % self.fname)
396 -
        
397 -
        nt.assert_equal(_ip.user_ns['answer'], 42)
394 +
395 +
        assert _ip.user_ns["answer"] == 42
398 396
399 397
    def test_run_nb_error(self):
400 398
        """Test %run notebook.ipynb error"""
401 399
        from nbformat import v4, writes
402 400
        # %run when a file name isn't provided
403 -
        nt.assert_raises(Exception, _ip.magic, "run")
401 +
        pytest.raises(Exception, _ip.magic, "run")
404 402
405 403
        # %run when a file doesn't exist
406 -
        nt.assert_raises(Exception, _ip.magic, "run foobar.ipynb")
404 +
        pytest.raises(Exception, _ip.magic, "run foobar.ipynb")
407 405
408 406
        # %run on a notebook with an error
409 407
        nb = v4.new_notebook(
@@ -413,15 +411,15 @@
Loading
413 411
        )
414 412
        src = writes(nb, version=4)
415 413
        self.mktmp(src, ext='.ipynb')
416 -
        nt.assert_raises(Exception, _ip.magic, "run %s" % self.fname)
414 +
        pytest.raises(Exception, _ip.magic, "run %s" % self.fname)
417 415
418 416
    def test_file_options(self):
419 417
        src = ('import sys\n'
420 418
               'a = " ".join(sys.argv[1:])\n')
421 419
        self.mktmp(src)
422 -
        test_opts = '-x 3 --verbose'
423 -
        _ip.run_line_magic("run", '{0} {1}'.format(self.fname, test_opts))
424 -
        nt.assert_equal(_ip.user_ns['a'], test_opts)
420 +
        test_opts = "-x 3 --verbose"
421 +
        _ip.run_line_magic("run", "{0} {1}".format(self.fname, test_opts))
422 +
        assert _ip.user_ns["a"] == test_opts
425 423
426 424
427 425
class TestMagicRunWithPackage(unittest.TestCase):
@@ -500,33 +498,34 @@
Loading
500 498
        self.check_run_submodule('relative', '-d')
501 499
502 500
    def test_module_options(self):
503 -
        _ip.user_ns.pop('a', None)
504 -
        test_opts = '-x abc -m test'
505 -
        _ip.run_line_magic('run', '-m {0}.args {1}'.format(self.package, test_opts))
506 -
        nt.assert_equal(_ip.user_ns['a'], test_opts)
501 +
        _ip.user_ns.pop("a", None)
502 +
        test_opts = "-x abc -m test"
503 +
        _ip.run_line_magic("run", "-m {0}.args {1}".format(self.package, test_opts))
504 +
        assert _ip.user_ns["a"] == test_opts
507 505
508 506
    def test_module_options_with_separator(self):
509 -
        _ip.user_ns.pop('a', None)
510 -
        test_opts = '-x abc -m test'
511 -
        _ip.run_line_magic('run', '-m {0}.args -- {1}'.format(self.package, test_opts))
512 -
        nt.assert_equal(_ip.user_ns['a'], test_opts)
507 +
        _ip.user_ns.pop("a", None)
508 +
        test_opts = "-x abc -m test"
509 +
        _ip.run_line_magic("run", "-m {0}.args -- {1}".format(self.package, test_opts))
510 +
        assert _ip.user_ns["a"] == test_opts
511 +
513 512
514 513
def test_run__name__():
515 514
    with TemporaryDirectory() as td:
516 515
        path = pjoin(td, 'foo.py')
517 516
        with open(path, 'w') as f:
518 517
            f.write("q = __name__")
519 -
        
520 -
        _ip.user_ns.pop('q', None)
521 -
        _ip.magic('run {}'.format(path))
522 -
        nt.assert_equal(_ip.user_ns.pop('q'), '__main__')
523 -
        
524 -
        _ip.magic('run -n {}'.format(path))
525 -
        nt.assert_equal(_ip.user_ns.pop('q'), 'foo')
518 +
519 +
        _ip.user_ns.pop("q", None)
520 +
        _ip.magic("run {}".format(path))
521 +
        assert _ip.user_ns.pop("q") == "__main__"
522 +
523 +
        _ip.magic("run -n {}".format(path))
524 +
        assert _ip.user_ns.pop("q") == "foo"
526 525
527 526
        try:
528 -
            _ip.magic('run -i -n {}'.format(path))
529 -
            nt.assert_equal(_ip.user_ns.pop('q'), 'foo')
527 +
            _ip.magic("run -i -n {}".format(path))
528 +
            assert _ip.user_ns.pop("q") == "foo"
530 529
        finally:
531 530
            _ip.magic('reset -f')
532 531
@@ -546,9 +545,9 @@
Loading
546 545
        with capture_output() as io:
547 546
            _ip.magic('run {}'.format(path))
548 547
        out = io.stdout
549 -
        nt.assert_not_in("execfile", out)
550 -
        nt.assert_in("RuntimeError", out)
551 -
        nt.assert_equal(out.count("---->"), 3)
548 +
        assert "execfile" not in out
549 +
        assert "RuntimeError" in out
550 +
        assert out.count("---->") == 3
552 551
        del ip.user_ns['bar']
553 552
        del ip.user_ns['foo']
554 553
@@ -572,10 +571,10 @@
Loading
572 571
                _ip.run_line_magic('run', path)
573 572
                _ip.run_cell("i_m_undefined")
574 573
            out = io.stdout
575 -
            nt.assert_in("hoy", out)
576 -
            nt.assert_not_in("AttributeError", out)
577 -
            nt.assert_in("NameError", out)
578 -
            nt.assert_equal(out.count("---->"), 1)
574 +
            assert "hoy" in out
575 +
            assert "AttributeError" not in out
576 +
            assert "NameError" in out
577 +
            assert out.count("---->") == 1
579 578
        except:
580 579
            raise
581 580
        finally:
@@ -595,7 +594,6 @@
Loading
595 594
                "foo()",
596 595
            ]))
597 596
        out, err = tt.ipexec(path)
598 -
        nt.assert_not_in("execfile", out)
599 -
        nt.assert_in("RuntimeError", out)
600 -
        nt.assert_equal(out.count("---->"), 3)
601 -
597 +
        assert "execfile" not in out
598 +
        assert "RuntimeError" in out
599 +
        assert out.count("---->") == 3

@@ -4,9 +4,6 @@
Loading
4 4
# Module imports
5 5
#-----------------------------------------------------------------------------
6 6
7 -
# third party
8 -
import nose.tools as nt
9 -
10 7
# our own packages
11 8
from IPython.core import autocall
12 9
from IPython.testing import tools as tt
@@ -91,4 +88,4 @@
Loading
91 88
        ])
92 89
    ip.magic('autocall 1')
93 90
94 -
    nt.assert_equal(failures, [])
91 +
    assert failures == []

@@ -17,9 +17,10 @@
Loading
17 17
import random
18 18
import sys
19 19
20 -
import nose.tools as nt
21 20
from pathlib import Path
22 21
22 +
import pytest
23 +
23 24
from IPython.utils import text
24 25
25 26
#-----------------------------------------------------------------------------
@@ -116,8 +117,9 @@
Loading
116 117
    assert s == ns["u"]
117 118
    # This decodes in a platform dependent manner, but it shouldn't error out
118 119
    s = f.format("{b}", **ns)
119 -
        
120 -
    nt.assert_raises(NameError, f.format, '{dne}', **ns)
120 +
121 +
    pytest.raises(NameError, f.format, "{dne}", **ns)
122 +
121 123
122 124
def eval_formatter_slicing_check(f):
123 125
    ns = dict(n=12, pi=math.pi, stuff='hello there', os=os)
@@ -128,7 +130,7 @@
Loading
128 130
    s = f.format("{stuff[::2]}", **ns)
129 131
    assert s == ns["stuff"][::2]
130 132
131 -
    nt.assert_raises(SyntaxError, f.format, "{n:x}", **ns)
133 +
    pytest.raises(SyntaxError, f.format, "{n:x}", **ns)
132 134
133 135
def eval_formatter_no_slicing_check(f):
134 136
    ns = dict(n=12, pi=math.pi, stuff='hello there', os=os)
@@ -194,7 +196,7 @@
Loading
194 196
    assert lss.l == ["abc", "def"]
195 197
    assert lss.s == "abc def"
196 198
    lss = text.LSString(os.getcwd())
197 -
    nt.assert_is_instance(lss.p[0], Path)
199 +
    assert isinstance(lss.p[0], Path)
198 200
199 201
def test_SList():
200 202
    sl = text.SList(["a 11", "b 1", "a 2"])

@@ -7,7 +7,7 @@
Loading
7 7
    import numpy
8 8
except:
9 9
    numpy = None
10 -
import nose.tools as nt
10 +
import pytest
11 11
12 12
from IPython import get_ipython
13 13
from traitlets.config import Config
@@ -95,24 +95,25 @@
Loading
95 95
    """test various invalid values for float_precision."""
96 96
    f = PlainTextFormatter()
97 97
    def set_fp(p):
98 -
        f.float_precision=p
99 -
    nt.assert_raises(ValueError, set_fp, '%')
100 -
    nt.assert_raises(ValueError, set_fp, '%.3f%i')
101 -
    nt.assert_raises(ValueError, set_fp, 'foo')
102 -
    nt.assert_raises(ValueError, set_fp, -1)
98 +
        f.float_precision = p
99 +
100 +
    pytest.raises(ValueError, set_fp, "%")
101 +
    pytest.raises(ValueError, set_fp, "%.3f%i")
102 +
    pytest.raises(ValueError, set_fp, "foo")
103 +
    pytest.raises(ValueError, set_fp, -1)
103 104
104 105
def test_for_type():
105 106
    f = PlainTextFormatter()
106 107
    
107 108
    # initial return, None
108 -
    nt.assert_is(f.for_type(C, foo_printer), None)
109 +
    assert f.for_type(C, foo_printer) is None
109 110
    # no func queries
110 -
    nt.assert_is(f.for_type(C), foo_printer)
111 +
    assert f.for_type(C) is foo_printer
111 112
    # shouldn't change anything
112 -
    nt.assert_is(f.for_type(C), foo_printer)
113 +
    assert f.for_type(C) is foo_printer
113 114
    # None should do the same
114 -
    nt.assert_is(f.for_type(C, None), foo_printer)
115 -
    nt.assert_is(f.for_type(C, None), foo_printer)
115 +
    assert f.for_type(C, None) is foo_printer
116 +
    assert f.for_type(C, None) is foo_printer
116 117
117 118
def test_for_type_string():
118 119
    f = PlainTextFormatter()
@@ -120,13 +121,13 @@
Loading
120 121
    type_str = '%s.%s' % (C.__module__, 'C')
121 122
    
122 123
    # initial return, None
123 -
    nt.assert_is(f.for_type(type_str, foo_printer), None)
124 +
    assert f.for_type(type_str, foo_printer) is None
124 125
    # no func queries
125 -
    nt.assert_is(f.for_type(type_str), foo_printer)
126 -
    nt.assert_in(_mod_name_key(C), f.deferred_printers)
127 -
    nt.assert_is(f.for_type(C), foo_printer)
128 -
    nt.assert_not_in(_mod_name_key(C), f.deferred_printers)
129 -
    nt.assert_in(C, f.type_printers)
126 +
    assert f.for_type(type_str) is foo_printer
127 +
    assert _mod_name_key(C) in f.deferred_printers
128 +
    assert f.for_type(C) is foo_printer
129 +
    assert _mod_name_key(C) not in f.deferred_printers
130 +
    assert C in f.type_printers
130 131
131 132
def test_for_type_by_name():
132 133
    f = PlainTextFormatter()
@@ -134,21 +135,22 @@
Loading
134 135
    mod = C.__module__
135 136
    
136 137
    # initial return, None
137 -
    nt.assert_is(f.for_type_by_name(mod, 'C', foo_printer), None)
138 +
    assert f.for_type_by_name(mod, "C", foo_printer) is None
138 139
    # no func queries
139 -
    nt.assert_is(f.for_type_by_name(mod, 'C'), foo_printer)
140 +
    assert f.for_type_by_name(mod, "C") is foo_printer
140 141
    # shouldn't change anything
141 -
    nt.assert_is(f.for_type_by_name(mod, 'C'), foo_printer)
142 +
    assert f.for_type_by_name(mod, "C") is foo_printer
142 143
    # None should do the same
143 -
    nt.assert_is(f.for_type_by_name(mod, 'C', None), foo_printer)
144 -
    nt.assert_is(f.for_type_by_name(mod, 'C', None), foo_printer)
144 +
    assert f.for_type_by_name(mod, "C", None) is foo_printer
145 +
    assert f.for_type_by_name(mod, "C", None) is foo_printer
146 +
145 147
146 148
def test_lookup():
147 149
    f = PlainTextFormatter()
148 150
    
149 151
    f.for_type(C, foo_printer)
150 -
    nt.assert_is(f.lookup(C()), foo_printer)
151 -
    with nt.assert_raises(KeyError):
152 +
    assert f.lookup(C()) is foo_printer
153 +
    with pytest.raises(KeyError):
152 154
        f.lookup(A())
153 155
154 156
def test_lookup_string():
@@ -156,16 +158,16 @@
Loading
156 158
    type_str = '%s.%s' % (C.__module__, 'C')
157 159
    
158 160
    f.for_type(type_str, foo_printer)
159 -
    nt.assert_is(f.lookup(C()), foo_printer)
161 +
    assert f.lookup(C()) is foo_printer
160 162
    # should move from deferred to imported dict
161 -
    nt.assert_not_in(_mod_name_key(C), f.deferred_printers)
162 -
    nt.assert_in(C, f.type_printers)
163 +
    assert _mod_name_key(C) not in f.deferred_printers
164 +
    assert C in f.type_printers
163 165
164 166
def test_lookup_by_type():
165 167
    f = PlainTextFormatter()
166 168
    f.for_type(C, foo_printer)
167 -
    nt.assert_is(f.lookup_by_type(C), foo_printer)
168 -
    with nt.assert_raises(KeyError):
169 +
    assert f.lookup_by_type(C) is foo_printer
170 +
    with pytest.raises(KeyError):
169 171
        f.lookup_by_type(A)
170 172
171 173
def test_lookup_by_type_string():
@@ -174,69 +176,69 @@
Loading
174 176
    f.for_type(type_str, foo_printer)
175 177
    
176 178
    # verify insertion
177 -
    nt.assert_in(_mod_name_key(C), f.deferred_printers)
178 -
    nt.assert_not_in(C, f.type_printers)
179 +
    assert _mod_name_key(C) in f.deferred_printers
180 +
    assert C not in f.type_printers
179 181
    
180 -
    nt.assert_is(f.lookup_by_type(type_str), foo_printer)
182 +
    assert f.lookup_by_type(type_str) is foo_printer
181 183
    # lookup by string doesn't cause import
182 -
    nt.assert_in(_mod_name_key(C), f.deferred_printers)
183 -
    nt.assert_not_in(C, f.type_printers)
184 +
    assert _mod_name_key(C) in f.deferred_printers
185 +
    assert C not in f.type_printers
184 186
    
185 -
    nt.assert_is(f.lookup_by_type(C), foo_printer)
187 +
    assert f.lookup_by_type(C) is foo_printer
186 188
    # should move from deferred to imported dict
187 -
    nt.assert_not_in(_mod_name_key(C), f.deferred_printers)
188 -
    nt.assert_in(C, f.type_printers)
189 +
    assert _mod_name_key(C) not in f.deferred_printers
190 +
    assert C in f.type_printers
189 191
190 192
def test_in_formatter():
191 193
    f = PlainTextFormatter()
192 194
    f.for_type(C, foo_printer)
193 195
    type_str = '%s.%s' % (C.__module__, 'C')
194 -
    nt.assert_in(C, f)
195 -
    nt.assert_in(type_str, f)
196 +
    assert C in f
197 +
    assert type_str in f
196 198
197 199
def test_string_in_formatter():
198 200
    f = PlainTextFormatter()
199 201
    type_str = '%s.%s' % (C.__module__, 'C')
200 202
    f.for_type(type_str, foo_printer)
201 -
    nt.assert_in(type_str, f)
202 -
    nt.assert_in(C, f)
203 +
    assert type_str in f
204 +
    assert C in f
203 205
204 206
def test_pop():
205 207
    f = PlainTextFormatter()
206 208
    f.for_type(C, foo_printer)
207 -
    nt.assert_is(f.lookup_by_type(C), foo_printer)
208 -
    nt.assert_is(f.pop(C, None), foo_printer)
209 +
    assert f.lookup_by_type(C) is foo_printer
210 +
    assert f.pop(C, None) is foo_printer
209 211
    f.for_type(C, foo_printer)
210 -
    nt.assert_is(f.pop(C), foo_printer)
211 -
    with nt.assert_raises(KeyError):
212 +
    assert f.pop(C) is foo_printer
213 +
    with pytest.raises(KeyError):
212 214
        f.lookup_by_type(C)
213 -
    with nt.assert_raises(KeyError):
215 +
    with pytest.raises(KeyError):
214 216
        f.pop(C)
215 -
    with nt.assert_raises(KeyError):
217 +
    with pytest.raises(KeyError):
216 218
        f.pop(A)
217 -
    nt.assert_is(f.pop(A, None), None)
219 +
    assert f.pop(A, None) is None
218 220
219 221
def test_pop_string():
220 222
    f = PlainTextFormatter()
221 223
    type_str = '%s.%s' % (C.__module__, 'C')
222 224
    
223 -
    with nt.assert_raises(KeyError):
225 +
    with pytest.raises(KeyError):
224 226
        f.pop(type_str)
225 227
    
226 228
    f.for_type(type_str, foo_printer)
227 229
    f.pop(type_str)
228 -
    with nt.assert_raises(KeyError):
230 +
    with pytest.raises(KeyError):
229 231
        f.lookup_by_type(C)
230 -
    with nt.assert_raises(KeyError):
232 +
    with pytest.raises(KeyError):
231 233
        f.pop(type_str)
232 234
233 235
    f.for_type(C, foo_printer)
234 -
    nt.assert_is(f.pop(type_str, None), foo_printer)
235 -
    with nt.assert_raises(KeyError):
236 +
    assert f.pop(type_str, None) is foo_printer
237 +
    with pytest.raises(KeyError):
236 238
        f.lookup_by_type(C)
237 -
    with nt.assert_raises(KeyError):
239 +
    with pytest.raises(KeyError):
238 240
        f.pop(type_str)
239 -
    nt.assert_is(f.pop(type_str, None), None)
241 +
    assert f.pop(type_str, None) is None
240 242
    
241 243
242 244
def test_error_method():
@@ -247,10 +249,10 @@
Loading
247 249
    bad = BadHTML()
248 250
    with capture_output() as captured:
249 251
        result = f(bad)
250 -
    nt.assert_is(result, None)
251 -
    nt.assert_in("Traceback", captured.stdout)
252 -
    nt.assert_in("Bad HTML", captured.stdout)
253 -
    nt.assert_in("_repr_html_", captured.stdout)
252 +
    assert result is None
253 +
    assert "Traceback" in captured.stdout
254 +
    assert "Bad HTML" in captured.stdout
255 +
    assert "_repr_html_" in captured.stdout
254 256
255 257
def test_nowarn_notimplemented():
256 258
    f = HTMLFormatter()
@@ -260,7 +262,7 @@
Loading
260 262
    h = HTMLNotImplemented()
261 263
    with capture_output() as captured:
262 264
        result = f(h)
263 -
    nt.assert_is(result, None)
265 +
    assert result is None
264 266
    assert "" == captured.stderr
265 267
    assert "" == captured.stdout
266 268
@@ -270,10 +272,10 @@
Loading
270 272
    f.for_type(int, lambda i: name_error)
271 273
    with capture_output() as captured:
272 274
        result = f(5)
273 -
    nt.assert_is(result, None)
274 -
    nt.assert_in("Traceback", captured.stdout)
275 -
    nt.assert_in("NameError", captured.stdout)
276 -
    nt.assert_in("name_error", captured.stdout)
275 +
    assert result is None
276 +
    assert "Traceback" in captured.stdout
277 +
    assert "NameError" in captured.stdout
278 +
    assert "name_error" in captured.stdout
277 279
278 280
def test_error_pretty_method():
279 281
    f = PlainTextFormatter()
@@ -283,11 +285,11 @@
Loading
283 285
    bad = BadPretty()
284 286
    with capture_output() as captured:
285 287
        result = f(bad)
286 -
    nt.assert_is(result, None)
287 -
    nt.assert_in("Traceback", captured.stdout)
288 -
    nt.assert_in("_repr_pretty_", captured.stdout)
289 -
    nt.assert_in("given", captured.stdout)
290 -
    nt.assert_in("argument", captured.stdout)
288 +
    assert result is None
289 +
    assert "Traceback" in captured.stdout
290 +
    assert "_repr_pretty_" in captured.stdout
291 +
    assert "given" in captured.stdout
292 +
    assert "argument" in captured.stdout
291 293
292 294
293 295
def test_bad_repr_traceback():
@@ -296,10 +298,10 @@
Loading
296 298
    with capture_output() as captured:
297 299
        result = f(bad)
298 300
    # catches error, returns None
299 -
    nt.assert_is(result, None)
300 -
    nt.assert_in("Traceback", captured.stdout)
301 -
    nt.assert_in("__repr__", captured.stdout)
302 -
    nt.assert_in("ValueError", captured.stdout)
301 +
    assert result is None
302 +
    assert "Traceback" in captured.stdout
303 +
    assert "__repr__" in captured.stdout
304 +
    assert "ValueError" in captured.stdout
303 305
304 306
305 307
class MakePDF(object):
@@ -319,8 +321,8 @@
Loading
319 321
            return "hello"
320 322
    with capture_output() as captured:
321 323
        result = f(MyHTML)
322 -
    nt.assert_is(result, None)
323 -
    nt.assert_not_in("FormatterWarning", captured.stderr)
324 +
    assert result is None
325 +
    assert "FormatterWarning" not in captured.stderr
324 326
325 327
    with capture_output() as captured:
326 328
        result = f(MyHTML())
@@ -341,8 +343,8 @@
Loading
341 343
    with capture_output() as captured:
342 344
        result = f(text_hat)
343 345
    
344 -
    nt.assert_is(result, None)
345 -
    nt.assert_not_in("FormatterWarning", captured.stderr)
346 +
    assert result is None
347 +
    assert "FormatterWarning" not in captured.stderr
346 348
347 349
    class CallableMagicHat(object):
348 350
        def __getattr__(self, key):
@@ -362,8 +364,8 @@
Loading
362 364
    with capture_output() as captured:
363 365
        result = f(bad)
364 366
    
365 -
    nt.assert_is(result, None)
366 -
    nt.assert_not_in("FormatterWarning", captured.stderr)
367 +
    assert result is None
368 +
    assert "FormatterWarning" not in captured.stderr
367 369
368 370
369 371
def test_format_config():
@@ -372,12 +374,12 @@
Loading
372 374
    cfg = Config()
373 375
    with capture_output() as captured:
374 376
        result = f(cfg)
375 -
    nt.assert_is(result, None)
377 +
    assert result is None
376 378
    assert captured.stderr == ""
377 379
378 380
    with capture_output() as captured:
379 381
        result = f(Config)
380 -
    nt.assert_is(result, None)
382 +
    assert result is None
381 383
    assert captured.stderr == ""
382 384
383 385

@@ -7,7 +7,7 @@
Loading
7 7
8 8
from unittest import mock
9 9
10 -
import nose.tools as nt
10 +
import pytest
11 11
12 12
from IPython import display
13 13
from IPython.core.getipython import get_ipython
@@ -22,15 +22,15 @@
Loading
22 22
    """Simple test for display.Image(args, width=x,height=y)"""
23 23
    thisurl = 'http://www.google.fr/images/srpr/logo3w.png'
24 24
    img = display.Image(url=thisurl, width=200, height=200)
25 -
    nt.assert_equal(u'<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 26
    img = display.Image(url=thisurl, metadata={'width':200, 'height':200})
27 -
    nt.assert_equal(u'<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 28
    img = display.Image(url=thisurl, width=200)
29 -
    nt.assert_equal(u'<img src="%s" width="200"/>' % (thisurl), img._repr_html_())
29 +
    assert '<img src="%s" width="200"/>' % (thisurl) == img._repr_html_()
30 30
    img = display.Image(url=thisurl)
31 -
    nt.assert_equal(u'<img src="%s"/>' % (thisurl), img._repr_html_())
31 +
    assert '<img src="%s"/>' % (thisurl) == img._repr_html_()
32 32
    img = display.Image(url=thisurl, unconfined=True)
33 -
    nt.assert_equal(u'<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 36
def test_image_mimes():
@@ -39,7 +39,7 @@
Loading
39 39
        mime = display.Image._MIMETYPES[format]
40 40
        img = display.Image(b'garbage', format=format)
41 41
        data, metadata = fmt(img)
42 -
        nt.assert_equal(sorted(data), sorted([mime, 'text/plain']))
42 +
        assert sorted(data) == sorted([mime, "text/plain"])
43 43
44 44
45 45
def test_geojson():
@@ -60,17 +60,20 @@
Loading
60 60
            "attribution": "Celestia/praesepe",
61 61
            "minZoom": 0,
62 62
            "maxZoom": 18,
63 -
        })
64 -
    nt.assert_equal(u'<IPython.core.display.GeoJSON object>', str(gj))
63 +
        },
64 +
    )
65 +
    assert "<IPython.core.display.GeoJSON object>" == str(gj)
66 +
65 67
66 68
def test_retina_png():
67 69
    here = os.path.dirname(__file__)
68 70
    img = display.Image(os.path.join(here, "2x2.png"), retina=True)
69 -
    nt.assert_equal(img.height, 1)
70 -
    nt.assert_equal(img.width, 1)
71 +
    assert img.height == 1
72 +
    assert img.width == 1
71 73
    data, md = img._repr_png_()
72 -
    nt.assert_equal(md['width'], 1)
73 -
    nt.assert_equal(md['height'], 1)
74 +
    assert md["width"] == 1
75 +
    assert md["height"] == 1
76 +
74 77
75 78
def test_embed_svg_url():
76 79
    import gzip
@@ -102,18 +105,20 @@
Loading
102 105
103 106
    with mock.patch('urllib.request.urlopen', side_effect=mocked_urlopen):
104 107
        svg = display.SVG(url=url)
105 -
        nt.assert_true(svg._repr_svg_().startswith('<svg'))
106 -
        svg = display.SVG(url=url + 'z')
107 -
        nt.assert_true(svg._repr_svg_().startswith('<svg'))
108 +
        assert svg._repr_svg_().startswith("<svg") is True
109 +
        svg = display.SVG(url=url + "z")
110 +
        assert svg._repr_svg_().startswith("<svg") is True
111 +
108 112
109 113
def test_retina_jpeg():
110 114
    here = os.path.dirname(__file__)
111 115
    img = display.Image(os.path.join(here, "2x2.jpg"), retina=True)
112 -
    nt.assert_equal(img.height, 1)
113 -
    nt.assert_equal(img.width, 1)
116 +
    assert img.height == 1
117 +
    assert img.width == 1
114 118
    data, md = img._repr_jpeg_()
115 -
    nt.assert_equal(md['width'], 1)
116 -
    nt.assert_equal(md['height'], 1)
119 +
    assert md["width"] == 1
120 +
    assert md["height"] == 1
121 +
117 122
118 123
def test_base64image():
119 124
    display.Image("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB94BCRQnOqNu0b4AAAAKSURBVAjXY2AAAAACAAHiIbwzAAAAAElFTkSuQmCC")
@@ -121,18 +126,30 @@
Loading
121 126
def test_image_filename_defaults():
122 127
    '''test format constraint, and validity of jpeg and png'''
123 128
    tpath = ipath.get_ipython_package_dir()
124 -
    nt.assert_raises(ValueError, display.Image, filename=os.path.join(tpath, 'testing/tests/badformat.zip'),
125 -
                     embed=True)
126 -
    nt.assert_raises(ValueError, display.Image)
127 -
    nt.assert_raises(ValueError, display.Image, data='this is not an image', format='badformat', embed=True)
128 -
    # check both paths to allow packages to test at build and install time
129 +
    pytest.raises(
130 +
        ValueError,
131 +
        display.Image,
132 +
        filename=os.path.join(tpath, "testing/tests/badformat.zip"),
133 +
        embed=True,
134 +
    )
135 +
    pytest.raises(ValueError, display.Image)
136 +
    pytest.raises(
137 +
        ValueError,
138 +
        display.Image,
139 +
        data="this is not an image",
140 +
        format="badformat",
141 +
        embed=True,
142 +
    )
143 +
    # check boths paths to allow packages to test at build and install time
129 144
    imgfile = os.path.join(tpath, 'core/tests/2x2.png')
130 145
    img = display.Image(filename=imgfile)
131 -
    nt.assert_equal('png', img.format)
132 -
    nt.assert_is_not_none(img._repr_png_())
133 -
    img = display.Image(filename=os.path.join(tpath, 'testing/tests/logo.jpg'), embed=False)
134 -
    nt.assert_equal('jpeg', img.format)
135 -
    nt.assert_is_none(img._repr_jpeg_())
146 +
    assert "png" == img.format
147 +
    assert img._repr_png_() is not None
148 +
    img = display.Image(
149 +
        filename=os.path.join(tpath, "testing/tests/logo.jpg"), embed=False
150 +
    )
151 +
    assert "jpeg" == img.format
152 +
    assert img._repr_jpeg_() is None
136 153
137 154
def _get_inline_config():
138 155
    from matplotlib_inline.config import InlineBackend
@@ -171,9 +188,9 @@
Loading
171 188
        display.set_matplotlib_formats(*formats)
172 189
        for mime, f in formatters.items():
173 190
            if mime in active_mimes:
174 -
                nt.assert_in(Figure, f)
191 +
                assert Figure in f
175 192
            else:
176 -
                nt.assert_not_in(Figure, f)
193 +
                assert Figure not in f
177 194
178 195
179 196
@dec.skip_without("ipykernel")
@@ -192,7 +209,7 @@
Loading
192 209
    expected["base64"] = True
193 210
    expected["fmt"] = "png"
194 211
    expected.update(cfg.print_figure_kwargs)
195 -
    nt.assert_equal(formatter_kwargs, expected)
212 +
    assert formatter_kwargs == expected
196 213
197 214
def test_display_available():
198 215
    """
@@ -213,27 +230,28 @@
Loading
213 230
        ip.run_cell('display')
214 231
215 232
def test_textdisplayobj_pretty_repr():
216 -
     p = display.Pretty("This is a simple test")
217 -
     nt.assert_equal(repr(p), '<IPython.core.display.Pretty object>')
218 -
     nt.assert_equal(p.data, 'This is a simple test')
233 +
    p = display.Pretty("This is a simple test")
234 +
    assert repr(p) == "<IPython.core.display.Pretty object>"
235 +
    assert p.data == "This is a simple test"
236 +
237 +
    p._show_mem_addr = True
238 +
    assert repr(p) == object.__repr__(p)
219 239
220 -
     p._show_mem_addr = True
221 -
     nt.assert_equal(repr(p), object.__repr__(p))
222 240
223 241
def test_displayobject_repr():
224 -
    h = display.HTML('<br />')
225 -
    nt.assert_equal(repr(h), '<IPython.core.display.HTML object>')
242 +
    h = display.HTML("<br />")
243 +
    assert repr(h) == "<IPython.core.display.HTML object>"
226 244
    h._show_mem_addr = True
227 -
    nt.assert_equal(repr(h), object.__repr__(h))
245 +
    assert repr(h) == object.__repr__(h)
228 246
    h._show_mem_addr = False
229 -
    nt.assert_equal(repr(h), '<IPython.core.display.HTML object>')
247 +
    assert repr(h) == "<IPython.core.display.HTML object>"
230 248
231 -
    j = display.Javascript('')
232 -
    nt.assert_equal(repr(j), '<IPython.core.display.Javascript object>')
249 +
    j = display.Javascript("")
250 +
    assert repr(j) == "<IPython.core.display.Javascript object>"
233 251
    j._show_mem_addr = True
234 -
    nt.assert_equal(repr(j), object.__repr__(j))
252 +
    assert repr(j) == object.__repr__(j)
235 253
    j._show_mem_addr = False
236 -
    nt.assert_equal(repr(j), '<IPython.core.display.Javascript object>')
254 +
    assert repr(j) == "<IPython.core.display.Javascript object>"
237 255
238 256
@mock.patch('warnings.warn')
239 257
def test_encourage_iframe_over_html(m_warn):
@@ -255,18 +273,22 @@
Loading
255 273
256 274
def test_progress():
257 275
    p = display.ProgressBar(10)
258 -
    nt.assert_in('0/10',repr(p))
259 -
    p.html_width = '100%'
276 +
    assert "0/10" in repr(p)
277 +
    p.html_width = "100%"
260 278
    p.progress = 5
261 -
    nt.assert_equal(p._repr_html_(), "<progress style='width:100%' max='10' value='5'></progress>")
279 +
    assert (
280 +
        p._repr_html_() == "<progress style='width:100%' max='10' value='5'></progress>"
281 +
    )
282 +
262 283
263 284
def test_progress_iter():
264 285
    with capture_output(display=False) as captured:
265 286
        for i in display.ProgressBar(5):
266 287
            out = captured.stdout
267 -
            nt.assert_in('{0}/5'.format(i), out)
288 +
            assert "{0}/5".format(i) in out
268 289
    out = captured.stdout
269 -
    nt.assert_in('5/5', out)
290 +
    assert "5/5" in out
291 +
270 292
271 293
def test_json():
272 294
    d = {'a': 5}
@@ -284,13 +306,13 @@
Loading
284 306
        display.JSON(d, expanded=True, root='custom'),
285 307
    ]
286 308
    for j, md in zip(json_objs, metadata):
287 -
        nt.assert_equal(j._repr_json_(), (d, md))
309 +
        assert j._repr_json_() == (d, md)
288 310
289 311
    with warnings.catch_warnings(record=True) as w:
290 312
        warnings.simplefilter("always")
291 313
        j = display.JSON(json.dumps(d))
292 -
        nt.assert_equal(len(w), 1)
293 -
        nt.assert_equal(j._repr_json_(), (d, metadata[0]))
314 +
        assert len(w) == 1
315 +
        assert j._repr_json_() == (d, metadata[0])
294 316
295 317
    json_objs = [
296 318
        display.JSON(lis),
@@ -299,23 +321,24 @@
Loading
299 321
        display.JSON(lis, expanded=True, root='custom'),
300 322
    ]
301 323
    for j, md in zip(json_objs, metadata):
302 -
        nt.assert_equal(j._repr_json_(), (lis, md))
324 +
        assert j._repr_json_() == (lis, md)
303 325
304 326
    with warnings.catch_warnings(record=True) as w:
305 327
        warnings.simplefilter("always")
306 328
        j = display.JSON(json.dumps(lis))
307 -
        nt.assert_equal(len(w), 1)
308 -
        nt.assert_equal(j._repr_json_(), (lis, metadata[0]))
329 +
        assert len(w) == 1
330 +
        assert j._repr_json_() == (lis, metadata[0])
331 +
309 332
310 333
def test_video_embedding():
311 334
    """use a tempfile, with dummy-data, to ensure that video embedding doesn't crash"""
312 335
    v = display.Video("http://ignored")
313 336
    assert not v.embed
314 337
    html = v._repr_html_()
315 -
    nt.assert_not_in('src="data:', html)
316 -
    nt.assert_in('src="http://ignored"', html)
338 +
    assert 'src="data:' not in html
339 +
    assert 'src="http://ignored"' in html
317 340
318 -
    with nt.assert_raises(ValueError):
341 +
    with pytest.raises(ValueError):
319 342
        v = display.Video(b'abc')
320 343
321 344
    with NamedFileInTemporaryDirectory('test.mp4') as f:
@@ -325,52 +348,53 @@
Loading
325 348
        v = display.Video(f.name)
326 349
        assert not v.embed
327 350
        html = v._repr_html_()
328 -
        nt.assert_not_in('src="data:', html)
351 +
        assert 'src="data:' not in html
329 352
330 353
        v = display.Video(f.name, embed=True)
331 354
        html = v._repr_html_()
332 -
        nt.assert_in('src="data:video/mp4;base64,YWJj"',html)
355 +
        assert 'src="data:video/mp4;base64,YWJj"' in html
333 356
334 357
        v = display.Video(f.name, embed=True, mimetype='video/other')
335 358
        html = v._repr_html_()
336 -
        nt.assert_in('src="data:video/other;base64,YWJj"',html)
359 +
        assert 'src="data:video/other;base64,YWJj"' in html
337 360
338 361
        v = display.Video(b'abc', embed=True, mimetype='video/mp4')
339 362
        html = v._repr_html_()
340 -
        nt.assert_in('src="data:video/mp4;base64,YWJj"',html)
363 +
        assert 'src="data:video/mp4;base64,YWJj"' in html
341 364
342 365
        v = display.Video(u'YWJj', embed=True, mimetype='video/xyz')
343 366
        html = v._repr_html_()
344 -
        nt.assert_in('src="data:video/xyz;base64,YWJj"',html)
367 +
        assert 'src="data:video/xyz;base64,YWJj"' in html
345 368
346 369
def test_html_metadata():
347 370
    s = "<h1>Test</h1>"
348 371
    h = display.HTML(s, metadata={"isolated": True})
349 -
    nt.assert_equal(h._repr_html_(), (s, {"isolated": True}))
372 +
    assert h._repr_html_() == (s, {"isolated": True})
373 +
350 374
351 375
def test_display_id():
352 376
    ip = get_ipython()
353 377
    with mock.patch.object(ip.display_pub, 'publish') as pub:
354 378
        handle = display.display('x')
355 -
        nt.assert_is(handle, None)
379 +
        assert handle is None
356 380
        handle = display.display('y', display_id='secret')
357 -
        nt.assert_is_instance(handle, display.DisplayHandle)
381 +
        assert isinstance(handle, display.DisplayHandle)
358 382
        handle2 = display.display('z', display_id=True)
359 -
        nt.assert_is_instance(handle2, display.DisplayHandle)
360 -
    nt.assert_not_equal(handle.display_id, handle2.display_id)
383 +
        assert isinstance(handle2, display.DisplayHandle)
384 +
    assert handle.display_id != handle2.display_id
361 385
362 -
    nt.assert_equal(pub.call_count, 3)
386 +
    assert pub.call_count == 3
363 387
    args, kwargs = pub.call_args_list[0]
364 -
    nt.assert_equal(args, ())
365 -
    nt.assert_equal(kwargs, {
388 +
    assert args == ()
389 +
    assert kwargs == {
366 390
        'data': {
367 391
            'text/plain': repr('x')
368 392
        },
369 393
        'metadata': {},
370 -
    })
394 +
    }
371 395
    args, kwargs = pub.call_args_list[1]
372 -
    nt.assert_equal(args, ())
373 -
    nt.assert_equal(kwargs, {
396 +
    assert args == ()
397 +
    assert kwargs == {
374 398
        'data': {
375 399
            'text/plain': repr('y')
376 400
        },
@@ -378,10 +402,10 @@
Loading
378 402
        'transient': {
379 403
            'display_id': handle.display_id,
380 404
        },
381 -
    })
405 +
    }
382 406
    args, kwargs = pub.call_args_list[2]
383 -
    nt.assert_equal(args, ())
384 -
    nt.assert_equal(kwargs, {
407 +
    assert args == ()
408 +
    assert kwargs == {
385 409
        'data': {
386 410
            'text/plain': repr('z')
387 411
        },
@@ -389,19 +413,19 @@
Loading
389 413
        'transient': {
390 414
            'display_id': handle2.display_id,
391 415
        },
392 -
    })
416 +
    }
393 417
394 418
395 419
def test_update_display():
396 420
    ip = get_ipython()
397 421
    with mock.patch.object(ip.display_pub, 'publish') as pub:
398 -
        with nt.assert_raises(TypeError):
422 +
        with pytest.raises(TypeError):
399 423
            display.update_display('x')
400 424
        display.update_display('x', display_id='1')
401 425
        display.update_display('y', display_id='2')
402 426
    args, kwargs = pub.call_args_list[0]
403 -
    nt.assert_equal(args, ())
404 -
    nt.assert_equal(kwargs, {
427 +
    assert args == ()
428 +
    assert kwargs == {
405 429
        'data': {
406 430
            'text/plain': repr('x')
407 431
        },
@@ -410,10 +434,10 @@
Loading
410 434
            'display_id': '1',
411 435
        },
412 436
        'update': True,
413 -
    })
437 +
    }
414 438
    args, kwargs = pub.call_args_list[1]
415 -
    nt.assert_equal(args, ())
416 -
    nt.assert_equal(kwargs, {
439 +
    assert args == ()
440 +
    assert kwargs == {
417 441
        'data': {
418 442
            'text/plain': repr('y')
419 443
        },
@@ -422,22 +446,22 @@
Loading
422 446
            'display_id': '2',
423 447
        },
424 448
        'update': True,
425 -
    })
449 +
    }
426 450
427 451
428 452
def test_display_handle():
429 453
    ip = get_ipython()
430 454
    handle = display.DisplayHandle()
431 -
    nt.assert_is_instance(handle.display_id, str)
432 -
    handle = display.DisplayHandle('my-id')
433 -
    nt.assert_equal(handle.display_id, 'my-id')
434 -
    with mock.patch.object(ip.display_pub, 'publish') as pub:
435 -
        handle.display('x')
436 -
        handle.update('y')
455 +
    assert isinstance(handle.display_id, str)
456 +
    handle = display.DisplayHandle("my-id")
457 +
    assert handle.display_id == "my-id"
458 +
    with mock.patch.object(ip.display_pub, "publish") as pub:
459 +
        handle.display("x")
460 +
        handle.update("y")
437 461
438 462
    args, kwargs = pub.call_args_list[0]
439 -
    nt.assert_equal(args, ())
440 -
    nt.assert_equal(kwargs, {
463 +
    assert args == ()
464 +
    assert kwargs == {
441 465
        'data': {
442 466
            'text/plain': repr('x')
443 467
        },
@@ -445,10 +469,10 @@
Loading
445 469
        'transient': {
446 470
            'display_id': handle.display_id,
447 471
        }
448 -
    })
472 +
    }
449 473
    args, kwargs = pub.call_args_list[1]
450 -
    nt.assert_equal(args, ())
451 -
    nt.assert_equal(kwargs, {
474 +
    assert args == ()
475 +
    assert kwargs == {
452 476
        'data': {
453 477
            'text/plain': repr('y')
454 478
        },
@@ -457,34 +481,31 @@
Loading
457 481
            'display_id': handle.display_id,
458 482
        },
459 483
        'update': True,
460 -
    })
484 +
    }
461 485
462 486
463 487
def test_image_alt_tag():
464 488
    """Simple test for display.Image(args, alt=x,)"""
465 489
    thisurl = "http://example.com/image.png"
466 490
    img = display.Image(url=thisurl, alt="an image")
467 -
    nt.assert_equal(u'<img src="%s" alt="an image"/>' % (thisurl), img._repr_html_())
491 +
    assert '<img src="%s" alt="an image"/>' % (thisurl) == img._repr_html_()
468 492
    img = display.Image(url=thisurl, unconfined=True, alt="an image")
469 -
    nt.assert_equal(
470 -
        u'<img src="%s" class="unconfined" alt="an image"/>' % (thisurl),
471 -
        img._repr_html_(),
493 +
    assert (
494 +
        '<img src="%s" class="unconfined" alt="an image"/>' % (thisurl)
495 +
        == img._repr_html_()
472 496
    )
473 497
    img = display.Image(url=thisurl, alt='>"& <')
474 -
    nt.assert_equal(
475 -
        u'<img src="%s" alt="&gt;&quot;&amp; &lt;"/>' % (thisurl), img._repr_html_()
476 -
    )
498 +
    assert '<img src="%s" alt="&gt;&quot;&amp; &lt;"/>' % (thisurl) == img._repr_html_()
477 499
478 500
    img = display.Image(url=thisurl, metadata={"alt": "an image"})
479 -
    nt.assert_equal(img.alt, "an image")
480 -
501 +
    assert img.alt == "an image"
481 502
    here = os.path.dirname(__file__)
482 503
    img = display.Image(os.path.join(here, "2x2.png"), alt="an image")
483 -
    nt.assert_equal(img.alt, "an image")
504 +
    assert img.alt == "an image"
484 505
    _, md = img._repr_png_()
485 -
    nt.assert_equal(md["alt"], "an image")
506 +
    assert md["alt"] == "an image"
486 507
487 508
488 -
@nt.raises(FileNotFoundError)
489 509
def test_image_bad_filename_raises_proper_exception():
490 -
    display.Image("/this/file/does/not/exist/")._repr_png_()
510 +
    with pytest.raises(FileNotFoundError):
511 +
        display.Image("/this/file/does/not/exist/")._repr_png_()

@@ -8,8 +8,6 @@
Loading
8 8
import unittest
9 9
import sys
10 10
11 -
import nose.tools as nt
12 -
13 11
from IPython.core import inputsplitter as isp
14 12
from IPython.core.inputtransformer import InputTransformer
15 13
from IPython.core.tests.test_inputtransformer import syntax, syntax_ml
@@ -98,10 +96,10 @@
Loading
98 96
99 97
def test_get_input_encoding():
100 98
    encoding = isp.get_input_encoding()
101 -
    nt.assert_true(isinstance(encoding, str))
99 +
    assert isinstance(encoding, str)
102 100
    # simple-minded check that at least encoding a simple string works with the
103 101
    # encoding we got.
104 -
    nt.assert_equal(u'test'.encode(encoding), b'test')
102 +
    assert "test".encode(encoding) == b"test"
105 103
106 104
107 105
class NoInputEncodingTestCase(unittest.TestCase):
@@ -419,7 +417,7 @@
Loading
419 417
                for lraw, out_t_part in line_pairs:
420 418
                    if out_t_part is not None:
421 419
                        out_t_parts.append(out_t_part)
422 -
                    
420 +
423 421
                    if lraw is not None:
424 422
                        isp.push(lraw)
425 423
                        raw_parts.append(lraw)
@@ -442,7 +440,7 @@
Loading
442 440
                out = isp.transform_cell(raw)
443 441
                # Match ignoring trailing whitespace
444 442
                self.assertEqual(out.rstrip(), out_t.rstrip())
445 -
    
443 +
446 444
    def test_cellmagic_preempt(self):
447 445
        isp = self.isp
448 446
        for raw, name, line, cell in [
@@ -464,17 +462,17 @@
Loading
464 462
        class CommentTransformer(InputTransformer):
465 463
            def __init__(self):
466 464
                self._lines = []
467 -
            
465 +
468 466
            def push(self, line):
469 467
                self._lines.append(line + '#')
470 -
            
468 +
471 469
            def reset(self):
472 470
                text = '\n'.join(self._lines)
473 471
                self._lines = []
474 472
                return text
475 -
        
473 +
476 474
        isp.physical_line_transforms.insert(0, CommentTransformer())
477 -
        
475 +
478 476
        for raw, expected in [
479 477
            ("a=5", "a=5#"),
480 478
            ("%ls foo", "get_ipython().run_line_magic(%r, %r)" % (u'ls', u'foo#')),
@@ -527,38 +525,38 @@
Loading
527 525
# Tests for cell magics support
528 526
529 527
def test_last_blank():
530 -
    nt.assert_false(isp.last_blank(''))
531 -
    nt.assert_false(isp.last_blank('abc'))
532 -
    nt.assert_false(isp.last_blank('abc\n'))
533 -
    nt.assert_false(isp.last_blank('abc\na'))
528 +
    assert isp.last_blank("") is False
529 +
    assert isp.last_blank("abc") is False
530 +
    assert isp.last_blank("abc\n") is False
531 +
    assert isp.last_blank("abc\na") is False
534 532
535 -
    nt.assert_true(isp.last_blank('\n'))
536 -
    nt.assert_true(isp.last_blank('\n '))
537 -
    nt.assert_true(isp.last_blank('abc\n '))
538 -
    nt.assert_true(isp.last_blank('abc\n\n'))
539 -
    nt.assert_true(isp.last_blank('abc\nd\n\n'))
540 -
    nt.assert_true(isp.last_blank('abc\nd\ne\n\n'))
541 -
    nt.assert_true(isp.last_blank('abc \n \n \n\n'))
533 +
    assert isp.last_blank("\n") is True
534 +
    assert isp.last_blank("\n ") is True
535 +
    assert isp.last_blank("abc\n ") is True
536 +
    assert isp.last_blank("abc\n\n") is True
537 +
    assert isp.last_blank("abc\nd\n\n") is True
538 +
    assert isp.last_blank("abc\nd\ne\n\n") is True
539 +
    assert isp.last_blank("abc \n \n \n\n") is True
542 540
543 541
544 542
def test_last_two_blanks():
545 -
    nt.assert_false(isp.last_two_blanks(''))
546 -
    nt.assert_false(isp.last_two_blanks('abc'))
547 -
    nt.assert_false(isp.last_two_blanks('abc\n'))
548 -
    nt.assert_false(isp.last_two_blanks('abc\n\na'))
549 -
    nt.assert_false(isp.last_two_blanks('abc\n \n'))
550 -
    nt.assert_false(isp.last_two_blanks('abc\n\n'))
551 -
552 -
    nt.assert_true(isp.last_two_blanks('\n\n'))
553 -
    nt.assert_true(isp.last_two_blanks('\n\n '))
554 -
    nt.assert_true(isp.last_two_blanks('\n \n'))
555 -
    nt.assert_true(isp.last_two_blanks('abc\n\n '))
556 -
    nt.assert_true(isp.last_two_blanks('abc\n\n\n'))
557 -
    nt.assert_true(isp.last_two_blanks('abc\n\n \n'))
558 -
    nt.assert_true(isp.last_two_blanks('abc\n\n \n '))
559 -
    nt.assert_true(isp.last_two_blanks('abc\n\n \n \n'))
560 -
    nt.assert_true(isp.last_two_blanks('abc\nd\n\n\n'))
561 -
    nt.assert_true(isp.last_two_blanks('abc\nd\ne\nf\n\n\n'))
543 +
    assert isp.last_two_blanks("") is False
544 +
    assert isp.last_two_blanks("abc") is False
545 +
    assert isp.last_two_blanks("abc\n") is False
546 +
    assert isp.last_two_blanks("abc\n\na") is False
547 +
    assert isp.last_two_blanks("abc\n \n") is False
548 +
    assert isp.last_two_blanks("abc\n\n") is False
549 +
550 +
    assert isp.last_two_blanks("\n\n") is True
551 +
    assert isp.last_two_blanks("\n\n ") is True
552 +
    assert isp.last_two_blanks("\n \n") is True
553 +
    assert isp.last_two_blanks("abc\n\n ") is True
554 +
    assert isp.last_two_blanks("abc\n\n\n") is True
555 +
    assert isp.last_two_blanks("abc\n\n \n") is True
556 +
    assert isp.last_two_blanks("abc\n\n \n ") is True
557 +
    assert isp.last_two_blanks("abc\n\n \n \n") is True
558 +
    assert isp.last_two_blanks("abc\nd\n\n\n") is True
559 +
    assert isp.last_two_blanks("abc\nd\ne\nf\n\n\n") is True
562 560
563 561
564 562
class CellMagicsCommon(object):
@@ -567,11 +565,11 @@
Loading
567 565
        src = "%%cellm line\nbody\n"
568 566
        out = self.sp.transform_cell(src)
569 567
        ref = "get_ipython().run_cell_magic('cellm', 'line', 'body')\n"
570 -
        nt.assert_equal(out, ref)
571 -
    
568 +
        assert out == ref
569 +
572 570
    def test_cellmagic_help(self):
573 571
        self.sp.push('%%cellm?')
574 -
        nt.assert_false(self.sp.push_accepts_more())
572 +
        assert self.sp.push_accepts_more() is False
575 573
576 574
    def tearDown(self):
577 575
        self.sp.reset()
@@ -582,14 +580,14 @@
Loading
582 580
583 581
    def test_incremental(self):
584 582
        sp = self.sp
585 -
        sp.push('%%cellm firstline\n')
586 -
        nt.assert_true(sp.push_accepts_more()) #1
587 -
        sp.push('line2\n')
588 -
        nt.assert_true(sp.push_accepts_more()) #2
589 -
        sp.push('\n')
583 +
        sp.push("%%cellm firstline\n")
584 +
        assert sp.push_accepts_more() is True  # 1
585 +
        sp.push("line2\n")
586 +
        assert sp.push_accepts_more() is True  # 2
587 +
        sp.push("\n")
590 588
        # This should accept a blank line and carry on until the cell is reset
591 -
        nt.assert_true(sp.push_accepts_more()) #3
592 -
    
589 +
        assert sp.push_accepts_more() is True  # 3
590 +
593 591
    def test_no_strip_coding(self):
594 592
        src = '\n'.join([
595 593
            '%%writefile foo.py',
@@ -597,7 +595,7 @@
Loading
597 595
            'print(u"üñîçø∂é")',
598 596
        ])
599 597
        out = self.sp.transform_cell(src)
600 -
        nt.assert_in('# coding: utf-8', out)
598 +
        assert "# coding: utf-8" in out
601 599
602 600
603 601
class LineModeCellMagics(CellMagicsCommon, unittest.TestCase):
@@ -605,11 +603,12 @@
Loading
605 603
606 604
    def test_incremental(self):
607 605
        sp = self.sp
608 -
        sp.push('%%cellm line2\n')
609 -
        nt.assert_true(sp.push_accepts_more()) #1
610 -
        sp.push('\n')
606 +
        sp.push("%%cellm line2\n")
607 +
        assert sp.push_accepts_more() is True  # 1
608 +
        sp.push("\n")
611 609
        # In this case, a blank line should end the cell magic
612 -
        nt.assert_false(sp.push_accepts_more()) #2
610 +
        assert sp.push_accepts_more() is False  # 2
611 +
613 612
614 613
indentation_samples = [
615 614
    ('a = 1', 0),

@@ -1,7 +1,6 @@
Loading
1 1
import tempfile, os
2 2
3 3
from traitlets.config.loader import Config
4 -
import nose.tools as nt
5 4
6 5
7 6
def setup_module():
@@ -23,10 +22,10 @@
Loading
23 22
    ip.magic('store foobar foobaz')
24 23
25 24
    # Check storing
26 -
    nt.assert_equal(ip.db['autorestore/foo'], 78)
27 -
    nt.assert_in('bar', ip.db['stored_aliases'])
28 -
    nt.assert_equal(ip.db['autorestore/foobar'], 79)
29 -
    nt.assert_equal(ip.db['autorestore/foobaz'], '80')
25 +
    assert ip.db["autorestore/foo"] == 78