예제 #1
0
 def test_reconnect(self):
     self.mock_listener.expects(once()).first_key_heared()
     self.mock_listener.expects(once()).first_key_heared_again()
     self.notifier.disconnect('simple_key', self.first_key_heared_again)
     self.notifier.connect('simple_key', self.first_key_heared_again)
     self.notifier.notify('simple_key')
     self.mock_listener.verify()
예제 #2
0
 def test_disallow_duplicating_id_of_existing_method(self):
     self.mock.expects(pmock.once()).method("cow")
     try:
         self.mock.expects(pmock.once()).method("bovine").id("cow")
         self.fail()
     except pmock.DefinitionError, err:
         self.assertDuplicateIdMsg(err.msg, "cow")
예제 #3
0
    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()
예제 #4
0
 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")
예제 #5
0
 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()
예제 #6
0
 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()
예제 #7
0
 def test_check(self):
     self.mock_listener.expects(once()).question_changed()
     assert self.quiz.check(self.quiz.question[self.quiz.answer_to])
     self.mock_listener.verify()
     self.mock_listener.expects(once()).question_changed()
     assert not self.quiz.check('a wrong answer')
     assert self.quiz.check(self.quiz.question[self.quiz.answer_to])
     self.mock_listener.verify()
예제 #8
0
 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()
예제 #9
0
 def test_check(self):
     self.mock_listener.expects(once()).question_changed()
     assert self.quiz.check(self.quiz.question[self.quiz.answer_to])
     self.mock_listener.verify()
     self.mock_listener.expects(once()).question_changed()
     assert not self.quiz.check("a wrong answer")
     assert self.quiz.check(self.quiz.question[self.quiz.answer_to])
     self.mock_listener.verify()
예제 #10
0
 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
예제 #11
0
 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_combine_feeds():
    """Should combine feeds into a list of FeedEntries"""
    subject = AggregateFeed()
    mock_feeds = [Mock(), Mock()]
    aggregate_feed = Mock()
    aggregate_feed.expects(once()).add_single_feed(same(aggregate_feed),
                                                   same(mock_feeds[0]))
    aggregate_feed.expects(once()).add_single_feed(same(aggregate_feed),
                                                   same(mock_feeds[1]))
    subject.combine_feeds(aggregate_feed, mock_feeds)
    aggregate_feed.verify()
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 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 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 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_add_singled_feed():
    """Should add a single xkcd_feed to a set of feeds"""
    entries = [Mock(), Mock()]
    xkcd_feed = {'entries': entries}
    aggregate_feed = Mock()
    aggregate_feed.expects(once()).create_entry(same(aggregate_feed),
                                                same(xkcd_feed),
                                                same(entries[0]))
    aggregate_feed.expects(once()).create_entry(same(aggregate_feed),
                                                same(xkcd_feed),
                                                same(entries[1]))
    AggregateFeed().add_single_feed(aggregate_feed, xkcd_feed)
    aggregate_feed.verify()
예제 #18
0
 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)
예제 #19
0
 def test_remove_quizzes_from_multiple_choices(self):
     """
     Removing questions in the list of multiple choices.
     """
     self.mock_listener.expects(once()).question_changed()
     self.quiz.remove_quizzes([self.quiz.multi_choices[0]])
     self.mock_listener.verify()
     self.mock_listener.expects(once()).question_changed()
     self.quiz.remove_quizzes([self.quiz.multi_choices[-1]])
     self.mock_listener.verify()
     self.mock_listener.expects(once()).question_changed()
     self.quiz.remove_quizzes([self.quiz.question])
     self.mock_listener.verify()
     assert self.quiz.question in self.quiz.quiz_pool, "Question not in quiz_pool."
예제 #20
0
 def test_raises_an_exception_if_not_found(self):
     "Hierarchical Configuration - Raises an exception if not found"
     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.raise_exception(Exception("Uknown key...")))
     configuration = HierarchicalConfiguration([fake_config, other_config])
     try:
         configuration.get("output_folder")
         self.fail("Should have thrown exception")
     except KeyError, e:
         self.assertEquals("'output_folder'", str(e))
예제 #21
0
 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)
예제 #22
0
 def test_remove_quizzes_from_multiple_choices(self):
     """
     Removing questions in the list of multiple choices.
     """
     self.mock_listener.expects(once()).question_changed()
     self.quiz.remove_quizzes([self.quiz.multi_choices[0]])
     self.mock_listener.verify()
     self.mock_listener.expects(once()).question_changed()
     self.quiz.remove_quizzes([self.quiz.multi_choices[-1]])
     self.mock_listener.verify()
     self.mock_listener.expects(once()).question_changed()
     self.quiz.remove_quizzes([self.quiz.question])
     self.mock_listener.verify()
     assert self.quiz.question in self.quiz.quiz_pool, \
             "Question not in quiz_pool."
예제 #23
0
 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()
예제 #24
0
 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)
예제 #25
0
 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"))
예제 #26
0
 def test_notifier_with_message(self):
     self.mock_listener.expects(never()).first_key_heared()
     self.mock_listener.expects(never()).first_key_heared_again()
     self.mock_listener.expects(once()).method('second_key_heared').\
             with_at_least(same('little message'))
     self.notifier.notify('key_with_message', 'little message')
     self.mock_listener.verify()
예제 #27
0
 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()
예제 #28
0
 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"))
예제 #29
0
 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"))
예제 #30
0
 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()
예제 #32
0
 def test_notify(self):
     """
     Tests that new_question and next notify properly.
     """
     # test_new_question #
     for i in range(self.quiz.session_length * 2):
         self.mock_listener.expects(once()).question_changed()
         self.quiz.new_question()
         self.mock_listener.verify()
     # test_next #
     for i in range(self.quiz.session_length - 1):
         self.mock_listener.expects(once()).question_changed()
         self.quiz.next()
         self.mock_listener.verify()
     self.mock_listener.expects(once()).question_changed()
     self.mock_listener.expects(once()).break_time()
     self.quiz.next()
     self.mock_listener.verify()
예제 #33
0
파일: command.py 프로젝트: adamcik/comics
    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()
예제 #34
0
 def test_notify(self):
     """
     Tests that new_question and next notify properly.
     """
     # test_new_question #
     for i in range(self.quiz.session_length * 2):
         self.mock_listener.expects(once()).question_changed()
         self.quiz.new_question()
         self.mock_listener.verify()
     # test_next #
     for i in range(self.quiz.session_length - 1):
         self.mock_listener.expects(once()).question_changed()
         self.quiz.next()
         self.mock_listener.verify()
     self.mock_listener.expects(once()).question_changed()
     self.mock_listener.expects(once()).break_time()
     self.quiz.next()
     self.mock_listener.verify()
예제 #35
0
 def test_expected_method_not_invoked(self):
     mock = pmock.Mock()
     mock.expects(pmock.once()).ant()
     try:
         mock.verify()
     except pmock.VerificationError, err:
         self.assertEqual(
             err.msg,
             "expected method was not invoked: expected once: ant()")
예제 #36
0
 def test_remove_and_add_quizzes(self):
     """
     Removing all questions and then adding them again.
     """
     old_quiz_pool = self.quiz.quiz_pool[:]
     # Removing all questions #
     self.mock_listener.expects(once()).question_changed()
     self.quiz.remove_quizzes(self.quiz.quiz_pool[:])
     self.mock_listener.verify()
     assert self.quiz.quiz_pool == [], "quiz_pool still has %s after removing all quizzes" % self.quiz.quiz_pool
     assert self.quiz.question == ["", ""], "Non-empty question left though empty quiz_pool."
     # Adding original quizzes back. #
     self.mock_listener.expects(once()).question_changed()
     self.quiz.add_quizzes(old_quiz_pool[:])
     self.mock_listener.verify()
     assert self.quiz.quiz_pool == old_quiz_pool, "Adding %s to an empty quiz_pool leads to %s." % (
         old_quiz_pool,
         self.quiz.quiz_pool,
     )
예제 #37
0
 def test_score_on_correct_answer(self):
     current_question = self.quiz.question[self.quiz.ask_from]
     old_score = self.quiz.question_score[current_question]
     self.mock_listener.expects(once()).question_changed()
     self.quiz.check(self.quiz.question[self.quiz.answer_to])
     new_score = self.quiz.question_score[current_question]
     assert old_score < new_score or old_score == new_score == 1. , \
             "Score of %s doesn't increase with correct answer: %s, %s" % \
             (self.quiz.question[self.quiz.answer_to], old_score, new_score)
     self.mock_listener.verify()
예제 #38
0
 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()
예제 #39
0
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'
예제 #40
0
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'
예제 #41
0
 def test_score_on_wrong_answer(self):
     current_question = self.quiz.question[self.quiz.ask_from]
     old_score = self.quiz.question_score[current_question]
     self.mock_listener.expects(once()).question_changed()
     self.quiz.check('a wrong answer')
     self.quiz.check(self.quiz.question[self.quiz.answer_to])
     new_score = self.quiz.question_score[current_question]
     assert old_score > new_score or old_score == new_score == 0. , \
             "Score doesn't decrease with wrong answer: %s, %s" % \
             (self.quiz.question[self.quiz.answer_to], old_score, new_score)
     self.mock_listener.verify()
예제 #42
0
 def test_score_on_correct_answer(self):
     current_question = self.quiz.question[self.quiz.ask_from]
     old_score = self.quiz.question_score[current_question]
     self.mock_listener.expects(once()).question_changed()
     self.quiz.check(self.quiz.question[self.quiz.answer_to])
     new_score = self.quiz.question_score[current_question]
     assert old_score < new_score or old_score == new_score == 1.0, (
         "Score of %s doesn't increase with correct answer: %s, %s"
         % (self.quiz.question[self.quiz.answer_to], old_score, new_score)
     )
     self.mock_listener.verify()
예제 #43
0
파일: command.py 프로젝트: adamcik/comics
    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()
예제 #44
0
 def test_method_will_raise_exception(self):
     self.mock = pmock.Mock()
     custom_err = RuntimeError()
     self.mock.expects(pmock.once()).method("dog").will(
         pmock.raise_exception(custom_err))
     try:
         self.mock.proxy().dog()
         self.fail()
     except RuntimeError, err:
         self.assert_(err is custom_err)
         self.mock.verify()
예제 #45
0
 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()
예제 #46
0
 def test_remove_and_add_quizzes(self):
     """
     Removing all questions and then adding them again.
     """
     old_quiz_pool = self.quiz.quiz_pool[:]
     # Removing all questions #
     self.mock_listener.expects(once()).question_changed()
     self.quiz.remove_quizzes(self.quiz.quiz_pool[:])
     self.mock_listener.verify()
     assert self.quiz.quiz_pool == [ ], \
             "quiz_pool still has %s after removing all quizzes" % \
             self.quiz.quiz_pool
     assert self.quiz.question == [ '', '' ], \
             "Non-empty question left though empty quiz_pool."
     # Adding original quizzes back. #
     self.mock_listener.expects(once()).question_changed()
     self.quiz.add_quizzes(old_quiz_pool[:])
     self.mock_listener.verify()
     assert self.quiz.quiz_pool == old_quiz_pool, \
             "Adding %s to an empty quiz_pool leads to %s." % \
             (old_quiz_pool, self.quiz.quiz_pool)
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()
예제 #48
0
 def test_score_on_wrong_answer(self):
     current_question = self.quiz.question[self.quiz.ask_from]
     old_score = self.quiz.question_score[current_question]
     self.mock_listener.expects(once()).question_changed()
     self.quiz.check("a wrong answer")
     self.quiz.check(self.quiz.question[self.quiz.answer_to])
     new_score = self.quiz.question_score[current_question]
     assert old_score > new_score or old_score == new_score == 0.0, (
         "Score doesn't decrease with wrong answer: %s, %s"
         % (self.quiz.question[self.quiz.answer_to], old_score, new_score)
     )
     self.mock_listener.verify()
예제 #49
0
  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()
예제 #50
0
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()
예제 #51
0
 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)
예제 #52
0
  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()
예제 #53
0
 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()")
예제 #54
0
    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)
예제 #55
0
  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
예제 #56
0
    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")
예제 #57
0
 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)