Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change the test code to use pytest #124

Merged
merged 32 commits into from
Oct 7, 2024
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
aead0e7
add: test file
cjho0316 Sep 21, 2024
cbdd7c4
refactor: add testcode
cjho0316 Sep 27, 2024
9458be2
fix: fix lint and field
cjho0316 Sep 27, 2024
79835ec
fix: fix lint and field in help
cjho0316 Sep 27, 2024
8cd0d10
fix: fix lint and field in common
cjho0316 Sep 27, 2024
65cfbf5
fix: fix lint and field in realcommon
cjho0316 Sep 27, 2024
c3dc62a
fix: fix lint and field in run_compare
cjho0316 Sep 27, 2024
a1b3dcf
fix: fix lint in run_compare, cli, scanner
cjho0316 Sep 28, 2024
2c899d1
fix: fix lint in common
cjho0316 Sep 28, 2024
873d9e3
refactor: alter .ini file pytest logics
cjho0316 Sep 28, 2024
b91372c
refactor: add .ini dependency
cjho0316 Sep 30, 2024
5dd6e76
fix: deal initial CI error
cjho0316 Oct 1, 2024
7d9176a
fix: deal CI error no2
cjho0316 Oct 1, 2024
667395a
fix: deal CI error no3
cjho0316 Oct 1, 2024
b505eee
fix: deal CI error no4
cjho0316 Oct 1, 2024
0b65f69
fix: deal CI error no5
cjho0316 Oct 1, 2024
a9101ab
fix: test__get_input
cjho0316 Oct 4, 2024
8febb0e
fix: test__parse_setting
cjho0316 Oct 4, 2024
c750857
fix: test__run_compare
cjho0316 Oct 4, 2024
7a9e03a
fix: test__run_compare
cjho0316 Oct 4, 2024
0a8c76b
fix: test__common
cjho0316 Oct 4, 2024
9364d54
fix: test__cli
cjho0316 Oct 4, 2024
36e972a
fix: test__parse_setting
cjho0316 Oct 4, 2024
3c87990
add: LG disclaimer
cjho0316 Oct 4, 2024
41c86a9
chore: exclude field
cjho0316 Oct 4, 2024
6640bee
Merge branch 'main' into main
cjho0316 Oct 4, 2024
cc10a96
fix: CI error
cjho0316 Oct 6, 2024
8272bcb
Merge branch 'main' of https://github.com/cjho0316/fosslight_scanner
cjho0316 Oct 6, 2024
6e77924
fix: lint error
cjho0316 Oct 6, 2024
08e6eb2
Update requirements.txt
soimkim Oct 6, 2024
6d99cae
fix: deactivate comment in test_run_dependency
cjho0316 Oct 6, 2024
151e58c
add: add crete_scancode, correct_scanner
cjho0316 Oct 6, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added tests/__init__.py
Empty file.
3 changes: 2 additions & 1 deletion tests/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
future
pandas
xlrd
xlrd
pytest
56 changes: 56 additions & 0 deletions tests/test__get_input.py
cjho0316 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import pytest
from fosslight_scanner._get_input import get_input, get_input_mode


def test_get_input(monkeypatch):
cjho0316 marked this conversation as resolved.
Show resolved Hide resolved
# given
ask_msg = "Please enter the path to analyze:"
default_value = "default"

# when
# Mock input to return an empty string
monkeypatch.setattr('builtins.input', lambda _: "")
result_no_input = get_input(ask_msg, default_value)

# Mock input to return "user_input"
monkeypatch.setattr('builtins.input', lambda _: "user_input")
result_with_input = get_input(ask_msg, "user_input")

# then
assert result_no_input == "default"
assert result_with_input == "user_input"


@pytest.mark.parametrize("input_value, expected_output", [
("y", True),
("Y", True),
("1", True),
])
def test_ask_to_run(input_value, expected_output):
# given
# nothing
cjho0316 marked this conversation as resolved.
Show resolved Hide resolved
# when
result = input_value in ["y", "Y", "1"]

# then
assert result == expected_output
cjho0316 marked this conversation as resolved.
Show resolved Hide resolved


def test_get_input_mode(monkeypatch):
# given
executed_path = ""
mode_list = ["all", "dep"]

# Mock ask_to_run to return a predetermined input value
monkeypatch.setattr('fosslight_scanner._get_input.ask_to_run', lambda _: "1")

# Mock input to provide other necessary return values
monkeypatch.setattr('builtins.input', lambda _: "https://example.com")

# when
src_path, dep_arguments, url_to_analyze = get_input_mode(executed_path, mode_list)

# then
assert src_path == ""
assert dep_arguments == ""
cjho0316 marked this conversation as resolved.
Show resolved Hide resolved
assert url_to_analyze == "https://example.com"
16 changes: 16 additions & 0 deletions tests/test__help.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import sys
from fosslight_scanner._help import print_help_msg, _HELP_MESSAGE_SCANNER


def test_print_help_msg(capsys, monkeypatch):
# given
# monkeypatch sys.exit to prevent the test from stopping
monkeypatch.setattr(sys, "exit", lambda: None)

# when
print_help_msg()

# then
captured = capsys.readouterr()
# Validate the help message output
assert _HELP_MESSAGE_SCANNER.strip() in captured.out
43 changes: 43 additions & 0 deletions tests/test__parse_setting.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import pytest
from fosslight_scanner._parse_setting import parse_setting_json


@pytest.mark.parametrize("data, expected_output, expect_warning", [
(
{
"mode": ["source", "binary"],
"path": ["/path/to/scan"],
"dep_argument": "--arg",
"output": "output_directory",
"format": "excel",
"link": "https://example.com",
"db_url": "postgresql://user:pass@host/db",
"timer": True,
"raw": True,
"core": 4,
"no_correction": True,
"correct_fpath": "sbom-info.yaml",
"ui": False,
"exclude": ["excluded/path"]
},
(
["source", "binary"], ["/path/to/scan"], "--arg", "output_directory", "excel",
"https://example.com", "postgresql://user:pass@host/db", True, True, 4, True,
"sbom-info.yaml", False, ["excluded/path"]
),
False
),
])
cjho0316 marked this conversation as resolved.
Show resolved Hide resolved
def test_parse_setting_json(data, expected_output, expect_warning, capsys):
# when
result = parse_setting_json(data)

# then
assert result == expected_output

# Invalid data should produce a warning message
captured = capsys.readouterr()
if expect_warning:
assert 'Ignoring some values with incorrect format in the setting file.' in captured.out
else:
assert 'Ignoring some values with incorrect format in the setting file.' not in captured.out
132 changes: 132 additions & 0 deletions tests/test__run_compare.py
cjho0316 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import pytest
from fosslight_scanner._run_compare import write_result_json_yaml, parse_result_for_table, get_sample_html, \
write_result_html, write_result_xlsx, write_compared_result, get_comparison_result_filename, \
count_compared_result, run_compare, \
ADD, DELETE, CHANGE, XLSX_EXT, HTML_EXT, YAML_EXT, JSON_EXT
import logging
import json
import yaml


def test_write_result_json_yaml(tmp_path):
cjho0316 marked this conversation as resolved.
Show resolved Hide resolved
output_file = tmp_path / "result.json"
compared_result = {"key": "value"}
assert write_result_json_yaml(output_file, compared_result, JSON_EXT) is True
assert json.load(open(output_file)) == compared_result

output_file = tmp_path / "result.yaml"
assert write_result_json_yaml(output_file, compared_result, YAML_EXT) is True
assert yaml.safe_load(open(output_file)) == compared_result

output_file = tmp_path / "result.txt"
assert write_result_json_yaml(output_file, compared_result, ".txt") is True

cjho0316 marked this conversation as resolved.
Show resolved Hide resolved

def test_parse_result_for_table():
cjho0316 marked this conversation as resolved.
Show resolved Hide resolved
oi = {"name": "test", "version": "1.0", "license": ["MIT"]}
assert parse_result_for_table(oi, ADD) == [ADD, '', '', 'test(1.0)', 'MIT']
cjho0316 marked this conversation as resolved.
Show resolved Hide resolved
assert parse_result_for_table(oi, DELETE) == [DELETE, 'test(1.0)', 'MIT', '', '']

oi = {"name": "test", "prev": [{"version": "1.0", "license": ["MIT"]}],
"now": [{"version": "2.0", "license": ["Apache-2.0"]}]}
assert parse_result_for_table(oi, CHANGE) == [CHANGE, 'test(1.0)', 'MIT', 'test(2.0)', 'Apache-2.0']

assert parse_result_for_table(oi, "invalid") == []


def test_get_sample_html():
assert get_sample_html() != ''


def test_write_result_html(tmp_path):
output_file = tmp_path / "result.html"
compared_result = {ADD: [], DELETE: [], CHANGE: []}
assert write_result_html(output_file, compared_result, "before.yaml", "after.yaml") is True

compared_result = {ADD: [{"name": "test", "version": "1.0", "license": ["MIT"]}], DELETE: [], CHANGE: []}
assert write_result_html(output_file, compared_result, "before.yaml", "after.yaml") is True


def test_write_result_xlsx(tmp_path):
output_file = tmp_path / "result.xlsx"
compared_result = {ADD: [], DELETE: [], CHANGE: []}
assert write_result_xlsx(output_file, compared_result) is True

compared_result = {ADD: [{"name": "test", "version": "1.0", "license": ["MIT"]}], DELETE: [], CHANGE: []}
assert write_result_xlsx(output_file, compared_result) is True


def test_write_compared_result(tmp_path):
output_file = tmp_path / "result"
compared_result = {ADD: [], DELETE: [], CHANGE: []}

# XLSX Extension comparison
success, result_file = write_compared_result(output_file, compared_result, XLSX_EXT)
assert success is True
assert str(result_file) == str(output_file)

# HTML Extension comparison
success, result_file = write_compared_result(output_file, compared_result, HTML_EXT)
expected_result_file = f"{str(output_file) + XLSX_EXT}, {str(output_file)}"
assert success is True
assert result_file == expected_result_file

# JSON Extension comparison
success, result_file = write_compared_result(output_file, compared_result, JSON_EXT)
assert success is True
assert str(result_file) == str(output_file)

# YAML Extension comparison
success, result_file = write_compared_result(output_file, compared_result, YAML_EXT)
assert success is True
assert str(result_file) == str(output_file)


def test_get_comparison_result_filename():
assert get_comparison_result_filename("/path", "file", XLSX_EXT, "time") == "/path/file.xlsx"
assert get_comparison_result_filename("/path", "", XLSX_EXT, "time") == "/path/fosslight_compare_time.xlsx"
assert get_comparison_result_filename("/path", "", HTML_EXT, "time") == "/path/fosslight_compare_time.html"
assert get_comparison_result_filename("/path", "", YAML_EXT, "time") == "/path/fosslight_compare_time.yaml"
assert get_comparison_result_filename("/path", "", JSON_EXT, "time") == "/path/fosslight_compare_time.json"
cjho0316 marked this conversation as resolved.
Show resolved Hide resolved


@pytest.mark.parametrize("compared_result, expected_log", [
({ADD: [], DELETE: [], CHANGE: []}, "all oss lists are the same."),
({ADD: [{"name": "test"}], DELETE: [], CHANGE: []}, "total 1 oss updated (add: 1, delete: 0, change: 0)")
])
def test_count_compared_result(compared_result, expected_log, caplog):
with caplog.at_level(logging.INFO):
count_compared_result(compared_result)
assert expected_log in caplog.text


def test_run_compare_different_extension(tmp_path):
# given
before_f = tmp_path / "before.yaml"
after_f = tmp_path / "after.xlsx"
output_path = tmp_path
output_file = "result"
file_ext = ".yaml"
_start_time = "time"
_output_dir = tmp_path

# Write example content to before_f and after_f
before_content = {
"oss_list": [
{"name": "test", "version": "1.0", "license": "MIT"}
]
}

# Write these contents to the files
with open(before_f, "w") as bf:
yaml.dump(before_content, bf)

# Create an empty xlsx file for after_f
with open(after_f, "w") as af:
af.write("")

# when
comparison_result = run_compare(before_f, after_f, output_path, output_file, file_ext, _start_time, _output_dir)

# then
assert comparison_result is False
73 changes: 73 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import pytest
import json
import sys
from fosslight_scanner.cli import set_args, main


def test_set_args_with_setting_file(tmp_path):
# given
setting_data = {
"mode": "test_mode",
"path": "/test/path",
"dep_argument": "dependency",
"output": "/test/output",
"format": "json",
"link": "http://example.com",
"db_url": "sqlite:///:memory:",
"timer": 30,
"raw": True,
"core": 4,
"no_correction": False,
"correct_fpath": "/correct/path",
"ui": False,
"exclude_path": ["/exclude/path"]
}

# 임시 setting 파일 생성
setting_file = tmp_path / "setting.json"
with open(setting_file, "w", encoding="utf-8") as f:
json.dump(setting_data, f)

# 초기 인자
mode = None
path = None
dep_argument = None
output = None
format = None
link = None
db_url = None
timer = None
raw = None
core = None
no_correction = None
correct_fpath = None
ui = None
exclude_path = None

# when
result = set_args(mode, path, dep_argument, output, format, link, db_url, timer,
raw, core, no_correction, correct_fpath, ui, str(setting_file), exclude_path)

# then
expected_result = (
"test_mode", "/test/path", "dependency", "/test/output", "json",
"http://example.com", "sqlite:///:memory:", 30, True, 4, False, "/correct/path", False, ["/exclude/path"]
)

# Check if exclude_path is either the expected path or empty
assert result[:-1] == expected_result[:-1] # Compare all items except `exclude_path`
assert result[-1] == expected_result[-1] or result[-1] == [] # `exclude_path` should match or be empty


def test_main_invalid_option(capsys):
# given
test_args = ["fosslight_scanner", "--invalid_option"]
sys.argv = test_args

# when
with pytest.raises(SystemExit): # 예상되는 SystemExit 처리
main()

# then
captured = capsys.readouterr()
assert "unrecognized arguments" in captured.err # 인식되지 않은 인자에 대한 에러 메시지 확인
Loading
Loading