• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2016 Google LLC
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#      http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import json
16import os
17
18from google.auth import _helpers
19import google.auth.transport.requests
20import google.auth.transport.urllib3
21import pytest
22import requests
23import urllib3
24
25
26HERE = os.path.dirname(__file__)
27DATA_DIR = os.path.join(HERE, "../data")
28IMPERSONATED_SERVICE_ACCOUNT_FILE = os.path.join(
29    DATA_DIR, "impersonated_service_account.json"
30)
31SERVICE_ACCOUNT_FILE = os.path.join(DATA_DIR, "service_account.json")
32URLLIB3_HTTP = urllib3.PoolManager(retries=False)
33REQUESTS_SESSION = requests.Session()
34REQUESTS_SESSION.verify = False
35TOKEN_INFO_URL = "https://www.googleapis.com/oauth2/v3/tokeninfo"
36
37
38@pytest.fixture
39def service_account_file():
40    """The full path to a valid service account key file."""
41    yield SERVICE_ACCOUNT_FILE
42
43
44@pytest.fixture
45def impersonated_service_account_file():
46    """The full path to a valid service account key file."""
47    yield IMPERSONATED_SERVICE_ACCOUNT_FILE
48
49
50@pytest.fixture
51def authorized_user_file():
52    """The full path to a valid authorized user file."""
53    yield AUTHORIZED_USER_FILE
54
55
56@pytest.fixture(params=["urllib3", "requests"])
57def request_type(request):
58    yield request.param
59
60
61@pytest.fixture
62def http_request(request_type):
63    """A transport.request object."""
64    if request_type == "urllib3":
65        yield google.auth.transport.urllib3.Request(URLLIB3_HTTP)
66    elif request_type == "requests":
67        yield google.auth.transport.requests.Request(REQUESTS_SESSION)
68
69
70@pytest.fixture
71def authenticated_request(request_type):
72    """A transport.request object that takes credentials"""
73    if request_type == "urllib3":
74
75        def wrapper(credentials):
76            return google.auth.transport.urllib3.AuthorizedHttp(
77                credentials, http=URLLIB3_HTTP
78            ).request
79
80        yield wrapper
81    elif request_type == "requests":
82
83        def wrapper(credentials):
84            session = google.auth.transport.requests.AuthorizedSession(credentials)
85            session.verify = False
86            return google.auth.transport.requests.Request(session)
87
88        yield wrapper
89
90
91@pytest.fixture
92def token_info(http_request):
93    """Returns a function that obtains OAuth2 token info."""
94
95    def _token_info(access_token=None, id_token=None):
96        query_params = {}
97
98        if access_token is not None:
99            query_params["access_token"] = access_token
100        elif id_token is not None:
101            query_params["id_token"] = id_token
102        else:
103            raise ValueError("No token specified.")
104
105        url = _helpers.update_query(TOKEN_INFO_URL, query_params)
106
107        response = http_request(url=url, method="GET")
108
109        return json.loads(response.data.decode("utf-8"))
110
111    yield _token_info
112
113
114@pytest.fixture
115def verify_refresh(http_request):
116    """Returns a function that verifies that credentials can be refreshed."""
117
118    def _verify_refresh(credentials):
119        if credentials.requires_scopes:
120            credentials = credentials.with_scopes(["email", "profile"])
121
122        credentials.refresh(http_request)
123
124        assert credentials.token
125        assert credentials.valid
126
127    yield _verify_refresh
128
129
130def verify_environment():
131    """Checks to make sure that requisite data files are available."""
132    if not os.path.isdir(DATA_DIR):
133        raise EnvironmentError(
134            "In order to run system tests, test data must exist in "
135            "system_tests/data. See CONTRIBUTING.rst for details."
136        )
137
138
139def pytest_configure(config):
140    """Pytest hook that runs before Pytest collects any tests."""
141    verify_environment()
142