def test(c): m = Mocker() tv = TextView.alloc().initWithFrame_(fn.NSMakeRect(0, 0, 100, 100)) # x, y, w, h tc = m.method(tv.textContainer)() >> (m.mock(ak.NSTextContainer) if c.setup else None) lm = m.method(tv.layoutManager)() >> (m.mock(ak.NSLayoutManager) if c.setup else None) sv = m.method(tv.enclosingScrollView)() >> (m.mock(ak.NSScrollView) if c.setup else None) height = 100 if c.setup: lm.usedRectForTextContainer_(tc) >> fn.NSMakeRect(0, 0, 100, c.content_height) sv.contentSize() >> fn.NSMakeSize(100, 100) # w, h if c.content_height + 75 > 100: height = c.content_height + 75 with m: tv.setFrameSize_(fn.NSMakeSize(100, height)) eq_(tv.frameSize(), fn.NSMakeSize(100, c.final_height))
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_wait_for_disappear_works_even_when_is_visible_raises(): mocker = Mocker() context = Context(Settings()) selenium_mock = mocker.mock() selenium_mock.is_element_present('some element') mocker.count(min=1, max=None) mocker.result(True) selenium_mock.is_visible('some element') mocker.throw(Exception("ERROR: Element some element not found")) with mocker: driver = SeleniumDriver(context, selenium=selenium_mock) driver.wait_for_element_to_disappear("some element", 1)
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_page_am_in_action_calls_the_right_browser_driver_methods(): mocker = Mocker() class SomePage(Page): url = "http://www.somepage.com" context = FakeContext(mocker) with mocker: action = PageAmInAction() action.execute(context, url="http://www.somepage.com") assert isinstance(context.current_page, SomePage) assert context.url == "http://www.somepage.com"
def test_story_runner_returns_a_result(): mocker = Mocker() settings = Settings() fixture = Fixture() runner = StoryRunner() context = Object() context.browser_driver = mocker.mock() context.browser_driver.start_test("http://localhost") context.browser_driver.stop_test() with mocker: result = runner.run_stories(settings, fixture, context=context) assert result is not None
def test_page_am_in_action_sets_page_if_page_is_supplied(): mocker = Mocker() class SomePage1(Page): url = "http://www.somepage.com" context = FakeContext(mocker) with mocker: action = PageAmInAction() action.execute(context, url="Some Page 1") assert isinstance(context.current_page, SomePage1) assert context.url == "http://www.somepage.com"
def test_parsing_stories_returns_list(): mocker = Mocker() settings = Settings() filemock = mocker.mock() filemock.list_files(directories=settings.tests_dirs, pattern=settings.file_pattern) mocker.result([]) with mocker: parser = FileParser(file_object=filemock) fixture = parser.get_stories(settings=settings) assert isinstance(fixture, Fixture)
def test_OpenPathController_windowDidLoad(): m = Mocker() opc = OpenPathController.alloc().init() tv = m.property(opc, "paths").value >> m.mock(ak.NSTextView) tc = tv.textContainer() >> m.mock(ak.NSTextContainer) tc.setContainerSize_( fn.NSMakeSize(const.LARGE_NUMBER_FOR_TEXT, const.LARGE_NUMBER_FOR_TEXT)) tc.setWidthTracksTextView_(False) tv.setHorizontallyResizable_(True) tv.setAutoresizingMask_(ak.NSViewNotSizable) tv.setFieldEditor_(True) tv.setFont_(ANY) with m: opc.windowDidLoad()
def test(c): m = Mocker() nsapp = m.replace(ak, 'NSApp', spec=False) opc = OpenPathController.alloc().init() tv = m.mock(ak.NSTextView) if c.sel == "insertNewline:": nsapp().currentEvent().modifierFlags() >> c.mod if c.mod & ak.NSCommandKeyMask or c.mod & ak.NSShiftKeyMask: tv.insertNewlineIgnoringFieldEditor_(opc) else: m.method(opc.open_)(opc) # check for shift or command (tv.insertTabIgnoringFieldEditor_(self)) # otherwise open file with m: eq_(opc.textView_doCommandBySelector_(tv, c.sel), c.res)
def test_delete_volume_udf(self): """Delete a volume that was a udf.""" mocker = Mocker() # user, with an exception when asking for the share, and # the udf deletion user = mocker.mock() expect(user.get_share('volume_id')).throw(errors.DoesNotExist) expect(user.delete_udf('volume_id')) self.dal._get_user = lambda *a: user with mocker: result = self.dal.delete_volume('user_id', 'volume_id', 'session_id') self.assertEqual(result, {})
def test(c): from editxt.document import TextDocument m = Mocker() el = ErrorLog() doc_factory = m.replace(mod, "create_error_log_document") doc = m.mock(TextDocument) if not c.created: doc_factory(ANY) >> doc doc.text_storage = el.text doc.setLastComponentOfFileName_(const.LOG_NAME) doc.setHasUndoManager_(False) else: el._document = doc with m: eq_(el.document, doc)
def test_create(): m = Mocker() sv = m.mock(ak.NSScrollView) tv = m.mock(TextView) sv.documentView() >> tv not_class = m.replace(fn, 'NSNotificationCenter') notifier = not_class.defaultCenter() >> m.mock(fn.NSNotificationCenter) notifier.addObserver_selector_name_object_(ANY, "invalidateRuleThickness", ak.NSTextDidChangeNotification, tv) with m: lnv = create_lnv(scrollview=sv) eq_(lnv.lines, []) eq_(lnv.textview, tv) eq_(lnv.paragraph_style.alignment(), ak.NSRightTextAlignment)
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_shared_exon(self): mocker = Mocker() self.model = mocker.mock() self.model.blockStarts mocker.result([100, 400, 700]) mocker.count(2, None) self.model.blockSizes mocker.result([100, 100, 100]) mocker.count(1, None) self.model.chrom mocker.result('chr1') mocker.count(2, None) self.model.start mocker.result(0) mocker.count(1, None) self.junctions1 = mocker.mock() self.junctions2 = mocker.mock() self.junc1 = [400] self.junc2 = [700] juncKey = 'chr1:200' self.junctions1[juncKey] mocker.result(self.junc1) self.junctions2[juncKey] mocker.result(self.junc2) juncKey = 'chr1:500' self.junctions1[juncKey] mocker.throw(KeyError) juncKey = 'chr1:800' self.junctions1[juncKey] mocker.throw(KeyError) mocker.replay() self.sharedExons = {} jc.scanJunctions(self.model, self.junctions1, self.junctions2, self.sharedExons) for j in self.sharedExons: self.assertEqual(self.sharedExons[j], [400]) self.assertEqual(j, 'chr1:200')
def test_get_node_no_content(self): """Get a node that has no content.""" mocker = Mocker() # node node = mocker.mock() expect(node.id).result('node_id') expect(node.path).result('path') expect(node.name).result('name') expect(node.vol_id).result('volume_id') expect(node.parent_id).result('parent_id') expect(node.status).result(model.STATUS_LIVE) expect(node.generation).result('generation') expect(node.is_public).result(False) expect(node.content_hash).result('content_hash') expect(node.kind).result('File') expect(node.when_last_modified).result('last_modified') expect(node.content).result(None) # user user = mocker.mock() self.dal._get_user = lambda *a: user expect( user.volume('volume_id').get_node('node_id', with_content=True)).result(node) with mocker: result = self.dal.get_node(user_id='user_id', node_id='node_id', volume_id='volume_id') should = dict(id='node_id', name='name', parent_id='parent_id', is_public=False, is_live=True, is_file=True, size=None, last_modified='last_modified', crc32=None, generation='generation', content_hash='content_hash', deflated_size=None, storage_key=None, volume_id='volume_id', path="path", has_content=False) self.assertEqual(result, should)
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_save_with_path_when_project_has_a_path(): m = Mocker() path = "<path>" nsdict = m.replace(fn, 'NSMutableDictionary') proj = Project.create() proj.name = "<name>" serial = proj.serialize() assert serial, "serial should not be empty: %r" % (serial, ) serial["path"] = path proj.path = path data = nsdict.alloc().init() >> m.mock(dict) data.update(serial) data.writeToFile_atomically_(path, True) m.nospec() with m: proj.save_with_path(path)
def test_delete_volume_none(self): """Delete a volume that was not there.""" mocker = Mocker() # user, with an exception when asking for the share, and # the udf deletion user = mocker.mock() expect(user.get_share('volume_id')).throw(errors.DoesNotExist) expect(user.delete_udf('volume_id')).throw(errors.DoesNotExist) self.dal._get_user = lambda *a: user with mocker: err = self.assertRaises(errors.DoesNotExist, self.dal.delete_volume, 'user_id', 'volume_id', 'session_id') self.assertEqual(str(err), "Volume 'volume_id' does not exist")
def test(c): app = Application() m = Mocker() opc_class = m.replace(mod, 'OpenPathController') opc = m.mock(mod.OpenPathController) m.property(app, "path_opener").value >> (opc if c.exists else None) if c.exists: app.path_opener.window().makeKeyAndOrderFront_(app) else: (opc_class.alloc() >> opc).initWithWindowNibName_("OpenPath") >> opc app.path_opener = opc opc.showWindow_(app) app.path_opener.populateWithClipboard() with m: app.open_path_dialog()
def test_decline_share(self): """Decline a share.""" mocker = Mocker() # share share = mocker.mock() expect(share.decline()) # user, with the chained calls to the operation user = mocker.mock() expect(user.get_share('share_id')).result(share) self.dal._get_user = lambda *a: user with mocker: result = self.dal.decline_share('user_id', 'share_id') self.assertEqual(result, {})
def test(c): m = Mocker() nspb = m.replace(ak, 'NSPasteboard') pboard = nspb.pasteboardWithName_(ak.NSFindPboard) pboard.availableTypeFromArray_([ak.NSStringPboardType ]) >> (c.ftext is not None) if c.ftext is not None: pboard.stringForType_(ak.NSStringPboardType) >> c.ftext with replace_history() as history: if c.hist is not None: history.append(c.hist) with m: fc = FindController() # calls load_options() eq_(fc.options._target, FindOptions(**c.opts)) eq_(fc.options.recent_finds, [] if c.hist is None else [c.hist])
def test_connectionMade(self): """Test connectionMade with handshake done.""" mocker = Mocker() metrics = self.server.metrics = mocker.mock() transport = self.server.transport = mocker.mock() self.server.factory = ssl_proxy.SSLProxyFactory(0, 'host', 0) called = [] self.patch(reactor, 'connectTCP', lambda *a: called.append('connectTCP')) expect(metrics.meter('frontend_connection_made', 1)) expect(transport.getPeer()).result("host:port info").count(1) expect(transport.pauseProducing()) with mocker: self.server.connectionMade() self.assertEqual(called, ['connectTCP'])
def test_selenium_driver_overrides_start_test_properly_when_extra_args_specified(): mocker = Mocker() context = Context(Settings()) context.settings.extra_args = { "selenium.server":"localhost", "selenium.port":4444 } selenium_mock = mocker.mock() selenium_mock.start() with mocker: driver = SeleniumDriver(context, selenium=selenium_mock) driver.start_test("http://localhost")
def test_laguage_getter_format_args(): mocker = Mocker() language = 'error_one_ok_args = you expected %s but got %s' filemock = mocker.mock() filemock.read() mocker.result(language) with mocker: lg = LanguageGetter('en-us', file_object=filemock) lg.fill_data() assert lg.format('error_one_ok_args', 'X', 'Y') == u'you expected X but got Y'
def test_wait_for_disappear(): mocker = Mocker() context = Context(Settings()) selenium_mock = mocker.mock() selenium_mock.is_element_present('some element') mocker.count(min=1, max=None) mocker.result(True) selenium_mock.is_visible('some element') mocker.count(min=1, max=None) mocker.result(True) with mocker: driver = SeleniumDriver(context, selenium=selenium_mock) driver.wait_for_element_to_disappear("some element", 1)
def test_url_checker_with_port(): mocker = Mocker() urlmock = mocker.mock() urlmock.urlopen("http://foo.bar.com:8080") mocker.result(None) with mocker: checker = URLChecker(lib=urlmock) checker.set_url("http://foo.bar.com:8080") assert checker.url == "http://foo.bar.com:8080" assert checker.is_valid() assert checker.exists()
def test_url_checker_with_port_with_sub_folder_in_localhost(): mocker = Mocker() urlmock = mocker.mock() urlmock.urlopen("http://localhost:8080/login") mocker.result(None) with mocker: checker = URLChecker(lib=urlmock) checker.set_url("http://localhost:8080/login") assert checker.url == "http://localhost:8080/login" assert checker.is_valid() assert checker.exists()
def test_parsing_folder_with_no_stories_returns_empty_list(): mocker = Mocker() settings = Settings() files = [] filemock = mocker.mock() filemock.list_files(directories=settings.tests_dirs, pattern=settings.file_pattern) mocker.result(files) with mocker: parser = FileParser(file_object=filemock) fixture = parser.get_stories(settings=settings) assert len(fixture.stories) == 0
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)