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 __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_urlfield_success_verify(self): checker_mock = pmock.Mock() blog_url = "http://foo.bar.com/blog" 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(True)) john = Person.from_dict(person_dict) assert_equals(john.blog, blog_url) assert_equals(john.to_dict(), person_dict) checker_mock.verify()
def testBrowserTypeMustBeUnique(self): browser_launcher1 = pmock.Mock() browser_launcher2 = pmock.Mock() duplicated_type = "same type value" browser_launcher1.stubs().type().will(pmock.return_value(duplicated_type)) browser_launcher2.stubs().type().will(pmock.return_value(duplicated_type)) self.assertRaises(ValueError, TestRunner, [browser_launcher1, browser_launcher2], self.test_webserver)
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_get_feeds_from_urls(): """Should get a feed for every URL""" urls = [Mock(), Mock()] feeds = [Mock(), Mock()] subject = AggregateFeed() subject.feedparser = Mock() subject.feedparser.expects(once()).parse(same(urls[0])).will( return_value(feeds[0])) subject.feedparser.expects(once()).parse(same(urls[1])).will( return_value(feeds[1])) returned_feeds = subject.feeds_from_urls(urls) assert_equals(feeds, returned_feeds) subject.feedparser.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 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 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 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_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 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 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 testReportResultsWritesToFile(self): test_result_data = {'browser1': 'TIMED-OUT'} self.testrunner_mock.expects(pmock.once()).runTests() \ .will(pmock.return_value(test_result_data)) output_stream = StringIO.StringIO() self.suites_report_mock.expects(pmock.once()).method("writeReport") self.bootstrap.startTesting() self.bootstrap.writeResultsToFile()
def testRaisesExceptionInCaseCompilationFails(self): "JavaFileCompiler - raises exception in case compilation fails" executor = pmock.Mock() config = pmock.Mock() classpath = pmock.Mock() config.expects(pmock.once()).method("get").will(pmock.return_value("")) classpath.expects(pmock.once()).getClasspath().will( pmock.return_value("myclasspath")) executor.expects(pmock.once()).method("run").will( pmock.return_value(1)) try: result = JavaFileCompiler(config, classpath, executor).compile(["polop/MyClass.java"]) self.fail("Should have raised an exception") except Exception, e: self.assertEquals( "Sorry, an exception occured in the compilation process", str(e))
def test_feed_writer_prints_nothing_with_an_empty_feed(): """Empty aggregate feed should print nothing""" subject = FeedWriter() (feed_writer, aggregate_feed) = (Mock(), Mock()) subject.stdout = Mock() aggregate_feed.expects(once()).is_empty().will(return_value(True)) subject.print_entry_listings(feed_writer, aggregate_feed) aggregate_feed.verify() subject.stdout.verify()
def test_laguage_getter_format(): language = 'error_one_ok_kwargs = you expected %(expected)s but got %(what_got)s' filemock = pmock.Mock() filemock.expects(pmock.once()).read().will(pmock.return_value(language)) lg = LanguageGetter('en-us', file_object=filemock) lg.fill_data() assert lg.format('error_one_ok_kwargs', expected='Xabba', what_got='Yabba') == u'you expected Xabba but got Yabba'
def test_laguage_getter_format_args(): language = 'error_one_ok_args = you expected %s but got %s' filemock = pmock.Mock() filemock.expects(pmock.once()).read().will(pmock.return_value(language)) 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_specified_like_expectations(self): mock = pmock.Mock() mock.stubs().method("fox") mock.stubs().method("fox").taking_at_least("sly") mock.stubs().method("fox").taking("sly", meal="chicken") mock.stubs().method("fox").will(pmock.return_value("trot")) self.assertEqual(mock.proxy().fox(), "trot") mock.fox("sly", meal="chicken") mock.fox("sly") mock.fox()
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_cant_take_two_configuration_second_is_called_if_necessary(self): "Hierarchical Configuration - Can take two childs configuration, second child is called if necessary" fake_config = pmock.Mock() fake_config.expects(pmock.once()).get(pmock.eq("output_folder")).will( pmock.raise_exception(Exception("Uknown key..."))) other_config = pmock.Mock() other_config.expects(pmock.once()).get(pmock.eq("output_folder")).will( pmock.return_value("polop")) configuration = HierarchicalConfiguration([fake_config, other_config]) self.assertEquals("polop", configuration.get("output_folder"))
def test_create_entry(): """Create a xkcd_feed item from a xkcd_feed and a xkcd_feed entry""" agg_feed = AggregateFeed() agg_feed.feed_factory = Mock() (aggregate_feed, xkcd_feed, entry, converted) = (Mock(), Mock(), Mock(), Mock()) agg_feed.feed_factory.expects(once()).from_parsed_feed( same(xkcd_feed), same(entry)).will(return_value(converted)) aggregate_feed.expects(once()).add(same(converted)) agg_feed.create_entry(aggregate_feed, xkcd_feed, entry) aggregate_feed.verify()
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 test_from_urls(): """Should get feeds from URLs and combine them""" urls = [Mock(), Mock()] feeds = [Mock(), Mock()] subject = AggregateFeed() aggregate_feed = Mock() subject.feedparser = Mock() # subject.feedparser.expects(once()).parse(same(urls[0])).will( return_value(feeds[0])) aggregate_feed.expects(once()).\ add_single_feed(same(aggregate_feed), same(feeds[0])) # subject.feedparser.expects(once()).parse(same(urls[1])).will( return_value(feeds[1])) aggregate_feed.expects(once()).\ add_single_feed(same(aggregate_feed), same(feeds[1])) # subject.from_urls(aggregate_feed, urls) subject.feedparser.verify() aggregate_feed.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 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 test_laguage_getter_format_raises_args_got_kwargs(): language = 'error_five_args_got_kwargs = impossible to check %s' filemock = pmock.Mock() filemock.expects(pmock.once()).read().will(pmock.return_value(language)) lg = LanguageGetter('en-us', file_object=filemock) lg.fill_data() @raises(WrongArgumentsError) def format_wrong_args_got_kwargs(): assert lg.format('error_five_args_got_kwargs', what='X') != u'impossible to check X in %s' format_wrong_args_got_kwargs()
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 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_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_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_init_optparse_config(self): optparse_options_mock = pmock.Mock() optparse_options_mock.comic_slugs = None optparse_options_mock.from_date = None optparse_options_mock.to_date = None optparse_options_mock.stubs().method('get').will( pmock.return_value(None)) result = command.Aggregator(optparse_options=optparse_options_mock) self.assertEquals(len(self.aggregator.config.comics), len(result.config.comics)) self.assertEquals(self.aggregator.config.from_date, result.config.from_date) self.assertEquals(self.aggregator.config.to_date, result.config.to_date)
def test_language_getter_get(): language = 'data1 = something\n' \ 'data2 = something else' filemock = pmock.Mock() filemock.expects(pmock.once()).read().will(pmock.return_value(language)) lg = LanguageGetter('en-us', file_object=filemock) lg.fill_data() assert lg.raw_data == language assert 'data' in lg.language_path assert lg.language_path.endswith('en-us.txt') assert lg.get('data1') == u'something' assert lg.get('data2') == u'something else' filemock.verify()
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 __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 setUp(self): self.test_url = TestRunner.TEST_URL self.test_webserver = pmock.Mock() self.browser_launcher = pmock.Mock() self.browser_launcher.stubs().type().will(pmock.return_value("launcher")) self.browser_launcher.stubs().killAllInstances()
def test_method_will_return_value(self): self.mock = pmock.Mock() self.mock.expects(pmock.once()).method("dog").will( pmock.return_value("bone")) self.assertEqual(self.mock.proxy().dog(), "bone")
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 test_set_default_stub(self): mock = pmock.Mock() mock.set_default_stub(pmock.return_value("trot")) self.assertEqual(mock.fox(), "trot")
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)