Example #1
0
    def test_it_encodes_the_salt_correctly(self, salt, expected_salt,
                                           pbkdf2_hmac):
        _, returned_salt = hash_password(sentinel.password, salt)

        pbkdf2_hmac.assert_called_once_with(Any(), Any(), expected_salt, Any())

        assert returned_salt == expected_salt
Example #2
0
    def test_summary(self, presenter):
        results = presenter.asdict(summary=True)

        assert results == Any.dict.containing({
            "name": Any(),
            "logo": Any(),
        })
    def test_combo(self):
        matcher = (Any().list().containing([
            Any(),
            Any.instance_of(ValueError),
            Any().dict().containing({"a": Any().iterable().containing([2])}),
        ]).of_size(at_least=2))

        assert matcher == [{"a": range(4), "b": None}, None, ValueError()]
Example #4
0
    def test_passes_connection_to_consumer(self, fake_realtime, fake_consumer, queue):
        messages.process_messages({}, "foobar", queue, raise_error=False)

        fake_consumer.assert_called_once_with(
            connection=fake_realtime.get_connection.return_value,
            routing_key=Any(),
            handler=Any(),
        )
Example #5
0
    def test_passes_routing_key_to_consumer(self, fake_consumer, queue):
        messages.process_messages({}, "foobar", queue, raise_error=False)

        fake_consumer.assert_called_once_with(
            connection=Any(),
            routing_key="foobar",
            handler=Any(),
            statsd_client=Any(),
        )
Example #6
0
    def test_add_causes_flush_if_we_change_command_type(
            self, batch, on_flush, command, other_command):
        self.add_commands(batch, [command])
        batch.batch = [command]
        on_flush.assert_not_called()

        with batch.add(other_command):
            on_flush.assert_called_once_with(Any(), Any(), [command])

        batch.batch = [other_command]
Example #7
0
    def test_it_calls_elasticsearch_as_expected(self, search_index, annotation,
                                                es_client):
        search_index.add_annotation(annotation)

        es_client.conn.index.assert_called_once_with(
            index=es_client.index,
            doc_type=es_client.mapping_type,
            body=Any(),
            id=Any(),
            refresh=False,
        )
Example #8
0
    def test_it_adds_timeout_options_for_failfast(self, Connection):
        realtime.get_connection({}, fail_fast=True)

        Connection.assert_called_once_with(
            Any.string(),
            transport_options={
                "max_retries": Any.int(),
                "interval_start": Any(),
                "interval_step": Any(),
                "interval_max": Any(),
            },
        )
    def test_it_initializes_sentry_sdk_from_config(self, pyramid_config,
                                                   sentry_sdk):
        pyramid_config.add_settings(
            {"h_pyramid_sentry.init.environment": "test"})

        includeme(pyramid_config)

        sentry_sdk.init.assert_called_once_with(
            integrations=Any(),
            environment="test",
            send_default_pii=Any(),
            before_send=Any.function(),
        )
Example #10
0
    def test_it_signs_request_with_oauth1(self, svc, requests, oauth1_service):
        requests.post.side_effect = OSError()

        # We don't care if this actually does anything afterwards, so just
        # fail here so we can see how we were called
        with pytest.raises(OSError):
            svc.record_result(self.GRADING_ID)

        requests.post.assert_called_with(
            url=Any(),
            data=Any(),
            headers=Any(),
            auth=oauth1_service.get_client.return_value,
        )
Example #11
0
    def test_iter_file_accepts_resource_key(self, api, AuthorizedSession):
        list(api.iter_file("FILE_ID", "SPECIFIED_RESOURCE_ID"))

        # pylint: disable=no-member,protected-access
        AuthorizedSession.return_value.request.assert_called_once_with(
            "GET",
            Any(),
            headers=Any.dict.containing({
                "X-Goog-Drive-Resource-Keys":
                "FILE_ID/SPECIFIED_RESOURCE_ID",
            }),
            stream=Any(),
            timeout=Any(),
            max_allowed_time=Any(),
        )
Example #12
0
    def _assert_response_has_expected_values(response):
        lines = response.body.decode("utf-8").split("\n")
        lines = [json.loads(line) for line in lines if line]

        assert lines == [
            {
                "data": {
                    "id": "acct:[email protected]",
                    "type": "user"
                }
            },
            {
                "data": {
                    "id": "group:[email protected]",
                    "type": "group"
                }
            },
            {
                "data": {
                    "id": "group:[email protected]",
                    "type": "group"
                }
            },
            {
                "data": {
                    "id": "group:[email protected]",
                    "type": "group"
                }
            },
            {
                "data": {
                    "id": Any(),
                    "type": "group_membership"
                }
            },
            {
                "data": {
                    "id": Any(),
                    "type": "group_membership"
                }
            },
            {
                "data": {
                    "id": Any(),
                    "type": "group_membership"
                }
            },
        ]
Example #13
0
    def test_present_adds_formatters(self, svc, annotation_resource, presenters):
        formatters = [mock.Mock(), mock.Mock()]
        svc.formatters = formatters

        svc.present(annotation_resource)

        presenters.AnnotationJSONPresenter.assert_called_once_with(Any(), formatters)
Example #14
0
    def test_list_files(self, api_client, http_session):
        files = [
            {
                "display_name": "display_name_1",
                "id": 1,
                "updated_at": "updated_at_1"
            },
            {
                "display_name": "display_name_1",
                "id": 1,
                "updated_at": "updated_at_1"
            },
        ]
        files_with_noise = [dict(file, unexpected="igored") for file in files]
        http_session.send.return_value = _make_response(files_with_noise)

        response = api_client.list_files("COURSE_ID")

        assert response == files
        AnyRequest.assert_on_comparison = True
        http_session.send.assert_called_once_with(
            AnyRequest(
                "GET",
                url=Any.url.with_path(
                    "api/v1/courses/COURSE_ID/files").with_query({
                        "content_types[]":
                        "application/pdf",
                        "per_page":
                        str(api_client.PAGINATION_PER_PAGE),
                    }),
                headers={"Authorization": "Bearer existing_access_token"},
            ),
            timeout=Any(),
        )
Example #15
0
    def test_it_follows_pagination_links_for_many_schema(
            self, base_client, http_session, PaginatedSchema):
        result = base_client._validated_response(
            Request("method", "http://example.com/start").prepare(),
            PaginatedSchema)

        # Values are from the PaginatedSchema fixture
        assert result == ["item_0", "item_1", "item_2"]

        # We'd love to say the first call here isn't to 'next_url', but we
        # mutate the object in place, so the information is destroyed
        http_session.send.assert_has_calls([
            call(AnyRequest(), timeout=Any()),
            call(AnyRequest(url="http://example.com/next"), timeout=Any()),
            call(AnyRequest(url="http://example.com/next"), timeout=Any()),
        ])
Example #16
0
    def test__get_refreshed_token(self, base_client, http_session, db_session,
                                  pyramid_request, json_data):
        http_session.send.return_value = _make_response(json_data)

        base_client._get_refreshed_token("new_refresh_token")

        http_session.send.assert_called_once_with(
            AnyRequest(
                method="POST",
                url=Any.url().with_path("login/oauth2/token").with_query({
                    "grant_type":
                    "refresh_token",
                    "client_id":
                    "developer_key",
                    "client_secret":
                    "developer_secret",
                    "refresh_token":
                    "new_refresh_token",
                }),
            ),
            timeout=Any(),
        )

        # We use our own refresh token if none was passed back from Canvas
        json_data.setdefault("refresh_token", "new_refresh_token")
        self._assert_token_is_saved_in_db(db_session, pyramid_request,
                                          json_data)
Example #17
0
    def test_users_sections(self, api_client, http_session):
        http_session.send.return_value = _make_response({
            "enrollments": [
                {
                    "course_section_id": 101,
                    "unexpected": "ignored"
                },
                {
                    "course_section_id": 102,
                    "unexpected": "ignored"
                },
            ]
        })

        response = api_client.users_sections("USER_ID", "COURSE_ID")

        assert response == [{"id": 101}, {"id": 102}]
        http_session.send.assert_called_once_with(
            AnyRequest(
                "GET",
                url=Any.url.with_path(
                    "api/v1/courses/COURSE_ID/users/USER_ID").with_query(
                        {"include[]": "enrollments"}),
                headers={"Authorization": "Bearer existing_access_token"},
            ),
            timeout=Any(),
        )
Example #18
0
    def test_course_sections(self, api_client, http_session):
        sections = [
            {
                "id": 101,
                "name": "name_1"
            },
            {
                "id": 102,
                "name": "name_2"
            },
        ]
        sections_with_noise = [
            dict(section, unexpected="ignored") for section in sections
        ]
        http_session.send.return_value = _make_response(sections_with_noise)

        response = api_client.course_sections("COURSE_ID")

        assert response == sections
        http_session.send.assert_called_once_with(
            AnyRequest(
                "GET",
                url=Any.url.with_path("api/v1/courses/COURSE_ID/sections"),
                headers={"Authorization": "Bearer existing_access_token"},
            ),
            timeout=Any(),
        )
Example #19
0
    def test_it_calls_get_for_normal_urls(
        # pylint: disable=too-many-arguments
        self,
        response,
        content_type,
        mime_type,
        status_code,
        http_service,
    ):
        if content_type:
            response.headers = {"Content-Type": content_type}
        else:
            response.headers = {}

        response.status_code = status_code

        url = "http://example.com"

        result = get_url_details(http_service, url, headers=sentinel.headers)

        assert result == (mime_type, status_code)
        http_service.get.assert_called_once_with(
            url,
            allow_redirects=True,
            stream=True,
            headers=Any(),
            timeout=10,
            raise_for_status=False,
        )
Example #20
0
    def test_search_uses_passed_in_page_size_for_pagination(
            self, controller, pyramid_request, paginate):
        pyramid_request.params["page_size"] = 100

        controller.search()

        paginate.assert_called_once_with(pyramid_request, Any(), page_size=100)
Example #21
0
    def test_get_token(self, base_client, http_session, db_session,
                       pyramid_request, json_data):
        http_session.send.return_value = _make_response(json_data)

        base_client.get_token("authorization_code")

        http_session.send.assert_called_once_with(
            AnyRequest(
                method="POST",
                url=Any.url().with_path("login/oauth2/token").with_query({
                    "grant_type":
                    "authorization_code",
                    "client_id":
                    "developer_key",
                    "client_secret":
                    "developer_secret",
                    "redirect_uri":
                    base_client._redirect_uri,
                    "code":
                    "authorization_code",
                    "replace_tokens":
                    "True",
                }),
            ),
            timeout=Any(),
        )
        self._assert_token_is_saved_in_db(db_session, pyramid_request,
                                          json_data)
Example #22
0
    def test_it_generates_basic_reports(self, command_processor, commands,
                                        config_command):
        config_command.body.raw["view"] = "basic"
        results = command_processor.process(commands)

        assert isinstance(results, GeneratorType)
        # Our commands below only include a user object
        assert list(results) == [{"data": {"id": Any(), "type": "user"}}]
Example #23
0
    def test_you_can_make_one_part_wild_with_a_base_url(
            self, part, url_with_part_changed):
        # Create a matcher with the specified part wild i.e. `scheme=Any()`

        matcher = AnyURLCore(self.BASE_URL, **{part: Any()})

        # Check it matches the original URL and the URL with that part changed
        assert self.BASE_URL == matcher
        assert url_with_part_changed == matcher
Example #24
0
    def test_sets_correct_mappings_and_settings(self, mock_es_client):
        configure_index(mock_es_client)

        mock_es_client.conn.indices.create.assert_called_once_with(
            Any(),
            body={
                "mappings": {"annotation": ANNOTATION_MAPPING},
                "settings": {"analysis": ANALYSIS_SETTINGS},
            },
        )
Example #25
0
    def _http_intercept(self):
        # Mock all calls to the H API
        httpretty.register_uri(
            method=Any(),
            uri=re.compile(r"^https://example.com/private/api/.*"),
            body="",
        )

        # Catch URLs we aren't expecting or have failed to mock
        def error_response(request, uri, _response_headers):
            raise NotImplementedError(
                f"Unexpected call to URL: {request.method} {uri}")

        httpretty.register_uri(method=Any(),
                               uri=re.compile(".*"),
                               body=error_response)

        httpretty.enable()
        yield
        httpretty.disable()
Example #26
0
    def test_id_returns_jsonld_id_link(self, groupfinder_service,
                                       links_service):
        annotation = mock.Mock(id="foobar")
        resource = AnnotationContext(annotation, groupfinder_service,
                                     links_service)
        presenter = AnnotationJSONLDPresenter(resource)

        result = presenter.id

        assert result == links_service.get.return_value
        links_service.get.assert_called_once_with(annotation, Any())
Example #27
0
    def test_it_serialises(
        self,
        search_index,
        annotation,
        pyramid_request,
        es_client,
        AnnotationSearchIndexPresenter,
    ):
        search_index.add_annotation(annotation)

        AnnotationSearchIndexPresenter.assert_called_once_with(
            annotation, pyramid_request)
        es_client.conn.index.assert_called_once_with(
            index=Any(),
            doc_type=Any(),
            body=AnnotationSearchIndexPresenter.return_value.asdict.
            return_value,
            id=annotation.id,
            refresh=Any(),
        )
Example #28
0
    def test_a_wild_part_does_not_just_match_everything(self, part):
        # Create a matcher with the specified part wild i.e. `scheme=Any()`
        matcher = AnyURLCore(self.BASE_URL, **{part: Any()})

        for modified_part, modified_url in self.PART_MODIFIED_URLS.items():
            # We expect to match the part where the modified part is the part
            # we have made wild so skip
            if modified_part == part:
                continue

            assert modified_url != matcher
Example #29
0
    def test_it_calls_elasticsearch_again_for_a_reindex(
            self, search_index, es_client, refresh):
        search_index.delete_annotation_by_id(sentinel.annotation_id, refresh)

        assert es_client.conn.index.call_count == 2
        es_client.conn.index.assert_called_with(
            index="another_index",
            doc_type=es_client.mapping_type,
            body=Any(),
            id=sentinel.annotation_id,
            refresh=refresh,
        )
Example #30
0
    def test_it_calls_elasticsearch_again_for_a_reindex(
            self, search_index, annotation, es_client):
        search_index.add_annotation(annotation)

        assert es_client.conn.index.call_count == 2
        es_client.conn.index.assert_called_with(
            index="another_index",
            doc_type=es_client.mapping_type,
            body=Any(),
            id=annotation.id,
            refresh=False,
        )