Esempio n. 1
0
def test_client_forbidden_when_wrapping():
    r = _response({"foo": 1})
    to_wrap = GlobusHTTPResponse(r, client=mock.Mock())

    GlobusHTTPResponse(to_wrap)  # ok
    with pytest.raises(ValueError):
        GlobusHTTPResponse(to_wrap, client=mock.Mock())  # not ok
Esempio n. 2
0
    def setUp(self):
        """
        Makes GlobusHTTPResponses wrapped around HTTP responses for testing
        Uses responses with well formed json, malformed json, and plain text
        """
        super(GlobusHTTPResponseTests, self).setUp()

        # well formed json
        self.json_data = {"label1": "value1", "label2": "value2"}
        json_response = requests.Response()
        json_response._content = six.b(json.dumps(self.json_data))
        json_response.headers["Content-Type"] = "application/json"
        self.globus_json_response = GlobusHTTPResponse(json_response)

        # malformed json
        malformed_response = requests.Response()
        malformed_response._content = six.b("{")
        malformed_response.headers["Content-Type"] = "application/json"
        self.globus_malformed_response = GlobusHTTPResponse(malformed_response)

        # text
        self.text_data = "text data"
        text_response = requests.Response()
        text_response._content = six.b(self.text_data)
        text_response.headers["Content-Type"] = "text/plain"
        self.globus_text_response = GlobusHTTPResponse(text_response)
Esempio n. 3
0
    def __init__(self, *args, **kwargs):
        GlobusHTTPResponse.__init__(self, *args, **kwargs)

        # call the helper on everything in the response array
        self._by_resource_server = dict(
            (unprocessed_item['resource_server'],
             _convert_token_info_dict(unprocessed_item))
            for unprocessed_item in self.data)
Esempio n. 4
0
def test_http_headers_from_response():
    r1 = _response(headers={"Content-Length": "5"})
    assert r1.headers["content-length"] == "5"

    r2 = GlobusHTTPResponse(r1, client=mock.Mock())  # handle a Response object
    assert r2.headers["content-length"] == "5"

    r3 = GlobusHTTPResponse(r2)  # wrap another response
    assert r3.headers["content-length"] == "5"
Esempio n. 5
0
def test_http_status_code_on_response():
    r1 = _response(status=404)
    assert r1.status_code == 404

    r2 = GlobusHTTPResponse(r1, client=mock.Mock())  # handle a Response object
    assert r2.http_status == 404

    r3 = GlobusHTTPResponse(r2)  # wrap another response
    assert r3.http_status == 404
Esempio n. 6
0
    def __init__(self, *args, **kwargs):
        GlobusHTTPResponse.__init__(self, *args, **kwargs)

        # call the helper at the top level
        self._by_resource_server = {
            self.resource_server: _convert_token_info_dict(self)
        }
        # call the helper on everything in 'other_tokens'
        self._by_resource_server.update(
            dict((unprocessed_item['resource_server'],
                  _convert_token_info_dict(unprocessed_item))
                 for unprocessed_item in self.other_tokens))
Esempio n. 7
0
def test_http_reason_on_response():
    r1 = _response(status=404)
    r2 = GlobusHTTPResponse(r1, client=mock.Mock())  # handle a Response object
    r3 = GlobusHTTPResponse(r2)  # wrap another response
    assert r1.reason == "Not Found"
    assert r2.http_reason == "Not Found"
    assert r3.http_reason == "Not Found"

    r4 = _response(status=200)
    r5 = GlobusHTTPResponse(r4, client=mock.Mock())  # handle a Response object
    r6 = GlobusHTTPResponse(r5)  # wrap another response
    assert r4.reason == "OK"
    assert r5.http_reason == "OK"
    assert r6.http_reason == "OK"
def invalid_token(live_api, monkeypatch):
    if live_api:
        return
    else:
        fake_introspect = Mock(return_value=GlobusHTTPResponse(
            canned_responses.resp({"active": False})))
        monkeypatch.setattr(AuthState, "introspect_token", fake_introspect)
Esempio n. 9
0
def text_http_response():
    text_data = "text data"
    text_response = _response(text_data,
                              encoding="utf-8",
                              headers={"Content-Type": "text/plain"})
    return _TestResponse(text_data,
                         GlobusHTTPResponse(text_response, client=mock.Mock()))
Esempio n. 10
0
def _convert_token_info_dict(
        source_dict: GlobusHTTPResponse) -> Dict[str, Any]:
    """
    Extract a set of fields into a new dict for indexing by resource server.
    Allow for these fields to be `None` when absent:
        - "refresh_token"
        - "token_type"
    """
    expires_in = source_dict.get("expires_in", 0)

    return {
        "scope": source_dict["scope"],
        "access_token": source_dict["access_token"],
        "refresh_token": source_dict.get("refresh_token"),
        "token_type": source_dict.get("token_type"),
        "expires_at_seconds": int(time.time() + expires_in),
        "resource_server": source_dict["resource_server"],
    }
Esempio n. 11
0
def test_text_response_repr_and_str_contain_raw_data():
    expect_text = """pu-erh is a distinctive aged tea primarily produced in Yunnan

    depending on the tea used and how it is aged, it can be bright, floral, and fruity
    or it can take on mushroomy, fermented, and malty notes
    """
    raw = _response(expect_text,
                    encoding="utf-8",
                    headers={"Content-Type": "text/plain"})
    res = GlobusHTTPResponse(raw, client=mock.Mock())

    assert expect_text in repr(res)
    assert expect_text in str(res)
def introspect_response() -> Callable[[], GlobusHTTPResponse]:
    now = time()
    return Mock(return_value=GlobusHTTPResponse(
        resp({
            "username":
            mock_username(),
            "dependent_tokens_cache_id":
            "CACHE_ID",
            "token_type":
            "Bearer",
            "client_id":
            mock_client_id(),
            "scope":
            mock_scope(),
            "active":
            True,
            "nbf":
            now - 300,
            "name":
            mock_username(),
            "aud": [
                "e6c75d97-532a-4c88-b031-8584a319fa3e",
                "952d2aa2-aa0c-4d6e-ba1a-9d5fb131ec93",
                "action_provider_tools_automated_tests",
            ],
            "identity_set": [
                "ae2a1750-d274-11e5-b867-e74762c29f57",
                "6e259134-032a-11e6-a68a-537f3952f25a",
                "4984bc70-c0b7-11e5-9076-8b4826e7e700",
                "ae2a64c6-d274-11e5-b868-2bbfe4b1a2b7",
                "ca73e829-715f-4522-9dec-a507fe57a661",
                "14bf3755-6267-42f2-9e9c-ad324de4a1fb",
                mock_effective_identity(),
            ],
            "sub":
            mock_effective_identity(),
            "iss":
            "https://auth.globus.org",
            "exp":
            now + 3600,
            "iat":
            now - 300,
            "email":
            "*****@*****.**",
        })))
Esempio n. 13
0
    def simulate_get(self, *args, **params):
        """
        Simulates a paginated response from a Globus API get supporting limit,
        offset, and has next page
        """
        offset = params.get("offset", 0)
        limit = params["limit"]
        data = {}  # dict that will be treated as the json data of a response
        data["offset"] = offset
        data["limit"] = limit
        # fill data field
        data["DATA"] = []
        for i in range(offset, min(self.n, offset + limit)):
            data["DATA"].append({"value": i})
        # fill has_next_page field
        data["has_next_page"] = (offset + limit) < self.n

        # make the simulated response
        response = requests.Response()
        response._content = six.b(json.dumps(data))
        response.headers["Content-Type"] = "application/json"
        return IterableTransferResponse(GlobusHTTPResponse(response, mock.Mock()))
def make_response(
    activated=True,
    expires_in=0,
    auto_activation_supported=True,
    oauth_server=None,
    DATA=None,
):
    """
    Helper for making ActivationRequirementsResponses with known fields
    """
    DATA = DATA or []
    data = {
        "activated": activated,
        "expires_in": expires_in,
        "oauth_server": oauth_server,
        "DATA": DATA,
        "auto_activation_supported": auto_activation_supported,
    }
    response = requests.Response()
    response.headers["Content-Type"] = "application/json"
    response._content = json.dumps(data).encode("utf-8")
    return ActivationRequirementsResponse(
        GlobusHTTPResponse(response, client=mock.Mock()))
Esempio n. 15
0
 def __init__(self, *args, **kwargs):
     GlobusHTTPResponse.__init__(self, *args, **kwargs)
     self._init_rs_dict()
     self._init_scopes_getter()
Esempio n. 16
0
def test_value_error_indexing_on_non_json_data():
    r = _response(b"foo: bar, baz: buzz")
    res = GlobusHTTPResponse(r, client=mock.Mock())

    with pytest.raises(ValueError):
        res["foo"]
Esempio n. 17
0
def _mk_json_response(data):
    json_response = _response(data)
    return _TestResponse(data,
                         GlobusHTTPResponse(json_response, client=mock.Mock()))
Esempio n. 18
0
 def __init__(self, *args, **kwargs):
     GlobusHTTPResponse.__init__(self, *args, **kwargs)
     self._init_rs_dict()
     self._init_scopes_getter()
Esempio n. 19
0
def text_http_response():
    text_data = "text data"
    text_response = requests.Response()
    text_response._content = six.b(text_data)
    text_response.headers["Content-Type"] = "text/plain"
    return _TestResponse(text_data, GlobusHTTPResponse(text_response))
Esempio n. 20
0
def malformed_http_response():
    malformed_response = requests.Response()
    malformed_response._content = six.b("{")
    malformed_response.headers["Content-Type"] = "application/json"
    return _TestResponse("{", GlobusHTTPResponse(malformed_response))
Esempio n. 21
0
def http_no_content_type_response():
    res = requests.Response()
    assert "Content-Type" not in res.headers
    return _TestResponse(None, GlobusHTTPResponse(res))
Esempio n. 22
0
def json_http_response():
    json_data = {"label1": "value1", "label2": "value2"}
    json_response = requests.Response()
    json_response._content = six.b(json.dumps(json_data))
    json_response.headers["Content-Type"] = "application/json"
    return _TestResponse(json_data, GlobusHTTPResponse(json_response))
Esempio n. 23
0
    def request(
        self,
        method: str,
        path: str,
        *,
        query_params: Optional[Dict[str, Any]] = None,
        data: DataParamType = None,
        headers: Optional[Dict[str, str]] = None,
        encoding: Optional[str] = None,
        allow_redirects: bool = True,
        stream: bool = False,
    ) -> GlobusHTTPResponse:
        """
        Send an HTTP request

        :param method: HTTP request method, as an all caps string
        :type method: str
        :param path: Path for the request, with or without leading slash
        :type path: str
        :param query_params: Parameters to be encoded as a query string
        :type query_params: dict, optional
        :param headers: HTTP headers to add to the request
        :type headers: dict
        :param data: Data to send as the request body. May pass through encoding.
        :type data: dict or str
        :param encoding: A way to encode request data. "json", "form", and "text"
            are all valid values. Custom encodings can be used only if they are
            registered with the transport. By default, strings get "text" behavior and
            all other objects get "json".
        :type encoding: str
        :param allow_redirects: Follow Location headers on redirect response
            automatically. Defaults to ``True``
        :type allow_redirects: bool
        :param stream: Do not immediately download the response content. Defaults to
            ``False``
        :type stream: bool

        :return: :class:`GlobusHTTPResponse \
        <globus_sdk.response.GlobusHTTPResponse>` object

        :raises GlobusAPIError: a `GlobusAPIError` will be raised if the response to the
            request is received and has a status code in the 4xx or 5xx categories
        """
        # prepare data...
        # copy headers if present
        rheaders = {**headers} if headers else {}

        # if a client is asked to make a request against a full URL, not just the path
        # component, then do not resolve the path, simply pass it through as the URL
        if path.startswith("https://") or path.startswith("http://"):
            url = path
        else:
            url = utils.slash_join(self.base_url, urllib.parse.quote(path))

        # make the request
        log.debug("request will hit URL: %s", url)
        r = self.transport.request(
            method=method,
            url=url,
            data=data.data if isinstance(data, utils.PayloadWrapper) else data,
            query_params=query_params,
            headers=rheaders,
            encoding=encoding,
            authorizer=self.authorizer,
            allow_redirects=allow_redirects,
            stream=stream,
        )
        log.debug("request made to URL: %s", r.url)

        if 200 <= r.status_code < 400:
            log.debug(f"request completed with response code: {r.status_code}")
            return GlobusHTTPResponse(r, self)

        log.debug(
            f"request completed with (error) response code: {r.status_code}")
        raise self.error_class(r)
Esempio n. 24
0
def http_no_content_type_response():
    res = _response()
    assert "Content-Type" not in res.headers
    return _TestResponse(None, GlobusHTTPResponse(res, client=mock.Mock()))
Esempio n. 25
0
def test_client_required_with_requests_response():
    r = _response({"foo": 1})
    GlobusHTTPResponse(r, client=mock.Mock())  # ok
    with pytest.raises(ValueError):
        GlobusHTTPResponse(r)  # not ok
Esempio n. 26
0
def malformed_http_response():
    malformed_response = _response(
        b"{", headers={"Content-Type": "application/json"})
    return _TestResponse(
        "{", GlobusHTTPResponse(malformed_response, client=mock.Mock()))