Example #1
0
    def test_the_code_from_auth_can_be_exchanged(self, app, user, params):
        self.login(app, user)
        response = app.get("/oauth/authorize", params=params, status=200)
        js_settings = self._approve_authorize_request(response)
        code = js_settings["code"]

        response = app.post(
            "/api/token",
            params={
                "client_id": params["client_id"],
                "code": code,
                "grant_type": GrantType.authorization_code.value,
            },
            status=200,
        )

        assert response.headers["Content-Type"] == Any.string.matching(
            "application/json"
        )
        assert response.json == Any.dict.containing(
            {
                "token_type": "Bearer",
                "access_token": Any.string(),
                "refresh_token": Any.string(),
            }
        )
Example #2
0
    def test_calls_renderers_with_appropriate_context(self, pyramid_request,
                                                      html_renderer,
                                                      text_renderer):
        generate(pyramid_request, "*****@*****.**")

        expected_context = {
            "time": Any.string(),
            "hostname": Any.string(),
            "python_version": Any.string(),
            "version": __version__,
        }
        html_renderer.assert_(**expected_context)
        text_renderer.assert_(**expected_context)
Example #3
0
    def test_it(self, newrelic, search_index):
        indexer.report_sync_annotations_queue_length()

        search_index._queue.count.assert_called_once_with(
            ["storage.create_annotation", "storage.update_annotation"])
        newrelic.agent.record_custom_metric.assert_called_once_with(
            Any.string(), search_index._queue.count.return_value)
    def test_it_can_apply_a_matcher_to_all_elements(self):
        matcher = HostClass.comprised_of(Any.string())

        assert matcher == ["a", "b"]
        assert matcher == {"a": 1, "b": 2}

        assert matcher != ["a", "b", 1]
        assert matcher != {"a": 1, "b": 1, 3: None}
Example #5
0
    def test_it_extracts_config(self, call_view_pdf, Configuration):
        response = call_view_pdf()

        Configuration.extract_from_params.assert_called_once_with(
            Any.mapping.containing({"url": Any.string()})
        )

        assert response["hypothesis_config"] == sentinel.h_config
Example #6
0
    def test_it_works_with_good_params(self, pyramid_request):
        pyramid_request.params[
            "launch_presentation_return_url"] = "http://example.com"

        schema = BasicLTILaunchSchema(pyramid_request)
        params = schema.parse()

        assert params == Any.dict.containing(
            {"resource_link_id": Any.string()})
    def test_it_logs_when_an_error_is_filtered(self, caplog):
        caplog.set_level(logging.INFO)

        get_before_send([self.always_filter])(sentinel.event_dict,
                                              sentinel.hint_dict)

        assert caplog.record_tuples == [
            (Any.string(), logging.INFO,
             Any.string.containing(LOG_MESSAGE_PREFIX))
        ]
Example #8
0
    def test_get_static_content(self, url, mime_type, test_app):
        response = test_app.get(url)

        assert dict(response.headers) == Any.dict.containing({
            "Content-Type":
            Any.string.containing(mime_type),
            "ETag":
            Any.string()
        })

        assert_cache_control(response.headers, ["public", "max-age=60"])
Example #9
0
    def test_authorisation_presents_form_if_logged_in(self, app, user, params):
        self.login(app, user)
        response = app.get("/oauth/authorize", params=params, status=200)

        js_settings = self._approve_authorize_request(response)

        assert js_settings == {
            "code": Any.string(),
            "origin": "http://localhost:5000",
            "state": params["state"],
        }
Example #10
0
    def test_creation(self, json_schema_error, JSONAPIErrorBody):
        error = SchemaValidationError([json_schema_error])

        assert error.error_bodies == [JSONAPIErrorBody.create.return_value]

        JSONAPIErrorBody.create.assert_called_once_with(
            error,
            detail=Any.string(),
            meta={"schema": {"pointer": "properties/a/type"}, "context": []},
            pointer="a",
            status=400,
        )
Example #11
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(),
            },
        )
Example #12
0
    def test_iter_file(self, api, AuthorizedSession):
        # This is all a bit black box, we don't necessarily know what all these
        # Google objects do, so we'll just check we call them in the right way
        list(api.iter_file("FILE_ID"))

        # pylint: disable=no-member,protected-access
        AuthorizedSession.return_value.request.assert_called_once_with(
            "GET",
            "https://www.googleapis.com/drive/v3/files/FILE_ID?alt=media",
            headers={
                "Accept": "*/*",
                "Accept-Encoding": "gzip, deflate",
                "User-Agent": "(gzip)",
                # This is looked up from the resource mapping
                "X-Goog-Drive-Resource-Keys": "FILE_ID/RESOURCE_ID",
                # Quick check to show we use `add_request_headers`
                "X-Abuse-Policy": Any.string(),
                "X-Complaints-To": Any.string(),
            },
            stream=True,
            timeout=GoogleDriveAPI.TIMEOUT,
            max_allowed_time=GoogleDriveAPI.TIMEOUT,
        )
Example #13
0
    def test_proxy_pdf(self, test_app):
        target_url = "http://example.com"

        response = test_app.get(f"/route?url={target_url}")

        assert response.status_code == 302
        query = dict(self.DEFAULT_OPTIONS)
        query["via.sec"] = Any.string()
        query["url"] = target_url
        assert response.location == Any.url.matching(
            f"http://localhost/pdf?url={quote_plus(target_url)}").with_query(
                query)
        assert_cache_control(
            response.headers,
            ["public", "max-age=300", "stale-while-revalidate=86400"])
Example #14
0
    def test_it(self, pyramid_request, user):
        pyramid_request.matched_route = None
        pyramid_request.params["q"] = "tag:question"
        pyramid_request.user = user

        result = navbar_data(pyramid_request)

        assert result == {
            "create_group_item": {
                "link": "http://example.com/groups/new",
                "title": "Create new group",
            },
            "groups_menu_items": [
                {
                    "title": group.name,
                    "link": f"http://example.com/groups/{group.pubid}/{group.slug}",
                }
                for group in user.groups
            ],
            "groups_suggestions": [
                {
                    "name": group.name,
                    "pubid": group.pubid,
                    "relationship": "Creator" if group.creator == user else None,
                }
                for group in user.groups
            ],
            "q": "tag:question",
            "search_url": Any.string(),
            "settings_menu_items": [
                {"link": "http://example.com/account", "title": "Account details"},
                {"link": "http://example.com/account/profile", "title": "Edit profile"},
                {
                    "link": "http://example.com/account/notifications",
                    "title": "Notifications",
                },
                {"link": "http://example.com/account/developer", "title": "Developer"},
            ],
            "signout_item": {"link": "http://example.com/logout", "title": "Sign out"},
            "username": user.username,
            "username_url": f"http://example.com/users/{user.username}",
        }
Example #15
0
    def test_it_sets_expected_fields(self, pyramid_request, parsed_params,
                                     url_params):
        parsed_params["h_username"] = "******"
        parsed_params["learner_canvas_user_id"] = "learner_canvas_user_id"
        pyramid_request.parsed_params = parsed_params

        result = CanvasPreRecordHook(pyramid_request)(score=None,
                                                      request_body={
                                                          "resultRecord": {}
                                                      })

        assert result == {
            "resultRecord": {
                "result": {
                    "resultData": {
                        "ltiLaunchUrl": Any.string()
                    }
                }
            },
            "submissionDetails": {
                "submittedAt": datetime.datetime(2001,
                                                 1,
                                                 1,
                                                 tzinfo=timezone.utc)
            },
        }

        launch_url = result["resultRecord"]["result"]["resultData"][
            "ltiLaunchUrl"]
        assert launch_url.startswith("http://example.com/lti_launches?")

        query_string = parse_qs(urlparse(launch_url).query)
        assert query_string == dict(
            url_params,
            focused_user=["h_username"],
            learner_canvas_user_id=["learner_canvas_user_id"],
        )
Example #16
0
    def test_deleted_still_returns_read_permissions(self, get_context_acl,
                                                    factories):
        acl = get_context_acl(factories.Annotation(deleted=True))

        assert acl[0] == ("Allow", Any.string(), "read")
Example #17
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=RETRY_POLICY_QUICK)
Example #18
0
def assert_cache_control(headers, cache_parts):
    """Assert that all parts of the Cache-Control header are present."""
    assert dict(headers) == Any.dict.containing(
        {"Cache-Control": Any.string()})
    assert (headers["Cache-Control"].split(", ") == Any.list.containing(
        cache_parts).only())