| 1 |
import contextlib |
| 2 |
from io import StringIO |
| 3 |
|
| 4 |
import pytest |
| 5 |
import responses |
| 6 |
|
| 7 |
from censys.cli import main as cli_main |
| 8 |
from censys.cli.commands import subdomains |
| 9 |
from tests.utils import V2_URL, CensysTestCase |
| 10 |
|
| 11 |
TEST_DOMAINS = { |
| 12 |
"help.censys.io", |
| 13 |
"lp.censys.io", |
| 14 |
"about.censys.io", |
| 15 |
"fast.github.com", |
| 16 |
} |
| 17 |
|
| 18 |
CERT_SEARCH_RESPONSE = { |
| 19 |
"result": { |
| 20 |
"total": len(TEST_DOMAINS), |
| 21 |
"hits": [{"names": [name]} for name in TEST_DOMAINS], |
| 22 |
"links": {}, |
| 23 |
}, |
| 24 |
} |
| 25 |
|
| 26 |
|
| 27 |
class CensysCliSubdomainsTest(CensysTestCase): |
| 28 |
@pytest.mark.parametrize( |
| 29 |
"test_json_bool", |
| 30 |
[True, False], |
| 31 |
) |
| 32 |
def test_print_subdomains( |
| 33 |
self, |
| 34 |
test_json_bool: bool, |
| 35 |
test_subdomains: set[str] = TEST_DOMAINS, |
| 36 |
): |
| 37 |
# Mock |
| 38 |
mock_print_json = self.mocker.patch("censys.cli.utils.console.print_json") |
| 39 |
mock_print = self.mocker.patch("censys.cli.utils.console.print") |
| 40 |
|
| 41 |
# Actual call |
| 42 |
subdomains.print_subdomains(test_subdomains, test_json_bool) |
| 43 |
|
| 44 |
# Assertions |
| 45 |
if test_json_bool: |
| 46 |
mock_print_json.assert_called_once() |
| 47 |
else: |
| 48 |
for subdomain in test_subdomains: |
| 49 |
mock_print.assert_any_call(f" - {subdomain}") # noqa: E221 |
| 50 |
|
| 51 |
def test_search_subdomains(self): |
| 52 |
# Mock |
| 53 |
self.responses.add( |
| 54 |
responses.POST, |
| 55 |
V2_URL + "/certificates/search", |
| 56 |
json=CERT_SEARCH_RESPONSE, |
| 57 |
match=[responses.matchers.json_params_matcher({"per_page": 100, "q": "names: censys.io"})], |
| 58 |
) |
| 59 |
self.mocker.patch( |
| 60 |
"argparse._sys.argv", |
| 61 |
["censys", "subdomains", "censys.io"] + CensysTestCase.cli_args, |
| 62 |
) |
| 63 |
|
| 64 |
# Actual call |
| 65 |
temp_stdout = StringIO() |
| 66 |
with contextlib.redirect_stdout(temp_stdout): |
| 67 |
cli_main() |
| 68 |
|
| 69 |
# Assertions |
| 70 |
mock_cli_response = temp_stdout.getvalue().strip() |
| 71 |
for line in mock_cli_response.split("\n"): |
| 72 |
assert "censys.io" in line |