diff --git a/qpc/report/tests_report_deployments.py b/qpc/report/test_report_deployments.py similarity index 83% rename from qpc/report/tests_report_deployments.py rename to qpc/report/test_report_deployments.py index 2e1e6f5a..da713da4 100644 --- a/qpc/report/tests_report_deployments.py +++ b/qpc/report/test_report_deployments.py @@ -1,14 +1,15 @@ """Test the CLI module.""" import json +import logging import os import sys import time -import unittest from argparse import ArgumentParser, Namespace # noqa: I100 from io import StringIO # noqa: I100 from unittest.mock import patch +import pytest import requests_mock from qpc import messages @@ -21,7 +22,7 @@ from qpc.utils import create_tar_buffer, get_server_location, write_server_config -class ReportDeploymentsTests(unittest.TestCase): +class TestReportDeployments: """Class for testing the deployments report command.""" def _init_command(self): @@ -30,7 +31,7 @@ def _init_command(self): subparser = argument_parser.add_subparsers(dest="subcommand") return ReportDeploymentsCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" # different from most other test cases where command is initialized once per # class, this one requires to be initialized for each test method because @@ -46,7 +47,7 @@ def setUp(self): self.test_csv_filename = f"test_{time.time():.0f}.csv" sys.stderr = HushUpStderr() - def tearDown(self): + def teardown_method(self, _test_method): """Remove test setup.""" # Restore stderr sys.stderr = self.orig_stderr @@ -59,7 +60,7 @@ def tearDown(self): except FileNotFoundError: pass - def test_deployments_report_as_json(self): + def test_deployments_report_as_json(self, caplog): """Testing retrieving deployments report as json.""" get_scanjob_url = get_server_location() + SCAN_JOB_URI + "1" get_scanjob_json_data = {"id": 1, "report_id": 1} @@ -84,15 +85,15 @@ def test_deployments_report_as_json(self): path=self.test_json_filename, mask=False, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) - self.assertIn(messages.REPORT_SUCCESSFULLY_WRITTEN, log.output[-1]) + assert messages.REPORT_SUCCESSFULLY_WRITTEN in caplog.text with open(self.test_json_filename, "r", encoding="utf-8") as json_file: data = json_file.read() file_content_dict = json.loads(data) - self.assertDictEqual(get_report_json_data, file_content_dict) + assert get_report_json_data == file_content_dict - def test_deployments_report_as_json_report_id(self): + def test_deployments_report_as_json_report_id(self, caplog): """Testing retrieving deployments report as json with report id.""" get_report_url = get_server_location() + REPORT_URI + "1/deployments/" get_report_json_data = {"id": 1, "report": [{"key": "value"}]} @@ -114,15 +115,15 @@ def test_deployments_report_as_json_report_id(self): path=self.test_json_filename, mask=False, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) - self.assertIn(messages.REPORT_SUCCESSFULLY_WRITTEN, log.output[-1]) + assert messages.REPORT_SUCCESSFULLY_WRITTEN in caplog.text with open(self.test_json_filename, "r", encoding="utf-8") as json_file: data = json_file.read() file_content_dict = json.loads(data) - self.assertDictEqual(get_report_json_data, file_content_dict) + assert get_report_json_data == file_content_dict - def test_deployments_report_as_csv(self): + def test_deployments_report_as_csv(self, caplog): """Testing retreiving deployments report as csv.""" get_scanjob_url = get_server_location() + SCAN_JOB_URI + "1" get_scanjob_json_data = {"id": 1, "report_id": 1} @@ -150,18 +151,18 @@ def test_deployments_report_as_csv(self): path=self.test_csv_filename, mask=False, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) - self.assertIn(messages.REPORT_SUCCESSFULLY_WRITTEN, log.output[-1]) + assert messages.REPORT_SUCCESSFULLY_WRITTEN in caplog.text with open(self.test_csv_filename, "r", encoding="utf-8") as json_file: data = json_file.read() file_content_dict = json.loads(data) - self.assertDictEqual(get_report_csv_data, file_content_dict) + assert get_report_csv_data == file_content_dict # Test validation def test_deployments_report_output_directory(self): """Testing fail because output directory.""" - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): sys.argv = [ "/bin/qpc", "report", @@ -174,7 +175,7 @@ def test_deployments_report_output_directory(self): def test_deployments_report_output_directory_not_exist(self): """Testing fail because output directory does not exist.""" - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): sys.argv = [ "/bin/qpc", "report", @@ -187,7 +188,7 @@ def test_deployments_report_output_directory_not_exist(self): def test_deployments_report_output_file_empty(self): """Testing fail because output file empty.""" - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): sys.argv = [ "/bin/qpc", "report", @@ -215,12 +216,10 @@ def test_deployments_report_scan_job_not_exist(self): path=self.test_json_filename, mask=False, ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(report_out): self.command.main(args) - self.assertEqual( - report_out.getvalue(), messages.REPORT_SJ_DOES_NOT_EXIST - ) + assert report_out.getvalue() == messages.REPORT_SJ_DOES_NOT_EXIST def test_deployments_report_invalid_scan_job(self): """Deployments report with scanjob but no report_id.""" @@ -239,16 +238,16 @@ def test_deployments_report_invalid_scan_job(self): path=self.test_json_filename, mask=False, ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(report_out): self.command.main(args) - self.assertEqual( - report_out.getvalue(), - messages.REPORT_NO_DEPLOYMENTS_REPORT_FOR_SJ, + assert ( + report_out.getvalue() + == messages.REPORT_NO_DEPLOYMENTS_REPORT_FOR_SJ ) @patch("qpc.report.deployments.write_file") - def test_deployments_file_fails_to_write(self, file): + def test_deployments_file_fails_to_write(self, file, caplog): """Testing deployments failure while writing to file.""" file.side_effect = EnvironmentError() get_report_url = get_server_location() + REPORT_URI + "1/deployments/" @@ -271,16 +270,16 @@ def test_deployments_file_fails_to_write(self, file): path=self.test_json_filename, mask=False, ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.WRITE_FILE_ERROR % { "path": self.test_json_filename, "error": "", } - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text - def test_deployments_nonexistent_directory(self): + def test_deployments_nonexistent_directory(self, caplog): """Testing error for nonexistent directory in output.""" fake_dir = "/cody/is/awesome/deployments.json" get_report_url = get_server_location() + REPORT_URI + "1/deployments/" @@ -298,15 +297,15 @@ def test_deployments_nonexistent_directory(self): path=fake_dir, mask=False, ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.REPORT_DIRECTORY_DOES_NOT_EXIST % os.path.dirname( fake_dir ) - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text - def test_deployments_nonjson_directory(self): + def test_deployments_nonjson_directory(self, caplog): """Testing error for nonjson output path.""" non_json_dir = "/Users/deployments.tar.gz" get_report_url = get_server_location() + REPORT_URI + "1/deployments/" @@ -324,13 +323,13 @@ def test_deployments_nonjson_directory(self): path=non_json_dir, mask=False, ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.OUTPUT_FILE_TYPE % ".json" - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text - def test_deployments_noncsv_directory(self): + def test_deployments_noncsv_directory(self, caplog): """Testing error for noncsv output path.""" non_csv_dir = "/cody/is/awesome/deployments.tar.gz" get_report_url = get_server_location() + REPORT_URI + "1/deployments/" @@ -348,13 +347,13 @@ def test_deployments_noncsv_directory(self): path=non_csv_dir, mask=False, ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.OUTPUT_FILE_TYPE % ".csv" - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text - def test_deployments_report_id_not_exist(self): + def test_deployments_report_id_not_exist(self, caplog): """Test deployments with nonexistent report id.""" get_report_url = get_server_location() + REPORT_URI + "1/deployments/" get_report_json_data = {"id": 1, "report": [{"key": "value"}]} @@ -376,13 +375,13 @@ def test_deployments_report_id_not_exist(self): path=self.test_json_filename, mask=False, ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.REPORT_NO_DEPLOYMENTS_REPORT_FOR_REPORT_ID % 1 - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text - def test_deployments_report_error_scan_job(self): + def test_deployments_report_error_scan_job(self, caplog): """Testing error with scan job id.""" get_scanjob_url = get_server_location() + SCAN_JOB_URI + "1" get_scanjob_json_data = {"id": 1, "report_id": 1} @@ -407,14 +406,14 @@ def test_deployments_report_error_scan_job(self): path=self.test_json_filename, mask=False, ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.REPORT_NO_DEPLOYMENTS_REPORT_FOR_SJ % 1 - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text - def test_deployments_report_mask(self): - """Testing retreiving json deployments report with masked values.""" + def test_deployments_report_mask(self, caplog): + """Testing retrieving json deployments report with masked values.""" get_report_url = ( get_server_location() + REPORT_URI + "1/deployments/" + "?mask=True" ) @@ -437,15 +436,15 @@ def test_deployments_report_mask(self): path=self.test_json_filename, mask=True, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) - self.assertIn(messages.REPORT_SUCCESSFULLY_WRITTEN, log.output[-1]) + assert messages.REPORT_SUCCESSFULLY_WRITTEN in caplog.text with open(self.test_json_filename, "r", encoding="utf-8") as json_file: data = json_file.read() file_content_dict = json.loads(data) - self.assertDictEqual(get_report_json_data, file_content_dict) + assert get_report_json_data == file_content_dict - def test_deployments_masked_sj_428(self): + def test_deployments_masked_sj_428(self, caplog): """Deployments report retrieved from sj returns 428.""" get_scanjob_url = get_server_location() + SCAN_JOB_URI + "1" get_scanjob_json_data = {"id": 1, "report_id": 1} @@ -470,13 +469,13 @@ def test_deployments_masked_sj_428(self): path=self.test_json_filename, mask=True, ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.REPORT_COULD_NOT_BE_MASKED_SJ % 1 - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text - def test_deployments_masked_report_428(self): + def test_deployments_masked_report_428(self, caplog): """Deployments report retrieved from report returns 428.""" get_report_url = ( get_server_location() + REPORT_URI + "1/deployments/" + "?mask=True" @@ -500,13 +499,13 @@ def test_deployments_masked_report_428(self): path=self.test_json_filename, mask=True, ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.REPORT_COULD_NOT_BE_MASKED_REPORT_ID % 1 - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text - def test_deployments_old_version(self): + def test_deployments_old_version(self, caplog): """Test too old server version.""" get_report_url = get_server_location() + REPORT_URI + "1/deployments/" get_report_json_data = {"id": 1, "report": [{"key": "value"}]} @@ -526,14 +525,14 @@ def test_deployments_old_version(self): path=self.test_json_filename, mask=False, ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.SERVER_TOO_OLD_FOR_CLI % { "min_version": "0.9.2", "current_version": "0.0.45", } - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text def test_deployments_report_as_json_no_output_file(caplog, capsys, requests_mock): @@ -559,6 +558,6 @@ def test_deployments_report_as_json_no_output_file(caplog, capsys, requests_mock "1", ] CLI().main() - assert caplog.messages[-1] == messages.REPORT_SUCCESSFULLY_WRITTEN + assert messages.REPORT_SUCCESSFULLY_WRITTEN in caplog.text captured = capsys.readouterr() assert json.loads(captured.out) diff --git a/qpc/report/tests_report_details.py b/qpc/report/test_report_details.py similarity index 84% rename from qpc/report/tests_report_details.py rename to qpc/report/test_report_details.py index b8ac924f..d035473e 100644 --- a/qpc/report/tests_report_details.py +++ b/qpc/report/test_report_details.py @@ -1,14 +1,15 @@ """Test the CLI module.""" import json +import logging import os import sys import time -import unittest from argparse import ArgumentParser, Namespace # noqa: I100 from io import StringIO # noqa: I100 from unittest.mock import patch +import pytest import requests_mock from qpc import messages @@ -21,7 +22,7 @@ from qpc.utils import create_tar_buffer, get_server_location, write_server_config -class ReportDetailsTests(unittest.TestCase): +class TestReportDetails: """Class for testing the details report command.""" def _init_command(self): @@ -30,7 +31,7 @@ def _init_command(self): subparser = argument_parser.add_subparsers(dest="subcommand") return ReportDetailsCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" # different from most other test cases where command is initialized once per # class, this one requires to be initialized for each test method because @@ -46,7 +47,7 @@ def setUp(self): self.test_csv_filename = f"test_{time.time():.0f}.csv" sys.stderr = HushUpStderr() - def tearDown(self): + def teardown_method(self): """Remove test setup.""" # Restore stderr sys.stderr = self.orig_stderr @@ -59,7 +60,7 @@ def tearDown(self): except FileNotFoundError: pass - def test_detail_report_as_json(self): + def test_detail_report_as_json(self, caplog): """Testing retrieving detail report as json.""" get_scanjob_url = get_server_location() + SCAN_JOB_URI + "1" get_scanjob_json_data = {"id": 1, "report_id": 1} @@ -84,15 +85,15 @@ def test_detail_report_as_json(self): path=self.test_json_filename, mask=False, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) - self.assertIn(messages.REPORT_SUCCESSFULLY_WRITTEN, log.output[-1]) + assert messages.REPORT_SUCCESSFULLY_WRITTEN in caplog.text with open(self.test_json_filename, "r", encoding="utf-8") as json_file: data = json_file.read() file_content_dict = json.loads(data) - self.assertDictEqual(get_report_json_data, file_content_dict) + assert get_report_json_data == file_content_dict - def test_detail_report_as_json_report_id(self): + def test_detail_report_as_json_report_id(self, caplog): """Testing retrieving detail report as json with report id.""" get_report_url = get_server_location() + REPORT_URI + "1/details/" get_report_json_data = {"id": 1, "report": [{"key": "value"}]} @@ -114,15 +115,15 @@ def test_detail_report_as_json_report_id(self): path=self.test_json_filename, mask=False, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) - self.assertIn(messages.REPORT_SUCCESSFULLY_WRITTEN, log.output[-1]) + assert messages.REPORT_SUCCESSFULLY_WRITTEN in caplog.text with open(self.test_json_filename, "r", encoding="utf-8") as json_file: data = json_file.read() file_content_dict = json.loads(data) - self.assertDictEqual(get_report_json_data, file_content_dict) + assert get_report_json_data == file_content_dict - def test_detail_report_as_csv(self): + def test_detail_report_as_csv(self, caplog): """Testing retrieving detail report as csv.""" get_scanjob_url = get_server_location() + SCAN_JOB_URI + "1" get_scanjob_json_data = {"id": 1, "report_id": 1} @@ -150,24 +151,24 @@ def test_detail_report_as_csv(self): path=self.test_csv_filename, mask=False, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) - self.assertIn(messages.REPORT_SUCCESSFULLY_WRITTEN, log.output[-1]) + assert messages.REPORT_SUCCESSFULLY_WRITTEN in caplog.text with open(self.test_csv_filename, "r", encoding="utf-8") as json_file: data = json_file.read() file_content_dict = json.loads(data) - self.assertDictEqual(get_report_csv_data, file_content_dict) + assert get_report_csv_data == file_content_dict # Test validation def test_detail_report_output_directory(self): """Testing fail because output directory.""" - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): sys.argv = ["/bin/qpc", "report", "detail", "--json", "--output-file", "/"] CLI().main() def test_detail_report_output_directory_not_exist(self): """Testing fail because output directory does not exist.""" - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): sys.argv = [ "/bin/qpc", "report", @@ -180,7 +181,7 @@ def test_detail_report_output_directory_not_exist(self): def test_detail_report_output_file_empty(self): """Testing fail because output file empty.""" - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): sys.argv = ["/bin/qpc", "report", "detail", "--json", "--output-file", ""] CLI().main() @@ -201,12 +202,10 @@ def test_detail_report_scan_job_not_exist(self): path=self.test_json_filename, mask=False, ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(report_out): self.command.main(args) - self.assertEqual( - report_out.getvalue(), messages.REPORT_SJ_DOES_NOT_EXIST - ) + assert report_out.getvalue() == messages.REPORT_SJ_DOES_NOT_EXIST def test_detail_report_invalid_scan_job(self): """Details report with scanjob but no report_id.""" @@ -225,15 +224,15 @@ def test_detail_report_invalid_scan_job(self): path=self.test_json_filename, mask=False, ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(report_out): self.command.main(args) - self.assertEqual( - report_out.getvalue(), messages.REPORT_NO_DETAIL_REPORT_FOR_SJ + assert ( + report_out.getvalue() == messages.REPORT_NO_DETAIL_REPORT_FOR_SJ ) @patch("qpc.report.details.write_file") - def test_details_file_fails_to_write(self, file): + def test_details_file_fails_to_write(self, file, caplog): """Testing details failure while writing to file.""" file.side_effect = EnvironmentError() get_report_url = get_server_location() + REPORT_URI + "1/details/" @@ -256,16 +255,16 @@ def test_details_file_fails_to_write(self, file): path=self.test_json_filename, mask=False, ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.WRITE_FILE_ERROR % { "path": self.test_json_filename, "error": "", } - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text - def test_details_nonexistent_directory(self): + def test_details_nonexistent_directory(self, caplog): """Testing error for nonexistent directory in output.""" fake_dir = "/cody/is/awesome/details.json" get_report_url = get_server_location() + REPORT_URI + "1/details/" @@ -283,15 +282,15 @@ def test_details_nonexistent_directory(self): path=fake_dir, mask=False, ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.REPORT_DIRECTORY_DOES_NOT_EXIST % os.path.dirname( fake_dir ) - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text - def test_details_nonjson_path(self): + def test_details_nonjson_path(self, caplog): """Testing error for non json file path.""" non_json_dir = "/Users/details.tar.gz" get_report_url = get_server_location() + REPORT_URI + "1/details/" @@ -309,13 +308,13 @@ def test_details_nonjson_path(self): path=non_json_dir, mask=False, ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.OUTPUT_FILE_TYPE % ".json" - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text - def test_details_noncsv_path(self): + def test_details_noncsv_path(self, caplog): """Testing error for noncsv file path.""" non_csv_dir = "/Users/details.tar.gz" get_report_url = get_server_location() + REPORT_URI + "1/details/" @@ -333,13 +332,13 @@ def test_details_noncsv_path(self): path=non_csv_dir, mask=False, ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.OUTPUT_FILE_TYPE % ".csv" - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text - def test_details_report_id_not_exist(self): + def test_details_report_id_not_exist(self, caplog): """Test details with nonexistent report id.""" get_report_url = get_server_location() + REPORT_URI + "1/details/" get_report_json_data = {"id": 1, "report": [{"key": "value"}]} @@ -359,13 +358,13 @@ def test_details_report_id_not_exist(self): path=self.test_json_filename, mask=False, ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.REPORT_NO_DETAIL_REPORT_FOR_REPORT_ID % 1 - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text - def test_detail_report_error_scan_job(self): + def test_detail_report_error_scan_job(self, caplog): """Testing error with scan job id.""" get_scanjob_url = get_server_location() + SCAN_JOB_URI + "1" get_scanjob_json_data = {"id": 1, "report_id": 1} @@ -390,13 +389,13 @@ def test_detail_report_error_scan_job(self): path=self.test_json_filename, mask=False, ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.REPORT_NO_DETAIL_REPORT_FOR_SJ % 1 - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text - def test_detail_report_as_csv_masked(self): + def test_detail_report_as_csv_masked(self, caplog): """Testing retrieving csv details report with masked query param.""" get_scanjob_url = get_server_location() + SCAN_JOB_URI + "1" get_scanjob_json_data = {"id": 1, "report_id": 1} @@ -426,15 +425,15 @@ def test_detail_report_as_csv_masked(self): path=self.test_csv_filename, mask=True, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) - self.assertIn(messages.REPORT_SUCCESSFULLY_WRITTEN, log.output[-1]) + assert messages.REPORT_SUCCESSFULLY_WRITTEN in caplog.text with open(self.test_csv_filename, "r", encoding="utf-8") as json_file: data = json_file.read() file_content_dict = json.loads(data) - self.assertDictEqual(get_report_csv_data, file_content_dict) + assert get_report_csv_data == file_content_dict - def test_details_old_version(self): + def test_details_old_version(self, caplog): """Test too old server version.""" get_report_url = get_server_location() + REPORT_URI + "1/details/" get_report_json_data = {"id": 1, "report": [{"key": "value"}]} @@ -454,14 +453,14 @@ def test_details_old_version(self): path=self.test_csv_filename, mask=False, ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.SERVER_TOO_OLD_FOR_CLI % { "min_version": "0.9.2", "current_version": "0.0.45", } - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text def test_details_report_as_json_no_output_file(caplog, capsys, requests_mock): diff --git a/qpc/report/tests_report_download.py b/qpc/report/test_report_download.py similarity index 82% rename from qpc/report/tests_report_download.py rename to qpc/report/test_report_download.py index af97ce09..382903b6 100644 --- a/qpc/report/tests_report_download.py +++ b/qpc/report/test_report_download.py @@ -1,12 +1,13 @@ """Test the CLI module.""" +import logging import os import sys import time -import unittest from argparse import ArgumentParser, Namespace # noqa: I100 from unittest.mock import patch +import pytest import requests_mock from qpc import messages @@ -19,7 +20,7 @@ from qpc.utils import create_tar_buffer, get_server_location, write_server_config -class ReportDownloadTests(unittest.TestCase): +class TestReportDownload: """Class for testing the report download command.""" def _init_command(self): @@ -28,7 +29,7 @@ def _init_command(self): subparser = argument_parser.add_subparsers(dest="subcommand") return ReportDownloadCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" # different from most other test cases where command is initialized once per # class, this one requires to be initialized for each test method because @@ -43,7 +44,7 @@ def setUp(self): self.test_tar_filename = f"test_{time.time():.0f}.tar.gz" sys.stderr = HushUpStderr() - def tearDown(self): + def teardown_method(self, _test_method): """Remove test setup.""" # Restore stderr sys.stderr = self.orig_stderr @@ -52,7 +53,7 @@ def tearDown(self): except FileNotFoundError: pass - def test_download_scan_job(self): + def test_download_scan_job(self, caplog): """Testing download with scan job id.""" get_scanjob_url = get_server_location() + SCAN_JOB_URI + "1" get_scanjob_json_data = {"id": 1, "report_id": 1} @@ -73,15 +74,15 @@ def test_download_scan_job(self): args = Namespace( scan_job_id="1", report_id=None, path=self.test_tar_filename, mask=False ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_msg = messages.DOWNLOAD_SUCCESSFULLY_WRITTEN % { "report": "1", "path": self.test_tar_filename, } - self.assertIn(expected_msg, log.output[-1]) + assert expected_msg in caplog.text - def test_download_report_id(self): + def test_download_report_id(self, caplog): """Testing download with report id.""" get_report_url = get_server_location() + REPORT_URI + "1" get_report_json_data = {"id": 1, "report": [{"key": "value"}]} @@ -98,35 +99,35 @@ def test_download_report_id(self): args = Namespace( scan_job_id=None, report_id="1", path=self.test_tar_filename, mask=False ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_msg = messages.DOWNLOAD_SUCCESSFULLY_WRITTEN % { "report": "1", "path": self.test_tar_filename, } - self.assertIn(expected_msg, log.output[-1]) + assert expected_msg in caplog.text def test_download_output_directory(self): """Testing fail because of output directory.""" - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): sys.argv = ["/bin/qpc", "report", "download", "--output-file", "/foo/bar"] CLI().main() def test_download_output_directory_not_exist(self): """Testing fail because output directory does not exist.""" - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): sys.argv = ["/bin/qpc", "report", "download", "--output-file", "/foo/bar/"] CLI().main() def test_download_output_file_empty(self): """Testing fail because output file empty.""" - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): sys.argv = ["/bin/qpc", "report", "download", "--output-file", ""] CLI().main() def test_download_report_empty(self): """Testing fail because output file empty.""" - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): sys.argv = [ "/bin/qpc", "report", @@ -138,7 +139,7 @@ def test_download_report_empty(self): ] CLI().main() - def test_download_scan_job_not_exist(self): + def test_download_scan_job_not_exist(self, caplog): """Testing download with nonexistent scanjob.""" get_scanjob_url = get_server_location() + SCAN_JOB_URI + "1" get_scanjob_json_data = {"id": 1, "report_id": 1} @@ -148,13 +149,13 @@ def test_download_scan_job_not_exist(self): args = Namespace( scan_job_id="1", report_id=None, path=self.test_tar_filename, mask=False ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.DOWNLOAD_SJ_DOES_NOT_EXIST % 1 - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text - def test_download_invalid_scan_job(self): + def test_download_invalid_scan_job(self, caplog): """Testing download with scanjob but no report_id.""" get_scanjob_url = get_server_location() + SCAN_JOB_URI + "1" get_scanjob_json_data = {"id": 1} @@ -164,13 +165,13 @@ def test_download_invalid_scan_job(self): args = Namespace( scan_job_id="1", report_id=None, path=self.test_tar_filename, mask=False ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.DOWNLOAD_NO_REPORT_FOR_SJ % "1" - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text - def test_output_is_nonexistent_directory(self): + def test_output_is_nonexistent_directory(self, caplog): """Testing error for nonexistent directory in output.""" fake_dir = "/cody/is/awesome/" get_report_url = get_server_location() + REPORT_URI + "1" @@ -181,16 +182,16 @@ def test_output_is_nonexistent_directory(self): mocker.get(get_report_url, status_code=200, content=buffer_content) args = Namespace(scan_job_id=None, report_id="1", path=fake_dir, mask=False) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.REPORT_DIRECTORY_DOES_NOT_EXIST % os.path.dirname( fake_dir ) - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text @patch("qpc.report.download.write_file") - def test_file_fails_to_write(self, file): + def test_file_fails_to_write(self, file, caplog): """Testing download failure while writing to file.""" err = "Mock Fail" file.side_effect = OSError(err) @@ -209,16 +210,16 @@ def test_file_fails_to_write(self, file): args = Namespace( scan_job_id=None, report_id="1", path=self.test_tar_filename, mask=False ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.WRITE_FILE_ERROR % { "path": self.test_tar_filename, "error": err, } - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text - def test_download_report_id_not_exist(self): + def test_download_report_id_not_exist(self, caplog): """Test download with nonexistent report id.""" get_report_url = get_server_location() + REPORT_URI + "1" get_report_json_data = {"id": 1, "report": [{"key": "value"}]} @@ -233,13 +234,13 @@ def test_download_report_id_not_exist(self): args = Namespace( scan_job_id=None, report_id=1, path=self.test_tar_filename, mask=False ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.DOWNLOAD_NO_REPORT_FOUND % 1 - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text - def test_download_from_server_with_old_version(self): + def test_download_from_server_with_old_version(self, caplog): """Test download with nonexistent report id.""" get_report_url = get_server_location() + REPORT_URI + "1" get_report_json_data = {"id": 1, "report": [{"key": "value"}]} @@ -254,16 +255,16 @@ def test_download_from_server_with_old_version(self): args = Namespace( scan_job_id=None, report_id=1, path=self.test_tar_filename, mask=False ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.SERVER_TOO_OLD_FOR_CLI % { "min_version": "0.9.2", "current_version": "0.0.45", } - self.assertIn(err_msg, log.output[-1]) + assert err_msg in caplog.text - def test_download_bad_file_extension(self): + def test_download_bad_file_extension(self, caplog): """Test download with bad file extension.""" get_report_url = get_server_location() + REPORT_URI + "1" get_report_json_data = {"id": 1, "report": [{"key": "value"}]} @@ -280,13 +281,13 @@ def test_download_bad_file_extension(self): args = Namespace( scan_job_id=None, report_id="1", path="test.json", mask=False ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.OUTPUT_FILE_TYPE % "tar.gz" - self.assertIn(err_msg, log.output[-1]) + assert err_msg in caplog.text - def test_download_report_id_masked(self): + def test_download_report_id_masked(self, caplog): """Testing download with report id and mask set to true.""" get_report_url = get_server_location() + REPORT_URI + "1" + "?mask=True" get_report_json_data = {"id": 1, "report": [{"key": "value"}]} @@ -303,15 +304,15 @@ def test_download_report_id_masked(self): args = Namespace( scan_job_id=None, report_id="1", path=self.test_tar_filename, mask=True ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_msg = messages.DOWNLOAD_SUCCESSFULLY_WRITTEN % { "report": "1", "path": self.test_tar_filename, } - self.assertIn(expected_msg, log.output[-1]) + assert expected_msg in caplog.text - def test_download_report_id_428(self): + def test_download_report_id_428(self, caplog): """Test download with nonexistent report id.""" get_report_url = get_server_location() + REPORT_URI + "1" get_report_json_data = {"id": 1, "report": [{"key": "value"}]} @@ -326,8 +327,8 @@ def test_download_report_id_428(self): args = Namespace( scan_job_id=None, report_id="1", path=self.test_tar_filename, mask=False ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.DOWNLOAD_NO_MASK_REPORT % 1 - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text diff --git a/qpc/report/tests_report_insights.py b/qpc/report/test_report_insights.py similarity index 84% rename from qpc/report/tests_report_insights.py rename to qpc/report/test_report_insights.py index 8161b2de..87d9a56a 100644 --- a/qpc/report/tests_report_insights.py +++ b/qpc/report/test_report_insights.py @@ -1,14 +1,15 @@ """Test the CLI module.""" import json +import logging import os import sys import time -import unittest from argparse import ArgumentParser, Namespace # noqa: I100 from io import StringIO # noqa: I100 from unittest.mock import patch +import pytest import requests_mock from qpc import messages @@ -22,7 +23,7 @@ VERSION = "0.9.4" -class ReportInsightsTests(unittest.TestCase): +class TestReportInsights: """Class for testing the insights report command.""" def _init_command(self): @@ -31,7 +32,7 @@ def _init_command(self): subparser = argument_parser.add_subparsers(dest="subcommand") return ReportInsightsCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" # different from most other test cases where command is initialized once per # class, this one requires to be initialized for each test method because @@ -46,7 +47,7 @@ def setUp(self): self.test_json_filename = f"test_{time.time():.0f}.json" sys.stderr = HushUpStderr() - def tearDown(self): + def teardown_method(self, _test_method): """Remove test setup.""" # Restore stderr sys.stderr = self.orig_stderr @@ -55,7 +56,7 @@ def tearDown(self): except FileNotFoundError: pass - def test_insights_report_as_json(self): + def test_insights_report_as_json(self, caplog): """Testing retrieving insights report as json.""" get_scanjob_url = get_server_location() + SCAN_JOB_URI + "1" get_scanjob_json_data = {"id": 1, "report_id": 1} @@ -79,11 +80,11 @@ def test_insights_report_as_json(self): args = Namespace( scan_job_id="1", report_id=None, path=self.test_tar_gz_filename ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) - self.assertIn(messages.REPORT_SUCCESSFULLY_WRITTEN, log.output[-1]) + assert messages.REPORT_SUCCESSFULLY_WRITTEN in caplog.text - def test_insights_report_as_json_report_id(self): + def test_insights_report_as_json_report_id(self, caplog): """Testing retreiving insights report as json with report id.""" get_report_url = get_server_location() + REPORT_URI + "1/insights/" get_report_json_data = { @@ -104,26 +105,26 @@ def test_insights_report_as_json_report_id(self): args = Namespace( scan_job_id=None, report_id="1", path=self.test_tar_gz_filename ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) - self.assertIn(messages.REPORT_SUCCESSFULLY_WRITTEN, log.output[-1]) + assert messages.REPORT_SUCCESSFULLY_WRITTEN in caplog.text # Test validation def test_insights_report_output_directory(self): """Testing fail because output directory.""" - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): sys.argv = ["/bin/qpc", "report", "insights", "--output-file", "/"] CLI().main() def test_insights_report_output_directory_not_exist(self): """Testing fail because output directory does not exist.""" - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): sys.argv = ["/bin/qpc", "report", "insights", "--output-file", "/foo/bar/"] CLI().main() def test_insights_report_output_file_empty(self): """Testing fail because output file empty.""" - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): sys.argv = ["/bin/qpc", "report", "insights", "--output-file", ""] CLI().main() @@ -139,12 +140,10 @@ def test_insights_report_scan_job_not_exist(self): args = Namespace( scan_job_id="1", report_id=None, path=self.test_tar_gz_filename ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(report_out): self.command.main(args) - self.assertEqual( - report_out.getvalue(), messages.REPORT_SJ_DOES_NOT_EXIST - ) + assert report_out.getvalue() == messages.REPORT_SJ_DOES_NOT_EXIST def test_insights_report_invalid_scan_job(self): """Deployments report with scanjob but no report_id.""" @@ -158,16 +157,16 @@ def test_insights_report_invalid_scan_job(self): args = Namespace( scan_job_id="1", report_id=None, path=self.test_tar_gz_filename ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(report_out): self.command.main(args) - self.assertEqual( - report_out.getvalue(), - messages.REPORT_NO_DEPLOYMENTS_REPORT_FOR_SJ, + assert ( + report_out.getvalue() + == messages.REPORT_NO_DEPLOYMENTS_REPORT_FOR_SJ ) @patch("qpc.report.insights.write_file") - def test_insights_file_fails_to_write(self, file): + def test_insights_file_fails_to_write(self, file, caplog): """Testing insights failure while writing to file.""" file.side_effect = EnvironmentError() get_report_url = get_server_location() + REPORT_URI + "1/insights/" @@ -185,16 +184,16 @@ def test_insights_file_fails_to_write(self, file): args = Namespace( scan_job_id=None, report_id="1", path=self.test_tar_gz_filename ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.WRITE_FILE_ERROR % { "path": self.test_tar_gz_filename, "error": "", } - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text - def test_insights_nonexistent_directory(self): + def test_insights_nonexistent_directory(self, caplog): """Testing error for nonexistent directory in output.""" fake_dir = "/kevan/is/awesome/insights.tar.gz" get_report_url = get_server_location() + REPORT_URI + "1/insights/" @@ -205,15 +204,15 @@ def test_insights_nonexistent_directory(self): mocker.get(get_report_url, status_code=200, content=buffer_content) args = Namespace(scan_job_id=None, report_id="1", path=fake_dir) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.REPORT_DIRECTORY_DOES_NOT_EXIST % os.path.dirname( fake_dir ) - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text - def test_insights_tar_path(self): + def test_insights_tar_path(self, caplog): """Testing error for nonjson output path.""" non_tar_file = "/Users/insights.json" get_report_url = get_server_location() + REPORT_URI + "1/insights/" @@ -229,13 +228,13 @@ def test_insights_tar_path(self): ) args = Namespace(scan_job_id=None, report_id="1", path=non_tar_file) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.OUTPUT_FILE_TYPE % "tar.gz" - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text - def test_insights_report_id_not_exist(self): + def test_insights_report_id_not_exist(self, caplog): """Test insights with nonexistent report id.""" get_report_url = get_server_location() + REPORT_URI + "1/insights/" get_report_json_data = {"id": 1, "report": [{"key": "value"}]} @@ -252,13 +251,13 @@ def test_insights_report_id_not_exist(self): args = Namespace( scan_job_id=None, report_id="1", path=self.test_tar_gz_filename ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.REPORT_NO_INSIGHTS_REPORT_FOR_REPORT_ID % 1 - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text - def test_insights_report_error_scan_job(self): + def test_insights_report_error_scan_job(self, caplog): """Testing error with scan job id.""" get_scanjob_url = get_server_location() + SCAN_JOB_URI + "1" get_scanjob_json_data = {"id": 1, "report_id": 1} @@ -278,11 +277,11 @@ def test_insights_report_error_scan_job(self): args = Namespace( scan_job_id="1", report_id=None, path=self.test_tar_gz_filename ) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.REPORT_NO_INSIGHTS_REPORT_FOR_SJ % 1 - self.assertIn(err_msg, log.output[0]) + assert err_msg in caplog.text def test_insights_report_as_json_no_output_file(caplog, capsys, requests_mock): diff --git a/qpc/report/tests_report_merge.py b/qpc/report/test_report_merge.py similarity index 91% rename from qpc/report/tests_report_merge.py rename to qpc/report/test_report_merge.py index 9f9fb140..98e5f870 100644 --- a/qpc/report/tests_report_merge.py +++ b/qpc/report/test_report_merge.py @@ -3,10 +3,10 @@ import os import sys import time -import unittest from argparse import ArgumentParser, Namespace from io import StringIO +import pytest import requests_mock from qpc import messages @@ -63,17 +63,17 @@ ] -class ReportMergeTests(unittest.TestCase): +class TestReportMergeTests: """Class for testing the scan show commands for qpc.""" @classmethod - def setUpClass(cls): + def setup_class(cls): """Set up test case.""" argument_parser = ArgumentParser() subparser = argument_parser.add_subparsers(dest="subcommand") cls.command = ReportMergeCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" write_server_config(DEFAULT_CONFIG) # Temporarily disable stderr for these tests, CLI errors clutter up @@ -88,7 +88,7 @@ def setUp(self): with open(file[0], "w", encoding="utf-8") as test_file: test_file.write(file[1]) - def tearDown(self): + def teardown_method(self, _test_method): """Remove test setup.""" # Restore stderr for file in JSON_FILES_LIST: @@ -126,7 +126,7 @@ def test_detail_merge_job_ids(self): "id": "1", "prog_name": QPC_VAR_PROGRAM_NAME, } - self.assertIn(expected_msg, captured_stdout.getvalue()) + assert expected_msg in captured_stdout.getvalue() def test_detail_merge_error_job_ids(self): """Testing report merge error with scan job ids.""" @@ -147,7 +147,7 @@ def test_detail_merge_error_job_ids(self): args = Namespace( scan_job_ids=[1, 2], json_files=None, report_ids=None, json_dir=None ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(report_out): self.command.main(args) @@ -167,7 +167,7 @@ def test_detail_merge_report_ids(self): "id": "1", "prog_name": QPC_VAR_PROGRAM_NAME, } - self.assertIn(expected_msg, captured_stdout.getvalue()) + assert expected_msg in captured_stdout.getvalue() def test_detail_merge_error_report_ids(self): """Testing report merge error with report ids.""" @@ -182,7 +182,7 @@ def test_detail_merge_error_report_ids(self): args = Namespace( scan_job_ids=None, json_files=None, report_ids=[1, 2], json_dir=None ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(report_out): self.command.main(args) @@ -204,7 +204,7 @@ def test_detail_merge_json_files(self): "id": "1", "prog_name": QPC_VAR_PROGRAM_NAME, } - self.assertIn(expected_msg, captured_stdout.getvalue()) + assert expected_msg in captured_stdout.getvalue() def test_detail_merge_json_files_not_exist(self): """Testing report merge file not found error with json files.""" @@ -216,12 +216,12 @@ def test_detail_merge_json_files_not_exist(self): report_ids=None, json_dir=None, ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(report_out): self.command.main(args) - self.assertIn( - messages.FILE_NOT_FOUND % NONEXIST_FILE[0], - report_out.getvalue().strip(), + assert ( + messages.FILE_NOT_FOUND % NONEXIST_FILE[0] + in report_out.getvalue().strip() ) def test_detail_merge_error_json_files(self): @@ -234,7 +234,7 @@ def test_detail_merge_error_json_files(self): report_ids=None, json_dir=None, ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(report_out): self.command.main(args) @@ -248,7 +248,7 @@ def test_detail_merge_error_all_json_files(self): report_ids=None, json_dir=None, ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(report_out): self.command.main(args) @@ -264,7 +264,7 @@ def test_detail_merge_only_one_json_file(self): report_ids=None, json_dir=None, ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(report_out): self.command.main(args) @@ -275,7 +275,7 @@ def test_detail_merge_error_no_args(self): args = Namespace( scan_job_ids=None, json_files=None, report_ids=None, json_dir=None ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(report_out): self.command.main(args) @@ -286,7 +286,7 @@ def test_detail_merge_error_too_few_args(self): args = Namespace( scan_job_ids=[1], json_files=None, report_ids=None, json_dir=None ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(report_out): self.command.main(args) @@ -306,7 +306,7 @@ def test_detail_merge_json_directory(self): "id": "1", "prog_name": QPC_VAR_PROGRAM_NAME, } - self.assertIn(expected_msg, captured_stdout.getvalue()) + assert expected_msg in captured_stdout.getvalue() def test_detail_merge_json_directory_error_dir_not_found(self): """Testing report merge command with json_dir parameter (notdir).""" @@ -319,7 +319,7 @@ def test_detail_merge_json_directory_error_dir_not_found(self): report_ids=None, json_dir=bad_json_directory, ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(report_out): self.command.main(args) @@ -333,7 +333,7 @@ def test_detail_merge_json_directory_error_path_passed(self): report_ids=None, json_dir=TMP_BADDETAILS1[0], ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(report_out): self.command.main(args) @@ -347,7 +347,7 @@ def test_detail_merge_json_invalid_report_type_passed(self): report_ids=None, json_dir=TMP_BADDETAILS5[0], ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(report_out): self.command.main(args) @@ -362,6 +362,6 @@ def test_detail_merge_json_directory_no_detail_reports(self): args = Namespace( scan_job_ids=None, json_files=None, report_ids=None, json_dir="/tmp/" ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(report_out): self.command.main(args) diff --git a/qpc/report/tests_report_merge_status.py b/qpc/report/test_report_merge_status.py similarity index 87% rename from qpc/report/tests_report_merge_status.py rename to qpc/report/test_report_merge_status.py index 22fc7c17..b95e8686 100644 --- a/qpc/report/tests_report_merge_status.py +++ b/qpc/report/test_report_merge_status.py @@ -1,10 +1,10 @@ """Test the CLI module.""" import sys -import unittest from argparse import ArgumentParser, Namespace from io import StringIO +import pytest import requests_mock from qpc import messages @@ -15,24 +15,24 @@ from qpc.utils import get_server_location, write_server_config -class ReportMergeStatusTests(unittest.TestCase): +class TestReportMergeStatus: """Class for testing the report merge status commands for qpc.""" @classmethod - def setUpClass(cls): + def setup_class(cls): """Set up test case.""" argument_parser = ArgumentParser() subparser = argument_parser.add_subparsers(dest="subcommand") cls.command = ReportMergeStatusCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" write_server_config(DEFAULT_CONFIG) self.orig_stderr = sys.stderr sys.stderr = HushUpStderr() self.url = get_server_location() + ASYNC_MERGE_URI - def tearDown(self): + def teardown_method(self, _test_method): """Remove test setup.""" sys.stderr = self.orig_stderr @@ -72,8 +72,8 @@ def test_job_valid_id(self): "prog_name": QPC_VAR_PROGRAM_NAME, } stdout_lines = captured_stdout.getvalue().splitlines() - self.assertIn(result1, stdout_lines[-2]) - self.assertIn(result2, stdout_lines[-1]) + assert result1 in stdout_lines[-2] + assert result2 in stdout_lines[-1] def test_job_id_not_exist(self): """Test the job command with an invalid ID.""" @@ -82,9 +82,9 @@ def test_job_id_not_exist(self): mocker.get(self.url + "1/", status_code=404, json=None) args = Namespace(job_id="1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(report_out): self.command.main(args) - self.assertEqual( - report_out.getvalue(), messages.MERGE_JOB_ID_NOT_FOUND % "1" + assert ( + report_out.getvalue() == messages.MERGE_JOB_ID_NOT_FOUND % "1" ) diff --git a/qpc/report/tests_report_upload.py b/qpc/report/test_report_upload.py similarity index 82% rename from qpc/report/tests_report_upload.py rename to qpc/report/test_report_upload.py index 66479b3d..4f46dd46 100644 --- a/qpc/report/tests_report_upload.py +++ b/qpc/report/test_report_upload.py @@ -1,10 +1,11 @@ """Test the CLI module.""" +import logging import os import sys -import unittest from argparse import ArgumentParser, Namespace +import pytest import requests_mock from qpc import messages @@ -26,17 +27,17 @@ JSON_FILES_LIST = [TMP_BADDETAILS1, TMP_GOODDETAILS] -class ReportUploadTests(unittest.TestCase): +class TestReportUploadTests: """Class for testing the scan show commands for qpc.""" @classmethod - def setUpClass(cls): + def setup_class(cls): """Set up test case.""" argument_parser = ArgumentParser() subparser = argument_parser.add_subparsers(dest="subcommand") cls.command = ReportUploadCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" write_server_config(DEFAULT_CONFIG) # Temporarily disable stderr for these tests, CLI errors clutter up @@ -49,7 +50,7 @@ def setUp(self): with open(file[0], "w", encoding="utf-8") as test_file: test_file.write(file[1]) - def tearDown(self): + def teardown_method(self, _test_method): """Remove test setup.""" # Restore stderr for file in JSON_FILES_LIST: @@ -57,7 +58,7 @@ def tearDown(self): os.remove(file[0]) sys.stderr = self.orig_stderr - def test_upload_good_details_report(self): + def test_upload_good_details_report(self, caplog): """Test uploading a good details report.""" put_report_data = {"id": 1} put_merge_url = get_server_location() + ASYNC_MERGE_URI @@ -65,16 +66,16 @@ def test_upload_good_details_report(self): mocker.post(put_merge_url, status_code=201, json=put_report_data) args = Namespace(json_file=TMP_GOODDETAILS[0]) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.REPORT_SUCCESSFULLY_UPLOADED % { "id": "1", "prog_name": QPC_VAR_PROGRAM_NAME, } - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text - def test_upload_bad_details_report(self): + def test_upload_bad_details_report(self, caplog): """Test uploading a bad details report.""" put_report_data = {"id": 1} put_merge_url = get_server_location() + ASYNC_MERGE_URI @@ -82,15 +83,15 @@ def test_upload_bad_details_report(self): mocker.post(put_merge_url, status_code=201, json=put_report_data) args = Namespace(json_file=TMP_BADDETAILS1[0]) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.REPORT_UPLOAD_FILE_INVALID_JSON % ( TMP_BADDETAILS1[0] ) - self.assertIn(err_msg, log.output[-1]) + assert err_msg in caplog.text - def test_upload_bad_details_report_no_fingerprints(self): + def test_upload_bad_details_report_no_fingerprints(self, caplog): """Test uploading a details report that produces no fingerprints.""" put_report_data = { "error": "FAILED to create report id=23 - produced no valid fingerprints" @@ -100,10 +101,10 @@ def test_upload_bad_details_report_no_fingerprints(self): mocker.post(put_merge_url, status_code=400, json=put_report_data) args = Namespace(json_file=TMP_GOODDETAILS[0]) - with self.assertLogs(level="ERROR") as log: - with self.assertRaises(SystemExit): + with caplog.at_level(logging.ERROR): + with pytest.raises(SystemExit): self.command.main(args) err_msg = messages.REPORT_FAILED_TO_UPLOADED % ( put_report_data.get("error") ) - self.assertIn(err_msg, log.output[-1]) + assert err_msg in caplog.text diff --git a/qpc/scan/tests_scan_add.py b/qpc/scan/test_scan_add.py similarity index 85% rename from qpc/scan/tests_scan_add.py rename to qpc/scan/test_scan_add.py index 9512999c..e32c5412 100644 --- a/qpc/scan/tests_scan_add.py +++ b/qpc/scan/test_scan_add.py @@ -1,10 +1,11 @@ """Test the CLI module.""" +import logging import sys -import unittest from argparse import ArgumentParser, Namespace from io import StringIO +import pytest import requests import requests_mock @@ -18,17 +19,17 @@ from qpc.utils import get_server_location, write_server_config -class ScanAddCliTests(unittest.TestCase): +class TestScanAddCli: """Class for testing the scan add commands for qpc.""" @classmethod - def setUpClass(cls): + def setup_class(cls): """Set up test case.""" argument_parser = ArgumentParser() subparser = argument_parser.add_subparsers(dest="subcommand") cls.command = ScanAddCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" write_server_config(DEFAULT_CONFIG) # Temporarily disable stderr for these tests, CLI errors clutter up @@ -36,14 +37,14 @@ def setUp(self): self.orig_stderr = sys.stderr sys.stderr = HushUpStderr() - def tearDown(self): + def teardown_method(self, _test_method): """Tear down test case setup.""" # Restore stderr sys.stderr = self.orig_stderr def test_add_req_args_err(self): """Testing the scan add command required flags.""" - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): sys.argv = ["/bin/qpc", "scan", "add", "--name", "scan1"] CLI().main() @@ -55,13 +56,11 @@ def test_scan_source_none(self): mocker.get(url, status_code=200, json={"count": 0}) args = Namespace(sources=["source_none"]) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) self.command.main(args) - self.assertTrue( - 'Source "source_none" does not exist' in scan_out.getvalue() - ) + assert 'Source "source_none" does not exist' in scan_out.getvalue() def test_add_scan_ssl_err(self): """Testing the add scan command with a connection error.""" @@ -71,10 +70,10 @@ def test_add_scan_ssl_err(self): mocker.get(url, exc=requests.exceptions.SSLError) args = Namespace(sources=["source1"]) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), CONNECTION_ERROR_MSG) + assert scan_out.getvalue() == CONNECTION_ERROR_MSG def test_add_scan_conn_err(self): """Testing the add scan command with a connection error.""" @@ -84,10 +83,10 @@ def test_add_scan_conn_err(self): mocker.get(url, exc=requests.exceptions.ConnectTimeout) args = Namespace(sources=["source1"]) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), CONNECTION_ERROR_MSG) + assert scan_out.getvalue() == CONNECTION_ERROR_MSG def test_add_scan_bad_resp(self): """Testing the add scan command with a 500.""" @@ -97,14 +96,12 @@ def test_add_scan_bad_resp(self): mocker.get(url_get_source, status_code=500, json=None) args = Namespace(sources=["source1"], max_concurrency=50) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual( - scan_out.getvalue(), messages.SERVER_INTERNAL_ERROR - ) + assert scan_out.getvalue() == messages.SERVER_INTERNAL_ERROR - def test_add_scan(self): + def test_add_scan(self, caplog): """Testing the add scan command successfully.""" url_get_source = get_server_location() + SOURCE_URI + "?name=source1" url_post = get_server_location() + SCAN_URI @@ -137,12 +134,12 @@ def test_add_scan(self): enabled_ext_product_search=None, ext_product_search_dirs=None, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SCAN_ADDED % "scan1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text - def test_disable_optional_products(self): + def test_disable_optional_products(self, caplog): """Testing that the disable-optional-products flag works correctly.""" url_get_source = get_server_location() + SOURCE_URI + "?name=source1" url_post = get_server_location() + SCAN_URI @@ -172,12 +169,12 @@ def test_disable_optional_products(self): enabled_ext_product_search=None, ext_product_search_dirs=None, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SCAN_ADDED % "scan1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text - def test_enabled_products_and_dirs(self): + def test_enabled_products_and_dirs(self, caplog): """Testing that the ext products & search dirs flags work correctly.""" url_get_source = get_server_location() + SOURCE_URI + "?name=source1" url_post = get_server_location() + SCAN_URI @@ -208,12 +205,12 @@ def test_enabled_products_and_dirs(self): enabled_ext_product_search=["jboss-eap", "jboss-brms"], ext_product_search_dirs="/foo/bar/", ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SCAN_ADDED % "scan1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text - def test_enabled_products_only(self): + def test_enabled_products_only(self, caplog): """Testing that the enabled-ext-product-search flag works.""" url_get_source = get_server_location() + SOURCE_URI + "?name=source1" url_post = get_server_location() + SCAN_URI @@ -243,12 +240,12 @@ def test_enabled_products_only(self): enabled_ext_product_search=["jboss_eap", "jboss_brms"], ext_product_search_dirs=None, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SCAN_ADDED % "scan1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text - def test_disable_optional_products_empty(self): + def test_disable_optional_products_empty(self, caplog): """Testing that the disable-optional-products flag works correctly.""" url_get_source = get_server_location() + SOURCE_URI + "?name=source1" url_post = get_server_location() + SCAN_URI @@ -266,7 +263,7 @@ def test_disable_optional_products_empty(self): enabled_ext_product_search=None, ext_product_search_dirs=None, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SCAN_ADDED % "scan1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text diff --git a/qpc/scan/tests_scan_cancel.py b/qpc/scan/test_scan_cancel.py similarity index 83% rename from qpc/scan/tests_scan_cancel.py rename to qpc/scan/test_scan_cancel.py index 5d6b527f..6d00becb 100644 --- a/qpc/scan/tests_scan_cancel.py +++ b/qpc/scan/test_scan_cancel.py @@ -1,10 +1,11 @@ """Test the CLI module.""" +import logging import sys -import unittest from argparse import ArgumentParser, Namespace from io import StringIO +import pytest import requests import requests_mock @@ -16,7 +17,7 @@ from qpc.utils import get_server_location, write_server_config -class ScanCancelCliTests(unittest.TestCase): +class TestScanCancelCli: """Class for testing the scan cancel commands for qpc.""" def _init_command(self): @@ -25,7 +26,7 @@ def _init_command(self): subparser = argument_parser.add_subparsers(dest="subcommand") return ScanCancelCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" # different from most other test cases where command is initialized once per # class, this one requires to be initialized for each test method because @@ -39,7 +40,7 @@ def setUp(self): self.orig_stderr = sys.stderr sys.stderr = HushUpStderr() - def tearDown(self): + def teardown_method(self, _test_method): """Remove test setup.""" # Restore stderr sys.stderr = self.orig_stderr @@ -52,10 +53,10 @@ def test_cancel_scan_ssl_err(self): mocker.put(url, exc=requests.exceptions.SSLError) args = Namespace(id="1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), CONNECTION_ERROR_MSG) + assert scan_out.getvalue() == CONNECTION_ERROR_MSG def test_cancel_scan_conn_err(self): """Testing the cancel scan command with a connection error.""" @@ -65,10 +66,10 @@ def test_cancel_scan_conn_err(self): mocker.put(url, exc=requests.exceptions.ConnectTimeout) args = Namespace(id="1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), CONNECTION_ERROR_MSG) + assert scan_out.getvalue() == CONNECTION_ERROR_MSG def test_cancel_scan_internal_err(self): """Testing the cancel scan command with an internal error.""" @@ -78,19 +79,19 @@ def test_cancel_scan_internal_err(self): mocker.put(url, status_code=500, json={"error": ["Server Error"]}) args = Namespace(id="1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), "Server Error") + assert scan_out.getvalue() == "Server Error" - def test_cancel_scan_data(self): + def test_cancel_scan_data(self, caplog): """Testing the cancel scan command successfully with stubbed data.""" url = get_server_location() + SCAN_JOB_URI + "1/cancel/" with requests_mock.Mocker() as mocker: mocker.put(url, status_code=200, json=None) args = Namespace(id="1") - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SCAN_CANCELED % "1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text diff --git a/qpc/scan/tests_scan_clear.py b/qpc/scan/test_scan_clear.py similarity index 83% rename from qpc/scan/tests_scan_clear.py rename to qpc/scan/test_scan_clear.py index f197da45..2c772336 100644 --- a/qpc/scan/tests_scan_clear.py +++ b/qpc/scan/test_scan_clear.py @@ -1,10 +1,11 @@ """Test the CLI module.""" +import logging import sys -import unittest from argparse import ArgumentParser, Namespace from io import StringIO +import pytest import requests import requests_mock @@ -16,17 +17,17 @@ from qpc.utils import get_server_location, write_server_config -class ScanClearCliTests(unittest.TestCase): +class TestScanClearCli: """Class for testing the scan clear commands for qpc.""" @classmethod - def setUpClass(cls): + def setup_class(cls): """Set up test case.""" argument_parser = ArgumentParser() subparser = argument_parser.add_subparsers(dest="subcommand") cls.command = ScanClearCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" write_server_config(DEFAULT_CONFIG) # Temporarily disable stderr for these tests, CLI errors clutter up @@ -34,7 +35,7 @@ def setUp(self): self.orig_stderr = sys.stderr sys.stderr = HushUpStderr() - def tearDown(self): + def teaddown_method(self, _test_method): """Remove test setup.""" # Restore stderr sys.stderr = self.orig_stderr @@ -47,10 +48,10 @@ def test_clear_scan_ssl_err(self): mocker.get(url, exc=requests.exceptions.SSLError) args = Namespace(name="scan1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), CONNECTION_ERROR_MSG) + assert scan_out.getvalue() == CONNECTION_ERROR_MSG def test_clear_scan_conn_err(self): """Testing the clear scan command with a connection error.""" @@ -60,10 +61,10 @@ def test_clear_scan_conn_err(self): mocker.get(url, exc=requests.exceptions.ConnectTimeout) args = Namespace(name="scan1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), CONNECTION_ERROR_MSG) + assert scan_out.getvalue() == CONNECTION_ERROR_MSG def test_clear_scan_internal_err(self): """Testing the clear scan command with an internal error.""" @@ -73,10 +74,10 @@ def test_clear_scan_internal_err(self): mocker.get(url, status_code=500, json={"error": ["Server Error"]}) args = Namespace(name="scan1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), "Server Error") + assert scan_out.getvalue() == "Server Error" def test_clear_scan_empty(self): """Testing the clear scan command successfully with empty data.""" @@ -86,14 +87,12 @@ def test_clear_scan_empty(self): mocker.get(url, status_code=200, json={"count": 0}) args = Namespace(name="scan1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual( - scan_out.getvalue(), 'scan "scan1" was not found\n' - ) + assert scan_out.getvalue() == 'scan "scan1" was not found\n' - def test_clear_by_name(self): + def test_clear_by_name(self, caplog): """Testing the clear scan command. Successfully with stubbed data when specifying a name @@ -108,10 +107,10 @@ def test_clear_by_name(self): mocker.delete(delete_url, status_code=204) args = Namespace(name="scan1") - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_msg = messages.SCAN_REMOVED % "scan1" - self.assertIn(expected_msg, log.output[-1]) + assert expected_msg in caplog.text def test_clear_by_name_err(self): """Test the clear scan command successfully. @@ -130,11 +129,11 @@ def test_clear_by_name_err(self): mocker.delete(delete_url, status_code=500, json=err_data) args = Namespace(name="scan1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) expected = 'Failed to remove scan "scan1"' - self.assertTrue(expected in scan_out.getvalue()) + assert expected in scan_out.getvalue() def test_clear_all_empty(self): """Test the clear scan command successfully. @@ -147,11 +146,11 @@ def test_clear_all_empty(self): mocker.get(get_url, status_code=200, json={"count": 0}) args = Namespace(name=None) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) expected = "No scans exist to be removed\n" - self.assertEqual(scan_out.getvalue(), expected) + assert scan_out.getvalue() == expected def test_clear_all_with_error(self): """Testing the clear scan command successfully. @@ -173,7 +172,7 @@ def test_clear_all_with_error(self): mocker.delete(delete_url2, status_code=204) args = Namespace(name=None) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) expected = ( @@ -181,9 +180,9 @@ def test_clear_all_with_error(self): " error occurred removing the following" " credentials:" ) - self.assertTrue(expected in scan_out.getvalue()) + assert expected in scan_out.getvalue() - def test_clear_all(self): + def test_clear_all(self, caplog): """Testing the clear scan command successfully with stubbed data.""" get_url = get_server_location() + SCAN_URI delete_url = get_server_location() + SCAN_URI + "1/" @@ -198,6 +197,6 @@ def test_clear_all(self): mocker.delete(delete_url2, status_code=204) args = Namespace(name=None) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) - self.assertIn(messages.SCAN_CLEAR_ALL_SUCCESS, log.output[-1]) + assert messages.SCAN_CLEAR_ALL_SUCCESS in caplog.text diff --git a/qpc/scan/tests_scan_edit.py b/qpc/scan/test_scan_edit.py similarity index 87% rename from qpc/scan/tests_scan_edit.py rename to qpc/scan/test_scan_edit.py index 824af9e0..9d35be65 100644 --- a/qpc/scan/tests_scan_edit.py +++ b/qpc/scan/test_scan_edit.py @@ -1,10 +1,11 @@ """Test the CLI module.""" +import logging import sys -import unittest from argparse import ArgumentParser, Namespace from io import StringIO +import pytest import requests_mock from qpc import messages @@ -18,7 +19,7 @@ TMP_HOSTFILE = "/tmp/testhostsfile" -class SourceEditCliTests(unittest.TestCase): +class TestSourceEditCli: """Class for testing the source edit commands for qpc.""" def _init_command(self): @@ -27,7 +28,7 @@ def _init_command(self): subparser = argument_parser.add_subparsers(dest="subcommand") return ScanEditCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" # different from most other test cases where command is initialized once per # class, this one requires to be initialized for each test method because @@ -40,7 +41,7 @@ def setUp(self): self.orig_stderr = sys.stderr sys.stderr = HushUpStderr() - def tearDown(self): + def teardown_method(self, _test_method): """Tear down test case setup.""" # Restore stderr sys.stderr = self.orig_stderr @@ -48,12 +49,12 @@ def tearDown(self): def test_edit_req_args_err(self): """Testing the edit command required flags.""" source_out = StringIO() - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): sys.argv = ["/bin/qpc", "scan", "edit", "--name", "scan1"] CLI().main() - self.assertEqual( - source_out.getvalue(), "No arguments provided to edit scan scan1" + assert ( + source_out.getvalue() == "No arguments provided to edit scan scan1" ) def test_edit_scan_none(self): @@ -64,16 +65,16 @@ def test_edit_scan_none(self): mocker.get(url, status_code=200, json={"count": 0}) args = Namespace(name="scan_none", sources=["source1"]) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) self.command.main(args) - self.assertTrue( + assert ( messages.SCAN_DOES_NOT_EXIST % "scan_none" in scan_out.getvalue() ) - def test_edit_scan_source(self): + def test_edit_scan_source(self, caplog): """Testing the edit scan source command successfully.""" url_get_source = get_server_location() + SOURCE_URI + "?name=source1" url_get_scan = get_server_location() + SCAN_URI + "?name=scan1" @@ -98,12 +99,12 @@ def test_edit_scan_source(self): enabled_ext_product_search=None, ext_product_search_dirs=None, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SCAN_UPDATED % "scan1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text - def test_partial_edit_scan_source(self): + def test_partial_edit_scan_source(self, caplog): """Testing the edit scan source command successfully.""" url_get_source = get_server_location() + SOURCE_URI + "?name=source1" url_get_scan = get_server_location() + SCAN_URI + "?name=scan1" @@ -129,12 +130,12 @@ def test_partial_edit_scan_source(self): enabled_ext_product_search=None, ext_product_search_dirs=None, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SCAN_UPDATED % "scan1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text - def test_edit_scan_ext_products(self): + def test_edit_scan_ext_products(self, caplog): """Testing the edit scanvcommand with enabled products successfully.""" url_get_scan = get_server_location() + SCAN_URI + "?name=scan1" url_patch = get_server_location() + SCAN_URI + "1/" @@ -165,12 +166,12 @@ def test_edit_scan_ext_products(self): enabled_ext_product_search=["jboss_eap", "jboss_brms"], ext_product_search_dirs=None, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SCAN_UPDATED % "scan1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text - def test_edit_scan_search_dirs(self): + def test_edit_scan_search_dirs(self, caplog): """Testing the edit scan command with search dirs successfully.""" url_get_scan = get_server_location() + SCAN_URI + "?name=scan1" url_patch = get_server_location() + SCAN_URI + "1/" @@ -197,12 +198,12 @@ def test_edit_scan_search_dirs(self): enabled_ext_product_search=None, ext_product_search_dirs="/foo/bar/", ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SCAN_UPDATED % "scan1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text - def test_edit_scan_reset_ext_products(self): + def test_edit_scan_reset_ext_products(self, caplog): """Testing the edit scan command with reset successfully.""" url_get_scan = get_server_location() + SCAN_URI + "?name=scan1" url_patch = get_server_location() + SCAN_URI + "1/" @@ -233,12 +234,12 @@ def test_edit_scan_reset_ext_products(self): enabled_ext_product_search=[], ext_product_search_dirs=None, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SCAN_UPDATED % "scan1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text - def test_edit_scan_reset_search_dirs(self): + def test_edit_scan_reset_search_dirs(self, caplog): """Testing the edit scan command with reset successfully.""" url_get_scan = get_server_location() + SCAN_URI + "?name=scan1" url_patch = get_server_location() + SCAN_URI + "1/" @@ -269,12 +270,12 @@ def test_edit_scan_reset_search_dirs(self): enabled_ext_product_search=None, ext_product_search_dirs=[], ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SCAN_UPDATED % "scan1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text - def test_edit_scan_reset_dis_products(self): + def test_edit_scan_reset_dis_products(self, caplog): """Testing the edit scan command with reset successfully.""" url_get_scan = get_server_location() + SCAN_URI + "?name=scan1" url_patch = get_server_location() + SCAN_URI + "1/" @@ -305,10 +306,10 @@ def test_edit_scan_reset_dis_products(self): enabled_ext_product_search=None, ext_product_search_dirs=None, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SCAN_UPDATED % "scan1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text def test_edit_scan_no_val(self): """Testing the edit scan command with a scan that doesn't exist.""" @@ -325,9 +326,7 @@ def test_edit_scan_no_val(self): enabled_ext_product_search=None, ext_product_search_dirs=None, ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual( - scan_out.getvalue(), messages.SERVER_INTERNAL_ERROR - ) + assert scan_out.getvalue() == messages.SERVER_INTERNAL_ERROR diff --git a/qpc/scan/tests_scan_job.py b/qpc/scan/test_scan_job.py similarity index 87% rename from qpc/scan/tests_scan_job.py rename to qpc/scan/test_scan_job.py index 0acca9de..0952f0ca 100644 --- a/qpc/scan/tests_scan_job.py +++ b/qpc/scan/test_scan_job.py @@ -1,10 +1,10 @@ """Test the CLI module.""" import sys -import unittest from argparse import ArgumentParser, Namespace from io import StringIO +import pytest import requests import requests_mock @@ -16,7 +16,7 @@ from qpc.utils import get_server_location, write_server_config -class ScanJobCliTests(unittest.TestCase): +class TestScanJobCli: """Class for testing the scan job commands for qpc.""" def _init_command(self): @@ -25,7 +25,7 @@ def _init_command(self): subparser = argument_parser.add_subparsers(dest="subcommand") return ScanJobCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" # different from most other test cases where command is initialized once per # class, this one requires to be initialized for each test method because @@ -38,7 +38,7 @@ def setUp(self): self.orig_stderr = sys.stderr sys.stderr = HushUpStderr() - def tearDown(self): + def teardown_method(self, _test_method): """Remove test setup.""" # Restore stderr sys.stderr = self.orig_stderr @@ -51,10 +51,10 @@ def test_scan_job_ssl_err(self): mocker.get(url, exc=requests.exceptions.SSLError) args = Namespace(name="scan1", id=None) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), CONNECTION_ERROR_MSG) + assert scan_out.getvalue() == CONNECTION_ERROR_MSG def test_scan_job_conn_err(self): """Testing the scan job command with a connection error.""" @@ -64,10 +64,10 @@ def test_scan_job_conn_err(self): mocker.get(url, exc=requests.exceptions.ConnectTimeout) args = Namespace(name="scan1", id=None) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), CONNECTION_ERROR_MSG) + assert scan_out.getvalue() == CONNECTION_ERROR_MSG def test_scan_job_internal_err(self): """Testing the scan job command with an internal error.""" @@ -77,10 +77,10 @@ def test_scan_job_internal_err(self): mocker.get(url, status_code=500, json={"error": ["Server Error"]}) args = Namespace(name="scan1", id=None) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), "Server Error") + assert scan_out.getvalue() == "Server Error" def test_scan_job_empty(self): """Testing the scan job command successfully with empty data.""" @@ -90,12 +90,10 @@ def test_scan_job_empty(self): mocker.get(url, status_code=200, json={"count": 0}) args = Namespace(name="scan1", id=None) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual( - scan_out.getvalue(), messages.SCAN_LIST_NO_SCANS + "\n" - ) + assert scan_out.getvalue() == messages.SCAN_LIST_NO_SCANS + "\n" def test_scan_job_filter_id(self): """Testing the list scan with filter by id.""" @@ -121,9 +119,9 @@ def test_scan_job_filter_id(self): with redirect_stdout(scan_out): self.command.main(args) expected = '{"id":1,"scan":"scan1","status":"completed"}' - self.assertEqual( - scan_out.getvalue().replace("\n", "").replace(" ", "").strip(), - expected, + assert ( + scan_out.getvalue().replace("\n", "").replace(" ", "").strip() + == expected ) def test_scan_job_filter_status(self): @@ -159,9 +157,9 @@ def test_scan_job_filter_status(self): '[{"id":1,"scan":"scan1","status":"completed"},' '{"id":2,"scan":"scan1","status":"completed"}]' ) - self.assertEqual( - scan_out.getvalue().replace("\n", "").replace(" ", "").strip(), - expected, + assert ( + scan_out.getvalue().replace("\n", "").replace(" ", "").strip() + == expected ) def test_scan_job_no_filter(self): @@ -197,9 +195,9 @@ def test_scan_job_no_filter(self): '[{"id":1,"scan":"scan1","status":"completed"},' '{"id":2,"scan":"scan1","status":"running"}]' ) - self.assertEqual( - scan_out.getvalue().replace("\n", "").replace(" ", "").strip(), - expected, + assert ( + scan_out.getvalue().replace("\n", "").replace(" ", "").strip() + == expected ) def test_scan_job_name_and_id(self): @@ -207,7 +205,7 @@ def test_scan_job_name_and_id(self): scan_out = StringIO() args = Namespace(name="scan1", id=1, status=None) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) expected = ( @@ -216,17 +214,17 @@ def test_scan_job_name_and_id(self): ": error: argument --name: not allowed " "with argument --id" ) - self.assertEqual(scan_out.getvalue(), expected) + assert scan_out.getvalue() == expected def test_scan_job_id_and_status(self): """Testing the scan job with id and status filter.""" scan_out = StringIO() args = Namespace(name=None, id=1, status="completed") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), messages.SCAN_JOB_ID_STATUS) + assert scan_out.getvalue() == messages.SCAN_JOB_ID_STATUS def test_scan_job_no_jobs(self): """Testing the scan job with no jobs.""" @@ -249,7 +247,7 @@ def test_scan_job_no_jobs(self): mocker.get(urlscanjob, status_code=200, json=scan_job) args = Namespace(name="scan1", id=None) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), messages.SCAN_LIST_NO_SCANS) + assert scan_out.getvalue() == messages.SCAN_LIST_NO_SCANS diff --git a/qpc/scan/tests_scan_list.py b/qpc/scan/test_scan_list.py similarity index 84% rename from qpc/scan/tests_scan_list.py rename to qpc/scan/test_scan_list.py index a4538b08..e5d75316 100644 --- a/qpc/scan/tests_scan_list.py +++ b/qpc/scan/test_scan_list.py @@ -1,11 +1,12 @@ """Test the CLI module.""" +import logging import sys -import unittest from argparse import ArgumentParser, Namespace # noqa: I100 from io import StringIO from unittest.mock import ANY, patch +import pytest import requests import requests_mock @@ -17,17 +18,17 @@ from qpc.utils import get_server_location, write_server_config -class ScanListCliTests(unittest.TestCase): +class TestScanListCli: """Class for testing the scan list commands for qpc.""" @classmethod - def setUpClass(cls): + def setup_class(cls): """Set up test case.""" argument_parser = ArgumentParser() subparser = argument_parser.add_subparsers(dest="subcommand") cls.command = ScanListCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" write_server_config(DEFAULT_CONFIG) # Temporarily disable stderr for these tests, CLI errors clutter up @@ -35,7 +36,7 @@ def setUp(self): self.orig_stderr = sys.stderr sys.stderr = HushUpStderr() - def tearDown(self): + def teardown_method(self, _test_method): """Remove test setup.""" # Restore stderr sys.stderr = self.orig_stderr @@ -48,10 +49,10 @@ def test_list_scan_ssl_err(self): mocker.get(url, exc=requests.exceptions.SSLError) args = Namespace() - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), CONNECTION_ERROR_MSG) + assert scan_out.getvalue() == CONNECTION_ERROR_MSG def test_list_scan_conn_err(self): """Testing the list scan command with a connection error.""" @@ -61,10 +62,10 @@ def test_list_scan_conn_err(self): mocker.get(url, exc=requests.exceptions.ConnectTimeout) args = Namespace() - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), CONNECTION_ERROR_MSG) + assert scan_out.getvalue() == CONNECTION_ERROR_MSG def test_list_scan_internal_err(self): """Testing the list scan command with an internal error.""" @@ -74,21 +75,21 @@ def test_list_scan_internal_err(self): mocker.get(url, status_code=500, json={"error": ["Server Error"]}) args = Namespace() - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), "Server Error") + assert scan_out.getvalue() == "Server Error" - def test_list_scan_empty(self): + def test_list_scan_empty(self, caplog): """Testing the list scan command successfully with empty data.""" url = get_server_location() + SCAN_URI with requests_mock.Mocker() as mocker: mocker.get(url, status_code=200, json={"count": 0}) args = Namespace() - with self.assertLogs(level="ERROR") as log: + with caplog.at_level(logging.ERROR): self.command.main(args) - self.assertIn(messages.SCAN_LIST_NO_SCANS, log.output[-1]) + assert messages.SCAN_LIST_NO_SCANS in caplog.text @patch("builtins.input", return_value="yes") def test_list_scan_data(self, b_input): @@ -116,9 +117,9 @@ def test_list_scan_data(self, b_input): ',"source":{"id":1,"name":"scan1"}' "}]" ) - self.assertEqual( - scan_out.getvalue().replace("\n", "").replace(" ", "").strip(), - expected + expected, + assert ( + scan_out.getvalue().replace("\n", "").replace(" ", "").strip() + == expected + expected ) b_input.assert_called_with(ANY) @@ -144,7 +145,7 @@ def test_list_filter_type(self): ',"source":{"id":1,"name":"scan1"}' "}]" ) - self.assertEqual( - scan_out.getvalue().replace("\n", "").replace(" ", "").strip(), - expected, + assert ( + scan_out.getvalue().replace("\n", "").replace(" ", "").strip() + == expected ) diff --git a/qpc/scan/tests_scan_pause.py b/qpc/scan/test_scan_pause.py similarity index 83% rename from qpc/scan/tests_scan_pause.py rename to qpc/scan/test_scan_pause.py index 7dae0fe7..63ca530f 100644 --- a/qpc/scan/tests_scan_pause.py +++ b/qpc/scan/test_scan_pause.py @@ -1,10 +1,11 @@ """Test the CLI module.""" +import logging import sys -import unittest from argparse import ArgumentParser, Namespace from io import StringIO +import pytest import requests import requests_mock @@ -16,7 +17,7 @@ from qpc.utils import get_server_location, write_server_config -class ScanPauseCliTests(unittest.TestCase): +class TestScanPauseCli: """Class for testing the scan pause commands for qpc.""" def _init_command(self): @@ -25,7 +26,7 @@ def _init_command(self): subparser = argument_parser.add_subparsers(dest="subcommand") return ScanPauseCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" # different from most other test cases where command is initialized once per # class, this one requires to be initialized for each test method because @@ -39,7 +40,7 @@ def setUp(self): self.orig_stderr = sys.stderr sys.stderr = HushUpStderr() - def tearDown(self): + def teardown_method(self, _test_method): """Remove test setup.""" # Restore stderr sys.stderr = self.orig_stderr @@ -52,10 +53,10 @@ def test_pause_scan_ssl_err(self): mocker.put(url, exc=requests.exceptions.SSLError) args = Namespace(id="1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), CONNECTION_ERROR_MSG) + assert scan_out.getvalue() == CONNECTION_ERROR_MSG def test_pause_scan_conn_err(self): """Testing the pause scan command with a connection error.""" @@ -65,10 +66,10 @@ def test_pause_scan_conn_err(self): mocker.put(url, exc=requests.exceptions.ConnectTimeout) args = Namespace(id="1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), CONNECTION_ERROR_MSG) + assert scan_out.getvalue() == CONNECTION_ERROR_MSG def test_pause_scan_internal_err(self): """Testing the pause scan command with an internal error.""" @@ -78,19 +79,19 @@ def test_pause_scan_internal_err(self): mocker.put(url, status_code=500, json={"error": ["Server Error"]}) args = Namespace(id="1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), "Server Error") + assert scan_out.getvalue() == "Server Error" - def test_pause_scan_data(self): + def test_pause_scan_data(self, caplog): """Testing the pause scan command successfully with stubbed data.""" url = get_server_location() + SCAN_JOB_URI + "1/pause/" with requests_mock.Mocker() as mocker: mocker.put(url, status_code=200, json=None) args = Namespace(id="1") - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SCAN_PAUSED % "1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text diff --git a/qpc/scan/tests_scan_restart.py b/qpc/scan/test_scan_restart.py similarity index 83% rename from qpc/scan/tests_scan_restart.py rename to qpc/scan/test_scan_restart.py index cdc87930..6c905414 100644 --- a/qpc/scan/tests_scan_restart.py +++ b/qpc/scan/test_scan_restart.py @@ -1,10 +1,11 @@ """Test the CLI module.""" +import logging import sys -import unittest from argparse import ArgumentParser, Namespace from io import StringIO +import pytest import requests import requests_mock @@ -16,7 +17,7 @@ from qpc.utils import get_server_location, write_server_config -class ScanRestartCliTests(unittest.TestCase): +class TestScanRestartCli: """Class for testing the scan restart commands for qpc.""" def _init_command(self): @@ -25,7 +26,7 @@ def _init_command(self): subparser = argument_parser.add_subparsers(dest="subcommand") return ScanRestartCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" # different from most other test cases where command is initialized once per # class, this one requires to be initialized for each test method because @@ -38,7 +39,7 @@ def setUp(self): self.orig_stderr = sys.stderr sys.stderr = HushUpStderr() - def tearDown(self): + def teardown_method(self, _test_method): """Remove test setup.""" # Restore stderr sys.stderr = self.orig_stderr @@ -51,10 +52,10 @@ def test_restart_scan_ssl_err(self): mocker.put(url, exc=requests.exceptions.SSLError) args = Namespace(id="1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), CONNECTION_ERROR_MSG) + assert scan_out.getvalue() == CONNECTION_ERROR_MSG def test_restart_scan_conn_err(self): """Testing the restart scan command with a connection error.""" @@ -64,10 +65,10 @@ def test_restart_scan_conn_err(self): mocker.put(url, exc=requests.exceptions.ConnectTimeout) args = Namespace(id="1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), CONNECTION_ERROR_MSG) + assert scan_out.getvalue() == CONNECTION_ERROR_MSG def test_restart_scan_internal_err(self): """Testing the restart scan command with an internal error.""" @@ -77,19 +78,19 @@ def test_restart_scan_internal_err(self): mocker.put(url, status_code=500, json={"error": ["Server Error"]}) args = Namespace(id="1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), "Server Error") + assert scan_out.getvalue() == "Server Error" - def test_restart_scan_data(self): + def test_restart_scan_data(self, caplog): """Testing the restart scan command successfully with stubbed data.""" url = get_server_location() + SCAN_JOB_URI + "1/restart/" with requests_mock.Mocker() as mocker: mocker.put(url, status_code=200, json=None) args = Namespace(id="1") - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SCAN_RESTARTED % "1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text diff --git a/qpc/scan/tests_scan_show.py b/qpc/scan/test_scan_show.py similarity index 87% rename from qpc/scan/tests_scan_show.py rename to qpc/scan/test_scan_show.py index 664fdb47..8c0af12a 100644 --- a/qpc/scan/tests_scan_show.py +++ b/qpc/scan/test_scan_show.py @@ -1,10 +1,10 @@ """Test the CLI module.""" import sys -import unittest from argparse import ArgumentParser, Namespace from io import StringIO +import pytest import requests import requests_mock @@ -15,7 +15,7 @@ from qpc.utils import get_server_location, write_server_config -class ScanShowCliTests(unittest.TestCase): +class TestScanShowCli: """Class for testing the scan show commands for qpc.""" def _init_command(self): @@ -24,7 +24,7 @@ def _init_command(self): subparser = argument_parser.add_subparsers(dest="subcommand") return ScanShowCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" # different from most other test cases where command is initialized once per # class, this one requires to be initialized for each test method because @@ -37,7 +37,7 @@ def setUp(self): self.orig_stderr = sys.stderr sys.stderr = HushUpStderr() - def tearDown(self): + def teardown_method(self, _test_method): """Remove test setup.""" # Restore stderr sys.stderr = self.orig_stderr @@ -50,10 +50,10 @@ def test_show_scan_ssl_err(self): mocker.get(url, exc=requests.exceptions.SSLError) args = Namespace(name="scan1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), CONNECTION_ERROR_MSG) + assert scan_out.getvalue() == CONNECTION_ERROR_MSG def test_show_scan_conn_err(self): """Testing the show scan command with a connection error.""" @@ -63,10 +63,10 @@ def test_show_scan_conn_err(self): mocker.get(url, exc=requests.exceptions.ConnectTimeout) args = Namespace(name="scan1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), CONNECTION_ERROR_MSG) + assert scan_out.getvalue() == CONNECTION_ERROR_MSG def test_show_scan_internal_err(self): """Testing the show scan command with an internal error.""" @@ -76,10 +76,10 @@ def test_show_scan_internal_err(self): mocker.get(url, status_code=500, json={"error": ["Server Error"]}) args = Namespace(name="scan1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual(scan_out.getvalue(), "Server Error") + assert scan_out.getvalue() == "Server Error" def test_show_scan_data_multiple_scans(self): """Testing the show scan command successfully with stubbed data.""" @@ -98,9 +98,9 @@ def test_show_scan_data_multiple_scans(self): with redirect_stdout(scan_out): self.command.main(args) expected = '{"id":1,"name":"scan1","sources":["source1"]}' - self.assertEqual( - scan_out.getvalue().replace("\n", "").replace(" ", "").strip(), - expected, + assert ( + scan_out.getvalue().replace("\n", "").replace(" ", "").strip() + == expected ) def test_show_scan_data_one_scan(self): @@ -119,7 +119,7 @@ def test_show_scan_data_one_scan(self): with redirect_stdout(scan_out): self.command.main(args) expected = '{"id":1,"name":"scan1","sources":["source1"]}' - self.assertEqual( - scan_out.getvalue().replace("\n", "").replace(" ", "").strip(), - expected, + assert ( + scan_out.getvalue().replace("\n", "").replace(" ", "").strip() + == expected ) diff --git a/qpc/scan/tests_scan_start.py b/qpc/scan/test_scan_start.py similarity index 83% rename from qpc/scan/tests_scan_start.py rename to qpc/scan/test_scan_start.py index 116fde42..df1ac160 100644 --- a/qpc/scan/tests_scan_start.py +++ b/qpc/scan/test_scan_start.py @@ -1,10 +1,10 @@ """Test the CLI module.""" import sys -import unittest from argparse import ArgumentParser, Namespace from io import StringIO +import pytest import requests_mock from qpc import messages @@ -15,17 +15,17 @@ from qpc.utils import get_server_location, write_server_config -class ScanStartCliTests(unittest.TestCase): +class TestScanStartCli: """Class for testing the scan start commands for qpc.""" @classmethod - def setUpClass(cls): + def setup_class(cls): """Set up test case.""" argument_parser = ArgumentParser() subparser = argument_parser.add_subparsers(dest="subcommand") cls.command = ScanStartCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" write_server_config(DEFAULT_CONFIG) # Temporarily disable stderr for these tests, CLI errors clutter up @@ -33,14 +33,14 @@ def setUp(self): self.orig_stderr = sys.stderr sys.stderr = HushUpStderr() - def tearDown(self): + def teardown_method(self, _test_method): """Tear down test case setup.""" # Restore stderr sys.stderr = self.orig_stderr def test_start_req_args_err(self): """Testing the scan start command required flags.""" - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): sys.argv = ["/bin/qpc", "scan", "start", "--name", "scan1"] CLI().main() @@ -54,12 +54,10 @@ def test_scan_with_scan_none(self): mocker.post(url_post, status_code=300, json=None) args = Namespace(name="scan_none") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertTrue( - 'Scan "scan_none" does not exist.' in scan_out.getvalue() - ) + assert 'Scan "scan_none" does not exist.' in scan_out.getvalue() def test_start_scan(self): """Testing the start scan command successfully.""" @@ -86,7 +84,7 @@ def test_start_scan(self): args = Namespace(name="scan1") self.command.main(args) expected_message = messages.SCAN_STARTED % "1" - self.assertIn(expected_message, captured_stdout.getvalue()) + assert expected_message in captured_stdout.getvalue() def test_unsuccessful_start_scan(self): """Testing the start scan command unsuccessfully.""" @@ -111,12 +109,10 @@ def test_unsuccessful_start_scan(self): mocker.post(url_post, status_code=201, json={"id": 1}) args = Namespace(name="scan2") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertTrue( - 'Scan "scan2" does not exist' in scan_out.getvalue() - ) + assert 'Scan "scan2" does not exist' in scan_out.getvalue() def test_start_scan_bad_resp(self): """Testing the start scan command with a 500 error.""" @@ -126,9 +122,7 @@ def test_start_scan_bad_resp(self): mocker.get(url_get_scan, status_code=500, json=None) args = Namespace(name="scan1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(scan_out): self.command.main(args) - self.assertEqual( - scan_out.getvalue(), messages.SERVER_INTERNAL_ERROR - ) + assert scan_out.getvalue() == messages.SERVER_INTERNAL_ERROR diff --git a/qpc/scan/tests_utils.py b/qpc/scan/test_utils.py similarity index 84% rename from qpc/scan/tests_utils.py rename to qpc/scan/test_utils.py index 09fced29..0f521333 100644 --- a/qpc/scan/tests_utils.py +++ b/qpc/scan/test_utils.py @@ -1,12 +1,10 @@ """Test the CLI module.""" -import unittest - from qpc.scan import JBOSS_BRMS, JBOSS_EAP, JBOSS_FUSE, JBOSS_WS from qpc.scan.utils import get_enabled_products, get_optional_products -class ScanUtilsTests(unittest.TestCase): +class TestScanUtils: """Class for testing the scan utils.""" def test_default_optional_values(self): @@ -18,7 +16,7 @@ def test_default_optional_values(self): JBOSS_WS: False, } result = get_optional_products([]) - self.assertEqual(disabled_default, result) + assert disabled_default == result def test_default_extended_search_values(self): """Testing the scan default extended searchvalues.""" @@ -30,4 +28,4 @@ def test_default_extended_search_values(self): "search_directories": [], } result = get_enabled_products([], [], True) - self.assertEqual(disabled_default, result) + assert disabled_default == result diff --git a/qpc/server/tests_configure_host.py b/qpc/server/test_configure_host.py similarity index 72% rename from qpc/server/tests_configure_host.py rename to qpc/server/test_configure_host.py index b570a247..57703184 100644 --- a/qpc/server/tests_configure_host.py +++ b/qpc/server/test_configure_host.py @@ -1,7 +1,9 @@ """Test the CLI module.""" +import logging import sys -import unittest + +import pytest from qpc import messages from qpc.cli import CLI @@ -11,17 +13,22 @@ DEFAULT_PORT = 9443 -class ConfigureHostTests(unittest.TestCase): +class TestConfigureHost: """Class for testing the server host configuration.""" - def setUp(self): + @pytest.fixture(autouse=True) + def inject_fixtures(self, caplog): + """Inject caplog as we need to use it during teardown.""" + self._caplog = caplog + + def setup_method(self, _test_method): """Create test setup.""" # Temporarily disable stderr for these tests, CLI errors clutter up # nosetests command. self.orig_stderr = sys.stderr sys.stderr = HushUpStderr() - def tearDown(self): + def teardown_method(self, _test_method): """Remove test case setup.""" # Reset server config to default ip/port sys.argv = [ @@ -34,29 +41,29 @@ def tearDown(self): str(DEFAULT_PORT), ] - with self.assertLogs(level="INFO") as log: + with self._caplog.at_level(logging.INFO): CLI().main() config = read_server_config() - self.assertEqual(config["host"], "127.0.0.1") - self.assertEqual(config["port"], DEFAULT_PORT) + assert config["host"] == "127.0.0.1" + assert config["port"] == DEFAULT_PORT expected_message = messages.SERVER_CONFIG_SUCCESS % { "protocol": "https", "host": "127.0.0.1", "port": str(DEFAULT_PORT), } - self.assertIn(expected_message, log.output[-1]) + assert expected_message in self._caplog.text # Restore stderr sys.stderr = self.orig_stderr def test_config_host_req_args_err(self): """Testing the configure server requires host arg.""" - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): sys.argv = ["/bin/qpc", "server", "config"] CLI().main() def test_config_host_alpha_port_err(self): """Testing the configure server requires bad port.""" - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): sys.argv = [ "/bin/qpc", "server", @@ -68,7 +75,7 @@ def test_config_host_alpha_port_err(self): ] CLI().main() - def test_success_config_server(self): + def test_success_config_server(self, caplog): """Testing the configure server green path.""" sys.argv = [ "/bin/qpc", @@ -79,25 +86,25 @@ def test_success_config_server(self): "--port", "8005", ] - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): CLI().main() config = read_server_config() - self.assertEqual(config["host"], "127.0.0.1") - self.assertEqual(config["port"], 8005) + assert config["host"] == "127.0.0.1" + assert config["port"] == 8005 expected_message = messages.SERVER_CONFIG_SUCCESS % { "protocol": "https", "host": "127.0.0.1", "port": "8005", } - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text def test_config_server_default_port(self): """Testing the configure server default port.""" sys.argv = ["/bin/qpc", "server", "config", "--host", "127.0.0.1"] CLI().main() config = read_server_config() - self.assertEqual(config["host"], "127.0.0.1") - self.assertEqual(config["port"], DEFAULT_PORT) + assert config["host"] == "127.0.0.1" + assert config["port"] == DEFAULT_PORT def test_invalid_configuration(self): """Test reading bad JSON on cli start.""" @@ -106,13 +113,13 @@ def test_invalid_configuration(self): sys.argv = ["/bin/qpc", "server", "config", "--host", "127.0.0.1"] CLI().main() config = read_server_config() - self.assertEqual(config["host"], "127.0.0.1") - self.assertEqual(config["port"], DEFAULT_PORT) + assert config["host"] == "127.0.0.1" + assert config["port"] == DEFAULT_PORT def test_run_command_no_config(self): """Test running command without config.""" write_server_config({}) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): sys.argv = ["/bin/qpc", "cred"] CLI().main() diff --git a/qpc/server/tests_login_host.py b/qpc/server/test_login_host.py similarity index 78% rename from qpc/server/tests_login_host.py rename to qpc/server/test_login_host.py index 22e7d42e..68bcad48 100644 --- a/qpc/server/tests_login_host.py +++ b/qpc/server/test_login_host.py @@ -1,11 +1,12 @@ """Test the CLI module.""" +import logging import sys -import unittest from argparse import ArgumentParser, Namespace # noqa: I100 from io import StringIO from unittest.mock import patch +import pytest import requests_mock from qpc import messages @@ -17,17 +18,16 @@ TMP_KEY = "/tmp/testkey" -class LoginCliTests(unittest.TestCase): +class TestLoginCli: """Class for testing the login server command for qpc.""" - @classmethod - def setUpClass(cls): + def setup_class(cls): """Set up test case.""" argument_parser = ArgumentParser() subparser = argument_parser.add_subparsers(dest="subcommand") cls.command = LoginHostCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" write_server_config(DEFAULT_CONFIG) # Temporarily disable stderr for these tests, CLI errors clutter up @@ -37,7 +37,7 @@ def setUp(self): self.login_url = get_server_location() + LOGIN_URI self.success_json = {"token": "a_token"} - def tearDown(self): + def teardown_method(self, _test_method): """Remove test setup.""" # Restore stderr sys.stderr = self.orig_stderr @@ -54,13 +54,13 @@ def test_login_bad_cred(self, do_mock_raw_input): mocker.post(self.login_url, status_code=400, json=error) args = Namespace(username="admin") do_mock_raw_input.return_value = "abc" - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(server_out): self.command.main(args) - self.assertTrue(e_msg in server_out.getvalue()) + assert e_msg in server_out.getvalue() @patch("getpass._raw_input") - def test_login_good(self, do_mock_raw_input): + def test_login_good(self, do_mock_raw_input, caplog): """Testing the login with good creds.""" with requests_mock.Mocker() as mocker, patch.object( self.command, "password", "password" @@ -68,13 +68,13 @@ def test_login_good(self, do_mock_raw_input): mocker.post(self.login_url, status_code=200, json=self.success_json) args = Namespace(username="admin") do_mock_raw_input.return_value = "abc" - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) - self.assertIn(messages.LOGIN_SUCCESS, log.output[-1]) + assert messages.LOGIN_SUCCESS in caplog.text @patch("builtins.input") @patch("getpass._raw_input") - def test_prompts_with_no_args(self, user_mock, pass_mock): + def test_prompts_with_no_args(self, user_mock, pass_mock, caplog): """Testing the login with no args passed.""" pass_mock.return_value = "abc" user_mock.return_value = "admin" @@ -82,16 +82,16 @@ def test_prompts_with_no_args(self, user_mock, pass_mock): mocker.post(self.login_url, status_code=200, json=self.success_json) args = Namespace() - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) - self.assertIn(messages.LOGIN_SUCCESS, log.output[-1]) + assert messages.LOGIN_SUCCESS in caplog.text - def test_no_prompts_with_args(self): + def test_no_prompts_with_args(self, caplog): """Testing no prompts with args passed.""" with requests_mock.Mocker() as mocker: mocker.post(self.login_url, status_code=200, json=self.success_json) args = Namespace(username="admin", password="pass") - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) - self.assertIn(messages.LOGIN_SUCCESS, log.output[-1]) + assert messages.LOGIN_SUCCESS in caplog.text diff --git a/qpc/server/tests_logout_host.py b/qpc/server/test_logout_host.py similarity index 85% rename from qpc/server/tests_logout_host.py rename to qpc/server/test_logout_host.py index 7e842add..b7f2eb06 100644 --- a/qpc/server/tests_logout_host.py +++ b/qpc/server/test_logout_host.py @@ -2,7 +2,6 @@ import os import sys -import unittest from argparse import ArgumentParser, Namespace import requests_mock @@ -13,17 +12,16 @@ from qpc.tests_utilities import HushUpStderr -class LogoutTests(unittest.TestCase): +class TestLogout: """Class for testing the logout host function.""" - @classmethod - def setUpClass(cls): + def setup_class(cls): """Set up test case.""" argument_parser = ArgumentParser() subparser = argument_parser.add_subparsers(dest="subcommand") cls.command = LogoutHostCommand(subparser) - def setUp(self): + def setup_method(self, _method): """Create test setup.""" # Temporarily disable stderr for these tests, CLI errors clutter up # nosetests command. @@ -31,7 +29,7 @@ def setUp(self): sys.stderr = HushUpStderr() utils.write_server_config({"host": "127.0.0.1", "port": 8000, "use_http": True}) - def tearDown(self): + def teardown_method(self, _method): """Remove test case setup.""" # Restore stderr sys.stderr = self.orig_stderr @@ -43,4 +41,4 @@ def test_success_logout(self): mocker.put(url, status_code=200) args = Namespace() self.command.main(args) - self.assertFalse(os.path.exists(utils.QPC_CLIENT_TOKEN)) + assert not os.path.exists(utils.QPC_CLIENT_TOKEN) diff --git a/qpc/server/tests_status.py b/qpc/server/test_status.py similarity index 81% rename from qpc/server/tests_status.py rename to qpc/server/test_status.py index 9a669945..119b2a7c 100644 --- a/qpc/server/tests_status.py +++ b/qpc/server/test_status.py @@ -1,13 +1,14 @@ """Test the CLI module.""" import json +import logging import os import sys import time -import unittest from argparse import ArgumentParser, Namespace from io import StringIO +import pytest import requests_mock from qpc import messages @@ -20,17 +21,16 @@ TMP_KEY = "/tmp/testkey" -class ServerStatusTests(unittest.TestCase): +class TestServerStatus: """Class for testing the server status command for qpc.""" - @classmethod - def setUpClass(cls): + def setup_class(cls): """Set up test case.""" argument_parser = ArgumentParser() subparser = argument_parser.add_subparsers(dest="subcommand") cls.command = ServerStatusCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" write_server_config(DEFAULT_CONFIG) # Temporarily disable stderr for these tests, CLI errors clutter up @@ -39,7 +39,7 @@ def setUp(self): self.test_json_filename = f"test_{time.time():.0f}.json" sys.stderr = HushUpStderr() - def tearDown(self): + def teardown_method(self, _test_method): """Remove test setup.""" # Restore stderr sys.stderr = self.orig_stderr @@ -48,7 +48,7 @@ def tearDown(self): except FileNotFoundError: pass - def test_download_server_status(self): + def test_download_server_status(self, caplog): """Testing recording server status command in a file.""" get_status_url = get_server_location() + STATUS_URI get_status_json_data = { @@ -60,14 +60,14 @@ def test_download_server_status(self): mocker.get(get_status_url, status_code=200, json=get_status_json_data) args = Namespace(path=self.test_json_filename) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.STATUS_SUCCESSFULLY_WRITTEN - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text with open(self.test_json_filename, "r", encoding="utf-8") as json_file: data = json_file.read() file_content_dict = json.loads(data) - self.assertDictEqual(get_status_json_data, file_content_dict) + assert get_status_json_data == file_content_dict def test_print_server_status(self): """Testing recording server status command in a file.""" @@ -85,19 +85,17 @@ def test_print_server_status(self): args = Namespace(path=None) with redirect_stdout(status_out): self.command.main(args) - self.assertDictEqual( - json.loads(status_out.getvalue().strip()), get_status_json_data - ) + assert json.loads(status_out.getvalue().strip()) == get_status_json_data def test_write_status_output_directory_not_exist(self): """Testing fail because output directory does not exist.""" - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): sys.argv = ["/bin/qpc", "server", "status", "--output-file", "/foo/bar/"] CLI().main() def test_write_status_output_file_empty(self): """Testing fail because output file empty.""" - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): sys.argv = ["/bin/qpc", "server", "status", "--output-file"] CLI().main() @@ -111,9 +109,7 @@ def test_status_unexpected_failure(self): mocker.get(get_status_url, status_code=400, json=get_status_json_data) args = Namespace(path=None) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(status_out): self.command.main(args) - self.assertEqual( - status_out.getvalue(), messages.SERVER_STATUS_FAILURE - ) + assert status_out.getvalue() == messages.SERVER_STATUS_FAILURE diff --git a/qpc/source/tests_source_add.py b/qpc/source/test_source_add.py similarity index 85% rename from qpc/source/tests_source_add.py rename to qpc/source/test_source_add.py index e1b03fe8..8dae81b6 100644 --- a/qpc/source/tests_source_add.py +++ b/qpc/source/test_source_add.py @@ -1,11 +1,12 @@ """Test the CLI module.""" +import logging import os import sys -import unittest from argparse import ArgumentParser, ArgumentTypeError, Namespace from io import StringIO +import pytest import requests import requests_mock @@ -22,17 +23,17 @@ TMP_HOSTFILE = "/tmp/testhostsfile" -class SourceAddCliTests(unittest.TestCase): +class TestSourceAddCli: """Class for testing the source add commands for qpc.""" @classmethod - def setUpClass(cls): + def setup_class(cls): """Set up test case.""" argument_parser = ArgumentParser() subparser = argument_parser.add_subparsers(dest="subcommand") cls.command = SourceAddCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" write_server_config(DEFAULT_CONFIG) # Temporarily disable stderr for these tests, CLI errors clutter up @@ -45,7 +46,7 @@ def setUp(self): test_hostfile.write("1.2.3.4\n") test_hostfile.write("1.2.3.[1:10]\n") - def tearDown(self): + def teardown_method(self, _test_method): """Remove test case setup.""" # Restore stderr sys.stderr = self.orig_stderr @@ -54,13 +55,13 @@ def tearDown(self): def test_add_req_args_err(self): """Testing the add source command required flags.""" - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): sys.argv = ["/bin/qpc", "source", "add", "--name", "source1"] CLI().main() def test_add_process_file(self): """Testing the add source command process file.""" - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): sys.argv = [ "/bin/qpc", "source", @@ -79,31 +80,31 @@ def test_add_process_file(self): def test_validate_port_string(self): """Testing the add source command with port validation non-integer.""" source_out = StringIO() - with self.assertRaises(ArgumentTypeError): + with pytest.raises(ArgumentTypeError): with redirect_stdout(source_out): validate_port("ff") - self.assertTrue("Port value ff" in source_out.getvalue()) + assert "Port value ff" in source_out.getvalue() def test_validate_port_bad_type(self): """Testing the add source command with port validation bad type.""" source_out = StringIO() - with self.assertRaises(ArgumentTypeError): + with pytest.raises(ArgumentTypeError): with redirect_stdout(source_out): validate_port(["ff"]) - self.assertTrue("Port value ff" in source_out.getvalue()) + assert "Port value ff" in source_out.getvalue() def test_validate_port_range_err(self): """Test the add source command with port validation out of range.""" source_out = StringIO() - with self.assertRaises(ArgumentTypeError): + with pytest.raises(ArgumentTypeError): with redirect_stdout(source_out): validate_port("65537") - self.assertTrue("Port value 65537" in source_out.getvalue()) + assert "Port value 65537" in source_out.getvalue() def test_validate_port_good(self): """Testing the add source command with port validation success.""" val = validate_port("80") - self.assertEqual(80, val) + assert val == 80 def test_add_source_name_dup(self): """Testing the add source command duplicate name.""" @@ -124,11 +125,11 @@ def test_add_source_name_dup(self): hosts=["1.2.3.4"], port=22, ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) self.command.main(args) - self.assertTrue( + assert ( "source with this name already exists." in source_out.getvalue() ) @@ -148,12 +149,12 @@ def test_add_source_cred_less(self): type="network", port=22, ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) - self.assertTrue( - "An error occurred while processing " - 'the "--cred" input' in source_out.getvalue() + assert ( + 'An error occurred while processing the "--cred" input' + in source_out.getvalue() ) def test_add_source_cred_err(self): @@ -170,12 +171,12 @@ def test_add_source_cred_err(self): type="network", port=22, ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) - self.assertTrue( - "An error occurred while processing " - 'the "--cred" input' in source_out.getvalue() + assert ( + 'An error occurred while processing the "--cred" input' + in source_out.getvalue() ) def test_add_source_ssl_err(self): @@ -192,10 +193,10 @@ def test_add_source_ssl_err(self): type="network", port=22, ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) - self.assertEqual(source_out.getvalue(), CONNECTION_ERROR_MSG) + assert source_out.getvalue() == CONNECTION_ERROR_MSG def test_add_source_conn_err(self): """Testing the add source command with a connection error.""" @@ -211,15 +212,15 @@ def test_add_source_conn_err(self): type="network", port=22, ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) - self.assertEqual(source_out.getvalue(), CONNECTION_ERROR_MSG) + assert source_out.getvalue() == CONNECTION_ERROR_MSG ################################################## # Network Source Test ################################################## - def test_add_source_net_one_host(self): + def test_add_source_net_one_host(self, caplog): """Testing add network source command successfully with one host.""" get_cred_url = get_server_location() + CREDENTIAL_URI + "?name=cred1" cred_results = [{"id": 1, "name": "cred1"}] @@ -236,12 +237,12 @@ def test_add_source_net_one_host(self): type="network", port=22, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SOURCE_ADDED % "source1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text - def test_add_source_net_valid_hosts(self): + def test_add_source_net_valid_hosts(self, caplog): """Testing add network source command with hosts in valid formats.""" get_cred_url = get_server_location() + CREDENTIAL_URI + "?name=cred1" cred_results = [{"id": 1, "name": "cred1"}] @@ -267,12 +268,12 @@ def test_add_source_net_valid_hosts(self): type="network", port=22, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SOURCE_ADDED % "source1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text - def test_add_source_with_paramiko(self): + def test_add_source_with_paramiko(self, caplog): """Testing add network source command with use_paramiko set to true.""" get_cred_url = get_server_location() + CREDENTIAL_URI + "?name=cred1" cred_results = [{"id": 1, "name": "cred1"}] @@ -291,10 +292,10 @@ def test_add_source_with_paramiko(self): port=22, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SOURCE_ADDED % "source1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text def test_add_source_with_paramiko_and_ssl(self): """Testing add network source command with use_paramiko set to true.""" @@ -316,11 +317,11 @@ def test_add_source_with_paramiko_and_ssl(self): type="network", port=22, ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) - def test_add_source_one_excludehost(self): + def test_add_source_one_excludehost(self, caplog): """Testing the add network source command with one exclude host.""" get_cred_url = get_server_location() + CREDENTIAL_URI + "?name=cred1" cred_results = [{"id": 1, "name": "cred1"}] @@ -338,12 +339,12 @@ def test_add_source_one_excludehost(self): exclude_hosts=["1.2.3.4"], port=22, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SOURCE_ADDED % "source1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text - def test_add_source_exclude_hosts(self): + def test_add_source_exclude_hosts(self, caplog): """Testing add network source command with many valid exclude hosts.""" get_cred_url = get_server_location() + CREDENTIAL_URI + "?name=cred1" cred_results = [{"id": 1, "name": "cred1"}] @@ -376,15 +377,15 @@ def test_add_source_exclude_hosts(self): type="network", port=22, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SOURCE_ADDED % "source1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text ################################################## # Vcenter Source Test ################################################## - def test_add_source_vc(self): + def test_add_source_vc(self, caplog): """Testing the add vcenter source command successfully.""" get_cred_url = get_server_location() + CREDENTIAL_URI + "?name=cred1" cred_results = [{"id": 1, "name": "cred1"}] @@ -397,12 +398,12 @@ def test_add_source_vc(self): args = Namespace( name="source1", cred=["cred1"], hosts=["1.2.3.4"], type="vcenter" ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SOURCE_ADDED % "source1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text - def test_add_source_with_ssl_params(self): + def test_add_source_with_ssl_params(self, caplog): """Testing add vcenter source command with all ssl params.""" get_cred_url = get_server_location() + CREDENTIAL_URI + "?name=cred1" cred_results = [{"id": 1, "name": "cred1"}] @@ -422,15 +423,15 @@ def test_add_source_with_ssl_params(self): type="vcenter", port=22, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SOURCE_ADDED % "source1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text ################################################## # Satellite Source Test ################################################## - def test_add_source_sat(self): + def test_add_source_sat(self, caplog): """Testing the add satellite source command successfully.""" get_cred_url = get_server_location() + CREDENTIAL_URI + "?name=cred1" cred_results = [{"id": 1, "name": "cred1"}] @@ -443,12 +444,12 @@ def test_add_source_sat(self): args = Namespace( name="source1", cred=["cred1"], hosts=["1.2.3.4"], type="satellite" ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SOURCE_ADDED % "source1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text - def test_add_source_sat_no_ssl(self): + def test_add_source_sat_no_ssl(self, caplog): """Testing the add satellite with ssl_cert_verify set to false.""" get_cred_url = get_server_location() + CREDENTIAL_URI + "?name=cred1" cred_results = [{"id": 1, "name": "cred1"}] @@ -465,7 +466,7 @@ def test_add_source_sat_no_ssl(self): type="satellite", ssl_cert_verify="false", ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SOURCE_ADDED % "source1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text diff --git a/qpc/source/tests_source_clear.py b/qpc/source/test_source_clear.py similarity index 83% rename from qpc/source/tests_source_clear.py rename to qpc/source/test_source_clear.py index 6eae1c30..9c070b7f 100644 --- a/qpc/source/tests_source_clear.py +++ b/qpc/source/test_source_clear.py @@ -1,10 +1,11 @@ """Test the CLI module.""" +import logging import sys -import unittest from argparse import ArgumentParser, Namespace from io import StringIO +import pytest import requests import requests_mock @@ -16,17 +17,16 @@ from qpc.utils import get_server_location, write_server_config -class SourceClearCliTests(unittest.TestCase): +class TestSourceClearCli: """Class for testing the source clear commands for qpc.""" - @classmethod - def setUpClass(cls): + def setup_class(cls): """Set up test case.""" argument_parser = ArgumentParser() subparser = argument_parser.add_subparsers(dest="subcommand") cls.command = SourceClearCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" write_server_config(DEFAULT_CONFIG) # Temporarily disable stderr for these tests, CLI errors clutter up @@ -34,7 +34,7 @@ def setUp(self): self.orig_stderr = sys.stderr sys.stderr = HushUpStderr() - def tearDown(self): + def teardown_method(self, _test_method): """Remove test setup.""" # Restore stderr sys.stderr = self.orig_stderr @@ -47,10 +47,10 @@ def test_clear_source_ssl_err(self): mocker.get(url, exc=requests.exceptions.SSLError) args = Namespace(name="source1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) - self.assertEqual(source_out.getvalue(), CONNECTION_ERROR_MSG) + assert source_out.getvalue() == CONNECTION_ERROR_MSG def test_clear_source_conn_err(self): """Testing the clear source command with a connection error.""" @@ -60,10 +60,10 @@ def test_clear_source_conn_err(self): mocker.get(url, exc=requests.exceptions.ConnectTimeout) args = Namespace(name="source1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) - self.assertEqual(source_out.getvalue(), CONNECTION_ERROR_MSG) + assert source_out.getvalue() == CONNECTION_ERROR_MSG def test_clear_source_internal_err(self): """Testing the clear source command with an internal error.""" @@ -73,10 +73,10 @@ def test_clear_source_internal_err(self): mocker.get(url, status_code=500, json={"error": ["Server Error"]}) args = Namespace(name="source1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) - self.assertEqual(source_out.getvalue(), "Server Error") + assert source_out.getvalue() == "Server Error" def test_clear_source_empty(self): """Testing the clear source command successfully with empty data.""" @@ -86,14 +86,12 @@ def test_clear_source_empty(self): mocker.get(url, status_code=200, json={"count": 0}) args = Namespace(name="source1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) - self.assertEqual( - source_out.getvalue(), 'Source "source1" was not found\n' - ) + assert source_out.getvalue() == 'Source "source1" was not found\n' - def test_clear_by_name(self): + def test_clear_by_name(self, caplog): """Testing the clear source command. Successfully with stubbed data when specifying a name @@ -114,10 +112,10 @@ def test_clear_by_name(self): mocker.delete(delete_url, status_code=204) args = Namespace(name="source1") - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SOURCE_REMOVED % "source1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text def test_clear_by_name_err(self): """Test the clear source command successfully. @@ -142,11 +140,11 @@ def test_clear_by_name_err(self): mocker.delete(delete_url, status_code=500, json=err_data) args = Namespace(name="source1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) expected = 'Failed to remove source "source1"' - self.assertTrue(expected in source_out.getvalue()) + assert expected in source_out.getvalue() def test_clear_all_empty(self): """Test the clear source command successfully. @@ -159,11 +157,11 @@ def test_clear_all_empty(self): mocker.get(get_url, status_code=200, json={"count": 0}) args = Namespace(name=None) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) expected = "No sources exist to be removed\n" - self.assertEqual(source_out.getvalue(), expected) + assert source_out.getvalue() == expected def test_clear_all_with_error(self): """Testing the clear source command successfully. @@ -188,7 +186,7 @@ def test_clear_all_with_error(self): mocker.delete(delete_url, status_code=500, json=err_data) args = Namespace(name=None) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) expected = ( @@ -196,9 +194,9 @@ def test_clear_all_with_error(self): " error occurred removing the following" " credentials:" ) - self.assertTrue(expected in source_out.getvalue()) + assert expected in source_out.getvalue() - def test_clear_all(self): + def test_clear_all(self, caplog): """Testing the clear source command successfully with stubbed data.""" get_url = get_server_location() + SOURCE_URI delete_url = get_server_location() + SOURCE_URI + "1/" @@ -216,6 +214,6 @@ def test_clear_all(self): mocker.delete(delete_url, status_code=204) args = Namespace(name=None) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) - self.assertIn(messages.SOURCE_CLEAR_ALL_SUCCESS, log.output[-1]) + assert messages.SOURCE_CLEAR_ALL_SUCCESS in caplog.text diff --git a/qpc/source/tests_source_edit.py b/qpc/source/test_source_edit.py similarity index 87% rename from qpc/source/tests_source_edit.py rename to qpc/source/test_source_edit.py index 37763ce3..30e5af0b 100644 --- a/qpc/source/tests_source_edit.py +++ b/qpc/source/test_source_edit.py @@ -1,11 +1,12 @@ """Test the CLI module.""" +import logging import os import sys -import unittest from argparse import ArgumentParser, Namespace from io import StringIO +import pytest import requests import requests_mock @@ -21,7 +22,7 @@ TMP_HOSTFILE = "/tmp/testhostsfile" -class SourceEditCliTests(unittest.TestCase): +class TestSourceEditCli: """Class for testing the source edit commands for qpc.""" def _init_command(self): @@ -30,7 +31,7 @@ def _init_command(self): subparser = argument_parser.add_subparsers(dest="subcommand") return SourceEditCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" # different from most other test cases where command is initialized once per # class, this one requires to be initialized for each test method because @@ -48,7 +49,7 @@ def setUp(self): test_hostfile.write("1.2.3.4\n") test_hostfile.write("1.2.3.[1:10]\n") - def tearDown(self): + def teardown_method(self, _test_method): """Remove test setup.""" # Restore stderr sys.stderr = self.orig_stderr @@ -58,18 +59,18 @@ def tearDown(self): def test_edit_req_args_err(self): """Testing the add edit command required flags.""" source_out = StringIO() - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): sys.argv = ["/bin/qpc", "source", "edit", "--name", "source1"] CLI().main() - self.assertEqual( - source_out.getvalue(), - "No arguments provided to edit source source1", + assert ( + source_out.getvalue() + == "No arguments provided to edit source source1" ) def test_edit_process_file(self): """Testing the add source command process file.""" - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): sys.argv = [ "/bin/qpc", "source", @@ -89,7 +90,7 @@ def test_read_input(self): """Test the input reading mechanism.""" vals = read_in_file(TMP_HOSTFILE) expected = ["1.2.3.4", "1.2.3.[1:10]"] - self.assertEqual(expected, vals) + assert expected == vals def test_edit_source_none(self): """Testing the edit cred command for none existing cred.""" @@ -100,11 +101,11 @@ def test_edit_source_none(self): args = Namespace( name="source_none", hosts=["1.2.3.4"], cred=["credential1"], port=22 ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) self.command.main(args) - self.assertTrue( + assert ( 'Source "source_none" does not exist' in source_out.getvalue() ) @@ -117,10 +118,10 @@ def test_edit_source_ssl_err(self): args = Namespace( name="source1", hosts=["1.2.3.4"], cred=["credential1"], port=22 ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) - self.assertEqual(source_out.getvalue(), CONNECTION_ERROR_MSG) + assert source_out.getvalue() == CONNECTION_ERROR_MSG def test_edit_source_conn_err(self): """Testing the edit source command with a connection error.""" @@ -132,15 +133,15 @@ def test_edit_source_conn_err(self): args = Namespace( name="source1", hosts=["1.2.3.4"], cred=["credential1"], port=22 ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) - self.assertEqual(source_out.getvalue(), CONNECTION_ERROR_MSG) + assert source_out.getvalue() == CONNECTION_ERROR_MSG ################################################## # Network Source Test ################################################## - def test_edit_net_source(self): + def test_edit_net_source(self, caplog): """Testing the edit network source command successfully.""" url_get_cred = get_server_location() + CREDENTIAL_URI + "?name=credential1" url_get_source = get_server_location() + SOURCE_URI + "?name=source1" @@ -171,12 +172,12 @@ def test_edit_net_source(self): cred=["credential1"], port=22, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SOURCE_UPDATED % "source1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text - def test_edit_source_exclude_host(self): + def test_edit_source_exclude_host(self, caplog): """Testing edit network source command by adding an excluded host.""" url_get_cred = get_server_location() + CREDENTIAL_URI + "?name=credential1" url_get_source = get_server_location() + SOURCE_URI + "?name=source1" @@ -206,15 +207,15 @@ def test_edit_source_exclude_host(self): cred=["credential1"], port=22, ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SOURCE_UPDATED % "source1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text ################################################## # Vcenter Source Test ################################################## - def test_edit_vc_source(self): + def test_edit_vc_source(self, caplog): """Testing the edit vcenter source command successfully.""" url_get_cred = get_server_location() + CREDENTIAL_URI + "?name=credential1" url_get_source = get_server_location() + SOURCE_URI + "?name=source1" @@ -238,12 +239,12 @@ def test_edit_vc_source(self): mocker.patch(url_patch, status_code=200) args = Namespace(name="source1", hosts=["1.2.3.5"], cred=["credential1"]) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SOURCE_UPDATED % "source1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text - def test_edit_disable_ssl(self): + def test_edit_disable_ssl(self, caplog): """Testing that you can edit the disable-ssl arg successfully.""" url_get_cred = get_server_location() + CREDENTIAL_URI + "?name=credential1" url_get_source = get_server_location() + SOURCE_URI + "?name=source1" @@ -273,12 +274,12 @@ def test_edit_disable_ssl(self): cred=["credential1"], disable_ssl="True", ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SOURCE_UPDATED % "source1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text - def test_edit_ssl_protocol(self): + def test_edit_ssl_protocol(self, caplog): """Testing that you can edit the ssl_protocol arg successfully.""" url_get_cred = get_server_location() + CREDENTIAL_URI + "?name=credential1" url_get_source = get_server_location() + SOURCE_URI + "?name=source1" @@ -308,10 +309,10 @@ def test_edit_ssl_protocol(self): cred=["credential1"], ssl_protocol="SSLv23", ) - with self.assertLogs(level="INFO") as log: + with caplog.at_level(logging.INFO): self.command.main(args) expected_message = messages.SOURCE_UPDATED % "source1" - self.assertIn(expected_message, log.output[-1]) + assert expected_message in caplog.text def test_edit_source_no_val(self): """Testing the edit source command with a server error.""" @@ -323,12 +324,10 @@ def test_edit_source_no_val(self): args = Namespace( name="source1", hosts=["1.2.3.4"], cred=["credential1"], port=22 ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) - self.assertEqual( - source_out.getvalue(), messages.SERVER_INTERNAL_ERROR - ) + assert source_out.getvalue() == messages.SERVER_INTERNAL_ERROR def test_edit_source_cred_nf(self): """Testing the edit source command where cred is not found.""" @@ -360,12 +359,12 @@ def test_edit_source_cred_nf(self): cred=["credential1", "cred2"], port=22, ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) - self.assertTrue( - "An error occurred while processing " - 'the "--cred" input' in source_out.getvalue() + assert ( + 'An error occurred while processing the "--cred" input' + in source_out.getvalue() ) def test_edit_source_cred_err(self): @@ -394,10 +393,10 @@ def test_edit_source_cred_err(self): cred=["credential1", "cred2"], port=22, ) - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) - self.assertTrue( - "An error occurred while processing " - 'the "--cred" input' in source_out.getvalue() + assert ( + 'An error occurred while processing the "--cred" input' + in source_out.getvalue() ) diff --git a/qpc/source/tests_source_list.py b/qpc/source/test_source_list.py similarity index 84% rename from qpc/source/tests_source_list.py rename to qpc/source/test_source_list.py index e627922e..e30a64e1 100644 --- a/qpc/source/tests_source_list.py +++ b/qpc/source/test_source_list.py @@ -1,11 +1,12 @@ """Test the CLI module.""" +import logging import sys -import unittest from argparse import ArgumentParser, Namespace # noqa: I100 from io import StringIO from unittest.mock import ANY, patch +import pytest import requests import requests_mock @@ -17,17 +18,16 @@ from qpc.utils import get_server_location, write_server_config -class SourceListCliTests(unittest.TestCase): +class TestSourceListCli: """Class for testing the source list commands for qpc.""" - @classmethod - def setUpClass(cls): + def setup_class(cls): """Set up test case.""" argument_parser = ArgumentParser() subparser = argument_parser.add_subparsers(dest="subcommand") cls.command = SourceListCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" write_server_config(DEFAULT_CONFIG) # Temporarily disable stderr for these tests, CLI errors clutter up @@ -35,7 +35,7 @@ def setUp(self): self.orig_stderr = sys.stderr sys.stderr = HushUpStderr() - def tearDown(self): + def teardown_method(self, _test_method): """Remove test setup.""" # Restore stderr sys.stderr = self.orig_stderr @@ -47,10 +47,10 @@ def test_list_source_ssl_err(self): with requests_mock.Mocker() as mocker: mocker.get(url, exc=requests.exceptions.SSLError) args = Namespace() - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) - self.assertEqual(source_out.getvalue(), CONNECTION_ERROR_MSG) + assert source_out.getvalue() == CONNECTION_ERROR_MSG def test_list_source_conn_err(self): """Testing the list source command with a connection error.""" @@ -59,10 +59,10 @@ def test_list_source_conn_err(self): with requests_mock.Mocker() as mocker: mocker.get(url, exc=requests.exceptions.ConnectTimeout) args = Namespace() - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) - self.assertEqual(source_out.getvalue(), CONNECTION_ERROR_MSG) + assert source_out.getvalue() == CONNECTION_ERROR_MSG def test_list_source_internal_err(self): """Testing the list source command with an internal error.""" @@ -71,20 +71,20 @@ def test_list_source_internal_err(self): with requests_mock.Mocker() as mocker: mocker.get(url, status_code=500, json={"error": ["Server Error"]}) args = Namespace() - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) - self.assertEqual(source_out.getvalue(), "Server Error") + assert source_out.getvalue() == "Server Error" - def test_list_source_empty(self): + def test_list_source_empty(self, caplog): """Testing the list source command successfully with empty data.""" url = get_server_location() + SOURCE_URI with requests_mock.Mocker() as mocker: mocker.get(url, status_code=200, json={"count": 0}) args = Namespace() - with self.assertLogs(level="ERROR") as log: + with caplog.at_level(logging.ERROR): self.command.main(args) - self.assertIn(messages.SOURCE_LIST_NO_SOURCES, log.output[-1]) + assert messages.SOURCE_LIST_NO_SOURCES in caplog.text @patch("builtins.input", return_value="yes") def test_list_source_data(self, b_input): @@ -111,9 +111,9 @@ def test_list_source_data(self, b_input): '[{"credentials":[{"id":1,"name":"cred1"}],' '"hosts":["1.2.3.4"],"id":1,"name":"source1"}]' ) - self.assertEqual( - source_out.getvalue().replace("\n", "").replace(" ", "").strip(), - expected + expected, + assert ( + source_out.getvalue().replace("\n", "").replace(" ", "").strip() + == expected + expected ) b_input.assert_called_with(ANY) @@ -140,7 +140,7 @@ def test_list_filtered_source_data(self): '"hosts":["1.2.3.4"],"id":1,"name":"source1",' '"source_type":"network"}]' ) - self.assertEqual( - source_out.getvalue().replace("\n", "").replace(" ", "").strip(), - expected, + assert ( + source_out.getvalue().replace("\n", "").replace(" ", "").strip() + == expected ) diff --git a/qpc/source/tests_source_show.py b/qpc/source/test_source_show.py similarity index 82% rename from qpc/source/tests_source_show.py rename to qpc/source/test_source_show.py index 1517f6aa..9c799dd9 100644 --- a/qpc/source/tests_source_show.py +++ b/qpc/source/test_source_show.py @@ -1,10 +1,10 @@ """Test the CLI module.""" import sys -import unittest from argparse import ArgumentParser, Namespace from io import StringIO +import pytest import requests import requests_mock @@ -15,17 +15,16 @@ from qpc.utils import get_server_location, write_server_config -class SourceShowCliTests(unittest.TestCase): +class TestSourceShowCli: """Class for testing the source show commands for qpc.""" - @classmethod - def setUpClass(cls): + def setup_class(cls): """Set up test case.""" argument_parser = ArgumentParser() subparser = argument_parser.add_subparsers(dest="subcommand") cls.command = SourceShowCommand(subparser) - def setUp(self): + def setup_method(self, _test_method): """Create test setup.""" # Temporarily disable stderr for these tests, CLI errors clutter up self.orig_stderr = sys.stderr @@ -33,7 +32,7 @@ def setUp(self): write_server_config({"host": "127.0.0.1", "port": 8000, "use_http": True}) self.base_url = get_server_location() - def tearDown(self): + def teardown_method(self, _test_method): """Remove test setup.""" # Restore stderr sys.stderr = self.orig_stderr @@ -45,10 +44,10 @@ def test_show_source_ssl_err(self): with requests_mock.Mocker() as mocker: mocker.get(url, exc=requests.exceptions.SSLError) args = Namespace(name="source1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) - self.assertEqual(source_out.getvalue(), CONNECTION_ERROR_MSG) + assert source_out.getvalue() == CONNECTION_ERROR_MSG def test_show_source_conn_err(self): """Testing the show source command with a connection error.""" @@ -57,10 +56,10 @@ def test_show_source_conn_err(self): with requests_mock.Mocker() as mocker: mocker.get(url, exc=requests.exceptions.ConnectTimeout) args = Namespace(name="source1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) - self.assertEqual(source_out.getvalue(), CONNECTION_ERROR_MSG) + assert source_out.getvalue() == CONNECTION_ERROR_MSG def test_show_source_internal_err(self): """Testing the show source command with an internal error.""" @@ -69,10 +68,10 @@ def test_show_source_internal_err(self): with requests_mock.Mocker() as mocker: mocker.get(url, status_code=500, json={"error": ["Server Error"]}) args = Namespace(name="source1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) - self.assertEqual(source_out.getvalue(), "Server Error") + assert source_out.getvalue() == "Server Error" def test_show_source_empty(self): """Testing the show source command successfully with empty data.""" @@ -81,12 +80,10 @@ def test_show_source_empty(self): with requests_mock.Mocker() as mocker: mocker.get(url, status_code=200, json={"count": 0}) args = Namespace(name="source1") - with self.assertRaises(SystemExit): + with pytest.raises(SystemExit): with redirect_stdout(source_out): self.command.main(args) - self.assertEqual( - source_out.getvalue(), 'Source "source1" does not exist\n' - ) + assert source_out.getvalue() == 'Source "source1" does not exist\n' def test_show_source_data(self): """Testing the show source command successfully with stubbed data.""" @@ -109,7 +106,7 @@ def test_show_source_data(self): '{"credentials":[{"id":1,"name":"cred1"}],' '"hosts":["1.2.3.4"],"id":1,"name":"source1"}' ) - self.assertEqual( - source_out.getvalue().replace("\n", "").replace(" ", "").strip(), - expected, + assert ( + source_out.getvalue().replace("\n", "").replace(" ", "").strip() + == expected ) diff --git a/qpc/tests_qpc_utils.py b/qpc/test_qpc_utils.py similarity index 84% rename from qpc/tests_qpc_utils.py rename to qpc/test_qpc_utils.py index 18d21ee8..b9f1781c 100644 --- a/qpc/tests_qpc_utils.py +++ b/qpc/test_qpc_utils.py @@ -1,12 +1,11 @@ """Test the utils module.""" import os -import unittest from qpc import utils -class UtilsTests(unittest.TestCase): +class TestUtils: """Class for testing the utils module qpc.""" def test_read_client_token(self): @@ -18,9 +17,9 @@ def test_read_client_token(self): token_json = {"token": expected_token} utils.write_client_token(token_json) token = utils.read_client_token() - self.assertTrue(isinstance(token, str)) + assert isinstance(token, str) if check_value: - self.assertEqual(token, expected_token) + assert token == expected_token def test_extract_json_from_tarfile(self): """Test extracting json from tarfile.""" @@ -35,4 +34,4 @@ def test_extract_json_from_tarfile(self): test_file = {"test.json": report_json} fileobj = utils.create_tar_buffer(test_file) json = utils.extract_json_from_tar(fileobj, print_pretty=False) - self.assertEqual(json, report_json) + assert json == report_json