Example #1
0
        def run(obj):
            m = mocker.Mocker()
            ob2 = object()
            # part 1: replace method
            if method_as_string:
                args = (obj, "isEqualTo_")
            else:
                args = (obj.isEqualTo_, )
            iseq = m.method(*args)
            iseq(ob2) >> True
            with m:
                assert obj.isEqualTo_(ob2)
            assert not obj.isEqualTo_(ob2), "%r == %r" % (obj, ob2)
            # part 2: check if the original is called after test
            func = iseq.replaced.func
            try:

                class Error(Exception):
                    pass

                def error(self, arg):
                    assert self is obj, "%r != %r" % (self, obj)
                    assert arg is ob2, repr(arg)
                    raise Error("expected error")

                iseq.replaced.func = error
                assert_raises(Error, obj.isEqualTo_, ob2)
            finally:
                iseq.replaced.func = func
Example #2
0
 def run(obj):
     m = mocker.Mocker()
     ob2 = object()
     # part 1: replace method
     if method_as_string:
         args = (obj, "isEqualTo_")
     else:
         args = (obj.isEqualTo_,)
     iseq = m.method(*args)
     iseq(ob2) >> True
     with m:
         assert obj.isEqualTo_(ob2)
     assert not obj.isEqualTo_(ob2), "%r == %r" % (obj, ob2)
     # part 2: check if the original is called after test
     func = iseq.replaced.func
     try:
         class Error(Exception): pass
         def error(self, arg):
             assert self is obj, "%r != %r" % (self, obj)
             assert arg is ob2, repr(arg)
             raise Error("expected error")
         iseq.replaced.func = error
         assert_raises(Error, obj.isEqualTo_, ob2)
     finally:
         iseq.replaced.func = func
Example #3
0
    def test(c):
        m = Mocker()
        options = make_options(c)
        tv = m.mock(TextView)
        tv.selectedRange() >> fn.NSMakeRange(0, 16)
        tv.string() >> fn.NSString.alloc().initWithString_(c.text)
        if not isinstance(c.expect, Exception):
            result = [c.text]

            def replace(range, value):
                start, end = range
                text = result[0]
                result[0] = text[:start] + value + text[start + end:]

            tv.shouldChangeTextInRange_replacementString_(ANY, ANY) >> True
            expect(tv.textStorage().replaceCharactersInRange_withString_(
                ANY, ANY)).call(replace)
            tv.didChangeText()
            tv.setNeedsDisplay_(True)
        finder = Finder((lambda: tv), options)
        with m:
            if isinstance(c.expect, Exception):

                def check(err):
                    print(err)
                    eq_(str(err), str(c.expect))

                with assert_raises(type(c.expect), msg=check):
                    getattr(finder, c.action)(None)
            else:
                getattr(finder, c.action)(None)
                eq_(result[0], c.expect)
Example #4
0
 def test(expect, old_value=None):
     if isinstance(expect, Exception):
         exc = type(expect)
         exc_val = expect
     elif expect == old_value:
         exc = IOError
         exc_val = IOError("fail")
     else:
         exc = exc_val = None
     with tempdir() as tmp:
         path = os.path.join(tmp, "file.txt")
         if old_value is not None:
             with open(path, "x") as fh:
                 fh.write(old_value)
         with assert_raises(exc, msg=exc_val):
             with mod.atomicfile(path) as fh:
                 fh.write("new")
                 if exc_val is not None:
                     raise exc_val
         files = os.listdir(tmp)
         if exc is None:
             with open(path) as fh:
                 eq_(fh.read(), expect)
             assert files == ["file.txt"], files
         elif old_value is not None:
             assert files == ["file.txt"], files
             with open(path) as fh:
                 eq_(fh.read(), old_value)
         else:
             assert not files, files
Example #5
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')
Example #6
0
 def test(c):
     m = Mocker()
     options = make_options(c)
     tv = m.mock(TextView)
     tv.selectedRange() >> fn.NSMakeRange(0, 16)
     tv.string() >> fn.NSString.alloc().initWithString_(c.text)
     if not isinstance(c.expect, Exception):
         result = [c.text]
         def replace(range, value):
             start, end = range
             text = result[0]
             result[0] = text[:start] + value + text[start + end:]
         tv.shouldChangeTextInRange_replacementString_(ANY, ANY) >> True
         expect(tv.textStorage().replaceCharactersInRange_withString_(
             ANY, ANY)).call(replace)
         tv.didChangeText()
         tv.setNeedsDisplay_(True)
     finder = Finder((lambda: tv), options)
     with m:
         if isinstance(c.expect, Exception):
             def check(err):
                 print(err)
                 eq_(str(err), str(c.expect))
             with assert_raises(type(c.expect), msg=check):
                 getattr(finder, c.action)(None)
         else:
             getattr(finder, c.action)(None)
             eq_(result[0], c.expect)
Example #7
0
 def test(expect, old_value=None):
     if isinstance(expect, Exception):
         exc = type(expect)
         exc_val = expect
     elif expect == old_value:
         exc = IOError
         exc_val = IOError("fail")
     else:
         exc = exc_val = None
     with tempdir() as tmp:
         path = os.path.join(tmp, "file.txt")
         if old_value is not None:
             with open(path, "x") as fh:
                 fh.write(old_value)
         with assert_raises(exc, msg=exc_val):
             with mod.atomicfile(path) as fh:
                 fh.write("new")
                 if exc_val is not None:
                     raise exc_val
         files = os.listdir(tmp)
         if exc is None:
             with open(path) as fh:
                 eq_(fh.read(), expect)
             assert files == ["file.txt"], files
         elif old_value is not None:
             assert files == ["file.txt"], files
             with open(path) as fh:
                 eq_(fh.read(), old_value)
         else:
             assert not files, files
Example #8
0
 def test(c):
     m = Mocker()
     beep = m.replace(mod, "beep")
     options = make_options(c)
     editor = m.mock(Editor)
     editor.selection >> c.select
     (editor.text << Text(c.text)).count(0, None)
     tv = m.mock(ak.NSTextView)
     (editor.text_view << tv).count(0, 1)
     (tv.shouldChangeTextInRange_replacementString_(ANY, ANY) << True).count(0, 1)
     expect(tv.didChangeText()).count(0, 1)
     expect(tv.setNeedsDisplay_(True)).count(0, 1)
     if c.expect is BEEP:
         beep()
     finder = Finder((lambda: editor), options, None)
     with m:
         if isinstance(c.expect, Exception):
             def check(err):
                 print(err)
                 eq_(str(err), str(c.expect))
             with assert_raises(type(c.expect), msg=check):
                 getattr(finder, c.action)(None)
         else:
             getattr(finder, c.action)(None)
             if c.expect is BEEP:
                 eq_(editor.text[:], c.text)
             else:
                 eq_(editor.text[:], c.expect)
Example #9
0
    def test(c):
        m = Mocker()
        beep = m.replace(mod, "beep")
        options = make_options(c)
        editor = m.mock(Editor)
        (editor.selection << c.select).count(0, None)
        (editor.text << Text(c.text)).count(0, None)

        def put(text, rng, select=False):
            editor.text[rng] = text
        (editor.put(ANY, ANY) << (c.expect is not BEEP)).call(put).count(0, 1)
        if c.expect is BEEP:
            beep()
        finder = Finder((lambda: editor), options, None)
        with m:
            if isinstance(c.expect, Exception):
                def check(err):
                    print(err)
                    eq_(str(err), str(c.expect))
                with assert_raises(type(c.expect), msg=check):
                    getattr(finder, c.action)(None)
            else:
                getattr(finder, c.action)(None)
                if c.expect is BEEP:
                    eq_(editor.text[:], c.text)
                else:
                    eq_(editor.text[:], c.expect)
Example #10
0
 def test(rng, expect):
     with assert_raises(expect if not isinstance(expect, str) else None):
         if callable(rng):
             result = rng(text)
         else:
             result = text[rng]
     if isinstance(expect, str):
         eq_(result, expect)
Example #11
0
 def type_checker_test(text, start, expect):
     if isinstance(expect, Exception):
         def check(err):
             eq_(err, expect)
         with assert_raises(type(expect), msg=check):
             field.consume(text, start)
     else:
         eq_(field.consume(text, start), expect)
Example #12
0
 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)
Example #13
0
def verify_editor_interface(editor):
    from editxt.util import KVOProxy
    from editxt.platform.window import OutputPanel

    assert editor.id is not None
    assert not editor.is_dirty
    assert hasattr(editor, "file_path")

    dn = editor.name
    assert dn is not None
    icon = editor.icon()
    if isinstance(editor, Editor):
        assert editor.project is not None, editor.project
        assert icon is not None
        with assert_raises(AttributeError):
            editor.name = "something"
        assert editor.name == dn
        assert editor.is_leaf
        #assert not editor.expanded
    else:
        assert icon is None
        assert not editor.is_leaf
        assert editor.expanded

    # verify command output interface
    m = Mocker()
    command_view = editor.command_view = CommandView()
    output = editor.get_output_view()
    assert not command_view.is_waiting()
    proc = m.mock()
    output.process = proc
    eq_(editor.command_output, output)
    assert command_view.is_waiting()

    rect = object()
    panel = editor.create_output_panel("some text", rect)
    assert not command_view.is_waiting()
    assert panel.is_waiting()
    eq_(command_view.output_text, "")
    eq_(editor.command_output, None)
    eq_(panel.text, "some text")
    eq_(panel.rect, rect)
    proc.terminate()
    with m:
        output.kill_process()
    assert not panel.is_waiting()

    command_view = editor.command_view = CommandView()
    output = editor.get_output_view()
    m = Mocker()
    proc = m.mock()
    proc.terminate()
    output.process = proc
    with m:
        editor.stop_output()
    eq_(editor.command_output, None)
Example #14
0
    def test(text, start, expect):
        if isinstance(expect, Exception):

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

            with assert_raises(type(expect), msg=check):
                arg.consume(text, start)
        else:
            eq_(arg.consume(text, start), expect)
Example #15
0
 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)
Example #16
0
 def test(config_data, error):
     with tempdir() as tmp, CaptureLog(mod) as log:
         path = join(tmp, const.CONFIG_FILENAME)
         with open(path, "w") as f:
             f.write(config_data)
         conf = mod.Config(tmp, SCHEMA)
         with assert_raises(KeyError):
             conf["key"]
         regex = Regex("cannot load [^:]+/config\.yaml: {}".format(error))
         eq_(log.data, {"error": [regex]})
Example #17
0
 def test(config_data, error):
     with tempdir() as tmp, CaptureLog(mod) as log:
         path = join(tmp, const.CONFIG_FILENAME)
         with open(path, "w") as f:
             f.write(config_data)
         conf = mod.Config(tmp, SCHEMA)
         with assert_raises(KeyError):
             conf["key"]
         regex = Regex("cannot load [^:]+/config\.yaml: {}".format(error))
         eq_(log.data, {"error": [regex]})
Example #18
0
 def test(Type, input, value, default=NOT_SET):
     if default is NOT_SET:
         type_ = Type()
     else:
         type_ = Type(default=default)
     if isinstance(value, Exception):
         with assert_raises(type(value), msg=str(value)):
             type_.validate(input, "key")
     else:
         eq_(type_.validate(input, "key"), value)
Example #19
0
 def test(Type, input, value, default=NOT_SET):
     if default is NOT_SET:
         type_ = Type()
     else:
         type_ = Type(default=default)
     if isinstance(value, Exception):
         with assert_raises(type(value), msg=str(value)):
             type_.validate(input, "key")
     else:
         eq_(type_.validate(input, "key"), value)
Example #20
0
 def test(args, msg):
     class Test(object): pass
     def func(arg): pass
     t = Test()
     t.func = func
     m = MockerExt()
     m.replace(t, "func")(*args)
     def check(err):
         assert msg in str(err), "{!r} not in {!r}".format(msg, err)
     with m, assert_raises(AssertionError, msg=check):
         t.func(*args)
Example #21
0
    def test(data, key, value, errors={}):
        config = mod.Config("/tmp/missing.3216546841325465132546514321654")
        config.data = data

        with CaptureLog(mod) as log:
            if isinstance(value, Exception):
                with assert_raises(type(value), msg=str(value)):
                    config[key]
            else:
                eq_(config[key], value)
            eq_(log.data, errors)
Example #22
0
    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)
Example #23
0
    def test(data, key, value, errors={}):
        config = mod.Config("/tmp/missing.3216546841325465132546514321654")
        config.data = data

        with CaptureLog(mod) as log:
            if isinstance(value, Exception):
                with assert_raises(type(value), msg=str(value)):
                    config[key]
            else:
                eq_(config[key], value)
            eq_(log.data, errors)
Example #24
0
    def test(data, key, value, errors={}, stop=[1]):
        config = mod.Config("/tmp/missing.3216546841325465132546514321654")
        config.data = configify(data)
        config.transform_deprecations()

        with CaptureLog(mod) as log:
            if isinstance(value, Exception):
                with assert_raises(type(value), msg=str(value)):
                    config[key]
            else:
                eq_(config[key], value)
            eq_(dict(log.data), errors)
Example #25
0
 def test(command, attribute, value=None):
     m = Mocker()
     tv = m.mock(TextView)
     view = tv.doc_view >> m.mock(TextDocumentView)
     do = CommandTester(mod.set_variable, textview=tv)
     if isinstance(attribute, Exception):
         with assert_raises(type(attribute), msg=str(attribute)), m:
             do(command)
     else:
         setattr(view.props >> m.mock(), attribute, value)
         with m:
             do(command)
Example #26
0
 def test(command, attribute, value=None):
     m = Mocker()
     tv = m.mock(TextView)
     view = tv.doc_view >> m.mock(TextDocumentView)
     do = CommandTester(mod.set_variable, textview=tv)
     if isinstance(attribute, Exception):
         with assert_raises(type(attribute), msg=str(attribute)), m:
             do(command)
     else:
         setattr(view.props >> m.mock(), attribute, value)
         with m:
             do(command)
Example #27
0
 def test_get_argstring(value, argstr, round_trip_equal=True):
     if isinstance(argstr, Exception):
         def check(err):
             eq_(err, argstr)
         with assert_raises(type(argstr), msg=check):
             arg.arg_string(value)
     else:
         eq_(arg.arg_string(value), argstr)
         if round_trip_equal:
             eq_(arg.consume(argstr, 0), (value, len(argstr)))
         else:
             assert arg.consume(argstr, 0) != (value, len(argstr))
Example #28
0
 def test(i, line, text, preset=None):
     text = Text(text)
     lines = LineNumbers(text)
     if preset is END:
         lines[len(text) - 1]
     elif preset is not None:
         lines[preset]
     if isinstance(line, int):
         eq_(lines[i], line)
     else:
         with assert_raises(line):
             lines[i]
Example #29
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')
Example #30
0
    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)
Example #31
0
 def test_get_argstring(value, argstr, index=None):
     if isinstance(argstr, Exception):
         def check(err):
             eq_(err, argstr)
         with assert_raises(type(argstr), msg=check):
             field.arg_string(value)
     else:
         if index is not False:
             if index is None:
                 index = len(argstr) + 1
             eq_(field.consume(argstr, 0), (value, index))
         else:
             assert field.consume(argstr, 0) != (value, len(argstr))
Example #32
0
 def test(command, attribute, value=None):
     with test_app("editor*") as app:
         m = Mocker()
         editor = app.windows[0].current_editor
         editor.text_view = fake_text_view
         proxy = editor.proxy = m.mock()
         do = CommandTester(mod.set_variable, editor=editor)
         if isinstance(attribute, Exception):
             with assert_raises(type(attribute), msg=str(attribute)):
                 do(command)
         else:
             setattr(proxy, attribute, value)
             do(command)
Example #33
0
def test_CommandParser_with_SubParser_errors():
    sub = SubArgs("num", Int("num"), abc="xyz")
    arg = SubParser("var", sub)
    parser = CommandParser(arg)
    def check(err):
        eq_(str(err), "invalid arguments: num x\n"
                      "invalid literal for int() with base 10: 'x'")
        eq_(err.options, Options(var=None))
        eq_(err.errors,
            [ParseError("invalid literal for int() with base 10: 'x'",
                        Int("num"), 4, 5)])
    with assert_raises(ArgumentError, msg=check):
        parser.parse('num x')
Example #34
0
 def test(msg, has_path=False):
     with test_app("editor") as app:
         editor = app.windows[0].projects[0].editors[0]
         if has_path:
             path = editor.file_path = "/file-that-does-not-exist.not"
             msg = msg.format(path)
         if editor.file_path and os.path.exists(editor.file_path):
             raise RuntimeError("cannot run test because file exists: {}"
                 .format(editor.file_path))
         msg.format(editor.file_path)
         m = Mocker()
         with m, assert_raises(mod.CommandError, msg=msg):
             mod.diff(editor, None)
Example #35
0
    def test_get_argstring(value, argstr, round_trip_equal=True):
        if isinstance(argstr, Exception):

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

            with assert_raises(type(argstr), msg=check):
                arg.arg_string(value)
        else:
            eq_(arg.arg_string(value), argstr)
            if round_trip_equal:
                eq_(arg.consume(argstr, 0), (value, len(argstr)))
            else:
                assert arg.consume(argstr, 0) != (value, len(argstr))
Example #36
0
    def test(args, msg):
        class Test(object):
            pass

        def func(arg):
            pass

        t = Test()
        t.func = func
        m = MockerExt()
        m.replace(t, "func")(*args)

        def check(err):
            assert msg in str(err), "{!r} not in {!r}".format(msg, err)

        with m, assert_raises(AssertionError, msg=check):
            t.func(*args)
Example #37
0
def test_CommandParser_with_SubParser_errors():
    sub = SubArgs("num", Int("num"), abc="xyz")
    arg = SubParser("var", sub)
    parser = CommandParser(arg)

    def check(err):
        eq_(
            str(err), "invalid arguments: num x\n"
            "invalid literal for int() with base 10: 'x'")
        eq_(err.options, Options(var=None))
        eq_(err.errors, [
            ParseError("invalid literal for int() with base 10: 'x'",
                       Int("num"), 4, 5)
        ])

    with assert_raises(ArgumentError, msg=check):
        parser.parse('num x')
Example #38
0
 def test(num, expect, text, iter_to_line=None):
     text = Text(text)
     lines = LineNumbers(text)
     if iter_to_line is END:
         list(lines.iter_from(0))
         assert lines.end is not None
     elif iter_to_line is not None:
         if iter_to_line is LINE:
             iter_to_line = num
         for line, index in lines.iter_from(0):
             if line >= iter_to_line:
                 break
     if isinstance(expect, int):
         eq_(lines.index_of(num), expect)
     else:
         with assert_raises(expect):
             lines.index_of(num)
Example #39
0
 def test(path, saved=True):
     with tempdir() as tmp, test_app() as app:
         path, begin_content = setup_path(tmp, path)
         doc = app.document_with_path(path)
         end_content = "modified"
         m = Mocker()
         undo = doc.undo_manager = m.mock(mod.UndoManager)
         if saved:
             m.method(doc.update_syntaxer)()
             undo.savepoint()
         doc.text = end_content
         with m:
             if saved:
                 doc.save()
                 eq_(get_content(doc.file_path), end_content)
             else:
                 with assert_raises(mod.Error):
                     doc.save()
                 eq_(get_content(doc.file_path), begin_content)
Example #40
0
 def regex_test(text, start, expect, flags=0):
     if isinstance(expect, Exception):
         def check(err):
             eq_(err, expect)
         with assert_raises(type(expect), msg=check):
             field.consume(text, start)
         return
     value = field.consume(text, start)
     if expect[0] in [None, (None, None)]:
         eq_(value, expect)
         return
     expr, index = value
     if field.replace:
         (expr, replace) = expr
         got = ((expr, replace), index)
     else:
         got = (expr, index)
     eq_(got, expect)
     eq_(expr.flags, flags | re.UNICODE | re.MULTILINE)
Example #41
0
    def regex_test(text, start, expect, flags=0):
        if isinstance(expect, Exception):

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

            with assert_raises(type(expect), msg=check):
                arg.consume(text, start)
            return
        value = arg.consume(text, start)
        if expect[0] in [None, (None, None)]:
            eq_(value, expect)
            return
        expr, index = value
        if arg.replace:
            (expr, replace) = expr
            got = ((expr, replace), index)
        else:
            got = (expr, index)
        eq_(got, expect)
        eq_(expr.flags, flags | re.UNICODE | re.MULTILINE)
Example #42
0
def test_Config_init_with_no_file():
    with tempdir() as tmp:
        conf = mod.Config(tmp, SCHEMA)
        with assert_raises(KeyError):
            conf["key"]
Example #43
0
 def test_get_missing(m, target, proxy):
     expect(target.thekey).throw(AttributeError)
     with m:
         assert_raises(AttributeError, lambda:proxy.thekey)
Example #44
0
def test_CommandParser_too_many_args():
    with assert_raises(ArgumentError, msg="unexpected argument(s): unexpected"):
        arg_parser.parse('yes unexpected')
Example #45
0
 def test(text, result):
     if isinstance(result, Options):
         eq_(parser.parse(text), result)
     else:
         assert_raises(result, parser.parse, text)
Example #46
0
 def test(text, result):
     if isinstance(result, Options):
         eq_(parser.parse(text), result)
     else:
         assert_raises(result, parser.parse, text)
Example #47
0
def test_CommandParser_too_many_args():
    with assert_raises(ArgumentError,
                       msg="unexpected argument(s): unexpected"):
        arg_parser.parse('yes unexpected')
Example #48
0
def test_Config_init_with_no_file():
    with tempdir() as tmp:
        path = join(tmp, const.CONFIG_FILENAME)
        conf = mod.Config(path, SCHEMA)
        with assert_raises(KeyError):
            conf["key"]
Example #49
0
def test_Config_init_with_no_file():
    with tempdir() as tmp:
        conf = mod.Config(tmp, SCHEMA)
        with assert_raises(KeyError):
            conf["key"]