Skip to content

Commit

Permalink
Remove all explicit event loop usage. Use pytest.mark.asyncio decorator
Browse files Browse the repository at this point in the history
  • Loading branch information
serhiibuniak-okta committed Feb 14, 2022
1 parent 5d4ffa5 commit 2b55c30
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 41 deletions.
36 changes: 21 additions & 15 deletions tests/unit/test_client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import aiohttp
import asyncio
import aiohttp
import logging
from aiohttp.client_reqrep import ConnectionKey
Expand Down Expand Up @@ -634,16 +633,18 @@ def test_constructor_client_logging():
assert logger.level == logging.DEBUG


def test_client_raise_exception():
@pytest.mark.asyncio
async def test_client_raise_exception():
org_url = "https://test.okta.com"
token = "TOKEN"
config = {'orgUrl': org_url, 'token': token, 'raiseException': True}
client = OktaClient(config)
with pytest.raises(HTTPException):
asyncio.run(client.list_users())
_ = await client.list_users()


def test_client_custom_headers(monkeypatch, mocker):
@pytest.mark.asyncio
async def test_client_custom_headers(monkeypatch, mocker):
org_url = "https://test.okta.com"
token = "TOKEN"
config = {'orgUrl': org_url, 'token': token}
Expand Down Expand Up @@ -679,7 +680,7 @@ async def mock_response_text():

mock_http_request = MockHTTPRequest()
monkeypatch.setattr(aiohttp.ClientSession, 'request', mock_http_request)
asyncio.run(client.list_users())
_ = await client.list_users()
assert 'Header-Test-1' in mock_http_request.headers
assert 'Header-Test-2' in mock_http_request.headers

Expand All @@ -688,7 +689,8 @@ async def mock_response_text():
assert client.get_custom_headers() == {}


def test_client_handle_aiohttp_error(monkeypatch, mocker):
@pytest.mark.asyncio
async def test_client_handle_aiohttp_error(monkeypatch, mocker):
org_url = "https://test.okta.com"
token = "TOKEN"
config = {'orgUrl': org_url, 'token': token}
Expand Down Expand Up @@ -720,13 +722,14 @@ async def mock_response_text():

mock_http_request = MockHTTPRequest()
monkeypatch.setattr(aiohttp.ClientSession, 'request', mock_http_request)
res, resp_body, error = asyncio.run(client.list_users())
res, resp_body, error = await client.list_users()
assert res is None
assert resp_body is None
assert isinstance(error, aiohttp.ClientError)


def test_client_log_debug(monkeypatch, caplog):
@pytest.mark.asyncio
async def test_client_log_debug(monkeypatch, caplog):
org_url = "https://test.okta.com"
token = "TOKEN"
config = {'orgUrl': org_url, 'token': token,
Expand Down Expand Up @@ -768,14 +771,15 @@ async def mock_response_text():
mock_http_request = MockHTTPRequest()
monkeypatch.setattr(aiohttp.ClientSession, 'request', mock_http_request)
with caplog.at_level(logging.DEBUG):
res, resp_body, error = asyncio.run(client.list_users())
res, resp_body, error = await client.list_users()
assert 'okta-sdk-python' in caplog.text
assert 'DEBUG' in caplog.text
assert "'method': 'GET'" in caplog.text
assert "'url': 'https://test.okta.com/api/v1/users'" in caplog.text


def test_client_log_info(monkeypatch, caplog):
@pytest.mark.asyncio
async def test_client_log_info(monkeypatch, caplog):
org_url = "https://test.okta.com"
token = "TOKEN"
config = {'orgUrl': org_url, 'token': token,
Expand Down Expand Up @@ -817,11 +821,12 @@ async def mock_response_text():
mock_http_request = MockHTTPRequest()
monkeypatch.setattr(aiohttp.ClientSession, 'request', mock_http_request)
with caplog.at_level(logging.INFO):
res, resp_body, error = asyncio.run(client.list_users())
res, resp_body, error = await client.list_users()
assert caplog.text == ''


def test_client_log_exception(monkeypatch, caplog):
@pytest.mark.asyncio
async def test_client_log_exception(monkeypatch, caplog):
org_url = "https://test.okta.com"
token = "TOKEN"
config = {'orgUrl': org_url, 'token': token,
Expand Down Expand Up @@ -855,11 +860,12 @@ async def mock_response_text():
mock_http_request = MockHTTPRequest()
monkeypatch.setattr(aiohttp.ClientSession, 'request', mock_http_request)
with caplog.at_level(logging.DEBUG):
res, resp_body, error = asyncio.run(client.list_users())
res, resp_body, error = await client.list_users()
assert 'Cannot connect to host https://test.okta.com' in caplog.text


def test_client_ssl_context(monkeypatch, mocker):
@pytest.mark.asyncio
async def test_client_ssl_context(monkeypatch, mocker):
org_url = "https://test.okta.com"
token = "TOKEN"
mock_ssl_context = mocker.MagicMock()
Expand Down Expand Up @@ -890,7 +896,7 @@ async def mock_response_text():

mock_http_request = MockHTTPRequest()
monkeypatch.setattr(aiohttp.ClientSession, 'request', mock_http_request)
asyncio.run(client.list_users())
_ = await client.list_users()

assert mock_http_request.request_info['ssl_context'] == mock_ssl_context

Expand Down
16 changes: 9 additions & 7 deletions tests/unit/test_domains.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import aiohttp
import asyncio
import pytest
from okta.client import Client as OktaClient
from okta.models import DnsRecord, DomainCertificate, DomainCertificateMetadata, Domain

Expand Down Expand Up @@ -149,7 +149,8 @@ class TestDomainResource:
Unit Tests for the Domain Resource
"""

def test_get_domain(self, monkeypatch):
@pytest.mark.asyncio
async def test_get_domain(self, monkeypatch):
org_url = "https://test.okta.com"
token = "TOKEN"
config = {'orgUrl': org_url, 'token': token}
Expand Down Expand Up @@ -183,7 +184,7 @@ async def mock_response_text():
mock_http_request = MockHTTPRequest()
monkeypatch.setattr(aiohttp.ClientSession, 'request', mock_http_request)

domain_resp, _, err = asyncio.run(client.get_domain('OcDz6iRyjkaCTXkdo0g3'))
domain_resp, _, err = await client.get_domain('OcDz6iRyjkaCTXkdo0g3')
assert err is None
assert isinstance(domain_resp, Domain)
assert isinstance(domain_resp.public_certificate, DomainCertificateMetadata)
Expand All @@ -192,7 +193,8 @@ async def mock_response_text():
assert isinstance(dns_record, DnsRecord)
assert domain_resp.domain == 'login.example.com'

def test_create_certificate_and_verify_domain(self, monkeypatch):
@pytest.mark.asyncio
async def test_create_certificate_and_verify_domain(self, monkeypatch):
org_url = "https://test.okta.com"
token = "TOKEN"
config = {'orgUrl': org_url, 'token': token}
Expand Down Expand Up @@ -240,15 +242,15 @@ async def mock_response_text():
"domain": "login.example.com",
"certificateSourceType": "MANUAL"
}
domain_resp, _, err = asyncio.run(client.create_domain(domain_config))
domain_resp, _, err = await client.create_domain(domain_config)
assert err is None

cert = DomainCertificate({'type': 'PEM',
'certificate': 'test_certificate',
'privateKey': 'test_private_key'})
cert_resp, err = asyncio.run(client.create_certificate(domain_resp.id, cert))
cert_resp, err = await client.create_certificate(domain_resp.id, cert)
assert err is None

domain_resp, _, err = asyncio.run(client.verify_domain(domain_resp.id))
domain_resp, _, err = await client.verify_domain(domain_resp.id)
assert err is None
assert domain_resp.validation_status == 'VERIFIED'
7 changes: 4 additions & 3 deletions tests/unit/test_request_executor.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import aiohttp
import asyncio
import datetime
import pytest
import time

from http import HTTPStatus
Expand All @@ -9,7 +9,8 @@
from okta.request_executor import RequestExecutor


def test_retry_count_header(monkeypatch):
@pytest.mark.asyncio
async def test_retry_count_header(monkeypatch):
org_url = "https://test.okta.com"
token = "TOKEN"
config = {'orgUrl': org_url, 'token': token, 'rateLimit': {'maxRetries': 2}}
Expand Down Expand Up @@ -64,7 +65,7 @@ async def mock_response_text():

mock_http_request = MockHTTPRequest()
monkeypatch.setattr(aiohttp.ClientSession, 'request', mock_http_request)
res, resp_body, error = asyncio.run(client.list_users())
res, resp_body, error = await client.list_users()
# Check request was retried max times and header 'X-Okta-Retry-Count' was set properly
assert mock_http_request.request_info['headers'].get('X-Okta-Retry-Count') == '2'

Expand Down
29 changes: 13 additions & 16 deletions tests/unit/test_sign_on_modes.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import asyncio
import copy
import pytest

from okta.client import Client
from okta.models import Application, SamlApplication, ApplicationSignOnMode
Expand Down Expand Up @@ -184,7 +184,8 @@ def set_response(self, response):
self.response = MockResponseObj(response)


def test_known_sign_on_mode():
@pytest.mark.asyncio
async def test_known_sign_on_mode():
response = copy.deepcopy(SAML_APP_RESP_DICT)

config = {
Expand All @@ -196,20 +197,19 @@ def test_known_sign_on_mode():

# check list applications
client._request_executor.set_response([response])
event_loop = asyncio.get_event_loop()
result, resp, err = event_loop.run_until_complete(client.list_applications())
result, resp, err = await client.list_applications()
assert type(result[0]) == SamlApplication
assert result[0].as_dict() == EXPECTED_SAML_APP_AS_DICT

# check get application
client._request_executor.set_response(response)
event_loop = asyncio.get_event_loop()
result, resp, err = event_loop.run_until_complete(client.get_application("test_id"))
result, resp, err = await client.get_application("test_id")
assert type(result) == SamlApplication
assert result.as_dict() == EXPECTED_SAML_APP_AS_DICT


def test_unknown_sign_on_mode():
@pytest.mark.asyncio
async def test_unknown_sign_on_mode():
response = copy.deepcopy(SAML_APP_RESP_DICT)
response["signOnMode"] = "UNKNOWN_SIGN_ON_MODE"
expected = copy.deepcopy(EXPECTED_SAML_APP_AS_DICT)
Expand All @@ -230,24 +230,23 @@ def test_unknown_sign_on_mode():

# check list applications
client._request_executor.set_response([response])
event_loop = asyncio.get_event_loop()
result, resp, err = event_loop.run_until_complete(client.list_applications())
result, resp, err = await client.list_applications()
# verify if result fallbacks to generic Application
assert type(result[0]) != SamlApplication
assert type(result[0]) == Application
assert result[0].as_dict() == expected

# check get application
client._request_executor.set_response(response)
event_loop = asyncio.get_event_loop()
result, resp, err = event_loop.run_until_complete(client.get_application("test_id"))
result, resp, err = await client.get_application("test_id")
# verify if result fallbacks to generic Application
assert type(result) != SamlApplication
assert type(result) == Application
assert result.as_dict() == expected


def test_no_sign_on_mode():
@pytest.mark.asyncio
async def test_no_sign_on_mode():
response = copy.deepcopy(SAML_APP_RESP_DICT)
response["signOnMode"] = None
expected = copy.deepcopy(EXPECTED_SAML_APP_AS_DICT)
Expand All @@ -268,16 +267,14 @@ def test_no_sign_on_mode():

# check list applications
client._request_executor.set_response([response])
event_loop = asyncio.get_event_loop()
result, resp, err = event_loop.run_until_complete(client.list_applications())
result, resp, err = await client.list_applications()
assert type(result[0]) != SamlApplication
assert type(result[0]) == Application
assert result[0].as_dict() == expected

# check get application
client._request_executor.set_response(response)
event_loop = asyncio.get_event_loop()
result, resp, err = event_loop.run_until_complete(client.get_application("test_id"))
result, resp, err = await client.get_application("test_id")
assert type(result) != SamlApplication
assert type(result) == Application
assert result.as_dict() == expected

0 comments on commit 2b55c30

Please sign in to comment.