def test_format_config():
    """config objects don't pretend to support fancy reprs with lazy attrs"""
    f = HTMLFormatter()
    cfg = Config()
    with capture_output() as captured:
        result = f(cfg)
    nt.assert_is(result, None)
    nt.assert_equal(captured.stderr, "")

    with capture_output() as captured:
        result = f(Config)
    nt.assert_is(result, None)
    nt.assert_equal(captured.stderr, "")
Exemple #2
0
def test_print_method_bound():
    f = HTMLFormatter()
    class MyHTML(object):
        def _repr_html_(self):
            return "hello"
    with capture_output() as captured:
        result = f(MyHTML)
    nt.assert_is(result, None)
    nt.assert_not_in("FormatterWarning", captured.stderr)

    with capture_output() as captured:
        result = f(MyHTML())
    nt.assert_equal(result, "hello")
    nt.assert_equal(captured.stderr, "")
Exemple #3
0
def run_cell(cmd):
    with capture_output() as io:
        res = ip.run_cell(content)
        #print 'suc', res.success
        #print 'res', res.result
    res_out = io.stdout
    print 'res out', res_out
def test_progress_iter():
    with capture_output(display=False) as captured:
        for i in display.ProgressBar(5):
            out = captured.stdout
            nt.assert_in('{0}/5'.format(i), out)
    out = captured.stdout
    nt.assert_in('5/5', out)
Exemple #5
0
    def sample(self, niter, thin=1, variables=None, run_diagnostic=True):
        """
        variables: if None, use all as extracted with self.get_variables(which='unobserved')
        """
        if not self._burnin_ok:
            print "WARNING: you might want to run burnin() first"
        if variables==None:
            variables=self.get_variables(which='unobserved')
        robj.r.assign('pyjags_variables', np.array(variables))
        
        with capture_output() as io: # get rid of some remaining output
            robj.r(_R_sample_dic.format(niter=niter,
                                        thin=thin))
    
        ## temporarily disable numpy conversion
        rpy2.robjects.numpy2ri.deactivate()
            
        if run_diagnostic:
            robj.r('pyjags_gelman=gelman.diag(pyjags_samp$samples)$psrf')
            self._gelmandiag_last_run=com.convert_robj(robj.r('pyjags_gelman'))
            if np.any(self._gelmandiag_last_run.iloc[:,0]>1.05):
                print "WARNING: there may be problems with your convergence (some R>1.05)"
        else:
            self._gelmandiag_last_run=None
        ms=com.convert_robj(robj.r('as.matrix(pyjags_samp$samples)'))        
        self._dic_last_run=com.convert_robj(robj.r('pyjags_samp$dic'))

        ## enable numpy conversion again
        rpy2.robjects.numpy2ri.activate()
        
        return ms
 def test_px_pylab(self):
     """%pylab works on engines"""
     ip = get_ipython()
     v = self.client[-1]
     v.block = True
     v.activate()
     
     with capture_output() as io:
         ip.magic("px %pylab inline")
     
     self.assertIn("Populating the interactive namespace from numpy and matplotlib", io.stdout)
     
     with capture_output(display=False) as io:
         ip.magic("px plot(rand(100))")
     self.assertIn('Out[', io.stdout)
     self.assertIn('matplotlib.lines', io.stdout)
Exemple #7
0
 def test_cellpx_groupby_engine(self):
     """%%px --group-outputs=engine"""
     ip = get_ipython()
     v = self.client[:]
     v.block = True
     v.activate()
     
     v['generate_output'] = generate_output
     
     with capture_output() as io:
         ip.run_cell_magic('px', '--group-outputs=engine', 'generate_output()')
     
     self.assertFalse('\n\n' in io.stdout)
     lines = io.stdout.splitlines()[1:]
     expected = [
         r'\[stdout:\d+\]',
         'stdout',
         'stdout2',
         r'\[output:\d+\]',
         r'IPython\.core\.display\.HTML',
         r'IPython\.core\.display\.Math',
         r'Out\[\d+:\d+\]:.*IPython\.core\.display\.Math',
         ] * len(v)
     
     self.assertEquals(len(lines), len(expected), io.stdout)
     for line,expect in zip(lines, expected):
         if isinstance(expect, str):
             expect = [expect]
         for ex in expect:
             self.assertTrue(re.search(ex, line) is not None, "Expected %r in %r" % (ex, line))
     
     self._check_generated_stderr(io.stderr, len(v))
Exemple #8
0
 def test_compositeerror_truncate(self):
     """Truncate CompositeErrors with many exceptions"""
     view = self.client[:]
     msg_ids = []
     for i in range(10):
         ar = view.execute("1/0")
         msg_ids.extend(ar.msg_ids)
     
     ar = self.client.get_result(msg_ids)
     try:
         ar.get()
     except error.CompositeError as _e:
         e = _e
     else:
         self.fail("Should have raised CompositeError")
     
     lines = e.render_traceback()
     with capture_output() as io:
         e.print_traceback()
     
     self.assertTrue("more exceptions" in lines[-1])
     count = e.tb_limit
     
     self.assertEqual(io.stdout.count('ZeroDivisionError'), 2 * count, io.stdout)
     self.assertEqual(io.stdout.count('by zero'), count, io.stdout)
     self.assertEqual(io.stdout.count(':execute'), count, io.stdout)
Exemple #9
0
    def test_autopx_blocking(self):
        ip = get_ipython()
        v = self.client[-1]
        v.activate()
        v.block=True

        with capture_output() as io:
            ip.magic('autopx')
            ip.run_cell('\n'.join(('a=5','b=12345','c=0')))
            ip.run_cell('b*=2')
            ip.run_cell('print (b)')
            ip.run_cell('b')
            ip.run_cell("b/c")
            ip.magic('autopx')
        
        output = io.stdout
        
        self.assertTrue(output.startswith('%autopx enabled'), output)
        self.assertTrue(output.rstrip().endswith('%autopx disabled'), output)
        self.assertTrue('RemoteError: ZeroDivisionError' in output, output)
        self.assertTrue('\nOut[' in output, output)
        self.assertTrue(': 24690' in output, output)
        ar = v.get_result(-1)
        self.assertEquals(v['a'], 5)
        self.assertEquals(v['b'], 24690)
        self.assertRaisesRemote(ZeroDivisionError, ar.get)
Exemple #10
0
    def _run_f2py(self, argv, show_captured=False, verbosity=0):
        """
        Here we directly call the numpy.f2py.f2py2e.run_compile() entry point,
        after some small amount of setup to get sys.argv and the current
        working directory set appropriately.
        """
        old_argv = sys.argv
        old_cwd = os.getcwdu() if sys.version_info[0] == 2 else os.getcwd()
        try:
            sys.argv = ['f2py'] + list(map(str, argv))
            if verbosity > 1:
                print("Running...\n   %s" % ' '.join(sys.argv))

            os.chdir(self._lib_dir)
            try:
                with capture_output() as captured:
                    f2py2e.main()
                if show_captured or verbosity > 2:
                    captured()
            except SystemExit as e:
                captured()
                raise UsageError(str(e))
        finally:
            sys.argv = old_argv
            os.chdir(old_cwd)
Exemple #11
0
    def test_autopx_nonblocking(self):
        ip = get_ipython()
        v = self.client[-1]
        v.activate()
        v.block=False

        with capture_output() as io:
            ip.magic('autopx')
            ip.run_cell('\n'.join(('a=5','b=10','c=0')))
            ip.run_cell('print (b)')
            ip.run_cell('import time; time.sleep(0.1)')
            ip.run_cell("b/c")
            ip.run_cell('b*=2')
            ip.magic('autopx')
        
        output = io.stdout.rstrip()
        
        self.assertTrue(output.startswith('%autopx enabled'))
        self.assertTrue(output.endswith('%autopx disabled'))
        self.assertFalse('ZeroDivisionError' in output)
        ar = v.get_result(-2)
        self.assertRaisesRemote(ZeroDivisionError, ar.get)
        # prevent TaskAborted on pulls, due to ZeroDivisionError
        time.sleep(0.5)
        self.assertEquals(v['a'], 5)
        # b*=2 will not fire, due to abort
        self.assertEquals(v['b'], 10)
def test__run_query():
    magics.context._credentials = None

    job_id = 'job_1234'
    sql = 'SELECT 17'
    responses = [
        futures.TimeoutError,
        futures.TimeoutError,
        [table.Row((17,), {'num': 0})]
    ]

    client_patch = mock.patch(
        'google.cloud.bigquery.magics.bigquery.Client', autospec=True)
    with client_patch as client_mock, io.capture_output() as captured:
        client_mock().query(sql).result.side_effect = responses
        client_mock().query(sql).job_id = job_id

        query_job = magics._run_query(client_mock(), sql)

    lines = re.split('\n|\r', captured.stdout)
    # Removes blanks & terminal code (result of display clearing)
    updates = list(filter(lambda x: bool(x) and x != '\x1b[2K', lines))

    assert query_job.job_id == job_id
    expected_first_line = "Executing query with job ID: {}".format(job_id)
    assert updates[0] == expected_first_line
    execution_updates = updates[1:-1]
    assert len(execution_updates) == 3  # one update per API response
    assert all(re.match("Query executing: .*s", line)
               for line in execution_updates)
    assert re.match("Query complete after .*s", updates[-1])
Exemple #13
0
def test_capture_output():
    """capture_output() context works"""

    with capture_output() as io:
        print("hi, stdout")
        print("hi, stderr", file=sys.stderr)

    nt.assert_equal(io.stdout, "hi, stdout\n")
    nt.assert_equal(io.stderr, "hi, stderr\n")
Exemple #14
0
 def capture(self, line, cell):
     """run the cell, capturing stdout/err"""
     args = magic_arguments.parse_argstring(self.capture, line)
     out = not args.no_stdout
     err = not args.no_stderr
     with capture_output(out, err) as io:
         self.shell.run_cell(cell)
     if args.output:
         self.shell.user_ns[args.output] = io
Exemple #15
0
def test_capture_output():
    """capture_output() context works"""
    
    with capture_output() as io:
        print('hi, stdout')
        print('hi, stderr', file=sys.stderr)
    
    nt.assert_equals(io.stdout, 'hi, stdout\n')
    nt.assert_equals(io.stderr, 'hi, stderr\n')
Exemple #16
0
def test_config_available_configs():
    """ test that config magic prints available configs in unique and
    sorted order. """
    with capture_output() as captured:
        _ip.magic('config')

    stdout = captured.stdout
    config_classes = stdout.strip().split('\n')[1:]
    nt.assert_list_equal(config_classes, sorted(set(config_classes)))
def test_warn_error_for_type():
    f = HTMLFormatter()
    f.for_type(int, lambda i: name_error)
    with capture_output() as captured:
        result = f(5)
    nt.assert_is(result, None)
    nt.assert_in("Traceback", captured.stdout)
    nt.assert_in("NameError", captured.stdout)
    nt.assert_in("name_error", captured.stdout)
Exemple #18
0
def test_warn_error_for_type():
    f = HTMLFormatter()
    f.for_type(int, lambda i: name_error)
    with capture_output() as captured:
        result = f(5)
    nt.assert_is(result, None)
    nt.assert_in("FormatterWarning", captured.stderr)
    nt.assert_in("text/html", captured.stderr)
    nt.assert_in("name_error", captured.stderr)
Exemple #19
0
    def test_display_empty_streams_single(self):
        """empty stdout/err are not displayed (single result)"""
        self.minimum_engines(1)
        
        v = self.client[-1]
        ar = v.execute("print (5555)")
        ar.get(5)
        with capture_output() as io:
            ar.display_outputs()
        self.assertEqual(io.stderr, '')
        self.assertEqual('5555\n', io.stdout)

        ar = v.execute("a=5")
        ar.get(5)
        with capture_output() as io:
            ar.display_outputs()
        self.assertEqual(io.stderr, '')
        self.assertEqual(io.stdout, '')
Exemple #20
0
 def test_px_pylab(self):
     """%pylab works on engines"""
     ip = get_ipython()
     v = self.client[-1]
     v.block = True
     v.activate()
     
     with capture_output() as io:
         ip.magic("px %pylab inline")
     
     self.assertTrue("Welcome to pylab" in io.stdout, io.stdout)
     self.assertTrue("backend_inline" in io.stdout, io.stdout)
     
     with capture_output() as io:
         ip.magic("px plot(rand(100))")
     
     self.assertTrue('Out[' in io.stdout, io.stdout)
     self.assertTrue('matplotlib.lines' in io.stdout, io.stdout)
def test_magic_magic():
    """Test %magic"""
    ip = get_ipython()
    with capture_output() as captured:
        ip.magic("magic")

    stdout = captured.stdout
    nt.assert_in('%magic', stdout)
    nt.assert_in('IPython', stdout)
    nt.assert_in('Available', stdout)
Exemple #22
0
 def test_remoteerror_render_exception(self):
     """RemoteErrors get nice tracebacks"""
     view = self.client[-1]
     ar = view.execute("1/0")
     ip = get_ipython()
     ip.user_ns['ar'] = ar
     with capture_output() as io:
         ip.run_cell("ar.get(2)")
     
     self.assertTrue('ZeroDivisionError' in io.stdout, io.stdout)
Exemple #23
0
def test_bad_repr_traceback():
    f = PlainTextFormatter()
    bad = BadRepr()
    with capture_output() as captured:
        result = f(bad)
    # catches error, returns None
    assert result is None
    assert "Traceback" in captured.stdout
    assert "__repr__" in captured.stdout
    assert "ValueError" in captured.stdout
Exemple #24
0
 def capture(self, line, cell):
     """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
     args = magic_arguments.parse_argstring(self.capture, line)
     out = not args.no_stdout
     err = not args.no_stderr
     disp = not args.no_display
     with capture_output(out, err, disp) as io:
         self.shell.run_cell(cell)
     if args.output:
         self.shell.user_ns[args.output] = io
def test_bad_repr_traceback():
    f = PlainTextFormatter()
    bad = BadRepr()
    with capture_output() as captured:
        result = f(bad)
    # catches error, returns None
    nt.assert_is(result, None)
    nt.assert_in("Traceback", captured.stdout)
    nt.assert_in("__repr__", captured.stdout)
    nt.assert_in("ValueError", captured.stdout)
def test_bad_repr_traceback():
    f = PlainTextFormatter()
    bad = BadRepr()
    with capture_output() as captured:
        result = f(bad)
    # catches error, returns None
    nt.assert_is(result, None)
    nt.assert_in("Traceback", captured.stdout)
    nt.assert_in("__repr__", captured.stdout)
    nt.assert_in("ValueError", captured.stdout)
Exemple #27
0
def test_magic_magic():
    """Test %magic"""
    ip = get_ipython()
    with capture_output() as captured:
        ip.magic("magic")

    stdout = captured.stdout
    assert "%magic" in stdout
    assert "IPython" in stdout
    assert "Available" in stdout
    def test_px_pylab(self):
        """%pylab works on engines"""
        pytest.importorskip('matplotlib')
        ip = get_ipython()
        v = self.client[-1]
        v.block = True
        v.activate()

        with capture_output() as io:
            ip.magic("px %pylab inline")

        self.assertIn(
            "Populating the interactive namespace from numpy and matplotlib",
            io.stdout)

        with capture_output(display=False) as io:
            ip.magic("px plot(rand(100))")
        self.assertIn('Out[', io.stdout)
        self.assertIn('matplotlib.lines', io.stdout)
Exemple #29
0
 def capture(self, line, cell):
     """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
     args = magic_arguments.parse_argstring(self.capture, line)
     out = not args.no_stdout
     err = not args.no_stderr
     disp = not args.no_display
     with capture_output(out, err, disp) as io:
         self.shell.run_cell(cell)
     if args.output:
         self.shell.user_ns[args.output] = io
Exemple #30
0
def test_config_print_class():
    """ test that config with a classname prints the class's options. """
    with capture_output() as captured:
        _ip.magic('config TerminalInteractiveShell')

    stdout = captured.stdout
    if not re.match("TerminalInteractiveShell.* options", stdout.splitlines()[0]):
        print(stdout)
        raise AssertionError("1st line of stdout not like "
                             "'TerminalInteractiveShell.* options'")
Exemple #31
0
def test_config_print_class():
    """ test that config with a classname prints the class's options. """
    with capture_output() as captured:
        _ip.magic('config TerminalInteractiveShell')

    stdout = captured.stdout
    assert re.match(
        "TerminalInteractiveShell.* options",
        stdout.splitlines()[0]
    ), f"{stdout}\n\n1st line of stdout not like 'TerminalInteractiveShell.* options'"
Exemple #32
0
def test_config_print_class():
    """ test that config with a classname prints the class's options. """
    with capture_output() as captured:
        _ip.magic('config TerminalInteractiveShell')

    stdout = captured.stdout
    if not re.match("TerminalInteractiveShell.* options", stdout.splitlines()[0]):
        print(stdout)
        raise AssertionError("1st line of stdout not like "
                             "'TerminalInteractiveShell.* options'")
Exemple #33
0
def test_magic_magic():
    """Test %magic"""
    ip = get_ipython()
    with capture_output() as captured:
        ip.magic("magic")
    
    stdout = captured.stdout
    nt.assert_in('%magic', stdout)
    nt.assert_in('IPython', stdout)
    nt.assert_in('Available', stdout)
Exemple #34
0
    def test_remoteerror_render_exception(self):
        """RemoteErrors get nice tracebacks"""
        view = self.client[-1]
        ar = view.execute("1/0")
        ip = get_ipython()
        ip.user_ns['ar'] = ar
        with capture_output() as io:
            ip.run_cell("ar.get(2)")

        self.assertTrue('ZeroDivisionError' in io.stdout, io.stdout)
Exemple #35
0
def run_py_code():
    remember_where = lisp.point()
    # check if the line contains \inputminted
    lisp.beginning_of_line()
    l1 = lisp.point()
    lisp.end_of_line()
    l2 = lisp.point()
    line = lisp.buffer_substring(l1,l2)
    # if code comes from file
    # get code content from latex
    block_begin,block_end,content = get_block_content("```python","```\n")

    # we have code content at this point

    # scan content to find plt.plot(). if there is, scan buffer
    # previous to *here* to determine order of _this_ plt.plot(), and
    # give it an appropiate index that will be appended to the end of
    # the .png image file, i.e. [buffer name]_[index].png. plt.plot()
    # commands will be replaced by the corresponding plt.savefig
    # command.

    # generate savefig for execution code (no output in emacs yet)
    bc = lisp.buffer_string()
    plt_count_before = len(re.findall('plt\.savefig\(',bc))
    base = os.path.splitext(lisp.buffer_name())[0]
    f = '%s_%s.png' % (base, two_digit(plt_count_before+1))
    rpl = "plt.savefig('%s')" % f
    show_replaced = True if "plt.show()" in content else False
    content=content.replace("plt.show()",rpl)
    content="plt.figure();\n"+content    
    include_graphics_command = "![](%s)" % f
    
    # we have code content at this point
    start = time.time()
    
    with capture_output() as io:
        res_code = ip.run_cell(content)
    res = io.stdout

    elapsed = (time.time() - start)
    if len(res) > 0: 
        display_results(block_end, res) # display it

    if show_replaced:
        lisp.goto_char(block_end)
        lisp.forward_line(2) # skip over end verbatim, leave one line emtpy
        lisp.insert('\n' + include_graphics_command + '\n')
        lisp.scroll_up(1) # skip over end verbatim, leave one line emtpy        
        lisp.goto_char(remember_where)
        lisp.replace_string("plt.show()",rpl,None,block_begin,block_end)

    
    lisp.goto_char(remember_where)
    
    lisp.message("Ran in " + str(elapsed) + " seconds")
Exemple #36
0
    def test_display_empty_streams_engine(self):
        """empty stdout/err are not displayed (groupby engine)"""
        self.minimum_engines(1)
        
        v = self.client[:]
        ar = v.execute("print (5555)")
        ar.get(5)
        with capture_output() as io:
            ar.display_outputs('engine')
        self.assertEqual(io.stderr, '')
        self.assertEqual(io.stdout.count('5555'), len(v), io.stdout)
        self.assertFalse('\n\n' in io.stdout, io.stdout)
        self.assertEqual(io.stdout.count('[stdout:'), len(v), io.stdout)

        ar = v.execute("a=5")
        ar.get(5)
        with capture_output() as io:
            ar.display_outputs('engine')
        self.assertEqual(io.stderr, '')
        self.assertEqual(io.stdout, '')
Exemple #37
0
 def animate(i):
     _plt.clf()
     func_kwargs['cutout_kwargs'] = {
         'timeRange': time.isel({
             time.dims[0]: i
         }).values,
         'dropAxes': 'time'
     }
     with _io.capture_output() as captured:
         plot_func(od, **func_kwargs)
     if 'pbar' in locals(): pbar.update(1)
def test_nowarn_notimplemented():
    f = HTMLFormatter()
    class HTMLNotImplemented(object):
        def _repr_html_(self):
            raise NotImplementedError
    h = HTMLNotImplemented()
    with capture_output() as captured:
        result = f(h)
    nt.assert_is(result, None)
    nt.assert_equal("", captured.stderr)
    nt.assert_equal("", captured.stdout)
Exemple #39
0
    def test_display_empty_streams_type(self):
        """empty stdout/err are not displayed (groupby type)"""
        self.minimum_engines(1)

        v = self.client[:]
        ar = v.execute("print (5555)")
        ar.get(5)
        with capture_output() as io:
            ar.display_outputs()
        self.assertEqual(io.stderr, "")
        self.assertEqual(io.stdout.count("5555"), len(v), io.stdout)
        self.assertFalse("\n\n" in io.stdout, io.stdout)
        self.assertEqual(io.stdout.count("[stdout:"), len(v), io.stdout)

        ar = v.execute("a=5")
        ar.get(5)
        with capture_output() as io:
            ar.display_outputs()
        self.assertEqual(io.stderr, "")
        self.assertEqual(io.stdout, "")
Exemple #40
0
    def log_line(self, line):
        """Run the line and add the output to the Olog"""
        msg = ">>>{}\n".format(line)
        msg += "\n"
        with capture_output() as c:
            self.shell.run_cell(line)

        c.show()

        msg += c.stdout
        olog(msg)
Exemple #41
0
def run_py_code():
    remember_where = lisp.point()
    # check if the line contains \inputminted
    lisp.beginning_of_line()
    l1 = lisp.point()
    lisp.end_of_line()
    l2 = lisp.point()
    line = lisp.buffer_substring(l1, l2)
    # if code comes from file
    # get code content from latex
    block_begin, block_end, content = get_block_content("```python", "```\n")

    # we have code content at this point

    # scan content to find plt.plot(). if there is, scan buffer
    # previous to *here* to determine order of _this_ plt.plot(), and
    # give it an appropiate index that will be appended to the end of
    # the .png image file, i.e. [buffer name]_[index].png. plt.plot()
    # commands will be replaced by the corresponding plt.savefig
    # command.

    # generate savefig for execution code (no output in emacs yet)
    bc = lisp.buffer_string()
    plt_count_before = len(re.findall('plt\.savefig\(', bc))
    base = os.path.splitext(lisp.buffer_name())[0]
    f = '%s_%s.png' % (base, two_digit(plt_count_before + 1))
    rpl = "plt.savefig('%s')" % f
    show_replaced = True if "plt.show()" in content else False
    content = content.replace("plt.show()", rpl)
    content = "plt.figure();\n" + content
    include_graphics_command = "![](%s)" % f

    # we have code content at this point
    start = time.time()

    with capture_output() as io:
        res_code = get_ip().run_cell(content)
    res = io.stdout

    elapsed = (time.time() - start)
    if len(res) > 0:
        display_results(block_end, res)  # display it

    if show_replaced:
        lisp.goto_char(block_end)
        lisp.forward_line(2)  # skip over end verbatim, leave one line emtpy
        lisp.insert('\n' + include_graphics_command + '\n')
        lisp.scroll_up(1)  # skip over end verbatim, leave one line emtpy
        lisp.goto_char(remember_where)
        lisp.replace_string("plt.show()", rpl, None, block_begin, block_end)

    lisp.goto_char(remember_where)

    lisp.message("Ran in " + str(elapsed) + " seconds")
    def test_display_empty_streams_engine(self):
        """empty stdout/err are not displayed (groupby engine)"""
        self.minimum_engines(1)

        v = self.client[:]
        ar = v.execute("print (5555)")
        ar.get(5)
        with capture_output() as io:
            ar.display_outputs('engine')
        self.assertEqual(io.stderr, '')
        self.assertEqual(io.stdout.count('5555'), len(v), io.stdout)
        self.assertFalse('\n\n' in io.stdout, io.stdout)
        self.assertEqual(io.stdout.count('[stdout:'), len(v), io.stdout)

        ar = v.execute("a=5")
        ar.get(5)
        with capture_output() as io:
            ar.display_outputs('engine')
        self.assertEqual(io.stderr, '')
        self.assertEqual(io.stdout, '')
Exemple #43
0
def tuna(line: str, cell: str | None = None) -> HTML:
    ip = get_ipython()  # noqa: F821
    with tempfile.TemporaryDirectory() as tmp_dir:
        prun_fname = f"{tmp_dir}/prun"
        prun_line = f"-q -D {prun_fname}"
        with capture_output():
            ip.run_cell_magic("prun", prun_line,
                              cell if cell is not None else line)
        args = [prun_fname, "-o", tmp_dir, "--no-browser"]
        tuna_main(args)
        return _display_tuna(tmp_dir)
Exemple #44
0
def test_nowarn_notimplemented():
    f = HTMLFormatter()
    class HTMLNotImplemented(object):
        def _repr_html_(self):
            raise NotImplementedError
    h = HTMLNotImplemented()
    with capture_output() as captured:
        result = f(h)
    nt.assert_is(result, None)
    nt.assert_equal("", captured.stderr)
    nt.assert_equal("", captured.stdout)
Exemple #45
0
 def test_compositeerror_render_exception(self):
     """CompositeErrors get nice tracebacks"""
     view = self.client[:]
     ar = view.execute("1/0")
     ip = get_ipython()
     ip.user_ns['ar'] = ar
     with capture_output() as io:
         ip.run_cell("ar.get(2)")
     
     self.assertEqual(io.stdout.count('ZeroDivisionError'), len(view) * 2, io.stdout)
     self.assertEqual(io.stdout.count('by zero'), len(view), io.stdout)
     self.assertEqual(io.stdout.count(':execute'), len(view), io.stdout)
Exemple #46
0
 def animate(i):
     _plt.clf()
     func_kwargs["cutout_kwargs"] = {
         "timeRange": time.isel({
             time.dims[0]: i
         }).values,
         "dropAxes": "time",
     }
     with _io.capture_output() as captured:
         plot_func(od, **func_kwargs)
     if "pbar" in locals():
         pbar.update(1)
Exemple #47
0
    def test_sync_imports_quiet(self):
        view = self.client[-1]
        with capture_output() as io:
            with view.sync_imports(quiet=True):
                import IPython
        self.assertEqual(io.stdout, '')

        @interactive
        def find_ipython():
            return 'IPython' in globals()

        assert view.apply_sync(find_ipython)
Exemple #48
0
def test_warn_error_pretty_method():
    f = PlainTextFormatter()
    class BadPretty(object):
        def _repr_pretty_(self):
            return "hello"
    bad = BadPretty()
    with capture_output() as captured:
        result = f(bad)
    nt.assert_is(result, None)
    nt.assert_in("WARNING", captured.stderr)
    nt.assert_in("text/plain", captured.stderr)
    nt.assert_in("argument", captured.stderr)
Exemple #49
0
def test_error_method():
    f = HTMLFormatter()
    class BadHTML(object):
        def _repr_html_(self):
            raise ValueError("Bad HTML")
    bad = BadHTML()
    with capture_output() as captured:
        result = f(bad)
    nt.assert_is(result, None)
    nt.assert_in("Traceback", captured.stdout)
    nt.assert_in("Bad HTML", captured.stdout)
    nt.assert_in("_repr_html_", captured.stdout)
Exemple #50
0
    def test_result(self):
        ip = get_ipython()
        v = self.client[-1]
        v.activate()
        data = dict(a=111, b=222)
        v.push(data, block=True)

        for name in ('a', 'b'):
            ip.magic('px ' + name)
            with capture_output(display=False) as io:
                ip.magic('pxresult')
            self.assertIn(str(data[name]), io.stdout)
Exemple #51
0
def test_warn_error_method():
    f = HTMLFormatter()
    class BadHTML(object):
        def _repr_html_(self):
            return 1/0
    bad = BadHTML()
    with capture_output() as captured:
        result = f(bad)
    nt.assert_is(result, None)
    nt.assert_in("WARNING", captured.stderr)
    nt.assert_in("text/html", captured.stderr)
    nt.assert_in("zero", captured.stderr)
Exemple #52
0
    def test_sync_imports(self):
        view = self.client[-1]
        with capture_output() as io:
            with view.sync_imports():
                import IPython
        self.assertIn("IPython", io.stdout)

        @interactive
        def find_ipython():
            return 'IPython' in globals()

        assert view.apply_sync(find_ipython)
def test_error_method():
    f = HTMLFormatter()
    class BadHTML(object):
        def _repr_html_(self):
            raise ValueError("Bad HTML")
    bad = BadHTML()
    with capture_output() as captured:
        result = f(bad)
    nt.assert_is(result, None)
    nt.assert_in("Traceback", captured.stdout)
    nt.assert_in("Bad HTML", captured.stdout)
    nt.assert_in("_repr_html_", captured.stdout)
Exemple #54
0
def test_nowarn_notimplemented():
    f = HTMLFormatter()

    class HTMLNotImplemented(object):
        def _repr_html_(self):
            raise NotImplementedError

    h = HTMLNotImplemented()
    with capture_output() as captured:
        result = f(h)
    assert result is None
    assert "" == captured.stderr
    assert "" == captured.stdout
Exemple #55
0
    def test_display_output_error(self):
        """display_outputs shows output on error"""
        self.minimum_engines(1)

        v = self.client[-1]
        ar = v.execute("print (5555)\n1/0")
        ar.get(5, return_exceptions=True)
        ar.wait_for_output(5)
        with capture_output() as io:
            ar.display_outputs()
        self.assertEqual(io.stderr, '')
        self.assertEqual('5555\n', io.stdout)
        assert 'ZeroDivisionError' not in io.stdout
def test_error_pretty_method():
    f = PlainTextFormatter()
    class BadPretty(object):
        def _repr_pretty_(self):
            return "hello"
    bad = BadPretty()
    with capture_output() as captured:
        result = f(bad)
    nt.assert_is(result, None)
    nt.assert_in("Traceback", captured.stdout)
    nt.assert_in("_repr_pretty_", captured.stdout)
    nt.assert_in("given", captured.stdout)
    nt.assert_in("argument", captured.stdout)
Exemple #57
0
    def test_cellpx_stream(self):
        """%%px --stream"""
        self.minimum_engines(6)
        ip = get_ipython()
        v = self.client[:]
        v.block = True
        v.activate()

        v['generate_output'] = generate_output

        with capture_output(display=False) as io:
            ip.run_cell_magic('px', '--stream', 'generate_output()')

        print(io.stdout)
        print(io.stderr, file=sys.stderr)
        assert '\n\n' not in io.stdout
        print(io.stdout)
        lines = io.stdout.splitlines()
        expected = []
        expected.extend([
            r'\[stdout:\d+\]',
            'stdout',
            r'\[stdout:\d+\]',
            'stdout2',
            r'\[output:\d+\]',
            r'IPython\.core\.display\.HTML',
            r'\[output:\d+\]',
            r'IPython\.core\.display\.Math',
            r'Out\[\d+:\d+\]:.*IPython\.core\.display\.Math',
        ] * len(v))

        # Check that all expected lines are in the output
        self._check_expected_lines_unordered(expected, lines)

        assert (len(expected) - len(v) <= len(lines) <= len(expected)
                ), f"expected {len(expected)} lines, got: {io.stdout}"

        # Do the same for stderr
        print(io.stderr, file=sys.stderr)
        assert '\n\n' not in io.stderr
        lines = io.stderr.splitlines()
        expected = []
        expected.extend([
            r'\[stderr:\d+\]',
            'stderr',
            r'\[stderr:\d+\]',
            'stderr2',
        ] * len(v))
        self._check_expected_lines_unordered(expected, lines)
        assert (len(expected) - len(v) <= len(lines) <= len(expected)
                ), f"expected {len(expected)} lines, got: {io.stderr}"
Exemple #58
0
    def test_stdout(self):
        """ Does the in-process kernel correctly capture IO?
        """
        kernel = InProcessKernel()

        with capture_output() as io:
            kernel.shell.run_cell('print("foo")')
        self.assertEqual(io.stdout, 'foo\n')

        kc = BlockingInProcessKernelClient(kernel=kernel)
        kernel.frontends.append(kc)
        kc.shell_channel.execute('print("bar")')
        msg = get_stream_message(kc)
        self.assertEqual(msg['content']['text'], 'bar\n')
Exemple #59
0
    def slack(self, line, cell):
        with io.capture_output() as captured:
            res = self.shell.run_cell(cell)

        print captured

        if not captured and not line:
            return

        self.client.api_call('chat.postMessage',
                             channel=self.channel,
                             text='{}\n```\n{}```'.format(
                                 str(line), str(captured)),
                             parse='full')
Exemple #60
0
def test_bigquery_magic_w_missing_query():
    ip = IPython.get_ipython()
    ip.extension_manager.load_extension("google.cloud.bigquery")
    magics.context._project = None

    cell_body = "   \n    \n   \t\t  \n  "

    with io.capture_output() as captured_io:
        ip.run_cell_magic("bigquery", "df", cell_body)

    output = captured_io.stderr
    assert "Could not save output to variable" in output
    assert "Query is missing" in output
    assert "Traceback (most recent call last)" not in output