Example #1
0
def test_inkey_1s_cbreak_input():
    "1-second inkey w/multibyte sequence; should return after ~1 second."
    pid, master_fd = pty.fork()
    if pid is 0:  # child
        try:
            cov = __import__('cov_core_init').init()
        except ImportError:
            cov = None
        term = TestTerminal()
        os.write(sys.__stdout__.fileno(), SEMAPHORE)
        with term.cbreak():
            inp = term.inkey(timeout=3)
            os.write(sys.__stdout__.fileno(), inp.name.encode('utf-8'))
            sys.stdout.flush()
        if cov is not None:
            cov.stop()
            cov.save()
        os._exit(0)

    with echo_off(master_fd):
        read_until_semaphore(master_fd)
        stime = time.time()
        time.sleep(1)
        os.write(master_fd, u'\x1b[C'.encode('ascii'))
        output = read_until_eof(master_fd)

    pid, status = os.waitpid(pid, 0)
    assert output == u'KEY_RIGHT'
    assert os.WEXITSTATUS(status) == 0
    assert math.floor(time.time() - stime) == 1.0
Example #2
0
def test_inkey_0s_cbreak_multibyte_utf8():
    "0-second inkey with multibyte utf-8 input; should decode immediately."
    # utf-8 bytes represent "latin capital letter upsilon".
    pid, master_fd = pty.fork()
    if pid is 0:  # child
        try:
            cov = __import__('cov_core_init').init()
        except ImportError:
            cov = None
        term = TestTerminal()
        read_until_semaphore(sys.__stdin__.fileno(), semaphore=SEMAPHORE)
        os.write(sys.__stdout__.fileno(), SEMAPHORE)
        with term.cbreak():
            inp = term.inkey(timeout=0)
            os.write(sys.__stdout__.fileno(), inp.encode('utf-8'))
        if cov is not None:
            cov.stop()
            cov.save()
        os._exit(0)

    with echo_off(master_fd):
        os.write(master_fd, SEND_SEMAPHORE)
        os.write(master_fd, u'\u01b1'.encode('utf-8'))
        read_until_semaphore(master_fd)
        stime = time.time()
        output = read_until_eof(master_fd)
    pid, status = os.waitpid(pid, 0)
    assert output == u'Ʊ'
    assert os.WEXITSTATUS(status) == 0
    assert math.floor(time.time() - stime) == 0.0
Example #3
0
def test_esc_delay_cbreak_timout_0():
    """esc_delay still in effect with timeout of 0 ("nonblocking")."""
    pid, master_fd = pty.fork()
    if pid is 0:  # child
        try:
            cov = __import__('cov_core_init').init()
        except ImportError:
            cov = None
        term = TestTerminal()
        os.write(sys.__stdout__.fileno(), SEMAPHORE)
        with term.cbreak():
            stime = time.time()
            inp = term.inkey(timeout=0)
            measured_time = (time.time() - stime) * 100
            os.write(sys.__stdout__.fileno(), ('%s %i' % (
                inp.name,
                measured_time,
            )).encode('ascii'))
            sys.stdout.flush()
        if cov is not None:
            cov.stop()
            cov.save()
        os._exit(0)

    with echo_off(master_fd):
        os.write(master_fd, u'\x1b'.encode('ascii'))
        read_until_semaphore(master_fd)
        stime = time.time()
        key_name, duration_ms = read_until_eof(master_fd).split()

    pid, status = os.waitpid(pid, 0)
    assert key_name == u'KEY_ESCAPE'
    assert os.WEXITSTATUS(status) == 0
    assert math.floor(time.time() - stime) == 0.0
    assert 35 <= int(duration_ms) <= 45, int(duration_ms)
Example #4
0
def test_inkey_0s_cbreak_input():
    "0-second inkey with input; Keypress should be immediately returned."
    pid, master_fd = pty.fork()
    if pid is 0:
        try:
            cov = __import__('cov_core_init').init()
        except ImportError:
            cov = None
        # child pauses, writes semaphore and begins awaiting input
        term = TestTerminal()
        read_until_semaphore(sys.__stdin__.fileno(), semaphore=SEMAPHORE)
        os.write(sys.__stdout__.fileno(), SEMAPHORE)
        with term.cbreak():
            inp = term.inkey(timeout=0)
            os.write(sys.__stdout__.fileno(), inp.encode('utf-8'))
        if cov is not None:
            cov.stop()
            cov.save()
        os._exit(0)

    with echo_off(master_fd):
        os.write(master_fd, SEND_SEMAPHORE)
        os.write(master_fd, u'x'.encode('ascii'))
        read_until_semaphore(master_fd)
        stime = time.time()
        output = read_until_eof(master_fd)

    pid, status = os.waitpid(pid, 0)
    assert output == u'x'
    assert os.WEXITSTATUS(status) == 0
    assert math.floor(time.time() - stime) == 0.0
Example #5
0
    def child(kind):
        t = TestTerminal(kind=kind)
        # test simple sugar,
        if t.bold:
            expected_output = u''.join((t.bold, u'hi', t.normal))
        else:
            expected_output = u'hi'
        assert t.bold(u'hi') == expected_output
        # Plain strs for Python 2.x
        if t.green:
            expected_output = u''.join((t.green, 'hi', t.normal))
        else:
            expected_output = u'hi'
        assert t.green('hi') == expected_output
        # Test unicode
        if t.underline:
            expected_output = u''.join((t.underline, u'boö', t.normal))
        else:
            expected_output = u'boö'
        assert (t.underline(u'boö') == expected_output)

        if t.subscript:
            expected_output = u''.join((t.subscript, u'[1]', t.normal))
        else:
            expected_output = u'[1]'

        assert (t.subscript(u'[1]') == expected_output)
Example #6
0
 def child(kind):
     t = TestTerminal(kind=kind, stream=StringIO(), force_styling=True)
     with t.location(0, 0):
         pass
     expected_output = u''.join(
         (unicode_cap('sc'), unicode_parm('cup', 0, 0), unicode_cap('rc')))
     assert (t.stream.getvalue() == expected_output)
Example #7
0
 def child_mnemonics_wontmove(kind):
     from blessed.sequences import measure_length
     t = TestTerminal(kind=kind)
     assert (0 == measure_length(u'', t))
     # not even a mbs
     assert (0 == measure_length(u'xyzzy', t))
     # negative numbers, though printable as %d, do not result
     # in movement; just garbage. Also not a valid sequence.
     assert (0 == measure_length(t.cuf(-333), t))
     assert (len(t.clear_eol) == measure_length(t.clear_eol, t))
     # various erases don't *move*
     assert (len(t.clear_bol) == measure_length(t.clear_bol, t))
     assert (len(t.clear_eos) == measure_length(t.clear_eos, t))
     assert (len(t.bold) == measure_length(t.bold, t))
     # various paints don't move
     assert (len(t.red) == measure_length(t.red, t))
     assert (len(t.civis) == measure_length(t.civis, t))
     if t.cvvis:
         assert (len(t.cvvis) == measure_length(t.cvvis, t))
     assert (len(t.underline) == measure_length(t.underline, t))
     assert (len(t.reverse) == measure_length(t.reverse, t))
     for _num in range(t.number_of_colors):
         assert (len(t.color(_num)) == measure_length(t.color(_num), t))
     assert (len(t.normal) == measure_length(t.normal, t))
     assert (len(t.normal_cursor) == measure_length(t.normal_cursor, t))
     assert (len(t.hide_cursor) == measure_length(t.hide_cursor, t))
     assert (len(t.save) == measure_length(t.save, t))
     assert (len(t.italic) == measure_length(t.italic, t))
     assert (len(t.standout) == measure_length(t.standout,
                                               t)), (t.standout,
                                                     t._wont_move)
Example #8
0
 def child():
     term = TestTerminal(stream=StringIO.StringIO())
     with term.cbreak():
         stime = time.time()
         inp = term.inkey(timeout=1)
         assert (inp == u'')
         assert (math.floor(time.time() - stime) == 1.0)
Example #9
0
 def child():
     term = TestTerminal()
     with term.cbreak():
         stime = time.time()
         inp = term.inkey(timeout=0)
         assert (inp == u'')
         assert (math.floor(time.time() - stime) == 0.0)
Example #10
0
 def child():
     # Also test that Terminal grabs a reasonable default stream. This test
     # assumes it will be run from a tty.
     t = TestTerminal()
     sc = unicode_cap('sc')
     assert t.save == sc
     assert t.save == sc  # Make sure caching doesn't screw it up.
Example #11
0
    def child(kind):
        t = TestTerminal(kind=kind)
        try:
            t.bold_misspelled('hey')
            assert not t.is_a_tty or False, 'Should have thrown exception'
        except TypeError:
            e = sys.exc_info()[1]
            assert 'probably misspelled' in e.args[0]
        try:
            t.bold_misspelled(u'hey')  # unicode
            assert not t.is_a_tty or False, 'Should have thrown exception'
        except TypeError:
            e = sys.exc_info()[1]
            assert 'probably misspelled' in e.args[0]

        try:
            t.bold_misspelled(None)  # an arbitrary non-string
            assert not t.is_a_tty or False, 'Should have thrown exception'
        except TypeError:
            e = sys.exc_info()[1]
            assert 'probably misspelled' not in e.args[0]

        if platform.python_implementation() != 'PyPy':
            # PyPy fails to toss an exception, Why?!
            try:
                t.bold_misspelled('a', 'b')  # >1 string arg
                assert not t.is_a_tty or False, 'Should have thrown exception'
            except TypeError:
                e = sys.exc_info()[1]
                assert 'probably misspelled' in e.args[0], e.args
Example #12
0
    def child(kind):
        t = TestTerminal(kind=kind)
        if t.magenta:
            assert t.color(5)('smoo') == t.magenta + 'smoo' + t.normal
        else:
            assert t.color(5)('smoo') == 'smoo'

        if t.on_magenta:
            assert t.on_color(5)('smoo') == t.on_magenta + 'smoo' + t.normal
        else:
            assert t.color(5)(u'smoo') == 'smoo'

        if t.color(4):
            assert t.color(4)(u'smoo') == t.color(4) + u'smoo' + t.normal
        else:
            assert t.color(4)(u'smoo') == 'smoo'

        if t.on_green:
            assert t.on_color(2)('smoo') == t.on_green + u'smoo' + t.normal
        else:
            assert t.on_color(2)('smoo') == 'smoo'

        if t.on_color(6):
            assert t.on_color(6)('smoo') == t.on_color(6) + u'smoo' + t.normal
        else:
            assert t.on_color(6)('smoo') == 'smoo'
Example #13
0
 def child(kind):
     t = TestTerminal(kind=kind, stream=StringIO())
     assert t._init_descriptor == sys.__stdout__.fileno()
     assert (isinstance(t.height, int))
     assert (isinstance(t.width, int))
     assert t.height == t._height_and_width()[0]
     assert t.width == t._height_and_width()[1]
Example #14
0
 def child():
     term = TestTerminal(force_styling=True)
     maxlen = None
     for sequence, code in term._keymap.items():
         if maxlen is not None:
             assert len(sequence) <= maxlen
         assert sequence
         maxlen = len(sequence)
Example #15
0
    def child_without_styling():
        """No side effect for location as a context manager without styling."""
        t = TestTerminal(stream=StringIO(), force_styling=None)

        with t.location(3, 4):
            t.stream.write(u'hi')

        assert t.stream.getvalue() == u'hi'
Example #16
0
 def child_with_styling(kind):
     t = TestTerminal(kind=kind, stream=StringIO(), force_styling=True)
     with t.location(3, 4):
         t.stream.write(u'hi')
     expected_output = u''.join(
         (unicode_cap('sc'), unicode_parm('cup', 4,
                                          3), u'hi', unicode_cap('rc')))
     assert (t.stream.getvalue() == expected_output)
Example #17
0
 def child(kind):
     buf = StringIO()
     t = TestTerminal(stream=buf, force_styling=True)
     y, x = 10, 20
     with t.location(y, x):
         xy_val = t.move(x, y)
         yx_val = buf.getvalue()[len(t.sc):]
         assert xy_val == yx_val
Example #18
0
 def child(kind):
     t = TestTerminal(stream=StringIO(), force_styling=True)
     t.hide_cursor = u'BEGIN'
     t.normal_cursor = u'END'
     with t.hidden_cursor():
         pass
     expected_output = u''.join((t.hide_cursor, t.normal_cursor))
     assert (t.stream.getvalue() == expected_output)
Example #19
0
 def child(kind):
     t = TestTerminal(stream=StringIO(), force_styling=True)
     t.enter_fullscreen = u'BEGIN'
     t.exit_fullscreen = u'END'
     with t.fullscreen():
         pass
     expected_output = u''.join((t.enter_fullscreen, t.exit_fullscreen))
     assert (t.stream.getvalue() == expected_output)
Example #20
0
    def child():
        warnings.filterwarnings("ignore", category=UserWarning)

        term = TestTerminal(kind='unknown', force_styling=True)
        assert term._kind is None
        assert term.does_styling is False
        assert term.number_of_colors == 0
        warnings.resetwarnings()
Example #21
0
 def child(kind):
     t = TestTerminal(kind=kind, stream=StringIO(), force_styling=False)
     assert (t.bold(u'hi') == u'hi')
     assert (t.green('hi') == u'hi')
     # Test non-ASCII chars, no longer really necessary:
     assert (t.bold_green(u'boö') == u'boö')
     assert (t.bold_underline_green_on_red('loo') == u'loo')
     assert (t.on_bright_red_bold_bright_green_underline('meh') == u'meh')
Example #22
0
 def child():
     t = TestTerminal()
     try:
         my_wrapped = t.wrap(u'------- -------------', WIDTH)
     except ValueError, err:
         assert err.args[0] == (
             "invalid width %r(%s) (must be integer > 0)" %
             (WIDTH, type(WIDTH)))
Example #23
0
 def child(kind):
     t = TestTerminal(kind=kind, stream=StringIO(), force_styling=True)
     ROW = 5
     with t.location(y=ROW):
         pass
     expected_output = u''.join(
         (unicode_cap('sc'), u'\x1b[{0}d'.format(ROW + 1),
          unicode_cap('rc')))
     assert (t.stream.getvalue() == expected_output)
Example #24
0
 def child():
     with mock.patch('locale.getpreferredencoding') as get_enc:
         with warnings.catch_warnings(record=True) as warned:
             get_enc.return_value = '---unknown--encoding---'
             t = TestTerminal()
             assert t._encoding == 'ascii'
             assert len(warned) == 1
             assert issubclass(warned[-1].category, UserWarning)
             assert "fallback to ASCII" in str(warned[-1].message)
Example #25
0
    def child():
        def side_effect(fd):
            raise IOError

        term = TestTerminal()
        term._winsize = side_effect
        os.environ['COLUMNS'] = '1984'
        os.environ['LINES'] = '1888'
        assert term._height_and_width() == (1888, 1984, None, None)
Example #26
0
 def child(kind):
     t = TestTerminal(stream=StringIO(), kind=kind)
     assert (t.clear == '')
     assert (t.move(1 == 2) == '')
     assert (t.move_x(1) == '')
     assert (t.bold() == '')
     assert (t.bold('', 'x', 'huh?') == '')
     assert (t.bold('', 9876) == '')
     assert (t.uhh(9876) == '')
     assert (t.clear('x') == 'x')
Example #27
0
 def child(lines=25, cols=80):
     # set the pty's virtual window size
     val = struct.pack('HHHH', lines, cols, 0, 0)
     fcntl.ioctl(sys.__stdout__.fileno(), termios.TIOCSWINSZ, val)
     t = TestTerminal()
     winsize = t._height_and_width()
     assert t.width == cols
     assert t.height == lines
     assert winsize.ws_col == cols
     assert winsize.ws_row == lines
Example #28
0
    def child():
        warnings.filterwarnings("error", category=UserWarning)

        # instantiate first terminal, of type xterm-256color
        term = TestTerminal(force_styling=True)

        try:
            # a second instantiation raises UserWarning
            term = TestTerminal(kind="vt220", force_styling=True)
        except UserWarning:
            err = sys.exc_info()[1]
            assert (err.args[0].startswith(
                'A terminal of kind "vt220" has been requested')), err.args[0]
            assert ('a terminal of kind "xterm-256color" will '
                    'continue to be returned' in err.args[0]), err.args[0]
        else:
            # unless term is not a tty and setupterm() is not called
            assert not term.is_a_tty or False, 'Should have thrown exception'
        warnings.resetwarnings()
Example #29
0
    def child():
        # build a test paragraph, along with a very colorful version
        t = TestTerminal()
        pgraph = u' '.join((
            'a',
            'ab',
            'abc',
            'abcd',
            'abcde',
            'abcdef',
            'abcdefgh',
            'abcdefghi',
            'abcdefghij',
            'abcdefghijk',
            'abcdefghijkl',
            'abcdefghijklm',
            'abcdefghijklmn',
            'abcdefghijklmno    ',
        ) * 4)

        pgraph_colored = u''.join([
            t.color(n % 7) + t.bold + ch if ch != ' ' else ' '
            for n, ch in enumerate(pgraph)
        ])

        internal_wrapped = textwrap.wrap(pgraph,
                                         width=WIDTH,
                                         break_long_words=False,
                                         drop_whitespace=True,
                                         subsequent_indent=u' ' * 3)
        my_wrapped = t.wrap(pgraph,
                            width=WIDTH,
                            drop_whitespace=True,
                            subsequent_indent=u' ' * 3)
        my_wrapped_colored = t.wrap(pgraph_colored,
                                    width=WIDTH,
                                    drop_whitespace=True,
                                    subsequent_indent=u' ' * 3)

        # ensure we textwrap ascii the same as python
        assert (internal_wrapped == my_wrapped)

        # ensure our first and last line wraps at its ends
        first_l = internal_wrapped[0]
        last_l = internal_wrapped[-1]
        my_first_l = my_wrapped_colored[0]
        my_last_l = my_wrapped_colored[-1]
        assert (len(first_l) == t.length(my_first_l))
        assert (len(last_l) == t.length(my_last_l)), (internal_wrapped,
                                                      my_wrapped_colored)
        assert (len(internal_wrapped[-1]) == t.length(my_wrapped_colored[-1]))

        # ensure our colored textwrap is the same line length
        assert (len(internal_wrapped) == len(my_wrapped_colored))
Example #30
0
    def child():
        warnings.filterwarnings("error", category=UserWarning)

        try:
            term = TestTerminal(kind='unknown', force_styling=True)
        except UserWarning:
            err = sys.exc_info()[1]
            assert err.args[0] == 'Failed to setupterm(kind=unknown)'
        else:
            assert not term.is_a_tty and not term.does_styling, (
                'Should have thrown exception')
        warnings.resetwarnings()