"""Test Oauth Client.""" import urllib.parse from unittest.mock import Mock import pytest import requests from product_review.lib.vapi.oauth_client import OauthClient from product_review.lib.vapi.oauth_code_error import OauthCodeError def build_client(): """Build client.""" base_url = "https://notreal.abc.com" client_id = "CLIENTID" client_secret = "SHHHHHHH" redirect_uri = "https://redirect.abc.com" user_id = 123 user_type = "oa" return OauthClient( client_id, client_secret, base_url, redirect_uri, user_id, user_type ) def parse_auth_url(): """Parse auth url.""" oauth_client = build_client() return urllib.parse.urlparse(oauth_client.auth_url()) def query_part(key): """Query part.""" url_parse_result = parse_auth_url() query_parse_result = urllib.parse.parse_qs(url_parse_result.query) if key not in query_parse_result: return None return query_parse_result[key][0] def test_auth_url_hostname(): """Test auth_url_hostname.""" url_parse_result = parse_auth_url() assert url_parse_result.hostname == "notreal.abc.com" def test_auth_url_user_type(): """Test auth_url_user_type.""" assert query_part("user_type") == "oa" def test_auth_url_user_id(): """Test auth_url_user_id.""" assert query_part("user_id") == "123" def test_auth_url_response_type(): """Test auth_url_response_type.""" assert query_part("response_type") == "code" def test_auth_url_client_id(): """Test auth_url_client_id.""" assert query_part("client_id") == "CLIENTID" def test_auth_url_redirect(): """Test auth_url_redirect.""" assert query_part("isRedirect") == "0" def test_fetch_code_success(): """Test fetch_code_success.""" def mock_json_method(): return {"query": {"code": "code-of-destiny"}} mock_response = Mock(json=mock_json_method, status_code=200) requests.get = Mock(return_value=mock_response) oauth_client = build_client() assert oauth_client.fetch_code() == "code-of-destiny" def test_fetch_code_error(): """Test fetch_code_error.""" with pytest.raises(OauthCodeError): def mock_json_method(): return {"error": "Bad Request"} mock_response = Mock(json=mock_json_method, status_code=400) requests.get = Mock(return_value=mock_response) oauth_client = build_client() oauth_client.fetch_code() def test_fetch_token_response(): """Test fetch_token_response.""" mock_response = { "access_token": "access-token-of-doom", "refresh_token": "refresh-token-of-wisdom", } oauth_client = build_client() oauth_client.fetch_code = Mock(return_value="code-of-destiny") oauth_client.oauth_session.fetch_token = Mock(return_value=mock_response) assert oauth_client.fetch_token() == mock_response def test_fetch_token_args(): """Test fetch_token_args.""" oauth_client = build_client() oauth_client.fetch_code = Mock(return_value="code-of-destiny") mock_fetch_token = Mock() oauth_client.oauth_session.fetch_token = mock_fetch_token oauth_client.fetch_token() mock_fetch_token.assert_called_with( "https://notreal.abc.com/authorize/getaccesstoken", "code-of-destiny", client_secret="SHHHHHHH", user_type="oa", )