def testRunTestsLaunchesTestForEachBrowser(self): browser_launchers = [pmock.Mock(), pmock.Mock()] self.test_webserver.expects(pmock.once()).startServing() expected_results = {} launcher_id = 0 for browser_launcher in browser_launchers: browser_launcher.stubs().type() \ .will(pmock.return_value(str(launcher_id))) expected_results[browser_launcher.type()] = "TIMED-OUT" launcher_id += 1 for browser_launcher in browser_launchers: self.test_webserver.expects(pmock.once()) \ .startTest(pmock.eq(TestRunner.TIMEOUT)) \ .will(pmock.return_value(expected_results[browser_launcher.type()])) browser_launcher.expects(pmock.once()) \ .launch(pmock.eq(TestRunner.TEST_URL)) self.test_webserver.expects(pmock.once()).testResults() \ .will(pmock.return_value(expected_results[browser_launcher.type()])) browser_launcher.expects(pmock.once()).killAllInstances() self.test_webserver.expects(pmock.once()).shutdown() aggregated_results = TestRunner(browser_launchers, self.test_webserver).runTests() self.assertEqual(expected_results, aggregated_results) for browser_launcher in browser_launchers: browser_launcher.verify()
def __mockHeaders(self, pmock): headers_mock = pmock.Mock() headers_mock.stubs().getheader(pmock.eq("content-type")).will( pmock.return_value("application/x-www-form-urlencoded") ) headers_mock.stubs().getheader(pmock.eq("content-length")).will(pmock.return_value(312)) self.request_handler.headers = headers_mock
def test_method(self): self.special = self.mock() self.special.expects(pmock.once()).__cmp__(pmock.eq("guppy")).\ will(pmock.return_value(0)) self.special.expects(pmock.once()).__call__(pmock.eq("blub"), pmock.eq("blub")) self.special == "guppy" self.special("blub", "blub")
def test_method_name_as_id_binds_to_last_matching_expectation(self): self.mock.expects(pmock.once()).method("cow").taking(pmock.eq("moo")) self.mock.expects(pmock.once()).method("cow").taking(pmock.eq("mooo")) self.mock.expects(pmock.once()).method("bull").after("cow") self.mock.proxy().cow("mooo") self.mock.proxy().bull() self.mock.proxy().cow("moo") self.mock.verify()
def testGetExistingValue(self): """Test getting an existing value.""" mock_namespace = SubscriptableMock() mock_namespace.expects(pmock.at_least_once()).acquire_read_lock() mock_namespace.expects(pmock.at_least_once()).release_read_lock() mock_namespace.expects(pmock.once()).has_key( pmock.eq(self.test_key)).will(pmock.return_value(True)) mock_namespace.expects(pmock.once()).mock__getitem__( pmock.eq(self.test_key)).will(pmock.return_value( (time.time() - 60*5, time.time() + 60*5, 42))) def mock_create_func(): self.fail('Attempted to create a new value.') value = out_of_band_cache.Value(self.test_key, mock_namespace, createfunc=mock_create_func).get_value() mock_namespace.verify()
def testAddsAndRemovesDirectoriesFromClasspath(self): "JavaTestLauncher - when launching a file it adds the directory to the classpath and removes it after" mock = pmock.Mock() mock.expects(pmock.once()).get(pmock.eq("java_command")).will( pmock.return_value("myJava")) mock.expects(pmock.once()).get(pmock.eq("output_folder")).will( pmock.return_value("myOutput")) mock.expects(pmock.once()).addDirectory(pmock.eq(".")).id("add") mock.expects(pmock.once()).getClasspath().will( pmock.return_value("myclasspath;.")).after("add").id("getPath") mock.expects(pmock.once()).run(pmock.eq("myJava -Dconcordion.output.dir=myOutput -cp myclasspath;. junit.textui.TestRunner polop.MyClass"), pmock.eq(True)) \ .will(pmock.return_value(0)).id("exec").after("getPath") mock.expects(pmock.once()).removeDirectory(pmock.eq(".")).after("exec") JavaTestLauncher(mock, mock, mock, ".").launch("polop/MyClass.class")
def testRunTestsWebserverLanchedBeforeBrowserInvoked(self): self.test_webserver.expects(pmock.once()).startServing() self.test_webserver.expects(pmock.once()) \ .startTest(pmock.eq(TestRunner.TIMEOUT)) self.browser_launcher.expects(pmock.once()) \ .launch(pmock.eq(TestRunner.TEST_URL)) \ .after("startTest", self.test_webserver) self.test_webserver.expects(pmock.once()) \ .testResults() \ .after("launch", self.browser_launcher) self.test_webserver.expects(pmock.once()).shutdown() TestRunner([self.browser_launcher], self.test_webserver).runTests()
def setUp(self): self.mock = pmock.Mock() self.toys = ["ball", "stick"] self.mock.expects(pmock.once()).method("dog").taking( pmock.eq("bone"), pmock.same(self.toys), pmock.string_contains("slipper"))
def __connectionStub(self): connection = pmock.Mock() connection.stubs().fileno() connection.stubs().setblocking(pmock.eq(0)) connection.stubs().getpeername() connection.stubs().close() return connection
def testDoPostCallsServerNotifyOnDoPost(self): post_data = "DATA CONTENT" full_request_path = "/tester/gui.html?foobar=goofy" request_path = "/tester/gui.html" self.request_handler.path = full_request_path self.server_mock.expects(pmock.once()).notifyOnDoPost(pmock.eq(post_data), pmock.eq(request_path)) self.__mockHeaders(pmock) self.request_handler.rfile = self.__mockRfile(post_data, pmock) try: self.request_handler.do_POST() # We are letting some errors happen, although mocking as # much as possible there is not way we can use composition to # get async and http server init code out. except TypeError, e: pass
def test_urlfield_success_no_verify(self): checker_mock = pmock.Mock() blog_url = "http://foo.bar.com/blog" class Person(Model): blog = fields.URLField(verify_exists=False, url_checker=checker_mock) person_dict = {'Person': {'blog': blog_url}} checker_mock.expects(pmock.once()) \ .set_url(pmock.eq(blog_url)) checker_mock.expects(pmock.once()) \ .is_valid() \ .will(pmock.return_value(True)) checker_mock.expects(pmock.never()) \ .does_exists() john = Person.from_dict(person_dict) assert_equals(john.blog, blog_url) assert_equals(john.to_dict(), person_dict) checker_mock.verify()
def testCanCompile(self): "JavaFileCompiler - can compile files" executor = pmock.Mock() config = pmock.Mock() classpath = pmock.Mock() config.expects(pmock.once()).get(pmock.eq("javac_command")).will( pmock.return_value("myJavac")) classpath.expects(pmock.once()).getClasspath().will( pmock.return_value("myclasspath")) executor.expects(pmock.once()).run( pmock.eq( "myJavac -cp myclasspath polop/MyClass.java a/pif.java")).will( pmock.return_value(0)) result = JavaFileCompiler(config, classpath, executor).compile( ["polop/MyClass.java", "a/pif.java"]) self.assertEquals(["polop/MyClass.class", "a/pif.class"], result)
def test_cant_take_one_configuration(self): "Hierarchical Configuration - Can take one child configuration" fake_config = pmock.Mock() fake_config.expects(pmock.once()).get(pmock.eq("output_folder")).will( pmock.return_value("polop")) configuration = HierarchicalConfiguration([fake_config]) self.assertEquals("polop", configuration.get("output_folder"))
def sendEvent(self, packet): endpoint = self.mock() endpoint.address = 2 self.one_run_completed = False self.picolcd_interface.endpoints = [endpoint] def should_i_stop(): if self.one_run_completed: return True else: self.one_run_completed = True return False self.picolcd_handle.expects(pmock.once()).interruptRead(pmock.eq(2), pmock.eq(24), pmock.eq(4000)).will( pmock.return_value(packet) ) return self.hw.get_event(should_i_stop)
def test_cant_take_two_configuration_first_is_default(self): "Hierarchical Configuration - Can take two childs configuration, first child value is returned if exist" fake_config = pmock.Mock() fake_config.expects(pmock.once()).get(pmock.eq("output_folder")).will( pmock.return_value("polop")) other_config = pmock.Mock() configuration = HierarchicalConfiguration([fake_config, other_config]) self.assertEquals("polop", configuration.get("output_folder"))
def testCanLaunchAndReturnFailure(self): "JavaTestLauncher - can launch a file and return a non zero code in case of failure" executor = pmock.Mock() config = pmock.Mock() classpath = pmock.Mock() config.expects(pmock.once()).get(pmock.eq("java_command")).will( pmock.return_value("")) config.expects(pmock.once()).get(pmock.eq("output_folder")).will( pmock.return_value("")) classpath.expects(pmock.once()).getClasspath().will( pmock.return_value("")) classpath.expects(pmock.once()).addDirectory(pmock.eq("")) classpath.expects(pmock.once()).removeDirectory(pmock.eq("")) executor.expects(pmock.once()).method("run").will( pmock.return_value(1)) result = JavaTestLauncher(config, classpath, executor, "").launch("") self.assertEquals(1, result)
def test_download_release(self): crawler_release = CrawlerRelease(self.comic, dt.date(2008, 3, 1)) self.downloader_mock.expects( pmock.once()).download(pmock.eq(crawler_release)) self.aggregator._get_downloader = lambda: self.downloader_mock self.aggregator._download_release(crawler_release) self.downloader_mock.verify()
def test_method_fifo_order(self): self.mock = pmock.Mock() self.mock.expects(pmock.once()).method("cat").taking(pmock.eq("mouse")) self.mock.expects(pmock.once()).method("cat") self.mock.proxy().cat(food="mouse") try: self.mock.proxy().cat() self.fail() except pmock.MatchError: pass
def testCanLaunchAndStopAServer(self): "XmlRpcServer - can be launched and stopped" config = pmock.Mock() config.expects(pmock.once()).get(pmock.eq("server_port")).will(pmock.return_value("8000")) server = XmlRpcServer(config, [__file__]) self.assertNotAvailable() server.launch() self.assertAvailable() server.stop() self.assertNotAvailable()
def test_add_direct_method_and_arg_matcher(self): self.assert_(self.builder.chicken(pmock.eq("egg")) is not None) self.assert_(isinstance(self.mocker.added_matchers[0], pmock.MethodMatcher)) self.assert_(self.mocker.added_matchers[0].matches( pmock.Invocation("chicken", (), {}))) self.assert_(self.mocker.added_matchers[1].matches( pmock.Invocation("chicken", ("egg",), {}))) self.assertEqual(self.builder_namespace.lookup_id("chicken"), self.builder)
def testCanLaunchAndStopAServer(self): "XmlRpcServer - can be launched and stopped" config = pmock.Mock() config.expects(pmock.once()).get(pmock.eq("server_port")).will( pmock.return_value("8000")) server = XmlRpcServer(config, [__file__]) self.assertNotAvailable() server.launch() self.assertAvailable() server.stop() self.assertNotAvailable()
def test_crawl_one_comic_one_date(self): pub_date = dt.date(2008, 3, 1) crawler_release = CrawlerRelease(self.comic, pub_date) self.crawler_mock.expects( pmock.once()).get_crawler_release(pmock.eq(pub_date)).will( pmock.return_value(crawler_release)) self.aggregator._crawl_one_comic_one_date( self.crawler_mock, pub_date) self.crawler_mock.verify()
def testCanLaunchAndReturnOK(self): "JavaTestLauncher - can launch a file and returns OK if executor returns OK" executor = pmock.Mock() config = pmock.Mock() classpath = pmock.Mock() config.expects(pmock.once()).get(pmock.eq("java_command")).will( pmock.return_value("myJava")) config.expects(pmock.once()).get(pmock.eq("output_folder")).will( pmock.return_value("myOutput")) classpath.expects(pmock.once()).getClasspath().will( pmock.return_value("myclasspath")) classpath.expects(pmock.once()).addDirectory(pmock.eq(".")) classpath.expects(pmock.once()).removeDirectory(pmock.eq(".")) executor.expects(pmock.once()).run( pmock. eq("myJava -Dconcordion.output.dir=myOutput -cp myclasspath junit.textui.TestRunner polop.MyClass" ), pmock.eq(True)).will(pmock.return_value(0)) result = JavaTestLauncher(config, classpath, executor, ".").launch("polop/MyClass.class") self.assertEquals(0, result)
def test_print_entry_listings(): """Verify that a listing was printed""" subject = FeedWriter() (feed_writer, aggregate_feed, listings) = (Mock(), Mock(), Mock()) subject.stdout = Mock() aggregate_feed.expects(once()).is_empty().will(return_value(False)) feed_writer.expects(once()).entry_listings(same(aggregate_feed)).\ will(return_value(listings)) subject.stdout.expects(once()).write(same(listings)) subject.stdout.expects(once()).write(eq(os.linesep)) subject.print_entry_listings(feed_writer, aggregate_feed) feed_writer.verify() subject.stdout.verify()
def test_main(): """"Main should create a feed and print results""" args = ["unused_program_name", "x1"] reader = RSReader() reader.aggregate_feed = Mock() reader.feed_writer = Mock() reader.aggregate_feed.expects(once()).from_urls( same(reader.aggregate_feed), eq(["x1"])) reader.feed_writer.expects(once()).print_entry_listings(same(reader.feed_writer), \ same(reader.aggregate_feed)) reader.main(args) reader.aggregate_feed.verify() reader.feed_writer.verify()
def testOneBrowserLaunchFailureDoesNotAffectOtherBrowserTesting(self): self.test_webserver.expects(pmock.once()).startServing() self.test_webserver.expects(pmock.once()) \ .startTest(pmock.eq(TestRunner.TIMEOUT)) self.test_webserver.expects(pmock.once()) \ .startTest(pmock.eq(TestRunner.TIMEOUT)) failing_browser_launcher = pmock.Mock() failing_browser_launcher.stubs().type() \ .will(pmock.return_value("launcher1")) failing_browser_launcher.expects(pmock.once()) \ .launch(pmock.eq(TestRunner.TEST_URL)) \ .will(pmock.raise_exception(RuntimeError("browser lauch failed"))) failing_browser_launcher.expects(pmock.once()).killAllInstances() self.test_webserver.expects(pmock.once()) \ .testResults() \ .after("launch", failing_browser_launcher) second_browser_launcher = pmock.Mock() second_browser_launcher.stubs().type() \ .will(pmock.return_value("launcher2")) second_browser_launcher.expects(pmock.once()) \ .launch(pmock.eq(TestRunner.TEST_URL)) second_browser_launcher.expects(pmock.once()).killAllInstances() self.test_webserver.expects(pmock.once()) \ .testResults() \ .after("launch", second_browser_launcher) self.test_webserver.expects(pmock.once()).shutdown() TestRunner([failing_browser_launcher, second_browser_launcher], self.test_webserver).runTests() failing_browser_launcher.verify() second_browser_launcher.verify()
def setUp(self): self.picolcd_usb = self.mock() self.picolcd_handle = self.mock() self.picolcd_configuration = self.mock() self.picolcd_usb.expects(pmock.once()).open().will(pmock.return_value(self.picolcd_handle)) self.picolcd_configuration = self.mock() self.picolcd_interface = self.mock() self.picolcd_configuration.interfaces = [[self.picolcd_interface]] self.picolcd_usb.configurations = [self.picolcd_configuration] self.picolcd_handle.expects(pmock.once()).detachKernelDriver(pmock.eq(0)) self.picolcd_handle.expects(pmock.once()).setConfiguration(pmock.same(self.picolcd_configuration)) self.picolcd_handle.expects(pmock.once()).claimInterface(pmock.same(self.picolcd_interface)) self.picolcd_handle.expects(pmock.once()).setAltInterface(pmock.same(self.picolcd_interface)) self.hw = peephole.drivers.picolcd.device.Device(self.picolcd_usb)
def test_unmatched_method(self): mock = pmock.Mock() mock.stubs().mite(looks=pmock.eq("creepy")) mock.expects(pmock.once()).termite() mock.termite() try: mock.ant() except pmock.MatchError, err: self.assertEqual(err.msg, "no match found\n" "invoked ant()\n" "in:\n" "stub: mite(looks=pmock.eq('creepy')),\n" "expected once and has been invoked: termite()")
def setUp(self): self.picolcd_usb = self.mock() self.picolcd_handle = self.mock() self.picolcd_configuration = self.mock() self.picolcd_usb.expects(pmock.once()).open().will(pmock.return_value(self.picolcd_handle)) self.picolcd_configuration = self.mock() self.picolcd_interface = self.mock() self.picolcd_configuration.interfaces = [ [ self.picolcd_interface ] ] self.picolcd_usb.configurations = [self.picolcd_configuration] self.picolcd_handle.expects(pmock.once()).detachKernelDriver(pmock.eq(0)) self.picolcd_handle.expects(pmock.once()).setConfiguration(pmock.same(self.picolcd_configuration)) self.picolcd_handle.expects(pmock.once()).claimInterface(pmock.same(self.picolcd_interface)) self.picolcd_handle.expects(pmock.once()).setAltInterface(pmock.same(self.picolcd_interface)) self.hw = peephole.drivers.picolcd.device.Device(self.picolcd_usb)
def test_url_checker(self): urlmock = pmock.Mock() fields.urllib2 = urlmock urlmock.expects(pmock.once()) \ .urlopen(pmock.eq("http://foo.bar.com")) \ .will(pmock.return_value(None)) checker = fields.URLChecker() checker.set_url("http://foo.bar.com") assert_equals(checker.url, "http://foo.bar.com") assert (checker.is_valid()) assert (checker.does_exists()) urlmock.verify()
def test_urlfield_fail_nonexistent_url(self): blog_url = "http://qwerty.foo.bar" checker_mock = pmock.Mock() class Person(Model): blog = fields.URLField(verify_exists=True, url_checker=checker_mock) person_dict = {'Person': {'blog': blog_url}} checker_mock.expects(pmock.once()) \ .set_url(pmock.eq(blog_url)) checker_mock.expects(pmock.once()) \ .is_valid() \ .will(pmock.return_value(True)) checker_mock.expects(pmock.once()) \ .does_exists() \ .will(pmock.return_value(False)) assert_raises(fields.FieldValidationError, Person.from_dict, person_dict)
def test_expectation(self): mock = pmock.Mock() mock.expects(pmock.once()).dog( pmock.eq("bone"), food=pmock.eq("biscuit")).will( pmock.return_value("bark")) self.assert_(mock.proxy().dog("bone", food="biscuit"), "bark")
def setUp(self): self.mock = pmock.Mock() self.mock.expects(pmock.once()).method("cat") self.mock.expects(pmock.once()).method("cat").taking(pmock.eq("mouse"))
def test_add_taking_at_least_matcher(self): self.assert_(self.builder.taking_at_least(pmock.eq("egg")) is not None) self.assert_(isinstance(self.mocker.added_matcher, pmock.LeastArgumentsMatcher)) self.assert_(self.mocker.added_matcher.matches( pmock.Invocation(None, ("egg", "feather"), {})))
def __mockRfile(self, post_data, pmock): rfile_mock = pmock.Mock() rfile_mock.stubs().read(pmock.eq(312)).will(pmock.return_value(post_data)) return rfile_mock
def test_insufficient_arguments(self): args_matcher = self.matcher_class((pmock.eq("slither"),), {}) self.assert_( not args_matcher.matches(pmock.Invocation("snake", (), {})))
def test_insufficient_keyword_arguments(self): args_matcher = self.matcher_class((), {"food": pmock.eq("goat")}) self.assert_( not args_matcher.matches(pmock.Invocation("snake", (), {})))
def setUp(self): self.mock = pmock.Mock() self.mock.expects(pmock.once()).method("dog").taking_at_least( pmock.eq("bone"))
def test_extra_arguments(self): args_matcher = pmock.AllArgumentsMatcher((pmock.eq("slither"),), {}) self.assert_(not args_matcher.matches( pmock.Invocation("snake", ("slither", "hiss"), {})))
def test_extra_keyword_arguments(self): args_matcher = pmock.AllArgumentsMatcher((), {"food": pmock.eq("goat")}) self.assert_(not args_matcher.matches( pmock.Invocation("snake", (), {"food": "goat", "colour": "red"})))