You're Invited:Meet the Socket Team at RSAC and BSidesSF 2026, March 23–26.RSVP
Socket
Book a DemoSign in
Socket

auth0-python

Package Overview
Dependencies
Maintainers
1
Versions
69
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

auth0-python - pypi Package Compare versions

Comparing version
3.22.0
to
3.23.0
+84
auth0/v3/asyncify.py
import aiohttp
from auth0.v3.rest_async import AsyncRestClient
def _gen_async(client, method):
m = getattr(client, method)
async def closure(*args, **kwargs):
return await m(*args, **kwargs)
return closure
def asyncify(cls):
methods = [
func
for func in dir(cls)
if callable(getattr(cls, func)) and not func.startswith("_")
]
class AsyncClient(cls):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
if token is None:
# Wrap the auth client
super(AsyncClient, self).__init__(domain, telemetry, timeout, protocol)
else:
# Wrap the mngtmt client
super(AsyncClient, self).__init__(
domain, token, telemetry, timeout, protocol, rest_options
)
self.client = AsyncRestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
class Wrapper(cls):
def __init__(
self,
domain,
token=None,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
if token is None:
# Wrap the auth client
super(Wrapper, self).__init__(domain, telemetry, timeout, protocol)
else:
# Wrap the mngtmt client
super(Wrapper, self).__init__(
domain, token, telemetry, timeout, protocol, rest_options
)
self._async_client = AsyncClient(
domain, token, telemetry, timeout, protocol, rest_options
)
for method in methods:
setattr(
self,
"{}_async".format(method),
_gen_async(self._async_client, method),
)
async def __aenter__(self):
"""Automatically create and set session within context manager."""
async_rest_client = self._async_client.client
self._session = aiohttp.ClientSession()
async_rest_client.set_session(self._session)
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
"""Automatically close session within context manager."""
await self._session.close()
return Wrapper
from ..rest import RestClient
class Branding(object):
"""Auth0 Branding endpoints
Args:
domain (str): Your Auth0 domain, e.g: 'username.auth0.com'
token (str): Management API v2 Token
telemetry (bool, optional): Enable or disable Telemetry
(defaults to True)
timeout (float or tuple, optional): Change the requests
connect and read timeout. Pass a tuple to specify
both values separately or a float to set both to it.
(defaults to 5.0 for both)
rest_options (RestClientOptions): Pass an instance of
RestClientOptions to configure additional RestClient
options, such as rate-limit retries.
(defaults to None)
"""
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, *args):
url = "{}://{}/api/v2/branding".format(self.protocol, self.domain)
for p in args:
if p is not None:
url = "{}/{}".format(url, p)
return url
def get(self, aud=None):
"""Retrieve branding settings. Requires "read:branding" scope.
See: https://auth0.com/docs/api/management/v2#!/Branding/get_branding
"""
return self.client.get(self._url())
def update(self, body):
"""Update branding settings. Requires "update:branding" scope.
Args:
body (dict): Attributes for the updated trigger binding.
See: https://auth0.com/docs/api/management/v2#!/Branding/patch_branding
"""
return self.client.patch(self._url(), data=body)
def get_template_universal_login(self):
"""Get template for New Universal Login Experience. Requires "read:branding" scope.
See: https://auth0.com/docs/api/management/v2#!/Branding/get_universal_login
"""
return self.client.get(self._url("templates", "universal-login"))
def delete_template_universal_login(self):
"""Delete template for New Universal Login Experience. Requires "delete:branding" scope.
See: https://auth0.com/docs/api/management/v2#!/Branding/delete_universal_login
"""
return self.client.delete(self._url("templates", "universal-login"))
def update_template_universal_login(self, body):
"""Update template for New Universal Login Experience. Requires "update:branding" scope.
Args:
body (str): Complete HTML content to assign to the template. See linked API documentation for example.
See: https://auth0.com/docs/api/management/v2#!/Branding/put_universal_login
"""
return self.client.put(
self._url("templates", "universal-login"),
type="put_universal-login_body",
body={"template": body},
)
import asyncio
import json
import aiohttp
from auth0.v3.exceptions import RateLimitError
from .rest import EmptyResponse, JsonResponse, PlainResponse
from .rest import Response as _Response
from .rest import RestClient
def _clean_params(params):
if params is None:
return params
return {k: v for k, v in params.items() if v is not None}
class AsyncRestClient(RestClient):
"""Provides simple methods for handling all RESTful api endpoints.
Args:
telemetry (bool, optional): Enable or disable Telemetry
(defaults to True)
timeout (float or tuple, optional): Change the requests
connect and read timeout. Pass a tuple to specify
both values separately or a float to set both to it.
(defaults to 5.0 for both)
options (RestClientOptions): Pass an instance of
RestClientOptions to configure additional RestClient
options, such as rate-limit retries. Overrides matching
options passed to the constructor.
(defaults to 3)
"""
def __init__(self, *args, **kwargs):
super(AsyncRestClient, self).__init__(*args, **kwargs)
self._session = None
sock_connect, sock_read = (
self.timeout
if isinstance(self.timeout, tuple)
else (self.timeout, self.timeout)
)
self.timeout = aiohttp.ClientTimeout(
sock_connect=sock_connect, sock_read=sock_read
)
def set_session(self, session):
"""Set Client Session to improve performance by reusing session.
Session should be closed manually or within context manager.
"""
self._session = session
async def _request(self, *args, **kwargs):
kwargs["headers"] = kwargs.get("headers", self.base_headers)
kwargs["timeout"] = self.timeout
if self._session is not None:
# Request with re-usable session
async with self._session.request(*args, **kwargs) as response:
return await self._process_response(response)
else:
# Request without re-usable session
async with aiohttp.ClientSession() as session:
async with session.request(*args, **kwargs) as response:
return await self._process_response(response)
async def get(self, url, params=None, headers=None):
request_headers = self.base_headers.copy()
request_headers.update(headers or {})
# Track the API request attempt number
attempt = 0
# Reset the metrics tracker
self._metrics = {"retries": 0, "backoff": []}
params = _clean_params(params)
while True:
# Increment attempt number
attempt += 1
try:
response = await self._request(
"get", url, params=params, headers=request_headers
)
return response
except RateLimitError as e:
# If the attempt number is greater than the configured retries, raise RateLimitError
if attempt > self._retries:
raise e
wait = self._calculate_wait(attempt)
# Skip calling sleep() when running unit tests
if self._skip_sleep is False:
# sleep() functions in seconds, so convert the milliseconds formula above accordingly
await asyncio.sleep(wait / 1000)
async def post(self, url, data=None, headers=None):
request_headers = self.base_headers.copy()
request_headers.update(headers or {})
return await self._request("post", url, json=data, headers=request_headers)
async def file_post(self, url, data=None, files=None):
headers = self.base_headers.copy()
headers.pop("Content-Type", None)
return await self._request("post", url, data={**data, **files}, headers=headers)
async def patch(self, url, data=None):
return await self._request("patch", url, json=data)
async def put(self, url, data=None):
return await self._request("put", url, json=data)
async def delete(self, url, params=None, data=None):
return await self._request(
"delete", url, json=data, params=_clean_params(params) or {}
)
async def _process_response(self, response):
parsed_response = await self._parse(response)
return parsed_response.content()
async def _parse(self, response):
text = await response.text()
requests_response = RequestsResponse(response, text)
if not text:
return EmptyResponse(response.status)
try:
return JsonResponse(requests_response)
except ValueError:
return PlainResponse(requests_response)
class RequestsResponse(object):
def __init__(self, response, text):
self.status_code = response.status
self.headers = response.headers
self.text = text
import base64
import json
import platform
import sys
from random import randint
from time import sleep
import requests
from auth0.v3.exceptions import Auth0Error, RateLimitError
UNKNOWN_ERROR = "a0.sdk.internal.unknown"
class RestClientOptions(object):
"""Configuration object for RestClient. Used for configuring
additional RestClient options, such as rate-limit
retries.
Args:
telemetry (bool, optional): Enable or disable Telemetry
(defaults to True)
timeout (float or tuple, optional): Change the requests
connect and read timeout. Pass a tuple to specify
both values separately or a float to set both to it.
(defaults to 5.0 for both)
retries (integer): In the event an API request returns a
429 response header (indicating rate-limit has been
hit), the RestClient will retry the request this many
times using an exponential backoff strategy, before
raising a RateLimitError exception. 10 retries max.
(defaults to 3)
"""
def __init__(self, telemetry=None, timeout=None, retries=None):
self.telemetry = True
self.timeout = 5.0
self.retries = 3
if telemetry is not None:
self.telemetry = telemetry
if timeout is not None:
self.timeout = timeout
if retries is not None:
self.retries = retries
class RestClient(object):
"""Provides simple methods for handling all RESTful api endpoints.
Args:
telemetry (bool, optional): Enable or disable Telemetry
(defaults to True)
timeout (float or tuple, optional): Change the requests
connect and read timeout. Pass a tuple to specify
both values separately or a float to set both to it.
(defaults to 5.0 for both)
options (RestClientOptions): Pass an instance of
RestClientOptions to configure additional RestClient
options, such as rate-limit retries. Overrides matching
options passed to the constructor.
(defaults to 3)
"""
def __init__(self, jwt, telemetry=True, timeout=5.0, options=None):
if options is None:
options = RestClientOptions(telemetry=telemetry, timeout=timeout)
self.options = options
self.jwt = jwt
self._metrics = {"retries": 0, "backoff": []}
self._skip_sleep = False
self.base_headers = {
"Content-Type": "application/json",
}
if jwt is not None:
self.base_headers["Authorization"] = "Bearer {}".format(self.jwt)
if options.telemetry:
py_version = platform.python_version()
version = sys.modules["auth0"].__version__
auth0_client = json.dumps(
{
"name": "auth0-python",
"version": version,
"env": {
"python": py_version,
},
}
).encode("utf-8")
self.base_headers.update(
{
"User-Agent": "Python/{}".format(py_version),
"Auth0-Client": base64.b64encode(auth0_client).decode(),
}
)
# Cap the maximum number of retries to 10 or fewer. Floor the retries at 0.
self._retries = min(self.MAX_REQUEST_RETRIES(), max(0, options.retries))
# For backwards compatibility reasons only
# TODO: Deprecate in the next major so we can prune these arguments. Guidance should be to use RestClient.options.*
self.telemetry = options.telemetry
self.timeout = options.timeout
# Returns a hard cap for the maximum number of retries allowed (10)
def MAX_REQUEST_RETRIES(self):
return 10
# Returns the maximum amount of jitter to introduce in milliseconds (100ms)
def MAX_REQUEST_RETRY_JITTER(self):
return 100
# Returns the maximum delay window allowed (1000ms)
def MAX_REQUEST_RETRY_DELAY(self):
return 1000
# Returns the minimum delay window allowed (100ms)
def MIN_REQUEST_RETRY_DELAY(self):
return 100
def get(self, url, params=None, headers=None):
request_headers = self.base_headers.copy()
request_headers.update(headers or {})
# Track the API request attempt number
attempt = 0
# Reset the metrics tracker
self._metrics = {"retries": 0, "backoff": []}
while True:
# Increment attempt number
attempt += 1
# Issue the request
response = requests.get(
url,
params=params,
headers=request_headers,
timeout=self.options.timeout,
)
# If the response did not have a 429 header, or the attempt number is greater than the configured retries, break
if response.status_code != 429 or attempt > self._retries:
break
wait = self._calculate_wait(attempt)
# Skip calling sleep() when running unit tests
if self._skip_sleep is False:
# sleep() functions in seconds, so convert the milliseconds formula above accordingly
sleep(wait / 1000)
# Return the final Response
return self._process_response(response)
def post(self, url, data=None, headers=None):
request_headers = self.base_headers.copy()
request_headers.update(headers or {})
response = requests.post(
url, json=data, headers=request_headers, timeout=self.options.timeout
)
return self._process_response(response)
def file_post(self, url, data=None, files=None):
headers = self.base_headers.copy()
headers.pop("Content-Type", None)
response = requests.post(
url, data=data, files=files, headers=headers, timeout=self.options.timeout
)
return self._process_response(response)
def patch(self, url, data=None):
headers = self.base_headers.copy()
response = requests.patch(
url, json=data, headers=headers, timeout=self.options.timeout
)
return self._process_response(response)
def put(self, url, data=None):
headers = self.base_headers.copy()
response = requests.put(
url, json=data, headers=headers, timeout=self.options.timeout
)
return self._process_response(response)
def delete(self, url, params=None, data=None):
headers = self.base_headers.copy()
response = requests.delete(
url,
headers=headers,
params=params or {},
json=data,
timeout=self.options.timeout,
)
return self._process_response(response)
def _calculate_wait(self, attempt):
# Retry the request. Apply a exponential backoff for subsequent attempts, using this formula:
# max(MIN_REQUEST_RETRY_DELAY, min(MAX_REQUEST_RETRY_DELAY, (100ms * (2 ** attempt - 1)) + random_between(1, MAX_REQUEST_RETRY_JITTER)))
# Increases base delay by (100ms * (2 ** attempt - 1))
wait = 100 * 2 ** (attempt - 1)
# Introduces jitter to the base delay; increases delay between 1ms to MAX_REQUEST_RETRY_JITTER (100ms)
wait += randint(1, self.MAX_REQUEST_RETRY_JITTER())
# Is never more than MAX_REQUEST_RETRY_DELAY (1s)
wait = min(self.MAX_REQUEST_RETRY_DELAY(), wait)
# Is never less than MIN_REQUEST_RETRY_DELAY (100ms)
wait = max(self.MIN_REQUEST_RETRY_DELAY(), wait)
self._metrics["retries"] = attempt
self._metrics["backoff"].append(wait)
return wait
def _process_response(self, response):
return self._parse(response).content()
def _parse(self, response):
if not response.text:
return EmptyResponse(response.status_code)
try:
return JsonResponse(response)
except ValueError:
return PlainResponse(response)
class Response(object):
def __init__(self, status_code, content, headers):
self._status_code = status_code
self._content = content
self._headers = headers
def content(self):
if self._is_error():
if self._status_code == 429:
reset_at = int(self._headers.get("x-ratelimit-reset", "-1"))
raise RateLimitError(
error_code=self._error_code(),
message=self._error_message(),
reset_at=reset_at,
)
raise Auth0Error(
status_code=self._status_code,
error_code=self._error_code(),
message=self._error_message(),
)
else:
return self._content
def _is_error(self):
return self._status_code is None or self._status_code >= 400
# Adding these methods to force implementation in subclasses because they are references in this parent class
def _error_code(self):
raise NotImplementedError
def _error_message(self):
raise NotImplementedError
class JsonResponse(Response):
def __init__(self, response):
content = json.loads(response.text)
super(JsonResponse, self).__init__(
response.status_code, content, response.headers
)
def _error_code(self):
if "errorCode" in self._content:
return self._content.get("errorCode")
elif "error" in self._content:
return self._content.get("error")
elif "code" in self._content:
return self._content.get("code")
else:
return UNKNOWN_ERROR
def _error_message(self):
if "error_description" in self._content:
return self._content.get("error_description")
message = self._content.get("message", "")
if message is not None and message != "":
return message
return self._content.get("error", "")
class PlainResponse(Response):
def __init__(self, response):
super(PlainResponse, self).__init__(
response.status_code, response.text, response.headers
)
def _error_code(self):
return UNKNOWN_ERROR
def _error_message(self):
return self._content
class EmptyResponse(Response):
def __init__(self, status_code):
super(EmptyResponse, self).__init__(status_code, "", {})
def _error_code(self):
return UNKNOWN_ERROR
def _error_message(self):
return ""
import base64
import json
import platform
import re
import sys
from tempfile import TemporaryFile
from unittest import IsolatedAsyncioTestCase
import aiohttp
from aioresponses import CallbackResult, aioresponses
from callee import Attrs
from mock import ANY, MagicMock
from auth0.v3.asyncify import asyncify
from auth0.v3.management import Clients, Guardian, Jobs
clients = re.compile(r"^https://example\.com/api/v2/clients.*")
factors = re.compile(r"^https://example\.com/api/v2/guardian/factors.*")
users_imports = re.compile(r"^https://example\.com/api/v2/jobs/users-imports.*")
payload = {"foo": "bar"}
telemetry = base64.b64encode(
json.dumps(
{
"name": "auth0-python",
"version": sys.modules["auth0"].__version__,
"env": {
"python": platform.python_version(),
},
}
).encode("utf-8")
).decode()
headers = {
"User-Agent": "Python/{}".format(platform.python_version()),
"Authorization": "Bearer jwt",
"Content-Type": "application/json",
"Auth0-Client": telemetry,
}
def get_callback(status=200):
mock = MagicMock(return_value=CallbackResult(status=status, payload=payload))
def callback(url, **kwargs):
return mock(url, **kwargs)
return callback, mock
class TestAsyncify(IsolatedAsyncioTestCase):
@aioresponses()
async def test_get(self, mocked):
callback, mock = get_callback()
mocked.get(clients, callback=callback)
c = asyncify(Clients)(domain="example.com", token="jwt")
self.assertEqual(await c.all_async(), payload)
mock.assert_called_with(
Attrs(path="/api/v2/clients"),
allow_redirects=True,
params={"include_fields": "true"},
headers=headers,
timeout=ANY,
)
@aioresponses()
async def test_post(self, mocked):
callback, mock = get_callback()
mocked.post(clients, callback=callback)
c = asyncify(Clients)(domain="example.com", token="jwt")
data = {"client": 1}
self.assertEqual(await c.create_async(data), payload)
mock.assert_called_with(
Attrs(path="/api/v2/clients"),
allow_redirects=True,
json=data,
headers=headers,
timeout=ANY,
)
@aioresponses()
async def test_file_post(self, mocked):
callback, mock = get_callback()
mocked.post(users_imports, callback=callback)
j = asyncify(Jobs)(domain="example.com", token="jwt")
users = TemporaryFile()
self.assertEqual(await j.import_users_async("connection-1", users), payload)
file_port_headers = headers.copy()
file_port_headers.pop("Content-Type")
mock.assert_called_with(
Attrs(path="/api/v2/jobs/users-imports"),
allow_redirects=True,
data={
"connection_id": "connection-1",
"upsert": "false",
"send_completion_email": "true",
"external_id": None,
"users": users,
},
headers=file_port_headers,
timeout=ANY,
)
users.close()
@aioresponses()
async def test_patch(self, mocked):
callback, mock = get_callback()
mocked.patch(clients, callback=callback)
c = asyncify(Clients)(domain="example.com", token="jwt")
data = {"client": 1}
self.assertEqual(await c.update_async("client-1", data), payload)
mock.assert_called_with(
Attrs(path="/api/v2/clients/client-1"),
allow_redirects=True,
json=data,
headers=headers,
timeout=ANY,
)
@aioresponses()
async def test_put(self, mocked):
callback, mock = get_callback()
mocked.put(factors, callback=callback)
g = asyncify(Guardian)(domain="example.com", token="jwt")
data = {"factor": 1}
self.assertEqual(await g.update_factor_async("factor-1", data), payload)
mock.assert_called_with(
Attrs(path="/api/v2/guardian/factors/factor-1"),
allow_redirects=True,
json=data,
headers=headers,
timeout=ANY,
)
@aioresponses()
async def test_delete(self, mocked):
callback, mock = get_callback()
mocked.delete(clients, callback=callback)
c = asyncify(Clients)(domain="example.com", token="jwt")
self.assertEqual(await c.delete_async("client-1"), payload)
mock.assert_called_with(
Attrs(path="/api/v2/clients/client-1"),
allow_redirects=True,
params={},
json=None,
headers=headers,
timeout=ANY,
)
@aioresponses()
async def test_shared_session(self, mocked):
callback, mock = get_callback()
mocked.get(clients, callback=callback)
async with asyncify(Clients)(domain="example.com", token="jwt") as c:
self.assertEqual(await c.all_async(), payload)
mock.assert_called_with(
Attrs(path="/api/v2/clients"),
allow_redirects=True,
params={"include_fields": "true"},
headers=headers,
timeout=ANY,
)
@aioresponses()
async def test_rate_limit(self, mocked):
callback, mock = get_callback(status=429)
mocked.get(clients, callback=callback)
mocked.get(clients, callback=callback)
mocked.get(clients, callback=callback)
mocked.get(clients, payload=payload)
c = asyncify(Clients)(domain="example.com", token="jwt")
rest_client = c._async_client.client
rest_client._skip_sleep = True
self.assertEqual(await c.all_async(), payload)
self.assertEqual(3, mock.call_count)
(a, b, c) = rest_client._metrics["backoff"]
self.assertTrue(100 <= a < b < c <= 1000)
@aioresponses()
async def test_timeout(self, mocked):
callback, mock = get_callback()
mocked.get(clients, callback=callback)
c = asyncify(Clients)(domain="example.com", token="jwt", timeout=(8.8, 9.9))
self.assertEqual(await c.all_async(), payload)
mock.assert_called_with(
ANY,
allow_redirects=ANY,
params=ANY,
headers=ANY,
timeout=aiohttp.ClientTimeout(sock_connect=8.8, sock_read=9.9),
)
import unittest
import mock
from ...management.branding import Branding
class TestBranding(unittest.TestCase):
def test_init_with_optionals(self):
branding = Branding(
domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2)
)
self.assertEqual(branding.client.options.timeout, (10, 2))
telemetry = branding.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry, None)
@mock.patch("auth0.v3.management.branding.RestClient")
def test_get(self, mock_rc):
api = mock_rc.return_value
branding = Branding(domain="domain", token="jwttoken")
branding.get()
api.get.assert_called_with(
"https://domain/api/v2/branding",
)
@mock.patch("auth0.v3.management.branding.RestClient")
def test_update(self, mock_rc):
api = mock_rc.return_value
api.patch.return_value = {}
branding = Branding(domain="domain", token="jwttoken")
branding.update({"a": "b", "c": "d"})
api.patch.assert_called_with(
"https://domain/api/v2/branding", data={"a": "b", "c": "d"}
)
@mock.patch("auth0.v3.management.branding.RestClient")
def test_get_template_universal_login(self, mock_rc):
api = mock_rc.return_value
branding = Branding(domain="domain", token="jwttoken")
branding.get_template_universal_login()
api.get.assert_called_with(
"https://domain/api/v2/branding/templates/universal-login",
)
@mock.patch("auth0.v3.management.branding.RestClient")
def test_delete_template_universal_login(self, mock_rc):
api = mock_rc.return_value
branding = Branding(domain="domain", token="jwttoken")
branding.delete_template_universal_login()
api.delete.assert_called_with(
"https://domain/api/v2/branding/templates/universal-login",
)
@mock.patch("auth0.v3.management.branding.RestClient")
def test_update_template_universal_login(self, mock_rc):
api = mock_rc.return_value
api.put.return_value = {}
branding = Branding(domain="domain", token="jwttoken")
branding.update_template_universal_login({"a": "b", "c": "d"})
api.put.assert_called_with(
"https://domain/api/v2/branding/templates/universal-login",
type="put_universal-login_body",
body={"template": {"a": "b", "c": "d"}},
)
import sys
def is_async_available():
if sys.version_info >= (3, 6):
try:
import asyncio
import aiohttp
return True
except ImportError:
pass
return False
+49
-1
Metadata-Version: 2.1
Name: auth0-python
Version: 3.22.0
Version: 3.23.0
Summary: Auth0 Python SDK

@@ -345,3 +345,51 @@ Home-page: https://github.com/auth0/auth0-python

=========================
Asynchronous Environments
=========================
This SDK provides async methods built on top of `asyncio <https://docs.python.org/3/library/asyncio.html>`__. To make them available you must have Python >=3.6 and the `aiohttp <https://docs.aiohttp.org/en/stable/>`__ module installed.
Then additional methods with the ``_async`` suffix will be added to modules created by the ``management.Auth0`` class or to classes that are passed to the ``asyncify`` method. For example:
.. code-block:: python
import asyncio
import aiohttp
from auth0.v3.asyncify import asyncify
from auth0.v3.management import Auth0, Users, Connections
from auth0.v3.authentication import Users as AuthUsers
auth0 = Auth0('domain', 'mgmt_api_token')
async def main():
# users = auth0.users.all() <= sync
users = await auth0.users.all_async() # <= async
# To share a session amongst multiple calls to the same service
async with auth0.users as users:
data = await users.get_async(id)
users.update_async(id, data)
# Use asyncify directly on services
Users = asyncify(Users)
Connections = asyncify(Connections)
users = Users(domain, mgmt_api_token)
connections = Connections(domain, mgmt_api_token)
# Create a session and share it among the services
session = aiohttp.ClientSession()
users.set_session(session)
connections.set_session(session)
u = await auth0.users.all_async()
c = await auth0.connections.all_async()
session.close()
# Use auth api
U = asyncify(AuthUsers)
u = U(domain=domain)
await u.userinfo_async(access_token)
asyncio.run(main())
==============

@@ -348,0 +396,0 @@ Supported APIs

@@ -5,3 +5,4 @@ requests>=2.14.0

[test]
coverage
mock>=1.3.0
pre-commit

@@ -6,3 +6,7 @@ LICENSE

auth0/v3/__init__.py
auth0/v3/asyncify.py
auth0/v3/exceptions.py
auth0/v3/rest.py
auth0/v3/rest_async.py
auth0/v3/utils.py
auth0/v3/authentication/__init__.py

@@ -26,2 +30,3 @@ auth0/v3/authentication/authorize_client.py

auth0/v3/management/blacklists.py
auth0/v3/management/branding.py
auth0/v3/management/client_grants.py

@@ -43,3 +48,2 @@ auth0/v3/management/clients.py

auth0/v3/management/resource_servers.py
auth0/v3/management/rest.py
auth0/v3/management/roles.py

@@ -73,2 +77,3 @@ auth0/v3/management/rules.py

auth0/v3/test/management/test_blacklists.py
auth0/v3/test/management/test_branding.py
auth0/v3/test/management/test_client_grants.py

@@ -100,2 +105,4 @@ auth0/v3/test/management/test_clients.py

auth0/v3/test/management/test_users_by_email.py
auth0/v3/test_async/__init__.py
auth0/v3/test_async/test_asyncify.py
auth0_python.egg-info/PKG-INFO

@@ -102,0 +109,0 @@ auth0_python.egg-info/SOURCES.txt

+1
-1

@@ -1,1 +0,1 @@

__version__ = '3.22.0'
__version__ = "3.23.0"
from .exceptions import Auth0Error, RateLimitError, TokenValidationError
__all__ = ("Auth0Error", "RateLimitError", "TokenValidationError")

@@ -11,1 +11,14 @@ from .authorize_client import AuthorizeClient

from .users import Users
__all__ = (
"AuthorizeClient",
"Database",
"Delegated",
"Enterprise",
"GetToken",
"Logout",
"Passwordless",
"RevokeToken",
"Social",
"Users",
)

@@ -12,4 +12,13 @@ from .base import AuthenticationBase

def authorize(self, client_id, audience=None, state=None, redirect_uri=None,
response_type='code', scope='openid', organization=None, invitation=None):
def authorize(
self,
client_id,
audience=None,
state=None,
redirect_uri=None,
response_type="code",
scope="openid",
organization=None,
invitation=None,
):
"""Authorization code grant

@@ -20,14 +29,14 @@

params = {
'client_id': client_id,
'audience': audience,
'response_type': response_type,
'scope': scope,
'state': state,
'redirect_uri': redirect_uri,
'organization': organization,
'invitation': invitation
"client_id": client_id,
"audience": audience,
"response_type": response_type,
"scope": scope,
"state": state,
"redirect_uri": redirect_uri,
"organization": organization,
"invitation": invitation,
}
return self.get(
'{}://{}/authorize'.format(self.protocol, self.domain),
params=params)
"{}://{}/authorize".format(self.protocol, self.domain), params=params
)
import base64
import json
import platform
import sys
import platform
import requests
from auth0.v3.rest import RestClient, RestClientOptions
from ..exceptions import Auth0Error, RateLimitError
UNKNOWN_ERROR = 'a0.sdk.internal.unknown'
UNKNOWN_ERROR = "a0.sdk.internal.unknown"

@@ -25,114 +29,12 @@

self.domain = domain
self.timeout = timeout
self.protocol = protocol
self.base_headers = {'Content-Type': 'application/json'}
self.client = RestClient(
None,
options=RestClientOptions(telemetry=telemetry, timeout=timeout, retries=0),
)
if telemetry:
py_version = platform.python_version()
version = sys.modules['auth0'].__version__
auth0_client = json.dumps({
'name': 'auth0-python',
'version': version,
'env': {
'python': py_version,
}
}).encode('utf-8')
self.base_headers.update({
'User-Agent': 'Python/{}'.format(py_version),
'Auth0-Client': base64.b64encode(auth0_client),
})
def post(self, url, data=None, headers=None):
request_headers = self.base_headers.copy()
request_headers.update(headers or {})
response = requests.post(url=url, json=data, headers=request_headers, timeout=self.timeout)
return self._process_response(response)
return self.client.post(url, data, headers)
def get(self, url, params=None, headers=None):
request_headers = self.base_headers.copy()
request_headers.update(headers or {})
response = requests.get(url=url, params=params, headers=request_headers, timeout=self.timeout)
return self._process_response(response)
def _process_response(self, response):
return self._parse(response).content()
def _parse(self, response):
if not response.text:
return EmptyResponse(response.status_code)
try:
return JsonResponse(response)
except ValueError:
return PlainResponse(response)
class Response(object):
def __init__(self, status_code, content, headers):
self._status_code = status_code
self._content = content
self._headers = headers
def content(self):
if not self._is_error():
return self._content
if self._status_code == 429:
reset_at = int(self._headers.get('x-ratelimit-reset', '-1'))
raise RateLimitError(error_code=self._error_code(),
message=self._error_message(),
reset_at=reset_at)
raise Auth0Error(status_code=self._status_code,
error_code=self._error_code(),
message=self._error_message())
def _is_error(self):
return self._status_code is None or self._status_code >= 400
# Adding these methods to force implementation in subclasses because they are references in this parent class
def _error_code(self):
raise NotImplementedError
def _error_message(self):
raise NotImplementedError
class JsonResponse(Response):
def __init__(self, response):
content = json.loads(response.text)
super(JsonResponse, self).__init__(response.status_code, content, response.headers)
def _error_code(self):
if 'error' in self._content:
return self._content.get('error')
elif 'code' in self._content:
return self._content.get('code')
else:
return UNKNOWN_ERROR
def _error_message(self):
return self._content.get('error_description', '')
class PlainResponse(Response):
def __init__(self, response):
super(PlainResponse, self).__init__(response.status_code, response.text, response.headers)
def _error_code(self):
return UNKNOWN_ERROR
def _error_message(self):
return self._content
class EmptyResponse(Response):
def __init__(self, status_code):
super(EmptyResponse, self).__init__(status_code, '', {})
def _error_code(self):
return UNKNOWN_ERROR
def _error_message(self):
return ''
return self.client.get(url, params, headers)

@@ -13,4 +13,13 @@ import warnings

def login(self, client_id, username, password, connection, id_token=None,
grant_type='password', device=None, scope='openid'):
def login(
self,
client_id,
username,
password,
connection,
id_token=None,
grant_type="password",
device=None,
scope="openid",
):
"""Login using username and password

@@ -24,20 +33,36 @@

"""
warnings.warn("/oauth/ro will be deprecated in future releases", DeprecationWarning)
warnings.warn(
"/oauth/ro will be deprecated in future releases", DeprecationWarning
)
body = {
'client_id': client_id,
'username': username,
'password': password,
'connection': connection,
'grant_type': grant_type,
'scope': scope,
"client_id": client_id,
"username": username,
"password": password,
"connection": connection,
"grant_type": grant_type,
"scope": scope,
}
if id_token:
body.update({'id_token': id_token})
body.update({"id_token": id_token})
if device:
body.update({'device': device})
return self.post('{}://{}/oauth/ro'.format(self.protocol, self.domain), data=body)
body.update({"device": device})
return self.post(
"{}://{}/oauth/ro".format(self.protocol, self.domain), data=body
)
def signup(self, client_id, email, password, connection, username=None, user_metadata=None,
given_name=None, family_name=None, name=None, nickname=None, picture=None):
def signup(
self,
client_id,
email,
password,
connection,
username=None,
user_metadata=None,
given_name=None,
family_name=None,
name=None,
nickname=None,
picture=None,
):
"""Signup using email and password.

@@ -73,39 +98,44 @@

body = {
'client_id': client_id,
'email': email,
'password': password,
'connection': connection,
"client_id": client_id,
"email": email,
"password": password,
"connection": connection,
}
if username:
body.update({'username': username})
body.update({"username": username})
if user_metadata:
body.update({'user_metadata': user_metadata})
body.update({"user_metadata": user_metadata})
if given_name:
body.update({'given_name': given_name})
body.update({"given_name": given_name})
if family_name:
body.update({'family_name': family_name})
body.update({"family_name": family_name})
if name:
body.update({'name': name})
body.update({"name": name})
if nickname:
body.update({'nickname': nickname})
body.update({"nickname": nickname})
if picture:
body.update({'picture': picture})
body.update({"picture": picture})
return self.post('{}://{}/dbconnections/signup'.format(self.protocol, self.domain), data=body)
return self.post(
"{}://{}/dbconnections/signup".format(self.protocol, self.domain), data=body
)
def change_password(self, client_id, email, connection, password=None):
"""Asks to change a password for a given user.
client_id (str): ID of the application to use.
email (str): The user's email address.
client_id (str): ID of the application to use.
connection (str): The name of the database connection where this user should be created.
email (str): The user's email address.
connection (str): The name of the database connection where this user should be created.
"""
body = {
'client_id': client_id,
'email': email,
'connection': connection,
"client_id": client_id,
"email": email,
"connection": connection,
}
return self.post('{}://{}/dbconnections/change_password'.format(self.protocol, self.domain), data=body)
return self.post(
"{}://{}/dbconnections/change_password".format(self.protocol, self.domain),
data=body,
)

@@ -11,28 +11,35 @@ from .base import AuthenticationBase

def get_token(self, client_id, target, api_type, grant_type,
id_token=None, refresh_token=None, scope='openid'):
def get_token(
self,
client_id,
target,
api_type,
grant_type,
id_token=None,
refresh_token=None,
scope="openid",
):
"""Obtain a delegation token.
"""
"""Obtain a delegation token."""
if id_token and refresh_token:
raise ValueError('Only one of id_token or refresh_token '
'can be None')
raise ValueError("Only one of id_token or refresh_token can be None")
data = {
'client_id': client_id,
'grant_type': grant_type,
'target': target,
'scope': scope,
'api_type': api_type,
"client_id": client_id,
"grant_type": grant_type,
"target": target,
"scope": scope,
"api_type": api_type,
}
if id_token:
data.update({'id_token': id_token})
data.update({"id_token": id_token})
elif refresh_token:
data.update({'refresh_token': refresh_token})
data.update({"refresh_token": refresh_token})
else:
raise ValueError('Either id_token or refresh_token must '
'have a value')
raise ValueError("Either id_token or refresh_token must have a value")
return self.post('{}://{}/delegation'.format(self.protocol, self.domain), data=data)
return self.post(
"{}://{}/delegation".format(self.protocol, self.domain), data=data
)

@@ -19,11 +19,13 @@ from .base import AuthenticationBase

return self.get(url='{}://{}/samlp/metadata/{}'.format(self.protocol, self.domain, client_id))
return self.get(
url="{}://{}/samlp/metadata/{}".format(
self.protocol, self.domain, client_id
)
)
def wsfed_metadata(self):
"""Returns the WS-Federation Metadata.
"""
"""Returns the WS-Federation Metadata."""
url = '{}://{}/wsfed/FederationMetadata' \
'/2007-06/FederationMetadata.xml'
url = "{}://{}/wsfed/FederationMetadata/2007-06/FederationMetadata.xml"
return self.get(url=url.format(self.protocol, self.domain))

@@ -12,4 +12,10 @@ from .base import AuthenticationBase

def authorization_code(self, client_id, client_secret, code,
redirect_uri, grant_type='authorization_code'):
def authorization_code(
self,
client_id,
client_secret,
code,
redirect_uri,
grant_type="authorization_code",
):
"""Authorization code grant

@@ -39,14 +45,20 @@

return self.post(
'{}://{}/oauth/token'.format(self.protocol, self.domain),
"{}://{}/oauth/token".format(self.protocol, self.domain),
data={
'client_id': client_id,
'client_secret': client_secret,
'code': code,
'grant_type': grant_type,
'redirect_uri': redirect_uri,
}
"client_id": client_id,
"client_secret": client_secret,
"code": code,
"grant_type": grant_type,
"redirect_uri": redirect_uri,
},
)
def authorization_code_pkce(self, client_id, code_verifier, code,
redirect_uri, grant_type='authorization_code'):
def authorization_code_pkce(
self,
client_id,
code_verifier,
code,
redirect_uri,
grant_type="authorization_code",
):
"""Authorization code pkce grant

@@ -76,14 +88,15 @@

return self.post(
'{}://{}/oauth/token'.format(self.protocol, self.domain),
"{}://{}/oauth/token".format(self.protocol, self.domain),
data={
'client_id': client_id,
'code_verifier': code_verifier,
'code': code,
'grant_type': grant_type,
'redirect_uri': redirect_uri,
}
"client_id": client_id,
"code_verifier": code_verifier,
"code": code,
"grant_type": grant_type,
"redirect_uri": redirect_uri,
},
)
def client_credentials(self, client_id, client_secret, audience,
grant_type='client_credentials'):
def client_credentials(
self, client_id, client_secret, audience, grant_type="client_credentials"
):
"""Client credentials grant

@@ -111,13 +124,22 @@

return self.post(
'{}://{}/oauth/token'.format(self.protocol, self.domain),
"{}://{}/oauth/token".format(self.protocol, self.domain),
data={
'client_id': client_id,
'client_secret': client_secret,
'audience': audience,
'grant_type': grant_type,
}
"client_id": client_id,
"client_secret": client_secret,
"audience": audience,
"grant_type": grant_type,
},
)
def login(self, client_id, client_secret, username, password, scope, realm,
audience, grant_type='http://auth0.com/oauth/grant-type/password-realm'):
def login(
self,
client_id,
client_secret,
username,
password,
scope,
realm,
audience,
grant_type="http://auth0.com/oauth/grant-type/password-realm",
):
"""Calls /oauth/token endpoint with password-realm grant type

@@ -158,16 +180,23 @@

return self.post(
'{}://{}/oauth/token'.format(self.protocol, self.domain),
"{}://{}/oauth/token".format(self.protocol, self.domain),
data={
'client_id': client_id,
'username': username,
'password': password,
'realm': realm,
'client_secret': client_secret,
'scope': scope,
'audience': audience,
'grant_type': grant_type
}
"client_id": client_id,
"username": username,
"password": password,
"realm": realm,
"client_secret": client_secret,
"scope": scope,
"audience": audience,
"grant_type": grant_type,
},
)
def refresh_token(self, client_id, client_secret, refresh_token, grant_type='refresh_token', scope=''):
def refresh_token(
self,
client_id,
client_secret,
refresh_token,
grant_type="refresh_token",
scope="",
):
"""Calls /oauth/token endpoint with refresh token grant type

@@ -195,13 +224,15 @@

return self.post(
'{}://{}/oauth/token'.format(self.protocol, self.domain),
"{}://{}/oauth/token".format(self.protocol, self.domain),
data={
'client_id': client_id,
'client_secret': client_secret,
'refresh_token': refresh_token,
'scope': scope,
'grant_type': grant_type
}
"client_id": client_id,
"client_secret": client_secret,
"refresh_token": refresh_token,
"scope": scope,
"grant_type": grant_type,
},
)
def passwordless_login(self, client_id, client_secret, username, otp, realm, scope, audience):
def passwordless_login(
self, client_id, client_secret, username, otp, realm, scope, audience
):
"""Calls /oauth/token endpoint with http://auth0.com/oauth/grant-type/passwordless/otp grant type

@@ -221,3 +252,3 @@

realm (str): use 'sms' or 'email'.
realm (str): use 'sms' or 'email'.
Should be the same as the one used to start the passwordless flow.

@@ -235,13 +266,13 @@

return self.post(
'{}://{}/oauth/token'.format(self.protocol, self.domain),
"{}://{}/oauth/token".format(self.protocol, self.domain),
data={
'client_id': client_id,
'username': username,
'otp': otp,
'realm': realm,
'client_secret': client_secret,
'scope': scope,
'audience': audience,
'grant_type': 'http://auth0.com/oauth/grant-type/passwordless/otp'
}
)
"client_id": client_id,
"username": username,
"otp": otp,
"realm": realm,
"client_secret": client_secret,
"scope": scope,
"audience": audience,
"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp",
},
)
from .base import AuthenticationBase
try:

@@ -34,10 +35,10 @@ from urllib.parse import quote_plus

return self.get(
'{}://{}/v2/logout?federated&client_id={}&returnTo={}'.format(
self.protocol, self.domain, client_id, return_to)
"{}://{}/v2/logout?federated&client_id={}&returnTo={}".format(
self.protocol, self.domain, client_id, return_to
)
)
return self.get(
'{}://{}/v2/logout?client_id={}&returnTo={}'.format(self.protocol,
self.domain,
client_id,
return_to)
"{}://{}/v2/logout?client_id={}&returnTo={}".format(
self.protocol, self.domain, client_id, return_to
)
)
import warnings
from .base import AuthenticationBase

@@ -13,3 +14,5 @@

def email(self, client_id, email, send='link', auth_params=None, client_secret=None):
def email(
self, client_id, email, send="link", auth_params=None, client_secret=None
):
"""Start flow sending an email.

@@ -42,16 +45,15 @@

data={
'client_id': client_id,
'connection': 'email',
'email': email,
'send': send,
data = {
"client_id": client_id,
"connection": "email",
"email": email,
"send": send,
}
if auth_params:
data.update({'authParams': auth_params})
data.update({"authParams": auth_params})
if client_secret:
data.update({'client_secret': client_secret})
data.update({"client_secret": client_secret})
return self.post(
'{}://{}/passwordless/start'.format(self.protocol, self.domain),
data=data
"{}://{}/passwordless/start".format(self.protocol, self.domain), data=data
)

@@ -62,3 +64,3 @@

Given the user phone number, it will send an SMS with
Given the user phone number, it will send an SMS with
a verification code. You can then authenticate with

@@ -77,16 +79,15 @@ this user using phone number as username and code as password.

data={
'client_id': client_id,
'connection': 'sms',
'phone_number': phone_number,
data = {
"client_id": client_id,
"connection": "sms",
"phone_number": phone_number,
}
if client_secret:
data.update({'client_secret': client_secret})
data.update({"client_secret": client_secret})
return self.post(
'{}://{}/passwordless/start'.format(self.protocol, self.domain),
data=data
"{}://{}/passwordless/start".format(self.protocol, self.domain), data=data
)
def sms_login(self, client_id, phone_number, code, scope='openid'):
def sms_login(self, client_id, phone_number, code, scope="openid"):
"""Login using phone number/verification code.

@@ -103,14 +104,16 @@

"""
warnings.warn("/oauth/ro will be deprecated in future releases", DeprecationWarning)
warnings.warn(
"/oauth/ro will be deprecated in future releases", DeprecationWarning
)
return self.post(
'{}://{}/oauth/ro'.format(self.protocol, self.domain),
"{}://{}/oauth/ro".format(self.protocol, self.domain),
data={
'client_id': client_id,
'connection': 'sms',
'grant_type': 'password',
'username': phone_number,
'password': code,
'scope': scope,
}
"client_id": client_id,
"connection": "sms",
"grant_type": "password",
"username": phone_number,
"password": code,
"scope": scope,
},
)

@@ -13,26 +13,28 @@ from .base import AuthenticationBase

"""Revokes a Refresh Token if it has been compromised
Each revocation request invalidates not only the specific token, but all other tokens
based on the same authorization grant. This means that all Refresh Tokens that have
been issued for the same user, application, and audience will be revoked.
Args:
client_id (str): The Client ID for your Application
Each revocation request invalidates not only the specific token, but all other tokens
based on the same authorization grant. This means that all Refresh Tokens that have
been issued for the same user, application, and audience will be revoked.
token (str): The Refresh Token you want to revoke
Args:
client_id (str): The Client ID for your Application
client_secret (str, optional): The Client Secret for your Application.
Required for confidential applications.
See: https://auth0.com/docs/applications/application-types#confidential-applications
See: https://auth0.com/docs/api/authentication#refresh-token
token (str): The Refresh Token you want to revoke
client_secret (str, optional): The Client Secret for your Application.
Required for confidential applications.
See: https://auth0.com/docs/applications/application-types#confidential-applications
See: https://auth0.com/docs/api/authentication#refresh-token
"""
body = {
'client_id': client_id,
'token': token,
"client_id": client_id,
"token": token,
}
if client_secret:
body.update({'client_secret': client_secret})
body.update({"client_secret": client_secret})
return self.post('{}://{}/oauth/revoke'.format(self.protocol, self.domain), data=body)
return self.post(
"{}://{}/oauth/revoke".format(self.protocol, self.domain), data=body
)

@@ -12,3 +12,3 @@ from .base import AuthenticationBase

def login(self, client_id, access_token, connection, scope='openid'):
def login(self, client_id, access_token, connection, scope="openid"):
"""Login using a social provider's access token

@@ -33,9 +33,9 @@

return self.post(
'{}://{}/oauth/access_token'.format(self.protocol, self.domain),
"{}://{}/oauth/access_token".format(self.protocol, self.domain),
data={
'client_id': client_id,
'access_token': access_token,
'connection': connection,
'scope': scope,
}
"client_id": client_id,
"access_token": access_token,
"connection": connection,
"scope": scope,
},
)

@@ -63,14 +63,19 @@ """Token Verifier module"""

alg = header.get('alg', None)
alg = header.get("alg", None)
if alg != self._algorithm:
raise TokenValidationError(
'Signature algorithm of "{}" is not supported. Expected the token '
'to be signed with "{}"'.format(alg, self._algorithm))
'to be signed with "{}"'.format(alg, self._algorithm)
)
kid = header.get('kid', None)
kid = header.get("kid", None)
secret_or_certificate = self._fetch_key(key_id=kid)
try:
decoded = jwt.decode(jwt=token, key=secret_or_certificate,
algorithms=[self._algorithm], options=self.DISABLE_JWT_CHECKS)
decoded = jwt.decode(
jwt=token,
key=secret_or_certificate,
algorithms=[self._algorithm],
options=self.DISABLE_JWT_CHECKS,
)
except jwt.exceptions.InvalidSignatureError:

@@ -169,3 +174,3 @@ raise TokenValidationError("Invalid token signature.")

for key in jwks['keys']:
for key in jwks["keys"]:
# noinspection PyUnresolvedReferences

@@ -177,3 +182,2 @@ # requirement already includes cryptography -> pyjwt[crypto]

def get_key(self, key_id):

@@ -200,6 +204,8 @@ """Obtains the JWK associated with the given key id.

return keys[key_id]
raise TokenValidationError('RSA Public Key with ID "{}" was not found.'.format(key_id))
raise TokenValidationError(
'RSA Public Key with ID "{}" was not found.'.format(key_id)
)
class TokenVerifier():
class TokenVerifier:
"""Class that verifies ID tokens following the steps defined in the OpenID Connect spec.

@@ -217,4 +223,8 @@ An OpenID Connect ID token is not meant to be consumed until it's verified.

def __init__(self, signature_verifier, issuer, audience, leeway=0):
if not signature_verifier or not isinstance(signature_verifier, SignatureVerifier):
raise TypeError("signature_verifier must be an instance of SignatureVerifier.")
if not signature_verifier or not isinstance(
signature_verifier, SignatureVerifier
):
raise TypeError(
"signature_verifier must be an instance of SignatureVerifier."
)

@@ -267,29 +277,36 @@ self.iss = issuer

# Issuer
if 'iss' not in payload or not isinstance(payload['iss'], (str, ustr)):
raise TokenValidationError('Issuer (iss) claim must be a string present in the ID token')
if payload['iss'] != self.iss:
if "iss" not in payload or not isinstance(payload["iss"], (str, ustr)):
raise TokenValidationError(
"Issuer (iss) claim must be a string present in the ID token"
)
if payload["iss"] != self.iss:
raise TokenValidationError(
'Issuer (iss) claim mismatch in the ID token; expected "{}", '
'found "{}"'.format(self.iss, payload['iss']))
'found "{}"'.format(self.iss, payload["iss"])
)
# Subject
if 'sub' not in payload or not isinstance(payload['sub'], (str, ustr)):
raise TokenValidationError('Subject (sub) claim must be a string present in the ID token')
if "sub" not in payload or not isinstance(payload["sub"], (str, ustr)):
raise TokenValidationError(
"Subject (sub) claim must be a string present in the ID token"
)
# Audience
if 'aud' not in payload or not isinstance(
payload['aud'], (str, ustr, list)
):
if "aud" not in payload or not isinstance(payload["aud"], (str, ustr, list)):
raise TokenValidationError(
'Audience (aud) claim must be a string or array of strings present in the ID token')
"Audience (aud) claim must be a string or array of strings present in"
" the ID token"
)
if isinstance(payload['aud'], list) and self.aud not in payload['aud']:
payload_audiences = ", ".join(payload['aud'])
if isinstance(payload["aud"], list) and self.aud not in payload["aud"]:
payload_audiences = ", ".join(payload["aud"])
raise TokenValidationError(
'Audience (aud) claim mismatch in the ID token; expected "{}" but was '
'not one of "{}"'.format(self.aud, payload_audiences))
elif isinstance(payload['aud'], (str, ustr)) and payload['aud'] != self.aud:
'not one of "{}"'.format(self.aud, payload_audiences)
)
elif isinstance(payload["aud"], (str, ustr)) and payload["aud"] != self.aud:
raise TokenValidationError(
'Audience (aud) claim mismatch in the ID token; expected "{}" '
'but found "{}"'.format(self.aud, payload['aud']))
'but found "{}"'.format(self.aud, payload["aud"])
)

@@ -301,56 +318,76 @@ # --Time validation (epoch)--

# Expires at
if 'exp' not in payload or not isinstance(payload['exp'], int):
raise TokenValidationError('Expiration Time (exp) claim must be a number present in the ID token')
if "exp" not in payload or not isinstance(payload["exp"], int):
raise TokenValidationError(
"Expiration Time (exp) claim must be a number present in the ID token"
)
exp_time = payload['exp'] + leeway
exp_time = payload["exp"] + leeway
if now > exp_time:
raise TokenValidationError(
'Expiration Time (exp) claim error in the ID token; current time ({}) is '
'after expiration time ({})'.format(now, exp_time))
"Expiration Time (exp) claim error in the ID token; current time ({})"
" is after expiration time ({})".format(now, exp_time)
)
# Issued at
if 'iat' not in payload or not isinstance(payload['iat'], int):
raise TokenValidationError('Issued At (iat) claim must be a number present in the ID token')
if "iat" not in payload or not isinstance(payload["iat"], int):
raise TokenValidationError(
"Issued At (iat) claim must be a number present in the ID token"
)
# Nonce
if nonce:
if 'nonce' not in payload or not isinstance(payload['nonce'], (str, ustr)):
raise TokenValidationError('Nonce (nonce) claim must be a string present in the ID token')
if payload['nonce'] != nonce:
if "nonce" not in payload or not isinstance(payload["nonce"], (str, ustr)):
raise TokenValidationError(
"Nonce (nonce) claim must be a string present in the ID token"
)
if payload["nonce"] != nonce:
raise TokenValidationError(
'Nonce (nonce) claim mismatch in the ID token; expected "{}", '
'found "{}"'.format(nonce, payload['nonce']))
'found "{}"'.format(nonce, payload["nonce"])
)
# Organization
if organization:
if 'org_id' not in payload or not isinstance(payload['org_id'], (str, ustr)):
raise TokenValidationError('Organization (org_id) claim must be a string present in the ID token')
if payload['org_id'] != organization:
if "org_id" not in payload or not isinstance(
payload["org_id"], (str, ustr)
):
raise TokenValidationError(
'Organization (org_id) claim mismatch in the ID token; expected "{}", '
'found "{}"'.format(organization, payload['org_id']))
"Organization (org_id) claim must be a string present in the ID"
" token"
)
if payload["org_id"] != organization:
raise TokenValidationError(
"Organization (org_id) claim mismatch in the ID token; expected"
' "{}", found "{}"'.format(organization, payload["org_id"])
)
# Authorized party
if isinstance(payload['aud'], list) and len(payload['aud']) > 1:
if 'azp' not in payload or not isinstance(payload['azp'], (str, ustr)):
if isinstance(payload["aud"], list) and len(payload["aud"]) > 1:
if "azp" not in payload or not isinstance(payload["azp"], (str, ustr)):
raise TokenValidationError(
'Authorized Party (azp) claim must be a string present in the ID token when '
'Audience (aud) claim has multiple values')
if payload['azp'] != self.aud:
"Authorized Party (azp) claim must be a string present in the ID"
" token when Audience (aud) claim has multiple values"
)
if payload["azp"] != self.aud:
raise TokenValidationError(
'Authorized Party (azp) claim mismatch in the ID token; expected "{}", '
'found "{}"'.format(self.aud, payload['azp']))
"Authorized Party (azp) claim mismatch in the ID token; expected"
' "{}", found "{}"'.format(self.aud, payload["azp"])
)
# Authentication time
if max_age:
if 'auth_time' not in payload or not isinstance(payload['auth_time'], int):
if "auth_time" not in payload or not isinstance(payload["auth_time"], int):
raise TokenValidationError(
'Authentication Time (auth_time) claim must be a number present in the ID token '
'when Max Age (max_age) is specified')
"Authentication Time (auth_time) claim must be a number present in"
" the ID token when Max Age (max_age) is specified"
)
auth_valid_until = payload['auth_time'] + max_age + leeway
auth_valid_until = payload["auth_time"] + max_age + leeway
if now > auth_valid_until:
raise TokenValidationError(
'Authentication Time (auth_time) claim in the ID token indicates that too much '
'time has passed since the last end-user authentication. Current time ({}) '
'is after last auth at ({})'.format(now, auth_valid_until))
"Authentication Time (auth_time) claim in the ID token indicates"
" that too much time has passed since the last end-user"
" authentication. Current time ({}) is after last auth at ({})".format(
now, auth_valid_until
)
)

@@ -1,5 +0,6 @@

from .base import AuthenticationBase
import warnings
from .base import AuthenticationBase
class Users(AuthenticationBase):

@@ -26,4 +27,4 @@

return self.get(
url='{}://{}/userinfo'.format(self.protocol, self.domain),
headers={'Authorization': 'Bearer {}'.format(access_token)}
url="{}://{}/userinfo".format(self.protocol, self.domain),
headers={"Authorization": "Bearer {}".format(access_token)},
)

@@ -45,6 +46,8 @@

"""
warnings.warn("/tokeninfo will be deprecated in future releases", DeprecationWarning)
warnings.warn(
"/tokeninfo will be deprecated in future releases", DeprecationWarning
)
return self.post(
url='{}://{}/tokeninfo'.format(self.protocol, self.domain),
data={'id_token': jwt}
url="{}://{}/tokeninfo".format(self.protocol, self.domain),
data={"id_token": jwt},
)

@@ -8,3 +8,3 @@ class Auth0Error(Exception):

def __str__(self):
return '{}: {}'.format(self.status_code, self.message)
return "{}: {}".format(self.status_code, self.message)

@@ -14,3 +14,5 @@

def __init__(self, error_code, message, reset_at):
super(RateLimitError, self).__init__(status_code=429, error_code=error_code, message=message)
super(RateLimitError, self).__init__(
status_code=429, error_code=error_code, message=message
)
self.reset_at = reset_at

@@ -17,0 +19,0 @@

@@ -1,4 +0,4 @@

from .auth0 import Auth0
from .actions import Actions
from .attack_protection import AttackProtection
from .auth0 import Auth0
from .blacklists import Blacklists

@@ -21,4 +21,4 @@ from .client_grants import ClientGrants

from .roles import Roles
from .rules import Rules
from .rules_configs import RulesConfigs
from .rules import Rules
from .stats import Stats

@@ -28,3 +28,34 @@ from .tenants import Tenants

from .user_blocks import UserBlocks
from .users import Users
from .users_by_email import UsersByEmail
from .users import Users
__all__ = (
"Auth0",
"Actions",
"AttackProtection",
"Blacklists",
"ClientGrants",
"Clients",
"Connections",
"CustomDomains",
"DeviceCredentials",
"EmailTemplates",
"Emails",
"Grants",
"Guardian",
"Hooks",
"Jobs",
"LogStreams",
"Logs",
"Organizations",
"ResourceServers",
"Roles",
"RulesConfigs",
"Rules",
"Stats",
"Tenants",
"Tickets",
"UserBlocks",
"UsersByEmail",
"Users",
)

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,15 +26,33 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, *args):
url = '{}://{}/api/v2/actions'.format(self.protocol, self.domain)
url = "{}://{}/api/v2/actions".format(self.protocol, self.domain)
for p in args:
if p is not None:
url = '{}/{}'.format(url, p)
url = "{}/{}".format(url, p)
return url
def get_actions(self, trigger_id=None, action_name=None, deployed=None, installed=False, page=None, per_page=None):
def get_actions(
self,
trigger_id=None,
action_name=None,
deployed=None,
installed=False,
page=None,
per_page=None,
):
"""Get all actions.

@@ -67,11 +85,11 @@

params = {
'triggerId': trigger_id,
'actionName': action_name,
'deployed': deployed,
'installed': str(installed).lower(),
'page': page,
'per_page': per_page
"triggerId": trigger_id,
"actionName": action_name,
"deployed": deployed,
"installed": str(installed).lower(),
"page": page,
"per_page": per_page,
}
return self.client.get(self._url('actions'), params=params)
return self.client.get(self._url("actions"), params=params)

@@ -87,3 +105,3 @@ def create_action(self, body):

return self.client.post(self._url('actions'), data=body)
return self.client.post(self._url("actions"), data=body)

@@ -101,3 +119,3 @@ def update_action(self, id, body):

return self.client.patch(self._url('actions', id), data=body)
return self.client.patch(self._url("actions", id), data=body)

@@ -114,3 +132,3 @@ def get_action(self, id):

return self.client.get(self._url('actions', id), params=params)
return self.client.get(self._url("actions", id), params=params)

@@ -128,7 +146,5 @@ def delete_action(self, id, force=False):

"""
params = {
'force': str(force).lower()
}
params = {"force": str(force).lower()}
return self.client.delete(self._url('actions', id), params=params)
return self.client.delete(self._url("actions", id), params=params)

@@ -142,3 +158,3 @@ def get_triggers(self):

return self.client.get(self._url('triggers'), params=params)
return self.client.get(self._url("triggers"), params=params)

@@ -155,3 +171,3 @@ def get_execution(self, id):

return self.client.get(self._url('executions', id), params=params)
return self.client.get(self._url("executions", id), params=params)

@@ -172,8 +188,5 @@ def get_action_versions(self, id, page=None, per_page=None):

"""
params = {
'page': page,
'per_page': per_page
}
params = {"page": page, "per_page": per_page}
return self.client.get(self._url('actions', id, 'versions'), params=params)
return self.client.get(self._url("actions", id, "versions"), params=params)

@@ -194,7 +207,4 @@ def get_trigger_bindings(self, id, page=None, per_page=None):

"""
params = {
'page': page,
'per_page': per_page
}
return self.client.get(self._url('triggers', id, 'bindings'), params=params)
params = {"page": page, "per_page": per_page}
return self.client.get(self._url("triggers", id, "bindings"), params=params)

@@ -213,3 +223,5 @@ def get_action_version(self, action_id, version_id):

return self.client.get(self._url('actions', action_id, 'versions', version_id), params=params)
return self.client.get(
self._url("actions", action_id, "versions", version_id), params=params
)

@@ -224,3 +236,3 @@ def deploy_action(self, id):

"""
return self.client.post(self._url('actions', id, 'deploy'))
return self.client.post(self._url("actions", id, "deploy"))

@@ -237,4 +249,5 @@ def rollback_action_version(self, action_id, version_id):

"""
params = {}
return self.client.post(self._url('actions', action_id, 'versions', version_id, 'deploy'), data={})
return self.client.post(
self._url("actions", action_id, "versions", version_id, "deploy"), data={}
)

@@ -251,2 +264,2 @@ def update_trigger_bindings(self, id, body):

"""
return self.client.patch(self._url('triggers', id, 'bindings'), data=body)
return self.client.patch(self._url("triggers", id, "bindings"), data=body)

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,9 +26,21 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, component):
return '{}://{}/api/v2/attack-protection/{}'.format(self.protocol, self.domain, component)
return "{}://{}/api/v2/attack-protection/{}".format(
self.protocol, self.domain, component
)

@@ -42,3 +54,3 @@ def get_breached_password_detection(self):

"""
url = self._url('breached-password-detection')
url = self._url("breached-password-detection")
return self.client.get(url)

@@ -57,3 +69,3 @@

"""
url = self._url('breached-password-detection')
url = self._url("breached-password-detection")
return self.client.patch(url, data=body)

@@ -68,3 +80,3 @@

"""
url = self._url('brute-force-protection')
url = self._url("brute-force-protection")
return self.client.get(url)

@@ -83,3 +95,3 @@

"""
url = self._url('brute-force-protection')
url = self._url("brute-force-protection")
return self.client.patch(url, data=body)

@@ -94,3 +106,3 @@

"""
url = self._url('suspicious-ip-throttling')
url = self._url("suspicious-ip-throttling")
return self.client.get(url)

@@ -109,3 +121,3 @@

"""
url = self._url('suspicious-ip-throttling')
url = self._url("suspicious-ip-throttling")
return self.client.patch(url, data=body)

@@ -0,1 +1,2 @@

from ..utils import is_async_available
from .actions import Actions

@@ -30,3 +31,34 @@ from .attack_protection import AttackProtection

modules = {
"actions": Actions,
"attack_protection": AttackProtection,
"blacklists": Blacklists,
"client_grants": ClientGrants,
"clients": Clients,
"connections": Connections,
"custom_domains": CustomDomains,
"device_credentials": DeviceCredentials,
"email_templates": EmailTemplates,
"emails": Emails,
"grants": Grants,
"guardian": Guardian,
"hooks": Hooks,
"jobs": Jobs,
"log_streams": LogStreams,
"logs": Logs,
"organizations": Organizations,
"prompts": Prompts,
"resource_servers": ResourceServers,
"roles": Roles,
"rules_configs": RulesConfigs,
"rules": Rules,
"stats": Stats,
"tenants": Tenants,
"tickets": Tickets,
"user_blocks": UserBlocks,
"users_by_email": UsersByEmail,
"users": Users,
}
class Auth0(object):

@@ -47,29 +79,10 @@ """Provides easy access to all endpoint classes

def __init__(self, domain, token, rest_options=None):
self.actions = Actions(domain=domain, token=token, rest_options=rest_options)
self.attack_protection = AttackProtection(domain=domain, token=token, rest_options=rest_options)
self.blacklists = Blacklists(domain=domain, token=token, rest_options=rest_options)
self.client_grants = ClientGrants(domain=domain, token=token, rest_options=rest_options)
self.clients = Clients(domain=domain, token=token, rest_options=rest_options)
self.connections = Connections(domain=domain, token=token, rest_options=rest_options)
self.custom_domains = CustomDomains(domain=domain, token=token, rest_options=rest_options)
self.device_credentials = DeviceCredentials(domain=domain, token=token, rest_options=rest_options)
self.email_templates = EmailTemplates(domain=domain, token=token, rest_options=rest_options)
self.emails = Emails(domain=domain, token=token, rest_options=rest_options)
self.grants = Grants(domain=domain, token=token, rest_options=rest_options)
self.guardian = Guardian(domain=domain, token=token, rest_options=rest_options)
self.hooks = Hooks(domain=domain, token=token, rest_options=rest_options)
self.jobs = Jobs(domain=domain, token=token, rest_options=rest_options)
self.log_streams = LogStreams(domain=domain, token=token, rest_options=rest_options)
self.logs = Logs(domain=domain, token=token, rest_options=rest_options)
self.organizations = Organizations(domain=domain, token=token, rest_options=rest_options)
self.prompts = Prompts(domain=domain, token=token, rest_options=rest_options)
self.resource_servers = ResourceServers(domain=domain, token=token, rest_options=rest_options)
self.roles = Roles(domain=domain, token=token, rest_options=rest_options)
self.rules_configs = RulesConfigs(domain=domain, token=token, rest_options=rest_options)
self.rules = Rules(domain=domain, token=token, rest_options=rest_options)
self.stats = Stats(domain=domain, token=token, rest_options=rest_options)
self.tenants = Tenants(domain=domain, token=token, rest_options=rest_options)
self.tickets = Tickets(domain=domain, token=token, rest_options=rest_options)
self.user_blocks = UserBlocks(domain=domain, token=token, rest_options=rest_options)
self.users_by_email = UsersByEmail(domain=domain, token=token, rest_options=rest_options)
self.users = Users(domain=domain, token=token, rest_options=rest_options)
if is_async_available():
from ..asyncify import asyncify
for name, cls in modules.items():
cls = asyncify(cls)
setattr(self, name, cls(domain=domain, token=token, rest_options=None))
else:
for name, cls in modules.items():
setattr(self, name, cls(domain=domain, token=token, rest_options=None))

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,5 +26,15 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
self.url = '{}://{}/api/v2/blacklists/tokens'.format(protocol, domain)
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.url = "{}://{}/api/v2/blacklists/tokens".format(protocol, domain)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)

@@ -42,5 +52,3 @@ def get(self, aud=None):

params = {
'aud': aud
}
params = {"aud": aud}

@@ -61,8 +69,8 @@ return self.client.get(self.url, params=params)

body = {
'jti': jti,
"jti": jti,
}
if aud:
body.update({'aud': aud})
body.update({"aud": aud})
return self.client.post(self.url, data=body)

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,14 +26,31 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, id=None):
url = '{}://{}/api/v2/client-grants'.format(self.protocol, self.domain)
url = "{}://{}/api/v2/client-grants".format(self.protocol, self.domain)
if id is not None:
return '{}/{}'.format(url, id)
return "{}/{}".format(url, id)
return url
def all(self, audience=None, page=None, per_page=None, include_totals=False, client_id=None):
def all(
self,
audience=None,
page=None,
per_page=None,
include_totals=False,
client_id=None,
):
"""Retrieves all client grants.

@@ -60,7 +77,7 @@

params = {
'audience': audience,
'page': page,
'per_page': per_page,
'include_totals': str(include_totals).lower(),
'client_id': client_id,
"audience": audience,
"page": page,
"per_page": per_page,
"include_totals": str(include_totals).lower(),
"client_id": client_id,
}

@@ -67,0 +84,0 @@

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,14 +26,31 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, id=None):
url = '{}://{}/api/v2/clients'.format(self.protocol, self.domain)
url = "{}://{}/api/v2/clients".format(self.protocol, self.domain)
if id is not None:
return '{}/{}'.format(url, id)
return "{}/{}".format(url, id)
return url
def all(self, fields=None, include_fields=True, page=None, per_page=None, extra_params=None):
def all(
self,
fields=None,
include_fields=True,
page=None,
per_page=None,
extra_params=None,
):
"""Retrieves a list of all the applications.

@@ -65,6 +82,6 @@

params = extra_params or {}
params['fields'] = fields and ','.join(fields) or None
params['include_fields'] = str(include_fields).lower()
params['page'] = page
params['per_page'] = per_page
params["fields"] = fields and ",".join(fields) or None
params["include_fields"] = str(include_fields).lower()
params["page"] = page
params["per_page"] = per_page

@@ -103,4 +120,6 @@ return self.client.get(self._url(), params=params)

params = {'fields': fields and ','.join(fields) or None,
'include_fields': str(include_fields).lower()}
params = {
"fields": fields and ",".join(fields) or None,
"include_fields": str(include_fields).lower(),
}

@@ -145,5 +164,5 @@ return self.client.get(self._url(id), params=params)

data = {'id': id}
data = {"id": id}
url = self._url('%s/rotate-secret' % id)
url = self._url("%s/rotate-secret" % id)
return self.client.post(url, data=data)

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,14 +26,32 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, id=None):
url = '{}://{}/api/v2/connections'.format(self.protocol, self.domain)
url = "{}://{}/api/v2/connections".format(self.protocol, self.domain)
if id is not None:
return '{}/{}'.format(url, id)
return "{}/{}".format(url, id)
return url
def all(self, strategy=None, fields=None, include_fields=True, page=None, per_page=None, extra_params=None):
def all(
self,
strategy=None,
fields=None,
include_fields=True,
page=None,
per_page=None,
extra_params=None,
):
"""Retrieves all connections.

@@ -69,7 +87,7 @@

params = extra_params or {}
params['strategy'] = strategy or None
params['fields'] = fields and ','.join(fields) or None
params['include_fields'] = str(include_fields).lower()
params['page'] = page
params['per_page'] = per_page
params["strategy"] = strategy or None
params["fields"] = fields and ",".join(fields) or None
params["include_fields"] = str(include_fields).lower()
params["page"] = page
params["per_page"] = per_page

@@ -97,4 +115,6 @@ return self.client.get(self._url(), params=params)

params = {'fields': fields and ','.join(fields) or None,
'include_fields': str(include_fields).lower()}
params = {
"fields": fields and ",".join(fields) or None,
"include_fields": str(include_fields).lower(),
}

@@ -158,2 +178,2 @@ return self.client.get(self._url(id), params=params)

"""
return self.client.delete(self._url(id) + '/users', params={'email': email})
return self.client.delete(self._url(id) + "/users", params={"email": email})

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,11 +26,21 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, id=None):
url = '{}://{}/api/v2/custom-domains'.format(self.protocol, self.domain)
url = "{}://{}/api/v2/custom-domains".format(self.protocol, self.domain)
if id is not None:
return url + '/' + id
return url + "/" + id
return url

@@ -50,3 +60,3 @@

"""
url = self._url('%s' % (id))
url = self._url("%s" % (id))
return self.client.get(url)

@@ -62,3 +72,3 @@

"""
url = self._url('%s' % (id))
url = self._url("%s" % (id))
return self.client.delete(url)

@@ -84,3 +94,3 @@

"""
url = self._url('%s/verify' % (id))
url = self._url("%s/verify" % (id))
return self.client.post(url)

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,14 +26,34 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, id=None):
url = '{}://{}/api/v2/device-credentials'.format(self.protocol, self.domain)
url = "{}://{}/api/v2/device-credentials".format(self.protocol, self.domain)
if id is not None:
return '{}/{}'.format(url, id)
return "{}/{}".format(url, id)
return url
def get(self, user_id, client_id, type, fields=None, include_fields=True, page=None, per_page=None, include_totals=False):
def get(
self,
user_id,
client_id,
type,
fields=None,
include_fields=True,
page=None,
per_page=None,
include_totals=False,
):
"""List device credentials.

@@ -67,10 +87,10 @@

params = {
'fields': fields and ','.join(fields) or None,
'include_fields': str(include_fields).lower(),
'user_id': user_id,
'client_id': client_id,
'type': type,
'page': page,
'per_page': per_page,
'include_totals': str(include_totals).lower()
"fields": fields and ",".join(fields) or None,
"include_fields": str(include_fields).lower(),
"user_id": user_id,
"client_id": client_id,
"type": type,
"page": page,
"per_page": per_page,
"include_totals": str(include_totals).lower(),
}

@@ -77,0 +97,0 @@ return self.client.get(self._url(), params=params)

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,11 +26,21 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, id=None):
url = '{}://{}/api/v2/email-templates'.format(self.protocol, self.domain)
url = "{}://{}/api/v2/email-templates".format(self.protocol, self.domain)
if id is not None:
return '{}/{}'.format(url, id)
return "{}/{}".format(url, id)
return url

@@ -37,0 +47,0 @@

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,11 +26,21 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, id=None):
url = '{}://{}/api/v2/emails/provider'.format(self.protocol, self.domain)
url = "{}://{}/api/v2/emails/provider".format(self.protocol, self.domain)
if id is not None:
return '{}/{}'.format(url, id)
return "{}/{}".format(url, id)
return url

@@ -51,4 +61,6 @@

"""
params = {'fields': fields and ','.join(fields) or None,
'include_fields': str(include_fields).lower()}
params = {
"fields": fields and ",".join(fields) or None,
"include_fields": str(include_fields).lower(),
}

@@ -55,0 +67,0 @@ return self.client.get(self._url(), params=params)

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,11 +26,21 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, id=None):
url = '{}://{}/api/v2/grants'.format(self.protocol, self.domain)
url = "{}://{}/api/v2/grants".format(self.protocol, self.domain)
if id is not None:
return url + '/' + id
return url + "/" + id
return url

@@ -58,7 +68,9 @@

params = extra_params or {}
params.update({
'page': page,
'per_page': per_page,
'include_totals': str(include_totals).lower()
})
params.update(
{
"page": page,
"per_page": per_page,
"include_totals": str(include_totals).lower(),
}
)

@@ -75,3 +87,3 @@ return self.client.get(self._url(), params=params)

"""
url = self._url('%s' % (id))
url = self._url("%s" % (id))
return self.client.delete(url)

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,11 +26,21 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, id=None):
url = '{}://{}/api/v2/guardian'.format(self.protocol, self.domain)
url = "{}://{}/api/v2/guardian".format(self.protocol, self.domain)
if id is not None:
return '{}/{}'.format(url, id)
return "{}/{}".format(url, id)
return url

@@ -45,3 +55,3 @@

return self.client.get(self._url('factors'))
return self.client.get(self._url("factors"))

@@ -59,3 +69,3 @@ def update_factor(self, name, body):

"""
url = self._url('factors/{}'.format(name))
url = self._url("factors/{}".format(name))
return self.client.put(url, data=body)

@@ -74,3 +84,3 @@

return self.client.put(self._url('factors/sms/templates'), data=body)
return self.client.put(self._url("factors/sms/templates"), data=body)

@@ -86,3 +96,3 @@ def get_templates(self):

return self.client.get(self._url('factors/sms/templates'))
return self.client.get(self._url("factors/sms/templates"))

@@ -98,3 +108,3 @@ def get_enrollment(self, id):

"""
url = self._url('enrollments/{}'.format(id))
url = self._url("enrollments/{}".format(id))
return self.client.get(url)

@@ -112,3 +122,3 @@

"""
url = self._url('enrollments/{}'.format(id))
url = self._url("enrollments/{}".format(id))
return self.client.delete(url)

@@ -127,3 +137,3 @@

"""
return self.client.post(self._url('enrollments/ticket'), data=body)
return self.client.post(self._url("enrollments/ticket"), data=body)

@@ -143,3 +153,3 @@ def get_factor_providers(self, factor_name, name):

"""
url = self._url('factors/{}/providers/{}'.format(factor_name, name))
url = self._url("factors/{}/providers/{}".format(factor_name, name))
return self.client.get(url)

@@ -161,3 +171,3 @@

"""
url = self._url('factors/{}/providers/{}'.format(factor_name, name))
url = self._url("factors/{}/providers/{}".format(factor_name, name))
return self.client.put(url, data=body)

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -27,6 +27,16 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)

@@ -33,0 +43,0 @@ def _url(self, id=None):

@@ -1,5 +0,6 @@

from .rest import RestClient
import warnings
from ..rest import RestClient
class Jobs(object):

@@ -27,11 +28,21 @@ """Auth0 jobs endpoints

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, path=None):
url = '{}://{}/api/v2/jobs'.format(self.protocol, self.domain)
url = "{}://{}/api/v2/jobs".format(self.protocol, self.domain)
if path is not None:
return '{}/{}'.format(url, path)
return "{}/{}".format(url, path)
return url

@@ -57,3 +68,3 @@

"""
url = self._url('{}/errors'.format(id))
url = self._url("{}/errors".format(id))
return self.client.get(url)

@@ -73,3 +84,7 @@

"""
warnings.warn("/jobs/{id}/results is no longer available. The get(id) function will be called instead.", DeprecationWarning)
warnings.warn(
"/jobs/{id}/results is no longer available. The get(id) function will be"
" called instead.",
DeprecationWarning,
)
return self.get(job_id)

@@ -88,5 +103,12 @@

"""
return self.client.post(self._url('users-exports'), data=body)
return self.client.post(self._url("users-exports"), data=body)
def import_users(self, connection_id, file_obj, upsert=False, send_completion_email=True, external_id=None):
def import_users(
self,
connection_id,
file_obj,
upsert=False,
send_completion_email=True,
external_id=None,
):
"""Imports users to a connection from a file.

@@ -114,8 +136,12 @@

"""
return self.client.file_post(self._url('users-imports'),
data={'connection_id': connection_id,
'upsert': str(upsert).lower(),
'send_completion_email': str(send_completion_email).lower(),
'external_id': external_id},
files={'users': file_obj})
return self.client.file_post(
self._url("users-imports"),
data={
"connection_id": connection_id,
"upsert": str(upsert).lower(),
"send_completion_email": str(send_completion_email).lower(),
"external_id": external_id,
},
files={"users": file_obj},
)

@@ -133,2 +159,2 @@ def send_verification_email(self, body):

"""
return self.client.post(self._url('verification-email'), data=body)
return self.client.post(self._url("verification-email"), data=body)

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,11 +26,21 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, id=None):
url = '{}://{}/api/v2/log-streams'.format(self.protocol, self.domain)
url = "{}://{}/api/v2/log-streams".format(self.protocol, self.domain)
if id is not None:
return '{}/{}'.format(url, id)
return "{}/{}".format(url, id)
return url

@@ -37,0 +47,0 @@

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,16 +26,35 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, id=None):
url = '{}://{}/api/v2/logs'.format(self.protocol, self.domain)
url = "{}://{}/api/v2/logs".format(self.protocol, self.domain)
if id is not None:
return '{}/{}'.format(url, id)
return "{}/{}".format(url, id)
return url
def search(self, page=0, per_page=50, sort=None, q=None,
include_totals=True, fields=None, from_param=None, take=None,
include_fields=True):
def search(
self,
page=0,
per_page=50,
sort=None,
q=None,
include_totals=True,
fields=None,
from_param=None,
take=None,
include_fields=True,
):
"""Search log events.

@@ -75,11 +94,11 @@

params = {
'per_page': per_page,
'page': page,
'include_totals': str(include_totals).lower(),
'sort': sort,
'fields': fields and ','.join(fields) or None,
'include_fields': str(include_fields).lower(),
'q': q,
'from': from_param,
'take': take
"per_page": per_page,
"page": page,
"include_totals": str(include_totals).lower(),
"sort": sort,
"fields": fields and ",".join(fields) or None,
"include_fields": str(include_fields).lower(),
"q": q,
"from": from_param,
"take": take,
}

@@ -86,0 +105,0 @@ return self.client.get(self._url(), params=params)

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,16 +26,28 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, *args):
url = '{}://{}/api/v2/organizations'.format(self.protocol, self.domain)
url = "{}://{}/api/v2/organizations".format(self.protocol, self.domain)
for p in args:
if p is not None:
url = '{}/{}'.format(url, p)
url = "{}/{}".format(url, p)
return url
# Organizations
def all_organizations(self, page=None, per_page=None, include_totals=True, from_param=None, take=None):
def all_organizations(
self, page=None, per_page=None, include_totals=True, from_param=None, take=None
):
"""Retrieves a list of all the organizations.

@@ -63,7 +75,7 @@

params = {
'page': page,
'per_page': per_page,
'include_totals': str(include_totals).lower(),
'from': from_param,
'take': take
"page": page,
"per_page": per_page,
"include_totals": str(include_totals).lower(),
"from": from_param,
"take": take,
}

@@ -83,3 +95,3 @@

return self.client.get(self._url('name', name), params=params)
return self.client.get(self._url("name", name), params=params)

@@ -133,3 +145,2 @@ def get_organization(self, id):

# Organization Connections

@@ -150,4 +161,4 @@ def all_organization_connections(self, id, page=None, per_page=None):

"""
params = {'page': page, 'per_page': per_page}
return self.client.get(self._url(id, 'enabled_connections'), params=params)
params = {"page": page, "per_page": per_page}
return self.client.get(self._url(id, "enabled_connections"), params=params)

@@ -166,3 +177,5 @@ def get_organization_connection(self, id, connection_id):

return self.client.get(self._url(id, 'enabled_connections', connection_id), params=params)
return self.client.get(
self._url(id, "enabled_connections", connection_id), params=params
)

@@ -180,3 +193,3 @@ def create_organization_connection(self, id, body):

return self.client.post(self._url(id, 'enabled_connections'), data=body)
return self.client.post(self._url(id, "enabled_connections"), data=body)

@@ -196,3 +209,5 @@ def update_organization_connection(self, id, connection_id, body):

return self.client.patch(self._url(id, 'enabled_connections', connection_id), data=body)
return self.client.patch(
self._url(id, "enabled_connections", connection_id), data=body
)

@@ -210,6 +225,14 @@ def delete_organization_connection(self, id, connection_id):

return self.client.delete(self._url(id, 'enabled_connections', connection_id))
return self.client.delete(self._url(id, "enabled_connections", connection_id))
# Organization Members
def all_organization_members(self, id, page=None, per_page=None, include_totals=True, from_param=None, take=None):
def all_organization_members(
self,
id,
page=None,
per_page=None,
include_totals=True,
from_param=None,
take=None,
):
"""Retrieves a list of all the organization members.

@@ -239,10 +262,10 @@

params = {
'page': page,
'per_page': per_page,
'include_totals': str(include_totals).lower(),
'from': from_param,
'take': take
"page": page,
"per_page": per_page,
"include_totals": str(include_totals).lower(),
"from": from_param,
"take": take,
}
return self.client.get(self._url(id, 'members'), params=params)
return self.client.get(self._url(id, "members"), params=params)

@@ -260,3 +283,3 @@ def create_organization_members(self, id, body):

return self.client.post(self._url(id, 'members'), data=body)
return self.client.post(self._url(id, "members"), data=body)

@@ -274,3 +297,3 @@ def delete_organization_members(self, id, body):

return self.client.delete(self._url(id, 'members'), data=body)
return self.client.delete(self._url(id, "members"), data=body)

@@ -294,4 +317,6 @@ # Organization Member Roles

"""
params = {'page': page, 'per_page': per_page}
return self.client.get(self._url(id, 'members', user_id, 'roles'), params=params)
params = {"page": page, "per_page": per_page}
return self.client.get(
self._url(id, "members", user_id, "roles"), params=params
)

@@ -311,3 +336,3 @@ def create_organization_member_roles(self, id, user_id, body):

return self.client.post(self._url(id, 'members', user_id, 'roles'), data=body)
return self.client.post(self._url(id, "members", user_id, "roles"), data=body)

@@ -327,5 +352,4 @@ def delete_organization_member_roles(self, id, user_id, body):

return self.client.delete(self._url(id, 'members', user_id, 'roles'), data=body)
return self.client.delete(self._url(id, "members", user_id, "roles"), data=body)
# Organization Invitations

@@ -346,4 +370,4 @@ def all_organization_invitations(self, id, page=None, per_page=None):

"""
params = {'page': page, 'per_page': per_page}
return self.client.get(self._url(id, 'invitations'), params=params)
params = {"page": page, "per_page": per_page}
return self.client.get(self._url(id, "invitations"), params=params)

@@ -362,3 +386,5 @@ def get_organization_invitation(self, id, invitaton_id):

return self.client.get(self._url(id, 'invitations', invitaton_id), params=params)
return self.client.get(
self._url(id, "invitations", invitaton_id), params=params
)

@@ -376,3 +402,3 @@ def create_organization_invitation(self, id, body):

return self.client.post(self._url(id, 'invitations'), data=body)
return self.client.post(self._url(id, "invitations"), data=body)

@@ -390,2 +416,2 @@ def delete_organization_invitation(self, id, invitation_id):

return self.client.delete(self._url(id, 'invitations', invitation_id))
return self.client.delete(self._url(id, "invitations", invitation_id))

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,6 +26,16 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)

@@ -32,0 +42,0 @@ def _url(self, prompt=None, language=None):

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,11 +26,21 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, id=None):
url = '{}://{}/api/v2/resource-servers'.format(self.protocol, self.domain)
url = "{}://{}/api/v2/resource-servers".format(self.protocol, self.domain)
if id is not None:
return '{}/{}'.format(url, id)
return "{}/{}".format(url, id)
return url

@@ -67,5 +77,5 @@

params = {
'page': page,
'per_page': per_page,
'include_totals': str(include_totals).lower()
"page": page,
"per_page": per_page,
"include_totals": str(include_totals).lower(),
}

@@ -72,0 +82,0 @@

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,11 +26,21 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, id=None):
url = '{}://{}/api/v2/roles'.format(self.protocol, self.domain)
url = "{}://{}/api/v2/roles".format(self.protocol, self.domain)
if id is not None:
return '{}/{}'.format(url, id)
return "{}/{}".format(url, id)
return url

@@ -57,6 +67,6 @@

params = {
'per_page': per_page,
'page': page,
'include_totals': str(include_totals).lower(),
'name_filter': name_filter
"per_page": per_page,
"page": page,
"include_totals": str(include_totals).lower(),
"name_filter": name_filter,
}

@@ -108,3 +118,5 @@ return self.client.get(self._url(), params=params)

def list_users(self, id, page=0, per_page=25, include_totals=True, from_param=None, take=None):
def list_users(
self, id, page=0, per_page=25, include_totals=True, from_param=None, take=None
):
"""List the users that have been associated with a given role.

@@ -134,10 +146,10 @@

params = {
'per_page': per_page,
'page': page,
'include_totals': str(include_totals).lower(),
'from': from_param,
'take': take
"per_page": per_page,
"page": page,
"include_totals": str(include_totals).lower(),
"from": from_param,
"take": take,
}
url = self._url('{}/users'.format(id))
url = self._url("{}/users".format(id))
return self.client.get(url, params=params)

@@ -155,4 +167,4 @@

"""
url = self._url('{}/users'.format(id))
body = {'users': users}
url = self._url("{}/users".format(id))
body = {"users": users}
return self.client.post(url, data=body)

@@ -178,7 +190,7 @@

params = {
'per_page': per_page,
'page': page,
'include_totals': str(include_totals).lower()
"per_page": per_page,
"page": page,
"include_totals": str(include_totals).lower(),
}
url = self._url('{}/permissions'.format(id))
url = self._url("{}/permissions".format(id))
return self.client.get(url, params=params)

@@ -196,4 +208,4 @@

"""
url = self._url('{}/permissions'.format(id))
body = {'permissions': permissions}
url = self._url("{}/permissions".format(id))
body = {"permissions": permissions}
return self.client.delete(url, data=body)

@@ -211,4 +223,4 @@

"""
url = self._url('{}/permissions'.format(id))
body = {'permissions': permissions}
url = self._url("{}/permissions".format(id))
body = {"permissions": permissions}
return self.client.post(url, data=body)

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,11 +26,21 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, id=None):
url = '{}://{}/api/v2/rules-configs'.format(self.protocol, self.domain)
url = "{}://{}/api/v2/rules-configs".format(self.protocol, self.domain)
if id is not None:
return url + '/' + id
return url + "/" + id
return url

@@ -65,4 +75,4 @@

"""
url = self._url('{}'.format(key))
body = {'value': value}
url = self._url("{}".format(key))
body = {"value": value}
return self.client.put(url, data=body)

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,15 +26,33 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, id=None):
url = '{}://{}/api/v2/rules'.format(self.protocol, self.domain)
url = "{}://{}/api/v2/rules".format(self.protocol, self.domain)
if id is not None:
return '{}/{}'.format(url, id)
return "{}/{}".format(url, id)
return url
def all(self, stage='login_success', enabled=True, fields=None,
include_fields=True, page=None, per_page=None, include_totals=False):
def all(
self,
stage="login_success",
enabled=True,
fields=None,
include_fields=True,
page=None,
per_page=None,
include_totals=False,
):
"""Retrieves a list of all rules.

@@ -69,8 +87,8 @@

params = {
'stage': stage,
'fields': fields and ','.join(fields) or None,
'include_fields': str(include_fields).lower(),
'page': page,
'per_page': per_page,
'include_totals': str(include_totals).lower()
"stage": stage,
"fields": fields and ",".join(fields) or None,
"include_fields": str(include_fields).lower(),
"page": page,
"per_page": per_page,
"include_totals": str(include_totals).lower(),
}

@@ -80,3 +98,3 @@

if enabled is not None:
params['enabled'] = str(enabled).lower()
params["enabled"] = str(enabled).lower()

@@ -110,4 +128,6 @@ return self.client.get(self._url(), params=params)

"""
params = {'fields': fields and ','.join(fields) or None,
'include_fields': str(include_fields).lower()}
params = {
"fields": fields and ",".join(fields) or None,
"include_fields": str(include_fields).lower(),
}
return self.client.get(self._url(id), params=params)

@@ -114,0 +134,0 @@

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,9 +26,19 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, action):
return '{}://{}/api/v2/stats/{}'.format(self.protocol, self.domain, action)
return "{}://{}/api/v2/stats/{}".format(self.protocol, self.domain, action)

@@ -43,3 +53,3 @@ def active_users(self):

return self.client.get(self._url('active-users'))
return self.client.get(self._url("active-users"))

@@ -59,3 +69,4 @@ def daily_stats(self, from_date=None, to_date=None):

return self.client.get(self._url('daily'), params={'from': from_date,
'to': to_date})
return self.client.get(
self._url("daily"), params={"from": from_date, "to": to_date}
)

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,9 +26,19 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self):
return '{}://{}/api/v2/tenants/settings'.format(self.protocol, self.domain)
return "{}://{}/api/v2/tenants/settings".format(self.protocol, self.domain)

@@ -49,4 +59,6 @@ def get(self, fields=None, include_fields=True):

params = {'fields': fields and ','.join(fields) or None,
'include_fields': str(include_fields).lower()}
params = {
"fields": fields and ",".join(fields) or None,
"include_fields": str(include_fields).lower(),
}

@@ -53,0 +65,0 @@ return self.client.get(self._url(), params=params)

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,9 +26,19 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, action):
return '{}://{}/api/v2/tickets/{}'.format(self.protocol, self.domain, action)
return "{}://{}/api/v2/tickets/{}".format(self.protocol, self.domain, action)

@@ -43,3 +53,3 @@ def create_email_verification(self, body):

"""
return self.client.post(self._url('email-verification'), data=body)
return self.client.post(self._url("email-verification"), data=body)

@@ -54,2 +64,2 @@ def create_pswd_change(self, body):

"""
return self.client.post(self._url('password-change'), data=body)
return self.client.post(self._url("password-change"), data=body)

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,11 +26,21 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, id=None):
url = '{}://{}/api/v2/user-blocks'.format(self.protocol, self.domain)
url = "{}://{}/api/v2/user-blocks".format(self.protocol, self.domain)
if id is not None:
return '{}/{}'.format(url, id)
return "{}/{}".format(url, id)
return url

@@ -47,3 +57,3 @@

params = {'identifier': identifier}
params = {"identifier": identifier}

@@ -61,3 +71,3 @@ return self.client.get(self._url(), params=params)

params = {'identifier': identifier}
params = {"identifier": identifier}

@@ -64,0 +74,0 @@ return self.client.delete(self._url(), params=params)

@@ -1,2 +0,2 @@

from .rest import RestClient
from ..rest import RestClient

@@ -26,9 +26,19 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self):
return '{}://{}/api/v2/users-by-email'.format(self.protocol, self.domain)
return "{}://{}/api/v2/users-by-email".format(self.protocol, self.domain)

@@ -52,6 +62,6 @@ def search_users_by_email(self, email, fields=None, include_fields=True):

params = {
'email': email,
'fields': fields and ','.join(fields) or None,
'include_fields': str(include_fields).lower()
"email": email,
"fields": fields and ",".join(fields) or None,
"include_fields": str(include_fields).lower(),
}
return self.client.get(self._url(), params=params)
import warnings
from .rest import RestClient
from ..rest import RestClient

@@ -28,16 +28,35 @@

def __init__(self, domain, token, telemetry=True, timeout=5.0, protocol="https", rest_options=None):
def __init__(
self,
domain,
token,
telemetry=True,
timeout=5.0,
protocol="https",
rest_options=None,
):
self.domain = domain
self.protocol = protocol
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options)
self.client = RestClient(
jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
)
def _url(self, id=None):
url = '{}://{}/api/v2/users'.format(self.protocol, self.domain)
url = "{}://{}/api/v2/users".format(self.protocol, self.domain)
if id is not None:
return '{}/{}'.format(url, id)
return "{}/{}".format(url, id)
return url
def list(self, page=0, per_page=25, sort=None, connection=None, q=None,
search_engine=None, include_totals=True, fields=None,
include_fields=True):
def list(
self,
page=0,
per_page=25,
sort=None,
connection=None,
q=None,
search_engine=None,
include_totals=True,
fields=None,
include_fields=True,
):
"""List or search users.

@@ -79,11 +98,11 @@

params = {
'per_page': per_page,
'page': page,
'include_totals': str(include_totals).lower(),
'sort': sort,
'connection': connection,
'fields': fields and ','.join(fields) or None,
'include_fields': str(include_fields).lower(),
'q': q,
'search_engine': search_engine
"per_page": per_page,
"page": page,
"include_totals": str(include_totals).lower(),
"sort": sort,
"connection": connection,
"fields": fields and ",".join(fields) or None,
"include_fields": str(include_fields).lower(),
"q": q,
"search_engine": search_engine,
}

@@ -108,3 +127,5 @@ return self.client.get(self._url(), params=params)

"""
warnings.warn("DELETE all users endpoint is no longer available.", DeprecationWarning)
warnings.warn(
"DELETE all users endpoint is no longer available.", DeprecationWarning
)
return self.client.delete(self._url())

@@ -128,4 +149,4 @@

params = {
'fields': fields and ','.join(fields) or None,
'include_fields': str(include_fields).lower()
"fields": fields and ",".join(fields) or None,
"include_fields": str(include_fields).lower(),
}

@@ -175,8 +196,8 @@

params = {
'per_page': per_page,
'page': page,
'include_totals': str(include_totals).lower()
"per_page": per_page,
"page": page,
"include_totals": str(include_totals).lower(),
}
url = self._url('{}/organizations'.format(id))
url = self._url("{}/organizations".format(id))
return self.client.get(url, params=params)

@@ -202,8 +223,8 @@

params = {
'per_page': per_page,
'page': page,
'include_totals': str(include_totals).lower()
"per_page": per_page,
"page": page,
"include_totals": str(include_totals).lower(),
}
url = self._url('{}/roles'.format(id))
url = self._url("{}/roles".format(id))
return self.client.get(url, params=params)

@@ -221,4 +242,4 @@

"""
url = self._url('{}/roles'.format(id))
body = {'roles': roles}
url = self._url("{}/roles".format(id))
body = {"roles": roles}
return self.client.delete(url, data=body)

@@ -236,4 +257,4 @@

"""
url = self._url('{}/roles'.format(id))
body = {'roles': roles}
url = self._url("{}/roles".format(id))
body = {"roles": roles}
return self.client.post(url, data=body)

@@ -260,7 +281,7 @@

params = {
'per_page': per_page,
'page': page,
'include_totals': str(include_totals).lower()
"per_page": per_page,
"page": page,
"include_totals": str(include_totals).lower(),
}
url = self._url('{}/permissions'.format(id))
url = self._url("{}/permissions".format(id))
return self.client.get(url, params=params)

@@ -278,4 +299,4 @@

"""
url = self._url('{}/permissions'.format(id))
body = {'permissions': permissions}
url = self._url("{}/permissions".format(id))
body = {"permissions": permissions}
return self.client.delete(url, data=body)

@@ -293,4 +314,4 @@

"""
url = self._url('{}/permissions'.format(id))
body = {'permissions': permissions}
url = self._url("{}/permissions".format(id))
body = {"permissions": permissions}
return self.client.post(url, data=body)

@@ -309,3 +330,3 @@

"""
url = self._url('{}/multifactor/{}'.format(id, provider))
url = self._url("{}/multifactor/{}".format(id, provider))
return self.client.delete(url)

@@ -321,3 +342,3 @@

"""
url = self._url('{}/authenticators'.format(id))
url = self._url("{}/authenticators".format(id))
return self.client.delete(url)

@@ -337,3 +358,3 @@

"""
url = self._url('{}/identities/{}/{}'.format(id, provider, user_id))
url = self._url("{}/identities/{}/{}".format(id, provider, user_id))
return self.client.delete(url)

@@ -355,3 +376,3 @@

"""
url = self._url('{}/identities'.format(user_id))
url = self._url("{}/identities".format(user_id))
return self.client.post(url, data=body)

@@ -367,3 +388,3 @@

"""
url = self._url('{}/recovery-code-regeneration'.format(user_id))
url = self._url("{}/recovery-code-regeneration".format(user_id))
return self.client.post(url)

@@ -379,7 +400,8 @@

"""
url = self._url('{}/enrollments'.format(user_id))
url = self._url("{}/enrollments".format(user_id))
return self.client.get(url)
def get_log_events(self, user_id, page=0, per_page=50, sort=None,
include_totals=False):
def get_log_events(
self, user_id, page=0, per_page=50, sort=None, include_totals=False
):
"""Retrieve every log event for a specific user id.

@@ -408,9 +430,9 @@

params = {
'per_page': per_page,
'page': page,
'include_totals': str(include_totals).lower(),
'sort': sort
"per_page": per_page,
"page": page,
"include_totals": str(include_totals).lower(),
"sort": sort,
}
url = self._url('{}/logs'.format(user_id))
url = self._url("{}/logs".format(user_id))
return self.client.get(url, params=params)

@@ -427,3 +449,5 @@

url = self._url('{}/multifactor/actions/invalidate-remember-browser'.format(user_id))
url = self._url(
"{}/multifactor/actions/invalidate-remember-browser".format(user_id)
)
return self.client.post(url)
import unittest
import mock
from ...authentication.authorize_client import AuthorizeClient

@@ -7,50 +9,57 @@

class TestAuthorizeClient(unittest.TestCase):
@mock.patch('auth0.v3.authentication.authorize_client.AuthorizeClient.get')
@mock.patch("auth0.v3.authentication.authorize_client.AuthorizeClient.get")
def test_login(self, mock_get):
a = AuthorizeClient('my.domain.com')
a = AuthorizeClient("my.domain.com")
a.authorize(client_id='cid',
audience='https://test.com/api',
state='st',
redirect_uri='http://localhost',
response_type='token',
scope='openid profile',
organization='org_123',
invitation='invitation_abc')
a.authorize(
client_id="cid",
audience="https://test.com/api",
state="st",
redirect_uri="http://localhost",
response_type="token",
scope="openid profile",
organization="org_123",
invitation="invitation_abc",
)
args, kwargs = mock_get.call_args
self.assertEqual(args[0], 'https://my.domain.com/authorize')
self.assertEqual(kwargs['params'], {
'client_id': 'cid',
'audience': 'https://test.com/api',
'state': 'st',
'redirect_uri': 'http://localhost',
'response_type': 'token',
'scope': 'openid profile',
'organization': 'org_123',
'invitation': 'invitation_abc'
})
self.assertEqual(args[0], "https://my.domain.com/authorize")
self.assertEqual(
kwargs["params"],
{
"client_id": "cid",
"audience": "https://test.com/api",
"state": "st",
"redirect_uri": "http://localhost",
"response_type": "token",
"scope": "openid profile",
"organization": "org_123",
"invitation": "invitation_abc",
},
)
@mock.patch('auth0.v3.authentication.authorize_client.AuthorizeClient.get')
@mock.patch("auth0.v3.authentication.authorize_client.AuthorizeClient.get")
def test_login_default_param_values(self, mock_get):
a = AuthorizeClient('my.domain.com')
a = AuthorizeClient("my.domain.com")
a.authorize(client_id='cid')
a.authorize(client_id="cid")
args, kwargs = mock_get.call_args
self.assertEqual(args[0], 'https://my.domain.com/authorize')
self.assertEqual(kwargs['params'], {
'audience': None,
'invitation': None,
'organization': None,
'redirect_uri': None,
'state': None,
'client_id': 'cid',
'response_type': 'code',
'scope': 'openid'
})
self.assertEqual(args[0], "https://my.domain.com/authorize")
self.assertEqual(
kwargs["params"],
{
"audience": None,
"invitation": None,
"organization": None,
"redirect_uri": None,
"state": None,
"client_id": "cid",
"response_type": "code",
"scope": "openid",
},
)
import base64
import json
from time import sleep
import sys
import unittest
import mock
import sys
import requests
import unittest
from ...authentication.base import AuthenticationBase

@@ -14,37 +14,36 @@ from ...exceptions import Auth0Error, RateLimitError

class TestBase(unittest.TestCase):
def test_telemetry_enabled_by_default(self):
ab = AuthenticationBase('auth0.com')
ab = AuthenticationBase("auth0.com")
base_headers = ab.client.base_headers
user_agent = ab.base_headers['User-Agent']
auth0_client_bytes = base64.b64decode(ab.base_headers['Auth0-Client'])
auth0_client_json = auth0_client_bytes.decode('utf-8')
user_agent = base_headers["User-Agent"]
auth0_client_bytes = base64.b64decode(base_headers["Auth0-Client"])
auth0_client_json = auth0_client_bytes.decode("utf-8")
auth0_client = json.loads(auth0_client_json)
content_type = ab.base_headers['Content-Type']
content_type = base_headers["Content-Type"]
from auth0 import __version__ as auth0_version
python_version = '{}.{}.{}'.format(sys.version_info.major,
sys.version_info.minor,
sys.version_info.micro)
python_version = "{}.{}.{}".format(
sys.version_info.major, sys.version_info.minor, sys.version_info.micro
)
client_info = {
'name': 'auth0-python',
'version': auth0_version,
'env': {
'python': python_version
}
"name": "auth0-python",
"version": auth0_version,
"env": {"python": python_version},
}
self.assertEqual(user_agent, 'Python/{}'.format(python_version))
self.assertEqual(user_agent, "Python/{}".format(python_version))
self.assertEqual(auth0_client, client_info)
self.assertEqual(content_type, 'application/json')
self.assertEqual(content_type, "application/json")
def test_telemetry_disabled(self):
ab = AuthenticationBase('auth0.com', telemetry=False)
ab = AuthenticationBase("auth0.com", telemetry=False)
self.assertEqual(ab.base_headers, {'Content-Type': 'application/json'})
self.assertEqual(ab.client.base_headers, {"Content-Type": "application/json"})
@mock.patch('requests.post')
@mock.patch("requests.post")
def test_post(self, mock_post):
ab = AuthenticationBase('auth0.com', telemetry=False, timeout=(10, 2))
ab = AuthenticationBase("auth0.com", telemetry=False, timeout=(10, 2))

@@ -54,12 +53,16 @@ mock_post.return_value.status_code = 200

data = ab.post('the-url', data={'a': 'b'}, headers={'c': 'd'})
data = ab.post("the-url", data={"a": "b"}, headers={"c": "d"})
mock_post.assert_called_with(url='the-url', json={'a': 'b'},
headers={'c': 'd', 'Content-Type': 'application/json'}, timeout=(10, 2))
mock_post.assert_called_with(
"the-url",
json={"a": "b"},
headers={"c": "d", "Content-Type": "application/json"},
timeout=(10, 2),
)
self.assertEqual(data, {'x': 'y'})
self.assertEqual(data, {"x": "y"})
@mock.patch('requests.post')
@mock.patch("requests.post")
def test_post_with_defaults(self, mock_post):
ab = AuthenticationBase('auth0.com', telemetry=False)
ab = AuthenticationBase("auth0.com", telemetry=False)

@@ -70,12 +73,16 @@ mock_post.return_value.status_code = 200

# Only required params are passed
data = ab.post('the-url')
data = ab.post("the-url")
mock_post.assert_called_with(url='the-url', json=None,
headers={'Content-Type': 'application/json'}, timeout=5.0)
mock_post.assert_called_with(
"the-url",
json=None,
headers={"Content-Type": "application/json"},
timeout=5.0,
)
self.assertEqual(data, {'x': 'y'})
self.assertEqual(data, {"x": "y"})
@mock.patch('requests.post')
@mock.patch("requests.post")
def test_post_includes_telemetry(self, mock_post):
ab = AuthenticationBase('auth0.com')
ab = AuthenticationBase("auth0.com")

@@ -85,62 +92,61 @@ mock_post.return_value.status_code = 200

data = ab.post('the-url', data={'a': 'b'}, headers={'c': 'd'})
data = ab.post("the-url", data={"a": "b"}, headers={"c": "d"})
self.assertEqual(mock_post.call_count, 1)
call_kwargs = mock_post.call_args[1]
self.assertEqual(call_kwargs['url'], 'the-url')
self.assertEqual(call_kwargs['json'], {'a': 'b'})
headers = call_kwargs['headers']
self.assertEqual(headers['c'], 'd')
self.assertEqual(headers['Content-Type'], 'application/json')
self.assertIn('User-Agent', headers)
self.assertIn('Auth0-Client', headers)
call_args, call_kwargs = mock_post.call_args
self.assertEqual(call_args[0], "the-url")
self.assertEqual(call_kwargs["json"], {"a": "b"})
headers = call_kwargs["headers"]
self.assertEqual(headers["c"], "d")
self.assertEqual(headers["Content-Type"], "application/json")
self.assertIn("User-Agent", headers)
self.assertIn("Auth0-Client", headers)
self.assertEqual(data, {'x': 'y'})
self.assertEqual(data, {"x": "y"})
@mock.patch('requests.post')
@mock.patch("requests.post")
def test_post_error(self, mock_post):
ab = AuthenticationBase('auth0.com', telemetry=False)
ab = AuthenticationBase("auth0.com", telemetry=False)
for error_status in [400, 500, None]:
mock_post.return_value.status_code = error_status
mock_post.return_value.text = '{"error": "e0",' \
'"error_description": "desc"}'
mock_post.return_value.text = '{"error": "e0","error_description": "desc"}'
with self.assertRaises(Auth0Error) as context:
ab.post('the-url', data={'a': 'b'}, headers={'c': 'd'})
ab.post("the-url", data={"a": "b"}, headers={"c": "d"})
self.assertEqual(context.exception.status_code, error_status)
self.assertEqual(context.exception.error_code, 'e0')
self.assertEqual(context.exception.message, 'desc')
self.assertEqual(context.exception.error_code, "e0")
self.assertEqual(context.exception.message, "desc")
@mock.patch('requests.post')
@mock.patch("requests.post")
def test_post_rate_limit_error(self, mock_post):
ab = AuthenticationBase('auth0.com', telemetry=False)
ab = AuthenticationBase("auth0.com", telemetry=False)
mock_post.return_value.text = '{"statusCode": 429,' \
' "error": "e0",' \
' "error_description": "desc"}'
mock_post.return_value.text = (
'{"statusCode": 429, "error": "e0", "error_description": "desc"}'
)
mock_post.return_value.status_code = 429
mock_post.return_value.headers = {
'x-ratelimit-limit': '3',
'x-ratelimit-remaining': '6',
'x-ratelimit-reset': '9',
"x-ratelimit-limit": "3",
"x-ratelimit-remaining": "6",
"x-ratelimit-reset": "9",
}
with self.assertRaises(Auth0Error) as context:
ab.post('the-url', data={'a': 'b'}, headers={'c': 'd'})
ab.post("the-url", data={"a": "b"}, headers={"c": "d"})
self.assertEqual(context.exception.status_code, 429)
self.assertEqual(context.exception.error_code, 'e0')
self.assertEqual(context.exception.message, 'desc')
self.assertEqual(context.exception.error_code, "e0")
self.assertEqual(context.exception.message, "desc")
self.assertIsInstance(context.exception, RateLimitError)
self.assertEqual(context.exception.reset_at, 9)
@mock.patch('requests.post')
@mock.patch("requests.post")
def test_post_rate_limit_error_without_headers(self, mock_post):
ab = AuthenticationBase('auth0.com', telemetry=False)
ab = AuthenticationBase("auth0.com", telemetry=False)
mock_post.return_value.text = '{"statusCode": 429,' \
' "error": "e0",' \
' "error_description": "desc"}'
mock_post.return_value.text = (
'{"statusCode": 429, "error": "e0", "error_description": "desc"}'
)
mock_post.return_value.status_code = 429

@@ -150,29 +156,28 @@ mock_post.return_value.headers = {}

with self.assertRaises(Auth0Error) as context:
ab.post('the-url', data={'a': 'b'}, headers={'c': 'd'})
ab.post("the-url", data={"a": "b"}, headers={"c": "d"})
self.assertEqual(context.exception.status_code, 429)
self.assertEqual(context.exception.error_code, 'e0')
self.assertEqual(context.exception.message, 'desc')
self.assertEqual(context.exception.error_code, "e0")
self.assertEqual(context.exception.message, "desc")
self.assertIsInstance(context.exception, RateLimitError)
self.assertEqual(context.exception.reset_at, -1)
@mock.patch('requests.post')
@mock.patch("requests.post")
def test_post_error_with_code_property(self, mock_post):
ab = AuthenticationBase('auth0.com', telemetry=False)
ab = AuthenticationBase("auth0.com", telemetry=False)
for error_status in [400, 500, None]:
mock_post.return_value.status_code = error_status
mock_post.return_value.text = '{"code": "e0",' \
'"error_description": "desc"}'
mock_post.return_value.text = '{"code": "e0","error_description": "desc"}'
with self.assertRaises(Auth0Error) as context:
ab.post('the-url', data={'a': 'b'}, headers={'c': 'd'})
ab.post("the-url", data={"a": "b"}, headers={"c": "d"})
self.assertEqual(context.exception.status_code, error_status)
self.assertEqual(context.exception.error_code, 'e0')
self.assertEqual(context.exception.message, 'desc')
self.assertEqual(context.exception.error_code, "e0")
self.assertEqual(context.exception.message, "desc")
@mock.patch('requests.post')
@mock.patch("requests.post")
def test_post_error_with_no_error_code(self, mock_post):
ab = AuthenticationBase('auth0.com', telemetry=False)
ab = AuthenticationBase("auth0.com", telemetry=False)

@@ -184,29 +189,28 @@ for error_status in [400, 500, None]:

with self.assertRaises(Auth0Error) as context:
ab.post('the-url', data={'a': 'b'}, headers={'c': 'd'})
ab.post("the-url", data={"a": "b"}, headers={"c": "d"})
self.assertEqual(context.exception.status_code, error_status)
self.assertEqual(context.exception.error_code,
'a0.sdk.internal.unknown')
self.assertEqual(context.exception.message, 'desc')
self.assertEqual(context.exception.error_code, "a0.sdk.internal.unknown")
self.assertEqual(context.exception.message, "desc")
@mock.patch('requests.post')
@mock.patch("requests.post")
def test_post_error_with_text_response(self, mock_post):
ab = AuthenticationBase('auth0.com', telemetry=False)
ab = AuthenticationBase("auth0.com", telemetry=False)
for error_status in [400, 500, None]:
mock_post.return_value.status_code = error_status
mock_post.return_value.text = 'there has been a terrible error'
mock_post.return_value.text = "there has been a terrible error"
with self.assertRaises(Auth0Error) as context:
ab.post('the-url', data={'a': 'b'}, headers={'c': 'd'})
ab.post("the-url", data={"a": "b"}, headers={"c": "d"})
self.assertEqual(context.exception.status_code, error_status)
self.assertEqual(context.exception.error_code,
'a0.sdk.internal.unknown')
self.assertEqual(context.exception.message,
'there has been a terrible error')
self.assertEqual(context.exception.error_code, "a0.sdk.internal.unknown")
self.assertEqual(
context.exception.message, "there has been a terrible error"
)
@mock.patch('requests.post')
@mock.patch("requests.post")
def test_post_error_with_no_response_text(self, mock_post):
ab = AuthenticationBase('auth0.com', telemetry=False)
ab = AuthenticationBase("auth0.com", telemetry=False)

@@ -218,12 +222,11 @@ for error_status in [400, 500, None]:

with self.assertRaises(Auth0Error) as context:
ab.post('the-url', data={'a': 'b'}, headers={'c': 'd'})
ab.post("the-url", data={"a": "b"}, headers={"c": "d"})
self.assertEqual(context.exception.status_code, error_status)
self.assertEqual(context.exception.error_code,
'a0.sdk.internal.unknown')
self.assertEqual(context.exception.message, '')
self.assertEqual(context.exception.error_code, "a0.sdk.internal.unknown")
self.assertEqual(context.exception.message, "")
@mock.patch('requests.get')
@mock.patch("requests.get")
def test_get(self, mock_get):
ab = AuthenticationBase('auth0.com', telemetry=False, timeout=(10, 2))
ab = AuthenticationBase("auth0.com", telemetry=False, timeout=(10, 2))

@@ -233,12 +236,16 @@ mock_get.return_value.status_code = 200

data = ab.get('the-url', params={'a': 'b'}, headers={'c': 'd'})
data = ab.get("the-url", params={"a": "b"}, headers={"c": "d"})
mock_get.assert_called_with(url='the-url', params={'a': 'b'},
headers={'c': 'd', 'Content-Type': 'application/json'}, timeout=(10, 2))
mock_get.assert_called_with(
"the-url",
params={"a": "b"},
headers={"c": "d", "Content-Type": "application/json"},
timeout=(10, 2),
)
self.assertEqual(data, {'x': 'y'})
self.assertEqual(data, {"x": "y"})
@mock.patch('requests.get')
@mock.patch("requests.get")
def test_get_with_defaults(self, mock_get):
ab = AuthenticationBase('auth0.com', telemetry=False)
ab = AuthenticationBase("auth0.com", telemetry=False)

@@ -249,12 +256,16 @@ mock_get.return_value.status_code = 200

# Only required params are passed
data = ab.get('the-url')
data = ab.get("the-url")
mock_get.assert_called_with(url='the-url', params=None,
headers={'Content-Type': 'application/json'}, timeout=5.0)
mock_get.assert_called_with(
"the-url",
params=None,
headers={"Content-Type": "application/json"},
timeout=5.0,
)
self.assertEqual(data, {'x': 'y'})
self.assertEqual(data, {"x": "y"})
@mock.patch('requests.get')
@mock.patch("requests.get")
def test_get_includes_telemetry(self, mock_get):
ab = AuthenticationBase('auth0.com')
ab = AuthenticationBase("auth0.com")

@@ -264,13 +275,13 @@ mock_get.return_value.status_code = 200

data = ab.get('the-url', params={'a': 'b'}, headers={'c': 'd'})
data = ab.get("the-url", params={"a": "b"}, headers={"c": "d"})
self.assertEqual(mock_get.call_count, 1)
call_kwargs = mock_get.call_args[1]
self.assertEqual(call_kwargs['url'], 'the-url')
self.assertEqual(call_kwargs['params'], {'a': 'b'})
headers = call_kwargs['headers']
self.assertEqual(headers['c'], 'd')
self.assertEqual(headers['Content-Type'], 'application/json')
self.assertIn('User-Agent', headers)
self.assertIn('Auth0-Client', headers)
call_args, call_kwargs = mock_get.call_args
self.assertEqual(call_args[0], "the-url")
self.assertEqual(call_kwargs["params"], {"a": "b"})
headers = call_kwargs["headers"]
self.assertEqual(headers["c"], "d")
self.assertEqual(headers["Content-Type"], "application/json")
self.assertIn("User-Agent", headers)
self.assertIn("Auth0-Client", headers)

@@ -280,11 +291,11 @@ self.assertEqual(data, {"x": "y"})

def test_get_can_timeout(self):
ab = AuthenticationBase('auth0.com', timeout=0.00001)
ab = AuthenticationBase("auth0.com", timeout=0.00001)
with self.assertRaises(requests.exceptions.Timeout):
ab.get('https://google.com', params={'a': 'b'}, headers={'c': 'd'})
ab.get("https://google.com", params={"a": "b"}, headers={"c": "d"})
def test_post_can_timeout(self):
ab = AuthenticationBase('auth0.com', timeout=0.00001)
ab = AuthenticationBase("auth0.com", timeout=0.00001)
with self.assertRaises(requests.exceptions.Timeout):
ab.post('https://google.com', data={'a': 'b'}, headers={'c': 'd'})
ab.post("https://google.com", data={"a": "b"}, headers={"c": "d"})

@@ -9,104 +9,109 @@ import unittest

class TestDatabase(unittest.TestCase):
@mock.patch('auth0.v3.authentication.database.Database.post')
@mock.patch("auth0.v3.authentication.database.Database.post")
def test_login(self, mock_post):
d = Database('my.domain.com')
d = Database("my.domain.com")
d.login(client_id='cid',
username='usrnm',
password='pswd',
id_token='idt',
connection='conn',
device='dev',
grant_type='gt',
scope='openid profile')
d.login(
client_id="cid",
username="usrnm",
password="pswd",
id_token="idt",
connection="conn",
device="dev",
grant_type="gt",
scope="openid profile",
)
args, kwargs = mock_post.call_args
self.assertEqual(args[0], 'https://my.domain.com/oauth/ro')
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'username': 'usrnm',
'password': 'pswd',
'id_token': 'idt',
'connection': 'conn',
'device': 'dev',
'grant_type': 'gt',
'scope': 'openid profile',
})
self.assertEqual(args[0], "https://my.domain.com/oauth/ro")
self.assertEqual(
kwargs["data"],
{
"client_id": "cid",
"username": "usrnm",
"password": "pswd",
"id_token": "idt",
"connection": "conn",
"device": "dev",
"grant_type": "gt",
"scope": "openid profile",
},
)
@mock.patch('auth0.v3.authentication.database.Database.post')
@mock.patch("auth0.v3.authentication.database.Database.post")
def test_signup(self, mock_post):
d = Database('my.domain.com')
d = Database("my.domain.com")
# using only email and password
d.signup(client_id='cid',
email='a@b.com',
password='pswd',
connection='conn')
d.signup(client_id="cid", email="a@b.com", password="pswd", connection="conn")
args, kwargs = mock_post.call_args
self.assertEqual(args[0], 'https://my.domain.com/dbconnections/signup')
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'email': 'a@b.com',
'password': 'pswd',
'connection': 'conn',
})
self.assertEqual(args[0], "https://my.domain.com/dbconnections/signup")
self.assertEqual(
kwargs["data"],
{
"client_id": "cid",
"email": "a@b.com",
"password": "pswd",
"connection": "conn",
},
)
# Using also optional properties
sample_meta = {
'hobby': 'surfing',
'preference': {
'color': 'pink'
}
}
d.signup(client_id='cid',
email='a@b.com',
password='pswd',
connection='conn',
username='usr',
user_metadata=sample_meta,
given_name='john',
family_name='doe',
name='john doe',
nickname='johnny',
picture='avatars.com/john-doe')
sample_meta = {"hobby": "surfing", "preference": {"color": "pink"}}
d.signup(
client_id="cid",
email="a@b.com",
password="pswd",
connection="conn",
username="usr",
user_metadata=sample_meta,
given_name="john",
family_name="doe",
name="john doe",
nickname="johnny",
picture="avatars.com/john-doe",
)
args, kwargs = mock_post.call_args
self.assertEqual(args[0], 'https://my.domain.com/dbconnections/signup')
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'email': 'a@b.com',
'password': 'pswd',
'connection': 'conn',
'username': 'usr',
'user_metadata': sample_meta,
'given_name': 'john',
'family_name': 'doe',
'name': 'john doe',
'nickname': 'johnny',
'picture': 'avatars.com/john-doe',
})
self.assertEqual(args[0], "https://my.domain.com/dbconnections/signup")
self.assertEqual(
kwargs["data"],
{
"client_id": "cid",
"email": "a@b.com",
"password": "pswd",
"connection": "conn",
"username": "usr",
"user_metadata": sample_meta,
"given_name": "john",
"family_name": "doe",
"name": "john doe",
"nickname": "johnny",
"picture": "avatars.com/john-doe",
},
)
@mock.patch('auth0.v3.authentication.database.Database.post')
@mock.patch("auth0.v3.authentication.database.Database.post")
def test_change_password(self, mock_post):
d = Database('my.domain.com')
d = Database("my.domain.com")
# ignores the password argument
d.change_password(client_id='cid',
email='a@b.com',
password='pswd',
connection='conn')
d.change_password(
client_id="cid", email="a@b.com", password="pswd", connection="conn"
)
args, kwargs = mock_post.call_args
self.assertEqual(args[0],
'https://my.domain.com/dbconnections/change_password')
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'email': 'a@b.com',
'connection': 'conn',
})
self.assertEqual(args[0], "https://my.domain.com/dbconnections/change_password")
self.assertEqual(
kwargs["data"],
{
"client_id": "cid",
"email": "a@b.com",
"connection": "conn",
},
)
import unittest
import mock
from ...authentication.delegated import Delegated

@@ -7,61 +9,72 @@

class TestDelegated(unittest.TestCase):
@mock.patch('auth0.v3.authentication.delegated.Delegated.post')
@mock.patch("auth0.v3.authentication.delegated.Delegated.post")
def test_get_token_id_token(self, mock_post):
d = Delegated('my.domain.com')
d = Delegated("my.domain.com")
d.get_token(client_id='cid',
target='tgt',
api_type='apt',
grant_type='gt',
id_token='idt',
scope='openid profile')
d.get_token(
client_id="cid",
target="tgt",
api_type="apt",
grant_type="gt",
id_token="idt",
scope="openid profile",
)
args, kwargs = mock_post.call_args
self.assertEqual(args[0], 'https://my.domain.com/delegation')
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'grant_type': 'gt',
'id_token': 'idt',
'target': 'tgt',
'scope': 'openid profile',
'api_type': 'apt',
})
self.assertEqual(args[0], "https://my.domain.com/delegation")
self.assertEqual(
kwargs["data"],
{
"client_id": "cid",
"grant_type": "gt",
"id_token": "idt",
"target": "tgt",
"scope": "openid profile",
"api_type": "apt",
},
)
@mock.patch('auth0.v3.authentication.delegated.Delegated.post')
@mock.patch("auth0.v3.authentication.delegated.Delegated.post")
def test_get_token_refresh_token(self, mock_post):
d = Delegated('my.domain.com')
d = Delegated("my.domain.com")
d.get_token(client_id='cid',
target='tgt',
api_type='apt',
grant_type='gt',
refresh_token='rtk')
d.get_token(
client_id="cid",
target="tgt",
api_type="apt",
grant_type="gt",
refresh_token="rtk",
)
args, kwargs = mock_post.call_args
self.assertEqual(args[0], 'https://my.domain.com/delegation')
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'grant_type': 'gt',
'refresh_token': 'rtk',
'target': 'tgt',
'scope': 'openid',
'api_type': 'apt',
})
self.assertEqual(args[0], "https://my.domain.com/delegation")
self.assertEqual(
kwargs["data"],
{
"client_id": "cid",
"grant_type": "gt",
"refresh_token": "rtk",
"target": "tgt",
"scope": "openid",
"api_type": "apt",
},
)
@mock.patch('auth0.v3.authentication.delegated.Delegated.post')
@mock.patch("auth0.v3.authentication.delegated.Delegated.post")
def test_get_token_value_error(self, mock_post):
d = Delegated('my.domain.com')
d = Delegated("my.domain.com")
with self.assertRaises(ValueError):
d.get_token(client_id='cid',
target='tgt',
api_type='apt',
grant_type='gt',
refresh_token='rtk',
id_token='idt')
d.get_token(
client_id="cid",
target="tgt",
api_type="apt",
grant_type="gt",
refresh_token="rtk",
id_token="idt",
)
import unittest
import mock
from ...authentication.enterprise import Enterprise

@@ -7,18 +9,15 @@

class TestEnterprise(unittest.TestCase):
@mock.patch('auth0.v3.authentication.enterprise.Enterprise.get')
@mock.patch("auth0.v3.authentication.enterprise.Enterprise.get")
def test_saml_metadata(self, mock_get):
e = Enterprise('my.domain.com')
e = Enterprise("my.domain.com")
e.saml_metadata('cid')
e.saml_metadata("cid")
mock_get.assert_called_with(
url='https://my.domain.com/samlp/metadata/cid'
)
mock_get.assert_called_with(url="https://my.domain.com/samlp/metadata/cid")
@mock.patch('auth0.v3.authentication.enterprise.Enterprise.get')
@mock.patch("auth0.v3.authentication.enterprise.Enterprise.get")
def test_wsfed_metadata(self, mock_get):
e = Enterprise('my.domain.com')
e = Enterprise("my.domain.com")

@@ -28,4 +27,6 @@ e.wsfed_metadata()

mock_get.assert_called_with(
url='https://my.domain.com/wsfed/FederationMetadata'
'/2007-06/FederationMetadata.xml'
url=(
"https://my.domain.com/wsfed/FederationMetadata"
"/2007-06/FederationMetadata.xml"
)
)
import unittest
import mock
from ...authentication.get_token import GetToken

@@ -7,172 +9,199 @@

class TestGetToken(unittest.TestCase):
@mock.patch('auth0.v3.authentication.get_token.GetToken.post')
@mock.patch("auth0.v3.authentication.get_token.GetToken.post")
def test_authorization_code(self, mock_post):
g = GetToken('my.domain.com')
g = GetToken("my.domain.com")
g.authorization_code(client_id='cid',
client_secret='clsec',
code='cd',
grant_type='gt',
redirect_uri='idt')
g.authorization_code(
client_id="cid",
client_secret="clsec",
code="cd",
grant_type="gt",
redirect_uri="idt",
)
args, kwargs = mock_post.call_args
self.assertEqual(args[0], 'https://my.domain.com/oauth/token')
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'client_secret': 'clsec',
'code': 'cd',
'grant_type': 'gt',
'redirect_uri': 'idt'
})
self.assertEqual(args[0], "https://my.domain.com/oauth/token")
self.assertEqual(
kwargs["data"],
{
"client_id": "cid",
"client_secret": "clsec",
"code": "cd",
"grant_type": "gt",
"redirect_uri": "idt",
},
)
@mock.patch('auth0.v3.authentication.get_token.GetToken.post')
@mock.patch("auth0.v3.authentication.get_token.GetToken.post")
def test_authorization_code_pkce(self, mock_post):
g = GetToken('my.domain.com')
g = GetToken("my.domain.com")
g.authorization_code_pkce(client_id='cid',
code_verifier='cdver',
code='cd',
grant_type='gt',
redirect_uri='idt')
g.authorization_code_pkce(
client_id="cid",
code_verifier="cdver",
code="cd",
grant_type="gt",
redirect_uri="idt",
)
args, kwargs = mock_post.call_args
self.assertEqual(args[0], 'https://my.domain.com/oauth/token')
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'code_verifier': 'cdver',
'code': 'cd',
'grant_type': 'gt',
'redirect_uri': 'idt'
})
self.assertEqual(args[0], "https://my.domain.com/oauth/token")
self.assertEqual(
kwargs["data"],
{
"client_id": "cid",
"code_verifier": "cdver",
"code": "cd",
"grant_type": "gt",
"redirect_uri": "idt",
},
)
@mock.patch('auth0.v3.authentication.get_token.GetToken.post')
@mock.patch("auth0.v3.authentication.get_token.GetToken.post")
def test_client_credentials(self, mock_post):
g = GetToken('my.domain.com')
g = GetToken("my.domain.com")
g.client_credentials(client_id='cid',
client_secret='clsec',
audience='aud',
grant_type='gt')
g.client_credentials(
client_id="cid", client_secret="clsec", audience="aud", grant_type="gt"
)
args, kwargs = mock_post.call_args
self.assertEqual(args[0], 'https://my.domain.com/oauth/token')
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'client_secret': 'clsec',
'audience': 'aud',
'grant_type': 'gt'
})
self.assertEqual(args[0], "https://my.domain.com/oauth/token")
self.assertEqual(
kwargs["data"],
{
"client_id": "cid",
"client_secret": "clsec",
"audience": "aud",
"grant_type": "gt",
},
)
@mock.patch('auth0.v3.authentication.get_token.GetToken.post')
@mock.patch("auth0.v3.authentication.get_token.GetToken.post")
def test_login(self, mock_post):
g = GetToken('my.domain.com')
g = GetToken("my.domain.com")
g.login(client_id='cid',
client_secret='clsec',
username='usrnm',
password='pswd',
scope='http://test.com/api',
realm='rlm',
audience='aud',
grant_type='gt')
g.login(
client_id="cid",
client_secret="clsec",
username="usrnm",
password="pswd",
scope="http://test.com/api",
realm="rlm",
audience="aud",
grant_type="gt",
)
args, kwargs = mock_post.call_args
self.assertEqual(args[0], 'https://my.domain.com/oauth/token')
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'client_secret': 'clsec',
'username': 'usrnm',
'password': 'pswd',
'scope': 'http://test.com/api',
'realm': 'rlm',
'audience': 'aud',
'grant_type': 'gt'
})
self.assertEqual(args[0], "https://my.domain.com/oauth/token")
self.assertEqual(
kwargs["data"],
{
"client_id": "cid",
"client_secret": "clsec",
"username": "usrnm",
"password": "pswd",
"scope": "http://test.com/api",
"realm": "rlm",
"audience": "aud",
"grant_type": "gt",
},
)
@mock.patch('auth0.v3.authentication.get_token.GetToken.post')
@mock.patch("auth0.v3.authentication.get_token.GetToken.post")
def test_refresh_token(self, mock_post):
g = GetToken('my.domain.com')
g = GetToken("my.domain.com")
g.refresh_token(client_id='cid',
client_secret='clsec',
refresh_token='rt',
grant_type='gt',
scope='s')
g.refresh_token(
client_id="cid",
client_secret="clsec",
refresh_token="rt",
grant_type="gt",
scope="s",
)
args, kwargs = mock_post.call_args
self.assertEqual(args[0], 'https://my.domain.com/oauth/token')
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'client_secret': 'clsec',
'refresh_token': 'rt',
'grant_type': 'gt',
'scope': 's'
})
self.assertEqual(args[0], "https://my.domain.com/oauth/token")
self.assertEqual(
kwargs["data"],
{
"client_id": "cid",
"client_secret": "clsec",
"refresh_token": "rt",
"grant_type": "gt",
"scope": "s",
},
)
@mock.patch('auth0.v3.authentication.get_token.GetToken.post')
@mock.patch("auth0.v3.authentication.get_token.GetToken.post")
def test_passwordless_login_with_sms(self, mock_post):
g = GetToken('my.domain.com')
g = GetToken("my.domain.com")
g.passwordless_login(
client_id='cid',
client_secret='csec',
username='123456',
otp='abcd',
realm='sms',
audience='aud',
scope='openid')
client_id="cid",
client_secret="csec",
username="123456",
otp="abcd",
realm="sms",
audience="aud",
scope="openid",
)
args, kwargs = mock_post.call_args
self.assertEqual(args[0], 'https://my.domain.com/oauth/token')
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'client_secret': 'csec',
'realm': 'sms',
'grant_type': 'http://auth0.com/oauth/grant-type/passwordless/otp',
'username': '123456',
'otp': 'abcd',
'audience': 'aud',
'scope': 'openid',
})
self.assertEqual(args[0], "https://my.domain.com/oauth/token")
self.assertEqual(
kwargs["data"],
{
"client_id": "cid",
"client_secret": "csec",
"realm": "sms",
"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp",
"username": "123456",
"otp": "abcd",
"audience": "aud",
"scope": "openid",
},
)
@mock.patch('auth0.v3.authentication.get_token.GetToken.post')
@mock.patch("auth0.v3.authentication.get_token.GetToken.post")
def test_passwordless_login_with_email(self, mock_post):
g = GetToken('my.domain.com')
g = GetToken("my.domain.com")
g.passwordless_login(
client_id='cid',
client_secret='csec',
username='a@b.c',
otp='abcd',
realm='email',
audience='aud',
scope='openid')
client_id="cid",
client_secret="csec",
username="a@b.c",
otp="abcd",
realm="email",
audience="aud",
scope="openid",
)
args, kwargs = mock_post.call_args
self.assertEqual(args[0], 'https://my.domain.com/oauth/token')
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'client_secret': 'csec',
'realm': 'email',
'grant_type': 'http://auth0.com/oauth/grant-type/passwordless/otp',
'username': 'a@b.c',
'otp': 'abcd',
'audience': 'aud',
'scope': 'openid',
})
self.assertEqual(args[0], "https://my.domain.com/oauth/token")
self.assertEqual(
kwargs["data"],
{
"client_id": "cid",
"client_secret": "csec",
"realm": "email",
"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp",
"username": "a@b.c",
"otp": "abcd",
"audience": "aud",
"scope": "openid",
},
)
import unittest
import mock
from ...authentication.logout import Logout

@@ -7,24 +9,25 @@

class TestLogout(unittest.TestCase):
@mock.patch('auth0.v3.authentication.logout.Logout.get')
@mock.patch("auth0.v3.authentication.logout.Logout.get")
def test_logout(self, mock_get):
g = Logout('my.domain.com')
g = Logout("my.domain.com")
g.logout(client_id='cid',
return_to='rto')
g.logout(client_id="cid", return_to="rto")
args, kwargs = mock_get.call_args
self.assertEqual(args[0], 'https://my.domain.com/v2/logout?client_id=cid&returnTo=rto')
self.assertEqual(
args[0], "https://my.domain.com/v2/logout?client_id=cid&returnTo=rto"
)
@mock.patch('auth0.v3.authentication.logout.Logout.get')
@mock.patch("auth0.v3.authentication.logout.Logout.get")
def test_federated_logout(self, mock_get):
g = Logout('my.domain.com')
g = Logout("my.domain.com")
g.logout(client_id='cid',
return_to='rto',
federated=True)
g.logout(client_id="cid", return_to="rto", federated=True)
args, kwargs = mock_get.call_args
self.assertEqual(args[0], 'https://my.domain.com/v2/logout?federated&client_id=cid&returnTo=rto')
self.assertEqual(
args[0],
"https://my.domain.com/v2/logout?federated&client_id=cid&returnTo=rto",
)
import unittest
import mock
from ...authentication.passwordless import Passwordless

@@ -7,132 +9,145 @@

class TestPasswordless(unittest.TestCase):
@mock.patch('auth0.v3.authentication.passwordless.Passwordless.post')
@mock.patch("auth0.v3.authentication.passwordless.Passwordless.post")
def test_send_email(self, mock_post):
p = Passwordless('my.domain.com')
p = Passwordless("my.domain.com")
p.email(client_id='cid',
email='a@b.com',
send='snd')
p.email(client_id="cid", email="a@b.com", send="snd")
args, kwargs = mock_post.call_args
self.assertEqual(args[0], 'https://my.domain.com/passwordless/start')
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'email': 'a@b.com',
'send': 'snd',
'connection': 'email',
})
self.assertEqual(args[0], "https://my.domain.com/passwordless/start")
self.assertEqual(
kwargs["data"],
{
"client_id": "cid",
"email": "a@b.com",
"send": "snd",
"connection": "email",
},
)
@mock.patch('auth0.v3.authentication.passwordless.Passwordless.post')
@mock.patch("auth0.v3.authentication.passwordless.Passwordless.post")
def test_send_email_with_auth_params(self, mock_post):
p = Passwordless('my.domain.com')
p = Passwordless("my.domain.com")
p.email(client_id='cid',
email='a@b.com',
send='snd',
auth_params={'a': 'b'})
p.email(client_id="cid", email="a@b.com", send="snd", auth_params={"a": "b"})
args, kwargs = mock_post.call_args
self.assertEqual(args[0], 'https://my.domain.com/passwordless/start')
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'email': 'a@b.com',
'send': 'snd',
'authParams': {'a': 'b'},
'connection': 'email',
})
self.assertEqual(args[0], "https://my.domain.com/passwordless/start")
self.assertEqual(
kwargs["data"],
{
"client_id": "cid",
"email": "a@b.com",
"send": "snd",
"authParams": {"a": "b"},
"connection": "email",
},
)
@mock.patch('auth0.v3.authentication.passwordless.Passwordless.post')
@mock.patch("auth0.v3.authentication.passwordless.Passwordless.post")
def test_send_email_with_client_secret(self, mock_post):
p = Passwordless('my.domain.com')
p = Passwordless("my.domain.com")
p.email(client_id='cid',
client_secret='csecret',
email='a@b.com',
send='snd')
p.email(client_id="cid", client_secret="csecret", email="a@b.com", send="snd")
args, kwargs = mock_post.call_args
self.assertEqual(args[0], 'https://my.domain.com/passwordless/start')
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'client_secret': 'csecret',
'email': 'a@b.com',
'send': 'snd',
'connection': 'email',
})
self.assertEqual(args[0], "https://my.domain.com/passwordless/start")
self.assertEqual(
kwargs["data"],
{
"client_id": "cid",
"client_secret": "csecret",
"email": "a@b.com",
"send": "snd",
"connection": "email",
},
)
@mock.patch('auth0.v3.authentication.passwordless.Passwordless.post')
@mock.patch("auth0.v3.authentication.passwordless.Passwordless.post")
def test_send_sms(self, mock_post):
p = Passwordless('my.domain.com')
p = Passwordless("my.domain.com")
p.sms(client_id='cid', phone_number='123456')
p.sms(client_id="cid", phone_number="123456")
args, kwargs = mock_post.call_args
self.assertEqual(args[0], 'https://my.domain.com/passwordless/start')
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'phone_number': '123456',
'connection': 'sms',
})
self.assertEqual(args[0], "https://my.domain.com/passwordless/start")
self.assertEqual(
kwargs["data"],
{
"client_id": "cid",
"phone_number": "123456",
"connection": "sms",
},
)
@mock.patch('auth0.v3.authentication.passwordless.Passwordless.post')
@mock.patch("auth0.v3.authentication.passwordless.Passwordless.post")
def test_send_sms_with_client_secret(self, mock_post):
p = Passwordless('my.domain.com')
p = Passwordless("my.domain.com")
p.sms(client_id='cid', client_secret='csecret', phone_number='123456')
p.sms(client_id="cid", client_secret="csecret", phone_number="123456")
args, kwargs = mock_post.call_args
self.assertEqual(args[0], 'https://my.domain.com/passwordless/start')
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'client_secret': 'csecret',
'phone_number': '123456',
'connection': 'sms',
})
@mock.patch('auth0.v3.authentication.passwordless.Passwordless.post')
self.assertEqual(args[0], "https://my.domain.com/passwordless/start")
self.assertEqual(
kwargs["data"],
{
"client_id": "cid",
"client_secret": "csecret",
"phone_number": "123456",
"connection": "sms",
},
)
@mock.patch("auth0.v3.authentication.passwordless.Passwordless.post")
def test_send_sms_login(self, mock_post):
p = Passwordless('my.domain.com')
p = Passwordless("my.domain.com")
p.sms_login(client_id='cid', phone_number='123456', code='abcd')
p.sms_login(client_id="cid", phone_number="123456", code="abcd")
args, kwargs = mock_post.call_args
self.assertEqual(args[0], 'https://my.domain.com/oauth/ro')
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'connection': 'sms',
'grant_type': 'password',
'username': '123456',
'password': 'abcd',
'scope': 'openid',
})
self.assertEqual(args[0], "https://my.domain.com/oauth/ro")
self.assertEqual(
kwargs["data"],
{
"client_id": "cid",
"connection": "sms",
"grant_type": "password",
"username": "123456",
"password": "abcd",
"scope": "openid",
},
)
@mock.patch('auth0.v3.authentication.passwordless.Passwordless.post')
@mock.patch("auth0.v3.authentication.passwordless.Passwordless.post")
def test_send_sms_login_with_scope(self, mock_post):
p = Passwordless('my.domain.com')
p = Passwordless("my.domain.com")
p.sms_login(client_id='cid', phone_number='123456',
code='abcd', scope='openid profile')
p.sms_login(
client_id="cid", phone_number="123456", code="abcd", scope="openid profile"
)
args, kwargs = mock_post.call_args
self.assertEqual(args[0], 'https://my.domain.com/oauth/ro')
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'connection': 'sms',
'grant_type': 'password',
'username': '123456',
'password': 'abcd',
'scope': 'openid profile',
})
self.assertEqual(args[0], "https://my.domain.com/oauth/ro")
self.assertEqual(
kwargs["data"],
{
"client_id": "cid",
"connection": "sms",
"grant_type": "password",
"username": "123456",
"password": "abcd",
"scope": "openid profile",
},
)
import unittest
import mock
from ...authentication.revoke_token import RevokeToken

@@ -7,31 +9,23 @@

class TestRevokeToken(unittest.TestCase):
@mock.patch('auth0.v3.authentication.revoke_token.RevokeToken.post')
@mock.patch("auth0.v3.authentication.revoke_token.RevokeToken.post")
def test_revoke_refresh_token(self, mock_post):
a = RevokeToken('my.domain.com')
a = RevokeToken("my.domain.com")
# regular apps
a.revoke_refresh_token(client_id='cid', token='tkn')
a.revoke_refresh_token(client_id="cid", token="tkn")
args, kwargs = mock_post.call_args
self.assertEqual(args[0], 'https://my.domain.com/oauth/revoke')
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'token': 'tkn'
})
self.assertEqual(args[0], "https://my.domain.com/oauth/revoke")
self.assertEqual(kwargs["data"], {"client_id": "cid", "token": "tkn"})
# confidential apps
a.revoke_refresh_token(client_id='cid',
token='tkn',
client_secret='sh!')
a.revoke_refresh_token(client_id="cid", token="tkn", client_secret="sh!")
args, kwargs = mock_post.call_args
self.assertEqual(args[0], 'https://my.domain.com/oauth/revoke')
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'token': 'tkn',
'client_secret': 'sh!'
})
self.assertEqual(args[0], "https://my.domain.com/oauth/revoke")
self.assertEqual(
kwargs["data"], {"client_id": "cid", "token": "tkn", "client_secret": "sh!"}
)
import unittest
import mock
from ...authentication.social import Social

@@ -7,32 +9,41 @@

class TestSocial(unittest.TestCase):
@mock.patch('auth0.v3.authentication.social.Social.post')
@mock.patch("auth0.v3.authentication.social.Social.post")
def test_login(self, mock_post):
s = Social('a.b.c')
s.login(client_id='cid', access_token='atk', connection='conn')
s = Social("a.b.c")
s.login(client_id="cid", access_token="atk", connection="conn")
args, kwargs = mock_post.call_args
self.assertEqual('https://a.b.c/oauth/access_token', args[0])
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'access_token': 'atk',
'connection': 'conn',
'scope': 'openid',
})
self.assertEqual("https://a.b.c/oauth/access_token", args[0])
self.assertEqual(
kwargs["data"],
{
"client_id": "cid",
"access_token": "atk",
"connection": "conn",
"scope": "openid",
},
)
@mock.patch('auth0.v3.authentication.social.Social.post')
@mock.patch("auth0.v3.authentication.social.Social.post")
def test_login_with_scope(self, mock_post):
s = Social('a.b.c')
s.login(client_id='cid', access_token='atk',
connection='conn', scope='openid profile')
s = Social("a.b.c")
s.login(
client_id="cid",
access_token="atk",
connection="conn",
scope="openid profile",
)
args, kwargs = mock_post.call_args
self.assertEqual('https://a.b.c/oauth/access_token', args[0])
self.assertEqual(kwargs['data'], {
'client_id': 'cid',
'access_token': 'atk',
'connection': 'conn',
'scope': 'openid profile',
})
self.assertEqual("https://a.b.c/oauth/access_token", args[0])
self.assertEqual(
kwargs["data"],
{
"client_id": "cid",
"access_token": "atk",
"connection": "conn",
"scope": "openid profile",
},
)
import json
import time
import unittest
import jwt
import unittest
import time
from mock import MagicMock, patch
from ...authentication.token_verifier import TokenVerifier, AsymmetricSignatureVerifier, \
SymmetricSignatureVerifier, JwksFetcher, SignatureVerifier
from ...authentication.token_verifier import (
AsymmetricSignatureVerifier,
JwksFetcher,
SignatureVerifier,
SymmetricSignatureVerifier,
TokenVerifier,
)
from ...exceptions import TokenValidationError

@@ -15,4 +19,16 @@

RSA_PUB_KEY_2_PEM = b"""-----BEGIN PUBLIC KEY-----\nMDowDQYJKoZIhvcNAQEBBQADKQAwJgIfAI7TBUCn8e1hj/fNpb5dqMf8Jj6Ja6qN\npqyeOGYEzAIDAQAB\n-----END PUBLIC KEY-----\n"""
RSA_PUB_KEY_1_JWK = {"kty": "RSA", "use": "sig", "n": "uGbXWiK3dQTyCbX5xdE4yCuYp0AF2d15Qq1JSXT_lx8CEcXb9RbDddl8jGDv-spi5qPa8qEHiK7FwV2KpRE983wGPnYsAm9BxLFb4YrLYcDFOIGULuk2FtrPS512Qea1bXASuvYXEpQNpGbnTGVsWXI9C-yjHztqyL2h8P6mlThPY9E9ue2fCqdgixfTFIF9Dm4SLHbphUS2iw7w1JgT69s7of9-I9l5lsJ9cozf1rxrXX4V1u_SotUuNB3Fp8oB4C1fLBEhSlMcUJirz1E8AziMCxS-VrRPDM-zfvpIJg3JljAh3PJHDiLu902v9w-Iplu1WyoB2aPfitxEhRN0Yw", "e": "AQAB", "kid": "test-key-1"}
RSA_PUB_KEY_2_JWK = {"kty": "RSA", "use": "sig", "n": "jtMFQKfx7WGP982lvl2ox_wmPolrqo2mrJ44ZgTM", "e": "AQAB", "kid": "test-key-2"}
RSA_PUB_KEY_1_JWK = {
"kty": "RSA",
"use": "sig",
"n": "uGbXWiK3dQTyCbX5xdE4yCuYp0AF2d15Qq1JSXT_lx8CEcXb9RbDddl8jGDv-spi5qPa8qEHiK7FwV2KpRE983wGPnYsAm9BxLFb4YrLYcDFOIGULuk2FtrPS512Qea1bXASuvYXEpQNpGbnTGVsWXI9C-yjHztqyL2h8P6mlThPY9E9ue2fCqdgixfTFIF9Dm4SLHbphUS2iw7w1JgT69s7of9-I9l5lsJ9cozf1rxrXX4V1u_SotUuNB3Fp8oB4C1fLBEhSlMcUJirz1E8AziMCxS-VrRPDM-zfvpIJg3JljAh3PJHDiLu902v9w-Iplu1WyoB2aPfitxEhRN0Yw",
"e": "AQAB",
"kid": "test-key-1",
}
RSA_PUB_KEY_2_JWK = {
"kty": "RSA",
"use": "sig",
"n": "jtMFQKfx7WGP982lvl2ox_wmPolrqo2mrJ44ZgTM",
"e": "AQAB",
"kid": "test-key-2",
}
JWKS_RESPONSE_SINGLE_KEY = {"keys": [RSA_PUB_KEY_1_JWK]}

@@ -26,6 +42,6 @@ JWKS_RESPONSE_MULTIPLE_KEYS = {"keys": [RSA_PUB_KEY_1_JWK, RSA_PUB_KEY_2_JWK]}

expectations = {
"audience": "tokens-test-123",
"audience_alt": "external-test-999",
"issuer": "https://tokens-test.auth0.com/",
"nonce": "a1b2c3d4e5"
"audience": "tokens-test-123",
"audience_alt": "external-test-999",
"issuer": "https://tokens-test.auth0.com/",
"nonce": "a1b2c3d4e5",
}

@@ -35,3 +51,2 @@

class TestSignatureVerifier(unittest.TestCase):
def test_fail_at_creation_with_invalid_algorithm(self):

@@ -69,4 +84,4 @@ alg = 12345

mock_fetcher = JwksFetcher('some URL')
mock_fetcher.get_key = MagicMock('get_key')
mock_fetcher = JwksFetcher("some URL")
mock_fetcher.get_key = MagicMock("get_key")
mock_fetcher.get_key.return_value = RSA_PUB_KEY_1_JWK

@@ -77,6 +92,6 @@

key = verifier._fetch_key('test-key')
key = verifier._fetch_key("test-key")
args, kwargs = mock_fetcher.get_key.call_args
self.assertEqual(args[0], 'test-key')
self.assertEqual(args[0], "test-key")

@@ -94,3 +109,7 @@ self.assertEqual(mock_fetcher, verifier._fetcher)

verifier.verify_signature(jwt)
self.assertEqual(str(err.exception), 'Signature algorithm of "none" is not supported. Expected the token to be signed with "HS256"')
self.assertEqual(
str(err.exception),
'Signature algorithm of "none" is not supported. Expected the token to be'
' signed with "HS256"',
)

@@ -100,8 +119,10 @@ verifier = AsymmetricSignatureVerifier("some url")

verifier.verify_signature(jwt)
self.assertEqual(str(err.exception),
'Signature algorithm of "none" is not supported. Expected the token to be signed with "RS256"')
self.assertEqual(
str(err.exception),
'Signature algorithm of "none" is not supported. Expected the token to be'
' signed with "RS256"',
)
class TestJwksFetcher(unittest.TestCase):
@staticmethod

@@ -112,7 +133,10 @@ def _get_pem_bytes(rsa_public_key):

from cryptography.hazmat.primitives import serialization
return rsa_public_key.public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo)
@patch('requests.get')
return rsa_public_key.public_bytes(
serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo
)
@patch("requests.get")
def test_get_jwks_json_twice_on_cache_expired(self, mock_get):
JWKS_URL = 'https://app.myhosting.com/.well-known/jwks.json'
JWKS_URL = "https://app.myhosting.com/.well-known/jwks.json"
fetcher = JwksFetcher(JWKS_URL, cache_ttl=1)

@@ -124,3 +148,3 @@

key_1 = fetcher.get_key('test-key-1')
key_1 = fetcher.get_key("test-key-1")
expected_key_1_pem = self._get_pem_bytes(key_1)

@@ -135,3 +159,3 @@ self.assertEqual(expected_key_1_pem, RSA_PUB_KEY_1_PEM)

# 2 seconds has passed, cache should be expired
key_1 = fetcher.get_key('test-key-1')
key_1 = fetcher.get_key("test-key-1")
expected_key_1_pem = self._get_pem_bytes(key_1)

@@ -143,5 +167,5 @@ self.assertEqual(expected_key_1_pem, RSA_PUB_KEY_1_PEM)

@patch('requests.get')
@patch("requests.get")
def test_get_jwks_json_once_on_cache_hit(self, mock_get):
JWKS_URL = 'https://app.myhosting.com/.well-known/jwks.json'
JWKS_URL = "https://app.myhosting.com/.well-known/jwks.json"
fetcher = JwksFetcher(JWKS_URL)

@@ -153,4 +177,4 @@

key_1 = fetcher.get_key('test-key-1')
key_2 = fetcher.get_key('test-key-2')
key_1 = fetcher.get_key("test-key-1")
key_2 = fetcher.get_key("test-key-2")
expected_key_1_pem = self._get_pem_bytes(key_1)

@@ -164,5 +188,5 @@ expected_key_2_pem = self._get_pem_bytes(key_2)

@patch('requests.get')
@patch("requests.get")
def test_fetches_jwks_json_forced_on_cache_miss(self, mock_get):
JWKS_URL = 'https://app.myhosting.com/.well-known/jwks.json'
JWKS_URL = "https://app.myhosting.com/.well-known/jwks.json"
fetcher = JwksFetcher(JWKS_URL)

@@ -172,6 +196,6 @@

mock_get.return_value.status_code = 200
mock_get.return_value.json.return_value = {'keys':[RSA_PUB_KEY_1_JWK]}
mock_get.return_value.json.return_value = {"keys": [RSA_PUB_KEY_1_JWK]}
# Triggers the first call
key_1 = fetcher.get_key('test-key-1')
key_1 = fetcher.get_key("test-key-1")
expected_key_1_pem = self._get_pem_bytes(key_1)

@@ -186,3 +210,3 @@ self.assertEqual(expected_key_1_pem, RSA_PUB_KEY_1_PEM)

# Triggers the second call
key_2 = fetcher.get_key('test-key-2')
key_2 = fetcher.get_key("test-key-2")
expected_key_2_pem = self._get_pem_bytes(key_2)

@@ -194,5 +218,5 @@ self.assertEqual(expected_key_2_pem, RSA_PUB_KEY_2_PEM)

@patch('requests.get')
@patch("requests.get")
def test_fetches_jwks_json_once_on_cache_miss(self, mock_get):
JWKS_URL = 'https://app.myhosting.com/.well-known/jwks.json'
JWKS_URL = "https://app.myhosting.com/.well-known/jwks.json"
fetcher = JwksFetcher(JWKS_URL)

@@ -205,11 +229,13 @@

with self.assertRaises(Exception) as err:
key_1 = fetcher.get_key('missing-key')
fetcher.get_key("missing-key")
mock_get.assert_called_with(JWKS_URL)
self.assertEqual(str(err.exception), 'RSA Public Key with ID "missing-key" was not found.')
self.assertEqual(
str(err.exception), 'RSA Public Key with ID "missing-key" was not found.'
)
self.assertEqual(mock_get.call_count, 1)
@patch('requests.get')
@patch("requests.get")
def test_fails_to_fetch_jwks_json_after_retrying_twice(self, mock_get):
JWKS_URL = 'https://app.myhosting.com/.well-known/jwks.json'
JWKS_URL = "https://app.myhosting.com/.well-known/jwks.json"
fetcher = JwksFetcher(JWKS_URL)

@@ -222,6 +248,8 @@

with self.assertRaises(Exception) as err:
key_1 = fetcher.get_key('id1')
fetcher.get_key("id1")
mock_get.assert_called_with(JWKS_URL)
self.assertEqual(str(err.exception), 'RSA Public Key with ID "id1" was not found.')
self.assertEqual(
str(err.exception), 'RSA Public Key with ID "id1" was not found.'
)
self.assertEqual(mock_get.call_count, 2)

@@ -231,14 +259,26 @@

class TestTokenVerifier(unittest.TestCase):
@staticmethod
def asymmetric_signature_verifier_mock():
verifier = AsymmetricSignatureVerifier('some URL')
verifier._fetch_key = MagicMock('_fetch_key')
verifier = AsymmetricSignatureVerifier("some URL")
verifier._fetch_key = MagicMock("_fetch_key")
# noinspection PyUnresolvedReferences
# requirement already includes cryptography -> pyjwt[crypto]
verifier._fetch_key.return_value = jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(RSA_PUB_KEY_1_JWK))
verifier._fetch_key.return_value = jwt.algorithms.RSAAlgorithm.from_jwk(
json.dumps(RSA_PUB_KEY_1_JWK)
)
return verifier
def assert_fails_with_error(self, token, error_message, signature_verifier=None, audience=expectations['audience'], issuer=expectations['issuer'], nonce=None, max_age=None, clock=MOCKED_CLOCK, organization=None):
def assert_fails_with_error(
self,
token,
error_message,
signature_verifier=None,
audience=expectations["audience"],
issuer=expectations["issuer"],
nonce=None,
max_age=None,
clock=MOCKED_CLOCK,
organization=None,
):
sv = signature_verifier or self.asymmetric_signature_verifier_mock()

@@ -249,3 +289,3 @@ tv = TokenVerifier(

audience=audience,
leeway=DEFAULT_LEEWAY
leeway=DEFAULT_LEEWAY,
)

@@ -261,4 +301,9 @@ tv._clock = clock

# noinspection PyTypeChecker
TokenVerifier(signature_verifier=sv, issuer="valid issuer", audience="valid audience")
self.assertEqual(str(err.exception), "signature_verifier must be an instance of SignatureVerifier.")
TokenVerifier(
signature_verifier=sv, issuer="valid issuer", audience="valid audience"
)
self.assertEqual(
str(err.exception),
"signature_verifier must be an instance of SignatureVerifier.",
)

@@ -285,4 +330,4 @@ def test_err_token_empty(self):

signature_verifier=sv,
issuer=expectations['issuer'],
audience=expectations['audience']
issuer=expectations["issuer"],
audience=expectations["audience"],
)

@@ -298,4 +343,4 @@ tv._clock = MOCKED_CLOCK

signature_verifier=sv,
issuer=expectations['issuer'],
audience=expectations['audience']
issuer=expectations["issuer"],
audience=expectations["audience"],
)

@@ -309,3 +354,5 @@ tv._clock = MOCKED_CLOCK

self.assert_fails_with_error(token, "Invalid token signature.", signature_verifier=sv)
self.assert_fails_with_error(
token, "Invalid token signature.", signature_verifier=sv
)

@@ -316,7 +363,13 @@ def test_RS256_token_signature_fails(self):

self.assert_fails_with_error(token, "Invalid token signature.", signature_verifier=sv)
self.assert_fails_with_error(
token, "Invalid token signature.", signature_verifier=sv
)
def test_fails_with_algorithm_not_supported(self):
token = "eyJhbGciOiJub25lIn0.eyJpc3MiOiJodHRwczovL3Rva2Vucy10ZXN0LmF1dGgwLmNvbS8iLCJzdWIiOiJhdXRoMHwxMjM0NTY3ODkiLCJhdWQiOlsidG9rZW5zLXRlc3QtMTIzIiwiZXh0ZXJuYWwtdGVzdC05OTkiXSwiZXhwIjoxNTg3NzY1MzYxLCJpYXQiOjE1ODc1OTI1NjEsIm5vbmNlIjoiYTFiMmMzZDRlNSIsImF6cCI6InRva2Vucy10ZXN0LTEyMyIsImF1dGhfdGltZSI6MTU4NzY3ODk2MX0."
self.assert_fails_with_error(token, 'Signature algorithm of "none" is not supported. Expected the token to be signed with "RS256"')
self.assert_fails_with_error(
token,
'Signature algorithm of "none" is not supported. Expected the token to be'
' signed with "RS256"',
)
return

@@ -326,23 +379,42 @@

token = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJhdXRoMHwxMjM0NTY3ODkiLCJhdWQiOlsidG9rZW5zLXRlc3QtMTIzIiwiZXh0ZXJuYWwtdGVzdC05OTkiXSwiZXhwIjoxNTg3NzY1MzYxLCJpYXQiOjE1ODc1OTI1NjEsIm5vbmNlIjoiYTFiMmMzZDRlNSIsImF6cCI6InRva2Vucy10ZXN0LTEyMyIsImF1dGhfdGltZSI6MTU4NzY3ODk2MX0.XuWmo_XxNET0mOW1AaLwi8koUOd05TZULWCGF_3WbeR5VJB6aK0rzo8AkHXrSv9Yr6he_1N8xFDKBIIyXFa4Y2PN8kdwUQtsJcj-cj8_2Ta2S0vV6O7XqbW58eXhX8Ng0OUrqgkHT1leIUJnBZ10YhM0-0zmdIq_WlNnwTdmvAGtYAUGcjyUmq-QEKBc2YYnf83vtGuFT2xGUGsTKR_Jj7lH_QTYdFaiT4t7gwFyXhP5KVUkG3ebdQUkIAQnoY0TXwrgDDCQhAWiUYZehMlv7Ml4tqLsiIUMgm4w5wSfdTdhVEMa7wHPj7gp4s-bfEqaOuyg0xH24rP19LkJROITDw"
self.assert_fails_with_error(token, 'Issuer (iss) claim must be a string present in the ID token')
self.assert_fails_with_error(
token, "Issuer (iss) claim must be a string present in the ID token"
)
def test_fails_with_iss_invalid(self):
token = "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJzb21ldGhpbmctZWxzZSIsInN1YiI6ImF1dGgwfDEyMzQ1Njc4OSIsImF1ZCI6WyJ0b2tlbnMtdGVzdC0xMjMiLCJleHRlcm5hbC10ZXN0LTk5OSJdLCJleHAiOjE1ODc3NjUzNjEsImlhdCI6MTU4NzU5MjU2MSwibm9uY2UiOiJhMWIyYzNkNGU1IiwiYXpwIjoidG9rZW5zLXRlc3QtMTIzIiwiYXV0aF90aW1lIjoxNTg3Njc4OTYxfQ.HNQ1lXWWQOC4D1-D4XfYlF2MBE6F7TW1EoBqt3ayxehNqtc8ZUJ6MR4aE_o7NnY0aBNbp7J9okgRC2PIKPHZkXUdxHvGZNldrEDDKeKPe0kZFxF5sEK8RYCnJk5m28JFpgRYvXA9KjKnLsBsbV--8VnkgRlw0-LClxqp3ynoGgmh2dVvBqXV8DiAbRvvRPZOg7CVFqCxJoMFD0FJ_dej7ChxMDSe_NDW-CjG9rgEsw_el-_vUcKSp7bzZ1jKm0zOcPDRPfgda5oek0xR6_bg2es_TarYKCwlQCVG1NEmgcJ5gNeVIsrwaPrMXqGr9KNs-nLerQO9Jl1EhCU8No5Sfg"
self.assert_fails_with_error(token, 'Issuer (iss) claim mismatch in the ID token; expected "{}", found "something-else"'.format(expectations['issuer']))
self.assert_fails_with_error(
token,
'Issuer (iss) claim mismatch in the ID token; expected "{}", found'
' "something-else"'.format(expectations["issuer"]),
)
def test_fails_with_sub_missing(self):
token = "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczovL3Rva2Vucy10ZXN0LmF1dGgwLmNvbS8iLCJhdWQiOlsidG9rZW5zLXRlc3QtMTIzIiwiZXh0ZXJuYWwtdGVzdC05OTkiXSwiZXhwIjoxNTg3NzY1MzYxLCJpYXQiOjE1ODc1OTI1NjEsIm5vbmNlIjoiYTFiMmMzZDRlNSIsImF6cCI6InRva2Vucy10ZXN0LTEyMyIsImF1dGhfdGltZSI6MTU4NzY3ODk2MX0.VtPtxkKh7vZKECzFiNXLWBeWcRgaX1lIOhW0fKU5WSgTcjYZRYoxW-wwI8pai7vgJMQQCizBpLpjMPpCBYBGEiYgGpa9D7vAD8XmYjcVZujG1FLFGkOTkgisCtgVT6WpvwxIejNrl_TcgSEBkCcD9f7gGnFVOjJe4YtSMEUdtuDz-pHEGGNbJLdq0L-pPUrO2Fyw3NspX1RrEYVn7uGuAlDQWQ4x6IOtM40NPzAmyLVrsOPmz_5Igyi7ZZar6epcfd5dBeUbgp8yK178XV-r6-UMuj39NJE4Bx8cDQR1qjxMsxgZ3Lem6OLfFvKWXsgJs7dh13kJDqrx2jXfhvpd-w"
self.assert_fails_with_error(token, 'Subject (sub) claim must be a string present in the ID token')
self.assert_fails_with_error(
token, "Subject (sub) claim must be a string present in the ID token"
)
def test_fails_with_aud_missing(self):
token = "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczovL3Rva2Vucy10ZXN0LmF1dGgwLmNvbS8iLCJzdWIiOiJhdXRoMHwxMjM0NTY3ODkiLCJleHAiOjE1ODc3NjUzNjEsImlhdCI6MTU4NzU5MjU2MSwibm9uY2UiOiJhMWIyYzNkNGU1IiwiYXpwIjoidG9rZW5zLXRlc3QtMTIzIiwiYXV0aF90aW1lIjoxNTg3Njc4OTYxfQ.t5SBd_J-k_GwPHfyGfPxOcT8n0Pbwy9R-pj7tK8231m3My1Zg3LyKx3tl7MFtymgRHcs2hd4WrWrKjyFrHMOzUWX8dQ2-b6KVRuFQjc70gnW54igj-cT-oo07Lzen0Ol6_7w_5rabWCOL9lM0UM9jpau_llVh97zyYgcUEBeA5lLld5ZLTB-JKMVehjJelBR-MPEDvMr2zT9nRPPUXqezAWZOPYG83oRRB2ktoafaUM4RVvp34q6uUWJq49m-qY2DfKuyDGK4axo1fHKE3JmrsayEDpuGDYDFNDQzy4g1lJvzBKxV2SJl0LKP6sxbM8sw7qaH4ViRNZpFQBZ7veGPQ"
self.assert_fails_with_error(token, 'Audience (aud) claim must be a string or array of strings present in the ID token')
self.assert_fails_with_error(
token,
"Audience (aud) claim must be a string or array of strings present in the"
" ID token",
)
def test_fails_with_aud_invalid(self):
token = "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczovL3Rva2Vucy10ZXN0LmF1dGgwLmNvbS8iLCJzdWIiOiJhdXRoMHwxMjM0NTY3ODkiLCJhdWQiOlsiZXh0ZXJuYWwtdGVzdC05OTkiXSwiZXhwIjoxNTg3NzY1MzYxLCJpYXQiOjE1ODc1OTI1NjEsIm5vbmNlIjoiYTFiMmMzZDRlNSIsImF6cCI6InRva2Vucy10ZXN0LTEyMyIsImF1dGhfdGltZSI6MTU4NzY3ODk2MX0.d1BFaw_h5VOAw0tXAQ98hrru4gWCNjIxcCQktFVcLIqrX9m74-vWv2SVoFBAQlXihEXoDS-5QSMhVPG1iry9arseN16PnSOmilBhSebiqAVSBojLxq5KFEDuUz90lApt4d5BSCMAIAQ1Dp1pGKwJC0BiLrFNOQ2KrmoEvQMgaD0PLlCLy1lL7MntABE86tX_BoqI4ZkWJ1lX1n2-SZAn-ldoOK8W8RUYiwBUDTktpgAfICFUSPAZXj_vn05vwvQBoozhMQkuJrPziz81Tj8lPh0iPsnMBtsAqvAhdwtp3p-eadXPVcjNu4yE3dkBgFDQwoNtV_elWQtmFBn49FEKyw"
self.assert_fails_with_error(token, 'Audience (aud) claim mismatch in the ID token; expected "{}" but was not one of "external-test-999"'.format(expectations['audience']))
self.assert_fails_with_error(
token,
'Audience (aud) claim mismatch in the ID token; expected "{}" but was not'
' one of "external-test-999"'.format(expectations["audience"]),
)
def test_fails_with_exp_missing(self):
token = "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczovL3Rva2Vucy10ZXN0LmF1dGgwLmNvbS8iLCJzdWIiOiJhdXRoMHwxMjM0NTY3ODkiLCJhdWQiOlsidG9rZW5zLXRlc3QtMTIzIiwiZXh0ZXJuYWwtdGVzdC05OTkiXSwiaWF0IjoxNTg3NTkyNTYxLCJub25jZSI6ImExYjJjM2Q0ZTUiLCJhenAiOiJ0b2tlbnMtdGVzdC0xMjMiLCJhdXRoX3RpbWUiOjE1ODc2Nzg5NjF9.qq4Tyz8VGnAJy2KmKo3zmThnWXviGwJB-Bz18lnJlicjAXk4ObeUVoX0WHB3I8vmDMscC9JXhkDP5KIGSAkeaLzil0FFJwwQB_saFE_y3zjfMQgdsz_qtDR96S1SQtnZ7AhChIAZ7cV4p_wmj_-TQYuZVQ0F6MoBmFsJITIr7gxnNFJWw6KJEU94nq8-q_IAyC5-9epdEtphUi_wkalHzEy6w8tQawKXCLYxo12VNlEy5mi8PlwqGsqVcwFwqec-ERt2hajyuqL1210-cZJMA-NmXz4mv4scHdiE09KZcLScKcezs9KaM5iaButMBL0Fyec0KcwwfELX_zghekALOA"
self.assert_fails_with_error(token, 'Expiration Time (exp) claim must be a number present in the ID token')
self.assert_fails_with_error(
token,
"Expiration Time (exp) claim must be a number present in the ID token",
)

@@ -352,7 +424,14 @@ def test_fails_with_exp_invalid(self):

mocked_clock = MOCKED_CLOCK + DEFAULT_LEEWAY + 1
self.assert_fails_with_error(token, 'Expiration Time (exp) claim error in the ID token; current time ({}) is after expiration time (1587592621)'.format(mocked_clock), clock=mocked_clock)
self.assert_fails_with_error(
token,
"Expiration Time (exp) claim error in the ID token; current time ({}) is"
" after expiration time (1587592621)".format(mocked_clock),
clock=mocked_clock,
)
def test_fails_with_iat_missing(self):
token = "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczovL3Rva2Vucy10ZXN0LmF1dGgwLmNvbS8iLCJzdWIiOiJhdXRoMHwxMjM0NTY3ODkiLCJhdWQiOlsidG9rZW5zLXRlc3QtMTIzIiwiZXh0ZXJuYWwtdGVzdC05OTkiXSwiZXhwIjoxNTg3NzY1MzYxLCJub25jZSI6ImExYjJjM2Q0ZTUiLCJhenAiOiJ0b2tlbnMtdGVzdC0xMjMiLCJhdXRoX3RpbWUiOjE1ODc2Nzg5NjF9.CWW7mWUhiI-rramQ2dIGi7vBsOMmsouIg32IL9u2g4Dg3PV0C55R7dL6Jvf9hqaZXvx9Psrw0vLnOlhFztAC6LlQuq2eCaLYsDme36NxeYGC7CFXygvlU_eXD5IdNK35GriTfpG_b5hC7tl2glMmNQcZWlsIyKw7eq8o1POpqo0K2bCVjoyJkHL6WUpw6_08HPspmTL_Qd0km08z6zgvbl8Hpzk-tLmXqN7LjmuhEsjnIFphu-dGwcQsoY3RAomYxAFXAPYT8siEIf2w3zlIoUde-mujiMUtMD-Od7t7w36GO6Kubb9M9inVwPEg1yFKlFTXZBKXu91xmOmvMJ5Qfg"
self.assert_fails_with_error(token, 'Issued At (iat) claim must be a number present in the ID token')
self.assert_fails_with_error(
token, "Issued At (iat) claim must be a number present in the ID token"
)

@@ -365,4 +444,4 @@ def test_passes_when_nonce_missing_but_not_required(self):

signature_verifier=sv,
issuer=expectations['issuer'],
audience=expectations['audience']
issuer=expectations["issuer"],
audience=expectations["audience"],
)

@@ -374,20 +453,41 @@ tv._clock = MOCKED_CLOCK

token = "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczovL3Rva2Vucy10ZXN0LmF1dGgwLmNvbS8iLCJzdWIiOiJhdXRoMHwxMjM0NTY3ODkiLCJhdWQiOlsidG9rZW5zLXRlc3QtMTIzIiwiZXh0ZXJuYWwtdGVzdC05OTkiXSwiZXhwIjoxNTg3NzY1MzYxLCJpYXQiOjE1ODc1OTI1NjEsImF6cCI6InRva2Vucy10ZXN0LTEyMyIsImF1dGhfdGltZSI6MTU4NzY3ODk2MX0.L-DveLCDf4Te7x3JZmQ6rCkUQrenl1NFpHqKD8Fs-glhd2iyc-TYffk1M30T0-wBri-3tTgraDAjZAjXuwSk0gV_V5uKCHyIoSRphrC88aX8IeECteQpHa4KR15lbzA5JdVhJu7LuCZ2EFvdjHh5GiViLRWsTSHGUM-uqcMK0q2kWGvCEgfOIXqocnQiyCNITxfgMYJd38zOsVeP7HFf9riuFEQz65oER22o3xyIZ-ILSaU10n6Ob559Rbjc0NVKH4hrggRg8kG7cJCiXbRxXnzO_VM8LmRHhF56jh3ZSrO4bzQa5xv04bMbX6A77muMZD0vghsaslvpWerWbwaSQQ"
self.assert_fails_with_error(token, 'Nonce (nonce) claim must be a string present in the ID token', nonce=expectations['nonce'])
self.assert_fails_with_error(
token,
"Nonce (nonce) claim must be a string present in the ID token",
nonce=expectations["nonce"],
)
def test_fails_with_nonce_invalid(self):
token = "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczovL3Rva2Vucy10ZXN0LmF1dGgwLmNvbS8iLCJzdWIiOiJhdXRoMHwxMjM0NTY3ODkiLCJhdWQiOlsidG9rZW5zLXRlc3QtMTIzIiwiZXh0ZXJuYWwtdGVzdC05OTkiXSwiZXhwIjoxNTg3NzY1MzYxLCJpYXQiOjE1ODc1OTI1NjEsIm5vbmNlIjoiMDAwOTk5IiwiYXpwIjoidG9rZW5zLXRlc3QtMTIzIiwiYXV0aF90aW1lIjoxNTg3Njc4OTYxfQ.Z0n4vKcTCTrKJXUx56TyoQk3-okpjOqCDRN9NqH5zkCi0at7WV-E3TxGbXpIN0UsXwUWxrHiuvL9lN2M4PoIvL4XvzUqgsepAYYBCPGR9Wxb-ALmhhWdS_LNRVAgfUCn94khc_G51XtyeP0bQgWRkV7VbeWxkBTnrhmGwEkVx6XbfpnTRUCDSR_luJfUu84LkFJf1n2ohnEU7Q74BXJjxIIJnhZrg4J65E3cNtZ9N7AOIrbpbZ0oB7NhcZP0xA0A75qt7ZnKOuLsbRppZjcz56QmVIArOSCkkegl3qLx4cNdVa-O840AQWCwkAcHxS9lHBIWyaToC7IVMOLxIcGVlQ"
self.assert_fails_with_error(token, 'Nonce (nonce) claim mismatch in the ID token; expected "{}", found "000999"'.format(expectations['nonce']), nonce=expectations['nonce'])
self.assert_fails_with_error(
token,
'Nonce (nonce) claim mismatch in the ID token; expected "{}", found'
' "000999"'.format(expectations["nonce"]),
nonce=expectations["nonce"],
)
def test_fails_with_aud_array_and_azp_missing(self):
token = "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczovL3Rva2Vucy10ZXN0LmF1dGgwLmNvbS8iLCJzdWIiOiJhdXRoMHwxMjM0NTY3ODkiLCJhdWQiOlsidG9rZW5zLXRlc3QtMTIzIiwiZXh0ZXJuYWwtdGVzdC05OTkiXSwiZXhwIjoxNTg3NzY1MzYxLCJpYXQiOjE1ODc1OTI1NjEsIm5vbmNlIjoiYTFiMmMzZDRlNSIsImF1dGhfdGltZSI6MTU4NzY3ODk2MX0.Xpxc2tj3sDwAYftYAcoiLO3kq0X54KSngDzQu_foTjlDQFTPApVVrX_BQqMAUFsmiNdt-3Tf9lkUlAagpvXy_VUY5LIjzEihEKDzqQFMQ8wm7RK7qV2XLS1abltxXd8AuOHcPnVHbtERpsCXR5eRt0-ESSPUw_scqHOwmYQOFF0sOQJ72r9EYZFMGhojyzpbzhBF0jgi9wMqj0VSpLEzZ3MnkWBCTlmc5OAPXQGdq6C1dVfcBXy4iiIBEaPCG962Yqrr-bbL92_T_XG-FmtpIViuRjHDWRJ26uoD0cmXwePwojxlyeY7VrAoKX3VtA4lm1Co0BMh9DjMKv-p3zT6XA"
self.assert_fails_with_error(token, 'Authorized Party (azp) claim must be a string present in the ID token when Audience (aud) claim has multiple values')
self.assert_fails_with_error(
token,
"Authorized Party (azp) claim must be a string present in the ID token when"
" Audience (aud) claim has multiple values",
)
def test_fails_with_aud_array_and_azp_invalid(self):
token = "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczovL3Rva2Vucy10ZXN0LmF1dGgwLmNvbS8iLCJzdWIiOiJhdXRoMHwxMjM0NTY3ODkiLCJhdWQiOlsidG9rZW5zLXRlc3QtMTIzIiwiZXh0ZXJuYWwtdGVzdC05OTkiXSwiZXhwIjoxNTg3NzY1MzYxLCJpYXQiOjE1ODc1OTI1NjEsIm5vbmNlIjoiYTFiMmMzZDRlNSIsImF6cCI6ImV4dGVybmFsLXRlc3QtOTk5IiwiYXV0aF90aW1lIjoxNTg3Njc4OTYxfQ.Bx56kdY8rBwlAZ8Walh6NjONs94Tdv37iP0EPKFxvpELFt_8RENhPp8Lqe52zrrgXqUdA1eeBynegqH7_duJawQ0l86u2dsaPonMOsh_W8ZjaqPOVHLv1z7xQb84UdjMSSJbMGMLPmuX2GMlc5hcjW5YgWU1xp-gpNpKMIzW19gNxpwtIWkLZ5zkjEVBYHSTAw7CO6HkncTZBqdYA3bq3ziQPljqvSvyPehuJ-2Q5TlrdVLRO5HS4-C6NEs-h8fpX25NP537FM9g7T7pRB1wDxsrJTny6uKBKFCwtNSF5laojV2edEDlDUsEEUCGh6zUzITGeZNa0M52ZsxGoAehIw"
self.assert_fails_with_error(token,
'Authorized Party (azp) claim mismatch in the ID token; expected "{}", found "external-test-999"'.format(expectations['audience']))
self.assert_fails_with_error(
token,
'Authorized Party (azp) claim mismatch in the ID token; expected "{}",'
' found "external-test-999"'.format(expectations["audience"]),
)
def test_fails_when_max_age_sent_with_auth_time_missing(self):
token = "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczovL3Rva2Vucy10ZXN0LmF1dGgwLmNvbS8iLCJzdWIiOiJhdXRoMHwxMjM0NTY3ODkiLCJhdWQiOlsidG9rZW5zLXRlc3QtMTIzIiwiZXh0ZXJuYWwtdGVzdC05OTkiXSwiZXhwIjoxNTg3NzY1MzYxLCJpYXQiOjE1ODc1OTI1NjEsIm5vbmNlIjoiYTFiMmMzZDRlNSIsImF6cCI6InRva2Vucy10ZXN0LTEyMyJ9.pWr6hjQ9Mi9cYSYIFWG1d-KJ98OeKeKb3F7X_DdUgQ5Xir8wHLLuZDrFAalKlxYiTJTMXqh9YkxKLcEjFQsTECEXA4VMliUv4A2Egk8EDUi5SQtoQ11xGJo-S7qM4cL-x-69ZnJvNWlZZ8NnvtTOSgzpa_fsG7T3PScr0b9ukxOQ-o8suV2fLE7bOliBKZn9PC7sowtF_oeQ03f0e0thtZFl121ROL65ARh9C-ic2azgmIn3YgsvguaoT5ZpAFRe2McaP026bNimOmfEzVIwHCDuR6rkFZvX4QUduX6UQ4bOQp_EC9G0XDk08H0nBXx2JXSHCW4YPZz9bz1f12B4kg"
self.assert_fails_with_error(token, "Authentication Time (auth_time) claim must be a number present in the ID token when Max Age (max_age) is specified", max_age=120)
self.assert_fails_with_error(
token,
"Authentication Time (auth_time) claim must be a number present in the ID"
" token when Max Age (max_age) is specified",
max_age=120,
)

@@ -400,3 +500,10 @@ def test_fails_when_max_age_sent_with_auth_time_invalid(self):

self.assert_fails_with_error(token, "Authentication Time (auth_time) claim in the ID token indicates that too much time has passed since the last end-user authentication. Current time ({}) is after last auth at ({})".format(mocked_clock, expected_auth_time), max_age=max_age, clock=mocked_clock)
self.assert_fails_with_error(
token,
"Authentication Time (auth_time) claim in the ID token indicates that too"
" much time has passed since the last end-user authentication. Current time"
" ({}) is after last auth at ({})".format(mocked_clock, expected_auth_time),
max_age=max_age,
clock=mocked_clock,
)

@@ -408,4 +515,4 @@ def test_passes_when_org_present_but_not_required(self):

signature_verifier=sv,
issuer=expectations['issuer'],
audience=expectations['audience']
issuer=expectations["issuer"],
audience=expectations["audience"],
)

@@ -420,19 +527,35 @@ tv._clock = MOCKED_CLOCK

signature_verifier=sv,
issuer=expectations['issuer'],
audience=expectations['audience']
issuer=expectations["issuer"],
audience=expectations["audience"],
)
tv._clock = MOCKED_CLOCK
tv.verify(token, organization='org_123')
tv.verify(token, organization="org_123")
def test_fails_when_org_specified_but_not_present(self):
token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhdXRoMHxzZGs0NThma3MiLCJhdWQiOiJ0b2tlbnMtdGVzdC0xMjMiLCJpc3MiOiJodHRwczovL3Rva2Vucy10ZXN0LmF1dGgwLmNvbS8iLCJleHAiOjE1ODc3NjUzNjEsImlhdCI6MTU4NzU5MjU2MX0.wotJnUdD5IfdZMewF_-BnHc0pI56uwzwr5qaSXvSu9w"
self.assert_fails_with_error(token, "Organization (org_id) claim must be a string present in the ID token", signature_verifier=SymmetricSignatureVerifier(HMAC_SHARED_SECRET), organization='org_123')
self.assert_fails_with_error(
token,
"Organization (org_id) claim must be a string present in the ID token",
signature_verifier=SymmetricSignatureVerifier(HMAC_SHARED_SECRET),
organization="org_123",
)
def test_fails_when_org_specified_but_not_(self):
token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhdXRoMHxzZGs0NThma3MiLCJhdWQiOiJ0b2tlbnMtdGVzdC0xMjMiLCJvcmdfaWQiOjQyLCJpc3MiOiJodHRwczovL3Rva2Vucy10ZXN0LmF1dGgwLmNvbS8iLCJleHAiOjE1ODc3NjUzNjEsImlhdCI6MTU4NzU5MjU2MX0.fGL1_akaHikdovS7NRYla3flne1xdtCjP0ei_CRxO6k"
self.assert_fails_with_error(token, "Organization (org_id) claim must be a string present in the ID token", signature_verifier=SymmetricSignatureVerifier(HMAC_SHARED_SECRET), organization='org_123')
self.assert_fails_with_error(
token,
"Organization (org_id) claim must be a string present in the ID token",
signature_verifier=SymmetricSignatureVerifier(HMAC_SHARED_SECRET),
organization="org_123",
)
def test_fails_when_org_specified_but_does_not_match(self):
token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhdXRoMHxzZGs0NThma3MiLCJhdWQiOiJ0b2tlbnMtdGVzdC0xMjMiLCJvcmdfaWQiOiJvcmdfMTIzIiwiaXNzIjoiaHR0cHM6Ly90b2tlbnMtdGVzdC5hdXRoMC5jb20vIiwiZXhwIjoxNTg3NzY1MzYxLCJpYXQiOjE1ODc1OTI1NjF9.hjSPgJpg0Dn2z0giCdGqVLD5Kmqy_yMYlSkgwKD7ahQ"
self.assert_fails_with_error(token, 'Organization (org_id) claim mismatch in the ID token; expected "org_abc", found "org_123"', signature_verifier=SymmetricSignatureVerifier(HMAC_SHARED_SECRET), organization='org_abc')
self.assert_fails_with_error(
token,
'Organization (org_id) claim mismatch in the ID token; expected "org_abc",'
' found "org_123"',
signature_verifier=SymmetricSignatureVerifier(HMAC_SHARED_SECRET),
organization="org_abc",
)

@@ -444,13 +567,13 @@ def test_verify_returns_payload(self):

signature_verifier=sv,
issuer=expectations['issuer'],
audience=expectations['audience']
issuer=expectations["issuer"],
audience=expectations["audience"],
)
tv._clock = MOCKED_CLOCK
response = tv.verify(token)
self.assertIn('sub', response);
self.assertIn('aud', response);
self.assertIn('org_id', response);
self.assertIn('iss', response);
self.assertIn('exp', response);
self.assertIn('iat', response);
self.assertEqual('org_123', response['org_id'])
self.assertIn("sub", response)
self.assertIn("aud", response)
self.assertIn("org_id", response)
self.assertIn("iss", response)
self.assertIn("exp", response)
self.assertIn("iat", response)
self.assertEqual("org_123", response["org_id"])
import unittest
import mock
from ...authentication.users import Users

@@ -7,25 +9,23 @@

class TestUsers(unittest.TestCase):
@mock.patch('auth0.v3.authentication.users.Users.get')
@mock.patch("auth0.v3.authentication.users.Users.get")
def test_userinfo(self, mock_get):
u = Users('my.domain.com')
u = Users("my.domain.com")
u.userinfo(access_token='atk')
u.userinfo(access_token="atk")
mock_get.assert_called_with(
url='https://my.domain.com/userinfo',
headers={'Authorization': 'Bearer atk'}
url="https://my.domain.com/userinfo",
headers={"Authorization": "Bearer atk"},
)
@mock.patch('auth0.v3.authentication.users.Users.post')
@mock.patch("auth0.v3.authentication.users.Users.post")
def test_tokeninfo(self, mock_post):
u = Users('my.domain.com')
u = Users("my.domain.com")
u.tokeninfo(jwt='jwtoken')
u.tokeninfo(jwt="jwtoken")
mock_post.assert_called_with(
url='https://my.domain.com/tokeninfo',
data={'id_token': 'jwtoken'}
url="https://my.domain.com/tokeninfo", data={"id_token": "jwtoken"}
)
import unittest
import mock
from ...management.actions import Actions

@@ -7,14 +9,13 @@

class TestActions(unittest.TestCase):
def test_init_with_optionals(self):
t = Actions(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = Actions(domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2))
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.actions.RestClient')
@mock.patch("auth0.v3.management.actions.RestClient")
def test_get_actions(self, mock_rc):
mock_instance = mock_rc.return_value
c = Actions(domain='domain', token='jwttoken')
c = Actions(domain="domain", token="jwttoken")

@@ -24,73 +25,87 @@ c.get_actions()

self.assertEqual('https://domain/api/v2/actions/actions', args[0])
self.assertEqual(kwargs['params'], {'triggerId': None,
'actionName': None,
'deployed': None,
'installed': 'false',
'page': None,
'per_page': None})
self.assertEqual("https://domain/api/v2/actions/actions", args[0])
self.assertEqual(
kwargs["params"],
{
"triggerId": None,
"actionName": None,
"deployed": None,
"installed": "false",
"page": None,
"per_page": None,
},
)
c.get_actions('trigger-id', 'action-name', True, True, 0, 5)
c.get_actions("trigger-id", "action-name", True, True, 0, 5)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/actions/actions', args[0])
self.assertEqual(kwargs['params'], {'triggerId': 'trigger-id',
'actionName': 'action-name',
'deployed': 'true',
'installed': 'true',
'page': 0,
'per_page': 5})
self.assertEqual("https://domain/api/v2/actions/actions", args[0])
self.assertEqual(
kwargs["params"],
{
"triggerId": "trigger-id",
"actionName": "action-name",
"deployed": "true",
"installed": "true",
"page": 0,
"per_page": 5,
},
)
c.get_actions('trigger-id', 'action-name', False, True, 0, 5)
c.get_actions("trigger-id", "action-name", False, True, 0, 5)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/actions/actions', args[0])
self.assertEqual(kwargs['params'], {'triggerId': 'trigger-id',
'actionName': 'action-name',
'deployed': 'false',
'installed': 'true',
'page': 0,
'per_page': 5})
self.assertEqual("https://domain/api/v2/actions/actions", args[0])
self.assertEqual(
kwargs["params"],
{
"triggerId": "trigger-id",
"actionName": "action-name",
"deployed": "false",
"installed": "true",
"page": 0,
"per_page": 5,
},
)
@mock.patch('auth0.v3.management.actions.RestClient')
@mock.patch("auth0.v3.management.actions.RestClient")
def test_create_action(self, mock_rc):
mock_instance = mock_rc.return_value
c = Actions(domain='domain', token='jwttoken')
c.create_action({'a': 'b', 'c': 'd'})
c = Actions(domain="domain", token="jwttoken")
c.create_action({"a": "b", "c": "d"})
mock_instance.post.assert_called_with(
'https://domain/api/v2/actions/actions',
data={'a': 'b', 'c': 'd'}
"https://domain/api/v2/actions/actions", data={"a": "b", "c": "d"}
)
@mock.patch('auth0.v3.management.actions.RestClient')
@mock.patch("auth0.v3.management.actions.RestClient")
def test_update_action(self, mock_rc):
mock_instance = mock_rc.return_value
c = Actions(domain='domain', token='jwttoken')
c.update_action('action-id', {'a': 'b', 'c': 'd'})
c = Actions(domain="domain", token="jwttoken")
c.update_action("action-id", {"a": "b", "c": "d"})
args, kwargs = mock_instance.patch.call_args
self.assertEqual('https://domain/api/v2/actions/actions/action-id', args[0])
self.assertEqual(kwargs['data'], {'a': 'b', 'c': 'd'})
self.assertEqual("https://domain/api/v2/actions/actions/action-id", args[0])
self.assertEqual(kwargs["data"], {"a": "b", "c": "d"})
@mock.patch('auth0.v3.management.actions.RestClient')
@mock.patch("auth0.v3.management.actions.RestClient")
def test_get_action(self, mock_rc):
mock_instance = mock_rc.return_value
c = Actions(domain='domain', token='jwttoken')
c.get_action('action-id')
c = Actions(domain="domain", token="jwttoken")
c.get_action("action-id")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/actions/actions/action-id', args[0])
self.assertEqual(kwargs['params'], {})
self.assertEqual("https://domain/api/v2/actions/actions/action-id", args[0])
self.assertEqual(kwargs["params"], {})
@mock.patch('auth0.v3.management.actions.RestClient')
@mock.patch("auth0.v3.management.actions.RestClient")
def test_get_triggers(self, mock_rc):
mock_instance = mock_rc.return_value
c = Actions(domain='domain', token='jwttoken')
c = Actions(domain="domain", token="jwttoken")
c.get_triggers()

@@ -100,124 +115,139 @@

self.assertEqual('https://domain/api/v2/actions/triggers', args[0])
self.assertEqual(kwargs['params'], {})
self.assertEqual("https://domain/api/v2/actions/triggers", args[0])
self.assertEqual(kwargs["params"], {})
@mock.patch('auth0.v3.management.actions.RestClient')
@mock.patch("auth0.v3.management.actions.RestClient")
def test_delete_action(self, mock_rc):
mock_instance = mock_rc.return_value
c = Actions(domain='domain', token='jwttoken')
c.delete_action('action-id')
c = Actions(domain="domain", token="jwttoken")
c.delete_action("action-id")
args, kwargs = mock_instance.delete.call_args
self.assertEqual('https://domain/api/v2/actions/actions/action-id', args[0])
self.assertEqual(kwargs['params'], {'force': 'false'})
self.assertEqual("https://domain/api/v2/actions/actions/action-id", args[0])
self.assertEqual(kwargs["params"], {"force": "false"})
c.delete_action('action-id', True)
c.delete_action("action-id", True)
args, kwargs = mock_instance.delete.call_args
self.assertEqual('https://domain/api/v2/actions/actions/action-id', args[0])
self.assertEqual(kwargs['params'], {'force': 'true'})
self.assertEqual("https://domain/api/v2/actions/actions/action-id", args[0])
self.assertEqual(kwargs["params"], {"force": "true"})
@mock.patch('auth0.v3.management.actions.RestClient')
@mock.patch("auth0.v3.management.actions.RestClient")
def test_get_execution(self, mock_rc):
mock_instance = mock_rc.return_value
c = Actions(domain='domain', token='jwttoken')
c.get_execution('execution-id')
c = Actions(domain="domain", token="jwttoken")
c.get_execution("execution-id")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/actions/executions/execution-id', args[0])
self.assertEqual(kwargs['params'], {})
self.assertEqual(
"https://domain/api/v2/actions/executions/execution-id", args[0]
)
self.assertEqual(kwargs["params"], {})
@mock.patch('auth0.v3.management.actions.RestClient')
@mock.patch("auth0.v3.management.actions.RestClient")
def test_get_action_versions(self, mock_rc):
mock_instance = mock_rc.return_value
c = Actions(domain='domain', token='jwttoken')
c.get_action_versions('action-id')
c = Actions(domain="domain", token="jwttoken")
c.get_action_versions("action-id")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/actions/actions/action-id/versions', args[0])
self.assertEqual(kwargs['params'], {'page': None,
'per_page': None})
self.assertEqual(
"https://domain/api/v2/actions/actions/action-id/versions", args[0]
)
self.assertEqual(kwargs["params"], {"page": None, "per_page": None})
c.get_action_versions('action-id', 0, 5)
c.get_action_versions("action-id", 0, 5)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/actions/actions/action-id/versions', args[0])
self.assertEqual(kwargs['params'], {'page': 0,
'per_page': 5})
self.assertEqual(
"https://domain/api/v2/actions/actions/action-id/versions", args[0]
)
self.assertEqual(kwargs["params"], {"page": 0, "per_page": 5})
@mock.patch('auth0.v3.management.actions.RestClient')
@mock.patch("auth0.v3.management.actions.RestClient")
def test_get_trigger_bindings(self, mock_rc):
mock_instance = mock_rc.return_value
c = Actions(domain='domain', token='jwttoken')
c.get_trigger_bindings('trigger-id')
c = Actions(domain="domain", token="jwttoken")
c.get_trigger_bindings("trigger-id")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/actions/triggers/trigger-id/bindings', args[0])
self.assertEqual(kwargs['params'], {'page': None,
'per_page': None})
self.assertEqual(
"https://domain/api/v2/actions/triggers/trigger-id/bindings", args[0]
)
self.assertEqual(kwargs["params"], {"page": None, "per_page": None})
c.get_trigger_bindings('trigger-id', 0, 5)
c.get_trigger_bindings("trigger-id", 0, 5)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/actions/triggers/trigger-id/bindings', args[0])
self.assertEqual(kwargs['params'], {'page': 0,
'per_page': 5})
self.assertEqual(
"https://domain/api/v2/actions/triggers/trigger-id/bindings", args[0]
)
self.assertEqual(kwargs["params"], {"page": 0, "per_page": 5})
@mock.patch('auth0.v3.management.actions.RestClient')
@mock.patch("auth0.v3.management.actions.RestClient")
def test_get_action_version(self, mock_rc):
mock_instance = mock_rc.return_value
c = Actions(domain='domain', token='jwttoken')
c.get_action_version('action-id', 'version-id')
c = Actions(domain="domain", token="jwttoken")
c.get_action_version("action-id", "version-id")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/actions/actions/action-id/versions/version-id', args[0])
self.assertEqual(kwargs['params'], {})
self.assertEqual(
"https://domain/api/v2/actions/actions/action-id/versions/version-id",
args[0],
)
self.assertEqual(kwargs["params"], {})
@mock.patch('auth0.v3.management.actions.RestClient')
@mock.patch("auth0.v3.management.actions.RestClient")
def test_deploy_action(self, mock_rc):
mock_instance = mock_rc.return_value
c = Actions(domain='domain', token='jwttoken')
c.deploy_action('action-id')
c = Actions(domain="domain", token="jwttoken")
c.deploy_action("action-id")
args, kwargs = mock_instance.post.call_args
self.assertEqual('https://domain/api/v2/actions/actions/action-id/deploy', args[0])
self.assertEqual(
"https://domain/api/v2/actions/actions/action-id/deploy", args[0]
)
@mock.patch('auth0.v3.management.actions.RestClient')
@mock.patch("auth0.v3.management.actions.RestClient")
def test_rollback_action(self, mock_rc):
mock_instance = mock_rc.return_value
c = Actions(domain='domain', token='jwttoken')
c.rollback_action_version('action-id', 'version-id')
c = Actions(domain="domain", token="jwttoken")
c.rollback_action_version("action-id", "version-id")
args, kwargs = mock_instance.post.call_args
self.assertEqual('https://domain/api/v2/actions/actions/action-id/versions/version-id/deploy', args[0])
self.assertEqual(kwargs['data'], {})
self.assertEqual(
"https://domain/api/v2/actions/actions/action-id/versions/version-id/deploy",
args[0],
)
self.assertEqual(kwargs["data"], {})
@mock.patch('auth0.v3.management.actions.RestClient')
@mock.patch("auth0.v3.management.actions.RestClient")
def test_update_trigger_bindings(self, mock_rc):
mock_instance = mock_rc.return_value
c = Actions(domain='domain', token='jwttoken')
c.update_trigger_bindings('trigger-id', {'a': 'b', 'c': 'd'})
c = Actions(domain="domain", token="jwttoken")
c.update_trigger_bindings("trigger-id", {"a": "b", "c": "d"})
args, kwargs = mock_instance.patch.call_args
self.assertEqual('https://domain/api/v2/actions/triggers/trigger-id/bindings', args[0])
self.assertEqual(kwargs['data'], {'a': 'b', 'c': 'd'})
self.assertEqual(
"https://domain/api/v2/actions/triggers/trigger-id/bindings", args[0]
)
self.assertEqual(kwargs["data"], {"a": "b", "c": "d"})
import unittest
import mock
from ...management.attack_protection import AttackProtection

@@ -7,10 +9,11 @@

class TestAttackProtection(unittest.TestCase):
def test_init_with_optionals(self):
t = AttackProtection(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = AttackProtection(
domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2)
)
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.attack_protection.RestClient')
@mock.patch("auth0.v3.management.attack_protection.RestClient")
def test_get_breached_password_detection(self, mock_rc):

@@ -20,3 +23,3 @@ mock_instance = mock_rc.return_value

ap = AttackProtection(domain='domain', token='jwttoken')
ap = AttackProtection(domain="domain", token="jwttoken")
ap.get_breached_password_detection()

@@ -26,5 +29,8 @@

self.assertEqual('https://domain/api/v2/attack-protection/breached-password-detection', args[0])
self.assertEqual(
"https://domain/api/v2/attack-protection/breached-password-detection",
args[0],
)
@mock.patch('auth0.v3.management.attack_protection.RestClient')
@mock.patch("auth0.v3.management.attack_protection.RestClient")
def test_update_breached_password_detection(self, mock_rc):

@@ -34,11 +40,11 @@ mock_instance = mock_rc.return_value

c = AttackProtection(domain='domain', token='jwttoken')
c.update_breached_password_detection({'a': 'b', 'c': 'd'})
c = AttackProtection(domain="domain", token="jwttoken")
c.update_breached_password_detection({"a": "b", "c": "d"})
mock_instance.patch.assert_called_with(
'https://domain/api/v2/attack-protection/breached-password-detection',
data={'a': 'b', 'c': 'd'}
"https://domain/api/v2/attack-protection/breached-password-detection",
data={"a": "b", "c": "d"},
)
@mock.patch('auth0.v3.management.attack_protection.RestClient')
@mock.patch("auth0.v3.management.attack_protection.RestClient")
def test_get_brute_force_protection(self, mock_rc):

@@ -48,3 +54,3 @@ mock_instance = mock_rc.return_value

ap = AttackProtection(domain='domain', token='jwttoken')
ap = AttackProtection(domain="domain", token="jwttoken")
ap.get_brute_force_protection()

@@ -54,5 +60,7 @@

self.assertEqual('https://domain/api/v2/attack-protection/brute-force-protection', args[0])
self.assertEqual(
"https://domain/api/v2/attack-protection/brute-force-protection", args[0]
)
@mock.patch('auth0.v3.management.attack_protection.RestClient')
@mock.patch("auth0.v3.management.attack_protection.RestClient")
def test_update_brute_force_protection(self, mock_rc):

@@ -62,11 +70,11 @@ mock_instance = mock_rc.return_value

c = AttackProtection(domain='domain', token='jwttoken')
c.update_brute_force_protection({'a': 'b', 'c': 'd'})
c = AttackProtection(domain="domain", token="jwttoken")
c.update_brute_force_protection({"a": "b", "c": "d"})
mock_instance.patch.assert_called_with(
'https://domain/api/v2/attack-protection/brute-force-protection',
data={'a': 'b', 'c': 'd'}
"https://domain/api/v2/attack-protection/brute-force-protection",
data={"a": "b", "c": "d"},
)
@mock.patch('auth0.v3.management.attack_protection.RestClient')
@mock.patch("auth0.v3.management.attack_protection.RestClient")
def test_get_suspicious_ip_throttling(self, mock_rc):

@@ -76,3 +84,3 @@ mock_instance = mock_rc.return_value

ap = AttackProtection(domain='domain', token='jwttoken')
ap = AttackProtection(domain="domain", token="jwttoken")
ap.get_suspicious_ip_throttling()

@@ -82,5 +90,7 @@

self.assertEqual('https://domain/api/v2/attack-protection/suspicious-ip-throttling', args[0])
self.assertEqual(
"https://domain/api/v2/attack-protection/suspicious-ip-throttling", args[0]
)
@mock.patch('auth0.v3.management.attack_protection.RestClient')
@mock.patch("auth0.v3.management.attack_protection.RestClient")
def test_update_suspicious_ip_throttling(self, mock_rc):

@@ -90,8 +100,8 @@ mock_instance = mock_rc.return_value

c = AttackProtection(domain='domain', token='jwttoken')
c.update_suspicious_ip_throttling({'a': 'b', 'c': 'd'})
c = AttackProtection(domain="domain", token="jwttoken")
c.update_suspicious_ip_throttling({"a": "b", "c": "d"})
mock_instance.patch.assert_called_with(
'https://domain/api/v2/attack-protection/suspicious-ip-throttling',
data={'a': 'b', 'c': 'd'}
"https://domain/api/v2/attack-protection/suspicious-ip-throttling",
data={"a": "b", "c": "d"},
)
import unittest
from ...management.auth0 import Auth0
from ...management.actions import Actions
from ...management.attack_protection import AttackProtection
from ...management.auth0 import Auth0
from ...management.blacklists import Blacklists

@@ -7,0 +7,0 @@ from ...management.client_grants import ClientGrants

import unittest
import mock
from ...management.blacklists import Blacklists

@@ -7,41 +9,41 @@

class TestBlacklists(unittest.TestCase):
def test_init_with_optionals(self):
t = Blacklists(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = Blacklists(
domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2)
)
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.blacklists.RestClient')
@mock.patch("auth0.v3.management.blacklists.RestClient")
def test_get(self, mock_rc):
mock_instance = mock_rc.return_value
t = Blacklists(domain='domain', token='jwttoken')
t.get(aud='an-id')
t = Blacklists(domain="domain", token="jwttoken")
t.get(aud="an-id")
mock_instance.get.assert_called_with(
'https://domain/api/v2/blacklists/tokens',
params={'aud': 'an-id'}
"https://domain/api/v2/blacklists/tokens", params={"aud": "an-id"}
)
@mock.patch('auth0.v3.management.blacklists.RestClient')
@mock.patch("auth0.v3.management.blacklists.RestClient")
def test_create(self, mock_rc):
mock_instance = mock_rc.return_value
t = Blacklists(domain='domain', token='jwttoken')
t = Blacklists(domain="domain", token="jwttoken")
# create without audience
t.create(jti='the-jti')
t.create(jti="the-jti")
args, kwargs = mock_instance.post.call_args
self.assertEqual('https://domain/api/v2/blacklists/tokens', args[0])
self.assertEqual(kwargs['data'], {'jti': 'the-jti'})
self.assertEqual("https://domain/api/v2/blacklists/tokens", args[0])
self.assertEqual(kwargs["data"], {"jti": "the-jti"})
# create with audience
t.create(jti='the-jti', aud='the-aud')
t.create(jti="the-jti", aud="the-aud")
args, kwargs = mock_instance.post.call_args
self.assertEqual('https://domain/api/v2/blacklists/tokens', args[0])
self.assertEqual(kwargs['data'], {'jti': 'the-jti', 'aud': 'the-aud'})
self.assertEqual("https://domain/api/v2/blacklists/tokens", args[0])
self.assertEqual(kwargs["data"], {"jti": "the-jti", "aud": "the-aud"})
import unittest
import mock
from ...management.client_grants import ClientGrants

@@ -7,14 +9,15 @@

class TestClientGrants(unittest.TestCase):
def test_init_with_optionals(self):
t = ClientGrants(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = ClientGrants(
domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2)
)
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.client_grants.RestClient')
@mock.patch("auth0.v3.management.client_grants.RestClient")
def test_all(self, mock_rc):
mock_instance = mock_rc.return_value
c = ClientGrants(domain='domain', token='jwttoken')
c = ClientGrants(domain="domain", token="jwttoken")

@@ -26,24 +29,30 @@ # With default params

self.assertEqual('https://domain/api/v2/client-grants', args[0])
self.assertEqual(kwargs['params'], {
'audience': None,
'page': None,
'per_page': None,
'include_totals': 'false',
'client_id': None,
})
self.assertEqual("https://domain/api/v2/client-grants", args[0])
self.assertEqual(
kwargs["params"],
{
"audience": None,
"page": None,
"per_page": None,
"include_totals": "false",
"client_id": None,
},
)
# With audience
c.all(audience='http://domain.auth0.com/api/v2/')
c.all(audience="http://domain.auth0.com/api/v2/")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/client-grants', args[0])
self.assertEqual(kwargs['params'], {
'audience': 'http://domain.auth0.com/api/v2/',
'page': None,
'per_page': None,
'include_totals': 'false',
'client_id': None,
})
self.assertEqual("https://domain/api/v2/client-grants", args[0])
self.assertEqual(
kwargs["params"],
{
"audience": "http://domain.auth0.com/api/v2/",
"page": None,
"per_page": None,
"include_totals": "false",
"client_id": None,
},
)

@@ -55,58 +64,63 @@ # With pagination params

self.assertEqual('https://domain/api/v2/client-grants', args[0])
self.assertEqual(kwargs['params'], {
'audience': None,
'page': 7,
'per_page': 23,
'include_totals': 'true',
'client_id': None,
})
self.assertEqual("https://domain/api/v2/client-grants", args[0])
self.assertEqual(
kwargs["params"],
{
"audience": None,
"page": 7,
"per_page": 23,
"include_totals": "true",
"client_id": None,
},
)
# With client_id param
c.all(client_id='exampleid')
c.all(client_id="exampleid")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/client-grants', args[0])
self.assertEqual(kwargs['params'], {
'audience': None,
'page': None,
'per_page': None,
'include_totals': 'false',
'client_id': 'exampleid',
})
self.assertEqual("https://domain/api/v2/client-grants", args[0])
self.assertEqual(
kwargs["params"],
{
"audience": None,
"page": None,
"per_page": None,
"include_totals": "false",
"client_id": "exampleid",
},
)
@mock.patch('auth0.v3.management.client_grants.RestClient')
@mock.patch("auth0.v3.management.client_grants.RestClient")
def test_create(self, mock_rc):
mock_instance = mock_rc.return_value
c = ClientGrants(domain='domain', token='jwttoken')
c.create({'a': 'b', 'c': 'd'})
c = ClientGrants(domain="domain", token="jwttoken")
c.create({"a": "b", "c": "d"})
mock_instance.post.assert_called_with(
'https://domain/api/v2/client-grants',
data={'a': 'b', 'c': 'd'}
"https://domain/api/v2/client-grants", data={"a": "b", "c": "d"}
)
@mock.patch('auth0.v3.management.client_grants.RestClient')
@mock.patch("auth0.v3.management.client_grants.RestClient")
def test_delete(self, mock_rc):
mock_instance = mock_rc.return_value
c = ClientGrants(domain='domain', token='jwttoken')
c.delete('this-id')
c = ClientGrants(domain="domain", token="jwttoken")
c.delete("this-id")
mock_instance.delete.assert_called_with(
'https://domain/api/v2/client-grants/this-id'
"https://domain/api/v2/client-grants/this-id"
)
@mock.patch('auth0.v3.management.client_grants.RestClient')
@mock.patch("auth0.v3.management.client_grants.RestClient")
def test_update(self, mock_rc):
mock_instance = mock_rc.return_value
c = ClientGrants(domain='domain', token='jwttoken')
c.update('this-id', {'a': 'b', 'c': 'd'})
c = ClientGrants(domain="domain", token="jwttoken")
c.update("this-id", {"a": "b", "c": "d"})
args, kwargs = mock_instance.patch.call_args
self.assertEqual('https://domain/api/v2/client-grants/this-id', args[0])
self.assertEqual(kwargs['data'], {'a': 'b', 'c': 'd'})
self.assertEqual("https://domain/api/v2/client-grants/this-id", args[0])
self.assertEqual(kwargs["data"], {"a": "b", "c": "d"})
import unittest
import mock
from ...management.clients import Clients

@@ -7,14 +9,13 @@

class TestClients(unittest.TestCase):
def test_init_with_optionals(self):
t = Clients(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = Clients(domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2))
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.clients.RestClient')
@mock.patch("auth0.v3.management.clients.RestClient")
def test_all(self, mock_rc):
mock_instance = mock_rc.return_value
c = Clients(domain='domain', token='jwttoken')
c = Clients(domain="domain", token="jwttoken")

@@ -26,18 +27,23 @@ # Default parameters are requested

self.assertEqual('https://domain/api/v2/clients', args[0])
self.assertEqual(kwargs['params'], {'fields': None,
'include_fields': 'true',
'page': None,
'per_page': None})
self.assertEqual("https://domain/api/v2/clients", args[0])
self.assertEqual(
kwargs["params"],
{"fields": None, "include_fields": "true", "page": None, "per_page": None},
)
# Fields filter
c.all(fields=['a', 'b'], include_fields=False)
c.all(fields=["a", "b"], include_fields=False)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/clients', args[0])
self.assertEqual(kwargs['params'], {'fields': 'a,b',
'include_fields': 'false',
'page': None,
'per_page': None})
self.assertEqual("https://domain/api/v2/clients", args[0])
self.assertEqual(
kwargs["params"],
{
"fields": "a,b",
"include_fields": "false",
"page": None,
"per_page": None,
},
)

@@ -49,88 +55,86 @@ # Specific pagination

self.assertEqual('https://domain/api/v2/clients', args[0])
self.assertEqual(kwargs['params'], {'fields': None,
'include_fields': 'true',
'page': 7,
'per_page': 25})
self.assertEqual("https://domain/api/v2/clients", args[0])
self.assertEqual(
kwargs["params"],
{"fields": None, "include_fields": "true", "page": 7, "per_page": 25},
)
# Extra parameters
c.all(extra_params={'some_key': 'some_value'})
c.all(extra_params={"some_key": "some_value"})
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/clients', args[0])
self.assertEqual(kwargs['params'], {'fields': None,
'include_fields': 'true',
'page': None,
'per_page': None,
'some_key': 'some_value'})
self.assertEqual("https://domain/api/v2/clients", args[0])
self.assertEqual(
kwargs["params"],
{
"fields": None,
"include_fields": "true",
"page": None,
"per_page": None,
"some_key": "some_value",
},
)
@mock.patch('auth0.v3.management.clients.RestClient')
@mock.patch("auth0.v3.management.clients.RestClient")
def test_create(self, mock_rc):
mock_instance = mock_rc.return_value
c = Clients(domain='domain', token='jwttoken')
c.create({'a': 'b', 'c': 'd'})
c = Clients(domain="domain", token="jwttoken")
c.create({"a": "b", "c": "d"})
mock_instance.post.assert_called_with(
'https://domain/api/v2/clients',
data={'a': 'b', 'c': 'd'}
"https://domain/api/v2/clients", data={"a": "b", "c": "d"}
)
@mock.patch('auth0.v3.management.clients.RestClient')
@mock.patch("auth0.v3.management.clients.RestClient")
def test_get(self, mock_rc):
mock_instance = mock_rc.return_value
c = Clients(domain='domain', token='jwttoken')
c.get('this-id')
c = Clients(domain="domain", token="jwttoken")
c.get("this-id")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/clients/this-id', args[0])
self.assertEqual(kwargs['params'], {'fields': None,
'include_fields': 'true'})
self.assertEqual("https://domain/api/v2/clients/this-id", args[0])
self.assertEqual(kwargs["params"], {"fields": None, "include_fields": "true"})
c.get('this-id', fields=['a', 'b'], include_fields=False)
c.get("this-id", fields=["a", "b"], include_fields=False)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/clients/this-id', args[0])
self.assertEqual(kwargs['params'], {'fields': 'a,b',
'include_fields': 'false'})
self.assertEqual("https://domain/api/v2/clients/this-id", args[0])
self.assertEqual(kwargs["params"], {"fields": "a,b", "include_fields": "false"})
@mock.patch('auth0.v3.management.clients.RestClient')
@mock.patch("auth0.v3.management.clients.RestClient")
def test_delete(self, mock_rc):
mock_instance = mock_rc.return_value
c = Clients(domain='domain', token='jwttoken')
c.delete('this-id')
c = Clients(domain="domain", token="jwttoken")
c.delete("this-id")
mock_instance.delete.assert_called_with(
'https://domain/api/v2/clients/this-id'
)
mock_instance.delete.assert_called_with("https://domain/api/v2/clients/this-id")
@mock.patch('auth0.v3.management.clients.RestClient')
@mock.patch("auth0.v3.management.clients.RestClient")
def test_update(self, mock_rc):
mock_instance = mock_rc.return_value
c = Clients(domain='domain', token='jwttoken')
c.update('this-id', {'a': 'b', 'c': 'd'})
c = Clients(domain="domain", token="jwttoken")
c.update("this-id", {"a": "b", "c": "d"})
args, kwargs = mock_instance.patch.call_args
self.assertEqual('https://domain/api/v2/clients/this-id', args[0])
self.assertEqual(kwargs['data'], {'a': 'b', 'c': 'd'})
self.assertEqual("https://domain/api/v2/clients/this-id", args[0])
self.assertEqual(kwargs["data"], {"a": "b", "c": "d"})
@mock.patch('auth0.v3.management.clients.RestClient')
@mock.patch("auth0.v3.management.clients.RestClient")
def test_rotate_secret(self, mock_rc):
mock_instance = mock_rc.return_value
c = Clients(domain='domain', token='jwttoken')
c.rotate_secret('this-id')
c = Clients(domain="domain", token="jwttoken")
c.rotate_secret("this-id")
mock_instance.post.assert_called_with(
'https://domain/api/v2/clients/this-id/rotate-secret', data={'id': 'this-id'}
"https://domain/api/v2/clients/this-id/rotate-secret",
data={"id": "this-id"},
)
import unittest
import mock
from ...management.connections import Connections

@@ -7,10 +9,11 @@

class TestConnection(unittest.TestCase):
def test_init_with_optionals(self):
t = Connections(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = Connections(
domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2)
)
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.connections.RestClient')
@mock.patch("auth0.v3.management.connections.RestClient")
def test_all(self, mock_rc):

@@ -21,3 +24,3 @@ mock_instance = mock_rc.return_value

# Default parameters are requested
c = Connections(domain='domain', token='jwttoken')
c = Connections(domain="domain", token="jwttoken")
c.all()

@@ -27,32 +30,47 @@

self.assertEqual('https://domain/api/v2/connections', args[0])
self.assertEqual(kwargs['params'], {'fields': None,
'strategy': None,
'page': None,
'per_page': None,
'include_fields': 'true'})
self.assertEqual("https://domain/api/v2/connections", args[0])
self.assertEqual(
kwargs["params"],
{
"fields": None,
"strategy": None,
"page": None,
"per_page": None,
"include_fields": "true",
},
)
# Fields filter
c.all(fields=['a', 'b'], include_fields=False)
c.all(fields=["a", "b"], include_fields=False)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/connections', args[0])
self.assertEqual(kwargs['params'], {'fields': 'a,b',
'strategy': None,
'page': None,
'per_page': None,
'include_fields': 'false'})
self.assertEqual("https://domain/api/v2/connections", args[0])
self.assertEqual(
kwargs["params"],
{
"fields": "a,b",
"strategy": None,
"page": None,
"per_page": None,
"include_fields": "false",
},
)
# Fields + strategy filter
c.all(fields=['a', 'b'], strategy='auth0', include_fields=True)
c.all(fields=["a", "b"], strategy="auth0", include_fields=True)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/connections', args[0])
self.assertEqual(kwargs['params'], {'fields': 'a,b',
'strategy': 'auth0',
'page': None,
'per_page': None,
'include_fields': 'true'})
self.assertEqual("https://domain/api/v2/connections", args[0])
self.assertEqual(
kwargs["params"],
{
"fields": "a,b",
"strategy": "auth0",
"page": None,
"per_page": None,
"include_fields": "true",
},
)

@@ -64,23 +82,33 @@ # Specific pagination

self.assertEqual('https://domain/api/v2/connections', args[0])
self.assertEqual(kwargs['params'], {'fields': None,
'strategy': None,
'page': 7,
'per_page': 25,
'include_fields': 'true'})
self.assertEqual("https://domain/api/v2/connections", args[0])
self.assertEqual(
kwargs["params"],
{
"fields": None,
"strategy": None,
"page": 7,
"per_page": 25,
"include_fields": "true",
},
)
# Extra parameters
c.all(extra_params={'some_key': 'some_value'})
c.all(extra_params={"some_key": "some_value"})
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/connections', args[0])
self.assertEqual(kwargs['params'], {'fields': None,
'strategy': None,
'page': None,
'per_page': None,
'include_fields': 'true',
'some_key': 'some_value'})
self.assertEqual("https://domain/api/v2/connections", args[0])
self.assertEqual(
kwargs["params"],
{
"fields": None,
"strategy": None,
"page": None,
"per_page": None,
"include_fields": "true",
"some_key": "some_value",
},
)
@mock.patch('auth0.v3.management.connections.RestClient')
@mock.patch("auth0.v3.management.connections.RestClient")
def test_get(self, mock_rc):

@@ -90,25 +118,22 @@ mock_instance = mock_rc.return_value

c = Connections(domain='domain', token='jwttoken')
c.get('an-id')
c = Connections(domain="domain", token="jwttoken")
c.get("an-id")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/connections/an-id', args[0])
self.assertEqual(kwargs['params'], {'fields': None,
'include_fields': 'true'})
self.assertEqual("https://domain/api/v2/connections/an-id", args[0])
self.assertEqual(kwargs["params"], {"fields": None, "include_fields": "true"})
c.get('an-id', fields=['a', 'b'])
c.get("an-id", fields=["a", "b"])
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/connections/an-id', args[0])
self.assertEqual(kwargs['params'], {'fields': 'a,b',
'include_fields': 'true'})
self.assertEqual("https://domain/api/v2/connections/an-id", args[0])
self.assertEqual(kwargs["params"], {"fields": "a,b", "include_fields": "true"})
c.get('an-id', fields=['a', 'b'], include_fields=False)
c.get("an-id", fields=["a", "b"], include_fields=False)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/connections/an-id', args[0])
self.assertEqual(kwargs['params'], {'fields': 'a,b',
'include_fields': 'false'})
self.assertEqual("https://domain/api/v2/connections/an-id", args[0])
self.assertEqual(kwargs["params"], {"fields": "a,b", "include_fields": "false"})
@mock.patch('auth0.v3.management.connections.RestClient')
@mock.patch("auth0.v3.management.connections.RestClient")
def test_delete(self, mock_rc):

@@ -118,10 +143,10 @@ mock_instance = mock_rc.return_value

c = Connections(domain='domain', token='jwttoken')
c.delete('this-id')
c = Connections(domain="domain", token="jwttoken")
c.delete("this-id")
mock_instance.delete.assert_called_with(
'https://domain/api/v2/connections/this-id'
"https://domain/api/v2/connections/this-id"
)
@mock.patch('auth0.v3.management.connections.RestClient')
@mock.patch("auth0.v3.management.connections.RestClient")
def test_update(self, mock_rc):

@@ -131,11 +156,10 @@ mock_instance = mock_rc.return_value

c = Connections(domain='domain', token='jwttoken')
c.update('that-id', {'a': 'b', 'c': 'd'})
c = Connections(domain="domain", token="jwttoken")
c.update("that-id", {"a": "b", "c": "d"})
mock_instance.patch.assert_called_with(
'https://domain/api/v2/connections/that-id',
data={'a': 'b', 'c': 'd'}
"https://domain/api/v2/connections/that-id", data={"a": "b", "c": "d"}
)
@mock.patch('auth0.v3.management.connections.RestClient')
@mock.patch("auth0.v3.management.connections.RestClient")
def test_create(self, mock_rc):

@@ -145,11 +169,10 @@ mock_instance = mock_rc.return_value

c = Connections(domain='domain', token='jwttoken')
c.create({'a': 'b', 'c': 'd'})
c = Connections(domain="domain", token="jwttoken")
c.create({"a": "b", "c": "d"})
mock_instance.post.assert_called_with(
'https://domain/api/v2/connections',
data={'a': 'b', 'c': 'd'}
"https://domain/api/v2/connections", data={"a": "b", "c": "d"}
)
@mock.patch('auth0.v3.management.connections.RestClient')
@mock.patch("auth0.v3.management.connections.RestClient")
def test_delete_user_by_email(self, mock_rc):

@@ -159,7 +182,8 @@ mock_instance = mock_rc.return_value

c = Connections(domain='domain', token='jwttoken')
c.delete_user_by_email('123', 'test@example.com')
c = Connections(domain="domain", token="jwttoken")
c.delete_user_by_email("123", "test@example.com")
mock_instance.delete.assert_called_with(
'https://domain/api/v2/connections/123/users',
params={'email': 'test@example.com'})
"https://domain/api/v2/connections/123/users",
params={"email": "test@example.com"},
)
import unittest
import mock
from ...management.custom_domains import CustomDomains

@@ -7,53 +9,51 @@

class TestCustomDomains(unittest.TestCase):
def test_init_with_optionals(self):
t = CustomDomains(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = CustomDomains(
domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2)
)
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.custom_domains.RestClient')
@mock.patch("auth0.v3.management.custom_domains.RestClient")
def test_get_all(self, mock_rc):
mock_instance = mock_rc.return_value
g = CustomDomains(domain='domain', token='jwttoken')
g = CustomDomains(domain="domain", token="jwttoken")
g.all()
mock_instance.get.assert_called_with(
'https://domain/api/v2/custom-domains'
)
mock_instance.get.assert_called_with("https://domain/api/v2/custom-domains")
@mock.patch('auth0.v3.management.custom_domains.RestClient')
@mock.patch("auth0.v3.management.custom_domains.RestClient")
def test_create_new(self, mock_rc):
mock_instance = mock_rc.return_value
g = CustomDomains(domain='domain', token='jwttoken')
g.create_new(body={'a': 'b', 'c': 'd','e': 'f'})
g = CustomDomains(domain="domain", token="jwttoken")
g.create_new(body={"a": "b", "c": "d", "e": "f"})
args, kwargs = mock_instance.post.call_args
self.assertEqual('https://domain/api/v2/custom-domains',args[0])
self.assertEqual(kwargs['data'], {'a': 'b', 'c': 'd','e': 'f'})
self.assertEqual("https://domain/api/v2/custom-domains", args[0])
self.assertEqual(kwargs["data"], {"a": "b", "c": "d", "e": "f"})
@mock.patch('auth0.v3.management.custom_domains.RestClient')
@mock.patch("auth0.v3.management.custom_domains.RestClient")
def test_get_domain_by_id(self, mock_rc):
mock_instance = mock_rc.return_value
g = CustomDomains(domain='domain', token='jwttoken')
g.get('an-id')
g = CustomDomains(domain="domain", token="jwttoken")
g.get("an-id")
mock_instance.get.assert_called_with('https://domain/api/v2/custom-domains/an-id')
mock_instance.get.assert_called_with(
"https://domain/api/v2/custom-domains/an-id"
)
@mock.patch('auth0.v3.management.custom_domains.RestClient')
@mock.patch("auth0.v3.management.custom_domains.RestClient")
def test_verify(self, mock_rc):
mock_instance = mock_rc.return_value
g = CustomDomains(domain='domain', token='jwttoken')
g.verify('an-id')
g = CustomDomains(domain="domain", token="jwttoken")
g.verify("an-id")
args, kwargs = mock_instance.post.call_args
self.assertEqual('https://domain/api/v2/custom-domains/an-id/verify', args[0])
self.assertEqual("https://domain/api/v2/custom-domains/an-id/verify", args[0])
import unittest
import mock
from ...management.device_credentials import DeviceCredentials

@@ -7,63 +9,81 @@

class TestDeviceCredentials(unittest.TestCase):
def test_init_with_optionals(self):
t = DeviceCredentials(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = DeviceCredentials(
domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2)
)
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.device_credentials.RestClient')
@mock.patch("auth0.v3.management.device_credentials.RestClient")
def test_get(self, mock_rc):
mock_instance = mock_rc.return_value
c = DeviceCredentials(domain='domain', token='jwttoken')
c.get(user_id='uid', client_id='cid', type='type', page=0, per_page=20)
c = DeviceCredentials(domain="domain", token="jwttoken")
c.get(user_id="uid", client_id="cid", type="type", page=0, per_page=20)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/device-credentials', args[0])
self.assertEqual(kwargs['params'], {'fields': None,
'include_fields': 'true',
'user_id': 'uid',
'client_id': 'cid',
'type': 'type',
'page': 0,
'per_page': 20,
'include_totals': 'false'})
self.assertEqual("https://domain/api/v2/device-credentials", args[0])
self.assertEqual(
kwargs["params"],
{
"fields": None,
"include_fields": "true",
"user_id": "uid",
"client_id": "cid",
"type": "type",
"page": 0,
"per_page": 20,
"include_totals": "false",
},
)
c.get(user_id='uid', client_id='cid', type='type', page=5, per_page=50, include_totals=True)
c.get(
user_id="uid",
client_id="cid",
type="type",
page=5,
per_page=50,
include_totals=True,
)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/device-credentials', args[0])
self.assertEqual(kwargs['params'], {'fields': None,
'include_fields': 'true',
'user_id': 'uid',
'client_id': 'cid',
'type': 'type',
'page': 5,
'per_page': 50,
'include_totals': 'true'})
self.assertEqual("https://domain/api/v2/device-credentials", args[0])
self.assertEqual(
kwargs["params"],
{
"fields": None,
"include_fields": "true",
"user_id": "uid",
"client_id": "cid",
"type": "type",
"page": 5,
"per_page": 50,
"include_totals": "true",
},
)
@mock.patch('auth0.v3.management.device_credentials.RestClient')
@mock.patch("auth0.v3.management.device_credentials.RestClient")
def test_create(self, mock_rc):
mock_instance = mock_rc.return_value
c = DeviceCredentials(domain='domain', token='jwttoken')
c.create({'a': 'b', 'c': 'd'})
c = DeviceCredentials(domain="domain", token="jwttoken")
c.create({"a": "b", "c": "d"})
args, kwargs = mock_instance.post.call_args
self.assertEqual('https://domain/api/v2/device-credentials', args[0])
self.assertEqual(kwargs['data'], {'a': 'b', 'c': 'd'})
self.assertEqual("https://domain/api/v2/device-credentials", args[0])
self.assertEqual(kwargs["data"], {"a": "b", "c": "d"})
@mock.patch('auth0.v3.management.device_credentials.RestClient')
@mock.patch("auth0.v3.management.device_credentials.RestClient")
def test_delete(self, mock_rc):
mock_instance = mock_rc.return_value
c = DeviceCredentials(domain='domain', token='jwttoken')
c.delete('an-id')
c = DeviceCredentials(domain="domain", token="jwttoken")
c.delete("an-id")
mock_instance.delete.assert_called_with(
'https://domain/api/v2/device-credentials/an-id',
"https://domain/api/v2/device-credentials/an-id",
)
import unittest
import mock
from ...management.email_templates import EmailTemplates

@@ -7,42 +9,42 @@

class TestClients(unittest.TestCase):
def test_init_with_optionals(self):
t = EmailTemplates(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = EmailTemplates(
domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2)
)
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.email_templates.RestClient')
@mock.patch("auth0.v3.management.email_templates.RestClient")
def test_create(self, mock_rc):
mock_instance = mock_rc.return_value
c = EmailTemplates(domain='domain', token='jwttoken')
c.create({'a': 'b', 'c': 'd'})
c = EmailTemplates(domain="domain", token="jwttoken")
c.create({"a": "b", "c": "d"})
mock_instance.post.assert_called_with(
'https://domain/api/v2/email-templates',
data={'a': 'b', 'c': 'd'}
"https://domain/api/v2/email-templates", data={"a": "b", "c": "d"}
)
@mock.patch('auth0.v3.management.email_templates.RestClient')
@mock.patch("auth0.v3.management.email_templates.RestClient")
def test_get(self, mock_rc):
mock_instance = mock_rc.return_value
c = EmailTemplates(domain='domain', token='jwttoken')
c.get('this-template-name')
c = EmailTemplates(domain="domain", token="jwttoken")
c.get("this-template-name")
mock_instance.get.assert_called_with(
'https://domain/api/v2/email-templates/this-template-name'
"https://domain/api/v2/email-templates/this-template-name"
)
@mock.patch('auth0.v3.management.email_templates.RestClient')
@mock.patch("auth0.v3.management.email_templates.RestClient")
def test_update(self, mock_rc):
mock_instance = mock_rc.return_value
c = EmailTemplates(domain='domain', token='jwttoken')
c.update('this-template-name', {'a': 'b', 'c': 'd'})
c = EmailTemplates(domain="domain", token="jwttoken")
c.update("this-template-name", {"a": "b", "c": "d"})
mock_instance.patch.assert_called_with(
'https://domain/api/v2/email-templates/this-template-name',
data={'a': 'b', 'c': 'd'}
"https://domain/api/v2/email-templates/this-template-name",
data={"a": "b", "c": "d"},
)
import unittest
import mock
from ...management.emails import Emails

@@ -7,14 +9,13 @@

class TestEmails(unittest.TestCase):
def test_init_with_optionals(self):
t = Emails(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = Emails(domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2))
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.emails.RestClient')
@mock.patch("auth0.v3.management.emails.RestClient")
def test_get(self, mock_rc):
mock_instance = mock_rc.return_value
e = Emails(domain='domain', token='jwttoken')
e = Emails(domain="domain", token="jwttoken")
e.get()

@@ -24,47 +25,43 @@

self.assertEqual('https://domain/api/v2/emails/provider', args[0])
self.assertEqual(kwargs['params'], {'fields': None,
'include_fields': 'true'})
self.assertEqual("https://domain/api/v2/emails/provider", args[0])
self.assertEqual(kwargs["params"], {"fields": None, "include_fields": "true"})
e.get(fields=['a', 'b'], include_fields=False)
e.get(fields=["a", "b"], include_fields=False)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/emails/provider', args[0])
self.assertEqual(kwargs['params'], {'fields': 'a,b',
'include_fields': 'false'})
self.assertEqual("https://domain/api/v2/emails/provider", args[0])
self.assertEqual(kwargs["params"], {"fields": "a,b", "include_fields": "false"})
@mock.patch('auth0.v3.management.emails.RestClient')
@mock.patch("auth0.v3.management.emails.RestClient")
def test_config(self, mock_rc):
mock_instance = mock_rc.return_value
e = Emails(domain='domain', token='jwttoken')
e.config({'a': 'b', 'c': 'd'})
e = Emails(domain="domain", token="jwttoken")
e.config({"a": "b", "c": "d"})
args, kwargs = mock_instance.post.call_args
self.assertEqual('https://domain/api/v2/emails/provider', args[0])
self.assertEqual(kwargs['data'], {'a': 'b', 'c': 'd'})
self.assertEqual("https://domain/api/v2/emails/provider", args[0])
self.assertEqual(kwargs["data"], {"a": "b", "c": "d"})
@mock.patch('auth0.v3.management.emails.RestClient')
@mock.patch("auth0.v3.management.emails.RestClient")
def test_update(self, mock_rc):
mock_instance = mock_rc.return_value
e = Emails(domain='domain', token='jwttoken')
e.update({'a': 'b', 'c': 'd'})
e = Emails(domain="domain", token="jwttoken")
e.update({"a": "b", "c": "d"})
args, kwargs = mock_instance.patch.call_args
self.assertEqual('https://domain/api/v2/emails/provider', args[0])
self.assertEqual(kwargs['data'], {'a': 'b', 'c': 'd'})
self.assertEqual("https://domain/api/v2/emails/provider", args[0])
self.assertEqual(kwargs["data"], {"a": "b", "c": "d"})
@mock.patch('auth0.v3.management.emails.RestClient')
@mock.patch("auth0.v3.management.emails.RestClient")
def test_delete(self, mock_rc):
mock_instance = mock_rc.return_value
e = Emails(domain='domain', token='jwttoken')
e = Emails(domain="domain", token="jwttoken")
e.delete()
mock_instance.delete.assert_called_with(
'https://domain/api/v2/emails/provider'
)
mock_instance.delete.assert_called_with("https://domain/api/v2/emails/provider")
import unittest
import mock
from ...management.grants import Grants

@@ -7,15 +9,16 @@

class TestGrants(unittest.TestCase):
def test_init_with_optionals(self):
t = Grants(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = Grants(domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2))
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.grants.RestClient')
@mock.patch("auth0.v3.management.grants.RestClient")
def test_get_all(self, mock_rc):
mock_instance = mock_rc.return_value
g = Grants(domain='domain', token='jwttoken')
g.all(extra_params={'user_id':'an-id', 'client_id': 'an-id', 'audience':'test'})
g = Grants(domain="domain", token="jwttoken")
g.all(
extra_params={"user_id": "an-id", "client_id": "an-id", "audience": "test"}
)

@@ -25,15 +28,20 @@ args, kwargs = mock_instance.get.call_args

mock_instance.get.assert_called_with(
'https://domain/api/v2/grants', params={'user_id': 'an-id', 'client_id': 'an-id', 'audience': 'test', 'page': None, 'per_page': None, 'include_totals': 'false'}
"https://domain/api/v2/grants",
params={
"user_id": "an-id",
"client_id": "an-id",
"audience": "test",
"page": None,
"per_page": None,
"include_totals": "false",
},
)
@mock.patch('auth0.v3.management.grants.RestClient')
@mock.patch("auth0.v3.management.grants.RestClient")
def test_delete(self, mock_rc):
mock_instance = mock_rc.return_value
c = Grants(domain='domain', token='jwttoken')
c.delete('an-id')
c = Grants(domain="domain", token="jwttoken")
c.delete("an-id")
mock_instance.delete.assert_called_with(
'https://domain/api/v2/grants/an-id'
)
mock_instance.delete.assert_called_with("https://domain/api/v2/grants/an-id")
import unittest
import mock
from ...management.guardian import Guardian

@@ -7,126 +9,144 @@

class TestGuardian(unittest.TestCase):
def test_init_with_optionals(self):
t = Guardian(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = Guardian(
domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2)
)
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.guardian.RestClient')
@mock.patch("auth0.v3.management.guardian.RestClient")
def test_all_factors(self, mock_rc):
mock_instance = mock_rc.return_value
g = Guardian(domain='domain', token='jwttoken')
g = Guardian(domain="domain", token="jwttoken")
g.all_factors()
mock_instance.get.assert_called_with(
'https://domain/api/v2/guardian/factors'
)
mock_instance.get.assert_called_with("https://domain/api/v2/guardian/factors")
@mock.patch('auth0.v3.management.guardian.RestClient')
@mock.patch("auth0.v3.management.guardian.RestClient")
def test_update_factor(self, mock_rc):
mock_instance = mock_rc.return_value
g = Guardian(domain='domain', token='jwttoken')
g.update_factor('push-notification', {'enabled': True})
g = Guardian(domain="domain", token="jwttoken")
g.update_factor("push-notification", {"enabled": True})
args, kwargs = mock_instance.put.call_args
self.assertEqual('https://domain/api/v2/guardian/factors/push-notification', args[0])
self.assertEqual(kwargs['data'], {'enabled': True})
self.assertEqual(
"https://domain/api/v2/guardian/factors/push-notification", args[0]
)
self.assertEqual(kwargs["data"], {"enabled": True})
g.update_factor('sms', {'enabled': False})
g.update_factor("sms", {"enabled": False})
args, kwargs = mock_instance.put.call_args
self.assertEqual('https://domain/api/v2/guardian/factors/sms', args[0])
self.assertEqual(kwargs['data'], {'enabled': False})
self.assertEqual("https://domain/api/v2/guardian/factors/sms", args[0])
self.assertEqual(kwargs["data"], {"enabled": False})
@mock.patch('auth0.v3.management.guardian.RestClient')
@mock.patch("auth0.v3.management.guardian.RestClient")
def test_update_templates(self, mock_rc):
mock_instance = mock_rc.return_value
g = Guardian(domain='domain', token='jwttoken')
g.update_templates({'enrollment_message': 'hello',
'verification_message': 'verified'})
g = Guardian(domain="domain", token="jwttoken")
g.update_templates(
{"enrollment_message": "hello", "verification_message": "verified"}
)
args, kwargs = mock_instance.put.call_args
self.assertEqual('https://domain/api/v2/guardian/factors/sms/templates', args[0])
self.assertEqual(kwargs['data'], {'enrollment_message': 'hello',
'verification_message': 'verified'})
self.assertEqual(
"https://domain/api/v2/guardian/factors/sms/templates", args[0]
)
self.assertEqual(
kwargs["data"],
{"enrollment_message": "hello", "verification_message": "verified"},
)
@mock.patch('auth0.v3.management.guardian.RestClient')
@mock.patch("auth0.v3.management.guardian.RestClient")
def test_get_templates(self, mock_rc):
mock_instance = mock_rc.return_value
g = Guardian(domain='domain', token='jwttoken')
g = Guardian(domain="domain", token="jwttoken")
g.get_templates()
mock_instance.get.assert_called_with(
'https://domain/api/v2/guardian/factors/sms/templates'
"https://domain/api/v2/guardian/factors/sms/templates"
)
@mock.patch('auth0.v3.management.guardian.RestClient')
@mock.patch("auth0.v3.management.guardian.RestClient")
def test_get_enrollment(self, mock_rc):
mock_instance = mock_rc.return_value
g = Guardian(domain='domain', token='jwttoken')
g.get_enrollment('some_id')
g = Guardian(domain="domain", token="jwttoken")
g.get_enrollment("some_id")
mock_instance.get.assert_called_with(
'https://domain/api/v2/guardian/enrollments/some_id'
"https://domain/api/v2/guardian/enrollments/some_id"
)
@mock.patch('auth0.v3.management.guardian.RestClient')
@mock.patch("auth0.v3.management.guardian.RestClient")
def test_delete_enrollment(self, mock_rc):
mock_instance = mock_rc.return_value
g = Guardian(domain='domain', token='jwttoken')
g.delete_enrollment('some_id')
g = Guardian(domain="domain", token="jwttoken")
g.delete_enrollment("some_id")
mock_instance.delete.assert_called_with(
'https://domain/api/v2/guardian/enrollments/some_id'
"https://domain/api/v2/guardian/enrollments/some_id"
)
@mock.patch('auth0.v3.management.guardian.RestClient')
@mock.patch("auth0.v3.management.guardian.RestClient")
def test_create_enrollment_ticket(self, mock_rc):
mock_instance = mock_rc.return_value
g = Guardian(domain='domain', token='jwttoken')
g.create_enrollment_ticket({'user_id': 'some_id',
'email': 'test@test.com',
'send_mail': 'false'})
g = Guardian(domain="domain", token="jwttoken")
g.create_enrollment_ticket(
{"user_id": "some_id", "email": "test@test.com", "send_mail": "false"}
)
args, kwargs = mock_instance.post.call_args
self.assertEqual('https://domain/api/v2/guardian/enrollments/ticket', args[0])
self.assertEqual(kwargs['data'], {'user_id': 'some_id',
'email': 'test@test.com',
'send_mail': 'false'})
self.assertEqual("https://domain/api/v2/guardian/enrollments/ticket", args[0])
self.assertEqual(
kwargs["data"],
{"user_id": "some_id", "email": "test@test.com", "send_mail": "false"},
)
@mock.patch('auth0.v3.management.guardian.RestClient')
@mock.patch("auth0.v3.management.guardian.RestClient")
def test_get_factor_providers(self, mock_rc):
mock_instance = mock_rc.return_value
g = Guardian(domain='domain', token='jwttoken')
g.get_factor_providers('sms', 'twilio')
g = Guardian(domain="domain", token="jwttoken")
g.get_factor_providers("sms", "twilio")
mock_instance.get.assert_called_with(
'https://domain/api/v2/guardian/factors/sms/providers/twilio'
"https://domain/api/v2/guardian/factors/sms/providers/twilio"
)
@mock.patch('auth0.v3.management.guardian.RestClient')
@mock.patch("auth0.v3.management.guardian.RestClient")
def test_update_factor_providers(self, mock_rc):
mock_instance = mock_rc.return_value
g = Guardian(domain='domain', token='jwttoken')
g.update_factor_providers('sms',
'twilio',
{'from': 'test@test.com',
'messaging_service_sid': 'qwerty',
'auth_token': 'abc.xyz.123',
'sid': 'abc.xyz'})
g = Guardian(domain="domain", token="jwttoken")
g.update_factor_providers(
"sms",
"twilio",
{
"from": "test@test.com",
"messaging_service_sid": "qwerty",
"auth_token": "abc.xyz.123",
"sid": "abc.xyz",
},
)
args, kwargs = mock_instance.put.call_args
self.assertEqual('https://domain/api/v2/guardian/factors/sms/providers/twilio', args[0])
self.assertEqual(kwargs['data'], {'from': 'test@test.com',
'messaging_service_sid': 'qwerty',
'auth_token': 'abc.xyz.123',
'sid': 'abc.xyz'})
self.assertEqual(
"https://domain/api/v2/guardian/factors/sms/providers/twilio", args[0]
)
self.assertEqual(
kwargs["data"],
{
"from": "test@test.com",
"messaging_service_sid": "qwerty",
"auth_token": "abc.xyz.123",
"sid": "abc.xyz",
},
)
import unittest
import mock
from ...management.hooks import Hooks

@@ -7,14 +9,13 @@

class TestRules(unittest.TestCase):
def test_init_with_optionals(self):
t = Hooks(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = Hooks(domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2))
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.hooks.RestClient')
@mock.patch("auth0.v3.management.hooks.RestClient")
def test_all(self, mock_rc):
mock_instance = mock_rc.return_value
c = Hooks(domain='domain', token='jwttoken')
c = Hooks(domain="domain", token="jwttoken")

@@ -26,25 +27,32 @@ # with default params

self.assertEqual('https://domain/api/v2/hooks', args[0])
self.assertEqual(kwargs['params'], {
"enabled": 'true',
"fields": None,
"include_fields": 'true',
"page": None,
"per_page": None,
"include_totals": 'false',
})
self.assertEqual("https://domain/api/v2/hooks", args[0])
self.assertEqual(
kwargs["params"],
{
"enabled": "true",
"fields": None,
"include_fields": "true",
"page": None,
"per_page": None,
"include_totals": "false",
},
)
# with fields params
c.all(enabled=False, fields=['a', 'b'],
include_fields=False)
c.all(enabled=False, fields=["a", "b"], include_fields=False)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/hooks', args[0])
self.assertEqual(kwargs['params'], {'fields': 'a,b',
'include_fields': 'false',
'enabled': 'false',
'page': None,
'per_page': None,
'include_totals': 'false'})
self.assertEqual("https://domain/api/v2/hooks", args[0])
self.assertEqual(
kwargs["params"],
{
"fields": "a,b",
"include_fields": "false",
"enabled": "false",
"page": None,
"per_page": None,
"include_totals": "false",
},
)

@@ -56,111 +64,114 @@ # with pagination params

self.assertEqual('https://domain/api/v2/hooks', args[0])
self.assertEqual(kwargs['params'], {'fields': None,
'include_fields': 'true',
'enabled': 'true',
'page': 3,
'per_page': 27,
'include_totals': 'true'})
self.assertEqual("https://domain/api/v2/hooks", args[0])
self.assertEqual(
kwargs["params"],
{
"fields": None,
"include_fields": "true",
"enabled": "true",
"page": 3,
"per_page": 27,
"include_totals": "true",
},
)
@mock.patch('auth0.v3.management.hooks.RestClient')
@mock.patch("auth0.v3.management.hooks.RestClient")
def test_create(self, mock_rc):
mock_instance = mock_rc.return_value
c = Hooks(domain='domain', token='jwttoken')
c.create({'a': 'b', 'c': 'd'})
c = Hooks(domain="domain", token="jwttoken")
c.create({"a": "b", "c": "d"})
args, kwargs = mock_instance.post.call_args
self.assertEqual('https://domain/api/v2/hooks', args[0])
self.assertEqual(kwargs['data'], {'a': 'b', 'c': 'd'})
self.assertEqual("https://domain/api/v2/hooks", args[0])
self.assertEqual(kwargs["data"], {"a": "b", "c": "d"})
@mock.patch('auth0.v3.management.hooks.RestClient')
@mock.patch("auth0.v3.management.hooks.RestClient")
def test_get(self, mock_rc):
mock_instance = mock_rc.return_value
c = Hooks(domain='domain', token='jwttoken')
c.get('an-id')
c = Hooks(domain="domain", token="jwttoken")
c.get("an-id")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/hooks/an-id', args[0])
self.assertEqual(kwargs['params'], {'fields': None})
self.assertEqual("https://domain/api/v2/hooks/an-id", args[0])
self.assertEqual(kwargs["params"], {"fields": None})
c.get('an-id', fields=['a', 'b'])
c.get("an-id", fields=["a", "b"])
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/hooks/an-id', args[0])
self.assertEqual(kwargs['params'], {'fields': 'a,b'})
self.assertEqual("https://domain/api/v2/hooks/an-id", args[0])
self.assertEqual(kwargs["params"], {"fields": "a,b"})
@mock.patch('auth0.v3.management.hooks.RestClient')
@mock.patch("auth0.v3.management.hooks.RestClient")
def test_delete(self, mock_rc):
mock_instance = mock_rc.return_value
c = Hooks(domain='domain', token='jwttoken')
c.delete('an-id')
c = Hooks(domain="domain", token="jwttoken")
c.delete("an-id")
mock_instance.delete.assert_called_with(
'https://domain/api/v2/hooks/an-id'
)
mock_instance.delete.assert_called_with("https://domain/api/v2/hooks/an-id")
@mock.patch('auth0.v3.management.hooks.RestClient')
@mock.patch("auth0.v3.management.hooks.RestClient")
def test_update(self, mock_rc):
mock_instance = mock_rc.return_value
c = Hooks(domain='domain', token='jwttoken')
c.update('an-id', {'a': 'b', 'c': 'd'})
c = Hooks(domain="domain", token="jwttoken")
c.update("an-id", {"a": "b", "c": "d"})
args, kwargs = mock_instance.patch.call_args
self.assertEqual('https://domain/api/v2/hooks/an-id', args[0])
self.assertEqual(kwargs['data'], {'a': 'b', 'c': 'd'})
self.assertEqual("https://domain/api/v2/hooks/an-id", args[0])
self.assertEqual(kwargs["data"], {"a": "b", "c": "d"})
# test for hooks secrets
@mock.patch('auth0.v3.management.hooks.RestClient')
@mock.patch("auth0.v3.management.hooks.RestClient")
def test_add_secret(self, mock_rc):
mock_instance = mock_rc.return_value
c = Hooks(domain='domain', token='jwttoken')
c.add_secrets('an-id', {'a': 'b', 'c': 'd'})
c = Hooks(domain="domain", token="jwttoken")
c.add_secrets("an-id", {"a": "b", "c": "d"})
args, kwargs = mock_instance.post.call_args
self.assertEqual('https://domain/api/v2/hooks/an-id/secrets', args[0])
self.assertEqual(kwargs['data'], {'a': 'b', 'c': 'd'})
self.assertEqual("https://domain/api/v2/hooks/an-id/secrets", args[0])
self.assertEqual(kwargs["data"], {"a": "b", "c": "d"})
@mock.patch('auth0.v3.management.hooks.RestClient')
@mock.patch("auth0.v3.management.hooks.RestClient")
def test_get_secrets(self, mock_rc):
mock_instance = mock_rc.return_value
c = Hooks(domain='domain', token='jwttoken')
c.get_secrets('an-id')
c = Hooks(domain="domain", token="jwttoken")
c.get_secrets("an-id")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/hooks/an-id/secrets', args[0])
self.assertEqual("https://domain/api/v2/hooks/an-id/secrets", args[0])
self.assertNotIn("params", kwargs)
@mock.patch('auth0.v3.management.hooks.RestClient')
@mock.patch("auth0.v3.management.hooks.RestClient")
def test_delete_secrets(self, mock_rc):
mock_instance = mock_rc.return_value
c = Hooks(domain='domain', token='jwttoken')
c.delete_secrets('an-id', ['a', 'b'])
c = Hooks(domain="domain", token="jwttoken")
c.delete_secrets("an-id", ["a", "b"])
args, kwargs = mock_instance.delete.call_args
self.assertEqual('https://domain/api/v2/hooks/an-id/secrets', args[0])
self.assertEqual(kwargs['data'], ['a', 'b'])
self.assertEqual("https://domain/api/v2/hooks/an-id/secrets", args[0])
self.assertEqual(kwargs["data"], ["a", "b"])
@mock.patch('auth0.v3.management.hooks.RestClient')
@mock.patch("auth0.v3.management.hooks.RestClient")
def test_update_secrets(self, mock_rc):
mock_instance = mock_rc.return_value
c = Hooks(domain='domain', token='jwttoken')
c.update_secrets('an-id', {'a': 'b', 'c': 'd'})
c = Hooks(domain="domain", token="jwttoken")
c.update_secrets("an-id", {"a": "b", "c": "d"})
args, kwargs = mock_instance.patch.call_args
self.assertEqual('https://domain/api/v2/hooks/an-id/secrets', args[0])
self.assertEqual(kwargs['data'], {'a': 'b', 'c': 'd'})
self.assertEqual("https://domain/api/v2/hooks/an-id/secrets", args[0])
self.assertEqual(kwargs["data"], {"a": "b", "c": "d"})
import unittest
import mock
from ...management.jobs import Jobs

@@ -7,92 +9,113 @@

class TestJobs(unittest.TestCase):
def test_init_with_optionals(self):
t = Jobs(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = Jobs(domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2))
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.jobs.RestClient')
@mock.patch("auth0.v3.management.jobs.RestClient")
def test_get(self, mock_rc):
mock_instance = mock_rc.return_value
j = Jobs(domain='domain', token='jwttoken')
j.get('an-id')
j = Jobs(domain="domain", token="jwttoken")
j.get("an-id")
mock_instance.get.assert_called_with(
'https://domain/api/v2/jobs/an-id',
"https://domain/api/v2/jobs/an-id",
)
@mock.patch('auth0.v3.management.jobs.RestClient')
@mock.patch("auth0.v3.management.jobs.RestClient")
def test_get_failed_job(self, mock_rc):
mock_instance = mock_rc.return_value
j = Jobs(domain='domain', token='jwttoken')
j.get_failed_job('an-id')
j = Jobs(domain="domain", token="jwttoken")
j.get_failed_job("an-id")
mock_instance.get.assert_called_with(
'https://domain/api/v2/jobs/an-id/errors',
"https://domain/api/v2/jobs/an-id/errors",
)
@mock.patch('auth0.v3.management.jobs.RestClient')
@mock.patch("auth0.v3.management.jobs.RestClient")
def test_get_job_results(self, mock_rc):
mock_instance = mock_rc.return_value
j = Jobs(domain='domain', token='jwttoken')
j.get_results('an-id')
j = Jobs(domain="domain", token="jwttoken")
j.get_results("an-id")
# Should use the 'get by id' URL
mock_instance.get.assert_called_with(
'https://domain/api/v2/jobs/an-id',
"https://domain/api/v2/jobs/an-id",
)
@mock.patch('auth0.v3.management.jobs.RestClient')
@mock.patch("auth0.v3.management.jobs.RestClient")
def test_export_users(self, mock_rc):
mock_instance = mock_rc.return_value
j = Jobs(domain='domain', token='jwttoken')
j.export_users({'connection_id': 'cxn_id', 'format': 'json'})
j = Jobs(domain="domain", token="jwttoken")
j.export_users({"connection_id": "cxn_id", "format": "json"})
mock_instance.post.assert_called_with(
'https://domain/api/v2/jobs/users-exports',
data={'connection_id': 'cxn_id', 'format': 'json'}
"https://domain/api/v2/jobs/users-exports",
data={"connection_id": "cxn_id", "format": "json"},
)
@mock.patch('auth0.v3.management.jobs.RestClient')
@mock.patch("auth0.v3.management.jobs.RestClient")
def test_import_users(self, mock_rc):
mock_instance = mock_rc.return_value
j = Jobs(domain='domain', token='jwttoken')
j.import_users(connection_id='1234', file_obj={})
j = Jobs(domain="domain", token="jwttoken")
j.import_users(connection_id="1234", file_obj={})
mock_instance.file_post.assert_called_with(
'https://domain/api/v2/jobs/users-imports',
data={'connection_id': '1234', 'upsert': 'false', 'send_completion_email': 'true', 'external_id': None},
files={'users': {}}
"https://domain/api/v2/jobs/users-imports",
data={
"connection_id": "1234",
"upsert": "false",
"send_completion_email": "true",
"external_id": None,
},
files={"users": {}},
)
j.import_users(connection_id='1234', file_obj={}, upsert=True, send_completion_email=False, external_id="ext-id-123")
j.import_users(
connection_id="1234",
file_obj={},
upsert=True,
send_completion_email=False,
external_id="ext-id-123",
)
mock_instance.file_post.assert_called_with(
'https://domain/api/v2/jobs/users-imports',
data={'connection_id': '1234', 'upsert': 'true', 'send_completion_email': 'false', 'external_id': 'ext-id-123'},
files={'users': {}}
"https://domain/api/v2/jobs/users-imports",
data={
"connection_id": "1234",
"upsert": "true",
"send_completion_email": "false",
"external_id": "ext-id-123",
},
files={"users": {}},
)
j.import_users(connection_id='1234', file_obj={}, upsert=False, send_completion_email=True)
j.import_users(
connection_id="1234", file_obj={}, upsert=False, send_completion_email=True
)
mock_instance.file_post.assert_called_with(
'https://domain/api/v2/jobs/users-imports',
data={'connection_id': '1234', 'upsert': 'false', 'send_completion_email': 'true', 'external_id': None},
files={'users': {}}
"https://domain/api/v2/jobs/users-imports",
data={
"connection_id": "1234",
"upsert": "false",
"send_completion_email": "true",
"external_id": None,
},
files={"users": {}},
)
@mock.patch('auth0.v3.management.jobs.RestClient')
@mock.patch("auth0.v3.management.jobs.RestClient")
def test_verification_email(self, mock_rc):
mock_instance = mock_rc.return_value
j = Jobs(domain='domain', token='jwttoken')
j.send_verification_email({'a': 'b', 'c': 'd'})
j = Jobs(domain="domain", token="jwttoken")
j.send_verification_email({"a": "b", "c": "d"})
mock_instance.post.assert_called_with(
'https://domain/api/v2/jobs/verification-email',
data={'a': 'b', 'c': 'd'}
"https://domain/api/v2/jobs/verification-email", data={"a": "b", "c": "d"}
)

@@ -9,14 +9,15 @@ import unittest

class TestLogStreams(unittest.TestCase):
def test_init_with_optionals(self):
t = LogStreams(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = LogStreams(
domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2)
)
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.log_streams.RestClient')
@mock.patch("auth0.v3.management.log_streams.RestClient")
def test_list(self, mock_rc):
mock_instance = mock_rc.return_value
c = LogStreams(domain='domain', token='jwttoken')
c = LogStreams(domain="domain", token="jwttoken")

@@ -27,20 +28,20 @@ c.list()

self.assertEqual('https://domain/api/v2/log-streams', args[0])
self.assertEqual("https://domain/api/v2/log-streams", args[0])
@mock.patch('auth0.v3.management.log_streams.RestClient')
@mock.patch("auth0.v3.management.log_streams.RestClient")
def test_get(self, mock_rc):
mock_instance = mock_rc.return_value
c = LogStreams(domain='domain', token='jwttoken')
c.get('an-id')
c = LogStreams(domain="domain", token="jwttoken")
c.get("an-id")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/log-streams/an-id', args[0])
self.assertEqual("https://domain/api/v2/log-streams/an-id", args[0])
@mock.patch('auth0.v3.management.log_streams.RestClient')
@mock.patch("auth0.v3.management.log_streams.RestClient")
def test_create(self, mock_rc):
mock_instance = mock_rc.return_value
c = LogStreams(domain='domain', token='jwttoken')
c = LogStreams(domain="domain", token="jwttoken")
# Sample data belongs to an `http` stream

@@ -54,4 +55,4 @@ log_stream_data = {

"httpContentFormat": "JSONLINES|JSONARRAY",
"httpAuthorization": "string"
}
"httpAuthorization": "string",
},
}

@@ -62,29 +63,27 @@ c.create(log_stream_data)

self.assertEqual('https://domain/api/v2/log-streams', args[0])
self.assertEqual(kwargs['data'], log_stream_data)
self.assertEqual("https://domain/api/v2/log-streams", args[0])
self.assertEqual(kwargs["data"], log_stream_data)
@mock.patch('auth0.v3.management.log_streams.RestClient')
@mock.patch("auth0.v3.management.log_streams.RestClient")
def test_delete(self, mock_rc):
mock_instance = mock_rc.return_value
c = LogStreams(domain='domain', token='jwttoken')
c.delete('an-id')
c = LogStreams(domain="domain", token="jwttoken")
c.delete("an-id")
mock_instance.delete.assert_called_with(
'https://domain/api/v2/log-streams/an-id'
"https://domain/api/v2/log-streams/an-id"
)
@mock.patch('auth0.v3.management.log_streams.RestClient')
@mock.patch("auth0.v3.management.log_streams.RestClient")
def test_update(self, mock_rc):
mock_instance = mock_rc.return_value
log_stream_update = {
"name": "string"
}
log_stream_update = {"name": "string"}
c = LogStreams(domain='domain', token='jwttoken')
c.update('an-id', log_stream_update)
c = LogStreams(domain="domain", token="jwttoken")
c.update("an-id", log_stream_update)
args, kwargs = mock_instance.patch.call_args
self.assertEqual('https://domain/api/v2/log-streams/an-id', args[0])
self.assertEqual(kwargs['data'], log_stream_update)
self.assertEqual("https://domain/api/v2/log-streams/an-id", args[0])
self.assertEqual(kwargs["data"], log_stream_update)
import unittest
import mock
from ...management.logs import Logs

@@ -7,32 +9,31 @@

class TestLogs(unittest.TestCase):
def test_init_with_optionals(self):
t = Logs(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = Logs(domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2))
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.logs.RestClient')
@mock.patch("auth0.v3.management.logs.RestClient")
def test_search(self, mock_rc):
mock_instance = mock_rc.return_value
logs = Logs(domain='domain', token='jwttoken')
logs = Logs(domain="domain", token="jwttoken")
logs.search()
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/logs', args[0])
self.assertIsNone(kwargs['params']['sort'])
self.assertIsNone(kwargs['params']['q'])
self.assertIsNone(kwargs['params']['from'])
self.assertIsNone(kwargs['params']['take'])
self.assertEqual(kwargs['params']['include_fields'], 'true')
self.assertEqual(kwargs['params']['include_totals'], 'true')
self.assertEqual(kwargs['params']['per_page'], 50)
self.assertEqual(kwargs['params']['page'], 0)
self.assertIsNone(kwargs['params']['fields'])
self.assertEqual("https://domain/api/v2/logs", args[0])
self.assertIsNone(kwargs["params"]["sort"])
self.assertIsNone(kwargs["params"]["q"])
self.assertIsNone(kwargs["params"]["from"])
self.assertIsNone(kwargs["params"]["take"])
self.assertEqual(kwargs["params"]["include_fields"], "true")
self.assertEqual(kwargs["params"]["include_totals"], "true")
self.assertEqual(kwargs["params"]["per_page"], 50)
self.assertEqual(kwargs["params"]["page"], 0)
self.assertIsNone(kwargs["params"]["fields"])
logs.search(fields=['description', 'client_id'])
logs.search(fields=["description", "client_id"])
args, kwargs = mock_instance.get.call_args
self.assertEqual(kwargs['params']['fields'], 'description,client_id')
self.assertEqual(kwargs["params"]["fields"], "description,client_id")

@@ -42,14 +43,12 @@ logs.search(page=0, per_page=2)

args, kwargs = mock_instance.get.call_args
self.assertEqual(kwargs['params']['per_page'], 2)
self.assertEqual(kwargs['params']['page'], 0)
self.assertEqual(kwargs["params"]["per_page"], 2)
self.assertEqual(kwargs["params"]["page"], 0)
@mock.patch('auth0.v3.management.logs.RestClient')
@mock.patch("auth0.v3.management.logs.RestClient")
def test_get(self, mock_rc):
mock_instance = mock_rc.return_value
logs = Logs(domain='domain', token='jwttoken')
logs.get('get_id')
logs = Logs(domain="domain", token="jwttoken")
logs.get("get_id")
mock_instance.get.assert_called_with(
'https://domain/api/v2/logs/get_id'
)
mock_instance.get.assert_called_with("https://domain/api/v2/logs/get_id")
import unittest
import mock
from ...management.organizations import Organizations

@@ -7,15 +9,16 @@

class TestOrganizations(unittest.TestCase):
def test_init_with_optionals(self):
t = Organizations(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = Organizations(
domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2)
)
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
# Organizations
@mock.patch('auth0.v3.management.organizations.RestClient')
@mock.patch("auth0.v3.management.organizations.RestClient")
def test_all_organizations(self, mock_rc):
mock_instance = mock_rc.return_value
c = Organizations(domain='domain', token='jwttoken')
c = Organizations(domain="domain", token="jwttoken")

@@ -27,8 +30,13 @@ # Default parameters are requested

self.assertEqual('https://domain/api/v2/organizations', args[0])
self.assertEqual(kwargs['params'], {'page': None,
'per_page': None,
'include_totals': 'true',
'from': None,
'take': None})
self.assertEqual("https://domain/api/v2/organizations", args[0])
self.assertEqual(
kwargs["params"],
{
"page": None,
"per_page": None,
"include_totals": "true",
"from": None,
"take": None,
},
)

@@ -40,8 +48,13 @@ # Basic pagination

self.assertEqual('https://domain/api/v2/organizations', args[0])
self.assertEqual(kwargs['params'], {'page': 7,
'per_page': 25,
'include_totals': 'false',
'from': None,
'take': None})
self.assertEqual("https://domain/api/v2/organizations", args[0])
self.assertEqual(
kwargs["params"],
{
"page": 7,
"per_page": 25,
"include_totals": "false",
"from": None,
"take": None,
},
)

@@ -53,314 +66,361 @@ # Checkpoint pagination

self.assertEqual('https://domain/api/v2/organizations', args[0])
self.assertEqual(kwargs['params'], {'from': 8675309,
'take': 75,
'page': None,
'per_page': None,
'include_totals': 'true'})
self.assertEqual("https://domain/api/v2/organizations", args[0])
self.assertEqual(
kwargs["params"],
{
"from": 8675309,
"take": 75,
"page": None,
"per_page": None,
"include_totals": "true",
},
)
@mock.patch('auth0.v3.management.organizations.RestClient')
@mock.patch("auth0.v3.management.organizations.RestClient")
def test_get_organization_by_name(self, mock_rc):
mock_instance = mock_rc.return_value
c = Organizations(domain='domain', token='jwttoken')
c.get_organization_by_name('test-org')
c = Organizations(domain="domain", token="jwttoken")
c.get_organization_by_name("test-org")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/organizations/name/test-org', args[0])
self.assertEqual(kwargs['params'], {})
self.assertEqual("https://domain/api/v2/organizations/name/test-org", args[0])
self.assertEqual(kwargs["params"], {})
@mock.patch('auth0.v3.management.organizations.RestClient')
@mock.patch("auth0.v3.management.organizations.RestClient")
def test_get_organization(self, mock_rc):
mock_instance = mock_rc.return_value
c = Organizations(domain='domain', token='jwttoken')
c.get_organization('org123')
c = Organizations(domain="domain", token="jwttoken")
c.get_organization("org123")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/organizations/org123', args[0])
self.assertEqual(kwargs['params'], {})
self.assertEqual("https://domain/api/v2/organizations/org123", args[0])
self.assertEqual(kwargs["params"], {})
@mock.patch('auth0.v3.management.organizations.RestClient')
@mock.patch("auth0.v3.management.organizations.RestClient")
def test_create_organization(self, mock_rc):
mock_instance = mock_rc.return_value
c = Organizations(domain='domain', token='jwttoken')
c.create_organization({'a': 'b', 'c': 'd'})
c = Organizations(domain="domain", token="jwttoken")
c.create_organization({"a": "b", "c": "d"})
mock_instance.post.assert_called_with(
'https://domain/api/v2/organizations',
data={'a': 'b', 'c': 'd'}
"https://domain/api/v2/organizations", data={"a": "b", "c": "d"}
)
@mock.patch('auth0.v3.management.organizations.RestClient')
@mock.patch("auth0.v3.management.organizations.RestClient")
def test_update_organization(self, mock_rc):
mock_instance = mock_rc.return_value
c = Organizations(domain='domain', token='jwttoken')
c.update_organization('this-id', {'a': 'b', 'c': 'd'})
c = Organizations(domain="domain", token="jwttoken")
c.update_organization("this-id", {"a": "b", "c": "d"})
args, kwargs = mock_instance.patch.call_args
self.assertEqual('https://domain/api/v2/organizations/this-id', args[0])
self.assertEqual(kwargs['data'], {'a': 'b', 'c': 'd'})
self.assertEqual("https://domain/api/v2/organizations/this-id", args[0])
self.assertEqual(kwargs["data"], {"a": "b", "c": "d"})
@mock.patch('auth0.v3.management.organizations.RestClient')
@mock.patch("auth0.v3.management.organizations.RestClient")
def test_delete_organization(self, mock_rc):
mock_instance = mock_rc.return_value
c = Organizations(domain='domain', token='jwttoken')
c.delete_organization('this-id')
c = Organizations(domain="domain", token="jwttoken")
c.delete_organization("this-id")
mock_instance.delete.assert_called_with(
'https://domain/api/v2/organizations/this-id'
"https://domain/api/v2/organizations/this-id"
)
# Organization Connections
@mock.patch('auth0.v3.management.organizations.RestClient')
@mock.patch("auth0.v3.management.organizations.RestClient")
def test_all_organization_connections(self, mock_rc):
mock_instance = mock_rc.return_value
c = Organizations(domain='domain', token='jwttoken')
c = Organizations(domain="domain", token="jwttoken")
# Default parameters are requested
c.all_organization_connections('test-org')
c.all_organization_connections("test-org")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/organizations/test-org/enabled_connections', args[0])
self.assertEqual(kwargs['params'], {'page': None,
'per_page': None})
self.assertEqual(
"https://domain/api/v2/organizations/test-org/enabled_connections", args[0]
)
self.assertEqual(kwargs["params"], {"page": None, "per_page": None})
# Specific pagination
c.all_organization_connections('test-org', page=7, per_page=25)
c.all_organization_connections("test-org", page=7, per_page=25)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/organizations/test-org/enabled_connections', args[0])
self.assertEqual(kwargs['params'], {'page': 7,
'per_page': 25})
self.assertEqual(
"https://domain/api/v2/organizations/test-org/enabled_connections", args[0]
)
self.assertEqual(kwargs["params"], {"page": 7, "per_page": 25})
@mock.patch('auth0.v3.management.organizations.RestClient')
@mock.patch("auth0.v3.management.organizations.RestClient")
def test_get_organization_connection(self, mock_rc):
mock_instance = mock_rc.return_value
c = Organizations(domain='domain', token='jwttoken')
c.get_organization_connection('test-org', 'test-con')
c = Organizations(domain="domain", token="jwttoken")
c.get_organization_connection("test-org", "test-con")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/organizations/test-org/enabled_connections/test-con', args[0])
self.assertEqual(kwargs['params'], {})
self.assertEqual(
"https://domain/api/v2/organizations/test-org/enabled_connections/test-con",
args[0],
)
self.assertEqual(kwargs["params"], {})
@mock.patch('auth0.v3.management.organizations.RestClient')
@mock.patch("auth0.v3.management.organizations.RestClient")
def test_create_organization_connection(self, mock_rc):
mock_instance = mock_rc.return_value
c = Organizations(domain='domain', token='jwttoken')
c.create_organization_connection('test-org', {'a': 'b', 'c': 'd'})
c = Organizations(domain="domain", token="jwttoken")
c.create_organization_connection("test-org", {"a": "b", "c": "d"})
mock_instance.post.assert_called_with(
'https://domain/api/v2/organizations/test-org/enabled_connections',
data={'a': 'b', 'c': 'd'}
"https://domain/api/v2/organizations/test-org/enabled_connections",
data={"a": "b", "c": "d"},
)
@mock.patch('auth0.v3.management.organizations.RestClient')
@mock.patch("auth0.v3.management.organizations.RestClient")
def test_update_organization_connection(self, mock_rc):
mock_instance = mock_rc.return_value
c = Organizations(domain='domain', token='jwttoken')
c.update_organization_connection('test-org', 'test-con', {'a': 'b', 'c': 'd'})
c = Organizations(domain="domain", token="jwttoken")
c.update_organization_connection("test-org", "test-con", {"a": "b", "c": "d"})
args, kwargs = mock_instance.patch.call_args
self.assertEqual('https://domain/api/v2/organizations/test-org/enabled_connections/test-con', args[0])
self.assertEqual(kwargs['data'], {'a': 'b', 'c': 'd'})
self.assertEqual(
"https://domain/api/v2/organizations/test-org/enabled_connections/test-con",
args[0],
)
self.assertEqual(kwargs["data"], {"a": "b", "c": "d"})
@mock.patch('auth0.v3.management.organizations.RestClient')
@mock.patch("auth0.v3.management.organizations.RestClient")
def test_delete_organization_connection(self, mock_rc):
mock_instance = mock_rc.return_value
c = Organizations(domain='domain', token='jwttoken')
c.delete_organization_connection('test-org', 'test-con')
c = Organizations(domain="domain", token="jwttoken")
c.delete_organization_connection("test-org", "test-con")
mock_instance.delete.assert_called_with(
'https://domain/api/v2/organizations/test-org/enabled_connections/test-con'
"https://domain/api/v2/organizations/test-org/enabled_connections/test-con"
)
# Organization Members
@mock.patch('auth0.v3.management.organizations.RestClient')
@mock.patch("auth0.v3.management.organizations.RestClient")
def test_all_organization_members(self, mock_rc):
mock_instance = mock_rc.return_value
c = Organizations(domain='domain', token='jwttoken')
c = Organizations(domain="domain", token="jwttoken")
# Default parameters are requested
c.all_organization_members('test-org')
c.all_organization_members("test-org")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/organizations/test-org/members', args[0])
self.assertEqual(kwargs['params'], {'page': None,
'per_page': None,
'include_totals': 'true',
'from': None,
'take': None})
self.assertEqual(
"https://domain/api/v2/organizations/test-org/members", args[0]
)
self.assertEqual(
kwargs["params"],
{
"page": None,
"per_page": None,
"include_totals": "true",
"from": None,
"take": None,
},
)
# Specific pagination
c.all_organization_members('test-org', page=7, per_page=25, include_totals=False)
c.all_organization_members(
"test-org", page=7, per_page=25, include_totals=False
)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/organizations/test-org/members', args[0])
self.assertEqual(kwargs['params'], {'page': 7,
'per_page': 25,
'include_totals': 'false',
'from': None,
'take': None})
self.assertEqual(
"https://domain/api/v2/organizations/test-org/members", args[0]
)
self.assertEqual(
kwargs["params"],
{
"page": 7,
"per_page": 25,
"include_totals": "false",
"from": None,
"take": None,
},
)
# Checkpoint pagination
c.all_organization_members('test-org', from_param=8675309, take=75)
c.all_organization_members("test-org", from_param=8675309, take=75)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/organizations/test-org/members', args[0])
self.assertEqual(kwargs['params'], {'from': 8675309,
'take': 75,
'page': None,
'per_page': None,
'include_totals': 'true'})
self.assertEqual(
"https://domain/api/v2/organizations/test-org/members", args[0]
)
self.assertEqual(
kwargs["params"],
{
"from": 8675309,
"take": 75,
"page": None,
"per_page": None,
"include_totals": "true",
},
)
@mock.patch('auth0.v3.management.organizations.RestClient')
@mock.patch("auth0.v3.management.organizations.RestClient")
def test_create_organization_members(self, mock_rc):
mock_instance = mock_rc.return_value
c = Organizations(domain='domain', token='jwttoken')
c.create_organization_members('test-org', {'a': 'b', 'c': 'd'})
c = Organizations(domain="domain", token="jwttoken")
c.create_organization_members("test-org", {"a": "b", "c": "d"})
mock_instance.post.assert_called_with(
'https://domain/api/v2/organizations/test-org/members',
data={'a': 'b', 'c': 'd'}
"https://domain/api/v2/organizations/test-org/members",
data={"a": "b", "c": "d"},
)
@mock.patch('auth0.v3.management.organizations.RestClient')
@mock.patch("auth0.v3.management.organizations.RestClient")
def test_delete_organization_members(self, mock_rc):
mock_instance = mock_rc.return_value
c = Organizations(domain='domain', token='jwttoken')
c.delete_organization_members('test-org', {'a': 'b', 'c': 'd'})
c = Organizations(domain="domain", token="jwttoken")
c.delete_organization_members("test-org", {"a": "b", "c": "d"})
mock_instance.delete.assert_called_with(
'https://domain/api/v2/organizations/test-org/members',
data={'a': 'b', 'c': 'd'}
"https://domain/api/v2/organizations/test-org/members",
data={"a": "b", "c": "d"},
)
# Organization Member Roles
@mock.patch('auth0.v3.management.organizations.RestClient')
@mock.patch("auth0.v3.management.organizations.RestClient")
def test_all_organization_member_roles(self, mock_rc):
mock_instance = mock_rc.return_value
c = Organizations(domain='domain', token='jwttoken')
c = Organizations(domain="domain", token="jwttoken")
# Default parameters are requested
c.all_organization_member_roles('test-org', 'test-user')
c.all_organization_member_roles("test-org", "test-user")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/organizations/test-org/members/test-user/roles', args[0])
self.assertEqual(kwargs['params'], {'page': None,
'per_page': None})
self.assertEqual(
"https://domain/api/v2/organizations/test-org/members/test-user/roles",
args[0],
)
self.assertEqual(kwargs["params"], {"page": None, "per_page": None})
# Specific pagination
c.all_organization_member_roles('test-org', 'test-user', page=7, per_page=25)
c.all_organization_member_roles("test-org", "test-user", page=7, per_page=25)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/organizations/test-org/members/test-user/roles', args[0])
self.assertEqual(kwargs['params'], {'page': 7,
'per_page': 25})
self.assertEqual(
"https://domain/api/v2/organizations/test-org/members/test-user/roles",
args[0],
)
self.assertEqual(kwargs["params"], {"page": 7, "per_page": 25})
@mock.patch('auth0.v3.management.organizations.RestClient')
@mock.patch("auth0.v3.management.organizations.RestClient")
def test_create_organization_member_roles(self, mock_rc):
mock_instance = mock_rc.return_value
c = Organizations(domain='domain', token='jwttoken')
c.create_organization_member_roles('test-org', 'test-user', {'a': 'b', 'c': 'd'})
c = Organizations(domain="domain", token="jwttoken")
c.create_organization_member_roles(
"test-org", "test-user", {"a": "b", "c": "d"}
)
mock_instance.post.assert_called_with(
'https://domain/api/v2/organizations/test-org/members/test-user/roles',
data={'a': 'b', 'c': 'd'}
"https://domain/api/v2/organizations/test-org/members/test-user/roles",
data={"a": "b", "c": "d"},
)
@mock.patch('auth0.v3.management.organizations.RestClient')
@mock.patch("auth0.v3.management.organizations.RestClient")
def test_delete_organization_member_roles(self, mock_rc):
mock_instance = mock_rc.return_value
c = Organizations(domain='domain', token='jwttoken')
c.delete_organization_member_roles('test-org', 'test-user', {'a': 'b', 'c': 'd'})
c = Organizations(domain="domain", token="jwttoken")
c.delete_organization_member_roles(
"test-org", "test-user", {"a": "b", "c": "d"}
)
mock_instance.delete.assert_called_with(
'https://domain/api/v2/organizations/test-org/members/test-user/roles',
data={'a': 'b', 'c': 'd'}
"https://domain/api/v2/organizations/test-org/members/test-user/roles",
data={"a": "b", "c": "d"},
)
# Organization Invitations
@mock.patch('auth0.v3.management.organizations.RestClient')
@mock.patch("auth0.v3.management.organizations.RestClient")
def test_all_organization_invitations(self, mock_rc):
mock_instance = mock_rc.return_value
c = Organizations(domain='domain', token='jwttoken')
c = Organizations(domain="domain", token="jwttoken")
# Default parameters are requested
c.all_organization_invitations('test-org')
c.all_organization_invitations("test-org")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/organizations/test-org/invitations', args[0])
self.assertEqual(kwargs['params'], {'page': None,
'per_page': None})
self.assertEqual(
"https://domain/api/v2/organizations/test-org/invitations", args[0]
)
self.assertEqual(kwargs["params"], {"page": None, "per_page": None})
# Specific pagination
c.all_organization_invitations('test-org', page=7, per_page=25)
c.all_organization_invitations("test-org", page=7, per_page=25)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/organizations/test-org/invitations', args[0])
self.assertEqual(kwargs['params'], {'page': 7,
'per_page': 25})
self.assertEqual(
"https://domain/api/v2/organizations/test-org/invitations", args[0]
)
self.assertEqual(kwargs["params"], {"page": 7, "per_page": 25})
@mock.patch('auth0.v3.management.organizations.RestClient')
@mock.patch("auth0.v3.management.organizations.RestClient")
def test_get_organization_invitation(self, mock_rc):
mock_instance = mock_rc.return_value
c = Organizations(domain='domain', token='jwttoken')
c.get_organization_invitation('test-org', 'test-inv')
c = Organizations(domain="domain", token="jwttoken")
c.get_organization_invitation("test-org", "test-inv")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/organizations/test-org/invitations/test-inv', args[0])
self.assertEqual(kwargs['params'], {})
self.assertEqual(
"https://domain/api/v2/organizations/test-org/invitations/test-inv", args[0]
)
self.assertEqual(kwargs["params"], {})
@mock.patch('auth0.v3.management.organizations.RestClient')
@mock.patch("auth0.v3.management.organizations.RestClient")
def test_create_organization_invitation(self, mock_rc):
mock_instance = mock_rc.return_value
c = Organizations(domain='domain', token='jwttoken')
c.create_organization_invitation('test-org', {'a': 'b', 'c': 'd'})
c = Organizations(domain="domain", token="jwttoken")
c.create_organization_invitation("test-org", {"a": "b", "c": "d"})
mock_instance.post.assert_called_with(
'https://domain/api/v2/organizations/test-org/invitations',
data={'a': 'b', 'c': 'd'}
"https://domain/api/v2/organizations/test-org/invitations",
data={"a": "b", "c": "d"},
)
@mock.patch('auth0.v3.management.organizations.RestClient')
@mock.patch("auth0.v3.management.organizations.RestClient")
def test_delete_organization_invitation(self, mock_rc):
mock_instance = mock_rc.return_value
c = Organizations(domain='domain', token='jwttoken')
c.delete_organization_invitation('test-org', 'test-inv')
c = Organizations(domain="domain", token="jwttoken")
c.delete_organization_invitation("test-org", "test-inv")
mock_instance.delete.assert_called_with(
'https://domain/api/v2/organizations/test-org/invitations/test-inv'
"https://domain/api/v2/organizations/test-org/invitations/test-inv"
)

@@ -47,3 +47,6 @@ import unittest

self.assertEqual("https://domain/api/v2/prompts/some-prompt/custom-text/some-language", args[0])
self.assertEqual(
"https://domain/api/v2/prompts/some-prompt/custom-text/some-language",
args[0],
)

@@ -59,3 +62,6 @@ @mock.patch("auth0.v3.management.prompts.RestClient")

self.assertEqual("https://domain/api/v2/prompts/some-prompt/custom-text/some-language", args[0])
self.assertEqual(
"https://domain/api/v2/prompts/some-prompt/custom-text/some-language",
args[0],
)
self.assertEqual(kwargs["data"], {"a": "b", "c": "d"})
import unittest
import mock
from ...management.resource_servers import ResourceServers

@@ -7,27 +9,28 @@

class TestResourceServers(unittest.TestCase):
def test_init_with_optionals(self):
t = ResourceServers(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = ResourceServers(
domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2)
)
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.resource_servers.RestClient')
@mock.patch("auth0.v3.management.resource_servers.RestClient")
def test_create(self, mock_rc):
mock_instance = mock_rc.return_value
r = ResourceServers(domain='domain', token='jwttoken')
r = ResourceServers(domain="domain", token="jwttoken")
r.create({'name': 'TestApi', 'identifier': 'https://test.com/api'})
r.create({"name": "TestApi", "identifier": "https://test.com/api"})
mock_instance.post.assert_called_with(
'https://domain/api/v2/resource-servers',
data={'name': 'TestApi', 'identifier': 'https://test.com/api'}
"https://domain/api/v2/resource-servers",
data={"name": "TestApi", "identifier": "https://test.com/api"},
)
@mock.patch('auth0.v3.management.resource_servers.RestClient')
@mock.patch("auth0.v3.management.resource_servers.RestClient")
def test_get_all(self, mock_rc):
mock_instance = mock_rc.return_value
r = ResourceServers(domain='domain', token='jwttoken')
r = ResourceServers(domain="domain", token="jwttoken")

@@ -38,8 +41,4 @@ # with default params

mock_instance.get.assert_called_with(
'https://domain/api/v2/resource-servers',
params={
'page': None,
'per_page': None,
'include_totals': 'false'
}
"https://domain/api/v2/resource-servers",
params={"page": None, "per_page": None, "include_totals": "false"},
)

@@ -51,47 +50,41 @@

mock_instance.get.assert_called_with(
'https://domain/api/v2/resource-servers',
params={
'page': 3,
'per_page': 27,
'include_totals': 'true'
}
"https://domain/api/v2/resource-servers",
params={"page": 3, "per_page": 27, "include_totals": "true"},
)
@mock.patch('auth0.v3.management.resource_servers.RestClient')
@mock.patch("auth0.v3.management.resource_servers.RestClient")
def test_get(self, mock_rc):
mock_instance = mock_rc.return_value
r = ResourceServers(domain='domain', token='jwttoken')
r = ResourceServers(domain="domain", token="jwttoken")
r.get('some_id')
r.get("some_id")
mock_instance.get.assert_called_with(
'https://domain/api/v2/resource-servers/some_id'
"https://domain/api/v2/resource-servers/some_id"
)
@mock.patch('auth0.v3.management.resource_servers.RestClient')
@mock.patch("auth0.v3.management.resource_servers.RestClient")
def test_delete(self, mock_rc):
mock_instance = mock_rc.return_value
r = ResourceServers(domain='domain', token='jwttoken')
r = ResourceServers(domain="domain", token="jwttoken")
r.delete('some_id')
r.delete("some_id")
mock_instance.delete.assert_called_with(
'https://domain/api/v2/resource-servers/some_id'
"https://domain/api/v2/resource-servers/some_id"
)
@mock.patch('auth0.v3.management.resource_servers.RestClient')
@mock.patch("auth0.v3.management.resource_servers.RestClient")
def test_update(self, mock_rc):
mock_instance = mock_rc.return_value
r = ResourceServers(domain='domain', token='jwttoken')
r = ResourceServers(domain="domain", token="jwttoken")
r.update('some_id', {'name': 'TestApi2',
'identifier': 'https://test.com/api2'})
r.update("some_id", {"name": "TestApi2", "identifier": "https://test.com/api2"})
mock_instance.patch.assert_called_with(
'https://domain/api/v2/resource-servers/some_id',
data={'name': 'TestApi2',
'identifier': 'https://test.com/api2'}
"https://domain/api/v2/resource-servers/some_id",
data={"name": "TestApi2", "identifier": "https://test.com/api2"},
)

@@ -0,5 +1,5 @@

import base64
import json
import sys
import unittest
import sys
import json
import base64

@@ -9,3 +9,4 @@ import mock

from ...management.rest import RestClient, RestClientOptions
from auth0.v3.rest import RestClient, RestClientOptions
from ...exceptions import Auth0Error, RateLimitError

@@ -24,7 +25,7 @@

options = RestClientOptions(telemetry=False, timeout=0.00001, retries=10)
rc = RestClient(jwt='a-token', telemetry=True, timeout=30, options=options)
rc = RestClient(jwt="a-token", telemetry=True, timeout=30, options=options)
# Does a timeout occur as expected?
with self.assertRaises(requests.exceptions.Timeout):
rc.get('http://google.com')
rc.get("http://google.com")

@@ -41,6 +42,9 @@ # Is RestClient using the RestClientOptions.timeout value properly?

# Is RestClient using the RestClientOptions.telemetry value properly?
self.assertEqual(rc.base_headers, {
'Content-Type': 'application/json',
'Authorization': 'Bearer a-token',
})
self.assertEqual(
rc.base_headers,
{
"Content-Type": "application/json",
"Authorization": "Bearer a-token",
},
)

@@ -55,7 +59,7 @@ def test_options_are_created_by_default(self):

rc = RestClient(jwt='a-token', telemetry=False, timeout=0.00002)
rc = RestClient(jwt="a-token", telemetry=False, timeout=0.00002)
# Does a timeout occur as expected?
with self.assertRaises(requests.exceptions.Timeout):
rc.get('http://google.com')
rc.get("http://google.com")

@@ -75,6 +79,9 @@ # Did RestClient create a RestClientOptions for us?

# Is RestClient using the RestClientOptions.telemetry value properly?
self.assertEqual(rc.base_headers, {
'Content-Type': 'application/json',
'Authorization': 'Bearer a-token',
})
self.assertEqual(
rc.base_headers,
{
"Content-Type": "application/json",
"Authorization": "Bearer a-token",
},
)

@@ -90,3 +97,3 @@ def test_default_options_are_used(self):

options = RestClientOptions()
rc = RestClient(jwt='a-token', options=options)
rc = RestClient(jwt="a-token", options=options)

@@ -106,37 +113,37 @@ # Did RestClient store the RestClientOptions?

def test_get_can_timeout(self):
rc = RestClient(jwt='a-token', telemetry=False, timeout=0.00001)
rc = RestClient(jwt="a-token", telemetry=False, timeout=0.00001)
with self.assertRaises(requests.exceptions.Timeout):
rc.get('http://google.com')
rc.get("http://google.com")
def test_post_can_timeout(self):
rc = RestClient(jwt='a-token', telemetry=False, timeout=0.00001)
rc = RestClient(jwt="a-token", telemetry=False, timeout=0.00001)
with self.assertRaises(requests.exceptions.Timeout):
rc.post('http://google.com')
rc.post("http://google.com")
def test_put_can_timeout(self):
rc = RestClient(jwt='a-token', telemetry=False, timeout=0.00001)
rc = RestClient(jwt="a-token", telemetry=False, timeout=0.00001)
with self.assertRaises(requests.exceptions.Timeout):
rc.put('http://google.com')
rc.put("http://google.com")
def test_patch_can_timeout(self):
rc = RestClient(jwt='a-token', telemetry=False, timeout=0.00001)
rc = RestClient(jwt="a-token", telemetry=False, timeout=0.00001)
with self.assertRaises(requests.exceptions.Timeout):
rc.patch('http://google.com')
rc.patch("http://google.com")
def test_delete_can_timeout(self):
rc = RestClient(jwt='a-token', telemetry=False, timeout=0.00001)
rc = RestClient(jwt="a-token", telemetry=False, timeout=0.00001)
with self.assertRaises(requests.exceptions.Timeout):
rc.delete('http://google.com')
rc.delete("http://google.com")
@mock.patch('requests.get')
@mock.patch("requests.get")
def test_get_custom_timeout(self, mock_get):
rc = RestClient(jwt='a-token', telemetry=False, timeout=(10, 2))
rc = RestClient(jwt="a-token", telemetry=False, timeout=(10, 2))
headers = {
'Authorization': 'Bearer a-token',
'Content-Type': 'application/json',
"Authorization": "Bearer a-token",
"Content-Type": "application/json",
}

@@ -146,11 +153,13 @@ mock_get.return_value.text = '["a", "b"]'

rc.get('the-url')
mock_get.assert_called_with('the-url', params=None, headers=headers, timeout=(10, 2))
rc.get("the-url")
mock_get.assert_called_with(
"the-url", params=None, headers=headers, timeout=(10, 2)
)
@mock.patch('requests.post')
@mock.patch("requests.post")
def test_post_custom_timeout(self, mock_post):
rc = RestClient(jwt='a-token', telemetry=False, timeout=(10, 2))
rc = RestClient(jwt="a-token", telemetry=False, timeout=(10, 2))
headers = {
'Authorization': 'Bearer a-token',
'Content-Type': 'application/json',
"Authorization": "Bearer a-token",
"Content-Type": "application/json",
}

@@ -160,11 +169,13 @@ mock_post.return_value.text = '["a", "b"]'

rc.post('the-url')
mock_post.assert_called_with('the-url', json=None, headers=headers, timeout=(10, 2))
rc.post("the-url")
mock_post.assert_called_with(
"the-url", json=None, headers=headers, timeout=(10, 2)
)
@mock.patch('requests.put')
@mock.patch("requests.put")
def test_put_custom_timeout(self, mock_put):
rc = RestClient(jwt='a-token', telemetry=False, timeout=(10, 2))
rc = RestClient(jwt="a-token", telemetry=False, timeout=(10, 2))
headers = {
'Authorization': 'Bearer a-token',
'Content-Type': 'application/json',
"Authorization": "Bearer a-token",
"Content-Type": "application/json",
}

@@ -174,11 +185,13 @@ mock_put.return_value.text = '["a", "b"]'

rc.put('the-url')
mock_put.assert_called_with('the-url', json=None, headers=headers, timeout=(10, 2))
rc.put("the-url")
mock_put.assert_called_with(
"the-url", json=None, headers=headers, timeout=(10, 2)
)
@mock.patch('requests.patch')
@mock.patch("requests.patch")
def test_patch_custom_timeout(self, mock_patch):
rc = RestClient(jwt='a-token', telemetry=False, timeout=(10, 2))
rc = RestClient(jwt="a-token", telemetry=False, timeout=(10, 2))
headers = {
'Authorization': 'Bearer a-token',
'Content-Type': 'application/json',
"Authorization": "Bearer a-token",
"Content-Type": "application/json",
}

@@ -188,11 +201,13 @@ mock_patch.return_value.text = '["a", "b"]'

rc.patch('the-url')
mock_patch.assert_called_with('the-url', json=None, headers=headers, timeout=(10, 2))
rc.patch("the-url")
mock_patch.assert_called_with(
"the-url", json=None, headers=headers, timeout=(10, 2)
)
@mock.patch('requests.delete')
@mock.patch("requests.delete")
def test_delete_custom_timeout(self, mock_delete):
rc = RestClient(jwt='a-token', telemetry=False, timeout=(10, 2))
rc = RestClient(jwt="a-token", telemetry=False, timeout=(10, 2))
headers = {
'Authorization': 'Bearer a-token',
'Content-Type': 'application/json',
"Authorization": "Bearer a-token",
"Content-Type": "application/json",
}

@@ -202,11 +217,13 @@ mock_delete.return_value.text = '["a", "b"]'

rc.delete('the-url')
mock_delete.assert_called_with('the-url', params={}, json=None, headers=headers, timeout=(10, 2))
rc.delete("the-url")
mock_delete.assert_called_with(
"the-url", params={}, json=None, headers=headers, timeout=(10, 2)
)
@mock.patch('requests.get')
@mock.patch("requests.get")
def test_get(self, mock_get):
rc = RestClient(jwt='a-token', telemetry=False)
rc = RestClient(jwt="a-token", telemetry=False)
headers = {
'Authorization': 'Bearer a-token',
'Content-Type': 'application/json',
"Authorization": "Bearer a-token",
"Content-Type": "application/json",
}

@@ -217,68 +234,70 @@

response = rc.get('the-url')
mock_get.assert_called_with('the-url', params=None, headers=headers, timeout=5.0)
response = rc.get("the-url")
mock_get.assert_called_with(
"the-url", params=None, headers=headers, timeout=5.0
)
self.assertEqual(response, ['a', 'b'])
self.assertEqual(response, ["a", "b"])
response = rc.get(url='the/url', params={'A': 'param', 'B': 'param'})
mock_get.assert_called_with('the/url', params={'A': 'param',
'B': 'param'},
headers=headers, timeout=5.0)
self.assertEqual(response, ['a', 'b'])
response = rc.get(url="the/url", params={"A": "param", "B": "param"})
mock_get.assert_called_with(
"the/url", params={"A": "param", "B": "param"}, headers=headers, timeout=5.0
)
self.assertEqual(response, ["a", "b"])
mock_get.return_value.text = ''
response = rc.get('the/url')
self.assertEqual(response, '')
mock_get.return_value.text = ""
response = rc.get("the/url")
self.assertEqual(response, "")
@mock.patch('requests.get')
@mock.patch("requests.get")
def test_get_errors(self, mock_get):
rc = RestClient(jwt='a-token', telemetry=False)
rc = RestClient(jwt="a-token", telemetry=False)
mock_get.return_value.text = '{"statusCode": 999,' \
' "errorCode": "code",' \
' "message": "message"}'
mock_get.return_value.text = (
'{"statusCode": 999, "errorCode": "code", "message": "message"}'
)
mock_get.return_value.status_code = 999
with self.assertRaises(Auth0Error) as context:
rc.get('the/url')
rc.get("the/url")
self.assertEqual(context.exception.status_code, 999)
self.assertEqual(context.exception.error_code, 'code')
self.assertEqual(context.exception.message, 'message')
self.assertEqual(context.exception.error_code, "code")
self.assertEqual(context.exception.message, "message")
@mock.patch('requests.get')
@mock.patch("requests.get")
def test_get_rate_limit_error(self, mock_get):
options = RestClientOptions(telemetry=False, retries=0)
rc = RestClient(jwt='a-token', options=options)
rc = RestClient(jwt="a-token", options=options)
rc._skip_sleep = True
mock_get.return_value.text = '{"statusCode": 429,' \
' "errorCode": "code",' \
' "message": "message"}'
mock_get.return_value.text = (
'{"statusCode": 429, "errorCode": "code", "message": "message"}'
)
mock_get.return_value.status_code = 429
mock_get.return_value.headers = {
'x-ratelimit-limit': '3',
'x-ratelimit-remaining': '6',
'x-ratelimit-reset': '9',
"x-ratelimit-limit": "3",
"x-ratelimit-remaining": "6",
"x-ratelimit-reset": "9",
}
with self.assertRaises(Auth0Error) as context:
rc.get('the/url')
rc.get("the/url")
self.assertEqual(context.exception.status_code, 429)
self.assertEqual(context.exception.error_code, 'code')
self.assertEqual(context.exception.message, 'message')
self.assertEqual(context.exception.error_code, "code")
self.assertEqual(context.exception.message, "message")
self.assertIsInstance(context.exception, RateLimitError)
self.assertEqual(context.exception.reset_at, 9)
self.assertEqual(rc._metrics['retries'], 0)
self.assertEqual(rc._metrics["retries"], 0)
@mock.patch('requests.get')
@mock.patch("requests.get")
def test_get_rate_limit_error_without_headers(self, mock_get):
options = RestClientOptions(telemetry=False, retries=1)
rc = RestClient(jwt='a-token', options=options)
rc = RestClient(jwt="a-token", options=options)
mock_get.return_value.text = '{"statusCode": 429,' \
' "errorCode": "code",' \
' "message": "message"}'
mock_get.return_value.text = (
'{"statusCode": 429, "errorCode": "code", "message": "message"}'
)
mock_get.return_value.status_code = 429

@@ -288,122 +307,121 @@

with self.assertRaises(Auth0Error) as context:
rc.get('the/url')
rc.get("the/url")
self.assertEqual(context.exception.status_code, 429)
self.assertEqual(context.exception.error_code, 'code')
self.assertEqual(context.exception.message, 'message')
self.assertEqual(context.exception.error_code, "code")
self.assertEqual(context.exception.message, "message")
self.assertIsInstance(context.exception, RateLimitError)
self.assertEqual(context.exception.reset_at, -1)
self.assertEqual(rc._metrics['retries'], 1)
self.assertEqual(rc._metrics["retries"], 1)
@mock.patch('requests.get')
@mock.patch("requests.get")
def test_get_rate_limit_custom_retries(self, mock_get):
options = RestClientOptions(telemetry=False, retries=5)
rc = RestClient(jwt='a-token', options=options)
rc = RestClient(jwt="a-token", options=options)
rc._skip_sleep = True
mock_get.return_value.text = '{"statusCode": 429,' \
' "errorCode": "code",' \
' "message": "message"}'
mock_get.return_value.text = (
'{"statusCode": 429, "errorCode": "code", "message": "message"}'
)
mock_get.return_value.status_code = 429
mock_get.return_value.headers = {
'x-ratelimit-limit': '3',
'x-ratelimit-remaining': '6',
'x-ratelimit-reset': '9',
"x-ratelimit-limit": "3",
"x-ratelimit-remaining": "6",
"x-ratelimit-reset": "9",
}
with self.assertRaises(Auth0Error) as context:
response = rc.get('the/url')
rc.get("the/url")
self.assertEqual(context.exception.status_code, 429)
self.assertEqual(context.exception.error_code, 'code')
self.assertEqual(context.exception.message, 'message')
self.assertEqual(context.exception.error_code, "code")
self.assertEqual(context.exception.message, "message")
self.assertIsInstance(context.exception, RateLimitError)
self.assertEqual(context.exception.reset_at, 9)
self.assertEqual(rc._metrics['retries'], 5)
self.assertEqual(rc._metrics['retries'], len(rc._metrics['backoff']))
self.assertEqual(rc._metrics["retries"], 5)
self.assertEqual(rc._metrics["retries"], len(rc._metrics["backoff"]))
@mock.patch('requests.get')
@mock.patch("requests.get")
def test_get_rate_limit_invalid_retries_below_min(self, mock_get):
options = RestClientOptions(telemetry=False, retries=-1)
rc = RestClient(jwt='a-token', options=options)
rc = RestClient(jwt="a-token", options=options)
rc._skip_sleep = True
mock_get.return_value.text = '{"statusCode": 429,' \
' "errorCode": "code",' \
' "message": "message"}'
mock_get.return_value.text = (
'{"statusCode": 429, "errorCode": "code", "message": "message"}'
)
mock_get.return_value.status_code = 429
mock_get.return_value.headers = {
'x-ratelimit-limit': '3',
'x-ratelimit-remaining': '6',
'x-ratelimit-reset': '9',
"x-ratelimit-limit": "3",
"x-ratelimit-remaining": "6",
"x-ratelimit-reset": "9",
}
with self.assertRaises(Auth0Error) as context:
response = rc.get('the/url')
rc.get("the/url")
self.assertEqual(context.exception.status_code, 429)
self.assertEqual(context.exception.error_code, 'code')
self.assertEqual(context.exception.message, 'message')
self.assertEqual(context.exception.error_code, "code")
self.assertEqual(context.exception.message, "message")
self.assertIsInstance(context.exception, RateLimitError)
self.assertEqual(context.exception.reset_at, 9)
self.assertEqual(rc._metrics['retries'], 0)
self.assertEqual(rc._metrics["retries"], 0)
@mock.patch('requests.get')
@mock.patch("requests.get")
def test_get_rate_limit_invalid_retries_above_max(self, mock_get):
options = RestClientOptions(telemetry=False, retries=11)
rc = RestClient(jwt='a-token', options=options)
rc = RestClient(jwt="a-token", options=options)
rc._skip_sleep = True
mock_get.return_value.text = '{"statusCode": 429,' \
' "errorCode": "code",' \
' "message": "message"}'
mock_get.return_value.text = (
'{"statusCode": 429, "errorCode": "code", "message": "message"}'
)
mock_get.return_value.status_code = 429
mock_get.return_value.headers = {
'x-ratelimit-limit': '3',
'x-ratelimit-remaining': '6',
'x-ratelimit-reset': '9',
"x-ratelimit-limit": "3",
"x-ratelimit-remaining": "6",
"x-ratelimit-reset": "9",
}
with self.assertRaises(Auth0Error) as context:
response = rc.get('the/url')
rc.get("the/url")
self.assertEqual(context.exception.status_code, 429)
self.assertEqual(context.exception.error_code, 'code')
self.assertEqual(context.exception.message, 'message')
self.assertEqual(context.exception.error_code, "code")
self.assertEqual(context.exception.message, "message")
self.assertIsInstance(context.exception, RateLimitError)
self.assertEqual(context.exception.reset_at, 9)
self.assertEqual(rc._metrics['retries'], rc.MAX_REQUEST_RETRIES())
self.assertEqual(rc._metrics["retries"], rc.MAX_REQUEST_RETRIES())
@mock.patch('requests.get')
@mock.patch("requests.get")
def test_get_rate_limit_retries_use_exponential_backoff(self, mock_get):
options = RestClientOptions(telemetry=False, retries=10)
rc = RestClient(jwt='a-token', options=options)
rc = RestClient(jwt="a-token", options=options)
rc._skip_sleep = True
mock_get.return_value.text = '{"statusCode": 429,' \
' "errorCode": "code",' \
' "message": "message"}'
mock_get.return_value.text = (
'{"statusCode": 429, "errorCode": "code", "message": "message"}'
)
mock_get.return_value.status_code = 429
mock_get.return_value.headers = {
'x-ratelimit-limit': '3',
'x-ratelimit-remaining': '6',
'x-ratelimit-reset': '9',
"x-ratelimit-limit": "3",
"x-ratelimit-remaining": "6",
"x-ratelimit-reset": "9",
}
with self.assertRaises(Auth0Error) as context:
response = rc.get('the/url')
rc.get("the/url")
self.assertEqual(context.exception.status_code, 429)
self.assertEqual(context.exception.error_code, 'code')
self.assertEqual(context.exception.message, 'message')
self.assertEqual(context.exception.error_code, "code")
self.assertEqual(context.exception.message, "message")
self.assertIsInstance(context.exception, RateLimitError)
self.assertEqual(context.exception.reset_at, 9)
self.assertEqual(rc._metrics['retries'], 10)
self.assertEqual(rc._metrics['retries'], len(rc._metrics['backoff']))
self.assertEqual(rc._metrics["retries"], 10)
self.assertEqual(rc._metrics["retries"], len(rc._metrics["backoff"]))

@@ -415,53 +433,53 @@ baseBackoff = [0]

for i in range(0, 9):
backoff = 100 * 2 ** i
backoff = 100 * 2**i
baseBackoff.append(backoff)
baseBackoffSum += backoff
for backoff in rc._metrics['backoff']:
for backoff in rc._metrics["backoff"]:
finalBackoff += backoff
# Assert that exponential backoff is happening.
self.assertGreaterEqual(rc._metrics['backoff'][1], rc._metrics['backoff'][0])
self.assertGreaterEqual(rc._metrics['backoff'][2], rc._metrics['backoff'][1])
self.assertGreaterEqual(rc._metrics['backoff'][3], rc._metrics['backoff'][2])
self.assertGreaterEqual(rc._metrics['backoff'][4], rc._metrics['backoff'][3])
self.assertGreaterEqual(rc._metrics['backoff'][5], rc._metrics['backoff'][4])
self.assertGreaterEqual(rc._metrics['backoff'][6], rc._metrics['backoff'][5])
self.assertGreaterEqual(rc._metrics['backoff'][7], rc._metrics['backoff'][6])
self.assertGreaterEqual(rc._metrics['backoff'][8], rc._metrics['backoff'][7])
self.assertGreaterEqual(rc._metrics['backoff'][9], rc._metrics['backoff'][8])
self.assertGreaterEqual(rc._metrics["backoff"][1], rc._metrics["backoff"][0])
self.assertGreaterEqual(rc._metrics["backoff"][2], rc._metrics["backoff"][1])
self.assertGreaterEqual(rc._metrics["backoff"][3], rc._metrics["backoff"][2])
self.assertGreaterEqual(rc._metrics["backoff"][4], rc._metrics["backoff"][3])
self.assertGreaterEqual(rc._metrics["backoff"][5], rc._metrics["backoff"][4])
self.assertGreaterEqual(rc._metrics["backoff"][6], rc._metrics["backoff"][5])
self.assertGreaterEqual(rc._metrics["backoff"][7], rc._metrics["backoff"][6])
self.assertGreaterEqual(rc._metrics["backoff"][8], rc._metrics["backoff"][7])
self.assertGreaterEqual(rc._metrics["backoff"][9], rc._metrics["backoff"][8])
# Ensure jitter is being applied.
self.assertNotEqual(rc._metrics['backoff'][1], baseBackoff[1])
self.assertNotEqual(rc._metrics['backoff'][2], baseBackoff[2])
self.assertNotEqual(rc._metrics['backoff'][3], baseBackoff[3])
self.assertNotEqual(rc._metrics['backoff'][4], baseBackoff[4])
self.assertNotEqual(rc._metrics['backoff'][5], baseBackoff[5])
self.assertNotEqual(rc._metrics['backoff'][6], baseBackoff[6])
self.assertNotEqual(rc._metrics['backoff'][7], baseBackoff[7])
self.assertNotEqual(rc._metrics['backoff'][8], baseBackoff[8])
self.assertNotEqual(rc._metrics['backoff'][9], baseBackoff[9])
self.assertNotEqual(rc._metrics["backoff"][1], baseBackoff[1])
self.assertNotEqual(rc._metrics["backoff"][2], baseBackoff[2])
self.assertNotEqual(rc._metrics["backoff"][3], baseBackoff[3])
self.assertNotEqual(rc._metrics["backoff"][4], baseBackoff[4])
self.assertNotEqual(rc._metrics["backoff"][5], baseBackoff[5])
self.assertNotEqual(rc._metrics["backoff"][6], baseBackoff[6])
self.assertNotEqual(rc._metrics["backoff"][7], baseBackoff[7])
self.assertNotEqual(rc._metrics["backoff"][8], baseBackoff[8])
self.assertNotEqual(rc._metrics["backoff"][9], baseBackoff[9])
# Ensure subsequent delay is never less than the minimum.
self.assertGreaterEqual(rc._metrics['backoff'][1], rc.MIN_REQUEST_RETRY_DELAY())
self.assertGreaterEqual(rc._metrics['backoff'][2], rc.MIN_REQUEST_RETRY_DELAY())
self.assertGreaterEqual(rc._metrics['backoff'][3], rc.MIN_REQUEST_RETRY_DELAY())
self.assertGreaterEqual(rc._metrics['backoff'][4], rc.MIN_REQUEST_RETRY_DELAY())
self.assertGreaterEqual(rc._metrics['backoff'][5], rc.MIN_REQUEST_RETRY_DELAY())
self.assertGreaterEqual(rc._metrics['backoff'][6], rc.MIN_REQUEST_RETRY_DELAY())
self.assertGreaterEqual(rc._metrics['backoff'][7], rc.MIN_REQUEST_RETRY_DELAY())
self.assertGreaterEqual(rc._metrics['backoff'][8], rc.MIN_REQUEST_RETRY_DELAY())
self.assertGreaterEqual(rc._metrics['backoff'][9], rc.MIN_REQUEST_RETRY_DELAY())
self.assertGreaterEqual(rc._metrics["backoff"][1], rc.MIN_REQUEST_RETRY_DELAY())
self.assertGreaterEqual(rc._metrics["backoff"][2], rc.MIN_REQUEST_RETRY_DELAY())
self.assertGreaterEqual(rc._metrics["backoff"][3], rc.MIN_REQUEST_RETRY_DELAY())
self.assertGreaterEqual(rc._metrics["backoff"][4], rc.MIN_REQUEST_RETRY_DELAY())
self.assertGreaterEqual(rc._metrics["backoff"][5], rc.MIN_REQUEST_RETRY_DELAY())
self.assertGreaterEqual(rc._metrics["backoff"][6], rc.MIN_REQUEST_RETRY_DELAY())
self.assertGreaterEqual(rc._metrics["backoff"][7], rc.MIN_REQUEST_RETRY_DELAY())
self.assertGreaterEqual(rc._metrics["backoff"][8], rc.MIN_REQUEST_RETRY_DELAY())
self.assertGreaterEqual(rc._metrics["backoff"][9], rc.MIN_REQUEST_RETRY_DELAY())
# Ensure delay is never more than the maximum.
self.assertLessEqual(rc._metrics['backoff'][0], rc.MAX_REQUEST_RETRY_DELAY())
self.assertLessEqual(rc._metrics['backoff'][1], rc.MAX_REQUEST_RETRY_DELAY())
self.assertLessEqual(rc._metrics['backoff'][2], rc.MAX_REQUEST_RETRY_DELAY())
self.assertLessEqual(rc._metrics['backoff'][3], rc.MAX_REQUEST_RETRY_DELAY())
self.assertLessEqual(rc._metrics['backoff'][4], rc.MAX_REQUEST_RETRY_DELAY())
self.assertLessEqual(rc._metrics['backoff'][5], rc.MAX_REQUEST_RETRY_DELAY())
self.assertLessEqual(rc._metrics['backoff'][6], rc.MAX_REQUEST_RETRY_DELAY())
self.assertLessEqual(rc._metrics['backoff'][7], rc.MAX_REQUEST_RETRY_DELAY())
self.assertLessEqual(rc._metrics['backoff'][8], rc.MAX_REQUEST_RETRY_DELAY())
self.assertLessEqual(rc._metrics['backoff'][9], rc.MAX_REQUEST_RETRY_DELAY())
self.assertLessEqual(rc._metrics["backoff"][0], rc.MAX_REQUEST_RETRY_DELAY())
self.assertLessEqual(rc._metrics["backoff"][1], rc.MAX_REQUEST_RETRY_DELAY())
self.assertLessEqual(rc._metrics["backoff"][2], rc.MAX_REQUEST_RETRY_DELAY())
self.assertLessEqual(rc._metrics["backoff"][3], rc.MAX_REQUEST_RETRY_DELAY())
self.assertLessEqual(rc._metrics["backoff"][4], rc.MAX_REQUEST_RETRY_DELAY())
self.assertLessEqual(rc._metrics["backoff"][5], rc.MAX_REQUEST_RETRY_DELAY())
self.assertLessEqual(rc._metrics["backoff"][6], rc.MAX_REQUEST_RETRY_DELAY())
self.assertLessEqual(rc._metrics["backoff"][7], rc.MAX_REQUEST_RETRY_DELAY())
self.assertLessEqual(rc._metrics["backoff"][8], rc.MAX_REQUEST_RETRY_DELAY())
self.assertLessEqual(rc._metrics["backoff"][9], rc.MAX_REQUEST_RETRY_DELAY())

@@ -471,108 +489,107 @@ # Ensure total delay sum is never more than 10s.

@mock.patch('requests.post')
@mock.patch("requests.post")
def test_post(self, mock_post):
rc = RestClient(jwt='a-token', telemetry=False)
headers = {'Authorization': 'Bearer a-token',
'Content-Type': 'application/json'}
rc = RestClient(jwt="a-token", telemetry=False)
headers = {
"Authorization": "Bearer a-token",
"Content-Type": "application/json",
}
mock_post.return_value.text = '{"a": "b"}'
data = {'some': 'data'}
data = {"some": "data"}
mock_post.return_value.status_code = 200
response = rc.post('the/url', data=data)
mock_post.assert_called_with('the/url', json=data,
headers=headers, timeout=5.0)
response = rc.post("the/url", data=data)
mock_post.assert_called_with("the/url", json=data, headers=headers, timeout=5.0)
self.assertEqual(response, {'a': 'b'})
self.assertEqual(response, {"a": "b"})
@mock.patch('requests.post')
@mock.patch("requests.post")
def test_post_errors(self, mock_post):
rc = RestClient(jwt='a-token', telemetry=False)
rc = RestClient(jwt="a-token", telemetry=False)
mock_post.return_value.text = '{"statusCode": 999,' \
' "errorCode": "code",' \
' "message": "message"}'
mock_post.return_value.text = (
'{"statusCode": 999, "errorCode": "code", "message": "message"}'
)
mock_post.return_value.status_code = 999
with self.assertRaises(Auth0Error) as context:
rc.post('the-url')
rc.post("the-url")
self.assertEqual(context.exception.status_code, 999)
self.assertEqual(context.exception.error_code, 'code')
self.assertEqual(context.exception.message, 'message')
self.assertEqual(context.exception.error_code, "code")
self.assertEqual(context.exception.message, "message")
@mock.patch('requests.post')
@mock.patch("requests.post")
def test_post_errors_with_no_message_property(self, mock_post):
rc = RestClient(jwt='a-token', telemetry=False)
rc = RestClient(jwt="a-token", telemetry=False)
mock_post.return_value.text = json.dumps({
"statusCode": 999,
"errorCode": "code",
"error": "error"
})
mock_post.return_value.text = json.dumps(
{"statusCode": 999, "errorCode": "code", "error": "error"}
)
mock_post.return_value.status_code = 999
with self.assertRaises(Auth0Error) as context:
rc.post('the-url')
rc.post("the-url")
self.assertEqual(context.exception.status_code, 999)
self.assertEqual(context.exception.error_code, 'code')
self.assertEqual(context.exception.message, 'error')
self.assertEqual(context.exception.error_code, "code")
self.assertEqual(context.exception.message, "error")
@mock.patch('requests.post')
@mock.patch("requests.post")
def test_post_errors_with_no_message_or_error_property(self, mock_post):
rc = RestClient(jwt='a-token', telemetry=False)
rc = RestClient(jwt="a-token", telemetry=False)
mock_post.return_value.text = json.dumps({
"statusCode": 999,
"errorCode": "code"
})
mock_post.return_value.text = json.dumps(
{"statusCode": 999, "errorCode": "code"}
)
mock_post.return_value.status_code = 999
with self.assertRaises(Auth0Error) as context:
rc.post('the-url')
rc.post("the-url")
self.assertEqual(context.exception.status_code, 999)
self.assertEqual(context.exception.error_code, 'code')
self.assertEqual(context.exception.message, '')
self.assertEqual(context.exception.error_code, "code")
self.assertEqual(context.exception.message, "")
@mock.patch('requests.post')
@mock.patch("requests.post")
def test_post_errors_with_message_and_error_property(self, mock_post):
rc = RestClient(jwt='a-token', telemetry=False)
rc = RestClient(jwt="a-token", telemetry=False)
mock_post.return_value.text = json.dumps({
"statusCode": 999,
"errorCode": "code",
"error": "error",
"message": "message"
})
mock_post.return_value.text = json.dumps(
{
"statusCode": 999,
"errorCode": "code",
"error": "error",
"message": "message",
}
)
mock_post.return_value.status_code = 999
with self.assertRaises(Auth0Error) as context:
rc.post('the-url')
rc.post("the-url")
self.assertEqual(context.exception.status_code, 999)
self.assertEqual(context.exception.error_code, 'code')
self.assertEqual(context.exception.message, 'message')
self.assertEqual(context.exception.error_code, "code")
self.assertEqual(context.exception.message, "message")
@mock.patch('requests.post')
@mock.patch("requests.post")
def test_post_error_with_code_property(self, mock_post):
rc = RestClient(jwt='a-token', telemetry=False)
rc = RestClient(jwt="a-token", telemetry=False)
for error_status in [400, 500, None]:
mock_post.return_value.status_code = error_status
mock_post.return_value.text = '{"errorCode": "e0",' \
'"message": "desc"}'
mock_post.return_value.text = '{"errorCode": "e0","message": "desc"}'
with self.assertRaises(Auth0Error) as context:
rc.post('the-url')
rc.post("the-url")
self.assertEqual(context.exception.status_code, error_status)
self.assertEqual(context.exception.error_code, 'e0')
self.assertEqual(context.exception.message, 'desc')
self.assertEqual(context.exception.error_code, "e0")
self.assertEqual(context.exception.message, "desc")
@mock.patch('requests.post')
@mock.patch("requests.post")
def test_post_error_with_no_error_code(self, mock_post):
rc = RestClient(jwt='a-token', telemetry=False)
rc = RestClient(jwt="a-token", telemetry=False)

@@ -584,27 +601,28 @@ for error_status in [400, 500, None]:

with self.assertRaises(Auth0Error) as context:
rc.post('the-url')
rc.post("the-url")
self.assertEqual(context.exception.status_code, error_status)
self.assertEqual(context.exception.error_code, 'a0.sdk.internal.unknown')
self.assertEqual(context.exception.message, 'desc')
self.assertEqual(context.exception.error_code, "a0.sdk.internal.unknown")
self.assertEqual(context.exception.message, "desc")
@mock.patch('requests.post')
@mock.patch("requests.post")
def test_post_error_with_text_response(self, mock_post):
rc = RestClient(jwt='a-token', telemetry=False)
rc = RestClient(jwt="a-token", telemetry=False)
for error_status in [400, 500, None]:
mock_post.return_value.status_code = error_status
mock_post.return_value.text = 'there has been a terrible error'
mock_post.return_value.text = "there has been a terrible error"
with self.assertRaises(Auth0Error) as context:
rc.post('the-url')
rc.post("the-url")
self.assertEqual(context.exception.status_code, error_status)
self.assertEqual(context.exception.error_code, 'a0.sdk.internal.unknown')
self.assertEqual(context.exception.message,
'there has been a terrible error')
self.assertEqual(context.exception.error_code, "a0.sdk.internal.unknown")
self.assertEqual(
context.exception.message, "there has been a terrible error"
)
@mock.patch('requests.post')
@mock.patch("requests.post")
def test_post_error_with_no_response_text(self, mock_post):
rc = RestClient(jwt='a-token', telemetry=False)
rc = RestClient(jwt="a-token", telemetry=False)

@@ -616,27 +634,31 @@ for error_status in [400, 500, None]:

with self.assertRaises(Auth0Error) as context:
rc.post('the-url')
rc.post("the-url")
self.assertEqual(context.exception.status_code, error_status)
self.assertEqual(context.exception.error_code, 'a0.sdk.internal.unknown')
self.assertEqual(context.exception.message, '')
self.assertEqual(context.exception.error_code, "a0.sdk.internal.unknown")
self.assertEqual(context.exception.message, "")
@mock.patch('requests.post')
@mock.patch("requests.post")
def test_file_post_content_type_is_none(self, mock_post):
rc = RestClient(jwt='a-token', telemetry=False)
headers = {'Authorization': 'Bearer a-token'}
rc = RestClient(jwt="a-token", telemetry=False)
headers = {"Authorization": "Bearer a-token"}
mock_post.return_value.status_code = 200
mock_post.return_value.text = 'Success'
mock_post.return_value.text = "Success"
data = {'some': 'data'}
data = {"some": "data"}
files = [mock.Mock()]
rc.file_post('the-url', data=data, files=files)
rc.file_post("the-url", data=data, files=files)
mock_post.assert_called_once_with('the-url', data=data, files=files, headers=headers, timeout=5.0)
mock_post.assert_called_once_with(
"the-url", data=data, files=files, headers=headers, timeout=5.0
)
@mock.patch('requests.put')
@mock.patch("requests.put")
def test_put(self, mock_put):
rc = RestClient(jwt='a-token', telemetry=False)
headers = {'Authorization': 'Bearer a-token',
'Content-Type': 'application/json'}
rc = RestClient(jwt="a-token", telemetry=False)
headers = {
"Authorization": "Bearer a-token",
"Content-Type": "application/json",
}

@@ -646,31 +668,32 @@ mock_put.return_value.text = '["a", "b"]'

data = {'some': 'data'}
data = {"some": "data"}
response = rc.put(url='the-url', data=data)
mock_put.assert_called_with('the-url', json=data,
headers=headers, timeout=5.0)
response = rc.put(url="the-url", data=data)
mock_put.assert_called_with("the-url", json=data, headers=headers, timeout=5.0)
self.assertEqual(response, ['a', 'b'])
self.assertEqual(response, ["a", "b"])
@mock.patch('requests.put')
@mock.patch("requests.put")
def test_put_errors(self, mock_put):
rc = RestClient(jwt='a-token', telemetry=False)
rc = RestClient(jwt="a-token", telemetry=False)
mock_put.return_value.text = '{"statusCode": 999,' \
' "errorCode": "code",' \
' "message": "message"}'
mock_put.return_value.text = (
'{"statusCode": 999, "errorCode": "code", "message": "message"}'
)
mock_put.return_value.status_code = 999
with self.assertRaises(Auth0Error) as context:
rc.put(url='the/url')
rc.put(url="the/url")
self.assertEqual(context.exception.status_code, 999)
self.assertEqual(context.exception.error_code, 'code')
self.assertEqual(context.exception.message, 'message')
self.assertEqual(context.exception.error_code, "code")
self.assertEqual(context.exception.message, "message")
@mock.patch('requests.patch')
@mock.patch("requests.patch")
def test_patch(self, mock_patch):
rc = RestClient(jwt='a-token', telemetry=False)
headers = {'Authorization': 'Bearer a-token',
'Content-Type': 'application/json'}
rc = RestClient(jwt="a-token", telemetry=False)
headers = {
"Authorization": "Bearer a-token",
"Content-Type": "application/json",
}

@@ -680,32 +703,33 @@ mock_patch.return_value.text = '["a", "b"]'

data = {'some': 'data'}
data = {"some": "data"}
response = rc.patch(url='the-url', data=data)
mock_patch.assert_called_with('the-url', json=data,
headers=headers, timeout=5.0)
response = rc.patch(url="the-url", data=data)
mock_patch.assert_called_with(
"the-url", json=data, headers=headers, timeout=5.0
)
self.assertEqual(response, ['a', 'b'])
self.assertEqual(response, ["a", "b"])
@mock.patch('requests.patch')
@mock.patch("requests.patch")
def test_patch_errors(self, mock_patch):
rc = RestClient(jwt='a-token', telemetry=False)
rc = RestClient(jwt="a-token", telemetry=False)
mock_patch.return_value.text = '{"statusCode": 999,' \
' "errorCode": "code",' \
' "message": "message"}'
mock_patch.return_value.text = (
'{"statusCode": 999, "errorCode": "code", "message": "message"}'
)
mock_patch.return_value.status_code = 999
with self.assertRaises(Auth0Error) as context:
rc.patch(url='the/url')
rc.patch(url="the/url")
self.assertEqual(context.exception.status_code, 999)
self.assertEqual(context.exception.error_code, 'code')
self.assertEqual(context.exception.message, 'message')
self.assertEqual(context.exception.error_code, "code")
self.assertEqual(context.exception.message, "message")
@mock.patch('requests.delete')
@mock.patch("requests.delete")
def test_delete(self, mock_delete):
rc = RestClient(jwt='a-token', telemetry=False)
rc = RestClient(jwt="a-token", telemetry=False)
headers = {
'Authorization': 'Bearer a-token',
'Content-Type': 'application/json',
"Authorization": "Bearer a-token",
"Content-Type": "application/json",
}

@@ -716,13 +740,15 @@

response = rc.delete(url='the-url/ID')
mock_delete.assert_called_with('the-url/ID', headers=headers, params={}, json=None, timeout=5.0)
response = rc.delete(url="the-url/ID")
mock_delete.assert_called_with(
"the-url/ID", headers=headers, params={}, json=None, timeout=5.0
)
self.assertEqual(response, ['a', 'b'])
self.assertEqual(response, ["a", "b"])
@mock.patch('requests.delete')
@mock.patch("requests.delete")
def test_delete_with_body_and_params(self, mock_delete):
rc = RestClient(jwt='a-token', telemetry=False)
rc = RestClient(jwt="a-token", telemetry=False)
headers = {
'Authorization': 'Bearer a-token',
'Content-Type': 'application/json',
"Authorization": "Bearer a-token",
"Content-Type": "application/json",
}

@@ -733,31 +759,33 @@

data = {'some': 'data'}
params = {'A': 'param', 'B': 'param'}
data = {"some": "data"}
params = {"A": "param", "B": "param"}
response = rc.delete(url='the-url/ID', params=params, data=data)
mock_delete.assert_called_with('the-url/ID', headers=headers, params=params, json=data, timeout=5.0)
response = rc.delete(url="the-url/ID", params=params, data=data)
mock_delete.assert_called_with(
"the-url/ID", headers=headers, params=params, json=data, timeout=5.0
)
self.assertEqual(response, ['a', 'b'])
self.assertEqual(response, ["a", "b"])
@mock.patch('requests.delete')
@mock.patch("requests.delete")
def test_delete_errors(self, mock_delete):
rc = RestClient(jwt='a-token', telemetry=False)
rc = RestClient(jwt="a-token", telemetry=False)
mock_delete.return_value.text = '{"statusCode": 999,' \
' "errorCode": "code",' \
' "message": "message"}'
mock_delete.return_value.text = (
'{"statusCode": 999, "errorCode": "code", "message": "message"}'
)
mock_delete.return_value.status_code = 999
with self.assertRaises(Auth0Error) as context:
rc.delete(url='the-url')
rc.delete(url="the-url")
self.assertEqual(context.exception.status_code, 999)
self.assertEqual(context.exception.error_code, 'code')
self.assertEqual(context.exception.message, 'message')
self.assertEqual(context.exception.error_code, "code")
self.assertEqual(context.exception.message, "message")
def test_disabled_telemetry(self):
rc = RestClient(jwt='a-token', telemetry=False)
rc = RestClient(jwt="a-token", telemetry=False)
expected_headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer a-token',
"Content-Type": "application/json",
"Authorization": "Bearer a-token",
}

@@ -768,25 +796,24 @@

def test_enabled_telemetry(self):
rc = RestClient(jwt='a-token', telemetry=True)
rc = RestClient(jwt="a-token", telemetry=True)
user_agent = rc.base_headers['User-Agent']
auth0_client_bytes = base64.b64decode(rc.base_headers['Auth0-Client'])
auth0_client_json = auth0_client_bytes.decode('utf-8')
user_agent = rc.base_headers["User-Agent"]
auth0_client_bytes = base64.b64decode(rc.base_headers["Auth0-Client"])
auth0_client_json = auth0_client_bytes.decode("utf-8")
auth0_client = json.loads(auth0_client_json)
content_type = rc.base_headers['Content-Type']
content_type = rc.base_headers["Content-Type"]
from auth0 import __version__ as auth0_version
python_version = '{}.{}.{}'.format(sys.version_info.major,
sys.version_info.minor,
sys.version_info.micro)
python_version = "{}.{}.{}".format(
sys.version_info.major, sys.version_info.minor, sys.version_info.micro
)
client_info = {
'name': 'auth0-python',
'version': auth0_version,
'env': {
'python': python_version
}
"name": "auth0-python",
"version": auth0_version,
"env": {"python": python_version},
}
self.assertEqual(user_agent, 'Python/{}'.format(python_version))
self.assertEqual(user_agent, "Python/{}".format(python_version))
self.assertEqual(auth0_client, client_info)
self.assertEqual(content_type, 'application/json')
self.assertEqual(content_type, "application/json")
import unittest
import mock
from ...management.roles import Roles

@@ -7,14 +9,13 @@

class TestRoles(unittest.TestCase):
def test_init_with_optionals(self):
t = Roles(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = Roles(domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2))
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.roles.RestClient')
@mock.patch("auth0.v3.management.roles.RestClient")
def test_list(self, mock_rc):
mock_instance = mock_rc.return_value
u = Roles(domain='domain', token='jwttoken')
u = Roles(domain="domain", token="jwttoken")
u.list()

@@ -24,175 +25,175 @@

self.assertEqual('https://domain/api/v2/roles', args[0])
self.assertEqual(kwargs['params'], {
'per_page': 25,
'page': 0,
'include_totals': 'true',
'name_filter': None
})
self.assertEqual("https://domain/api/v2/roles", args[0])
self.assertEqual(
kwargs["params"],
{"per_page": 25, "page": 0, "include_totals": "true", "name_filter": None},
)
u.list(page=1, per_page=50, include_totals=False, name_filter='little-role')
u.list(page=1, per_page=50, include_totals=False, name_filter="little-role")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/roles', args[0])
self.assertEqual(kwargs['params'], {
'per_page': 50,
'page': 1,
'include_totals': 'false',
'name_filter': 'little-role'
})
self.assertEqual("https://domain/api/v2/roles", args[0])
self.assertEqual(
kwargs["params"],
{
"per_page": 50,
"page": 1,
"include_totals": "false",
"name_filter": "little-role",
},
)
@mock.patch('auth0.v3.management.roles.RestClient')
@mock.patch("auth0.v3.management.roles.RestClient")
def test_create(self, mock_rc):
mock_instance = mock_rc.return_value
u = Roles(domain='domain', token='jwttoken')
u.create({'a': 'b', 'c': 'd'})
u = Roles(domain="domain", token="jwttoken")
u.create({"a": "b", "c": "d"})
args, kwargs = mock_instance.post.call_args
self.assertEqual('https://domain/api/v2/roles', args[0])
self.assertEqual(kwargs['data'], {'a': 'b', 'c': 'd'})
self.assertEqual("https://domain/api/v2/roles", args[0])
self.assertEqual(kwargs["data"], {"a": "b", "c": "d"})
@mock.patch('auth0.v3.management.roles.RestClient')
@mock.patch("auth0.v3.management.roles.RestClient")
def test_get(self, mock_rc):
mock_instance = mock_rc.return_value
u = Roles(domain='domain', token='jwttoken')
u.get('an-id')
u = Roles(domain="domain", token="jwttoken")
u.get("an-id")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/roles/an-id', args[0])
self.assertEqual("https://domain/api/v2/roles/an-id", args[0])
@mock.patch('auth0.v3.management.roles.RestClient')
@mock.patch("auth0.v3.management.roles.RestClient")
def test_delete(self, mock_rc):
mock_instance = mock_rc.return_value
u = Roles(domain='domain', token='jwttoken')
u.delete('an-id')
u = Roles(domain="domain", token="jwttoken")
u.delete("an-id")
mock_instance.delete.assert_called_with(
'https://domain/api/v2/roles/an-id'
)
mock_instance.delete.assert_called_with("https://domain/api/v2/roles/an-id")
@mock.patch('auth0.v3.management.roles.RestClient')
@mock.patch("auth0.v3.management.roles.RestClient")
def test_update(self, mock_rc):
mock_instance = mock_rc.return_value
u = Roles(domain='domain', token='jwttoken')
u.update('an-id', {'a': 'b', 'c': 'd'})
u = Roles(domain="domain", token="jwttoken")
u.update("an-id", {"a": "b", "c": "d"})
args, kwargs = mock_instance.patch.call_args
self.assertEqual('https://domain/api/v2/roles/an-id', args[0])
self.assertEqual(kwargs['data'], {'a': 'b', 'c': 'd'})
self.assertEqual("https://domain/api/v2/roles/an-id", args[0])
self.assertEqual(kwargs["data"], {"a": "b", "c": "d"})
@mock.patch('auth0.v3.management.roles.RestClient')
@mock.patch("auth0.v3.management.roles.RestClient")
def test_list_users(self, mock_rc):
mock_instance = mock_rc.return_value
u = Roles(domain='domain', token='jwttoken')
u.list_users('an-id')
u = Roles(domain="domain", token="jwttoken")
u.list_users("an-id")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/roles/an-id/users', args[0])
self.assertEqual(kwargs['params'], {
'per_page': 25,
'page': 0,
'include_totals': 'true',
'from': None,
'take': None
})
self.assertEqual("https://domain/api/v2/roles/an-id/users", args[0])
self.assertEqual(
kwargs["params"],
{
"per_page": 25,
"page": 0,
"include_totals": "true",
"from": None,
"take": None,
},
)
u.list_users(id='an-id', page=1, per_page=50, include_totals=False)
u.list_users(id="an-id", page=1, per_page=50, include_totals=False)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/roles/an-id/users', args[0])
self.assertEqual(kwargs['params'], {
'per_page': 50,
'page': 1,
'include_totals': 'false',
'from': None,
'take': None
})
self.assertEqual("https://domain/api/v2/roles/an-id/users", args[0])
self.assertEqual(
kwargs["params"],
{
"per_page": 50,
"page": 1,
"include_totals": "false",
"from": None,
"take": None,
},
)
u.list_users(id='an-id', from_param=8675309, take=75)
u.list_users(id="an-id", from_param=8675309, take=75)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/roles/an-id/users', args[0])
self.assertEqual(kwargs['params'], {
'from': 8675309,
'take': 75,
'per_page': 25,
'page': 0,
'include_totals': 'true',
})
self.assertEqual("https://domain/api/v2/roles/an-id/users", args[0])
self.assertEqual(
kwargs["params"],
{
"from": 8675309,
"take": 75,
"per_page": 25,
"page": 0,
"include_totals": "true",
},
)
@mock.patch('auth0.v3.management.roles.RestClient')
@mock.patch("auth0.v3.management.roles.RestClient")
def test_add_users(self, mock_rc):
mock_instance = mock_rc.return_value
u = Roles(domain='domain', token='jwttoken')
u.add_users('an-id', ['a', 'b'])
u = Roles(domain="domain", token="jwttoken")
u.add_users("an-id", ["a", "b"])
args, kwargs = mock_instance.post.call_args
self.assertEqual('https://domain/api/v2/roles/an-id/users',
args[0])
self.assertEqual(kwargs['data'], {'users': ['a', 'b']})
self.assertEqual("https://domain/api/v2/roles/an-id/users", args[0])
self.assertEqual(kwargs["data"], {"users": ["a", "b"]})
@mock.patch('auth0.v3.management.roles.RestClient')
@mock.patch("auth0.v3.management.roles.RestClient")
def test_list_permissions(self, mock_rc):
mock_instance = mock_rc.return_value
u = Roles(domain='domain', token='jwttoken')
u.list_permissions('an-id')
u = Roles(domain="domain", token="jwttoken")
u.list_permissions("an-id")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/roles/an-id/permissions', args[0])
self.assertEqual(kwargs['params'], {
'per_page': 25,
'page': 0,
'include_totals': 'true'
})
self.assertEqual("https://domain/api/v2/roles/an-id/permissions", args[0])
self.assertEqual(
kwargs["params"], {"per_page": 25, "page": 0, "include_totals": "true"}
)
u.list_permissions(id='an-id', page=1, per_page=50, include_totals=False)
u.list_permissions(id="an-id", page=1, per_page=50, include_totals=False)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/roles/an-id/permissions', args[0])
self.assertEqual(kwargs['params'], {
'per_page': 50,
'page': 1,
'include_totals': 'false'
})
self.assertEqual("https://domain/api/v2/roles/an-id/permissions", args[0])
self.assertEqual(
kwargs["params"], {"per_page": 50, "page": 1, "include_totals": "false"}
)
@mock.patch('auth0.v3.management.roles.RestClient')
@mock.patch("auth0.v3.management.roles.RestClient")
def test_remove_permissions(self, mock_rc):
mock_instance = mock_rc.return_value
u = Roles(domain='domain', token='jwttoken')
u.remove_permissions('an-id', ['a', 'b'])
u = Roles(domain="domain", token="jwttoken")
u.remove_permissions("an-id", ["a", "b"])
args, kwargs = mock_instance.delete.call_args
self.assertEqual('https://domain/api/v2/roles/an-id/permissions',
args[0])
self.assertEqual(kwargs['data'], {'permissions': ['a', 'b']})
self.assertEqual("https://domain/api/v2/roles/an-id/permissions", args[0])
self.assertEqual(kwargs["data"], {"permissions": ["a", "b"]})
@mock.patch('auth0.v3.management.roles.RestClient')
@mock.patch("auth0.v3.management.roles.RestClient")
def test_add_permissions(self, mock_rc):
mock_instance = mock_rc.return_value
u = Roles(domain='domain', token='jwttoken')
u.add_permissions('an-id', ['a', 'b'])
u = Roles(domain="domain", token="jwttoken")
u.add_permissions("an-id", ["a", "b"])
args, kwargs = mock_instance.post.call_args
self.assertEqual('https://domain/api/v2/roles/an-id/permissions',
args[0])
self.assertEqual(kwargs['data'], {'permissions': ['a', 'b']})
self.assertEqual("https://domain/api/v2/roles/an-id/permissions", args[0])
self.assertEqual(kwargs["data"], {"permissions": ["a", "b"]})
import unittest
import mock
from ...management.rules_configs import RulesConfigs

@@ -7,14 +9,15 @@

class TestRulesConfigs(unittest.TestCase):
def test_init_with_optionals(self):
t = RulesConfigs(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = RulesConfigs(
domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2)
)
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.rules_configs.RestClient')
@mock.patch("auth0.v3.management.rules_configs.RestClient")
def test_all(self, mock_rc):
mock_instance = mock_rc.return_value
c = RulesConfigs(domain='domain', token='jwttoken')
c = RulesConfigs(domain="domain", token="jwttoken")

@@ -25,27 +28,23 @@ c.all()

self.assertEqual('https://domain/api/v2/rules-configs', args[0])
self.assertEqual("https://domain/api/v2/rules-configs", args[0])
@mock.patch('auth0.v3.management.rules_configs.RestClient')
@mock.patch("auth0.v3.management.rules_configs.RestClient")
def test_unset(self, mock_rc):
mock_instance = mock_rc.return_value
c = RulesConfigs(domain='domain', token='jwttoken')
c.unset('an-id')
c = RulesConfigs(domain="domain", token="jwttoken")
c.unset("an-id")
mock_instance.delete.assert_called_with(
'https://domain/api/v2/rules-configs/an-id'
"https://domain/api/v2/rules-configs/an-id"
)
@mock.patch('auth0.v3.management.rules_configs.RestClient')
@mock.patch("auth0.v3.management.rules_configs.RestClient")
def test_set(self, mock_rc):
mock_instance = mock_rc.return_value
g = RulesConfigs(domain='domain', token='jwttoken')
g.set('key', 'MY_RULES_CONFIG_VALUES')
g = RulesConfigs(domain="domain", token="jwttoken")
g.set("key", "MY_RULES_CONFIG_VALUES")
args, kwargs = mock_instance.put.call_args
self.assertEqual('https://domain/api/v2/rules-configs/key', args[0])
self.assertEqual("https://domain/api/v2/rules-configs/key", args[0])
import unittest
import mock
from ...management.rules import Rules

@@ -7,14 +9,13 @@

class TestRules(unittest.TestCase):
def test_init_with_optionals(self):
t = Rules(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = Rules(domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2))
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.rules.RestClient')
@mock.patch("auth0.v3.management.rules.RestClient")
def test_all(self, mock_rc):
mock_instance = mock_rc.return_value
c = Rules(domain='domain', token='jwttoken')
c = Rules(domain="domain", token="jwttoken")

@@ -26,25 +27,34 @@ # with default params

self.assertEqual('https://domain/api/v2/rules', args[0])
self.assertEqual(kwargs['params'], {'fields': None,
'include_fields': 'true',
'enabled': 'true',
'stage': 'login_success',
'page': None,
'per_page': None,
'include_totals': 'false'})
self.assertEqual("https://domain/api/v2/rules", args[0])
self.assertEqual(
kwargs["params"],
{
"fields": None,
"include_fields": "true",
"enabled": "true",
"stage": "login_success",
"page": None,
"per_page": None,
"include_totals": "false",
},
)
# with stage and fields params
c.all(stage='stage', enabled=False, fields=['a', 'b'],
include_fields=False)
c.all(stage="stage", enabled=False, fields=["a", "b"], include_fields=False)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/rules', args[0])
self.assertEqual(kwargs['params'], {'fields': 'a,b',
'include_fields': 'false',
'enabled': 'false',
'stage': 'stage',
'page': None,
'per_page': None,
'include_totals': 'false'})
self.assertEqual("https://domain/api/v2/rules", args[0])
self.assertEqual(
kwargs["params"],
{
"fields": "a,b",
"include_fields": "false",
"enabled": "false",
"stage": "stage",
"page": None,
"per_page": None,
"include_totals": "false",
},
)

@@ -56,65 +66,66 @@ # with pagination params

self.assertEqual('https://domain/api/v2/rules', args[0])
self.assertEqual(kwargs['params'], {'fields': None,
'include_fields': 'true',
'enabled': 'true',
'stage': 'login_success',
'page': 3,
'per_page': 27,
'include_totals': 'true'})
self.assertEqual("https://domain/api/v2/rules", args[0])
self.assertEqual(
kwargs["params"],
{
"fields": None,
"include_fields": "true",
"enabled": "true",
"stage": "login_success",
"page": 3,
"per_page": 27,
"include_totals": "true",
},
)
@mock.patch('auth0.v3.management.rules.RestClient')
@mock.patch("auth0.v3.management.rules.RestClient")
def test_create(self, mock_rc):
mock_instance = mock_rc.return_value
c = Rules(domain='domain', token='jwttoken')
c.create({'a': 'b', 'c': 'd'})
c = Rules(domain="domain", token="jwttoken")
c.create({"a": "b", "c": "d"})
args, kwargs = mock_instance.post.call_args
self.assertEqual('https://domain/api/v2/rules', args[0])
self.assertEqual(kwargs['data'], {'a': 'b', 'c': 'd'})
self.assertEqual("https://domain/api/v2/rules", args[0])
self.assertEqual(kwargs["data"], {"a": "b", "c": "d"})
@mock.patch('auth0.v3.management.rules.RestClient')
@mock.patch("auth0.v3.management.rules.RestClient")
def test_get(self, mock_rc):
mock_instance = mock_rc.return_value
c = Rules(domain='domain', token='jwttoken')
c.get('an-id')
c = Rules(domain="domain", token="jwttoken")
c.get("an-id")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/rules/an-id', args[0])
self.assertEqual(kwargs['params'], {'fields': None,
'include_fields': 'true'})
self.assertEqual("https://domain/api/v2/rules/an-id", args[0])
self.assertEqual(kwargs["params"], {"fields": None, "include_fields": "true"})
c.get('an-id', fields=['a', 'b'], include_fields=False)
c.get("an-id", fields=["a", "b"], include_fields=False)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/rules/an-id', args[0])
self.assertEqual(kwargs['params'], {'fields': 'a,b',
'include_fields': 'false'})
self.assertEqual("https://domain/api/v2/rules/an-id", args[0])
self.assertEqual(kwargs["params"], {"fields": "a,b", "include_fields": "false"})
@mock.patch('auth0.v3.management.rules.RestClient')
@mock.patch("auth0.v3.management.rules.RestClient")
def test_delete(self, mock_rc):
mock_instance = mock_rc.return_value
c = Rules(domain='domain', token='jwttoken')
c.delete('an-id')
c = Rules(domain="domain", token="jwttoken")
c.delete("an-id")
mock_instance.delete.assert_called_with(
'https://domain/api/v2/rules/an-id'
)
mock_instance.delete.assert_called_with("https://domain/api/v2/rules/an-id")
@mock.patch('auth0.v3.management.rules.RestClient')
@mock.patch("auth0.v3.management.rules.RestClient")
def test_update(self, mock_rc):
mock_instance = mock_rc.return_value
c = Rules(domain='domain', token='jwttoken')
c.update('an-id', {'a': 'b', 'c': 'd'})
c = Rules(domain="domain", token="jwttoken")
c.update("an-id", {"a": "b", "c": "d"})
args, kwargs = mock_instance.patch.call_args
self.assertEqual('https://domain/api/v2/rules/an-id', args[0])
self.assertEqual(kwargs['data'], {'a': 'b', 'c': 'd'})
self.assertEqual("https://domain/api/v2/rules/an-id", args[0])
self.assertEqual(kwargs["data"], {"a": "b", "c": "d"})
import unittest
import mock
from ...management.stats import Stats

@@ -7,37 +9,36 @@

class TestStats(unittest.TestCase):
def test_init_with_optionals(self):
t = Stats(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = Stats(domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2))
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.stats.RestClient')
@mock.patch("auth0.v3.management.stats.RestClient")
def test_active_users(self, mock_rc):
mock_instance = mock_rc.return_value
s = Stats(domain='domain', token='jwttoken')
s = Stats(domain="domain", token="jwttoken")
s.active_users()
mock_instance.get.assert_called_with(
'https://domain/api/v2/stats/active-users',
"https://domain/api/v2/stats/active-users",
)
@mock.patch('auth0.v3.management.stats.RestClient')
@mock.patch("auth0.v3.management.stats.RestClient")
def test_daily_stats(self, mock_rc):
mock_instance = mock_rc.return_value
s = Stats(domain='domain', token='jwttoken')
s = Stats(domain="domain", token="jwttoken")
s.daily_stats()
mock_instance.get.assert_called_with(
'https://domain/api/v2/stats/daily',
params={'from': None, 'to': None},
"https://domain/api/v2/stats/daily",
params={"from": None, "to": None},
)
s.daily_stats(from_date='12341212', to_date='56785656')
s.daily_stats(from_date="12341212", to_date="56785656")
mock_instance.get.assert_called_with(
'https://domain/api/v2/stats/daily',
params={'from': '12341212', 'to': '56785656'},
"https://domain/api/v2/stats/daily",
params={"from": "12341212", "to": "56785656"},
)
import unittest
import mock
from ...management.tenants import Tenants

@@ -7,10 +9,9 @@

class TestTenants(unittest.TestCase):
def test_init_with_optionals(self):
t = Tenants(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = Tenants(domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2))
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.tenants.RestClient')
@mock.patch("auth0.v3.management.tenants.RestClient")
def test_get(self, mock_rc):

@@ -20,3 +21,3 @@ mock_instance = mock_rc.return_value

t = Tenants(domain='domain', token='jwttoken')
t = Tenants(domain="domain", token="jwttoken")
t.get()

@@ -26,23 +27,20 @@

self.assertEqual('https://domain/api/v2/tenants/settings', args[0])
self.assertEqual(kwargs['params'], {'fields': None,
'include_fields': 'true'})
self.assertEqual("https://domain/api/v2/tenants/settings", args[0])
self.assertEqual(kwargs["params"], {"fields": None, "include_fields": "true"})
t.get(fields=['a', 'b'], include_fields=False)
t.get(fields=["a", "b"], include_fields=False)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/tenants/settings', args[0])
self.assertEqual(kwargs['params'], {'fields': 'a,b',
'include_fields': 'false'})
self.assertEqual("https://domain/api/v2/tenants/settings", args[0])
self.assertEqual(kwargs["params"], {"fields": "a,b", "include_fields": "false"})
t.get(fields=['a', 'b'], include_fields=True)
t.get(fields=["a", "b"], include_fields=True)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/tenants/settings', args[0])
self.assertEqual(kwargs['params'], {'fields': 'a,b',
'include_fields': 'true'})
self.assertEqual("https://domain/api/v2/tenants/settings", args[0])
self.assertEqual(kwargs["params"], {"fields": "a,b", "include_fields": "true"})
@mock.patch('auth0.v3.management.tenants.RestClient')
@mock.patch("auth0.v3.management.tenants.RestClient")
def test_update(self, mock_rc):

@@ -52,8 +50,7 @@ mock_instance = mock_rc.return_value

t = Tenants(domain='domain', token='jwttoken')
t.update({'a': 'b', 'c': 'd'})
t = Tenants(domain="domain", token="jwttoken")
t.update({"a": "b", "c": "d"})
mock_instance.patch.assert_called_with(
'https://domain/api/v2/tenants/settings',
data={'a': 'b', 'c': 'd'}
"https://domain/api/v2/tenants/settings", data={"a": "b", "c": "d"}
)
import unittest
import mock
from ...management.tickets import Tickets

@@ -7,31 +9,29 @@

class TestTickets(unittest.TestCase):
def test_init_with_optionals(self):
t = Tickets(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = Tickets(domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2))
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.tickets.RestClient')
@mock.patch("auth0.v3.management.tickets.RestClient")
def test_email(self, mock_rc):
mock_instance = mock_rc.return_value
t = Tickets(domain='domain', token='jwttoken')
t.create_email_verification({'a': 'b', 'c': 'd'})
t = Tickets(domain="domain", token="jwttoken")
t.create_email_verification({"a": "b", "c": "d"})
mock_instance.post.assert_called_with(
'https://domain/api/v2/tickets/email-verification',
data={'a': 'b', 'c': 'd'}
"https://domain/api/v2/tickets/email-verification",
data={"a": "b", "c": "d"},
)
@mock.patch('auth0.v3.management.tickets.RestClient')
@mock.patch("auth0.v3.management.tickets.RestClient")
def test_pswd(self, mock_rc):
mock_instance = mock_rc.return_value
t = Tickets(domain='domain', token='jwttoken')
t.create_pswd_change({'a': 'b', 'c': 'd'})
t = Tickets(domain="domain", token="jwttoken")
t.create_pswd_change({"a": "b", "c": "d"})
mock_instance.post.assert_called_with(
'https://domain/api/v2/tickets/password-change',
data={'a': 'b', 'c': 'd'}
"https://domain/api/v2/tickets/password-change", data={"a": "b", "c": "d"}
)
import unittest
import mock
from ...management.user_blocks import UserBlocks

@@ -7,57 +9,57 @@

class TestUserBlocks(unittest.TestCase):
def test_init_with_optionals(self):
t = UserBlocks(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = UserBlocks(
domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2)
)
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.user_blocks.RestClient')
@mock.patch("auth0.v3.management.user_blocks.RestClient")
def test_get_by_identifier(self, mock_rc):
mock_instance = mock_rc.return_value
u = UserBlocks(domain='domain', token='jwttoken')
u = UserBlocks(domain="domain", token="jwttoken")
u.get_by_identifier('some_identifier')
u.get_by_identifier("some_identifier")
mock_instance.get.assert_called_with(
'https://domain/api/v2/user-blocks',
params={'identifier': 'some_identifier'}
"https://domain/api/v2/user-blocks",
params={"identifier": "some_identifier"},
)
@mock.patch('auth0.v3.management.user_blocks.RestClient')
@mock.patch("auth0.v3.management.user_blocks.RestClient")
def test_unblock_by_identifier(self, mock_rc):
mock_instance = mock_rc.return_value
u = UserBlocks(domain='domain', token='jwttoken')
u = UserBlocks(domain="domain", token="jwttoken")
u.unblock_by_identifier('test@test.com')
u.unblock_by_identifier("test@test.com")
mock_instance.delete.assert_called_with(
'https://domain/api/v2/user-blocks',
params={'identifier': 'test@test.com'}
"https://domain/api/v2/user-blocks", params={"identifier": "test@test.com"}
)
@mock.patch('auth0.v3.management.user_blocks.RestClient')
@mock.patch("auth0.v3.management.user_blocks.RestClient")
def test_get(self, mock_rc):
mock_instance = mock_rc.return_value
u = UserBlocks(domain='domain', token='jwttoken')
u = UserBlocks(domain="domain", token="jwttoken")
u.get('auth0|584ad3c228be27504a2c80d5')
u.get("auth0|584ad3c228be27504a2c80d5")
mock_instance.get.assert_called_with(
'https://domain/api/v2/user-blocks/auth0|584ad3c228be27504a2c80d5'
"https://domain/api/v2/user-blocks/auth0|584ad3c228be27504a2c80d5"
)
@mock.patch('auth0.v3.management.user_blocks.RestClient')
@mock.patch("auth0.v3.management.user_blocks.RestClient")
def test_unblock(self, mock_rc):
mock_instance = mock_rc.return_value
u = UserBlocks(domain='domain', token='jwttoken')
u = UserBlocks(domain="domain", token="jwttoken")
u.unblock('auth0|584ad3c228be27504a2c80d5')
u.unblock("auth0|584ad3c228be27504a2c80d5")
mock_instance.delete.assert_called_with(
'https://domain/api/v2/user-blocks/auth0|584ad3c228be27504a2c80d5'
"https://domain/api/v2/user-blocks/auth0|584ad3c228be27504a2c80d5"
)
import unittest
import mock
from ...management.users_by_email import UsersByEmail

@@ -7,36 +9,35 @@

class TestUsersByEmail(unittest.TestCase):
def test_init_with_optionals(self):
t = UsersByEmail(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = UsersByEmail(
domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2)
)
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.users_by_email.RestClient')
@mock.patch("auth0.v3.management.users_by_email.RestClient")
def test_search_users_by_email(self, mock_rc):
mock_instance = mock_rc.return_value
u = UsersByEmail(domain='domain', token='jwttoken')
u.search_users_by_email('A@B.com')
u = UsersByEmail(domain="domain", token="jwttoken")
u.search_users_by_email("A@B.com")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/users-by-email', args[0])
self.assertEqual(kwargs['params'], {
'email': 'A@B.com',
'fields': None,
'include_fields': 'true'
})
self.assertEqual("https://domain/api/v2/users-by-email", args[0])
self.assertEqual(
kwargs["params"],
{"email": "A@B.com", "fields": None, "include_fields": "true"},
)
u.search_users_by_email(email='a@b.com',
fields=['a', 'b'],
include_fields=False)
u.search_users_by_email(
email="a@b.com", fields=["a", "b"], include_fields=False
)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/users-by-email', args[0])
self.assertEqual(kwargs['params'], {
'email': 'a@b.com',
'fields': 'a,b',
'include_fields': 'false'
})
self.assertEqual("https://domain/api/v2/users-by-email", args[0])
self.assertEqual(
kwargs["params"],
{"email": "a@b.com", "fields": "a,b", "include_fields": "false"},
)
import unittest
import mock
from ...management.users import Users

@@ -7,14 +9,13 @@

class TestUsers(unittest.TestCase):
def test_init_with_optionals(self):
t = Users(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
t = Users(domain="domain", token="jwttoken", telemetry=False, timeout=(10, 2))
self.assertEqual(t.client.options.timeout, (10, 2))
telemetry_header = t.client.base_headers.get('Auth0-Client', None)
telemetry_header = t.client.base_headers.get("Auth0-Client", None)
self.assertEqual(telemetry_header, None)
@mock.patch('auth0.v3.management.users.RestClient')
@mock.patch("auth0.v3.management.users.RestClient")
def test_list(self, mock_rc):
mock_instance = mock_rc.return_value
u = Users(domain='domain', token='jwttoken')
u = Users(domain="domain", token="jwttoken")
u.list()

@@ -24,321 +25,315 @@

self.assertEqual('https://domain/api/v2/users', args[0])
self.assertEqual(kwargs['params'], {
'per_page': 25,
'page': 0,
'include_totals': 'true',
'sort': None,
'connection': None,
'fields': None,
'include_fields': 'true',
'q': None,
'search_engine': None
})
self.assertEqual("https://domain/api/v2/users", args[0])
self.assertEqual(
kwargs["params"],
{
"per_page": 25,
"page": 0,
"include_totals": "true",
"sort": None,
"connection": None,
"fields": None,
"include_fields": "true",
"q": None,
"search_engine": None,
},
)
u.list(page=1, per_page=50, sort='s', connection='con', q='q',
search_engine='se', include_totals=False, fields=['a', 'b'],
include_fields=False)
u.list(
page=1,
per_page=50,
sort="s",
connection="con",
q="q",
search_engine="se",
include_totals=False,
fields=["a", "b"],
include_fields=False,
)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/users', args[0])
self.assertEqual(kwargs['params'], {
'per_page': 50,
'page': 1,
'include_totals': 'false',
'sort': 's',
'connection': 'con',
'fields': 'a,b',
'include_fields': 'false',
'q': 'q',
'search_engine': 'se'
})
self.assertEqual("https://domain/api/v2/users", args[0])
self.assertEqual(
kwargs["params"],
{
"per_page": 50,
"page": 1,
"include_totals": "false",
"sort": "s",
"connection": "con",
"fields": "a,b",
"include_fields": "false",
"q": "q",
"search_engine": "se",
},
)
@mock.patch('auth0.v3.management.users.RestClient')
@mock.patch("auth0.v3.management.users.RestClient")
def test_create(self, mock_rc):
mock_instance = mock_rc.return_value
u = Users(domain='domain', token='jwttoken')
u.create({'a': 'b', 'c': 'd'})
u = Users(domain="domain", token="jwttoken")
u.create({"a": "b", "c": "d"})
args, kwargs = mock_instance.post.call_args
self.assertEqual('https://domain/api/v2/users', args[0])
self.assertEqual(kwargs['data'], {'a': 'b', 'c': 'd'})
self.assertEqual("https://domain/api/v2/users", args[0])
self.assertEqual(kwargs["data"], {"a": "b", "c": "d"})
@mock.patch('auth0.v3.management.users.RestClient')
@mock.patch("auth0.v3.management.users.RestClient")
def test_delete_all_users(self, mock_rc):
mock_instance = mock_rc.return_value
u = Users(domain='domain', token='jwttoken')
u = Users(domain="domain", token="jwttoken")
u.delete_all_users()
mock_instance.delete.assert_called_with(
'https://domain/api/v2/users'
)
mock_instance.delete.assert_called_with("https://domain/api/v2/users")
@mock.patch('auth0.v3.management.users.RestClient')
@mock.patch("auth0.v3.management.users.RestClient")
def test_get(self, mock_rc):
mock_instance = mock_rc.return_value
u = Users(domain='domain', token='jwttoken')
u.get('an-id')
u = Users(domain="domain", token="jwttoken")
u.get("an-id")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/users/an-id', args[0])
self.assertEqual(kwargs['params'], {'fields': None,
'include_fields': 'true'})
self.assertEqual("https://domain/api/v2/users/an-id", args[0])
self.assertEqual(kwargs["params"], {"fields": None, "include_fields": "true"})
u.get('an-id', fields=['a', 'b'], include_fields=False)
u.get("an-id", fields=["a", "b"], include_fields=False)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/users/an-id', args[0])
self.assertEqual(kwargs['params'], {'fields': 'a,b',
'include_fields': 'false'})
self.assertEqual("https://domain/api/v2/users/an-id", args[0])
self.assertEqual(kwargs["params"], {"fields": "a,b", "include_fields": "false"})
@mock.patch('auth0.v3.management.users.RestClient')
@mock.patch("auth0.v3.management.users.RestClient")
def test_delete(self, mock_rc):
mock_instance = mock_rc.return_value
u = Users(domain='domain', token='jwttoken')
u.delete('an-id')
u = Users(domain="domain", token="jwttoken")
u.delete("an-id")
mock_instance.delete.assert_called_with(
'https://domain/api/v2/users/an-id'
)
mock_instance.delete.assert_called_with("https://domain/api/v2/users/an-id")
@mock.patch('auth0.v3.management.users.RestClient')
@mock.patch("auth0.v3.management.users.RestClient")
def test_update(self, mock_rc):
mock_instance = mock_rc.return_value
u = Users(domain='domain', token='jwttoken')
u.update('an-id', {'a': 'b', 'c': 'd'})
u = Users(domain="domain", token="jwttoken")
u.update("an-id", {"a": "b", "c": "d"})
args, kwargs = mock_instance.patch.call_args
self.assertEqual('https://domain/api/v2/users/an-id', args[0])
self.assertEqual(kwargs['data'], {'a': 'b', 'c': 'd'})
self.assertEqual("https://domain/api/v2/users/an-id", args[0])
self.assertEqual(kwargs["data"], {"a": "b", "c": "d"})
@mock.patch('auth0.v3.management.users.RestClient')
@mock.patch("auth0.v3.management.users.RestClient")
def test_list_organizations(self, mock_rc):
mock_instance = mock_rc.return_value
u = Users(domain='domain', token='jwttoken')
u.list_organizations('an-id')
u = Users(domain="domain", token="jwttoken")
u.list_organizations("an-id")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/users/an-id/organizations', args[0])
self.assertEqual(kwargs['params'], {
'per_page': 25,
'page': 0,
'include_totals': 'true'
})
self.assertEqual("https://domain/api/v2/users/an-id/organizations", args[0])
self.assertEqual(
kwargs["params"], {"per_page": 25, "page": 0, "include_totals": "true"}
)
u.list_organizations(id='an-id', page=1, per_page=50, include_totals=False)
u.list_organizations(id="an-id", page=1, per_page=50, include_totals=False)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/users/an-id/organizations', args[0])
self.assertEqual(kwargs['params'], {
'per_page': 50,
'page': 1,
'include_totals': 'false'
})
self.assertEqual("https://domain/api/v2/users/an-id/organizations", args[0])
self.assertEqual(
kwargs["params"], {"per_page": 50, "page": 1, "include_totals": "false"}
)
@mock.patch('auth0.v3.management.users.RestClient')
@mock.patch("auth0.v3.management.users.RestClient")
def test_list_roles(self, mock_rc):
mock_instance = mock_rc.return_value
u = Users(domain='domain', token='jwttoken')
u.list_roles('an-id')
u = Users(domain="domain", token="jwttoken")
u.list_roles("an-id")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/users/an-id/roles', args[0])
self.assertEqual(kwargs['params'], {
'per_page': 25,
'page': 0,
'include_totals': 'true'
})
self.assertEqual("https://domain/api/v2/users/an-id/roles", args[0])
self.assertEqual(
kwargs["params"], {"per_page": 25, "page": 0, "include_totals": "true"}
)
u.list_roles(id='an-id', page=1, per_page=50, include_totals=False)
u.list_roles(id="an-id", page=1, per_page=50, include_totals=False)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/users/an-id/roles', args[0])
self.assertEqual(kwargs['params'], {
'per_page': 50,
'page': 1,
'include_totals': 'false'
})
self.assertEqual("https://domain/api/v2/users/an-id/roles", args[0])
self.assertEqual(
kwargs["params"], {"per_page": 50, "page": 1, "include_totals": "false"}
)
@mock.patch('auth0.v3.management.users.RestClient')
@mock.patch("auth0.v3.management.users.RestClient")
def test_remove_roles(self, mock_rc):
mock_instance = mock_rc.return_value
u = Users(domain='domain', token='jwttoken')
u.remove_roles('an-id', ['a', 'b'])
u = Users(domain="domain", token="jwttoken")
u.remove_roles("an-id", ["a", "b"])
args, kwargs = mock_instance.delete.call_args
self.assertEqual('https://domain/api/v2/users/an-id/roles',
args[0])
self.assertEqual(kwargs['data'], {'roles': ['a', 'b']})
self.assertEqual("https://domain/api/v2/users/an-id/roles", args[0])
self.assertEqual(kwargs["data"], {"roles": ["a", "b"]})
@mock.patch('auth0.v3.management.users.RestClient')
@mock.patch("auth0.v3.management.users.RestClient")
def test_add_roles(self, mock_rc):
mock_instance = mock_rc.return_value
u = Users(domain='domain', token='jwttoken')
u.add_roles('an-id', ['a', 'b'])
u = Users(domain="domain", token="jwttoken")
u.add_roles("an-id", ["a", "b"])
args, kwargs = mock_instance.post.call_args
self.assertEqual('https://domain/api/v2/users/an-id/roles',
args[0])
self.assertEqual(kwargs['data'], {'roles': ['a', 'b']})
self.assertEqual("https://domain/api/v2/users/an-id/roles", args[0])
self.assertEqual(kwargs["data"], {"roles": ["a", "b"]})
@mock.patch('auth0.v3.management.users.RestClient')
@mock.patch("auth0.v3.management.users.RestClient")
def test_list_permissions(self, mock_rc):
mock_instance = mock_rc.return_value
u = Users(domain='domain', token='jwttoken')
u.list_permissions('an-id')
u = Users(domain="domain", token="jwttoken")
u.list_permissions("an-id")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/users/an-id/permissions', args[0])
self.assertEqual(kwargs['params'], {
'per_page': 25,
'page': 0,
'include_totals': 'true'
})
self.assertEqual("https://domain/api/v2/users/an-id/permissions", args[0])
self.assertEqual(
kwargs["params"], {"per_page": 25, "page": 0, "include_totals": "true"}
)
u.list_permissions(id='an-id', page=1, per_page=50, include_totals=False)
u.list_permissions(id="an-id", page=1, per_page=50, include_totals=False)
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/users/an-id/permissions', args[0])
self.assertEqual(kwargs['params'], {
'per_page': 50,
'page': 1,
'include_totals': 'false'
})
self.assertEqual("https://domain/api/v2/users/an-id/permissions", args[0])
self.assertEqual(
kwargs["params"], {"per_page": 50, "page": 1, "include_totals": "false"}
)
@mock.patch('auth0.v3.management.users.RestClient')
@mock.patch("auth0.v3.management.users.RestClient")
def test_remove_permissions(self, mock_rc):
mock_instance = mock_rc.return_value
u = Users(domain='domain', token='jwttoken')
u.remove_permissions('an-id', ['a', 'b'])
u = Users(domain="domain", token="jwttoken")
u.remove_permissions("an-id", ["a", "b"])
args, kwargs = mock_instance.delete.call_args
self.assertEqual('https://domain/api/v2/users/an-id/permissions',
args[0])
self.assertEqual(kwargs['data'], {'permissions': ['a', 'b']})
self.assertEqual("https://domain/api/v2/users/an-id/permissions", args[0])
self.assertEqual(kwargs["data"], {"permissions": ["a", "b"]})
@mock.patch('auth0.v3.management.users.RestClient')
@mock.patch("auth0.v3.management.users.RestClient")
def test_add_permissions(self, mock_rc):
mock_instance = mock_rc.return_value
u = Users(domain='domain', token='jwttoken')
u.add_permissions('an-id', ['a', 'b'])
u = Users(domain="domain", token="jwttoken")
u.add_permissions("an-id", ["a", "b"])
args, kwargs = mock_instance.post.call_args
self.assertEqual('https://domain/api/v2/users/an-id/permissions',
args[0])
self.assertEqual(kwargs['data'], {'permissions': ['a', 'b']})
self.assertEqual("https://domain/api/v2/users/an-id/permissions", args[0])
self.assertEqual(kwargs["data"], {"permissions": ["a", "b"]})
@mock.patch('auth0.v3.management.users.RestClient')
@mock.patch("auth0.v3.management.users.RestClient")
def test_delete_multifactor(self, mock_rc):
mock_instance = mock_rc.return_value
u = Users(domain='domain', token='jwttoken')
u.delete_multifactor('an-id', 'provider')
u = Users(domain="domain", token="jwttoken")
u.delete_multifactor("an-id", "provider")
mock_instance.delete.assert_called_with(
'https://domain/api/v2/users/an-id/multifactor/provider'
"https://domain/api/v2/users/an-id/multifactor/provider"
)
@mock.patch('auth0.v3.management.users.RestClient')
@mock.patch("auth0.v3.management.users.RestClient")
def test_delete_authenticators(self, mock_rc):
mock_instance = mock_rc.return_value
u = Users(domain='domain', token='jwttoken')
u.delete_authenticators('an-id')
u = Users(domain="domain", token="jwttoken")
u.delete_authenticators("an-id")
mock_instance.delete.assert_called_with(
'https://domain/api/v2/users/an-id/authenticators'
"https://domain/api/v2/users/an-id/authenticators"
)
@mock.patch('auth0.v3.management.users.RestClient')
@mock.patch("auth0.v3.management.users.RestClient")
def test_unlink_user_account(self, mock_rc):
mock_instance = mock_rc.return_value
u = Users(domain='domain', token='jwttoken')
u.unlink_user_account('an-id', 'provider', 'user-id')
u = Users(domain="domain", token="jwttoken")
u.unlink_user_account("an-id", "provider", "user-id")
mock_instance.delete.assert_called_with(
'https://domain/api/v2/users/an-id/identities/provider/user-id'
"https://domain/api/v2/users/an-id/identities/provider/user-id"
)
@mock.patch('auth0.v3.management.users.RestClient')
@mock.patch("auth0.v3.management.users.RestClient")
def test_link_user_account(self, mock_rc):
mock_instance = mock_rc.return_value
u = Users(domain='domain', token='jwttoken')
u.link_user_account('user-id', {'a': 'b', 'c': 'd'})
u = Users(domain="domain", token="jwttoken")
u.link_user_account("user-id", {"a": "b", "c": "d"})
args, kwargs = mock_instance.post.call_args
self.assertEqual('https://domain/api/v2/users/user-id/identities',
args[0])
self.assertEqual(kwargs['data'], {'a': 'b', 'c': 'd'})
self.assertEqual("https://domain/api/v2/users/user-id/identities", args[0])
self.assertEqual(kwargs["data"], {"a": "b", "c": "d"})
@mock.patch('auth0.v3.management.users.RestClient')
@mock.patch("auth0.v3.management.users.RestClient")
def test_regenerate_recovery_code(self, mock_rc):
mock_instance = mock_rc.return_value
u = Users(domain='domain', token='jwttoken')
u.regenerate_recovery_code('user-id')
u = Users(domain="domain", token="jwttoken")
u.regenerate_recovery_code("user-id")
mock_instance.post.assert_called_with(
'https://domain/api/v2/users/user-id/recovery-code-regeneration'
"https://domain/api/v2/users/user-id/recovery-code-regeneration"
)
@mock.patch('auth0.v3.management.users.RestClient')
@mock.patch("auth0.v3.management.users.RestClient")
def test_get_guardian_enrollments(self, mock_rc):
mock_instance = mock_rc.return_value
u = Users(domain='domain', token='jwttoken')
u.get_guardian_enrollments('user-id')
u = Users(domain="domain", token="jwttoken")
u.get_guardian_enrollments("user-id")
mock_instance.get.assert_called_with(
'https://domain/api/v2/users/user-id/enrollments'
"https://domain/api/v2/users/user-id/enrollments"
)
@mock.patch('auth0.v3.management.users.RestClient')
@mock.patch("auth0.v3.management.users.RestClient")
def test_get_log_events(self, mock_rc):
mock_instance = mock_rc.return_value
u = Users(domain='domain', token='jwttoken')
u.get_log_events('used_id')
u = Users(domain="domain", token="jwttoken")
u.get_log_events("used_id")
args, kwargs = mock_instance.get.call_args
self.assertEqual('https://domain/api/v2/users/used_id/logs', args[0])
self.assertEqual(kwargs['params']['page'], 0)
self.assertEqual(kwargs['params']['per_page'], 50)
self.assertIsNone(kwargs['params']['sort'])
self.assertEqual(kwargs['params']['include_totals'], 'false')
self.assertEqual("https://domain/api/v2/users/used_id/logs", args[0])
self.assertEqual(kwargs["params"]["page"], 0)
self.assertEqual(kwargs["params"]["per_page"], 50)
self.assertIsNone(kwargs["params"]["sort"])
self.assertEqual(kwargs["params"]["include_totals"], "false")
@mock.patch('auth0.v3.management.users.RestClient')
@mock.patch("auth0.v3.management.users.RestClient")
def test_invalidate_remembered_browsers(self, mock_rc):
mock_instance = mock_rc.return_value
u = Users(domain='domain', token='jwttoken')
u.invalidate_remembered_browsers('user-id')
u = Users(domain="domain", token="jwttoken")
u.invalidate_remembered_browsers("user-id")
args, kwargs = mock_instance.post.call_args
self.assertEqual('https://domain/api/v2/users/user-id/multifactor/actions/invalidate-remember-browser', args[0])
self.assertEqual(
"https://domain/api/v2/users/user-id/multifactor/actions/invalidate-remember-browser",
args[0],
)
Metadata-Version: 2.1
Name: auth0-python
Version: 3.22.0
Version: 3.23.0
Summary: Auth0 Python SDK

@@ -345,3 +345,51 @@ Home-page: https://github.com/auth0/auth0-python

=========================
Asynchronous Environments
=========================
This SDK provides async methods built on top of `asyncio <https://docs.python.org/3/library/asyncio.html>`__. To make them available you must have Python >=3.6 and the `aiohttp <https://docs.aiohttp.org/en/stable/>`__ module installed.
Then additional methods with the ``_async`` suffix will be added to modules created by the ``management.Auth0`` class or to classes that are passed to the ``asyncify`` method. For example:
.. code-block:: python
import asyncio
import aiohttp
from auth0.v3.asyncify import asyncify
from auth0.v3.management import Auth0, Users, Connections
from auth0.v3.authentication import Users as AuthUsers
auth0 = Auth0('domain', 'mgmt_api_token')
async def main():
# users = auth0.users.all() <= sync
users = await auth0.users.all_async() # <= async
# To share a session amongst multiple calls to the same service
async with auth0.users as users:
data = await users.get_async(id)
users.update_async(id, data)
# Use asyncify directly on services
Users = asyncify(Users)
Connections = asyncify(Connections)
users = Users(domain, mgmt_api_token)
connections = Connections(domain, mgmt_api_token)
# Create a session and share it among the services
session = aiohttp.ClientSession()
users.set_session(session)
connections.set_session(session)
u = await auth0.users.all_async()
c = await auth0.connections.all_async()
session.close()
# Use auth api
U = asyncify(AuthUsers)
u = U(domain=domain)
await u.userinfo_async(access_token)
asyncio.run(main())
==============

@@ -348,0 +396,0 @@ Supported APIs

@@ -319,3 +319,51 @@ |pypi| |build| |coverage| |license|

=========================
Asynchronous Environments
=========================
This SDK provides async methods built on top of `asyncio <https://docs.python.org/3/library/asyncio.html>`__. To make them available you must have Python >=3.6 and the `aiohttp <https://docs.aiohttp.org/en/stable/>`__ module installed.
Then additional methods with the ``_async`` suffix will be added to modules created by the ``management.Auth0`` class or to classes that are passed to the ``asyncify`` method. For example:
.. code-block:: python
import asyncio
import aiohttp
from auth0.v3.asyncify import asyncify
from auth0.v3.management import Auth0, Users, Connections
from auth0.v3.authentication import Users as AuthUsers
auth0 = Auth0('domain', 'mgmt_api_token')
async def main():
# users = auth0.users.all() <= sync
users = await auth0.users.all_async() # <= async
# To share a session amongst multiple calls to the same service
async with auth0.users as users:
data = await users.get_async(id)
users.update_async(id, data)
# Use asyncify directly on services
Users = asyncify(Users)
Connections = asyncify(Connections)
users = Users(domain, mgmt_api_token)
connections = Connections(domain, mgmt_api_token)
# Create a session and share it among the services
session = aiohttp.ClientSession()
users.set_session(session)
connections.set_session(session)
u = await auth0.users.all_async()
c = await auth0.connections.all_async()
session.close()
# Use auth api
U = asyncify(AuthUsers)
u = U(domain=domain)
await u.userinfo_async(access_token)
asyncio.run(main())
==============

@@ -322,0 +370,0 @@ Supported APIs

+26
-25
import io
import os
import re
from setuptools import setup, find_packages
from setuptools import find_packages, setup
def find_version():
file_dir = os.path.dirname(__file__)
with io.open(os.path.join(file_dir, 'auth0', '__init__.py')) as f:
with io.open(os.path.join(file_dir, "auth0", "__init__.py")) as f:
version = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', f.read())

@@ -17,3 +18,3 @@ if version:

with io.open('README.rst', encoding='utf-8') as f:
with io.open("README.rst", encoding="utf-8") as f:
long_description = f.read()

@@ -23,29 +24,29 @@

setup(
name='auth0-python',
name="auth0-python",
version=find_version(),
description='Auth0 Python SDK',
description="Auth0 Python SDK",
long_description=long_description,
author='Auth0',
author_email='support@auth0.com',
license='MIT',
author="Auth0",
author_email="support@auth0.com",
license="MIT",
packages=find_packages(),
install_requires=['requests>=2.14.0', 'pyjwt[crypto]>=1.7.1'],
extras_require={'test': ['mock>=1.3.0', 'pre-commit']},
python_requires='>=2.7, !=3.0.*, !=3.1.*',
install_requires=["requests>=2.14.0", "pyjwt[crypto]>=1.7.1"],
extras_require={"test": ["coverage", "mock>=1.3.0", "pre-commit"]},
python_requires=">=2.7, !=3.0.*, !=3.1.*",
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
],
url='https://github.com/auth0/auth0-python',
url="https://github.com/auth0/auth0-python",
)
import base64
import json
import platform
import sys
import requests
from ..exceptions import Auth0Error, RateLimitError
from time import sleep
from random import randint
UNKNOWN_ERROR = 'a0.sdk.internal.unknown'
class RestClientOptions(object):
"""Configuration object for RestClient. Used for configuring
additional RestClient options, such as rate-limit
retries.
Args:
telemetry (bool, optional): Enable or disable Telemetry
(defaults to True)
timeout (float or tuple, optional): Change the requests
connect and read timeout. Pass a tuple to specify
both values separately or a float to set both to it.
(defaults to 5.0 for both)
retries (integer): In the event an API request returns a
429 response header (indicating rate-limit has been
hit), the RestClient will retry the request this many
times using an exponential backoff strategy, before
raising a RateLimitError exception. 10 retries max.
(defaults to 3)
"""
def __init__(self, telemetry=None, timeout=None, retries=None):
self.telemetry = True
self.timeout = 5.0
self.retries = 3
if telemetry is not None:
self.telemetry = telemetry
if timeout is not None:
self.timeout = timeout
if retries is not None:
self.retries = retries
class RestClient(object):
"""Provides simple methods for handling all RESTful api endpoints.
Args:
telemetry (bool, optional): Enable or disable Telemetry
(defaults to True)
timeout (float or tuple, optional): Change the requests
connect and read timeout. Pass a tuple to specify
both values separately or a float to set both to it.
(defaults to 5.0 for both)
options (RestClientOptions): Pass an instance of
RestClientOptions to configure additional RestClient
options, such as rate-limit retries. Overrides matching
options passed to the constructor.
(defaults to 3)
"""
def __init__(self, jwt, telemetry=True, timeout=5.0, options=None):
if options is None:
options = RestClientOptions(telemetry=telemetry, timeout=timeout)
self.options = options
self.jwt = jwt
self._metrics = {'retries': 0, 'backoff': []}
self._skip_sleep = False
self.base_headers = {
'Authorization': 'Bearer {}'.format(self.jwt),
'Content-Type': 'application/json',
}
if options.telemetry:
py_version = platform.python_version()
version = sys.modules['auth0'].__version__
auth0_client = json.dumps({
'name': 'auth0-python',
'version': version,
'env': {
'python': py_version,
}
}).encode('utf-8')
self.base_headers.update({
'User-Agent': 'Python/{}'.format(py_version),
'Auth0-Client': base64.b64encode(auth0_client),
})
# For backwards compatibility reasons only
# TODO: Deprecate in the next major so we can prune these arguments. Guidance should be to use RestClient.options.*
self.telemetry = options.telemetry
self.timeout = options.timeout
# Returns a hard cap for the maximum number of retries allowed (10)
def MAX_REQUEST_RETRIES(self):
return 10
# Returns the maximum amount of jitter to introduce in milliseconds (100ms)
def MAX_REQUEST_RETRY_JITTER(self):
return 100
# Returns the maximum delay window allowed (1000ms)
def MAX_REQUEST_RETRY_DELAY(self):
return 1000
# Returns the minimum delay window allowed (100ms)
def MIN_REQUEST_RETRY_DELAY(self):
return 100
def get(self, url, params=None):
headers = self.base_headers.copy()
# Track the API request attempt number
attempt = 0
# Reset the metrics tracker
self._metrics = {'retries': 0, 'backoff': []}
# Cap the maximum number of retries to 10 or fewer. Floor the retries at 0.
retries = min(self.MAX_REQUEST_RETRIES(), max(0, self.options.retries))
while True:
# Increment attempt number
attempt += 1
# Issue the request
response = requests.get(url, params=params, headers=headers, timeout=self.options.timeout);
# If the response did not have a 429 header, or the retries were configured at 0, or the attempt number is equal to or greater than the configured retries, break
if response.status_code != 429 or retries <= 0 or attempt > retries:
break
# Retry the request. Apply a exponential backoff for subsequent attempts, using this formula:
# max(MIN_REQUEST_RETRY_DELAY, min(MAX_REQUEST_RETRY_DELAY, (100ms * (2 ** attempt - 1)) + random_between(1, MAX_REQUEST_RETRY_JITTER)))
# Increases base delay by (100ms * (2 ** attempt - 1))
wait = 100 * 2 ** (attempt - 1)
# Introduces jitter to the base delay; increases delay between 1ms to MAX_REQUEST_RETRY_JITTER (100ms)
wait += randint(1, self.MAX_REQUEST_RETRY_JITTER())
# Is never more than MAX_REQUEST_RETRY_DELAY (1s)
wait = min(self.MAX_REQUEST_RETRY_DELAY(), wait)
# Is never less than MIN_REQUEST_RETRY_DELAY (100ms)
wait = max(self.MIN_REQUEST_RETRY_DELAY(), wait)
self._metrics['retries'] = attempt
self._metrics['backoff'].append(wait)
# Skip calling sleep() when running unit tests
if self._skip_sleep is False:
# sleep() functions in seconds, so convert the milliseconds formula above accordingly
sleep(wait / 1000)
# Return the final Response
return self._process_response(response)
def post(self, url, data=None):
headers = self.base_headers.copy()
response = requests.post(url, json=data, headers=headers, timeout=self.options.timeout)
return self._process_response(response)
def file_post(self, url, data=None, files=None):
headers = self.base_headers.copy()
headers.pop('Content-Type', None)
response = requests.post(url, data=data, files=files, headers=headers, timeout=self.options.timeout)
return self._process_response(response)
def patch(self, url, data=None):
headers = self.base_headers.copy()
response = requests.patch(url, json=data, headers=headers, timeout=self.options.timeout)
return self._process_response(response)
def put(self, url, data=None):
headers = self.base_headers.copy()
response = requests.put(url, json=data, headers=headers, timeout=self.options.timeout)
return self._process_response(response)
def delete(self, url, params=None, data=None):
headers = self.base_headers.copy()
response = requests.delete(url, headers=headers, params=params or {}, json=data, timeout=self.options.timeout)
return self._process_response(response)
def _process_response(self, response):
return self._parse(response).content()
def _parse(self, response):
if not response.text:
return EmptyResponse(response.status_code)
try:
return JsonResponse(response)
except ValueError:
return PlainResponse(response)
class Response(object):
def __init__(self, status_code, content, headers):
self._status_code = status_code
self._content = content
self._headers = headers
def content(self):
if self._is_error():
if self._status_code == 429:
reset_at = int(self._headers.get('x-ratelimit-reset', '-1'))
raise RateLimitError(error_code=self._error_code(),
message=self._error_message(),
reset_at=reset_at)
raise Auth0Error(status_code=self._status_code,
error_code=self._error_code(),
message=self._error_message())
else:
return self._content
def _is_error(self):
return self._status_code is None or self._status_code >= 400
# Adding these methods to force implementation in subclasses because they are references in this parent class
def _error_code(self):
raise NotImplementedError
def _error_message(self):
raise NotImplementedError
class JsonResponse(Response):
def __init__(self, response):
content = json.loads(response.text)
super(JsonResponse, self).__init__(response.status_code, content, response.headers)
def _error_code(self):
if 'errorCode' in self._content:
return self._content.get('errorCode')
elif 'error' in self._content:
return self._content.get('error')
else:
return UNKNOWN_ERROR
def _error_message(self):
message = self._content.get('message', '')
if message is not None and message != '':
return message
return self._content.get('error', '')
class PlainResponse(Response):
def __init__(self, response):
super(PlainResponse, self).__init__(response.status_code, response.text, response.headers)
def _error_code(self):
return UNKNOWN_ERROR
def _error_message(self):
return self._content
class EmptyResponse(Response):
def __init__(self, status_code):
super(EmptyResponse, self).__init__(status_code, '', {})
def _error_code(self):
return UNKNOWN_ERROR
def _error_message(self):
return ''