Esempio n. 1
0
def test_Choice_default_first():
    arg = Choice(('true on', True), ('false off', False))
    eq_(str(arg), 'true')
    eq_(arg.name, 'true')
    eq_(repr(arg), "Choice(('true on', True), ('false off', False))")

    test = make_type_checker(arg)
    yield test, '', 0, (True, 0)
    yield test, 't', 0, (True, 1)
    yield test, 'true', 0, (True, 4)
    yield test, 'false', 0, (False, 5)
    yield test, 'f', 0, (False, 1)
    yield test, 'True', 0, \
        ParseError("'True' does not match any of: true, false", arg, 0, 4)
    yield test, 'False', 0, \
        ParseError("'False' does not match any of: true, false", arg, 0, 5)

    test = make_placeholder_checker(arg)
    yield test, '', 0, ("true", 0)
    yield test, 't', 0, ("rue", 1)
    yield test, 'true', 0, ("", 4)
    yield test, 'false', 0, ("", 5)
    yield test, 'f', 0, ("alse", 1)
    yield test, 'o', 0, ("...", 1)
    yield test, 'on', 0, ("", 2)
    yield test, 'of', 0, ("f", 2)
Esempio n. 2
0
def test_SubParser():
    sub = SubArgs("val", Int("num"), abc="xyz")
    su2 = SubArgs("str", Choice(('yes', True), ('no', False)), abc="mno")
    su3 = SubArgs("stx", VarArgs("args", placeholder="..."), abc="pqr")
    arg = SubParser("var", sub, su2, su3)
    eq_(str(arg), 'var')
    eq_(
        repr(arg), "SubParser('var', SubArgs('val', Int('num'), abc='xyz'), "
        "SubArgs('str', Choice(('yes', True), ('no', False)), abc='mno'), "
        "SubArgs('stx', VarArgs('args', placeholder='...'), abc='pqr'))")

    test = make_completions_checker(arg)
    yield test, "", (["str", "stx", "val"], 0)
    yield test, "v", (["val"], 1)
    yield test, "v ", ([], 2)
    yield test, "val", (["val"], 3)
    yield test, "val ", ([], 4)
    yield test, "val v", (None, 4)
    yield test, "st", (["str", "stx"], 2)
    yield test, "str ", (["yes", "no"], 4)
    yield test, "str y", (["yes"], 5)

    test = make_placeholder_checker(arg)
    yield test, "", 0, ("var ...", 0)
    yield test, "v", 0, ("al num", 1)
    yield test, "v ", 0, ("num", 2)
    yield test, "val", 0, (" num", 3)
    yield test, "val ", 0, ("num", 4)
    yield test, "val 1", 0, ("", 5)
    yield test, "val x", 0, (None, None)
    yield test, "s", 0, ("...", 1)
    yield test, "s ", 0, (None, None)
    yield test, "st", 0, ("...", 2)
    yield test, "str", 0, (" yes", 3)
    yield test, "str ", 0, ("yes", 4)
    yield test, "str y", 0, ("es", 5)
    yield test, "str yes", 0, ("", 7)
    yield test, "str n", 0, ("o", 5)
    yield test, "str x", 0, (None, None)
    yield test, "str x ", 0, (None, None)

    test = make_type_checker(arg)
    yield test, '', 0, (None, 0)
    yield test, 'x', 0, ParseError("'x' does not match any of: str, stx, val",
                                   arg, 0, 1)
    yield test, 'v 1', 0, ((sub, Options(num=1)), 3)
    yield test, 'val 1', 0, ((sub, Options(num=1)), 5)
    yield test, 'val 1 2', 0, ((sub, Options(num=1)), 6)
    yield test, 'val x 2', 0, ArgumentError(
        "invalid arguments: val x 2", Options(num=None), [
            ParseError("invalid literal for int() with base 10: 'x'",
                       Int("num"), 4, 6)
        ], 4)

    test = make_arg_string_checker(arg)
    yield test, (sub, Options(num=1)), "val 1"
    yield test, (su2, Options(yes=True)), "str "
    yield test, (su2, Options(yes=False)), "str no"
Esempio n. 3
0
def test_CommandParser_incomplete():
    parser = CommandParser(Choice('arg', 'all'))

    def check(err):
        eq_(err.options, Options(arg="arg"))
        eq_(err.errors, [
            ParseError("'a' is ambiguous: arg, all", Choice('arg', 'all'), 0,
                       1)
        ])

    with assert_raises(ArgumentError, msg=check):
        parser.parse('a')
Esempio n. 4
0
def test_CommandParser_order():
    def test(text, result):
        if isinstance(result, Options):
            eq_(parser.parse(text), result)
        else:
            assert_raises(result, parser.parse, text)

    parser = CommandParser(
        Choice(('selection', True), ('all', False)),
        Choice(('forward', False), ('reverse', True), name='reverse'),
    )
    tt = Options(selection=True, reverse=True)
    yield test, 'selection reverse', tt
    yield test, 'sel rev', tt
    yield test, 'rev sel', ArgumentError
    yield test, 'r s', ArgumentError
    yield test, 's r', tt
    yield test, 'rev', tt
    yield test, 'sel', Options(selection=True, reverse=False)
    yield test, 'r', tt
    yield test, 's', Options(selection=True, reverse=False)
Esempio n. 5
0
    def test(c):
        m = Mocker()
        beep = m.replace(ak, 'NSBeep')

        @command(arg_parser=CommandParser(
            Choice(('selection', True), ('all', False)),
            Choice(('forward', False), ('reverse xyz', True), name='reverse'),
            Regex('sort_regex', True),
        ))
        def cmd(textview, sender, args):
            raise NotImplementedError("should not get here")

        @command(arg_parser=CommandParser(
            Regex('search_pattern'),
            Choice(('yes', True), ('no', False)),
        ),
                 lookup_with_arg_parser=True)
        def search(textview, sender, args):
            raise NotImplementedError("should not get here")

        bar = CommandTester(cmd, search)
        with m:
            eq_(bar.get_completions(c.text), c.expect)
Esempio n. 6
0
    def test(c):
        m = Mocker()
        beep = m.replace(ak, 'NSBeep')

        @command(arg_parser=CommandParser(
            Choice(('selection', True), ('all', False)),
            Choice(('no', False), ('yes', True)),
            Regex('sort_regex', True),
        ))
        def cmd(textview, sender, args):
            raise NotImplementedError("should not get here")

        @command(arg_parser=CommandParser(
            Regex('search_pattern', replace=c.replace),
            Choice(('yep', False), ('yes', True)),
            VarArgs("args", placeholder="..."),
        ),
                 lookup_with_arg_parser=True)
        def search(textview, sender, args):
            raise NotImplementedError("should not get here")

        bar = CommandTester(cmd, search)
        with m:
            eq_(bar.get_placeholder(c.text), c.expect)
Esempio n. 7
0
def test_CommandParser_arg_string():
    parser = CommandParser(yesno, Choice('arg', 'all'))

    def test(options, argstr):
        if isinstance(argstr, Exception):

            def check(err):
                eq_(err, argstr)

            with assert_raises(type(argstr), msg=check):
                parser.arg_string(options)
        else:
            result = parser.arg_string(options)
            eq_(result, argstr)

    yield test, Options(yes=True, arg="arg"), ""
    yield test, Options(yes=False, arg="arg"), "no"
    yield test, Options(yes=True, arg="all"), " all"
    yield test, Options(yes=False, arg="all"), "no all"
    yield test, Options(), Error("missing option: yes")
    yield test, Options(yes=True), Error("missing option: arg")
    yield test, Options(yes=None), Error("invalid value: yes=None")
Esempio n. 8
0
from editxt.command.parser import Choice, Int, CommandParser, Options
from editxt.command.util import has_selection, iterlines

log = logging.getLogger(__name__)

WHITESPACE = re.compile(r"[ \t]*")


@command(
    name='wrap',
    title="Hard Wrap...",
    hotkey=("\\", ak.NSCommandKeyMask | ak.NSShiftKeyMask),
    is_enabled=has_selection,
    arg_parser=CommandParser(  # TODO test
        Int('wrap_column', default=const.DEFAULT_RIGHT_MARGIN),
        Choice(('indent', True), ('no-indent', False)),
    ))
def wrap_lines(textview, sender, args):
    if args is None:
        wrapper = WrapLinesController(textview)
        wrapper.begin_sheet(sender)
    else:
        wrap_selected_lines(textview, args)


@command(
    title="Hard Wrap At Margin",
    hotkey=("\\", ak.NSCommandKeyMask),
    arg_parser=CommandParser(  # TODO test
        Choice(('indent', True),
               ('no-indent', False)),  # TODO default to last used value
Esempio n. 9
0
    textview.doc_view.finder.mark_occurrences("")


def set_docview_variable(textview, name, args):
    setattr(textview.doc_view.props, name, args.value)

def set_docview_indent_vars(textview, name, args):
    props = textview.doc_view.props
    setattr(props, "indent_size", args.size)
    setattr(props, "indent_mode", args.mode)

@command(name="set", arg_parser=CommandParser(SubParser("variable",
    SubArgs("highlight_selected_text",
        Choice(
            ("yes", True),
            ("no", False),
            name="value",
        ),
        setter=set_docview_variable),
    SubArgs("indent",
        Int("size", default=4), #lambda textview: app.config["indent_size"]),
        Choice(
            ("space", const.INDENT_MODE_SPACE),
            ("tab", const.INDENT_MODE_TAB),
            name="mode",
            #default=lambda textview: textview.doc_view.document.indent_mode)
        ),
        setter=set_docview_indent_vars),
    SubArgs("newline_mode",
        Choice(
            ("Unix unix LF lf \\n", const.NEWLINE_MODE_UNIX),
Esempio n. 10
0
FORWARD = "FORWARD"
BACKWARD = "BACKWARD"
WRAPTOKEN = "WRAPTOKEN"

REGEX = "regex"
REPY = "python-replace"
LITERAL = "literal"
WORD = "word"


@command(arg_parser=CommandParser(
    Regex('pattern', replace=True, default=(RegexPattern(), "")),
    Choice(('find-next next', 'find_next'),
           ('find-previous previous', 'find_previous'),
           ('replace-one one', 'replace_one'),
           ('replace-all all', 'replace_all'),
           ('replace-in-selection in-selection selection',
            'replace_all_in_selection'),
           ('count-occurrences highlight', 'count_occurrences'),
           name='action'),
    Choice('regex literal word python-replace', name='search_type'),
    Choice(('wrap', True), ('no-wrap', False), name='wrap_around'),
),
         lookup_with_arg_parser=True)
def find(textview, sender, args):
    assert args is not None, sender
    opts = FindOptions(**args.__dict__)
    save_to_find_pasteboard(opts.find_text)
    finder = Finder(lambda: textview, opts)
    return getattr(finder, args.action)(sender)

Esempio n. 11
0
import re
import time

import editxt.constants as const
from editxt.command.base import command, objc_delegate, SheetController
from editxt.command.parser import (Choice, Regex, RegexPattern, CommandParser,
                                   Options)
from editxt.commands import iterlines

log = logging.getLogger(__name__)


@command(name='sort',
         title="Sort Lines...",
         arg_parser=CommandParser(
             Choice(('selection', True), ('all', False)),
             Choice(('forward', False), ('reverse', True), name='reverse'),
             Choice(('sort-leading-whitespace', False),
                    ('ignore-leading-whitespace', True),
                    name='ignore_leading_whitespace'),
             Choice(('ignore-case', True), ('match-case', False)),
             Regex('sort-regex', True),
         ))
def sort_lines(textview, sender, args):
    if args is None:
        sorter = SortLinesController(textview)
        sorter.begin_sheet(sender)
    else:
        sortlines(textview, args)

Esempio n. 12
0
import logging
import re
from functools import partial

from mocker import Mocker, expect, ANY, MATCH
from nose.tools import eq_
from editxt.test.util import assert_raises, TestConfig

from editxt.command.parser import (Choice, Int, String, Regex, RegexPattern,
                                   CommandParser, SubArgs, SubParser, VarArgs,
                                   identifier, Options, Error, ArgumentError,
                                   ParseError)

log = logging.getLogger(__name__)

yesno = Choice(('yes', True), ('no', False))
arg_parser = CommandParser(yesno)


def test_CommandParser():
    def test_parser(argstr, options, parser):
        if isinstance(options, Exception):

            def check(err):
                eq_(err, options)

            with assert_raises(type(options), msg=check):
                parser.parse(argstr)
        else:
            opts = parser.default_options()
            opts.__dict__.update(options)
Esempio n. 13
0
 def test(rep, args):
     eq_(repr(Choice(*args[0], **args[1])), rep)
Esempio n. 14
0
def test_CommandParser():
    def test_parser(argstr, options, parser):
        if isinstance(options, Exception):

            def check(err):
                eq_(err, options)

            with assert_raises(type(options), msg=check):
                parser.parse(argstr)
        else:
            opts = parser.default_options()
            opts.__dict__.update(options)
            eq_(parser.parse(argstr), opts)

    test = partial(test_parser, parser=CommandParser(yesno))
    yield test, "", Options(yes=True)
    yield test, "no", Options(yes=False)

    manual = SubArgs("manual", Int("bass", default=50),
                     Int("treble", default=50))
    preset = SubArgs("preset", Choice("flat", "rock", "cinema", name="value"))
    level = Choice(("off", 0), ('high', 4), ("medium", 2), ('low', 1),
                   name="level")
    radio_parser = CommandParser(
        SubParser(
            "equalizer",
            manual,
            preset,
        ),
        level,
        Int("volume", default=50),  #, min=0, max=100),
        String("name"),  #, quoted=True),
    )
    test = partial(test_parser, parser=radio_parser)
    yield test, "manual", Options(equalizer=(manual,
                                             Options(bass=50, treble=50)))
    yield test, "", Options()
    yield test, "preset rock low", Options(level=1,
                                           equalizer=(preset,
                                                      Options(value="rock")))
    yield test, "  high", Options(level=0, name="high")
    yield test, " high", Options(level=4)
    yield test, "high", Options(level=4)
    yield test, "hi", Options(level=4)
    yield test, "high '' yes", ArgumentError(
        'unexpected argument(s): yes',
        Options(volume=50, equalizer=None, name='', level=4), [], 8)

    def test_placeholder(argstr, expected, parser=radio_parser):
        eq_(parser.get_placeholder(argstr), expected)

    test = test_placeholder
    yield test, "", "equalizer ... off 50 name"
    yield test, "  ", "50 name"
    yield test, "  5", " name"
    yield test, "  5 ", "name"
    yield test, "  high", ""
    yield test, " hi", "gh 50 name"
    yield test, " high", " 50 name"
    yield test, "hi", "gh 50 name"
    yield test, "high ", "50 name"

    def make_completions_checker(argstr, expected, parser=radio_parser):
        eq_(parser.get_completions(argstr), expected)

    test = make_completions_checker
    yield test, "", ['manual', 'preset']
    yield test, "  ", []
    yield test, "  5", []
    yield test, "  5 ", []
    yield test, "  high", []
    yield test, " ", ["off", "high", "medium", "low"]
    yield test, " hi", ["high"]

    parser = CommandParser(level, Int("value"),
                           Choice("highlander", "tundra", "4runner"))
    test = partial(make_completions_checker, parser=parser)
    yield test, "h", ["high"]
    yield test, "t", ["tundra"]
    yield test, "high", ["high"]
    yield test, "high ", []
    yield test, "high 4", []
    yield test, "high x", None  # ??? None indicates an error (the last token could not be consumed) ???
    yield test, "high  4", ["4runner"]
Esempio n. 15
0
def test_Choice_strings():
    arg = Choice('maybe yes no', name='yes')
    eq_(str(arg), 'maybe')
    eq_(arg.name, 'yes')
    eq_(repr(arg), "Choice('maybe yes no', name='yes')")
Esempio n. 16
0
 def check(err):
     eq_(err.options, Options(arg="arg"))
     eq_(err.errors, [
         ParseError("'a' is ambiguous: arg, all", Choice('arg', 'all'), 0,
                    1)
     ])
Esempio n. 17
0
def test_Choice():
    arg = Choice('arg-ument', 'nope', 'nah')
    eq_(str(arg), 'arg-ument')
    eq_(arg.name, 'arg_ument')

    test = make_type_checker(arg)
    yield test, 'arg-ument', 0, ("arg-ument", 9)
    yield test, 'arg', 0, ("arg-ument", 3)
    yield test, 'a', 0, ("arg-ument", 1)
    yield test, 'a', 1, ("arg-ument", 1)
    yield test, '', 0, ("arg-ument", 0)
    yield test, '', 3, ("arg-ument", 3)
    yield test, 'arg arg', 0, ("arg-ument", 4)
    yield test, 'nope', 0, ("nope", 4)
    yield test, 'nop', 0, ("nope", 3)
    yield test, 'no', 0, ("nope", 2)
    yield test, 'nah', 0, ("nah", 3)
    yield test, 'na', 0, ("nah", 2)

    test = make_arg_string_checker(arg)
    yield test, "arg-ument", ""
    yield test, "nope", "nope"
    yield test, "nah", "nah"
    yield test, "arg", Error("invalid value: arg_ument='arg'")

    arg = Choice(('arg-ument', True), ('nope', False), ('nah', ""))
    test = make_type_checker(arg)
    yield test, 'arg-ument', 0, (True, 9)
    yield test, 'arg', 0, (True, 3)
    yield test, 'a', 0, (True, 1)
    yield test, 'a', 1, (True, 1)
    yield test, '', 0, (True, 0)
    yield test, '', 3, (True, 3)
    yield test, 'arg arg', 0, (True, 4)
    yield test, 'nope', 0, (False, 4)
    yield test, 'nop', 0, (False, 3)
    yield test, 'no', 0, (False, 2)
    yield test, 'nah', 0, ("", 3)
    yield test, 'na', 0, ("", 2)
    yield test, 'n', 0, \
        ParseError("'n' is ambiguous: nope, nah", arg, 0, 1)
    yield test, 'arg', 1, \
        ParseError("'rg' does not match any of: arg-ument, nope, nah", arg, 1, 3)
    yield test, 'args', 0, \
        ParseError("'args' does not match any of: arg-ument, nope, nah", arg, 0, 4)
    yield test, 'args arg', 0, \
        ParseError("'args' does not match any of: arg-ument, nope, nah", arg, 0, 5)

    test = make_placeholder_checker(arg)
    yield test, '', 0, ("arg-ument", 0)
    yield test, 'a', 0, ("rg-ument", 1)
    yield test, 'n', 0, ("...", 1)

    arg = Choice("argument parameter", "find search")
    test = make_type_checker(arg)
    yield test, 'a', 0, ("argument", 1)
    yield test, 'arg', 0, ("argument", 3)
    yield test, 'argument', 0, ("argument", 8)
    yield test, 'p', 0, ("argument", 1)
    yield test, 'param', 0, ("argument", 5)
    yield test, 'parameter', 0, ("argument", 9)
    yield test, 'f', 0, ("find", 1)
    yield test, 'find', 0, ("find", 4)
    yield test, 's', 0, ("find", 1)
    yield test, 'search', 0, ("find", 6)
    yield test, 'arg-ument', 0, \
        ParseError("'arg-ument' does not match any of: argument, find", arg, 0, 9)

    arg = Choice(("argument parameter", True), ("find search", False))
    test = make_type_checker(arg)
    yield test, 'a', 0, (True, 1)
    yield test, 'arg', 0, (True, 3)
    yield test, 'argument', 0, (True, 8)
    yield test, 'p', 0, (True, 1)
    yield test, 'param', 0, (True, 5)
    yield test, 'parameter', 0, (True, 9)
    yield test, 'f', 0, (False, 1)
    yield test, 'find', 0, (False, 4)
    yield test, 's', 0, (False, 1)
    yield test, 'search', 0, (False, 6)
    yield test, 'arg-ument', 0, \
        ParseError("'arg-ument' does not match any of: argument, find", arg, 0, 9)