From ab2b88ef5b20b87ac99c19257f72a2561c5bc7a8 Mon Sep 17 00:00:00 2001 From: kiblik <5609770+kiblik@users.noreply.github.com> Date: Fri, 1 Nov 2024 19:11:29 +0100 Subject: [PATCH] Ruff: Add and fix S101 (#11066) --- dojo/middleware.py | 16 ++++++---- ruff.toml | 2 +- tests/Import_scanner_test.py | 8 ++--- tests/notifications_test.py | 41 +++++++++++++------------- unittests/test_rest_framework.py | 50 ++++++++++++++++++-------------- 5 files changed, 63 insertions(+), 54 deletions(-) diff --git a/dojo/middleware.py b/dojo/middleware.py index 29eff445b3..9fcb8a51db 100644 --- a/dojo/middleware.py +++ b/dojo/middleware.py @@ -35,12 +35,16 @@ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): - assert hasattr(request, "user"), "The Login Required middleware\ - requires authentication middleware to be installed. Edit your\ - MIDDLEWARE_CLASSES setting to insert\ - 'django.contrib.auth.middleware.AuthenticationMiddleware'. If that doesn't\ - work, ensure your TEMPLATE_CONTEXT_PROCESSORS setting includes\ - 'django.core.context_processors.auth'." + if not hasattr(request, "user"): + msg = ( + "The Login Required middleware " + "requires authentication middleware to be installed. Edit your " + "MIDDLEWARE_CLASSES setting to insert " + "'django.contrib.auth.middleware.AuthenticationMiddleware'. If that doesn't " + "work, ensure your TEMPLATE_CONTEXT_PROCESSORS setting includes " + "'django.core.context_processors.auth'." + ) + raise AttributeError(msg) if not request.user.is_authenticated: path = request.path_info.lstrip("/") if not any(m.match(path) for m in EXEMPT_URLS): diff --git a/ruff.toml b/ruff.toml index ac0f0ece1e..0f3ede2f2c 100644 --- a/ruff.toml +++ b/ruff.toml @@ -41,7 +41,7 @@ select = [ "UP", "YTT", "ASYNC", - "S2", "S5", "S7", + "S101", "S2", "S5", "S7", "FBT001", "FBT003", "A003", "A004", "A006", "COM", diff --git a/tests/Import_scanner_test.py b/tests/Import_scanner_test.py index b1597e9583..3006393aec 100644 --- a/tests/Import_scanner_test.py +++ b/tests/Import_scanner_test.py @@ -54,7 +54,7 @@ def test_check_test_file(self): logger.info("https://github.com/DefectDojo/sample-scan-files\n") for test in missing_tests: logger.info(test) - assert len(missing_tests) == 0 + self.assertEqual(len(missing_tests), 0) def test_check_for_forms(self): forms_path = dir_path[:-5] + "dojo/forms.py" @@ -91,7 +91,7 @@ def test_check_for_forms(self): logger.info("https://github.com/DefectDojo/django-DefectDojo/blob/master/dojo/forms.py\n") for tool in missing_forms: logger.info(tool) - assert len(missing_forms) == 0 + self.assertEqual(len(missing_forms), 0) @unittest.skip("Deprecated since Dynamic Parser infrastructure") def test_check_for_options(self): @@ -131,7 +131,7 @@ def test_check_for_options(self): logger.info("https://github.com/DefectDojo/django-DefectDojo/blob/master/dojo/templates/dojo/import_scan_results.html\n") for tool in missing_templates: logger.info(tool) - assert len(missing_templates) == 0 + self.assertEqual(len(missing_templates), 0) def test_engagement_import_scan_result(self): driver = self.driver @@ -216,7 +216,7 @@ def test_engagement_import_scan_result(self): logger.info("https://github.com/DefectDojo/sample-scan-files\n") for test in failed_tests: logger.info(test) - assert len(failed_tests) == 0 + self.assertEqual(len(failed_tests), 0) def tearDown(self): super().tearDown(self) diff --git a/tests/notifications_test.py b/tests/notifications_test.py index e64527cec9..d71067ce68 100644 --- a/tests/notifications_test.py +++ b/tests/notifications_test.py @@ -41,11 +41,13 @@ def test_disable_personal_notification(self): self.disable_notification() driver.get(self.base_url + "notifications") + in_place = False try: driver.find_element(By.XPATH, f"//input[@name='product_added' and @value='{self.type}']") - assert False + in_place = True except NoSuchElementException: - assert True + in_place = False + self.assertFalse(in_place) def test_enable_personal_notification(self): # Login to the site. Password will have to be modified @@ -56,13 +58,9 @@ def test_enable_personal_notification(self): driver.get(self.base_url + "notifications") try: driver.find_element(By.XPATH, f"//input[@name='product_added' and @value='{self.type}']") - assert True except NoSuchElementException: - if self.type == "msteams": - # msteam should be not in personal notifications - assert True - else: - assert False + # msteam should be not in personal notifications + self.assertEqual(self.type, "msteams") def test_disable_system_notification(self): # Login to the site. Password will have to be modified @@ -72,11 +70,13 @@ def test_disable_system_notification(self): self.disable_notification() driver.get(self.base_url + "notifications/system") + in_place = False try: driver.find_element(By.XPATH, f"//input[@name='product_added' and @value='{self.type}']") - assert False + in_place = True except NoSuchElementException: - assert True + in_place = False + self.assertFalse(in_place) def test_enable_system_notification(self): # Login to the site. Password will have to be modified @@ -84,12 +84,13 @@ def test_enable_system_notification(self): driver = self.driver self.enable_notification() - driver.get(self.base_url + "notifications/system") + in_place = False try: driver.find_element(By.XPATH, f"//input[@name='product_added' and @value='{self.type}']") - assert True + in_place = True except NoSuchElementException: - assert False + in_place = False + self.assertFalse(in_place) def test_disable_template_notification(self): # Login to the site. Password will have to be modified @@ -99,11 +100,13 @@ def test_disable_template_notification(self): self.disable_notification() driver.get(self.base_url + "notifications/template") + in_place = False try: driver.find_element(By.XPATH, f"//input[@name='product_added' and @value='{self.type}']") - assert False + in_place = True except NoSuchElementException: - assert True + in_place = False + self.assertFalse(in_place) def test_enable_template_notification(self): # Login to the site. Password will have to be modified @@ -114,13 +117,9 @@ def test_enable_template_notification(self): driver.get(self.base_url + "notifications/template") try: driver.find_element(By.XPATH, f"//input[@name='product_added' and @value='{self.type}']") - assert True except NoSuchElementException: - if self.type == "msteams": - # msteam should be not in personal notifications - assert True - else: - assert False + # msteam should be not in personal notifications + self.assertEqual(self.type, "msteams") def test_user_mail_notifications_change(self): # Login to the site. Password will have to be modified diff --git a/unittests/test_rest_framework.py b/unittests/test_rest_framework.py index 4021efc121..8b2c75e762 100644 --- a/unittests/test_rest_framework.py +++ b/unittests/test_rest_framework.py @@ -342,7 +342,8 @@ def _check(schema, obj): self._errors = [] self._prefix = [] _check(schema, obj) - assert not self._has_failed, "\n" + "\n".join(self._errors) + "\nFailed with " + str(len(self._errors)) + " errors" + if self._has_failed: + raise AssertionError("\n" + "\n".join(self._errors) + "\nFailed with " + str(len(self._errors)) + " errors") class TestType(Enum): @@ -1207,15 +1208,15 @@ def test_duplicate(self): result = self.client.get(self.url + "2/") self.assertEqual(result.status_code, status.HTTP_200_OK, "Could not check new duplicate") result_json = result.json() - assert result_json["duplicate"] - assert result_json["duplicate_finding"] == 3 + self.assertTrue(result_json["duplicate"]) + self.assertEqual(result_json["duplicate_finding"], 3) # Check duplicate status result = self.client.get(self.url + "3/duplicate/") - assert result.status_code == status.HTTP_200_OK, "Could not check duplicate status" + self.assertEqual(result.status_code, status.HTTP_200_OK, "Could not check duplicate status") result_json = result.json() # Should return all duplicates for id=3 - assert set(x["id"] for x in result_json) == {2, 4, 5, 6} # noqa: C401 + self.assertEqual({x["id"] for x in result_json}, {2, 4, 5, 6}) # Reset duplicate result = self.client.post(self.url + "2/duplicate/reset/") @@ -1223,44 +1224,44 @@ def test_duplicate(self): new_result = self.client.get(self.url + "2/") self.assertEqual(result.status_code, status.HTTP_204_NO_CONTENT, "Could not check reset duplicate status") result_json = new_result.json() - assert not result_json["duplicate"] - assert result_json["duplicate_finding"] is None + self.assertFalse(result_json["duplicate"]) + self.assertIsNone(result_json["duplicate_finding"]) def test_filter_steps_to_reproduce(self): # Confirm initial data result = self.client.get(self.url + "?steps_to_reproduce=lorem") self.assertEqual(result.status_code, status.HTTP_200_OK, "Could not filter on steps_to_reproduce") result_json = result.json() - assert result_json["count"] == 0 + self.assertEqual(result_json["count"], 0) # Set steps to reproduce result = self.client.patch(self.url + "2/", data={"steps_to_reproduce": "Lorem ipsum dolor sit amet"}) self.assertEqual(result.status_code, status.HTTP_200_OK, "Could not patch finding with steps to reproduce") - assert result.json()["steps_to_reproduce"] == "Lorem ipsum dolor sit amet" + self.assertEqual(result.json()["steps_to_reproduce"], "Lorem ipsum dolor sit amet") result = self.client.patch(self.url + "3/", data={"steps_to_reproduce": "Ut enim ad minim veniam"}) self.assertEqual(result.status_code, status.HTTP_200_OK, "Could not patch finding with steps to reproduce") - assert result.json()["steps_to_reproduce"] == "Ut enim ad minim veniam" + self.assertEqual(result.json()["steps_to_reproduce"], "Ut enim ad minim veniam") # Test result = self.client.get(self.url + "?steps_to_reproduce=lorem") self.assertEqual(result.status_code, status.HTTP_200_OK, "Could not filter on steps_to_reproduce") result_json = result.json() - assert result_json["count"] == 1 - assert result_json["results"][0]["id"] == 2 - assert result_json["results"][0]["steps_to_reproduce"] == "Lorem ipsum dolor sit amet" + self.assertEqual(result_json["count"], 1) + self.assertEqual(result_json["results"][0]["id"], 2) + self.assertEqual(result_json["results"][0]["steps_to_reproduce"], "Lorem ipsum dolor sit amet") # Set steps to reproduce result = self.client.patch(self.url + "2/", data={"steps_to_reproduce": ""}) self.assertEqual(result.status_code, status.HTTP_200_OK, "Could not patch finding with steps to reproduce") - assert result.json()["steps_to_reproduce"] == "" + self.assertEqual(result.json()["steps_to_reproduce"], "") result = self.client.patch(self.url + "3/", data={"steps_to_reproduce": ""}) self.assertEqual(result.status_code, status.HTTP_200_OK, "Could not patch finding with steps to reproduce") - assert result.json()["steps_to_reproduce"] == "" + self.assertEqual(result.json()["steps_to_reproduce"], "") def test_severity_validation(self): result = self.client.patch(self.url + "2/", data={"severity": "Not a valid choice"}) self.assertEqual(result.status_code, status.HTTP_400_BAD_REQUEST, "Severity just got set to something invalid") - assert result.json()["severity"] == ["Severity must be one of the following: ['Info', 'Low', 'Medium', 'High', 'Critical']"] + self.assertEqual(result.json()["severity"], ["Severity must be one of the following: ['Info', 'Low', 'Medium', 'High', 'Critical']"]) class FindingMetadataTest(BaseClass.BaseClassTest): @@ -1295,33 +1296,38 @@ def test_create(self): self.assertEqual(200, response.status_code, response.data) results = self.client.get(self.base_url).data + correct = False for result in results: if result["name"] == "test_meta2" and result["value"] == "40": + correct = True return - assert False, "Metadata was not created correctly" + self.assertTrue(correct, "Metadata was not created correctly") def test_create_duplicate(self): result = self.client.post(self.base_url, data={"name": "test_meta", "value": "40"}) - assert result.status_code == status.HTTP_400_BAD_REQUEST, "Metadata creation did not failed on duplicate" + self.assertEqual(result.status_code, status.HTTP_400_BAD_REQUEST, "Metadata creation did not failed on duplicate") def test_get(self): results = self.client.get(self.base_url, format="json").data + correct = False for result in results: if result["name"] == "test_meta" and result["value"] == "20": + correct = True return - assert False, "Metadata was not created correctly" + self.assertTrue(correct, "Metadata was not created correctly") def test_update(self): self.client.put(self.base_url + "?name=test_meta", data={"name": "test_meta", "value": "40"}) result = self.client.get(self.base_url).data[0] - assert result["name"] == "test_meta" and result["value"] == "40", "Metadata not edited correctly" + self.assertEqual(result["name"], "test_meta", "Metadata not edited correctly") + self.assertEqual(result["value"], "40", "Metadata not edited correctly") def test_delete(self): self.client.delete(self.base_url + "?name=test_meta") result = self.client.get(self.base_url).data - assert len(result) == 0, "Metadata not deleted correctly" + self.assertEqual(len(result), 0, "Metadata not deleted correctly") class FindingTemplatesTest(BaseClass.BaseClassTest): @@ -1543,7 +1549,7 @@ def __init__(self, *args, **kwargs): def test_severity_validation(self): result = self.client.patch(self.url + "2/", data={"severity": "Not a valid choice"}) self.assertEqual(result.status_code, status.HTTP_400_BAD_REQUEST, "Severity just got set to something invalid") - assert result.json()["severity"] == ["Severity must be one of the following: ['Info', 'Low', 'Medium', 'High', 'Critical']"] + self.assertEqual(result.json()["severity"], ["Severity must be one of the following: ['Info', 'Low', 'Medium', 'High', 'Critical']"]) class TestsTest(BaseClass.BaseClassTest):