Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
laramies
GitHub Repository: laramies/theHarvester
Path: blob/master/tests/lib/test_core.py
607 views
1
from __future__ import annotations
2
3
from pathlib import Path
4
from typing import Any
5
from unittest import mock
6
7
import pytest
8
import yaml
9
10
from theHarvester.lib.core import CONFIG_DIRS, DATA_DIR, Core
11
12
13
@pytest.fixture(autouse=True)
14
def mock_environ(monkeypatch, tmp_path: Path):
15
monkeypatch.setenv("HOME", str(tmp_path))
16
17
18
def mock_read_text(mocked: dict[Path, str | Exception]):
19
read_text = Path.read_text
20
21
def _read_text(self: Path, *args, **kwargs):
22
if result := mocked.get(self):
23
if isinstance(result, Exception):
24
raise result
25
return result
26
return read_text(self, *args, **kwargs)
27
28
return _read_text
29
30
31
@pytest.mark.parametrize(
32
("name", "contents", "expected"),
33
[
34
("api-keys", "apikeys: {}", {}),
35
("proxies", "http: [localhost:8080]", ["http://localhost:8080"]),
36
],
37
)
38
@pytest.mark.parametrize("dir", CONFIG_DIRS)
39
def test_read_config_searches_config_dirs(
40
name: str, contents: str, expected: Any, dir: Path, capsys
41
):
42
file = dir.expanduser() / f"{name}.yaml"
43
config_files = [d.expanduser() / file.name for d in CONFIG_DIRS]
44
side_effect = mock_read_text(
45
{f: contents if f == file else FileNotFoundError() for f in config_files}
46
)
47
48
with mock.patch("pathlib.Path.read_text", autospec=True, side_effect=side_effect):
49
got = Core.api_keys() if name == "api-keys" else Core.proxy_list()
50
51
assert got == expected
52
assert f"Read {file.name} from {file}" in capsys.readouterr().out
53
54
55
@pytest.mark.parametrize("name", ("api-keys", "proxies"))
56
def test_read_config_copies_default_to_home(name: str, capsys):
57
file = Path(f"~/.theHarvester/{name}.yaml").expanduser()
58
config_files = [d.expanduser() / file.name for d in CONFIG_DIRS]
59
side_effect = mock_read_text({f: FileNotFoundError() for f in config_files})
60
61
with mock.patch("pathlib.Path.read_text", autospec=True, side_effect=side_effect):
62
got = Core.api_keys() if name == "api-keys" else Core.proxy_list()
63
64
default = yaml.safe_load((DATA_DIR / file.name).read_text())
65
expected = (
66
default["apikeys"]
67
if name == "api-keys"
68
else [f"http://{h}" for h in default["http"]]
69
)
70
assert got == expected
71
assert f"Created default {file.name} at {file}" in capsys.readouterr().out
72
assert file.exists()
73
74