Esempio n. 1
0
 def test_generate_tag_list_gitok(self):
     request = Request(StubHandler())
     request_info = {'tags':'git-ok', 'branch':'test'}
     MockedSettings['git']['gitweb_servername'] = 'example.com'
     with mock.patch.dict(Settings, MockedSettings):
         gen_tags = request._generate_tag_list(request_info, 'repo')
         T.assert_equals(gen_tags[0][1], 'https://example.com/?p=repo.git;a=log;h=refs/heads/test')
Esempio n. 2
0
    def test_log_sqlite_db_ignore(self):
        self._mock_sqlite_connection()

        with patch('os.path.isfile', return_value=True):
            self.collector._log_sqlite_db(
                '/Users/test/sqlite/db/cayman_airways',
                ignore={'fruits': ['color']})

        expected_log_dict_calls = [
            call({
                'name': 'apple',
            }),
            call({
                'name': 'banana',
            }),
            call({
                'name': 'cherry',
            }),
            call({
                'name': 'carrot',
                'color': 'orange',
            }),
            call({
                'name': 'radish',
                'color': 'red',
            }),
        ]
        T.assert_equals(
            expected_log_dict_calls, self.mock_log_dict.call_args_list)
Esempio n. 3
0
 def test_generate_tag_list_gitok(self):
     request = Request(StubHandler())
     request_info = {'tags': 'git-ok', 'branch': 'test'}
     MockedSettings['git']['gitweb_servername'] = 'example.com'
     with mock.patch.dict(Settings, MockedSettings):
         gen_tags = request._generate_tag_list(request_info, 'repo')
         T.assert_equals(gen_tags[0][1], 'https://example.com/?p=repo.git;a=log;h=refs/heads/test')
Esempio n. 4
0
    def test_count_per_user(self):
        raw_data = [{
            'user': {
                'login': u'dochead'
            },
            'title': u'Vader6046 git'
        }, {
            'user': {
                'login': u'dochead'
            },
            'title': u'Vader6046 git'
        }, {
            'user': {
                'login': u'musamhlengi'
            },
            'title':
            u"lockerz bundle dict missing 'name' key value pair"
        }]

        expected = [{
            'count': 2,
            'login': u'dochead'
        }, {
            'count': 1,
            'login': u'musamhlengi'
        }]
        assert_equals(count_per_user(raw_data, 'username'), expected)
Esempio n. 5
0
    def test_update_req_sha_and_queue_pickme_added_test_conflicting_pickmes(self):
        new_sha = "1"*40
        pickme_request = copy.deepcopy(self.fake_request)
        pickme_request['state'] = 'added'
        pickme_request['tags'] = 'conflict-pickme'
        with mock.patch('pushmanager.core.git.GitQueue.enqueue_request') as enqueue_req:
            with mock.patch.dict(Settings, MockedSettings):
                GitQueue._update_req_sha_and_queue_pickme(pickme_request, new_sha)

                result = [None]

                def on_db_return(success, db_results):
                    assert success, "Database error"
                    result[0] = db_results.first()

                request_info_query = db.push_requests.select().where(
                    db.push_requests.c.id == self.fake_request['id']
                )
                db.execute_cb(request_info_query, on_db_return)
                T.assert_equal(result[0][5], new_sha)
                T.assert_equals(enqueue_req.call_count, 2)
                enqueue_req.assert_has_calls([
                    mock.call(
                        GitTaskAction.TEST_CONFLICTING_PICKMES,
                        GitQueue._get_push_for_request(pickme_request['id'])['push'],
                        pushmanager_url='https://%s:%s' % (
                            MockedSettings['main_app']['servername'],
                            MockedSettings['main_app']['port'])
                        )
                ])
Esempio n. 6
0
 def test_generate_tag_list_no_special(self):
     request = Request(StubHandler())
     request_info = {'tags':'git-not-ok', 'branch':'test'}
     MockedSettings['git']['gitweb_servername'] = 'example.com'
     with mock.patch.dict(Settings, MockedSettings):
         gen_tags = request._generate_tag_list(request_info, 'repo')
         T.assert_equals(gen_tags[0][1], None)
Esempio n. 7
0
    def test_generate_test_tag_none(self):
        del MockedSettings['tests_tag']

        request_info = {'tags':'test', 'branch':'test', 'revision': 'abc123'}
        with mock.patch.dict(Settings, MockedSettings):
            gen_tags = TestTagServlet._gen_test_tag_resp(request_info)
            T.assert_equals({}, gen_tags)
Esempio n. 8
0
    def test_update_req_sha_and_queue_pickme_added_test_conflicting_pickmes(self):
        new_sha = "1"*40
        pickme_request = copy.deepcopy(self.fake_request)
        pickme_request['state'] = 'added'
        pickme_request['tags'] = 'conflict-pickme'
        with mock.patch('pushmanager.core.git.GitQueue.enqueue_request') as enqueue_req:
            with mock.patch.dict(Settings, MockedSettings):
                GitQueue._update_req_sha_and_queue_pickme(pickme_request, new_sha)

                result = [None]
                def on_db_return(success, db_results):
                    assert success, "Database error"
                    result[0] = db_results.first()

                request_info_query = db.push_requests.select().where(
                    db.push_requests.c.id == self.fake_request['id']
                )
                db.execute_cb(request_info_query, on_db_return)
                T.assert_equal(result[0][5], new_sha)
                T.assert_equals(enqueue_req.call_count, 2)
                enqueue_req.assert_has_calls([
                    mock.call(
                        GitTaskAction.TEST_CONFLICTING_PICKMES,
                        GitQueue._get_push_for_request(pickme_request['id'])['push'],
                        pushmanager_url='https://%s:%s' % (MockedSettings['main_app']['servername'], MockedSettings['main_app']['port']))
                ])
Esempio n. 9
0
 def test_generate_tag_list_no_special(self):
     request = Request(StubHandler())
     request_info = {'tags': 'git-not-ok', 'branch': 'test'}
     MockedSettings['git']['gitweb_servername'] = 'example.com'
     with mock.patch.dict(Settings, MockedSettings):
         gen_tags = request._generate_tag_list(request_info, 'repo')
         T.assert_equals(gen_tags[0][1], None)
Esempio n. 10
0
 def test_generate_tag_list_gitok(self):
     request = Request(StubHandler())
     request_info = {"tags": "git-ok", "branch": "test"}
     MockedSettings["git"]["gitweb_servername"] = "example.com"
     with mock.patch.dict(Settings, MockedSettings):
         gen_tags = request._generate_tag_list(request_info, "repo")
         T.assert_equals(gen_tags[0][1], "https://example.com/?p=repo.git;a=log;h=refs/heads/test")
Esempio n. 11
0
 def test_generate_tag_list_no_special(self):
     request = Request(StubHandler())
     request_info = {"tags": "git-not-ok", "branch": "test"}
     MockedSettings["git"]["gitweb_servername"] = "example.com"
     with mock.patch.dict(Settings, MockedSettings):
         gen_tags = request._generate_tag_list(request_info, "repo")
         T.assert_equals(gen_tags[0][1], None)
Esempio n. 12
0
    def test_generate_test_tag_none(self):
        del MockedSettings['tests_tag']

        request_info = {'tags': 'test', 'branch': 'test', 'revision': 'abc123'}
        with mock.patch.dict(Settings, MockedSettings):
            gen_tags = TestTagServlet._gen_test_tag_resp(request_info)
            T.assert_equals({}, gen_tags)
Esempio n. 13
0
 def test_load_data(self):
     data = load_data(self.organisation)
     assert_equals(sorted(data.keys()), sorted(['pull_requests',
         'pull_requests_per_project',
         'pull_request_comments',
         'pull_request_comments_per_project',
         'projects',
         'projects_with_pulls']))
Esempio n. 14
0
    def test_pull_request_comments(self):
        pulls, comments = pull_requests_with_comments('yola', 'supporttools')
        assert isinstance(pulls, list)
        assert len(pulls) > 0
        assert_equals(len(pulls[0].keys()), 18)

        assert isinstance(comments, list)
        assert len(comments) > 0
        assert_equals(len(comments[0].keys()), 12)
Esempio n. 15
0
    def test_count_per_user(self):
        raw_data = [
            {'user': {'login': u'dochead'}, 'title': u'Vader6046 git'},
            {'user': {'login': u'dochead'}, 'title': u'Vader6046 git'},
            {'user': {'login': u'musamhlengi'}, 'title': u"lockerz bundle dict missing 'name' key value pair"}
        ]

        expected = [{'count': 2, 'login': u'dochead'}, {'count': 1, 'login': u'musamhlengi'}]
        assert_equals(count_per_user(raw_data, 'username'), expected)
Esempio n. 16
0
    def test_pull_request_comments(self):
        pulls, comments = pull_requests_with_comments('yola', 'supporttools')
        assert isinstance(pulls, list)
        assert len(pulls) > 0
        assert_equals(len(pulls[0].keys()), 18)

        assert isinstance(comments, list)
        assert len(comments) > 0
        assert_equals(len(comments[0].keys()), 12)
Esempio n. 17
0
 def test_load_data(self):
     data = load_data(self.organisation)
     assert_equals(
         sorted(data.keys()),
         sorted([
             'pull_requests', 'pull_requests_per_project',
             'pull_request_comments', 'pull_request_comments_per_project',
             'projects', 'projects_with_pulls'
         ]))
Esempio n. 18
0
    def test_pull_and_comment_stats(self):
        project_counts, user_counts = aggregate_stats(self.organisation)

        for thing_type in ['pulls', 'comments']:
            for project in project_counts.keys():
                item = project_counts[project][thing_type]
                if item:
                    user = item[0]['login']
                    pull_count = item[0]['count']
                    assert_equals(user_counts[user][project][thing_type], pull_count)
Esempio n. 19
0
    def test_pull_and_comment_stats(self):
        project_counts, user_counts = aggregate_stats(self.organisation)

        for thing_type in ['pulls', 'comments']:
            for project in project_counts.keys():
                item = project_counts[project][thing_type]
                if item:
                    user = item[0]['login']
                    pull_count = item[0]['count']
                    assert_equals(user_counts[user][project][thing_type],
                                  pull_count)
Esempio n. 20
0
    def test_multi_get_none_response(self):
        """Tests the behavior of the `multi_get()` method when one of the responses from `grequests.map` is `None`."""
        number_of_requests = 10
        query_params = [{'Jim Bridger': 'Will Poulter'}] * number_of_requests
        responses = self.mock_ok_responses(number_of_requests)
        responses[3] = None
        self.mock_grequests_map(responses)

        actual_responses = MultiRequest(max_retry=1).multi_get('example.com', query_params)

        T.assert_equals(10, len(actual_responses))
        T.assert_is(None, actual_responses[3])
Esempio n. 21
0
    def test_multi_get_none_response(self):
        """Tests the behavior of the `multi_get()` method when one of the responses from `grequests.map` is `None`."""
        number_of_requests = 10
        query_params = [{'Jim Bridger': 'Will Poulter'}] * number_of_requests
        responses = self.mock_ok_responses(number_of_requests)
        responses[3] = None
        self.mock_grequests_map(responses)

        actual_responses = MultiRequest(max_retry=1).multi_get(
            'example.com', query_params)

        T.assert_equals(10, len(actual_responses))
        T.assert_is(None, actual_responses[3])
Esempio n. 22
0
    def test_sample_arm_iadd(self):
        """Test SampleArm's __iadd__ overload operator.

        Verify that after x += y, x gets the new value x + y and still retains its old id.

        """
        arm1 = SampleArm(win=2, loss=1, total=3)
        arm2 = SampleArm(win=3, loss=2, total=5)
        arm3 = arm1 + arm2
        arm1_old_id = id(arm1)
        arm1 += arm2
        arm1_new_id = id(arm1)
        T.assert_equals(arm1_old_id, arm1_new_id)
        T.assert_equals(arm1.json_payload(), arm3.json_payload())
Esempio n. 23
0
    def test_sample_arm_iadd(self):
        """Test SampleArm's __iadd__ overload operator.

        Verify that after x += y, x gets the new value x + y and still retains its old id.

        """
        arm1 = SampleArm(win=2, loss=1, total=3)
        arm2 = SampleArm(win=3, loss=2, total=5)
        arm3 = arm1 + arm2
        arm1_old_id = id(arm1)
        arm1 += arm2
        arm1_new_id = id(arm1)
        T.assert_equals(arm1_old_id, arm1_new_id)
        T.assert_equals(arm1.json_payload(), arm3.json_payload())
Esempio n. 24
0
    def test_multi_get_response_to_json(self):
        """Tests the exception handling in the cases when the response was supposed to return JSON but did not."""
        number_of_requests = 5
        query_params = [{'Andrew Henry': 'Domhnall Gleeson'}] * number_of_requests
        responses = self.mock_ok_responses(number_of_requests)
        self.mock_json_convertion_error(responses[3])
        self.mock_grequests_map(responses)
        logging.warning = MagicMock()

        actual_responses = MultiRequest().multi_get('example.com', query_params)

        T.assert_equals(5, len(actual_responses))
        T.assert_is(None, actual_responses[3])
        logging.warning.called_once_with(
            'Expected response in JSON format from example.com/movie/TheRevenant but the actual response text is: This is not JSON')
Esempio n. 25
0
    def test_multi_get_retry_only_unsuccessful_requests(self):
        """Tests whether only the unsuccessful requests are passed to the consequitive calls to `grequests.map()`.
        The calls to `grequests.map()` return 3 unsuccessful responses to the first call and then 2 unsuccessful responses to the second.
        The third (and the last) call to `grequests.map()` returns successful responses only.
        """
        responses_to_calls = [
            self.mock_ok_responses(10),
            self.mock_ok_responses(3),
            self.mock_ok_responses(2)
        ]
        # mock unsuccessful responses to the first call to grequests.map
        unsuccessful_responses_first_call = [
            responses_to_calls[0][2],
            responses_to_calls[0][3],
            responses_to_calls[0][5],
        ]
        self.mock_unsuccessful_responses(unsuccessful_responses_first_call)
        # mock unsuccessful responses to the second call to grequests.map
        unsuccessful_responses_second_call = [
            responses_to_calls[1][0],
            responses_to_calls[1][2],
        ]
        self.mock_unsuccessful_responses(unsuccessful_responses_second_call)
        grequests.map = MagicMock()
        grequests.map.side_effect = responses_to_calls

        query_params = [
            {'Max Rockatansky': 'Tom Hardy'},
            {'Imperator Furiosa': 'Charlize Theron'},
            {'Nux': 'Nicholas Hoult'},
            {'Immortan Joe': 'Hugh Keays-Byrne'},
            {'Slit': 'Josh Helman'},
            {'Rictus Erectus': 'Nathan Jones'},
            {'Toast the Knowing': 'Zoë Kravitz'},
            {'The Splendid Angharad': 'Rosie Huntington-Whiteley'},
            {'Capable': 'Riley Keough'},
            {'The Dag': 'Abbey Lee'},
        ]

        MultiRequest().multi_get('example.com', query_params)

        T.assert_equals(3, grequests.map.call_count)
        # assert that only the failed requests from the first call to grequests.map are passed in the second call
        second_call = grequests.map.call_args_list[1]
        self.assert_only_unsuccessful_requests(second_call, unsuccessful_responses_first_call)
        # assert that only the failed requests from the second call to grequests.map are passed in the third call
        third_call = grequests.map.call_args_list[2]
        self.assert_only_unsuccessful_requests(third_call, unsuccessful_responses_second_call)
Esempio n. 26
0
    def test_generate_test_tag_no_url(self, mock_urlopen):
        m = mock.Mock()
        m.read.side_effect = ['{"tag" : "tag 0 fails"}', '{"url" : ""}']
        mock_urlopen.return_value = m

        MockedSettings['tests_tag'] = {}
        MockedSettings['tests_tag']['tag'] = 'test'
        MockedSettings['tests_tag']['tag_api_endpoint'] = 'example.com'
        MockedSettings['tests_tag']['tag_api_body'] = '{ "sha" : "%SHA%" }'
        MockedSettings['tests_tag']['url_api_endpoint'] = "http://example.com/api/v1/test_results_url"
        MockedSettings['tests_tag']['url_api_body'] = '{ "sha" : "%SHA%" }'
        MockedSettings['tests_tag']['url_tmpl'] = 'www.example.com/%ID%'

        request_info = {'tags':'test', 'branch':'test', 'revision': 'abc123'}
        with mock.patch.dict(Settings, MockedSettings):
            gen_tags = TestTagServlet._gen_test_tag_resp(request_info)
            T.assert_equals({'tag': 'tag 0 fails', 'url': ""}, gen_tags)
Esempio n. 27
0
    def test_log_sqlite_db(self):
        self._mock_sqlite_connection()

        with patch('os.path.isfile', return_value=True) as isfile_mock:
            self.collector._log_sqlite_db(
                '/Users/test/sqlite/db/panama_papers')

        isfile_mock.assert_called_once_with(
            '/Users/test/sqlite/db/panama_papers')
        self.connect_mock.assert_called_once_with(
            '/Users/test/sqlite/db/panama_papers')
        T.assert_truthy(self.conn_mock.cursor.called)

        expected_execute_calls = [
            call('SELECT * from sqlite_master WHERE type = "table"'),
            call('SELECT * from fruits'),
            call('SELECT * from veggies'),
        ]
        T.assert_equals(
            expected_execute_calls, self.cursor_mock.execute.call_args_list)

        expected_log_dict_calls = [
            call({
                'name': 'apple',
                'color': 'green',
            }),
            call({
                'name': 'banana',
                'color': 'yellow',
            }),
            call({
                'name': 'cherry',
                'color': 'red',
            }),
            call({
                'name': 'carrot',
                'color': 'orange',
            }),
            call({
                'name': 'radish',
                'color': 'red',
            }),
        ]
        T.assert_equals(
            expected_log_dict_calls, self.mock_log_dict.call_args_list)
Esempio n. 28
0
    def test_update_req_sha_and_queue_pickme_requested(self):
        new_sha = "1"*40
        request = copy.deepcopy(self.fake_request)
        request['state'] = 'requested'
        with mock.patch('pushmanager.core.git.GitQueue.enqueue_request') as enqueue_req:
            GitQueue._update_req_sha_and_queue_pickme(request, new_sha)

            result = [None]
            def on_db_return(success, db_results):
                assert success, "Database error"
                result[0] = db_results.first()

            request_info_query = db.push_requests.select().where(
                db.push_requests.c.id == self.fake_request['id']
            )
            db.execute_cb(request_info_query, on_db_return)
            T.assert_equals(enqueue_req.call_count, 1)
            T.assert_equal(result[0][5], new_sha)
Esempio n. 29
0
    def test_generate_test_tag_no_url(self, mock_urlopen):
        m = mock.Mock()
        m.read.side_effect = ['{"tag" : "tag 0 fails"}', '{"url" : ""}']
        mock_urlopen.return_value = m

        MockedSettings['tests_tag'] = {}
        MockedSettings['tests_tag']['tag'] = 'test'
        MockedSettings['tests_tag']['tag_api_endpoint'] = 'example.com'
        MockedSettings['tests_tag']['tag_api_body'] = '{ "sha" : "%SHA%" }'
        MockedSettings['tests_tag'][
            'url_api_endpoint'] = "http://example.com/api/v1/test_results_url"
        MockedSettings['tests_tag']['url_api_body'] = '{ "sha" : "%SHA%" }'
        MockedSettings['tests_tag']['url_tmpl'] = 'www.example.com/%ID%'

        request_info = {'tags': 'test', 'branch': 'test', 'revision': 'abc123'}
        with mock.patch.dict(Settings, MockedSettings):
            gen_tags = TestTagServlet._gen_test_tag_resp(request_info)
            T.assert_equals({'tag': 'tag 0 fails', 'url': ""}, gen_tags)
Esempio n. 30
0
    def test_signup(self, driver):
        driver.get("http://*****:*****@yelp.com')
        signup_form.find_element_by_name('password').send_keys('a_password')

        signup_form.find_element_by_tag_name('button').click()

        T.assert_equals(
            driver.find_element_by_css_selector('.success').text,
            "User is Signed up!"
        )

        user = app.db.get_user_by_email('*****@*****.**')
        T.assert_equal(user['name'], 'Ken')
        T.assert_equal(user['password'], 'a_password')
Esempio n. 31
0
    def test_update_req_sha_and_queue_pickme_requested(self):
        new_sha = "1"*40
        request = copy.deepcopy(self.fake_request)
        request['state'] = 'requested'
        with mock.patch('pushmanager.core.git.GitQueue.enqueue_request') as enqueue_req:
            GitQueue._update_req_sha_and_queue_pickme(request, new_sha)

            result = [None]

            def on_db_return(success, db_results):
                assert success, "Database error"
                result[0] = db_results.first()

            request_info_query = db.push_requests.select().where(
                db.push_requests.c.id == self.fake_request['id']
            )
            db.execute_cb(request_info_query, on_db_return)
            T.assert_equals(enqueue_req.call_count, 1)
            T.assert_equal(result[0][5], new_sha)
Esempio n. 32
0
    def test_multi_get_response_to_json(self):
        """Tests the exception handling in the cases when the response was supposed to return JSON but did not."""
        number_of_requests = 5
        query_params = [{
            'Andrew Henry': 'Domhnall Gleeson'
        }] * number_of_requests
        responses = self.mock_ok_responses(number_of_requests)
        self.mock_json_convertion_error(responses[3])
        self.mock_grequests_map(responses)
        logging.warning = MagicMock()

        actual_responses = MultiRequest().multi_get('example.com',
                                                    query_params)

        T.assert_equals(5, len(actual_responses))
        T.assert_is(None, actual_responses[3])
        logging.warning.called_once_with(
            'Expected response in JSON format from example.com/movie/TheRevenant but the actual response text is: This is not JSON'
        )
Esempio n. 33
0
 def test_sample_arm_str(self):
     """Test SampleArm's __str__ overload operator."""
     for historical_info in self.historical_infos_to_test:
         for arm in historical_info.arms_sampled.itervalues():
             T.assert_equals(str(arm), pprint.pformat(arm.json_payload()))
Esempio n. 34
0
 def assert_log(self, plist_path, expected_log):
     plist = self.collector._read_plist(plist_path)
     T.assert_equals({}, plist)
     self.mock_log_dict.assert_called_once_with(expected_log)
Esempio n. 35
0
 def test_historical_data_str(self):
     """Test HistoricalData's __str__ overload operator."""
     for historical_info in self.historical_infos_to_test:
         T.assert_equals(str(historical_info), pprint.pformat(historical_info.json_payload()))
Esempio n. 36
0
 def test_aggregate_data(self):
     data = aggregate_data(self.organisation)
     assert_equals(sorted(data.keys()), sorted(['raw', 'user_avatars', 'projects', 'users', 'totals']))
Esempio n. 37
0
 def test_organisation_repos(self):
     repos = organisation_repositories('yola')
     assert isinstance(repos, list)
     assert_equals(len(repos[0].keys()), 27)
Esempio n. 38
0
 def test_aggregate_data(self):
     data = aggregate_data(self.organisation)
     assert_equals(
         sorted(data.keys()),
         sorted(['raw', 'user_avatars', 'projects', 'users', 'totals']))
Esempio n. 39
0
 def test_organisation(self):
     org = organisation('yola')
     assert isinstance(org, dict)
     assert_equals(len(org.keys()), 23)
Esempio n. 40
0
 def test_organisation_repos(self):
     repos = organisation_repositories('yola')
     assert isinstance(repos, list)
     assert_equals(len(repos[0].keys()), 27)
Esempio n. 41
0
 def test_organisation(self):
     org = organisation('yola')
     assert isinstance(org, dict)
     assert_equals(len(org.keys()), 23)
Esempio n. 42
0
    def test_sample_arm_add(self):
        """Test SampleArm's __add__ overload operator."""
        arm1 = SampleArm(win=2, loss=1, total=3)
        arm2 = SampleArm(win=3, loss=2, total=5)
        arm3 = arm1 + arm2
        T.assert_equals(arm3.json_payload(), SampleArm(win=5, loss=3, total=8).json_payload())
        # Verify that the + operator does not modify arm1 and arm2
        T.assert_equals(arm1.json_payload(), SampleArm(win=2, loss=1, total=3).json_payload())
        T.assert_equals(arm2.json_payload(), SampleArm(win=3, loss=2, total=5).json_payload())

        arm1 += arm2
        arm2 += arm1
        T.assert_equals(arm1.json_payload(), SampleArm(win=5, loss=3, total=8).json_payload())
        T.assert_equals(arm2.json_payload(), SampleArm(win=8, loss=5, total=13).json_payload())
        # Verify that modifying arm1 and arm2 does not change arm3
        T.assert_equals(arm3.json_payload(), SampleArm(win=5, loss=3, total=8).json_payload())
Esempio n. 43
0
    def test_multi_get_retry_only_unsuccessful_requests(self):
        """Tests whether only the unsuccessful requests are passed to the consequitive calls to `grequests.map()`.
        The calls to `grequests.map()` return 3 unsuccessful responses to the first call and then 2 unsuccessful responses to the second.
        The third (and the last) call to `grequests.map()` returns successful responses only.
        """
        responses_to_calls = [
            self.mock_ok_responses(10),
            self.mock_ok_responses(3),
            self.mock_ok_responses(2)
        ]
        # mock unsuccessful responses to the first call to grequests.map
        unsuccessful_responses_first_call = [
            responses_to_calls[0][2],
            responses_to_calls[0][3],
            responses_to_calls[0][5],
        ]
        self.mock_unsuccessful_responses(unsuccessful_responses_first_call)
        # mock unsuccessful responses to the second call to grequests.map
        unsuccessful_responses_second_call = [
            responses_to_calls[1][0],
            responses_to_calls[1][2],
        ]
        self.mock_unsuccessful_responses(unsuccessful_responses_second_call)
        grequests.map = MagicMock()
        grequests.map.side_effect = responses_to_calls

        query_params = [
            {
                'Max Rockatansky': 'Tom Hardy'
            },
            {
                'Imperator Furiosa': 'Charlize Theron'
            },
            {
                'Nux': 'Nicholas Hoult'
            },
            {
                'Immortan Joe': 'Hugh Keays-Byrne'
            },
            {
                'Slit': 'Josh Helman'
            },
            {
                'Rictus Erectus': 'Nathan Jones'
            },
            {
                'Toast the Knowing': 'Zoë Kravitz'
            },
            {
                'The Splendid Angharad': 'Rosie Huntington-Whiteley'
            },
            {
                'Capable': 'Riley Keough'
            },
            {
                'The Dag': 'Abbey Lee'
            },
        ]

        MultiRequest().multi_get('example.com', query_params)

        T.assert_equals(3, grequests.map.call_count)
        # assert that only the failed requests from the first call to grequests.map are passed in the second call
        second_call = grequests.map.call_args_list[1]
        self.assert_only_unsuccessful_requests(
            second_call, unsuccessful_responses_first_call)
        # assert that only the failed requests from the second call to grequests.map are passed in the third call
        third_call = grequests.map.call_args_list[2]
        self.assert_only_unsuccessful_requests(
            third_call, unsuccessful_responses_second_call)
Esempio n. 44
0
 def test_sample_arm_str(self):
     """Test SampleArm's __str__ overload operator."""
     for historical_info in self.historical_infos_to_test:
         for arm in historical_info.arms_sampled.itervalues():
             T.assert_equals(str(arm), pprint.pformat(arm.json_payload()))
Esempio n. 45
0
    def test_sample_arm_add(self):
        """Test SampleArm's __add__ overload operator."""
        arm1 = SampleArm(win=2, loss=1, total=3)
        arm2 = SampleArm(win=3, loss=2, total=5)
        arm3 = arm1 + arm2
        T.assert_equals(arm3.json_payload(),
                        SampleArm(win=5, loss=3, total=8).json_payload())
        # Verify that the + operator does not modify arm1 and arm2
        T.assert_equals(arm1.json_payload(),
                        SampleArm(win=2, loss=1, total=3).json_payload())
        T.assert_equals(arm2.json_payload(),
                        SampleArm(win=3, loss=2, total=5).json_payload())

        arm1 += arm2
        arm2 += arm1
        T.assert_equals(arm1.json_payload(),
                        SampleArm(win=5, loss=3, total=8).json_payload())
        T.assert_equals(arm2.json_payload(),
                        SampleArm(win=8, loss=5, total=13).json_payload())
        # Verify that modifying arm1 and arm2 does not change arm3
        T.assert_equals(arm3.json_payload(),
                        SampleArm(win=5, loss=3, total=8).json_payload())
Esempio n. 46
0
 def test_historical_data_str(self):
     """Test HistoricalData's __str__ overload operator."""
     for historical_info in self.historical_infos_to_test:
         T.assert_equals(str(historical_info),
                         pprint.pformat(historical_info.json_payload()))