Exemplo n.º 1
0
 def setUp(self):
     self.SCORE = {}
     for question in range(10, 30):
         self.SCORE[str(question)] = question / 10.
     self.quiz = self.CLASS_TO_TEST(self.QUIZ_POOL[:], self.SCORE)
     self.mock_listener = Mock()
     self.quiz.connect('break_time', self.mock_listener.break_time)
     self.quiz.connect('question_changed',
                       self.mock_listener.question_changed)
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_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_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()
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_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 __init__(self,
              head_tag_dict={},
              build_tag_dict={},
              mandatory_head_tags=[],
              mandatory_build_tags=[],
              mandatory_has_questions=False):
     self.mock_hooks = Mock()
     mocked_head_tag_dict = {
         ' ': self.mock_hooks.on_default_header,
         'a_header': self.mock_hooks.on_a_header,
         'an_other_header': self.mock_hooks.on_an_other_header
     }
     mocked_build_tag_dict = {
         ' ': self.mock_hooks.on_default_builder,
         'a_builder': self.mock_hooks.on_a_builder,
         'an_other_builder': self.mock_hooks.on_an_other_builder
     }
     mocked_head_tag_dict.update(head_tag_dict)
     mocked_build_tag_dict.update(build_tag_dict)
     super(Mocked_SaDrill,
           self).__init__(mocked_head_tag_dict, mocked_build_tag_dict,
                          mandatory_head_tags, mandatory_build_tags,
                          mandatory_has_questions)
     self.on_comment = self.mock_hooks.on_comment
     self.on_section = self.mock_hooks.on_section
     self.on_question = self.mock_hooks.on_question
Exemplo n.º 10
0
 def setUp(self):
     self.SCORE = {}
     for question in range(10, 30):
         self.SCORE[str(question)] = question / 10.0
     self.quiz = self.CLASS_TO_TEST(self.QUIZ_POOL[:], self.SCORE)
     self.mock_listener = Mock()
     self.quiz.connect("break_time", self.mock_listener.break_time)
     self.quiz.connect("question_changed", self.mock_listener.question_changed)
Exemplo n.º 11
0
 def setUp(self):
     self.notifier = Notifier(['simple_key', 'key_with_message'])
     self.mock_listener = Mock()
     self.first_key_heared = self.mock_listener.first_key_heared
     self.first_key_heared_again = self.mock_listener.first_key_heared_again
     self.second_key_heared = self.mock_listener.second_key_heared
     self.notifier.connect('simple_key', self.first_key_heared)
     self.notifier.connect('simple_key', self.first_key_heared_again)
     self.notifier.connect('key_with_message', self.second_key_heared)
Exemplo n.º 12
0
class Test_Weighted_Quiz_with_scores(Test_Weighted_Quiz):
    """
    Unittest for the class Weighted_Quiz with predefined scores.

    questions form 0 to 29 with:
        0..9: Has no score; is selected.
        10..19: Has score; is selected.
        20..29: Has score; isn't selected.
        30..39: Has no score; isn't selected.
    """

    NOT_SELECTED_SCORED_QUIZZES = [[str(i), str(i * 10)] for i in range(20, 30)]
    NOT_SELECTED_NOT_SCORED_QUIZZES = [[str(i), str(i * 10)] for i in range(30, 40)]
    QUIZ_POOL = [[str(i), str(i * 10)] for i in range(20)]

    def setUp(self):
        self.SCORE = {}
        for question in range(10, 30):
            self.SCORE[str(question)] = question / 10.0
        self.quiz = self.CLASS_TO_TEST(self.QUIZ_POOL[:], self.SCORE)
        self.mock_listener = Mock()
        self.quiz.connect("break_time", self.mock_listener.break_time)
        self.quiz.connect("question_changed", self.mock_listener.question_changed)

    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()

    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()
Exemplo n.º 13
0
class Test_Weighted_Quiz_with_scores(Test_Weighted_Quiz):
    """
    Unittest for the class Weighted_Quiz with predefined scores.

    questions form 0 to 29 with:
        0..9: Has no score; is selected.
        10..19: Has score; is selected.
        20..29: Has score; isn't selected.
        30..39: Has no score; isn't selected.
    """
    NOT_SELECTED_SCORED_QUIZZES = [[str(i), str(i * 10)]
                                   for i in range(20, 30)]
    NOT_SELECTED_NOT_SCORED_QUIZZES = [[str(i), str(i * 10)]
                                       for i in range(30, 40)]
    QUIZ_POOL = [[str(i), str(i * 10)] for i in range(20)]

    def setUp(self):
        self.SCORE = {}
        for question in range(10, 30):
            self.SCORE[str(question)] = question / 10.
        self.quiz = self.CLASS_TO_TEST(self.QUIZ_POOL[:], self.SCORE)
        self.mock_listener = Mock()
        self.quiz.connect('break_time', self.mock_listener.break_time)
        self.quiz.connect('question_changed',
                          self.mock_listener.question_changed)

    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()

    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()
Exemplo n.º 14
0
 def setUp(self):
     self.quiz = self.CLASS_TO_TEST(self.QUIZ_POOL[:])
     self.mock_listener = Mock()
     self.quiz.connect("break_time", self.mock_listener.break_time)
     self.quiz.connect("question_changed", self.mock_listener.question_changed)
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()
Exemplo n.º 16
0
class Test_Quiz(unittest.TestCase):
    """
    Unittest for the class Quiz.
    """

    CLASS_TO_TEST = Quiz
    QUIZ_POOL = [[str(i), str(i * 10)] for i in range(10)]

    def setUp(self):
        self.quiz = self.CLASS_TO_TEST(self.QUIZ_POOL[:])
        self.mock_listener = Mock()
        self.quiz.connect("break_time", self.mock_listener.break_time)
        self.quiz.connect("question_changed", self.mock_listener.question_changed)

    ## Test add_quizzes and remove_quizzes ##

    def test_add_and_remove_quizzes(self):
        """
        Check that adding and removing quizzes come back to status quo.
        """
        old_quiz_pool = self.quiz.quiz_pool[:]
        new_quizzes = [[i, i * 100] for i in range(10, 20)]
        self.quiz.add_quizzes(new_quizzes)
        self.quiz.remove_quizzes(new_quizzes)
        assert old_quiz_pool == self.quiz.quiz_pool, (
            "quiz_pool changed after adding then removing "
            "%s from %s to %s" % (new_quizzes, old_quiz_pool, self.quiz.quiz_pool)
        )

    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_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."

    def test_remove_quizzes_not_from_multiple_choices(self):
        """
        Removing questions NOT in the list of multiple choices shouldn't 
        change multiple choice list.
        """
        self.mock_listener.expects(never()).question_changed()
        self.quiz = Quiz(self.QUIZ_POOL[:])
        old_multi_choices = self.quiz.multi_choices[:]
        old_question = self.quiz.question[:]
        quiz_list = self.QUIZ_POOL[:]
        for quiz in old_multi_choices:
            quiz_list.remove(quiz)
        for quiz in quiz_list:
            self.quiz.remove_quizzes([quiz])
            assert self.quiz.multi_choices == old_multi_choices, (
                "Multiple choice options changed after removing other "
                "quizzes. "
                "New: %s; Old: %s; Removed: %s." % (self.quiz.multi_choices, old_multi_choices, quiz)
            )
        self.mock_listener.verify()

    ## Single Method Tests ##

    hint_place_holder = "-"

    def test_first_hint_should_be_blank(self):
        """
        Test that hint() starts with letters replaced by the place_holder.
        """
        solution = self.quiz.question[self.quiz.answer_to]
        first_hint = self.quiz.hint()
        assert first_hint == re.sub("\w", self.hint_place_holder, solution)

    def test_hint_adds_two_lettres_each_time(self):
        """
        Test that hint starts with letters replaced by underscores and gives 
        two letters each next hint.
        """
        solution = self.quiz.question[self.quiz.answer_to]
        first_hint = self.quiz.hint()
        next_hint = first_hint
        for hint_num in range((first_hint.count(self.hint_place_holder) + 1) // 2):
            assert next_hint.count(self.hint_place_holder) + hint_num * 2 == first_hint.count(self.hint_place_holder), (
                "Hint no. %s gives %s letters, but %s should have been " + "given."
            ) % (
                hint_num,
                first_hint.count(self.hint_place_holder) - next_hint.count(self.hint_place_holder),
                hint_num * 2,
            )
            next_hint = self.quiz.hint(next_hint)
        assert next_hint == solution, 'Final hint ("%s") is not the solution ("%s").' % (next_hint, solution)

    def test_hint_with_double_lettres(self):
        """
        Run previous test (test_hint_adds_two_lettres_each_time) with '0000'
        as double letters make comparison of solution and hint non-trivial.
        """
        test_question = ["0000", "0000"]
        self.quiz.add_quizzes([test_question])
        self.quiz.question = test_question
        self.test_hint_adds_two_lettres_each_time()

    def test_invalid_previous_hint(self):
        """
        Test that a string which wasn't a hint still gives a valid hint.
        """
        solution = self.quiz.question[self.quiz.answer_to]
        for first_hint in [self.quiz.hint("a completely wrong answer"), self.quiz.hint("!" + solution[1:])]:
            for hint_letter, solution_letter in zip(first_hint, solution):
                assert (
                    hint_letter == self.hint_place_holder or hint_letter == solution_letter
                ), 'Hint ("%s") does not match solution ("%s").' % (first_hint, solution)

    def test_hint_increments_tries(self):
        """
        Test that a hint counts as a try.
        """
        assert self.quiz.tries == 0
        self.quiz.hint()
        assert self.quiz.tries == 1
        self.quiz.hint()
        assert self.quiz.tries == 2

    def test_hint_does_not_change_correct_answer(self):
        assert self.quiz.hint(self.quiz.question[self.quiz.answer_to]) == self.quiz.question[self.quiz.answer_to]

    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()

    def test__gen_multi_choices(self):
        multi_choices = self.quiz._gen_multi_choices()
        assert self.quiz.question in multi_choices, "Question %s not in multiple choice options %s." % (
            self.quiz.question,
            multi_choices,
        )

    def test__gen_multi_choices_has_no_answers_double(self):
        """Test that no answers are double in multi_choices."""
        multi_choices = self.quiz._gen_multi_choices()
        for i, choice in enumerate(multi_choices):
            assert not choice in multi_choices[i + 1 :], '"%s" is double in multi_choices ("%s").' % (
                choice,
                multi_choices,
            )

    def test__refit_multichoice_len(self):
        """
        Test length of multi_choices
        """
        self.mock_listener.expects(at_least_once()).question_changed()
        assert len(self.quiz.multi_choices) == self.quiz.DEFAULT_MULTICHOICE_LEN
        self.quiz.remove_quizzes(self.quiz.quiz_pool[self.quiz.DEFAULT_MULTICHOICE_LEN :])
        assert len(self.quiz.multi_choices) == self.quiz.DEFAULT_MULTICHOICE_LEN, (
            "self.quiz.multi_choices has wrong length: %s instead of %s."
            % (len(self.quiz.multi_choices), self.quiz.DEFAULT_MULTICHOICE_LEN)
        )
        self.quiz.remove_quizzes(self.quiz.quiz_pool[3 : self.quiz.DEFAULT_MULTICHOICE_LEN])
        assert len(self.quiz.multi_choices) == 3, "self.quiz.multi_choices has wrong length: %s instead of 3." % len(
            self.quiz.multi_choices
        )
        self.quiz.remove_quizzes(self.quiz.quiz_pool[:3])
        assert len(self.quiz.multi_choices) == 1
        self.mock_listener.verify()

    def test_get_answer_to_question(self):
        answer_to = self.quiz.answer_to
        ask_from = self.quiz.ask_from

        for question_pair in self.QUIZ_POOL:
            assert question_pair[answer_to] == self.quiz.get_answer_to_question(
                question_pair[ask_from]
            ), "%s should be answer to question %s." % (question_pair[answer_to], question_pair[ask_from])
        assert (
            self.quiz.get_answer_to_question("asdfasdf") == None
        ), "Non-existant question 'asdfasdf' should return 'None'."

    def test_get_question_to_answer_from_multichoices(self):
        answer_to = self.quiz.answer_to
        ask_from = self.quiz.ask_from

        for question_pair in self.quiz.multi_choices:
            assert question_pair[ask_from] == self.quiz.get_question_to_answer_from_multichoices(
                question_pair[answer_to]
            ), "%s should be question to answer %s." % (question_pair[ask_from], question_pair[answer_to])
        assert (
            self.quiz.get_question_to_answer_from_multichoices("asdfasdf") == None
        ), "Non-existant answer 'asdfasdf' should return 'None'."

    def test_get_question_to_answer(self):
        answer_to = self.quiz.answer_to
        ask_from = self.quiz.ask_from

        for question_pair in self.quiz.multi_choices:
            assert question_pair[ask_from] == self.quiz.get_question_to_answer(
                question_pair[answer_to]
            ), "%s should be question to answer %s." % (question_pair[ask_from], question_pair[answer_to])
        assert (
            self.quiz.get_question_to_answer("asdfasdf") == None
        ), "Non-existant answer 'asdfasdf' should return 'None'."

    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()

    def test_set_question_direction(self):
        self.quiz.set_question_direction(0)
        assert self.quiz.ask_from == 0 and self.quiz.answer_to == 1
        self.quiz.set_question_direction(0)
        assert self.quiz.ask_from == 0 and self.quiz.answer_to == 1
        self.quiz.set_question_direction(1)
        assert self.quiz.ask_from == 1 and self.quiz.answer_to == 0
Exemplo n.º 17
0
class Test_Notifier(unittest.TestCase):
    """
    Unittest for the class Notifier.
    """

    def setUp(self):
        self.notifier = Notifier(['simple_key', 'key_with_message'])
        self.mock_listener = Mock()
        self.first_key_heared = self.mock_listener.first_key_heared
        self.first_key_heared_again = self.mock_listener.first_key_heared_again
        self.second_key_heared = self.mock_listener.second_key_heared
        self.notifier.connect('simple_key', self.first_key_heared)
        self.notifier.connect('simple_key', self.first_key_heared_again)
        self.notifier.connect('key_with_message', self.second_key_heared)

    def test_notifier(self):
        self.mock_listener.expects(once()).first_key_heared()
        self.mock_listener.expects(once()).first_key_heared_again()
        self.mock_listener.expects(never()).second_key_heared()
        self.notifier.notify('simple_key')
        self.mock_listener.verify()

    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()

    def test_disconnect(self):
        self.mock_listener.expects(once()).first_key_heared()
        self.mock_listener.expects(never()).first_key_heared_again()
        self.notifier.disconnect('simple_key', self.first_key_heared_again)
        self.notifier.notify('simple_key')
        self.mock_listener.verify()

    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()
Exemplo n.º 18
0
 def setUp(self):
     self.quiz = self.CLASS_TO_TEST(self.QUIZ_POOL[:])
     self.mock_listener = Mock()
     self.quiz.connect('break_time', self.mock_listener.break_time)
     self.quiz.connect('question_changed',
                       self.mock_listener.question_changed)
Exemplo n.º 19
0
class Test_Quiz(unittest.TestCase):
    """
    Unittest for the class Quiz.
    """
    CLASS_TO_TEST = Quiz
    QUIZ_POOL = [[str(i), str(i * 10)] for i in range(10)]

    def setUp(self):
        self.quiz = self.CLASS_TO_TEST(self.QUIZ_POOL[:])
        self.mock_listener = Mock()
        self.quiz.connect('break_time', self.mock_listener.break_time)
        self.quiz.connect('question_changed',
                          self.mock_listener.question_changed)

    ## Test add_quizzes and remove_quizzes ##

    def test_add_and_remove_quizzes(self):
        """
        Check that adding and removing quizzes come back to status quo.
        """
        old_quiz_pool = self.quiz.quiz_pool[:]
        new_quizzes = [[i, i * 100] for i in range(10, 20)]
        self.quiz.add_quizzes(new_quizzes)
        self.quiz.remove_quizzes(new_quizzes)
        assert old_quiz_pool == self.quiz.quiz_pool, \
                "quiz_pool changed after adding then removing " \
                "%s from %s to %s" % \
                (new_quizzes, old_quiz_pool, self.quiz.quiz_pool)

    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_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."

    def test_remove_quizzes_not_from_multiple_choices(self):
        """
        Removing questions NOT in the list of multiple choices shouldn't 
        change multiple choice list.
        """
        self.mock_listener.expects(never()).question_changed()
        self.quiz = Quiz(self.QUIZ_POOL[:])
        old_multi_choices = self.quiz.multi_choices[:]
        old_question = self.quiz.question[:]
        quiz_list = self.QUIZ_POOL[:]
        for quiz in old_multi_choices:
            quiz_list.remove(quiz)
        for quiz in quiz_list:
            self.quiz.remove_quizzes([quiz])
            assert self.quiz.multi_choices == old_multi_choices, \
                    "Multiple choice options changed after removing other "\
                    "quizzes. " "New: %s; Old: %s; Removed: %s." % \
                    (self.quiz.multi_choices, old_multi_choices, quiz)
        self.mock_listener.verify()

    ## Single Method Tests ##

    hint_place_holder = '-'

    def test_first_hint_should_be_blank(self):
        """
        Test that hint() starts with letters replaced by the place_holder.
        """
        solution = self.quiz.question[self.quiz.answer_to]
        first_hint = self.quiz.hint()
        assert first_hint == re.sub('\w', self.hint_place_holder, solution)

    def test_hint_adds_two_lettres_each_time(self):
        """
        Test that hint starts with letters replaced by underscores and gives 
        two letters each next hint.
        """
        solution = self.quiz.question[self.quiz.answer_to]
        first_hint = self.quiz.hint()
        next_hint = first_hint
        for hint_num in \
                range((first_hint.count(self.hint_place_holder) + 1) // 2):
            assert next_hint.count(self.hint_place_holder) + hint_num * 2 == \
                    first_hint.count(self.hint_place_holder), \
                    ("Hint no. %s gives %s letters, but %s should have been " +
                            "given." )% \
                    (hint_num, first_hint.count(self.hint_place_holder) -
                            next_hint.count(self.hint_place_holder), \
                            hint_num * 2)
            next_hint = self.quiz.hint(next_hint)
        assert next_hint == solution, \
                'Final hint ("%s") is not the solution ("%s").' % \
                (next_hint, solution)

    def test_hint_with_double_lettres(self):
        """
        Run previous test (test_hint_adds_two_lettres_each_time) with '0000'
        as double letters make comparison of solution and hint non-trivial.
        """
        test_question = ['0000', '0000']
        self.quiz.add_quizzes([test_question])
        self.quiz.question = test_question
        self.test_hint_adds_two_lettres_each_time()

    def test_invalid_previous_hint(self):
        """
        Test that a string which wasn't a hint still gives a valid hint.
        """
        solution = self.quiz.question[self.quiz.answer_to]
        for first_hint in [
                self.quiz.hint("a completely wrong answer"),
                self.quiz.hint('!' + solution[1:])
        ]:
            for hint_letter, solution_letter in zip(first_hint, solution):
                assert hint_letter == self.hint_place_holder or \
                        hint_letter == solution_letter, \
                        'Hint ("%s") does not match solution ("%s").' % \
                        (first_hint, solution)

    def test_hint_increments_tries(self):
        """
        Test that a hint counts as a try.
        """
        assert self.quiz.tries == 0
        self.quiz.hint()
        assert self.quiz.tries == 1
        self.quiz.hint()
        assert self.quiz.tries == 2

    def test_hint_does_not_change_correct_answer(self):
        assert self.quiz.hint(self.quiz.question[self.quiz.answer_to]) == \
                self.quiz.question[self.quiz.answer_to]

    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()

    def test__gen_multi_choices(self):
        multi_choices = self.quiz._gen_multi_choices()
        assert self.quiz.question in multi_choices, \
                "Question %s not in multiple choice options %s." % \
                (self.quiz.question, multi_choices)

    def test__gen_multi_choices_has_no_answers_double(self):
        """Test that no answers are double in multi_choices."""
        multi_choices = self.quiz._gen_multi_choices()
        for i, choice in enumerate(multi_choices):
            assert not choice in multi_choices[i+1:], \
                    '"%s" is double in multi_choices ("%s").' % \
                    (choice, multi_choices)

    def test__refit_multichoice_len(self):
        """
        Test length of multi_choices
        """
        self.mock_listener.expects(at_least_once()).question_changed()
        assert len(
            self.quiz.multi_choices) == self.quiz.DEFAULT_MULTICHOICE_LEN
        self.quiz.remove_quizzes(
            self.quiz.quiz_pool[self.quiz.DEFAULT_MULTICHOICE_LEN:])
        assert len(self.quiz.multi_choices) == \
                self.quiz.DEFAULT_MULTICHOICE_LEN, \
                "self.quiz.multi_choices has wrong length: %s instead of %s." \
                % (len(self.quiz.multi_choices), \
                self.quiz.DEFAULT_MULTICHOICE_LEN)
        self.quiz.remove_quizzes(
            self.quiz.quiz_pool[3:self.quiz.DEFAULT_MULTICHOICE_LEN])
        assert len(self.quiz.multi_choices) == 3, \
            "self.quiz.multi_choices has wrong length: %s instead of 3." % \
            len(self.quiz.multi_choices)
        self.quiz.remove_quizzes(self.quiz.quiz_pool[:3])
        assert len(self.quiz.multi_choices) == 1
        self.mock_listener.verify()

    def test_get_answer_to_question(self):
        answer_to = self.quiz.answer_to
        ask_from = self.quiz.ask_from

        for question_pair in self.QUIZ_POOL:
            assert question_pair[answer_to] == \
                    self.quiz.get_answer_to_question(question_pair[ask_from]),\
                    "%s should be answer to question %s." % \
                    (question_pair[answer_to], question_pair[ask_from])
        assert self.quiz.get_answer_to_question('asdfasdf') == None, \
                "Non-existant question 'asdfasdf' should return 'None'."

    def test_get_question_to_answer_from_multichoices(self):
        answer_to = self.quiz.answer_to
        ask_from = self.quiz.ask_from

        for question_pair in self.quiz.multi_choices:
            assert question_pair[ask_from] == \
                    self.quiz.get_question_to_answer_from_multichoices(
                            question_pair[answer_to]),\
                    "%s should be question to answer %s." % \
                    (question_pair[ask_from], question_pair[answer_to])
        assert self.quiz.get_question_to_answer_from_multichoices('asdfasdf') \
                == None, \
                "Non-existant answer 'asdfasdf' should return 'None'."

    def test_get_question_to_answer(self):
        answer_to = self.quiz.answer_to
        ask_from = self.quiz.ask_from

        for question_pair in self.quiz.multi_choices:
            assert question_pair[ask_from] == \
                    self.quiz.get_question_to_answer(
                            question_pair[answer_to]),\
                    "%s should be question to answer %s." % \
                    (question_pair[ask_from], question_pair[answer_to])
        assert self.quiz.get_question_to_answer('asdfasdf') == None, \
                "Non-existant answer 'asdfasdf' should return 'None'."

    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()

    def test_set_question_direction(self):
        self.quiz.set_question_direction(0)
        assert self.quiz.ask_from == 0 and self.quiz.answer_to == 1
        self.quiz.set_question_direction(0)
        assert self.quiz.ask_from == 0 and self.quiz.answer_to == 1
        self.quiz.set_question_direction(1)
        assert self.quiz.ask_from == 1 and self.quiz.answer_to == 0
def test_add():
    """Add a xkcd_feed entry to the aggregate"""
    entry = Mock()
    subject = AggregateFeed()
    subject.add(entry)
    assert_equals(set([entry]), subject.entries)
Exemplo n.º 21
0
 def __init__(self, *arg, **kwarg): 
     Mock.__init__(self, `(arg, kwarg)`)