def do_kvolist_iter(lst): items = [] for it in lst: items.append(it) eq_(len(items), len(lst)) for i, it in enumerate(items): assert lst[i] is it
def test(command, token): with test_app("editor*") as app: editor = app.windows[0].current_editor editor.text_view = fake_text_view do = CommandTester(mod.set_variable, editor=editor) do(command) eq_(editor.document.comment_token, token)
def test(c): if c.eol != "\n": c.input = c.input.replace("\n", c.eol) c.output = c.output.replace("\n", c.eol) oldsel, input = get_selection(c.input, c._get("oldsel")) editor.document.indent_mode = c.mode editor.document.indent_size = c.size editor.document.eol = c.eol editor.text[:] = input editor.selection = oldsel c.setup(c, TestConfig(locals())) c.method(editor, None) if c.output == SAME: eq_(editor.text[:], input) elif 'newsel' in c or '^' in c.output: eq_(mark_selection(editor), mark_selection(c.output, c._get("newsel"))) else: eq_(editor.text[:], c.output.replace('^', '')) if "newsel" in c or '^' in c.output: newsel = get_selection(c.output, c._get("newsel"))[0] eq_(editor.selection, fn.NSMakeRange(*newsel)) if "prevchar" in c: prevchar = c.prevchar if c.eol != "\n": prevchar = prevchar.replace("\n", c.eol)[-1] eq_(editor.text[(newsel[0] - 1, 1)], prevchar)
def test_load_commands(): cmds = mod.load_commands() eq_(cmds["text_menu_commands"], [ mod.show_command_bar, mod.goto_line, mod.comment_text, mod.pad_comment_text, mod.indent_lines, mod.dedent_lines, mod.wrap_at_margin, mod.wrap_lines, mod.sort_lines, mod.reindent, mod.find, mod.clear_highlighted_text, mod.reload_config, mod.set_variable, ]) eq_(set(cmds["input_handlers"]), set([ "insertTab:", "insertBacktab:", "insertNewline:", "moveToBeginningOfLine:", "moveToLeftEndOfLine:", #"moveToBeginningOfLineAndModifySelection:", "deleteBackward:", #"deleteforward:", ]))
def test_load_commands(): cmds = mod.load_commands() eq_(cmds["text_menu_commands"], [ mod.show_command_bar, mod.goto_line, mod.comment_text, mod.pad_comment_text, mod.indent_lines, mod.dedent_lines, mod.wrap_at_margin, mod.wrap_lines, mod.sort_lines, mod.reindent, mod.find, mod.clear_highlighted_text, mod.reload_config, mod.set_variable, ]) eq_( set(cmds["input_handlers"]), set([ "insertTab:", "insertBacktab:", "insertNewline:", "moveToBeginningOfLine:", "moveToLeftEndOfLine:", #"moveToBeginningOfLineAndModifySelection:", "deleteBackward:", #"deleteforward:", ]))
def test(c): opts = TestConfig(wrap_column=c.wid, indent=c.ind) text = Text(c.text) sel = (0, len(c.text)) ctok = c.comment if c.ind else None output = "\n".join(wraplines(iterlines(text, sel), opts, ctok)) eq_(output, c.result)
def test_recent_items_queue_remove(): ris = RecentItemStack(4) ris.push(1) ris.push(2) eq_(list(ris), [1, 2]) ris.discard(1) eq_(list(ris), [2])
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
def test_test_app_context_manager(): from editxt.window import Window with test_app("editor(1)") as app: assert app is not None window = Window(app) app.windows.append(window) eq_(test_app(app).state, "window project editor(1) window[0]")
def test_WrapLinesController_default_options(): with test_app() as app: editor = base.Options(app=app) ctl = WrapLinesController(editor) eq_(ctl.options._target, mod.Options( wrap_column=const.DEFAULT_WRAP_COLUMN, indent=True, ))
def test(actions, result, state): if actions in seen: dups.append(actions) seen.add(actions) undo, stack = simulate(actions) eq_(stack.state, state) eq_(undo.has_unsaved_actions(), result)
def test(i, output, text, preset=None, start=1): text = Text(text) lines = LineNumbers(text) if preset is END: lines[len(text) - 1] elif preset is not None: lines[preset] eq_(list(lines.iter_from(i)), list(enumerate(output, start=start)))
def test(expect, text, iter_to_line=None): text = Text(text) lines = LineNumbers(text) if iter_to_line is not None: for line, index in lines.iter_from(0): if line >= iter_to_line: break eq_(lines.newline_at_end, expect)
def unicode_suite(text, length, breaks={}): eq_(len(Text(text)), length, text) line = 1 for i in range(length): if i in breaks: line = breaks[i] yield test(i, line, text); yield test(length, IndexError, text);
def test(command, size, mode): with test_app("editor*") as app: editor = app.windows[0].current_editor editor.text_view = fake_text_view do = CommandTester(mod.set_variable, editor=editor) do(command) eq_(editor.indent_size, size) eq_(editor.indent_mode, mode)
def test(appends, lookups): with tempdir() as tmp: history = mod.History(tmp, 3, 5) for item in appends: history.append(item) history = mod.History(tmp, 3, 5) eq_(list(enumerate(history)), lookups)
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)
def popen(command, **kw): popen_called.append(True) print(command) eq_(sum(1 for c in command if c == ";"), 1, command) args = shlex.split(command.split(";")[0]) print(args) eq_(args, ["true", "--arg", path, path]) check_call(command, **kw) assert not exists(path), "test file not removed: {}".format(path)
def test(app, filepath, config, create=[]): tapp = test_app(app) for name in create: with open(tapp.temp_path(name), "w") as fh: pass project = app.windows[0].projects[0] path = tapp.temp_path(filepath) mod.open_files([path], project) eq_(tapp.state, "window project " + config)
def test(f_exists): with make_file() as path: if f_exists: stat = os.stat(path) res = (stat.st_size, stat.st_mtime) else: path += "-not-found" res = None eq_(filestat(path), res)
def test(name, expect, appends='abcdefghiabca'): with tempdir() as tmp: history = mod.History(tmp, 3, 5) for i, item in enumerate(appends): history.append(item + " " + str(i)) history = mod.History(tmp, 3, 5) result = next(history.iter_matching(name), None) eq_(result, expect)
def do_kvolist_pop(lst, *args): len_before_pop = len(lst) if args: eq_(len(args), 1, "too many arguments for pop([index])") item = lst[args[0]] else: item = lst[-1] popped = lst.pop(*args) assert item is popped, (item, popped) eq_(len(lst), len_before_pop - 1)
def test_Invoker_invoke(): from editxt.util import Invoker called = [] def callback(): called.append(1) inv = Invoker.alloc().init(callback) Invoker.invoke_(inv) eq_(called, [1]) Invoker.invoke_(inv) eq_(called, [1, 1])
def do_kvolist_pop(lst, *args): len_before_pop = len(lst) if args: eq_(len(args), 1, "too many arguments for pop([index])") item = lst[args[0]] else: item = lst[-1] popped = lst.pop(*args) assert item is popped eq_(len(lst), len_before_pop - 1)
def message(msg, msg_type=const.INFO): if kw.get("output"): self.output = msg self.output_msg_type = msg_type return if kw.get("error"): eq_(msg, kw["error"]) return if isinstance(msg, Exception): raise msg raise AssertionError(msg)
def test(command, message=None, text=DOC_TEXT, select=None): with test_app("window project(/) editor*") as app: editor = app.windows[0].current_editor editor.document.text = text class textview: def selectedRange(): return select or (0, 0) editor.text_view = textview bar = CommandTester(mod.grab, editor=editor, output=True) bar(command) eq_(bar.output, message)
def test(command, expected="", error=None, config="", project_path="/"): project_config = "({})".format(project_path) if project_path else "" if "*" not in config: project_config += "*" base_config = "window project{} ".format(project_config) with test_app(base_config + config) as app: editor = app.windows[0].current_editor CommandTester(mod.open_, editor=editor, error=error)(command) if not error: base_config = base_config.replace("*", "") eq_(test_app(app).state, (base_config + expected).strip())
def test_config_shortcuts(): from editxt.config import config_schema eq_( { f["command"].default for f in config_schema()["shortcuts"].values() if f["command"].default.startswith(" doc ") }, {" doc previous", " doc next", " doc up", " doc down"}, )
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]
def test(pattern, expect_spans, *args): spans = [] texts = [] matches = [] for match in text.finditer(re.compile(pattern), *args): print(repr(match)) span = match.span() spans.append(span) texts.append(text[span[0]:span[1]]) matches.append(match.group(0)) eq_(texts, matches) eq_(spans, expect_spans)
def test_delitem_len_bug(): eq_(list(LineNumbers(Text("\n")).iter_from(0)), [(1, 0)]) # sanity check text = Text("\nx") lines = LineNumbers(text) # sanity check eq_(list(lines.iter_from(0)), [(1, 0), (2, 1)]) eq_(len(lines), 2, repr(text)) text[1:] = "" eq_(list(lines.iter_from(0)), [(1, 0)]) assert lines.newline_at_end, 'no newline at end: ' + repr(text) eq_(len(lines), 2, repr(text))
def test(f_exists): m = Mocker() exists = m.replace("os.path.exists") stat = m.replace("os.stat") path = "<path>" exists(path) >> f_exists if f_exists: stat(path) >> (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) res = (6, 8) else: res = None with m: result = filestat(path) eq_(result, res)
def test_kvolist_items(): lst = KVOList.alloc().init() obj = object() ob2 = object() # test KVO methods yield do_kvolist_countOfItems, lst, 0 yield do_kvolist_insertObject_inItemsAtIndex_, lst, obj, 0 yield do_kvolist_countOfItems, lst, 1 yield do_kvolist_objectInItemsAtIndex_, lst, obj, 0 yield do_kvolist_replaceObjectInItemsAtIndex_withObject_, lst, ob2, 0 yield do_kvolist_objectInItemsAtIndex_, lst, ob2, 0 yield do_kvolist_removeObjectFromItemsAtIndex_, lst, 0 yield do_kvolist_countOfItems, lst, 0 # test list convenience methods yield do_kvolist_len, lst, 0 yield do_kvolist_insert, lst, obj, 0 yield do_kvolist_len, lst, 1 yield do_kvolist_getitem, lst, obj, 0 yield do_kvolist_setitem, lst, ob2, 0 yield do_kvolist_append, lst, obj yield do_kvolist_delitem, lst, 1 yield do_kvolist_contains, lst, ob2 yield do_kvolist_not_contains, lst, obj yield do_kvolist_count, lst, obj, 0 yield do_kvolist_count, lst, ob2, 1 yield do_kvolist_extend, lst, [object(), object()] eq_(len(lst), 3) yield do_kvolist_index, lst, ob2, 0 yield do_kvolist_iter, lst yield do_kvolist_remove, lst, ob2 yield do_kvolist_remove_nonexistent, lst, obj yield do_kvolist_pop, lst, 1 yield do_kvolist_pop, lst lst.setItems_([1, 2, 3, 4]) yield do_kvolist_getslice, lst, 1, 3, [2, 3] lst.setItems_([1, 2, 3, 4]) yield do_kvolist_setslice, lst, 1, 3, [5, 6], [1, 5, 6, 4] lst.setItems_([1, 2, 3, 4]) yield do_kvolist_delslice, lst, 1, 3, [1, 4]
def test(files, lookups): # :param files: List of items representing history files, each # being a list of commands. # :param lookups: List of tuples (<history index>, <command text>), ...] index = [] name = "test" pattern = mod.History.FILENAME_PATTERN with tempdir() as tmp: for i, value in enumerate(files): index.append(pattern.format(name, i)) if value is not None: path = join(tmp, pattern.format(name, i)) with open(path, "w", encoding="utf-8") as fh: for command in reversed(value): fh.write(json.dumps(command) + "\n") path = join(tmp, mod.History.INDEX_FILENAME) with open(path, "w", encoding="utf-8") as fh: json.dump(index, fh) history = mod.History(tmp, 3, 5, name=name) eq_(list(enumerate(history)), lookups)
def test_context_map_put_and_pop(): map = ContextMap() obj = object() key = map.put(obj) assert isinstance(key, int) eq_(len(map), 1) eq_(map.pop(key), obj) eq_(len(map), 0)
def test_recent_items_queue_reset(): items = list(range(10)) ris = RecentItemStack(4) ris.reset(items) eq_(len(ris), 4) eq_(list(ris), items[-4:]) ris.reset() eq_(len(ris), 0)
def test_recent_items_queue_update_and_pop(): ris = RecentItemStack(4) items = [8, 2, 6, 4, 5, 7] for item in items: ris.push(item) eq_(len(ris), 4) for item in reversed(items[-4:]): eq_(ris.pop(), item) eq_(len(ris), 0)
def test_recent_items_queue_push_existing(): ris = RecentItemStack(4) ris.push(1) ris.push(2) ris.push(3) eq_(list(ris), [1, 2, 3]) ris.push(1) eq_(list(ris), [2, 3, 1]) ris.push(3) eq_(list(ris), [2, 1, 3])
def test(c): if c.eol != "\n": c.input = c.input.replace("\n", c.eol) c.output = c.output.replace("\n", c.eol) result = TestConfig() default = False m = Mocker() tv = m.mock(ak.NSTextView) (tv.doc_view.document.indent_mode << c.mode).count(0, None) (tv.doc_view.document.indent_size << c.size).count(0, None) (tv.doc_view.document.eol << c.eol).count(0, None) sel = fn.NSMakeRange(*c.oldsel) (tv.selectedRange() << sel).count(0, None) (tv.string() << fn.NSString.stringWithString_(c.input)).count(0, None) (tv.shouldChangeTextInRange_replacementString_(ANY, ANY) << True).count(0, None) ts = m.mock(ak.NSTextStorage) (tv.textStorage() << ts).count(0, None) c.setup(m, c, TestConfig(locals())) def do_text(sel, repl): result.text = c.input[:sel[0]] + repl + c.input[sel[0] + sel[1]:] expect(ts.replaceCharactersInRange_withString_( ANY, ANY)).call(do_text).count(0, None) def do_sel(sel): result.sel = sel expect(tv.setSelectedRange_(ANY)).call(do_sel).count(0, None) expect(tv.didChangeText()).count(0, None) if c.scroll: tv.scrollRangeToVisible_(ANY) with m: c.method(tv, None, None) if "text" in result: eq_(result.text, c.output) else: eq_(c.output, SAME) if "sel" in result: eq_(result.sel, c.newsel)
def test(mode, size, text): result = mod.calculate_indent_mode_and_size(text) eq_(result, (mode, size))
def test_recent_items_pop_empty(): ris = RecentItemStack(4) eq_(len(ris), 0) assert ris.pop() is None
def test_create_kvolist(): lst = KVOList.alloc().init() eq_(len(lst.items()), 0)
def test_context_map_pop_with_default(): map = ContextMap() DEF = "default" eq_(map.pop(1000, "default"), "default")
def test_recent_items_size_zero(): ris = RecentItemStack(0) eq_(list(ris), []) ris.push(1) eq_(list(ris), []) eq_(ris.pop(), None)
def test_kvolist_items(): lst = KVOList.alloc().init() newitems = fn.NSMutableArray.alloc().init() lst.setItems_(newitems) eq_(lst.items(), newitems)
def test(c): eq_(mod.comment_line(c.old, c.token, c.imode, c.isize, c.pad), c.new)
def test(c): range = c.range if "range" in c else (0, len(c.text)) eq_(mod.is_comment_range(c.text, range, c.token), c.result)
def test(command, completions, placeholder): bar = CommandTester(mod.set_variable) comps = (completions, (0 if completions else -1)) eq_(bar.get_completions(command), comps) eq_(bar.get_placeholder(command), placeholder)
def test_recent_items_queue_size(): ris = RecentItemStack(20) eq_(len(ris), 0) eq_(ris.max_size, 20)
def do_kvolist_delslice(lst, i, j, val): del lst[i:j] eq_(list(lst), val)
def test_get(m, target, proxy): value = target.thekey >> "<value>" with m: eq_(proxy.thekey, value)
def test_create_context_map(): map = ContextMap() eq_(len(map), 0)
def test(input, output): eq_(user_path(input), output)