def test_unhighlight_paren_bugs(self):
        """two previous bugs, parent didn't highlight until next render
        and paren didn't unhighlight until enter"""
        self.assertEqual(self.repl.rl_history.entries, [''])
        self.enter('(')
        self.assertEqual(self.repl.rl_history.entries, [''])
        screen = [">>> (",
                  "... "]
        self.assertEqual(self.repl.rl_history.entries, [''])
        self.assert_paint_ignoring_formatting(screen)
        self.assertEqual(self.repl.rl_history.entries, [''])

        with output_to_repl(self.repl):
            self.assertEqual(self.repl.rl_history.entries, [''])
            self.repl.process_event(')')
            self.assertEqual(self.repl.rl_history.entries, [''])
        screen = fsarray([cyan(">>> ") + on_magenta(bold(red('('))),
                         green("... ") + on_magenta(bold(red(')')))])
        self.assert_paint(screen, (1, 5))

        with output_to_repl(self.repl):
            self.repl.process_event(' ')
        screen = fsarray([cyan(">>> ") + yellow('('),
                         green("... ") + yellow(')') + bold(cyan(" "))])
        self.assert_paint(screen, (1, 6))
Example #2
0
    def test_syntaxerror(self):
        i = interpreter.Interp()
        a = []

        def append_to_a(message):
            a.append(message)

        i.write = append_to_a
        i.runsource('1.1.1.1')

        if pypy:
            expected = (
                '  File ' + green('"<input>"') +
                ', line ' + bold(magenta('1')) + '\n    1.1.1.1\n      ^\n' +
                bold(red('SyntaxError')) + ': ' + cyan('invalid syntax') +
                '\n')
        else:
            expected = (
                '  File ' + green('"<input>"') +
                ', line ' + bold(magenta('1')) + '\n    1.1.1.1\n        ^\n' +
                bold(red('SyntaxError')) + ': ' + cyan('invalid syntax') +
                '\n')

        self.assertMultiLineEqual(str(plain('').join(a)), str(expected))
        self.assertEquals(plain('').join(a), expected)
Example #3
0
    def test_traceback(self):
        i = interpreter.Interp()
        a = []

        def append_to_a(message):
            a.append(message)

        i.write = append_to_a

        def f():
            return 1/0

        def g():
            return f()

        i.runsource('g()', encode=False)

        if pypy:
            global_not_found = "global name 'g' is not defined"
        else:
            global_not_found = "name 'g' is not defined"

        expected = 'Traceback (most recent call last):\n  File ' + \
            green('"%s"' % _last_console_filename()) + ', line ' + bold(magenta('1')) + ', in ' + \
            cyan('<module>') + '\n    g()\n' + bold(red('NameError')) + ': ' + \
            cyan(global_not_found) + '\n'

        self.assertMultiLineEqual(str(plain('').join(a)), str(expected))
        self.assertEquals(plain('').join(a), expected)
 def test_argspec(self):
     def foo(x, y, z=10):
         "docstring!"
         pass
     argspec = inspection.getfuncprops('foo', foo)
     array = replpainter.formatted_argspec(argspec, 1, 30, setup_config())
     screen = [bold(cyan('foo')) + cyan(':') + cyan(' ') + cyan('(') +
               cyan('x') + yellow(',') + yellow(' ') + bold(cyan('y')) +
               yellow(',') + yellow(' ') + cyan('z') + yellow('=') +
               bold(cyan('10')) + yellow(')')]
     self.assertFSArraysEqual(fsarray(array), fsarray(screen))
Example #5
0
 def __repr__(self):
     s = fmtfuncs.bold(type(self).__name__)
     s += (': '+fmtfuncs.bold(self.title.title()) if self.title else '')
     s += '\n'
     s += fmtfuncs.gray(self.question)
     s += '\n'
     s += fmtfuncs.gray('\n').join(fmtfuncs.green(repr(x) if not isinstance(x, basestring) else x) for x in self.corrects)
     s += '\n'
     s += fmtfuncs.gray('\n').join(fmtfuncs.red(repr(x) if not isinstance(x, basestring) else x) for x in self.wrongs)
     s += '\n'
     return str(s)
 def __init__(self, width, height):
     self.width = width
     self.height = height
     n = 10
     self.player = Entity(on_blue(green(bold('5'))), width // 2, height // 2 - 2, speed=5)
     self.npcs = [Entity(on_blue(red('X')), i * width // (n * 2), j * height // (n * 2)) for i in range(1, 2*n, 2) for j in range(1, 2*n, 2)]
     self.turn = 0
    def test_parse(self):
        self.assertEquals(parse.parse('\x01y\x03print\x04'), yellow('print'))

        self.assertEquals(
            parse.parse('\x01y\x03print\x04\x01c\x03 \x04\x01g\x031\x04\x01c'
                        '\x03 \x04\x01Y\x03+\x04\x01c\x03 \x04\x01g\x032\x04'),
            yellow('print') + cyan(' ') + green('1') + cyan(' ') +
            bold(yellow('+')) + cyan(' ') + green(u'2'))
    def tick(self):
        for npc in self.npcs:
            self.move_entity(npc, *npc.towards(self.player))
        for entity1 in self.entities:
            for entity2 in self.entities:
                if entity1 is entity2: continue
                if (entity1.x, entity1.y) == (entity2.x, entity2.y):
                    if entity1 is self.player:
                        return 'you lost on turn %d' % self.turn
                    entity1.speed = 0
                    entity2.speed = 0
                    entity1.display = on_red(bold(yellow('o')))
                    entity2.display = on_red(bold(yellow('o')))

        if all(npc.speed == 0 for npc in self.npcs):
            return 'you won on turn %d' % self.turn
        self.turn += 1
        if self.turn % 20 == 0:
            self.player.speed = max(0, self.player.speed - 1)
            self.player.display = on_blue(green(bold(str(self.player.speed))))
Example #9
0
    def test_syntaxerror(self):
        i, a = self.interp_errlog()

        i.runsource('1.1.1.1')

        if pypy:
            expected = (
                '  File ' + green('"<input>"') +
                ', line ' + bold(magenta('1')) + '\n    1.1.1.1\n      ^\n' +
                bold(red('SyntaxError')) + ': ' + cyan('invalid syntax') +
                '\n')
        else:
            expected = (
                '  File ' + green('"<input>"') +
                ', line ' + bold(magenta('1')) + '\n    1.1.1.1\n        ^\n' +
                bold(red('SyntaxError')) + ': ' + cyan('invalid syntax') +
                '\n')

        self.assertMultiLineEqual(str(plain('').join(a)), str(expected))
        self.assertEqual(plain('').join(a), expected)
Example #10
0
def check_version():
    """Tests if Python version is >= 3.5.x and print user instructions if it is not."""

    message = (
        "Hey asshole, did you even read the README? You're using the wrong Python "
        "version and are going to be very sad when I don't save your score."
    )
    prompt = "Would you like to leave and restart after opening with the correct version [y,n]?:"

    if sys.version_info[0] < 3 or (sys.version_info[0] == 3 and sys.version_info[1] < 5):
        print(red(message))
        if input(prompt).lower() in ["y", "yes"]:
            print(bold("Remember to type 'python3'"))
            exit()
    def test_traceback(self):
        i = interpreter.Interp()
        a = []

        def append_to_a(message):
            a.append(message)

        i.write = append_to_a

        def f():
            return 1/0

        def g():
            return f()

        i.runsource('g()')

        expected = 'Traceback (most recent call last):\n  File ' + \
            green('"<input>"') + ', line ' + bold(magenta('1')) + ', in ' + \
            cyan('<module>') + '\n' + bold(red('NameError')) + ': ' + \
            cyan("name 'g' is not defined") + '\n'

        self.assertEquals(str(plain('').join(a)), str(expected))
        self.assertEquals(plain('').join(a), expected)
Example #12
0
    def test_traceback(self):
        i, a = self.interp_errlog()

        def f():
            return 1 / 0

        def gfunc():
            return f()

        i.runsource('gfunc()')

        if pypy and not py3:
            global_not_found = "global name 'gfunc' is not defined"
        else:
            global_not_found = "name 'gfunc' is not defined"

        expected = (
            'Traceback (most recent call last):\n  File ' +
            green('"<input>"') + ', line ' +
            bold(magenta('1')) + ', in ' + cyan('<module>') + '\n    gfunc()\n' +
            bold(red('NameError')) + ': ' + cyan(global_not_found) + '\n')

        self.assertMultiLineEqual(str(plain('').join(a)), str(expected))
        self.assertEqual(plain('').join(a), expected)
Example #13
0
    def tick(self):
        for npc in self.npcs:
            self.move_entity(npc, *npc.towards(self.player))
        for entity1, entity2 in itertools.combinations(self.entities, 2):
            if (entity1.x, entity1.y) == (entity2.x, entity2.y):
                if self.player in (entity1, entity2):
                    return 'you lost on turn %d' % self.turn
                entity1.die()
                entity2.die()

        if all(npc.speed == 0 for npc in self.npcs):
            return 'you won on turn %d' % self.turn
        self.turn += 1
        if self.turn % 20 == 0:
            self.player.speed = max(0, self.player.speed - 1)
            self.player.display = on_blue(green(bold(str(self.player.speed))))
Example #14
0
    def tick(self):
        """Returns a message to be displayed if game is over, else None"""
        for npc in self.npcs:
            self.move_entity(npc, *npc.towards(self.player))
        for entity1, entity2 in itertools.combinations(self.entities, 2):
            if (entity1.x, entity1.y) == (entity2.x, entity2.y):
                if self.player in (entity1, entity2):
                    return 'you lost on turn %d' % self.turn
                entity1.die()
                entity2.die()

        if all(npc.speed == 0 for npc in self.npcs):
            return 'you won on turn %d' % self.turn
        self.turn += 1
        if self.turn % 20 == 0:
            self.player.speed = max(1, self.player.speed - 1)
            self.player.display = on_blue(green(bold(str(self.player.speed).decode('utf8'))))
 def test_enter_text(self):
     [self.repl.add_normal_character(c) for c in '1 + 1']
     screen = fsarray([cyan('>>> ') + bold(green('1') + cyan(' ') +
                       yellow('+') + cyan(' ') + green('1')),
                       cyan('Welcome to')])
     self.assert_paint(screen, (0, 9))
Example #16
0
 def die(self):
     self.speed = 0
     self.display = on_red(bold(yellow('o')))
Example #17
0
 def test_enter_text(self):
     [self.repl.add_normal_character(c) for c in '1 + 1']
     screen = fsarray([cyan('>>> ') + bold(green('1')+cyan(' ')+
                       yellow('+') + cyan(' ') + green('1')), cyan('Welcome to')])
     self.assert_paint(screen, (0, 9))
Example #18
0
def formatted_argspec(funcprops, arg_pos, columns, config):
    # Pretty directly taken from bpython.cli
    func = funcprops.func
    args = funcprops.argspec.args
    kwargs = funcprops.argspec.defaults
    _args = funcprops.argspec.varargs
    _kwargs = funcprops.argspec.varkwargs
    is_bound_method = funcprops.is_bound_method
    kwonly = funcprops.argspec.kwonly
    kwonly_defaults = funcprops.argspec.kwonly_defaults or dict()

    arg_color = func_for_letter(config.color_scheme["name"])
    func_color = func_for_letter(config.color_scheme["name"].swapcase())
    punctuation_color = func_for_letter(config.color_scheme["punctuation"])
    token_color = func_for_letter(config.color_scheme["token"])
    bolds = {
        token_color: lambda x: bold(token_color(x)),
        arg_color: lambda x: bold(arg_color(x)),
    }

    s = func_color(func) + arg_color(": (")

    if is_bound_method and isinstance(arg_pos, int):
        # TODO what values could this have?
        arg_pos += 1

    for i, arg in enumerate(args):
        kw = None
        if kwargs and i >= len(args) - len(kwargs):
            kw = str(kwargs[i - (len(args) - len(kwargs))])
        color = token_color if arg_pos in (i, arg) else arg_color
        if i == arg_pos or arg == arg_pos:
            color = bolds[color]

        s += color(arg)

        if kw is not None:
            s += punctuation_color("=")
            s += token_color(kw)

        if i != len(args) - 1:
            s += punctuation_color(", ")

    if _args:
        if args:
            s += punctuation_color(", ")
        s += token_color(f"*{_args}")

    if kwonly:
        if not _args:
            if args:
                s += punctuation_color(", ")
            s += punctuation_color("*")
        marker = object()
        for arg in kwonly:
            s += punctuation_color(", ")
            color = token_color
            if arg_pos:
                color = bolds[color]
            s += color(arg)
            default = kwonly_defaults.get(arg, marker)
            if default is not marker:
                s += punctuation_color("=")
                s += token_color(repr(default))

    if _kwargs:
        if args or _args or kwonly:
            s += punctuation_color(", ")
        s += token_color(f"**{_kwargs}")
    s += punctuation_color(")")

    return linesplit(s, columns)
Example #19
0
import random

from curtsies import FullscreenWindow, Input, FSArray
from curtsies.fmtfuncs import red, bold, green, on_blue, yellow

if __name__ == '__main__':
    print(yellow('this prints normally, not to the alternate screen'))
    with FullscreenWindow() as window:
        with Input() as input_generator:
            msg = red(on_blue(bold('Press escape to exit')))
            a = FSArray(window.height, window.width)
            a[0:1, 0:msg.width] = [msg]
            window.render_to_terminal(a)
            for c in input_generator:
                if c == '<ESC>':
                    break
                elif c == '<SPACE>':
                    a = FSArray(window.height, window.width)
                else:
                    s = repr(c)
                    row = random.choice(range(window.height))
                    column = random.choice(range(window.width - len(s)))
                    color = random.choice([red, green, on_blue, yellow])
                    a[row, column:column + len(s)] = [color(s)]
                window.render_to_terminal(a)
Example #20
0
def formatted_argspec(argspec, columns, config):
    # Pretty directly taken from bpython.cli
    is_bound_method = argspec[2]
    func = argspec[0]
    args = argspec[1][0]
    kwargs = argspec[1][3]
    _args = argspec[1][1] #*args
    _kwargs = argspec[1][2] #**kwargs
    is_bound_method = argspec[2]
    in_arg = argspec[3]
    if py3:
        kwonly = argspec[1][4]
        kwonly_defaults = argspec[1][5] or dict()

    arg_color = func_for_letter(config.color_scheme['name'])
    func_color = func_for_letter(config.color_scheme['name'].swapcase())
    punctuation_color = func_for_letter(config.color_scheme['punctuation'])
    token_color = func_for_letter(config.color_scheme['token'])
    bolds = {token_color: lambda x: bold(token_color(x)),
            arg_color: lambda x: bold(arg_color(x))}

    s = func_color(func) + arg_color(': (')

    if is_bound_method and isinstance(in_arg, int): #TODO what values could this have?
        in_arg += 1

    for i, arg in enumerate(args):
        kw = None
        if kwargs and i >= len(args) - len(kwargs):
            kw = str(kwargs[i - (len(args) - len(kwargs))])
        color = token_color if in_arg in (i, arg) else arg_color
        if i == in_arg or arg == in_arg:
            color = bolds[color]

        if not py3:
            s += color(inspect.strseq(arg, str))
        else:
            s += color(arg)

        if kw is not None:
            s += punctuation_color('=')
            s += token_color(kw)

        if i != len(args) - 1:
            s += punctuation_color(', ')

    if _args:
        if args:
            s += punctuation_color(', ')
        s += token_color('*%s' % (_args,))

    if py3 and kwonly:
        if not _args:
            if args:
                s += punctuation_color(', ')
            s += punctuation_color('*')
        marker = object()
        for arg in kwonly:
            s += punctuation_color(', ')
            color = token_color
            if in_arg:
                color = bolds[color]
            s += color(arg)
            default = kwonly_defaults.get(arg, marker)
            if default is not marker:
                s += punctuation_color('=')
                s += token_color(repr(default))

    if _kwargs:
        if args or _args or (py3 and kwonly):
            s += punctuation_color(', ')
        s += token_color('**%s' % (_kwargs,))
    s += punctuation_color(')')

    return linesplit(s, columns)
Example #21
0
def formatted_argspec(funcprops, arg_pos, columns, config):
    # Pretty directly taken from bpython.cli
    func = funcprops.func
    args = funcprops.argspec.args
    kwargs = funcprops.argspec.defaults
    _args = funcprops.argspec.varargs
    _kwargs = funcprops.argspec.varkwargs
    is_bound_method = funcprops.is_bound_method
    if py3:
        kwonly = funcprops.argspec.kwonly
        kwonly_defaults = funcprops.argspec.kwonly_defaults or dict()

    arg_color = func_for_letter(config.color_scheme['name'])
    func_color = func_for_letter(config.color_scheme['name'].swapcase())
    punctuation_color = func_for_letter(config.color_scheme['punctuation'])
    token_color = func_for_letter(config.color_scheme['token'])
    bolds = {token_color: lambda x: bold(token_color(x)),
             arg_color: lambda x: bold(arg_color(x))}

    s = func_color(func) + arg_color(': (')

    if is_bound_method and isinstance(arg_pos, int):
        # TODO what values could this have?
        arg_pos += 1

    for i, arg in enumerate(args):
        kw = None
        if kwargs and i >= len(args) - len(kwargs):
            kw = str(kwargs[i - (len(args) - len(kwargs))])
        color = token_color if arg_pos in (i, arg) else arg_color
        if i == arg_pos or arg == arg_pos:
            color = bolds[color]

        if not py3:
            s += color(inspect.strseq(arg, unicode))
        else:
            s += color(arg)

        if kw is not None:
            s += punctuation_color('=')
            if not py3:
                kw = kw.decode('ascii', 'replace')
            s += token_color(kw)

        if i != len(args) - 1:
            s += punctuation_color(', ')

    if _args:
        if args:
            s += punctuation_color(', ')
        s += token_color('*%s' % (_args,))

    if py3 and kwonly:
        if not _args:
            if args:
                s += punctuation_color(', ')
            s += punctuation_color('*')
        marker = object()
        for arg in kwonly:
            s += punctuation_color(', ')
            color = token_color
            if arg_pos:
                color = bolds[color]
            s += color(arg)
            default = kwonly_defaults.get(arg, marker)
            if default is not marker:
                s += punctuation_color('=')
                s += token_color(repr(default))

    if _kwargs:
        if args or _args or (py3 and kwonly):
            s += punctuation_color(', ')
        s += token_color('**%s' % (_kwargs,))
    s += punctuation_color(')')

    return linesplit(s, columns)
Example #22
0
 def die(self):
     self.speed = 0
     self.display = on_red(bold(yellow('o')))
Example #23
0
import sys

from curtsies.fmtfuncs import blue, red, bold, on_red

from curtsies.window import Window
from curtsies.terminal import Terminal

if __name__ == '__main__':

    print(blue('hey') + ' ' + red('there') + ' ' + red(bold('you')))

    with Terminal(sys.stdin, sys.stdout) as tc:
        with Window(tc) as t:
            rows, columns = t.tc.get_screen_size()
            while True:
                c = t.tc.get_event()
                if c == "":
                    sys.exit() # same as raise SystemExit()
                elif c == "a":
                    a = [blue(on_red(c*columns)) for _ in range(rows)]
                elif c == "b":
                    a = t.array_from_text("a small array")
                else:
                    a = t.array_from_text("try a, b, or ctrl-D")
                t.render_to_terminal(a)


Example #24
0
def formatted_argspec(argspec, columns, config):
    # Pretty directly taken from bpython.cli
    is_bound_method = argspec[2]
    func = argspec[0]
    args = argspec[1][0]
    kwargs = argspec[1][3]
    _args = argspec[1][1] #*args
    _kwargs = argspec[1][2] #**kwargs
    is_bound_method = argspec[2]
    in_arg = argspec[3]
    if py3:
        kwonly = argspec[1][4]
        kwonly_defaults = argspec[1][5] or dict()

    arg_color = func_for_letter(config.color_scheme['name'])
    func_color = func_for_letter(config.color_scheme['name'].swapcase())
    punctuation_color = func_for_letter(config.color_scheme['punctuation'])
    token_color = func_for_letter(config.color_scheme['token'])
    bolds = {token_color: lambda x: bold(token_color(x)),
            arg_color: lambda x: bold(arg_color(x))}

    s = func_color(func) + arg_color(': (')

    if is_bound_method and isinstance(in_arg, int): #TODO what values could this have?
        in_arg += 1

    for i, arg in enumerate(args):
        kw = None
        if kwargs and i >= len(args) - len(kwargs):
            kw = str(kwargs[i - (len(args) - len(kwargs))])
        color = token_color if in_arg in (i, arg) else arg_color
        if i == in_arg or arg == in_arg:
            color = bolds[color]

        if not py3:
            s += color(inspect.strseq(arg, str))
        else:
            s += color(arg)

        if kw is not None:
            s += punctuation_color('=')
            s += token_color(kw)

        if i != len(args) - 1:
            s += punctuation_color(', ')

    if _args:
        if args:
            s += punctuation_color(', ')
        s += token_color('*%s' % (_args,))

    if py3 and kwonly:
        if not _args:
            if args:
                s += punctuation_color(', ')
            s += punctuation_color('*')
        marker = object()
        for arg in kwonly:
            s += punctuation_color(', ')
            color = token_color
            if in_arg:
                color = bolds[color]
            s += color(arg)
            default = kwonly_defaults.get(arg, marker)
            if default is not marker:
                s += punctuation_color('=')
                s += token_color(repr(default))

    if _kwargs:
        if args or _args or (py3 and kwonly):
            s += punctuation_color(', ')
        s += token_color('**%s' % (_kwargs,))
    s += punctuation_color(')')

    return linesplit(s, columns)
Example #25
0
from __future__ import unicode_literals # convenient for Python 2
import random

from curtsies import FullscreenWindow, Input, FSArray
from curtsies.fmtfuncs import red, bold, green, on_blue, yellow

print(yellow('this prints normally, not to the alternate screen'))
with FullscreenWindow() as window:
    with Input() as input_generator:
        msg = red(on_blue(bold('Press escape to exit')))
        a = FSArray(window.height, window.width)
        a[0:1, 0:msg.width] = [msg]
        window.render_to_terminal(a)
        for c in input_generator:
            if c == '<ESC>':
                break
            elif c == '<SPACE>':
                a = FSArray(window.height, window.width)
            else:
                s = repr(c)
                row = random.choice(range(window.height))
                column = random.choice(range(window.width-len(s)))
                color = random.choice([red, green, on_blue, yellow])
                a[row, column:column+len(s)] = [color(s)]
            window.render_to_terminal(a)
Example #26
0
from direct.showbase.ShowBase import ShowBase


base = ShowBase()
base.setSleep(0.001)


import random

from curtsies import FullscreenWindow, Input, FSArray
from curtsies.fmtfuncs import red, bold, green, on_blue, yellow
r = 0

print(yellow('the following code takes over the screen'))
with FullscreenWindow() as window:
    print(red(on_blue(bold('Press escape to exit'))))
    with Input() as input_generator:
        a = FSArray(window.height, window.width)
        a[r, 0] = [repr("Test " + str(r))]
        window.render_to_terminal(a)
        r += 1
        for c in input_generator:
            if c == '<ESC>':
                break
            elif c == '<SPACE>':
                a = FSArray(window.height, window.width)
            else:
                row = random.choice(range(window.height))
                column = random.choice(range(window.width-len(repr(c))))
                color = random.choice([red, green, on_blue, yellow])
                a[row, column:column+len(repr(c))] = [color(repr(c))]
Example #27
0
 def test_repr(self):
     self.assertEqual(fmtstr("hello", "red", bold=False), red("hello"))
     self.assertEqual(fmtstr("hello", "red", bold=True), bold(red("hello")))