Ejemplo n.º 1
0
    def test_dumpdata_progressbar(self):
        """
        Dumpdata shows a progress bar on the command line when --output is set,
        stdout is a tty, and verbosity > 0.
        """
        management.call_command('loaddata', 'fixture1.json', verbosity=0)
        new_io = StringIO()
        new_io.isatty = lambda: True
        with NamedTemporaryFile() as file:
            options = {
                'format': 'json',
                'stdout': new_io,
                'stderr': new_io,
                'output': file.name,
            }
            management.call_command('dumpdata', 'fixtures', **options)
            self.assertTrue(
                new_io.getvalue().endswith('[' +
                                           '.' * ProgressBar.progress_width +
                                           ']\n'))

            # Test no progress bar when verbosity = 0
            options['verbosity'] = 0
            new_io = StringIO()
            new_io.isatty = lambda: True
            options.update({'stdout': new_io, 'stderr': new_io})
            management.call_command('dumpdata', 'fixtures', **options)
            self.assertEqual(new_io.getvalue(), '')
Ejemplo n.º 2
0
 def test_isatty_false(self):
     w1 = StringIO()
     w1.isatty = lambda: True
     w2 = StringIO()
     w2.isatty = lambda: True
     writer = action.Writer(w1, w2)
     assert writer.isatty()
Ejemplo n.º 3
0
 def test_isatty_overwrite_no(self):
     w1 = StringIO()
     w1.isatty = lambda: True
     w2 = StringIO()
     w2.isatty = lambda: True
     writer = action.Writer(w1)
     writer.add_writer(w2, False)
Ejemplo n.º 4
0
 def test_isatty_overwrite_no(self):
     w1 = StringIO()
     w1.isatty = lambda: True
     w2 = StringIO()
     w2.isatty = lambda: True
     writer = action.Writer(w1)
     writer.add_writer(w2, False)
Ejemplo n.º 5
0
    def test_dumpdata_progressbar(self):
        """
        Dumpdata shows a progress bar on the command line when --output is set,
        stdout is a tty, and verbosity > 0.
        """
        management.call_command('loaddata', 'fixture1.json', verbosity=0)
        new_io = StringIO()
        new_io.isatty = lambda: True
        with NamedTemporaryFile() as file:
            options = {
                'format': 'json',
                'stdout': new_io,
                'stderr': new_io,
                'output': file.name,
            }
            management.call_command('dumpdata', 'fixtures', **options)
            self.assertTrue(new_io.getvalue().endswith('[' + '.' * ProgressBar.progress_width + ']\n'))

            # Test no progress bar when verbosity = 0
            options['verbosity'] = 0
            new_io = StringIO()
            new_io.isatty = lambda: True
            options.update({'stdout': new_io, 'stderr': new_io})
            management.call_command('dumpdata', 'fixtures', **options)
            self.assertEqual(new_io.getvalue(), '')
Ejemplo n.º 6
0
 def test_isatty_false(self):
     w1 = StringIO()
     w1.isatty = lambda: True
     w2 = StringIO()
     w2.isatty = lambda: True
     writer = action.Writer(w1, w2)
     assert writer.isatty()
Ejemplo n.º 7
0
 def __init__(self, *args, **kwargs):
     stream = kwargs.pop("stream", None)
     if not stream:
         stream = StringIO()
         stream.isatty = lambda: True
     with patch("pyout.tabular.Terminal", Terminal):
         super(Tabular, self).__init__(*args, stream=stream, **kwargs)
Ejemplo n.º 8
0
class _LoggingTee(object):
    """A tee object to redirect streams to the logger."""

    def __init__(self, src_filename):
        self.logger = logger
        self.src_filename = src_filename
        self.logger_buffer = ''
        self.set_std_and_reset_position()

    def set_std_and_reset_position(self):
        if not isinstance(sys.stdout, _LoggingTee):
            self.origs = (sys.stdout, sys.stderr)
        sys.stdout = sys.stderr = self
        self.first_write = True
        self.output = StringIO()
        return self

    def restore_std(self):
        sys.stdout.flush()
        sys.stderr.flush()
        sys.stdout, sys.stderr = self.origs

    def write(self, data):
        self.output.write(data)

        if self.first_write:
            self.logger.verbose('Output from %s', self.src_filename,
                                color='brown')
            self.first_write = False

        data = self.logger_buffer + data
        lines = data.splitlines()
        if data and data[-1] not in '\r\n':
            # Wait to write last line if it's incomplete. It will write next
            # time or when the LoggingTee is flushed.
            self.logger_buffer = lines[-1]
            lines = lines[:-1]
        else:
            self.logger_buffer = ''

        for line in lines:
            self.logger.verbose('%s', line)

    def flush(self):
        self.output.flush()
        if self.logger_buffer:
            self.logger.verbose('%s', self.logger_buffer)
            self.logger_buffer = ''

    # When called from a local terminal seaborn needs it in Python3
    def isatty(self):
        return self.output.isatty()

    # When called in gen_rst, conveniently use context managing
    def __enter__(self):
        return self

    def __exit__(self, type_, value, tb):
        self.restore_std()
def test_printing_exc_to_tty():
    if sys.platform == 'win32':
        return

    out = StringIO()
    out.isatty = lambda: True
    with printing_exc(reraise=False, file_=out):
        f(10)

    assert_smart_equals_ref('test_print.printing_exc_to_tty', out.getvalue())
Ejemplo n.º 10
0
class StringIO(object):
    def __init__(self, stringio=None):
        self.encoding = None
        self.stringio_object = stringio
        if self.stringio_object is None:
            self.stringio_object = WrappedStringIO()

    def close(self):
        return self.stringio_object.close()

    def closed(self, x):
        return self.stringio_object.closed(x)

    def flush(self):
        return self.stringio_object.flush()

    def getvalue(self, use_pos=None):
        return self.stringio_object.getvalue(use_pos)

    def isatty(self):
        return self.stringio_object.isatty()

    def __next__(self):
        return next(self.stringio_object)

    def read(self, s=None):
        return self.stringio_object.read(s)

    def readline(self):
        return self.stringio_object.readline()

    def readlines(self):
        return self.stringio_object.readlines()

    def reset(self):
        return self.stringio_object.reset()

    def seek(self, position):
        return self.stringio_object.seek(position)

    def softspace(self, x, base=None):
        return self.stringio_object.softspace(x, base)

    def tell(self):
        return self.stringio_object.tell()

    def truncate(self):
        return self.stringio_object.truncate()

    def write(self, s):
        return self.stringio_object.write(s)

    def writelines(self, sequence_of_strings):
        return self.stringio_object.writelines(sequence_of_strings)
Ejemplo n.º 11
0
    def test_dumpdata_progressbar(self):
        """
        Dumpdata shows a progress bar on the command line when --output is set,
        stdout is a tty, and verbosity > 0.
        """
        management.call_command("loaddata", "fixture1.json", verbosity=0)
        new_io = StringIO()
        new_io.isatty = lambda: True
        with NamedTemporaryFile() as file:
            options = {"format": "json", "stdout": new_io, "stderr": new_io, "output": file.name}
            management.call_command("dumpdata", "fixtures", **options)
            self.assertTrue(new_io.getvalue().endswith("[" + "." * ProgressBar.progress_width + "]\n"))

            # Test no progress bar when verbosity = 0
            options["verbosity"] = 0
            new_io = StringIO()
            new_io.isatty = lambda: True
            options.update({"stdout": new_io, "stderr": new_io})
            management.call_command("dumpdata", "fixtures", **options)
            self.assertEqual(new_io.getvalue(), "")
Ejemplo n.º 12
0
def captured_output():
    log = StringIO()
    log_handler = logging.StreamHandler(log)
    logging.getLogger().addHandler(log_handler)
    new_out, new_err = StringIO(), StringIO()
    old_out, old_err = sys.stdout, sys.stderr
    new_out.isatty = lambda: True
    try:
        sys.stdout, sys.stderr = new_out, new_err
        yield new_out, new_err, log
    finally:
        sys.stdout, sys.stderr = old_out, old_err
        logging.getLogger().removeHandler(log_handler)
Ejemplo n.º 13
0
def test_shell_tracer():
    # Alias helper functions
    remove_whitespace = pytest.helpers.remove_whitespace
    remove_ansi = pytest.helpers.remove_ansi

    sql = "SELECT 1 + 1 FROM (SELECT 2 + 2)"

    output = StringIO()
    output.isatty = MagicMock(return_value=True)

    with patch("sys.platform", "linux2"), ShellTracer(file=output, fancy=True):
        store.execute(sql)

    color_output = output.getvalue()
    output.close()

    assert color_output != sql
    assert \
        remove_whitespace(remove_ansi(color_output)).rsplit(";", 1)[0] == \
        remove_whitespace(sql)

    output = StringIO()
    output.isatty = MagicMock(return_value=False)

    with ShellTracer(file=output, fancy=False):
        store.execute(sql)

    colorless_output = output.getvalue()
    output.close()

    assert color_output != colorless_output
    assert \
        remove_ansi(color_output).rsplit(";", 1)[0] == \
        colorless_output.rsplit(";", 1)[0]
    assert \
        remove_whitespace(remove_ansi(color_output)).rsplit(";", 1)[0] == \
        remove_whitespace(sql)
Ejemplo n.º 14
0
def captured_output():
    """
    Record stdout, stderr and logging. This should be used in a context manager:

    >>> with captured_output():
    >>>     # ...
    """
    log = StringIO()
    log_handler = logging.StreamHandler(log)
    logging.getLogger().addHandler(log_handler)
    new_out, new_err = StringIO(), StringIO()
    old_out, old_err = sys.stdout, sys.stderr
    new_out.isatty = lambda: True
    try:
        sys.stdout, sys.stderr = new_out, new_err
        yield new_out, new_err, log
    finally:
        sys.stdout, sys.stderr = old_out, old_err
        logging.getLogger().removeHandler(log_handler)