|
1
|
|
|
import tempfile |
|
2
|
|
|
import filecmp |
|
3
|
|
|
import contextlib |
|
4
|
|
|
import pathlib |
|
5
|
|
|
import sys |
|
6
|
|
|
import subprocess |
|
7
|
|
|
import time |
|
8
|
|
|
|
|
9
|
|
|
import pytest |
|
10
|
|
|
|
|
11
|
|
|
from org_fedora_oscap import data_fetch |
|
12
|
|
|
|
|
13
|
|
|
|
|
14
|
|
|
PORT = 8001 |
|
15
|
|
|
|
|
16
|
|
|
|
|
17
|
|
|
@contextlib.contextmanager |
|
18
|
|
|
def serve_directory_in_separate_process(port): |
|
19
|
|
|
args = [sys.executable, "-m", "http.server", str(port)] |
|
20
|
|
|
proc = subprocess.Popen( |
|
21
|
|
|
args, |
|
22
|
|
|
stdout=subprocess.DEVNULL, |
|
23
|
|
|
stderr=subprocess.DEVNULL) |
|
24
|
|
|
# give the server some time to start |
|
25
|
|
|
time.sleep(0.4) |
|
26
|
|
|
yield |
|
27
|
|
|
proc.terminate() |
|
28
|
|
|
proc.wait() |
|
29
|
|
|
|
|
30
|
|
|
|
|
31
|
|
|
def test_file_retreival(): |
|
32
|
|
|
filename_to_test = pathlib.Path(__file__) |
|
33
|
|
|
relative_filename_to_test = filename_to_test.relative_to(pathlib.Path.cwd()) |
|
34
|
|
|
|
|
35
|
|
|
temp_file = tempfile.NamedTemporaryFile() |
|
36
|
|
|
temp_filename = temp_file.name |
|
37
|
|
|
|
|
38
|
|
|
with serve_directory_in_separate_process(PORT): |
|
39
|
|
|
data_fetch._curl_fetch( |
|
40
|
|
|
"http://localhost:{}/{}".format(PORT, relative_filename_to_test), temp_filename) |
|
41
|
|
|
|
|
42
|
|
|
assert filecmp.cmp(relative_filename_to_test, temp_filename) |
|
43
|
|
|
|
|
44
|
|
|
|
|
45
|
|
|
def test_file_absent(): |
|
46
|
|
|
relative_filename_to_test = "i_am_not_here.file" |
|
47
|
|
|
|
|
48
|
|
|
with serve_directory_in_separate_process(PORT): |
|
49
|
|
|
with pytest.raises(data_fetch.FetchError) as exc: |
|
50
|
|
|
data_fetch._curl_fetch( |
|
51
|
|
|
"http://localhost:{}/{}".format(PORT, relative_filename_to_test), "/dev/null") |
|
52
|
|
|
assert "error code 404" in str(exc) |
|
53
|
|
|
|
|
54
|
|
|
|
|
55
|
|
|
def test_supported_url(): |
|
56
|
|
|
assert data_fetch.can_fetch_from("http://example.com") |
|
57
|
|
|
assert data_fetch.can_fetch_from("https://example.com") |
|
58
|
|
|
|
|
59
|
|
|
|
|
60
|
|
|
def test_unsupported_url(): |
|
61
|
|
|
assert not data_fetch.can_fetch_from("aaaaa") |
|
62
|
|
|
|
|
63
|
|
|
|
|
64
|
|
|
def test_fetch_local(tmp_path): |
|
65
|
|
|
source_path = pathlib.Path(__file__).absolute() |
|
66
|
|
|
dest_path = tmp_path / "dest" |
|
67
|
|
|
data_fetch.fetch_data("file://" + str(source_path), dest_path) |
|
68
|
|
|
with open(dest_path, "r") as copied_file: |
|
69
|
|
|
assert "This line is here and in the copied file as well" in copied_file.read() |
|
70
|
|
|
|