| 1 |
import unittest |
| 2 |
from unittest.mock import mock_open, patch |
| 3 |
|
| 4 |
import pytest |
| 5 |
import responses |
| 6 |
from requests.models import Response |
| 7 |
|
| 8 |
from censys.common.exceptions import ( |
| 9 |
CensysException, |
| 10 |
CensysExceptionMapper, |
| 11 |
CensysSearchException, |
| 12 |
) |
| 13 |
from censys.search.v1.api import CensysSearchAPIv1 |
| 14 |
from tests.utils import V1_URL, CensysTestCase |
| 15 |
|
| 16 |
ACCOUNT_JSON = { |
| 17 |
"login": "[email protected]", |
| 18 |
"first_login": "2021-01-01 01:00:00", |
| 19 |
"last_login": "2021-01-01 01:00:00.000000", |
| 20 |
"email": "[email protected]", |
| 21 |
"quota": {"used": 1, "resets_at": "2021-01-01 01:00:00", "allowance": 100}, |
| 22 |
} |
| 23 |
|
| 24 |
SearchExceptionParams = [(code, exception) for code, exception in CensysExceptionMapper.SEARCH_EXCEPTIONS.items()] |
| 25 |
|
| 26 |
|
| 27 |
class CensysSearchAPITests(CensysTestCase): |
| 28 |
def setup_method(self): |
| 29 |
self.setUpApi(CensysSearchAPIv1(self.api_id, self.api_secret)) |
| 30 |
|
| 31 |
def test_account(self): |
| 32 |
self.responses.add( |
| 33 |
responses.GET, |
| 34 |
V1_URL + "/account", |
| 35 |
status=200, |
| 36 |
json=ACCOUNT_JSON, |
| 37 |
) |
| 38 |
res = self.api.account() |
| 39 |
|
| 40 |
assert res == ACCOUNT_JSON |
| 41 |
|
| 42 |
def test_quota(self): |
| 43 |
self.responses.add( |
| 44 |
responses.GET, |
| 45 |
V1_URL + "/account", |
| 46 |
status=200, |
| 47 |
json=ACCOUNT_JSON, |
| 48 |
) |
| 49 |
res = self.api.quota() |
| 50 |
|
| 51 |
assert res == ACCOUNT_JSON["quota"] |
| 52 |
|
| 53 |
@pytest.mark.parametrize(("status_code", "exception"), SearchExceptionParams) |
| 54 |
def test_get_exception_class(self, status_code, exception): |
| 55 |
response = Response() |
| 56 |
response.status_code = status_code |
| 57 |
|
| 58 |
assert self.api._get_exception_class(response) == exception |
| 59 |
|
| 60 |
def test_exception_repr(self): |
| 61 |
exception = CensysSearchException(404, "Not Found", const="notfound") |
| 62 |
|
| 63 |
assert repr(exception) == "404 (notfound): Not Found" |
| 64 |
|
| 65 |
|
| 66 |
@patch.dict("os.environ", {"CENSYS_API_ID": "", "CENSYS_API_SECRET": ""}) |
| 67 |
class CensysAPIBaseTestsNoSearchEnv(unittest.TestCase): |
| 68 |
@patch("builtins.open", new_callable=mock_open, read_data="[DEFAULT]") |
| 69 |
def test_no_env(self, mock_file): |
| 70 |
with pytest.raises(CensysException, match="No API ID or API secret configured."): |
| 71 |
CensysSearchAPIv1() |