def test(eds_config): app = Application() m = Mocker() create_window = m.method(app.create_window) open_error_log = m.method(app.open_error_log) nsapp = m.mock(ak.NSApplication) ud_class = m.replace(fn, 'NSUserDefaults') m.method(app.iter_saved_window_states)() >> iter(eds_config) tc = m.replace(app, 'text_commander', spec=CommandManager) dc = m.mock(DocumentController) tc.load_commands(dc.textMenu >> m.mock(ak.NSMenu)) tc.load_shortcuts(dc.shortcutsMenu >> m.mock(ak.NSMenu)) if eds_config: error = False for ed_config in eds_config: if isinstance(ed_config, mod.StateLoadFailure): error = True else: create_window(ed_config) if error: open_error_log(set_current=False) else: create_window() with m: app.application_will_finish_launching(nsapp, dc) eq_(app.text_commander, tc)
def test(c): with test_app() as app: m = Mocker() fc = FindController(app) fc.options = make_options(c) beep = m.replace(mod, "beep") sheet = m.replace(ak, "NSBeginAlertSheet") gui = m.replace(fc, "gui") ftext = m.mock(ak.NSTextField) if c.search != mod.LITERAL: if c.ftext is None: gui.find_text >> None else: (gui.find_text << ftext).count(1, None) ftext.stringValue() >> c.ftext if not c.expect: beep() sheet( ANY, "OK", None, None, gui.window >> "<window>", None, None, None, 0, ANY, ); with m: result = fc.validate_expression() eq_(result, c.expect)
def test(c): with test_app() as app: m = Mocker() fc = FindController(app) flog = m.replace("editxt.command.find.log") beep = m.replace(mod, "beep") get_editor = m.method(fc.get_editor) sender = m.mock() (sender.tag() << c.tag).count(1, 2) func = None for tag, meth in list(fc.action_registry.items()): fc.action_registry[tag] = temp = m.mock(meth) if tag == c.tag: func = temp if c.fail: flog.info(ANY, c.tag) else: if c.error: err = mod.CommandError("error!") expect(func(sender)).throw(err) beep() editor = get_editor() >> (m.mock() if c.target else None) if c.target: editor.message("error!", msg_type=const.ERROR) else: flog.warn(err) else: func(sender) with m: fc.perform_action(sender)
def test_closeAllDocumentsWithDelegate_didCloseAllSelector_contextInfo_(): import editxt.util as util context = 42 dc = ak.NSDocumentController.sharedDocumentController() m = Mocker() app = m.replace(editxt, 'app') def perf_sel(delegate, selector, *args): should_term(*args) dsd_class = m.replace(mod, 'DocumentSavingDelegate', spec=False) docs = m.mock() app.iter_dirty_documents() >> docs selector = "_docController:shouldTerminate:context:" delegate = m.mock() def test_callback(callback): callback("<result>") return True should_term = delegate._docController_shouldTerminate_context_ should_term(dc, "<result>", context) saver = m.mock(DocumentSavingDelegate) dsd_class.alloc() >> saver saver.init_callback_(docs, MATCH(test_callback)) >> saver saver.save_next_document() with replattr(mod, 'perform_selector', perf_sel), m: dc.closeAllDocumentsWithDelegate_didCloseAllSelector_contextInfo_( delegate, selector, context)
def test_closeAllDocumentsWithDelegate_didCloseAllSelector_contextInfo_(): context = 42 dc = NSDocumentController.sharedDocumentController() m = Mocker() app = m.replace("editxt.app", type=Application) perf_sel = m.replace("editxt.util.perform_selector", passthrough=False) dsd_class = m.replace("editxt.application.DocumentSavingDelegate", spec=False, passthrough=False) docs = m.mock() app.iter_dirty_documents() >> docs selector = "_docController:shouldTerminate:context:" delegate = m.mock() def test_callback(callback): callback("<result>") return True should_term = delegate._docController_shouldTerminate_context_ expect(perf_sel(delegate, selector, dc, "<result>", context)).call( lambda *a:should_term(dc, "<result>", context)) should_term(dc, "<result>", context) saver = m.mock(DocumentSavingDelegate) dsd_class.alloc() >> saver saver.init_callback_(docs, MATCH(test_callback)) >> saver saver.save_next_document() with m: dc.closeAllDocumentsWithDelegate_didCloseAllSelector_contextInfo_( delegate, selector, context)
def test(serial): m = Mocker() proj = Project.create() log = m.replace("editxt.project.log", passthrough=False) nsdat = m.replace(NSData, passthrough=False) nspls = m.replace(NSPropertyListSerialization, passthrough=False) create_document_view_with_state = m.method(Project.create_document_view_with_state) create_document_view = m.method(Project.create_document_view) proj._documents = docs = m.mock(KVOList) if "path" in serial: data = nsdat.dataWithContentsOfFile_(serial["path"]) >> m.mock() serial_, format, error = nspls. \ propertyListFromData_mutabilityOption_format_errorDescription_( \ data, NSPropertyListImmutable, None, None) >> ({}, m.mock(), None) else: serial_ = serial docs_ = serial_.get("documents", []) for item in docs_: create_document_view_with_state(item) if item == "doc_not_found": m.throw(Exception("document not found")) log.warn("cannot open document: %r" % item) #proj._is_dirty = True bool(docs); m.result(bool(docs_)) if not docs_: create_document_view() #proj._is_dirty = True with m: proj.deserialize(serial) if "path" in serial: eq_(proj.path, serial["path"]) assert "name" not in serial else: eq_(proj.name, serial.get("name", const.UNTITLED_PROJECT_NAME)) eq_(proj.expanded, serial.get("expanded", True))
def test(c): proj = Project.create() m = Mocker() dsd_class = m.replace("editxt.application.DocumentSavingDelegate") app = m.replace("editxt.app", type=Application) ed = m.mock(Editor) app.find_editors_with_project(proj) >> [ed for x in xrange(c.num_eds)] if c.num_eds == 1: docs = [m.mock(TextDocumentView)] doc = docs[0].document >> m.mock(TextDocument) app.iter_editors_with_view_of_document(doc) >> \ (ed for x in xrange(c.num_doc_views)) dirty_documents = m.method(proj.dirty_documents) dirty_documents() >> docs def check_docs(_docs): d = docs if c.num_doc_views == 1 else [] eq_(list(_docs), d + [proj]) return True callback = [] def get_callback(func): callback.append(func) return True def do_callback(): callback[0](c.should_close) saver = m.mock(DocumentSavingDelegate) dsd_class.alloc() >> saver saver.init_callback_(MATCH(check_docs), MATCH(get_callback)) >> saver expect(saver.save_next_document()).call(do_callback) if c.should_close: ed.discard_and_focus_recent(proj) else: ed.discard_and_focus_recent(proj) with m: proj.perform_close(ed)
def test(c): m = Mocker() regundo = m.replace(mod, 'register_undo_callback') convert = m.replace(mod, 'change_indentation') doc = m.mock(TextDocument) with m.off_the_record(): dv = Editor(None, document=doc) tv = dv.text_view = m.mock(ak.NSTextView) if c.convert: old_indent = "\t" if c.oldm is TAB else (" " * c.olds) new_indent = "\t" if c.newm is TAB else (" " * c.news) convert(tv, old_indent, new_indent, c.news) if c.oldm != c.newm: doc.props.indent_mode = c.newm if c.olds != c.news: doc.props.indent_size = c.news if c.convert or c.convert is None: undo_change = m.mock(); undo_change(c.newm, c.news, c.oldm, c.olds, None) def _undo(undoman, undo): dv.change_indentation = undo_change undo() undoman = doc.undo_manager >> m.mock(fn.NSUndoManager) expect(regundo(undoman, ANY)).call(_undo) with m: dv.change_indentation(c.oldm, c.olds, c.newm, c.news, c.convert)
def test(c): m = Mocker() opts = "<options>" tv = m.mock(TextView) ts = tv.textStorage() >> m.mock(ak.NSTextStorage) wrap = m.replace(mod, 'wraplines') iterlines = m.replace("editxt.command.wraplines.iterlines") text = tv.string() >> fn.NSString.stringWithString_(c.text) sel = (0, len(text)) if c.sel is None else c.sel sel = text.lineRangeForRange_(tv.selectedRange() >> sel) eol = tv.doc_view.document.eol >> m.mock() lines = iterlines(text, sel) >> "<lines>" eol.join(wrap(lines, opts, tv) >> [c.result]) >> c.result tv.shouldChangeTextInRange_replacementString_(sel, c.result) >> True output = [] def callback(range, text): output.append(text) expect(ts.replaceCharactersInRange_withString_( sel, c.result)).call(callback) tv.didChangeText() tv.setSelectedRange_((sel[0], len(c.result))) with m: wrap_selected_lines(tv, opts) eq_(c.result, output[0])
def test(c): m = Mocker() sv = ThinSplitView.alloc().init() nsanim = m.replace(NSViewAnimation, passthrough=False) nsdict = m.replace(NSDictionary, passthrough=False) nsval = m.replace(NSValue, passthrough=False) nsarr = m.replace(NSArray, passthrough=False) view = m.mock(NSView) rect = m.mock(NSRect) rval = nsval.valueWithRect_(rect) >> m.mock() resize = nsdict.dictionaryWithObjectsAndKeys_( view, NSViewAnimationTargetKey, rval, NSViewAnimationEndFrameKey, None ) >> m.mock(NSDictionary) anims = nsarr.arrayWithObject_(resize) >> m.mock(NSArray) anim = nsanim.alloc() >> m.mock(NSViewAnimation) anim.initWithViewAnimations_(anims) >> anim anim.setDuration_(0.5) if c.delegate: delegate = m.mock(RedrawOnAnimationEndedDelegate) anim.setDelegate_(delegate) else: delegate = None anim.startAnimation() with m: sv._animate_view(view, rect, delegate)
def test(c): m = Mocker() fc = FindController.shared_controller() beep = m.replace(ak, 'NSBeep') dobeep = True tv = m.replace(fc.finder, 'find_target')() >> (m.mock(TextView) if c.has_tv else None) options = m.replace(fc.finder, "options") ftext = options.find_text >> c.ftext range = ( tv.selectedRange() >> fn.NSRange(*c.sel)) if c.has_tv else None if c.has_tv and c.ftext and ((c.sel_only and c.sel[1] > 0) or not c.sel_only): text = tv.string() >> c.text if not c.sel_only: if (options.wrap_around >> c.wrap): range = fn.NSMakeRange(0, 0) else: range = fn.NSMakeRange(range[0], len(text) - range[0]) if options.regular_expression >> c.regex: finditer = m.method(fc.finder.regexfinditer) elif options.match_entire_word >> c.mword: ftext = "\\b" + re.escape(ftext) + "\\b" finditer = m.method(fc.finder.regexfinditer) else: finditer = m.method(fc.finder.simplefinditer) rtext = options.replace_text >> c.rtext found = None ranges = [] rtexts = [] items = [] FoundRange = make_found_range_factory( FindOptions(regular_expression=c.regex, match_entire_word=c.mword)) for r in c.ranges: found = FoundRange(fn.NSMakeRange(*r)) if ranges: rtexts.append(text[sum(ranges[-1]):r[0]]) ranges.append(found.range) rtexts.append(rtext) items.append(found) finditer(text, ftext, range, FORWARD, False) >> items if ranges: start = c.ranges[0][0] range = fn.NSMakeRange(start, sum(c.ranges[-1]) - start) value = "".join(rtexts) if tv.shouldChangeTextInRange_replacementString_( range, value) >> c.replace: ts = tv.textStorage() >> m.mock(ak.NSTextStorage) ts.replaceCharactersInRange_withString_(range, value) tv.didChangeText() tv.setNeedsDisplay_(True) dobeep = False eq_(dobeep, c.beep) if dobeep: beep() with m: fc.finder._replace_all(c.sel_only)
def test_application_init(): from editxt.util import ContextMap from editxt.errorlog import ErrorLog m = Mocker() m.replace("editxt.valuetrans.register_value_transformers", passthrough=False)() with m: app = Application() eq_(app.editors, []) assert isinstance(app.context, ContextMap)
def test(c): with test_app() as app: m = Mocker() fc = FindController(app) beep = m.replace(mod, 'beep') dobeep = True editor = m.replace(fc.finder, 'get_editor')() >> (m.mock(Editor) if c.has_tv else None) options = m.replace(fc.finder, "options") ftext = options.find_text >> c.ftext range = (editor.selection >> c.sel) if c.has_tv else None if c.has_tv and c.ftext and ((c.sel_only and c.sel[1] > 0) or not c.sel_only): text = editor.text >> Text(c.text) if not c.sel_only: if (options.wrap_around >> c.wrap): range = (0, 0) else: range = (range[0], len(text) - range[0]) if options.regular_expression >> c.regex: finditer = m.method(fc.finder.regexfinditer) elif options.match_entire_word >> c.mword: ftext = "\\b" + re.escape(ftext) + "\\b" finditer = m.method(fc.finder.regexfinditer) else: finditer = m.method(fc.finder.simplefinditer) rtext = options.replace_text >> c.rtext found = None ranges = [] rtexts = [] items = [] FoundRange = make_found_range_factory( FindOptions(regular_expression=c.regex, match_entire_word=c.mword)) for rng in c.ranges: found = FoundRange(rng) if ranges: rtexts.append(text[sum(ranges[-1]):rng[0]]) ranges.append(found.range) rtexts.append(rtext) items.append(found) finditer(text, ftext, range, FORWARD, False) >> items if ranges: start = c.ranges[0][0] range = (start, sum(c.ranges[-1]) - start) value = "".join(rtexts) tv = editor.text_view >> m.mock(TextView) if tv.shouldChangeTextInRange_replacementString_(range, value) >> c.replace: tv.didChangeText() tv.setNeedsDisplay_(True) dobeep = False eq_(dobeep, c.beep) if dobeep: beep() with m: fc.finder._replace_all(c.sel_only) if c.ranges and c.replace: eq_(text[:], "<XEXX>")
def test(c): with test_app() as app: m = Mocker() fc = FindController(app) beep = m.replace(mod, 'beep') editor = (m.mock(Editor) if c.has_tv else None) m.replace(fc.finder, 'get_editor')() >> editor options = m.replace(fc.finder, "options") ftext = options.find_text >> c.ftext range = (editor.selection >> c.sel) if c.has_tv else None if c.has_tv and c.ftext and ((c.sel_only and c.sel[1] > 0) or not c.sel_only): text = editor.text >> Text(c.text) if not c.sel_only: if (options.wrap_around >> c.wrap): range = (0, 0) else: range = (range[0], len(text) - range[0]) if options.regular_expression >> c.regex: finditer = m.method(fc.finder.regexfinditer) elif options.match_entire_word >> c.mword: ftext = "\\b" + re.escape(ftext) + "\\b" finditer = m.method(fc.finder.regexfinditer) else: finditer = m.method(fc.finder.simplefinditer) rtext = options.replace_text >> c.rtext found = None ranges = [] rtexts = [] items = [] FoundRange = make_found_range_factory( FindOptions(regular_expression=c.regex, match_entire_word=c.mword)) for rng in c.ranges: found = FoundRange(rng) if ranges: rtexts.append(text[sum(ranges[-1]):rng[0]]) ranges.append(found.range) rtexts.append(rtext) items.append(found) finditer(text, ftext, range, FORWARD, False) >> items if ranges: start = c.ranges[0][0] range = (start, sum(c.ranges[-1]) - start) value = "".join(rtexts) def put(val, rng, select=False): text[rng] = val (editor.put(value, range) << c.replace).call(put) if c.beep: beep() with m: fc.finder._replace_all(c.sel_only) if c.ranges and c.replace: eq_(text[:], "<XEXX>")
def test(file_exists=True): m = Mocker() app = Application() view = m.mock(TextDocumentView) m.method(app.open_documents_with_paths)([app.config.path]) >> [view] default_config = m.property(app.config, "default_config") m.replace("os.path.exists")(app.config.path) >> file_exists if not file_exists: default_config.value >> "# config" view.document.text = "# config" with m: app.open_config_file()
def test(c): m = Mocker() el = ErrorLog() app = m.replace('editxt.app') log = m.replace(mod, 'log') log.error("unexpected error", exc_info=True) # open_error = app.open_error_log(set_current=False) # if c.open_fail: # expect(open_error).throw(Exception) # log.warn("cannot open error log", exc_info=True) with m: assert el.unexpected_error()
def test(c): m = Mocker() fc = FindController.shared_controller() beep = m.replace(ak, 'NSBeep') dobeep = True tv = m.replace(fc.finder, 'find_target')() >> (m.mock(TextView) if c.has_tv else None) options = m.replace(fc.finder, "options") ftext = options.find_text >> c.ftext range = (tv.selectedRange() >> fn.NSRange(*c.sel)) if c.has_tv else None if c.has_tv and c.ftext and ((c.sel_only and c.sel[1] > 0) or not c.sel_only): text = tv.string() >> c.text if not c.sel_only: if (options.wrap_around >> c.wrap): range = fn.NSMakeRange(0, 0) else: range = fn.NSMakeRange(range[0], len(text) - range[0]) if options.regular_expression >> c.regex: finditer = m.method(fc.finder.regexfinditer) elif options.match_entire_word >> c.mword: ftext = "\\b" + re.escape(ftext) + "\\b" finditer = m.method(fc.finder.regexfinditer) else: finditer = m.method(fc.finder.simplefinditer) rtext = options.replace_text >> c.rtext found = None ranges = [] rtexts = [] items = [] FoundRange = make_found_range_factory( FindOptions(regular_expression=c.regex, match_entire_word=c.mword)) for r in c.ranges: found = FoundRange(fn.NSMakeRange(*r)) if ranges: rtexts.append(text[sum(ranges[-1]):r[0]]) ranges.append(found.range) rtexts.append(rtext) items.append(found) finditer(text, ftext, range, FORWARD, False) >> items if ranges: start = c.ranges[0][0] range = fn.NSMakeRange(start, sum(c.ranges[-1]) - start) value = "".join(rtexts) if tv.shouldChangeTextInRange_replacementString_(range, value) >> c.replace: ts = tv.textStorage() >> m.mock(ak.NSTextStorage) ts.replaceCharactersInRange_withString_(range, value) tv.didChangeText() tv.setNeedsDisplay_(True) dobeep = False eq_(dobeep, c.beep) if dobeep: beep() with m: fc.finder._replace_all(c.sel_only)
def test(c): m = Mocker() sf = SyntaxFactory() log = m.replace("editxt.syntax.log", passthrough=False) glob = m.replace("glob.glob", passthrough=False) exists = m.replace("os.path.exists", passthrough=False) load = sf.load_definition = m.mock() if c.path and exists(c.path) >> c.exists: info = { "disabled": dict(name="dis", disabled=True, filepatterns=[]), # should cause info log # these should cause error log "incomplete1": {}, "incomplete2": dict(name="none"), "incomplete3": dict(filepatterns=[]), # should only register twice despite duplication "python": dict(name="python", filepatterns=["*.py", "*.py", "*.pyw"]), "sql": dict(name="sequel", filepatterns=["*.sql"]), "text": dict(name="text", filepatterns=["*.txt"]), "text2": dict(name="text", filepatterns=["*.txt", "*.text"]), "text3": dict(name="text", disabled=True, filepatterns=["*.txt", "*.text"]), } glob(os.path.join(c.path, "*" + const.SYNTAX_DEF_EXTENSION)) >> sorted(info) def do(name): data = dict(info[name]) if name.startswith("incomplete"): raise Exception("incomplete definition: %r" % (data,)) data.setdefault("disabled", False) if "filepatterns" in data: data["filepatterns"] = set(data["filepatterns"]) return type("sdef", (object,), data)() expect(load(ANY)).count(len(info)).call(do) for fname, data in sorted(info.iteritems()): if fname.startswith("incomplete"): log.error(ANY, fname, exc_info=True) else: pats = ", ".join(sorted(set(data.get("filepatterns", [])))) stat = [data["name"], "[%s]" % pats] if fname in ("text", "text2", "text4"): stat.extend(["overrides", "*.txt"]) elif fname in ("disabled", "text3"): stat.append("DISABLED") stat.append(fname) log.info(ANY, " ".join(stat)) patterns = set(["*.py", "*.pyw", "*.sql", "*.text", "*.txt"]) else: patterns = set(["*.txt"]) with m: sf.load_definitions(c.path) eq_(set(sf.registry), patterns)
def test(c): m = Mocker() sf = SyntaxFactory() log = m.replace("editxt.syntax.log") glob = m.replace("glob.glob") exists = m.replace("os.path.exists") load = sf.load_definition = m.mock() if c.path and exists(c.path) >> c.exists: info = { "disabled": dict(name="dis", disabled=True, filepatterns=[]), # should cause info log # these should cause error log "incomplete1": {}, "incomplete2": dict(name="none"), "incomplete3": dict(filepatterns=[]), # should only register twice despite duplication "python": dict(name="python", filepatterns=["*.py", "*.py", "*.pyw"]), "sql": dict(name="sequel", filepatterns=["*.sql"]), "text": dict(name="text", filepatterns=["*.txt"]), "text2": dict(name="text", filepatterns=["*.txt", "*.text"]), "text3": dict(name="text", disabled=True, filepatterns=["*.txt", "*.text"]), } glob(os.path.join(c.path, "*" + const.SYNTAX_DEF_EXTENSION)) >> sorted(info) def do(name): data = dict(info[name]) if name.startswith("incomplete"): raise Exception("incomplete definition: %r" % (data,)) data.setdefault("disabled", False) if "filepatterns" in data: data["filepatterns"] = set(data["filepatterns"]) return type("sdef", (object,), data)() expect(load(ANY)).count(len(info)).call(do) for fname, data in sorted(info.items()): if fname.startswith("incomplete"): log.error(ANY, fname, exc_info=True) else: pats = ", ".join(sorted(set(data.get("filepatterns", [])))) stat = [data["name"], "[%s]" % pats] if fname in ("text", "text2", "text4"): stat.extend(["overrides", "*.txt"]) elif fname in ("disabled", "text3"): stat.append("DISABLED") stat.append(fname) log.info(ANY, " ".join(stat)) patterns = set(["*.py", "*.pyw", "*.sql", "*.text", "*.txt"]) else: patterns = set(["*.txt"]) with m: sf.load_definitions(c.path) eq_(set(sf.registry), patterns)
def test_get_connection_without_sandbox(self): # Mock connections['dataview'] to raise ConnectionDoesNotExist from django.db.utils import ConnectionDoesNotExist mocker = Mocker() connections = mocker.replace("django.db.connections") expect(connections['dataview']).throw(ConnectionDoesNotExist) connection = mocker.replace("django.db.connection") logging = mocker.replace("logging") logging.warning("dataview-specific database connection not available, dataview query is NOT sandboxed") with mocker: observed = DataView.get_connection() expected = connection self.assertIs(observed, expected)
def test_init_syntax_definitions(): import editxt.syntax as syntax m = Mocker() app = Application(profile='/editxtdev') rsrc_path = m.method(app.resource_path)() >> "/tmp/resources" SyntaxFactory = m.replace(syntax, 'SyntaxFactory', spec=False) sf = SyntaxFactory() >> m.mock(syntax.SyntaxFactory) app_log = m.replace("editxt.application.log") for path, info in [(rsrc_path, False), ('/editxtdev', True)]: sf.load_definitions(os.path.join(path, const.SYNTAX_DEFS_DIR), info) sf.index_definitions() with m: app.init_syntax_definitions()
def test(c): m = Mocker() hbc = HoverButtonCell.alloc().init() frame = m.mock(NSRect) view = m.mock(NSOutlineView) point, pressed = hbc.hover_info = c.info if point is not None: m.replace(NSPointInRect)(point, frame) >> (point == "in") row = view.rowAtPoint_(frame.origin >> (1, 1)) >> 2 dgt = m.property(hbc, "delegate").value >> m.mock(EditorWindowController) image = dgt.hoverButtonCell_imageForState_row_(hbc, c.state, row) >> "<img>" with m: eq_(hbc.buttonImageForFrame_inView_(frame, view), image)
def test_init_syntax_definitions(): import editxt.syntax as syntax m = Mocker() app = Application(profile='/editxtdev') rsrc_path = m.method(app.resource_path)() >> "/tmp/resources" SyntaxFactory = m.replace(syntax, 'SyntaxFactory', spec=False) sf = SyntaxFactory() >> m.mock(syntax.SyntaxFactory) app_log = m.replace("editxt.application.log") for path, info in [(rsrc_path, False), ('/editxtdev', True)]: sf.load_definitions(join(path, const.SYNTAX_DEFS_DIR), info) sf.index_definitions() with m: app.init_syntax_definitions()
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(c): m = Mocker() app = Application() doc = m.mock(TextDocument) m.method(app.open_documents_with_paths)([app.config.path]) >> [doc] (doc.file_path << app.config.path).count(1, None) default_config = m.property(app.config, "default_config") m.replace("os.path.exists")(app.config.path) >> c.exists if not c.exists: doc.document.text >> c.text if not c.text: doc.document.text = default_config.value >> "# config" with m: app.open_config_file()
def test_get_connection_without_sandbox(self): # Mock connections['dataview'] to raise ConnectionDoesNotExist from django.db.utils import ConnectionDoesNotExist mocker = Mocker() connections = mocker.replace("django.db.connections") expect(connections['dataview']).throw(ConnectionDoesNotExist) connection = mocker.replace("django.db.connection") logging = mocker.replace("logging") logging.warning( "dataview-specific database connection not available, dataview query is NOT sandboxed" ) with mocker: observed = DataView.get_connection() expected = connection self.assertIs(observed, expected)
def test(c): m = Mocker() editor = m.mock(Editor) ctl_class = m.replace("editxt.command.{}.{}".format(c.mod, c.ctl.__name__)) if c.func is not None: func = m.replace("editxt.command.{}.{}".format(c.mod, c.func.__name__)) if c.args: args = '<args>' func(editor, args) else: args = None ctl = ctl_class(editor) >> m.mock(c.ctl) ctl.begin_sheet(None) with m: c.action(editor, args)
def test(c): m = Mocker() hbc = HoverButtonCell.alloc().init() frame = m.mock(fn.NSRect) view = m.mock(ak.NSOutlineView) point, pressed = hbc.hover_info = c.info if point is not None: m.replace(fn, 'NSPointInRect')(point, frame) >> (point == "in") row = view.rowAtPoint_(frame.origin >> (1, 1)) >> 2 dgt = m.property(hbc, "delegate").value >> m.mock(EditorWindowController) image = dgt.hoverButtonCell_imageForState_row_(hbc, c.state, row) >> "<img>" with m: eq_(hbc.buttonImageForFrame_inView_(frame, view), image)
def test(c): m = Mocker() regundo = m.replace(mod, 'register_undo_callback') repnl = m.replace(mod, 'replace_newlines') doc = m.mock(TextDocument) with m.off_the_record(): dv = Editor(None, document=doc) proxy = m.property(dv, 'proxy') with m.order(): (getattr(doc, c.attr) << c.default).count(2 if c.value != c.default else 3) if c.value != c.default: c.do(TestConfig(**locals())) getattr(doc, c.attr) >> c.value with m: property_value_util(c, dv)
def test(c): m = Mocker() tv = m.mock(ak.NSTextView) ctl_class = m.replace("editxt.command.{}.{}".format(c.mod, c.ctl.__name__)) if c.func is not None: func = m.replace("editxt.command.{}.{}".format(c.mod, c.func.__name__)) if c.args: args = '<args>' func(tv, args) else: args = None ctl = ctl_class(tv) >> m.mock(c.ctl) ctl.begin_sheet('<sender>') with m: c.action(tv, '<sender>', args)
def test(c): m = Mocker() editor = m.mock() beep = m.replace(ak, 'NSBeep') commander = m.mock(TextCommandController) bar = mod.CommandBar(editor, commander) message = m.replace(bar, "message") args = c.text.split() if args and not c.current: editor.current_view >> None beep() elif args: view = editor.current_view >> m.mock(TextDocumentView) command = m.mock() if c.lookup == 'first': commander.lookup(args[0]) >> command if isinstance(c.args, Exception): expect(command.arg_parser.parse(c.argstr)).throw(c.args) else: command.arg_parser.parse(c.argstr) >> c.args elif c.lookup == 'full': commander.lookup(args[0]) >> None if c.args is None: commander.lookup_full_command(c.text) >> (None, None) else: commander.lookup_full_command(c.text) >> (command, c.args) else: assert c.lookup == None, c.lookup if c.args is None or isinstance(c.args, Exception): if isinstance(c.args, Exception): kw = {"exc_info": True} else: kw = {} message(c.msg, **kw) else: view.text_view >> '<view>' res = command('<view>', bar, '<args>') if c.error: expect(res).throw(Exception('bang!')) message(ANY, exc_info=True) elif not c.text.startswith(" "): res >> c.msg history = commander.history >> m.mock(mod.CommandHistory) history.append(c.text) if c.msg: message(c.msg, msg_type=const.INFO) with m: bar.execute(c.text)
def test_SyntaxFactory_index_definitions(): from editxt.valuetrans import SyntaxDefTransformer class FakeDef(object): def __init__(self, name): self.name = name def __repr__(self): return "<%s %x>" % (self.name, id(self)) text1 = FakeDef("Plain Text") text2 = FakeDef("Plain Text") python = FakeDef("Python") sf = SyntaxFactory() sf.registry = { "*.txt": text1, "*.text": text2, "*.txtx": text1, "*.py": python, } defs = sorted([text1, text2, python], key=lambda d:(d.name, id(d))) m = Mocker() vt = m.replace(mod, 'NSValueTransformer') st = vt.valueTransformerForName_("SyntaxDefTransformer") >> \ m.mock(SyntaxDefTransformer) st.update_definitions(defs) with m: sf.index_definitions() eq_(sf.definitions, defs)
def test_without_when(self): mocker = Mocker() mock_time = mocker.replace('time.time') mock_time() mocker.result(1.0) mock_time() mocker.result(2.0) mock_time() mocker.result(3.0) mock_time() mocker.result(4.0) mock_time() mocker.result(5.0) mocker.replay() controller = pid.PID(P = 0.5, I = 0.5, D = 0.5, setpoint = 0, initial = 12) self.assertEqual(controller.calculate_response(6), -3) self.assertEqual(controller.calculate_response(3), -4.5) self.assertEqual(controller.calculate_response(-1.5), -0.75) self.assertEqual(controller.calculate_response(-2.25), -1.125) mocker.restore() mocker.verify()
def test(c): text = "the text is made of many texts" m = Mocker() tv = m.mock(TextView) tv._Finder__last_mark >> (None, 0) tv._Finder__last_mark = (c.options.find_text, c.count) ts = tv.textStorage() >> m.mock(ak.NSTextStorage) app = m.replace(editxt, "app") app.config["highlight_selected_text.color"] >> "<color>" full_range = fn.NSMakeRange(0, ts.length() >> len(text)) layout = tv.layoutManager() layout.removeTemporaryAttribute_forCharacterRange_( ak.NSBackgroundColorAttributeName, full_range) find_target = lambda: tv finder = Finder(find_target, c.options) if c.options.find_text: text = fn.NSString.alloc().initWithString_(text) (tv.string() << text).count(1, None) mark_range = layout.addTemporaryAttribute_value_forCharacterRange_ >> m.mock( ) mark = mark_range(ak.NSBackgroundColorAttributeName, ANY, ANY) expect(mark).count(c.count) with m: count = finder.mark_occurrences(c.options.find_text, c.allow_regex) eq_(count, c.count)
def test(action, app_method): dc = DocumentController.sharedDocumentController() m = Mocker() app = m.replace(editxt, 'app') getattr(app, app_method)() with m: getattr(dc, action)(None)
def test(c): m = Mocker() lg = m.replace("editxt.textcommand.log") mi = m.mock(ak.NSMenuItem) tv = m.mock(ak.NSTextView) tc = m.mock() tcc = CommandManager("<history>") cmds = m.replace(tcc, "commands") cmds.get(mi.tag() >> 42) >> (tc if c.has_command else None) if c.has_command: tc(tv, None) if c.error: m.throw(Exception) lg.exception("%s.execute failed", ANY) with m: tcc.do_menu_command(tv, mi)
def test_call_no_unicode_and_no_error_desc(self): reg = getUtility(IRegistry).forInterface(ICollectiveFlattr) reg.access_token = u'' mocker = Mocker() func = mocker.replace('collective.flattr.browser.flattr.Flattr.getAccessToken') func(u'un8Vzv7pNMXNuAQY3uRgjYfM4V3Feirz') mocker.result({'access_token': u'NEW_ACCESS_TOKEN', 'token_type': u'bearer', 'error': u'blubber'}) with as_manager(self.portal) as view: from collective.flattr.browser.flattr import Flattr with mocker: self.layer['request']['code'] = 'un8Vzv7pNMXNuAQY3uRgjYfM4V3Feirz' view = Flattr(self.portal, self.layer['request']) ret = view() self.assertEquals(reg.access_token, u'') self.assertEquals(self.layer['request'].response\ .headers['location'], 'http://nohost/plone') ret = IStatusMessage(self.layer['request'])\ .showStatusMessages() self.assertEquals(ret[0].message, u'undefined: Undefined error while getting access token') self.assertEquals(ret[0].type, u'error')
def test_result_is_cached(self): view = self.get_view() self.assertNotIn('purple', view.generate_css(), 'Unexpectedly found "purple" in the CSS') # Setting a custom style automatically invalidates the cache. # For testing that things are cached, we stub the cache invalidation, # so that the cache persists. mocker = Mocker() invalidate_cache_mock = mocker.replace(invalidate_cache) expect(invalidate_cache_mock()).count(1, None) mocker.replay() ICustomStyles(self.layer['portal']).set('css.body-background', 'purple') self.assertNotIn('purple', view.generate_css(), 'The result was not cached.') # Removing the stub and invalidating the cache should update the result. mocker.restore() mocker.verify() invalidate_cache() self.assertIn( 'purple', view.generate_css(), 'Expected "purple" in CSS - does the style' ' css.body-background no longer work?')
def test_call_valid(self): reg = getUtility(IRegistry).forInterface(ICollectiveFlattr) reg.access_token = u'' mocker = Mocker() func = mocker.replace('collective.flattr.browser.flattr.Flattr.getAccessToken') func(u'un8Vzv7pNMXNuAQY3uRgjYfM4V3Feirz') mocker.result({'access_token': u'NEW_ACCESS_TOKEN', 'token_type': u'bearer'}) with as_manager(self.portal) as view: ## need the real class here, not the wrapped one, to get mocker ## working from collective.flattr.browser.flattr import Flattr with mocker: self.layer['request']['code'] = u'un8Vzv7pNMXNuAQY3uRgjYfM4V3Feirz' view = Flattr(self.portal, self.layer['request']) ret = view() self.assertEquals(reg.access_token, u'NEW_ACCESS_TOKEN') self.assertEquals(self.layer['request'].response\ .headers['location'], 'http://nohost/plone') ret = IStatusMessage(self.layer['request'])\ .showStatusMessages()[0] self.assertEquals(ret.message, u'collective.flattr successfully configured') self.assertEquals(ret.type, u'info')
def test(c): m = Mocker() beep = m.replace(mod, "beep") @command( arg_parser=CommandParser( Choice(("selection", True), ("all", False)), Choice(("no", False), ("yes", True)), Regex("sort_regex", True), ) ) def cmd(editor, args): raise NotImplementedError("should not get here") @command( arg_parser=CommandParser(Regex("search_pattern", replace=c.replace), Choice(("yep", False), ("yes", True))), lookup_with_arg_parser=True, ) def search(editor, args): raise NotImplementedError("should not get here") @command(arg_parser=CommandParser(IllBehaved("bang"))) def ill(editor, args): raise NotImplementedError("should not get here") bar = CommandTester(cmd, search, ill) with m: eq_(bar.get_placeholder(c.text), c.expect)
def test_wrap_to_margin_guide(): m = Mocker() tv = m.mock(ak.NSTextView) wrap = m.replace(mod, 'wrap_selected_lines') wrap(tv, mod.Options(wrap_column=const.DEFAULT_RIGHT_MARGIN, indent=True)) with m: mod.wrap_at_margin(tv, None, None)
def test(c): m = Mocker() window = m.mock() commander = m.mock(CommandManager) sys_exc_info = m.replace(mod.sys, "exc_info") format_exc = m.replace(mod.traceback, "format_exception") bar = mod.CommandBar(window, commander) editor = window.current_editor >> m.mock(Editor) kw = {} if c.exc_info is not None: kw["exc_info"] = c.exc_info exc_info = sys_exc_info() >> ("<type>", "<exc>", "<tb>") format_exc(*exc_info) >> ["Traceback", "...", "Error!"] editor.message(c.msg, msg_type=const.ERROR) with m: bar.message(c.text, **kw)
def setUpZope(self, app, configurationContext): # Mock postmonkey mocker = Mocker() postmonkey = mocker.replace("postmonkey") mailchimp = postmonkey.PostMonkey(ANY) mocker.count(0, 1000) # Lists mailchimp.lists() mocker.count(0, 1000) mocker.result({ u'total': 2, u'data': [ { u'id': 625, u'web_id': 625, u'name': u'ACME Newsletter', u'default_from_name': u'*****@*****.**', }, { u'id': 626, u'web_id': 626, u'name': u'ACME Newsletter 2', u'default_from_name': u'*****@*****.**', }, ] }) mocker.replay() # Load ZCML import example.tdd xmlconfig.file('configure.zcml', example.tdd, context=configurationContext)
def test(c): m = Mocker() lg = m.replace("editxt.textcommand.log") mi = m.mock(ak.NSMenuItem) tv = m.mock(ak.NSTextView) tc = m.mock() tcc = TextCommandController("<history>") cmds = m.replace(tcc, 'commands') cmds.get(mi.tag() >> 42) >> (tc if c.has_command else None) if c.has_command: tc(tv, mi, None) if c.error: m.throw(Exception) lg.error("%s.execute failed", ANY, exc_info=True) with m: tcc.do_textview_command(tv, mi)
def test(c): m = Mocker() editor = m.mock() commander = m.mock(TextCommandController) sys_exc_info = m.replace(mod.sys, "exc_info") format_exc = m.replace(mod.traceback, "format_exception") bar = mod.CommandBar(editor, commander) view = editor.current_view >> m.mock(TextDocumentView) kw = {} if c.exc_info is not None: kw["exc_info"] = c.exc_info exc_info = sys_exc_info() >> ("<type>", "<exc>", "<tb>") format_exc(*exc_info) >> ["Traceback", "...", "Error!"] view.message(c.msg, msg_type=const.ERROR) with m: bar.message(c.text, **kw)
def test(c): m = Mocker() lg = m.replace("editxt.textcommand.log") tv = m.mock(ak.NSTextView) tcc = TextCommandController("<history>") sel = "<selector>" callback = m.mock() handlers = m.replace(tcc, 'input_handlers') cmd = handlers.get(sel) >> (callback if c.has_selector else None) if c.has_selector: callback(tv, None, None) if c.error: m.throw(Exception) lg.error("%s failed", callback, exc_info=True) with m: result = tcc.do_textview_command_by_selector(tv, sel) eq_(result, c.result)
def do_test(doctype, doc_window_is_front=True): m = Mocker() app = m.replace(editxt, 'app') docs = [] dc = m.mock(DocumentController) note_ctr = m.replace(fn, 'NSNotificationCenter') controller = m.mock() callback = m.mock() context = 0 saver = DocumentSavingDelegate.alloc().init_callback_( iter(docs), callback) def do_stop_routine(): callback(saver.should_close) if doctype is None: do_stop_routine() else: doc = m.mock(doctype) docs.append(doc) if doctype is Project: doc.save() do_stop_routine() elif doctype is TextDocumentView: app.set_current_document_view(doc) win = m.mock() doc.window() >> win note_ctr.defaultCenter().addObserver_selector_name_object_( saver, "windowDidEndSheet:", ak.NSWindowDidEndSheetNotification, win) document = doc.document >> m.mock(TextDocument) wcs = m.mock(list) (document.windowControllers() << wcs).count(1, 2) wcs[0].window() >> (win if doc_window_is_front else m.mock()) if not doc_window_is_front: wcs.sort(key=ANY) document.canCloseDocumentWithDelegate_shouldCloseSelector_contextInfo_( saver, "document:shouldClose:contextInfo:", context) with m: saver.save_next_document() if doctype is TextDocumentView: assert not saver.document_called_back assert not saver.sheet_did_end else: eq_(saver.documents, None) assert id(saver) not in saver.registry
def test(c): m = Mocker() tv = m.mock(ak.NSTextView) ctl_class = m.replace("editxt.command.{}.{}".format( c.mod, c.ctl.__name__)) if c.func is not None: func = m.replace("editxt.command.{}.{}".format( c.mod, c.func.__name__)) if c.args: args = '<args>' func(tv, args) else: args = None ctl = ctl_class(tv) >> m.mock(c.ctl) ctl.begin_sheet('<sender>') with m: c.action(tv, '<sender>', args)
def test_applicationWillFinishLaunching_(): dc = DocumentController.sharedDocumentController() m = Mocker() app = m.replace(editxt, 'app') nsapp = m.mock(ak.NSApplication) app.application_will_finish_launching(nsapp, dc) with m: dc.applicationWillFinishLaunching_(nsapp)
def test(c): m = Mocker() fc = m.replace(mod, "FindController") tv = TextView.alloc().init() item = m.mock(ak.NSMenuItem) expectation = (item.action() << c.action) if c.action == "performFindPanelAction:": tag = item.tag() >> 42 (fc.shared_controller() >> m.mock(FindController)). \ validate_action(tag) >> True elif c.action == "performTextCommand:": expectation.count(2) tc = m.replace(mod, "app").text_commander >> m.mock(TextCommandController) tc.is_textview_command_enabled(tv, item) >> True else: raise NotImplementedError # left untested because I don't know how to mock a super call with m: assert tv.validateUserInterfaceItem_(item)
def test_applicationWillTerminate(): dc = ak.NSDocumentController.sharedDocumentController() m = Mocker() app = m.replace(editxt, 'app') notif = m.mock() # ak.NSApplicationWillTerminateNotification nsapp = m.mock(ak.NSApplication) app.app_will_terminate(notif.object() >> nsapp) with m: dc.applicationWillTerminate_(notif)
def test_TextView_performTextCommand_(): from editxt.textcommand import TextCommandController m = Mocker() tv = TextView.alloc().init() tc = m.replace(mod, "app").text_commander >> m.mock(TextCommandController) sender = m.mock() tc.do_textview_command(tv, sender) with m: tv.performTextCommand_(sender)
def test_TextView_doCommandBySelector_(): from editxt.textcommand import TextCommandController m = Mocker() tv = TextView.alloc().init() tc = m.replace(mod, "app").text_commander >> m.mock(TextCommandController) selector = m.mock() tc.do_textview_command_by_selector(tv, selector) >> True # omit super call with m: tv.doCommandBySelector_(selector)
def test(args): ac = Application() m = Mocker() ed_class = m.replace(editor, 'Editor') wc_class = m.replace(editor, 'EditorWindowController') wc = wc_class.alloc() >> m.mock(editor.EditorWindowController) wc.initWithWindowNibName_("EditorWindow") >> wc ed = ed_class(ac, wc, args[0] if args else None) >> m.mock( editor.Editor) wc.editor = ed #ed = wc.controller >> m.mock(Editor) #wc_class.create_with_serial_data(args[0] if args else None) >> wc with m.order(): ac.editors.append(ed) wc.showWindow_(ac) with m: result = ac.create_editor(*args) eq_(result, ed)
def test_TextView_performFindPanelAction_(): from editxt.command.find import FindController m = Mocker() tv = TextView.alloc().init() fc = m.replace(mod, "FindController") sender = m.mock() (fc.shared_controller() >> m.mock(FindController)).perform_action(sender) with m: tv.performFindPanelAction_(sender)