Skip to content

Commit 7c0173b

Browse files
authored
Change the test code to use pytest (#124)
Signed-off-by: cjho0316 <[email protected]>
1 parent 15ca9b6 commit 7c0173b

File tree

10 files changed

+734
-23
lines changed

10 files changed

+734
-23
lines changed

tests/__init__.py

Whitespace-only changes.

tests/requirements.txt

Lines changed: 0 additions & 3 deletions
This file was deleted.

tests/test__get_input.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
# Copyright (c) 2020 LG Electronics Inc.
4+
# SPDX-License-Identifier: Apache-2.0
5+
6+
7+
from fosslight_scanner._get_input import get_input, get_input_mode
8+
9+
10+
def test_get_input(monkeypatch):
11+
# given
12+
ask_msg = "Please enter the path to analyze:"
13+
default_value = "default"
14+
15+
# when
16+
# Mock input to return an empty string
17+
monkeypatch.setattr('builtins.input', lambda _: "")
18+
result_no_input = get_input(ask_msg, default_value)
19+
20+
# Mock input to return "user_input"
21+
monkeypatch.setattr('builtins.input', lambda _: "user_input")
22+
result_with_input = get_input(ask_msg, "user_input")
23+
24+
# then
25+
assert result_no_input == "default"
26+
assert result_with_input == "user_input"
27+
28+
29+
def test_get_input_mode(monkeypatch):
30+
# given
31+
executed_path = ""
32+
mode_list = ["all", "dep"]
33+
34+
# Mock ask_to_run to return a predetermined input value
35+
monkeypatch.setattr('fosslight_scanner._get_input.ask_to_run', lambda _: "1")
36+
37+
# Mock input to provide other necessary return values
38+
monkeypatch.setattr('builtins.input', lambda _: "https://example.com")
39+
40+
# when
41+
_, _, url_to_analyze = get_input_mode(executed_path, mode_list)
42+
43+
# then
44+
assert url_to_analyze == "https://example.com"

tests/test__help.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
# Copyright (c) 2020 LG Electronics Inc.
4+
# SPDX-License-Identifier: Apache-2.0
5+
6+
7+
import sys
8+
from fosslight_scanner._help import print_help_msg, _HELP_MESSAGE_SCANNER
9+
10+
11+
def test_print_help_msg(capsys, monkeypatch):
12+
# given
13+
# monkeypatch sys.exit to prevent the test from stopping
14+
monkeypatch.setattr(sys, "exit", lambda: None)
15+
16+
# when
17+
print_help_msg()
18+
19+
# then
20+
captured = capsys.readouterr()
21+
# Validate the help message output
22+
assert _HELP_MESSAGE_SCANNER.strip() in captured.out

tests/test__parse_setting.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
# Copyright (c) 2020 LG Electronics Inc.
4+
# SPDX-License-Identifier: Apache-2.0
5+
6+
from fosslight_scanner._parse_setting import parse_setting_json
7+
8+
9+
def test_parse_setting_json_valid_data():
10+
data = {
11+
'mode': ['test'],
12+
'path': ['/some/path'],
13+
'dep_argument': 'arg',
14+
'output': 'output',
15+
'format': 'json',
16+
'link': 'http://example.com',
17+
'db_url': 'sqlite:///:memory:',
18+
'timer': True,
19+
'raw': True,
20+
'core': 4,
21+
'no_correction': True,
22+
'correct_fpath': '/correct/path',
23+
'ui': True,
24+
'exclude': ['/exclude/path'],
25+
'selected_source_scanner': 'scanner',
26+
'source_write_json_file': True,
27+
'source_print_matched_text': True,
28+
'source_time_out': 60,
29+
'binary_simple': True
30+
}
31+
result = parse_setting_json(data)
32+
assert result == (
33+
['test'], ['/some/path'], 'arg', 'output', 'json', 'http://example.com', 'sqlite:///:memory:', True,
34+
True, 4, True, '/correct/path', True, ['/exclude/path'], 'scanner', True, True, 60, True
35+
)

tests/test__run_compare.py

Lines changed: 199 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,199 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
# Copyright (c) 2020 LG Electronics Inc.
4+
# SPDX-License-Identifier: Apache-2.0
5+
6+
7+
import pytest
8+
from fosslight_scanner._run_compare import write_result_json_yaml, parse_result_for_table, get_sample_html, \
9+
write_result_html, write_result_xlsx, write_compared_result, get_comparison_result_filename, \
10+
count_compared_result, run_compare, \
11+
ADD, DELETE, CHANGE, XLSX_EXT, HTML_EXT, YAML_EXT, JSON_EXT
12+
import logging
13+
import json
14+
import yaml
15+
16+
17+
@pytest.mark.parametrize("ext, expected_content", [
18+
# Test for JSON and YAML extensions
19+
(".json", {"key": "value"}),
20+
(".yaml", {"key": "value"}),
21+
22+
# Test for TXT extension (failure)
23+
(".txt", {"key": "value"}),
24+
])
25+
def test_write_result_json_yaml(tmp_path, ext, expected_content):
26+
# given
27+
output_file = tmp_path / f"result{ext}"
28+
compared_result = expected_content
29+
30+
# when
31+
success = write_result_json_yaml(output_file, compared_result, ext)
32+
33+
# then
34+
assert success is True, f"Failed to write file with extension {ext}"
35+
36+
# Verify content based on extension
37+
if ext == ".json":
38+
with open(output_file, 'r', encoding='utf-8') as f:
39+
result_content = json.load(f)
40+
assert result_content == compared_result, "The content of the JSON file does not match the expected content."
41+
42+
elif ext == ".yaml":
43+
with open(output_file, 'r', encoding='utf-8') as f:
44+
result_content = yaml.safe_load(f)
45+
assert result_content == compared_result, "The content of the YAML file does not match the expected content."
46+
47+
elif ext == ".txt":
48+
with open(output_file, 'r', encoding='utf-8') as f:
49+
result_lines = f.readlines()
50+
result_content = ''.join(result_lines)
51+
assert result_content != compared_result, "The content of the TXT file does not match the expected string representation."
52+
53+
54+
def test_parse_result_for_table():
55+
# given
56+
add_expected = [ADD, '', '', 'test(1.0)', 'MIT']
57+
oi = {"name": "test", "version": "1.0", "license": ["MIT"]}
58+
59+
# when
60+
add_result = parse_result_for_table(oi, ADD)
61+
62+
# then
63+
assert add_result == add_expected
64+
65+
66+
def test_get_sample_html():
67+
# then
68+
assert get_sample_html() != ''
69+
70+
71+
@pytest.mark.parametrize("compared_result, expected_before, expected_after", [
72+
# Case with empty add, delete, change
73+
({ADD: [], DELETE: [], CHANGE: []}, "before.yaml", "after.yaml"),
74+
75+
# Case with one entry in add and no deletes or changes
76+
({ADD: [{"name": "test", "version": "1.0", "license": ["MIT"]}], DELETE: [], CHANGE: []},
77+
"before.yaml", "after.yaml")
78+
])
79+
def test_write_result_html(tmp_path, compared_result, expected_before, expected_after):
80+
# given
81+
output_file = tmp_path / "result.html"
82+
83+
# when
84+
success = write_result_html(output_file, compared_result, expected_before, expected_after)
85+
86+
# then
87+
assert success is True, "Failed to write the HTML file."
88+
assert output_file.exists(), "The HTML file was not created."
89+
with open(output_file, 'r', encoding='utf-8') as f:
90+
content = f.read()
91+
assert content, "The HTML file is empty."
92+
93+
94+
@pytest.mark.parametrize("compared_result", [
95+
# Case with empty add, delete, change
96+
{ADD: [], DELETE: [], CHANGE: []},
97+
98+
# Case with one entry in add and no deletes or changes
99+
{ADD: [{"name": "test", "version": "1.0", "license": ["MIT"]}], DELETE: [], CHANGE: []}
100+
])
101+
def test_write_result_xlsx(tmp_path, compared_result):
102+
# given
103+
output_file = tmp_path / "result.xlsx"
104+
105+
# when
106+
success = write_result_xlsx(output_file, compared_result)
107+
108+
# then
109+
assert success is True, "Failed to write the XLSX file."
110+
assert output_file.exists(), "The XLSX file was not created."
111+
112+
113+
@pytest.mark.parametrize("ext, expected_output", [
114+
(XLSX_EXT, "xlsx"),
115+
(HTML_EXT, "html"),
116+
(JSON_EXT, "json"),
117+
(YAML_EXT, "yaml"),
118+
])
119+
def test_write_compared_result(tmp_path, ext, expected_output):
120+
# given
121+
output_file = tmp_path / "result"
122+
compared_result = {ADD: [], DELETE: [], CHANGE: []}
123+
124+
# when
125+
success, result_file = write_compared_result(output_file, compared_result, ext)
126+
127+
# then
128+
assert success is True, f"Failed to write the compared result for extension {ext}"
129+
if ext == XLSX_EXT:
130+
assert str(result_file) == str(output_file), "The XLSX result file path does not match the expected output path."
131+
elif ext == HTML_EXT:
132+
expected_result_file = f"{str(output_file) + XLSX_EXT}, {str(output_file)}"
133+
assert result_file == expected_result_file, "HTML file creation failed."
134+
elif ext == JSON_EXT:
135+
assert str(result_file) == str(output_file), "The JSON result file path does not match the expected output path."
136+
else:
137+
assert str(result_file) == str(output_file), "The YAML result file path does not match the expected output path."
138+
139+
140+
@pytest.mark.parametrize("path, file_name, ext, time_suffix, expected_output", [
141+
# Case when file name is provided
142+
("/path", "file", XLSX_EXT, "time", "/path/file.xlsx"),
143+
144+
# Case when file name is empty, with different extensions
145+
("/path", "", XLSX_EXT, "time", "/path/fosslight_compare_time.xlsx"),
146+
("/path", "", HTML_EXT, "time", "/path/fosslight_compare_time.html"),
147+
("/path", "", YAML_EXT, "time", "/path/fosslight_compare_time.yaml"),
148+
("/path", "", JSON_EXT, "time", "/path/fosslight_compare_time.json"),
149+
])
150+
def test_get_comparison_result_filename(path, file_name, ext, time_suffix, expected_output):
151+
# when
152+
result = get_comparison_result_filename(path, file_name, ext, time_suffix)
153+
154+
# then
155+
assert result == expected_output, f"Expected {expected_output} but got {result}"
156+
157+
158+
@pytest.mark.parametrize("compared_result, expected_log", [
159+
({ADD: [], DELETE: [], CHANGE: []}, "all oss lists are the same."),
160+
({ADD: [{"name": "test"}], DELETE: [], CHANGE: []}, "total 1 oss updated (add: 1, delete: 0, change: 0)")
161+
])
162+
def test_count_compared_result(compared_result, expected_log, caplog):
163+
# when
164+
with caplog.at_level(logging.INFO):
165+
count_compared_result(compared_result)
166+
# then
167+
assert expected_log in caplog.text
168+
169+
170+
def test_run_compare_different_extension(tmp_path):
171+
# given
172+
before_f = tmp_path / "before.yaml"
173+
after_f = tmp_path / "after.xlsx"
174+
output_path = tmp_path
175+
output_file = "result"
176+
file_ext = ".yaml"
177+
_start_time = "time"
178+
_output_dir = tmp_path
179+
180+
# Write example content to before_f and after_f
181+
before_content = {
182+
"oss_list": [
183+
{"name": "test", "version": "1.0", "license": "MIT"}
184+
]
185+
}
186+
187+
# Write these contents to the files
188+
with open(before_f, "w") as bf:
189+
yaml.dump(before_content, bf)
190+
191+
# Create an empty xlsx file for after_f
192+
with open(after_f, "w") as af:
193+
af.write("")
194+
195+
# when
196+
comparison_result = run_compare(before_f, after_f, output_path, output_file, file_ext, _start_time, _output_dir)
197+
198+
# then
199+
assert comparison_result is False

tests/test_cli.py

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
# Copyright (c) 2020 LG Electronics Inc.
4+
# SPDX-License-Identifier: Apache-2.0
5+
6+
import pytest
7+
import json
8+
import sys
9+
from fosslight_scanner.cli import main, set_args
10+
11+
12+
def test_set_args(monkeypatch):
13+
# Mocking os.path.isfile to return True
14+
monkeypatch.setattr("os.path.isfile", lambda x: True)
15+
16+
# Mocking the open function to return a mock file object
17+
mock_file_data = json.dumps({
18+
"mode": ["test_mode"],
19+
"path": ["test_path"],
20+
"dep_argument": "test_dep_argument",
21+
"output": "test_output",
22+
"format": "test_format",
23+
"link": "test_link",
24+
"db_url": "test_db_url",
25+
"timer": True,
26+
"raw": True,
27+
"core": 4,
28+
"no_correction": True,
29+
"correct_fpath": "test_correct_fpath",
30+
"ui": True,
31+
"exclude": ["test_exclude_path"],
32+
"selected_source_scanner": "test_scanner",
33+
"source_write_json_file": True,
34+
"source_print_matched_text": True,
35+
"source_time_out": 100,
36+
"binary_simple": True
37+
})
38+
39+
def mock_open(*args, **kwargs):
40+
from io import StringIO
41+
return StringIO(mock_file_data)
42+
43+
monkeypatch.setattr("builtins.open", mock_open)
44+
45+
# Call the function with some arguments
46+
result = set_args(
47+
mode=None, path=None, dep_argument=None, output=None, format=None, link=None, db_url=None, timer=None,
48+
raw=None, core=-1, no_correction=None, correct_fpath=None, ui=None, setting="dummy_path", exclude_path=None
49+
)
50+
51+
# Expected result
52+
expected = (
53+
["test_mode"], ["test_path"], "test_dep_argument", "test_output", "test_format", "test_link", "test_db_url", True,
54+
True, 4, True, "test_correct_fpath", True, ["test_exclude_path"], "test_scanner", True, True, 100, True
55+
)
56+
57+
assert result == expected
58+
59+
60+
def test_main_invalid_option(capsys):
61+
# given
62+
test_args = ["fosslight_scanner", "--invalid_option"]
63+
sys.argv = test_args
64+
65+
# when
66+
with pytest.raises(SystemExit): # 예상되는 SystemExit 처리
67+
main()
68+
69+
# then
70+
captured = capsys.readouterr()
71+
assert "unrecognized arguments" in captured.err # 인식되지 않은 인자에 대한 에러 메시지 확인

0 commit comments

Comments
 (0)