diff --git a/Packs/CofenseTriage/Integrations/CofenseTriagev2/CofenseTriagev2.py b/Packs/CofenseTriage/Integrations/CofenseTriagev2/CofenseTriagev2.py
index b8c1607e12cb..9dcf52da57bf 100644
--- a/Packs/CofenseTriage/Integrations/CofenseTriagev2/CofenseTriagev2.py
+++ b/Packs/CofenseTriage/Integrations/CofenseTriagev2/CofenseTriagev2.py
@@ -1,17 +1,16 @@
-import demistomock as demisto
-from CommonServerPython import *
-
-from io import BytesIO
-from PIL import Image
-from datetime import datetime
-from datetime import timezone
import functools
import itertools
import json
import math
-import urllib3
+from datetime import datetime, timezone
+from io import BytesIO
+import demistomock as demisto
+import urllib3
+from CommonServerPython import *
+from PIL import Image
from urllib3.exceptions import InsecureRequestWarning
+
urllib3.disable_warnings(category=InsecureRequestWarning)
TERSE_FIELDS = [
@@ -259,7 +258,7 @@ def fetch_report_pages(self):
"page": page_num,
},
)
- for page_num in range(0, math.ceil(self.max_pages))
+ for page_num in range(math.ceil(self.max_pages))
]
@@ -307,7 +306,7 @@ def fetch_reporters(self):
return itertools.chain.from_iterable(self.fetch_reporter_pages())
def fetch_reporter_pages(self):
- for page_num in range(0, math.ceil(self.max_pages)):
+ for page_num in range(math.ceil(self.max_pages)):
yield self.triage_instance.request(
"reporters", params={"email": self.email, "page": page_num}
)
@@ -661,9 +660,9 @@ def get_report_by_id_command(triage_instance) -> None:
demisto.results(
{
**report.attachment,
- **{
+
"HumanReadable": "### Cofense HTML Report:\nHTML report download request has been completed"
- },
+ ,
}
)
del report_attrs["report_body"]
diff --git a/Packs/CofenseTriage/Integrations/CofenseTriagev2/CofenseTriagev2_test.py b/Packs/CofenseTriage/Integrations/CofenseTriagev2/CofenseTriagev2_test.py
index 34c4e988a7c8..db977b877177 100644
--- a/Packs/CofenseTriage/Integrations/CofenseTriagev2/CofenseTriagev2_test.py
+++ b/Packs/CofenseTriage/Integrations/CofenseTriagev2/CofenseTriagev2_test.py
@@ -3,11 +3,13 @@
from unittest.mock import patch
import pytest
-from CofenseTriagev2 import TriageInboxReports
-from CofenseTriagev2 import TriageReport
-from CofenseTriagev2 import TriageReporter
-from CofenseTriagev2 import TriageRequestFailedError
-from CofenseTriagev2 import TriageNoReportersFoundError
+from CofenseTriagev2 import (
+ TriageInboxReports,
+ TriageNoReportersFoundError,
+ TriageReport,
+ TriageReporter,
+ TriageRequestFailedError,
+)
from freezegun import freeze_time
diff --git a/Packs/CofenseTriage/Integrations/CofenseTriagev3/CofenseTriagev3.py b/Packs/CofenseTriage/Integrations/CofenseTriagev3/CofenseTriagev3.py
index 47a3767f7ac3..d0abe10d5fbe 100644
--- a/Packs/CofenseTriage/Integrations/CofenseTriagev3/CofenseTriagev3.py
+++ b/Packs/CofenseTriage/Integrations/CofenseTriagev3/CofenseTriagev3.py
@@ -1,11 +1,14 @@
-import demistomock as demisto
-from CommonServerPython import * # noqa # pylint: disable=unused-wildcard-import
-from CommonServerUserPython import * # noqa
import time
-import requests
import traceback
-from typing import Any, Callable, Dict, Tuple
+from collections.abc import Callable
+from typing import Any
+
+import demistomock as demisto
+import requests
import urllib3
+from CommonServerPython import * # noqa # pylint: disable=unused-wildcard-import
+
+from CommonServerUserPython import * # noqa
# Disable insecure warnings
urllib3.disable_warnings()
@@ -237,7 +240,7 @@ def retrieve_fields(arg: str) -> str:
return ",".join([x.strip() for x in arg.split(",") if x.strip()])
-def validate_filter_by_argument(args: Dict[str, Any], custom_args: List[str]) -> Dict[str, Any]:
+def validate_filter_by_argument(args: dict[str, Any], custom_args: List[str]) -> dict[str, Any]:
"""
Validate filters in arguments for all list commands, raise ValueError on invalid arguments.
@@ -268,7 +271,7 @@ def validate_filter_by_argument(args: Dict[str, Any], custom_args: List[str]) ->
return params
-def validate_list_command_args(args: Dict[str, str], field_type: str) -> tuple:
+def validate_list_command_args(args: dict[str, str], field_type: str) -> tuple:
"""
Validate arguments for all list commands, raise ValueError on invalid arguments.
@@ -282,7 +285,7 @@ def validate_list_command_args(args: Dict[str, str], field_type: str) -> tuple:
:rtype: ``Tuple[Any]``
"""
- params: Dict[str, Any] = {}
+ params: dict[str, Any] = {}
custom_args = []
page_size = arg_to_number(args.get("page_size"))
if page_size is not None:
@@ -324,7 +327,7 @@ def validate_fetch_incidents_parameters(params: dict) -> dict:
:rtype: ``dict``
return: dictionary containing valid parameters
"""
- fetch_params: Dict[str, Any] = {}
+ fetch_params: dict[str, Any] = {}
custom_args = []
max_fetch = arg_to_number(params.get("max_fetch", DEFAULT_MAX_FETCH))
@@ -368,7 +371,7 @@ def validate_fetch_incidents_parameters(params: dict) -> dict:
return fetch_params
-def validate_list_threat_indicator_args(args: Dict[str, str]) -> Dict[str, Any]:
+def validate_list_threat_indicator_args(args: dict[str, str]) -> dict[str, Any]:
"""
Validate arguments for cofense-threat-indicator-list command, raise ValueError on invalid arguments.
@@ -407,7 +410,7 @@ def validate_list_threat_indicator_args(args: Dict[str, str]) -> Dict[str, Any]:
return params
-def prepare_hr_for_threat_indicators(results: List[Dict[str, Any]]) -> str:
+def prepare_hr_for_threat_indicators(results: List[dict[str, Any]]) -> str:
"""
Parse and convert the threat indicators in response into human-readable markdown string.
@@ -436,7 +439,7 @@ def prepare_hr_for_threat_indicators(results: List[Dict[str, Any]]) -> str:
"Threat Source", CREATED_AT, UPDATED_AT], removeNull=True)
-def prepare_hr_for_reports(reports: List[Dict[str, Any]]) -> str:
+def prepare_hr_for_reports(reports: List[dict[str, Any]]) -> str:
"""
Prepare human readable for list reports command.
:param reports:The report data.
@@ -463,7 +466,7 @@ def prepare_hr_for_reports(reports: List[Dict[str, Any]]) -> str:
'MD5', 'SHA256', CREATED_AT], removeNull=True)
-def prepare_hr_for_categories(categories: List[Dict[str, Any]]) -> str:
+def prepare_hr_for_categories(categories: List[dict[str, Any]]) -> str:
"""
Prepare human readable for list Categories command.
:param categories:The category data.
@@ -488,7 +491,7 @@ def prepare_hr_for_categories(categories: List[Dict[str, Any]]) -> str:
UPDATED_AT], removeNull=True)
-def prepare_hr_for_clusters(clusters: List[Dict[str, Any]]) -> str:
+def prepare_hr_for_clusters(clusters: List[dict[str, Any]]) -> str:
"""
Prepare human readable for list clusters command.
:param clusters:The cluster data.
@@ -519,7 +522,7 @@ def prepare_hr_for_clusters(clusters: List[Dict[str, Any]]) -> str:
CREATED_AT, UPDATED_AT], removeNull=True)
-def prepare_hr_for_rules(rules: List[Dict[str, Any]]) -> str:
+def prepare_hr_for_rules(rules: List[dict[str, Any]]) -> str:
"""
Prepare human readable for list rules command.
:param rules:The rule data.
@@ -549,7 +552,7 @@ def prepare_hr_for_rules(rules: List[Dict[str, Any]]) -> str:
removeNull=True)
-def validate_tags_argument(args: Dict[str, str]) -> Dict:
+def validate_tags_argument(args: dict[str, str]) -> dict:
"""
Validate tags argument.
:type args: ``Dict[str, str]``
@@ -566,7 +569,7 @@ def validate_tags_argument(args: Dict[str, str]) -> Dict:
return params
-def validate_match_priority_argument(args: Dict[str, str]) -> Dict:
+def validate_match_priority_argument(args: dict[str, str]) -> dict:
"""
Validate match_priority argument.
@@ -585,7 +588,7 @@ def validate_match_priority_argument(args: Dict[str, str]) -> Dict:
return params
-def validate_list_report_args(args: Dict[str, str]) -> Dict[str, Any]:
+def validate_list_report_args(args: dict[str, str]) -> dict[str, Any]:
"""
Validate arguments for cofense-report-list command, raise ValueError on invalid arguments.
@@ -625,7 +628,7 @@ def validate_list_report_args(args: Dict[str, str]) -> Dict[str, Any]:
return params
-def validate_list_category_args(args: Dict[str, str]) -> Dict[str, Any]:
+def validate_list_category_args(args: dict[str, str]) -> dict[str, Any]:
"""
Validate arguments for cofense-category-list command, raise ValueError on invalid arguments.
@@ -662,7 +665,7 @@ def validate_list_category_args(args: Dict[str, str]) -> Dict[str, Any]:
return params
-def validate_list_cluster_args(args: Dict[str, str]) -> Dict[str, Any]:
+def validate_list_cluster_args(args: dict[str, str]) -> dict[str, Any]:
"""
Validate arguments for cofense-cluster-list command, raise ValueError on invalid arguments.
@@ -698,7 +701,7 @@ def validate_list_cluster_args(args: Dict[str, str]) -> Dict[str, Any]:
return params
-def validate_list_url_args(args: Dict[str, str]) -> Dict[str, Any]:
+def validate_list_url_args(args: dict[str, str]) -> dict[str, Any]:
"""
Validate arguments for cofense-url-list command, raise ValueError on invalid arguments.
@@ -724,7 +727,7 @@ def validate_list_url_args(args: Dict[str, str]) -> Dict[str, Any]:
return params
-def prepare_hr_for_urls(results: List[Dict[str, Any]]) -> str:
+def prepare_hr_for_urls(results: List[dict[str, Any]]) -> str:
"""
Parse and convert the urls in the response into human-readable markdown string.
@@ -750,7 +753,7 @@ def prepare_hr_for_urls(results: List[Dict[str, Any]]) -> str:
headers=["URL ID", "URL", "Risk Score", CREATED_AT, UPDATED_AT], removeNull=True)
-def validate_list_rule_args(args: Dict[str, str]) -> Dict[str, Any]:
+def validate_list_rule_args(args: dict[str, str]) -> dict[str, Any]:
"""
Validate arguments for cofense-rule-list command, raise ValueError on invalid arguments.
@@ -807,7 +810,7 @@ def validate_list_rule_args(args: Dict[str, str]) -> Dict[str, Any]:
return params
-def validate_create_threat_indicator_args(args: Dict[str, str]) -> Dict[str, Any]:
+def validate_create_threat_indicator_args(args: dict[str, str]) -> dict[str, Any]:
"""
Validate arguments for cofense-threat-indicator-create command, raise ValueError on invalid arguments.
@@ -838,7 +841,7 @@ def validate_create_threat_indicator_args(args: Dict[str, str]) -> Dict[str, Any
return params
-def validate_list_reporter_args(args: Dict[str, str]) -> Dict[str, Any]:
+def validate_list_reporter_args(args: dict[str, str]) -> dict[str, Any]:
"""
Validate arguments for cofense-reporter-list command, raise ValueError on invalid arguments.
@@ -876,7 +879,7 @@ def validate_list_reporter_args(args: Dict[str, str]) -> Dict[str, Any]:
return params
-def prepare_hr_for_reporters(results: List[Dict[str, Any]]) -> str:
+def prepare_hr_for_reporters(results: List[dict[str, Any]]) -> str:
"""
Parse and convert the reporters in the response into human-readable markdown string.
@@ -906,7 +909,7 @@ def prepare_hr_for_reporters(results: List[Dict[str, Any]]) -> str:
"Last Reported At", CREATED_AT, UPDATED_AT], removeNull=True)
-def validate_categorize_report_args(args: Dict[str, str]) -> Dict[str, Any]:
+def validate_categorize_report_args(args: dict[str, str]) -> dict[str, Any]:
"""
Validate arguments for cofense-report-categorize command, raise ValueError on invalid arguments.
@@ -924,7 +927,7 @@ def validate_categorize_report_args(args: Dict[str, str]) -> Dict[str, Any]:
raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("category_id"))
arg_to_number(args.get("category_id"))
- params: Dict[str, Any] = {"category_id": args["category_id"]}
+ params: dict[str, Any] = {"category_id": args["category_id"]}
categorization_tags = retrieve_fields(args.get("categorization_tags", ""))
if categorization_tags:
@@ -933,7 +936,7 @@ def validate_categorize_report_args(args: Dict[str, str]) -> Dict[str, Any]:
return params
-def validate_list_attachment_payload_args(args: Dict[str, str]) -> Dict[str, Any]:
+def validate_list_attachment_payload_args(args: dict[str, str]) -> dict[str, Any]:
"""
Validate arguments for cofense-attachment-payload-list command, raise ValueError on invalid arguments.
@@ -959,7 +962,7 @@ def validate_list_attachment_payload_args(args: Dict[str, str]) -> Dict[str, Any
return params
-def prepare_hr_for_attachment_payloads(results: List[Dict[str, Any]]) -> str:
+def prepare_hr_for_attachment_payloads(results: List[dict[str, Any]]) -> str:
"""
Parse and convert the attachment payloads in the response into human-readable markdown string.
@@ -988,7 +991,7 @@ def prepare_hr_for_attachment_payloads(results: List[Dict[str, Any]]) -> str:
UPDATED_AT], removeNull=True)
-def prepare_hr_for_report_attachments(results: List[Dict[str, Any]]) -> str:
+def prepare_hr_for_report_attachments(results: List[dict[str, Any]]) -> str:
"""
Parse and convert the report attachment in the response into human-readable markdown string.
@@ -1017,7 +1020,7 @@ def prepare_hr_for_report_attachments(results: List[Dict[str, Any]]) -> str:
removeNull=True)
-def validate_comment_list_args(args: Dict[str, str]) -> Dict[str, Any]:
+def validate_comment_list_args(args: dict[str, str]) -> dict[str, Any]:
"""
Validate arguments for cofense-comment-list command, raise ValueError on invalid arguments.
@@ -1048,7 +1051,7 @@ def validate_comment_list_args(args: Dict[str, str]) -> Dict[str, Any]:
return params
-def prepare_hr_for_comments(comments: List[Dict[str, Any]]) -> str:
+def prepare_hr_for_comments(comments: List[dict[str, Any]]) -> str:
"""
Parse and convert the comments in the response into human-readable markdown string.
@@ -1085,7 +1088,7 @@ def prepare_hr_for_comments(comments: List[Dict[str, Any]]) -> str:
'Associated To', 'Associated To ID'], removeNull=True)
-def validate_get_integration_submission_args(args: Dict[str, str]) -> Dict[str, Any]:
+def validate_get_integration_submission_args(args: dict[str, str]) -> dict[str, Any]:
"""
Validate arguments for cofense-integration-submission-get command, raise ValueError on invalid arguments.
@@ -1122,7 +1125,7 @@ def validate_get_integration_submission_args(args: Dict[str, str]) -> Dict[str,
return params
-def prepare_hr_for_integration_submission(results: List[Dict[str, Any]]) -> str:
+def prepare_hr_for_integration_submission(results: List[dict[str, Any]]) -> str:
"""
Parse and convert integration submission in response into human-readable markdown string.
@@ -1168,7 +1171,7 @@ def check_fetch_incident_configuration(fetch_params, params):
raise ValueError(MESSAGES["INVALID_LOCATION_FOR_CATEGORY_ID"])
-def validate_update_threat_indicator_args(args: Dict[str, str]) -> Dict[str, Any]:
+def validate_update_threat_indicator_args(args: dict[str, str]) -> dict[str, Any]:
"""
Validate arguments for cofense-threat-indicator-update command, raise ValueError on invalid arguments.
@@ -1217,7 +1220,7 @@ def test_module(client: Client, params: dict) -> str:
return 'ok'
-def cofense_threat_indicator_list_command(client: Client, args: Dict[str, str]) -> CommandResults:
+def cofense_threat_indicator_list_command(client: Client, args: dict[str, str]) -> CommandResults:
"""
Retrieves the list of threat indicators based on the filter values provided in the command arguments.
@@ -1265,7 +1268,7 @@ def cofense_threat_indicator_list_command(client: Client, args: Dict[str, str])
)
-def cofense_report_list_command(client, args: Dict[str, str]) -> CommandResults:
+def cofense_report_list_command(client, args: dict[str, str]) -> CommandResults:
"""
List reports from Cofense Triage.
@@ -1318,7 +1321,7 @@ def cofense_report_list_command(client, args: Dict[str, str]) -> CommandResults:
)
-def cofense_report_download_command(client: Client, args: Dict[str, str]) -> dict:
+def cofense_report_download_command(client: Client, args: dict[str, str]) -> dict:
"""
Downloads the raw email for a specific report.
@@ -1346,7 +1349,7 @@ def cofense_report_download_command(client: Client, args: Dict[str, str]) -> dic
return fileResult(filename, data=str(raw_response))
-def cofense_report_image_download_command(client: Client, args: Dict[str, str]) -> dict:
+def cofense_report_image_download_command(client: Client, args: dict[str, str]) -> dict:
"""
Downloads the image for a specific report.
@@ -1383,7 +1386,7 @@ def cofense_report_image_download_command(client: Client, args: Dict[str, str])
return fileResult(filename, data=raw_response, file_type=entryTypes["image"])
-def cofense_report_attachment_payload_list_command(client: Client, args: Dict[str, str]) -> CommandResults:
+def cofense_report_attachment_payload_list_command(client: Client, args: dict[str, str]) -> CommandResults:
"""
Retrieves report attachment payloads based on the filter values provided in the command arguments.
Attachment payloads identify the MIME type and MD5 and SHA256 hash signatures of a reported email attachment.
@@ -1431,7 +1434,7 @@ def cofense_report_attachment_payload_list_command(client: Client, args: Dict[st
)
-def cofense_report_attachment_list_command(client: Client, args: Dict[str, str]) -> CommandResults:
+def cofense_report_attachment_list_command(client: Client, args: dict[str, str]) -> CommandResults:
"""
Retrieves report attachment list based on the filter values provided in the command arguments.
For reported emails that contain attachments, Cofense Triage captures the attachment's filename and size.
@@ -1479,7 +1482,7 @@ def cofense_report_attachment_list_command(client: Client, args: Dict[str, str])
)
-def cofense_report_attachment_download_command(client: Client, args: Dict[str, str]) -> dict:
+def cofense_report_attachment_download_command(client: Client, args: dict[str, str]) -> dict:
"""
Downloads the attachment for a the specified attachment ID.
@@ -1512,7 +1515,7 @@ def cofense_report_attachment_download_command(client: Client, args: Dict[str, s
return fileResult(file_name, data=response.content)
-def fetch_incidents(client: Client, last_run: dict, params: Dict) -> Tuple[dict, list]:
+def fetch_incidents(client: Client, last_run: dict, params: dict) -> tuple[dict, list]:
"""Fetches incidents from Cofense API.
:type client: ``Client``
@@ -1580,7 +1583,7 @@ def fetch_incidents(client: Client, last_run: dict, params: Dict) -> Tuple[dict,
return next_run, incidents
-def cofense_report_categorize_command(client: Client, args: Dict[str, str]) -> CommandResults:
+def cofense_report_categorize_command(client: Client, args: dict[str, str]) -> CommandResults:
"""Categorizes a report into a specific category provided by the user.
:type client: ``Client``
@@ -1604,7 +1607,7 @@ def cofense_report_categorize_command(client: Client, args: Dict[str, str]) -> C
return CommandResults(readable_output=f"Report with ID = {args['id']} is categorized successfully.")
-def cofense_category_list_command(client, args: Dict[str, str]) -> CommandResults:
+def cofense_category_list_command(client, args: dict[str, str]) -> CommandResults:
"""
List categories from Cofense Triage.
@@ -1643,7 +1646,7 @@ def cofense_category_list_command(client, args: Dict[str, str]) -> CommandResult
)
-def cofense_rule_list_command(client, args: Dict[str, str]) -> CommandResults:
+def cofense_rule_list_command(client, args: dict[str, str]) -> CommandResults:
"""
List rules from Cofense Triage.
@@ -1682,7 +1685,7 @@ def cofense_rule_list_command(client, args: Dict[str, str]) -> CommandResults:
)
-def cofense_url_list_command(client: Client, args: Dict[str, str]) -> CommandResults:
+def cofense_url_list_command(client: Client, args: dict[str, str]) -> CommandResults:
"""
Retrieves URLs based on the filter values provided in the command arguments.
URLs are the threats (or non-threat) that are detected in the Reported emails.
@@ -1731,7 +1734,7 @@ def cofense_url_list_command(client: Client, args: Dict[str, str]) -> CommandRes
)
-def cofense_threat_indicator_create_command(client: Client, args: Dict[str, str]) -> CommandResults:
+def cofense_threat_indicator_create_command(client: Client, args: dict[str, str]) -> CommandResults:
"""
Creates a threat indicator based on the values provided in the command arguments.
@@ -1773,7 +1776,7 @@ def cofense_threat_indicator_create_command(client: Client, args: Dict[str, str]
)
-def cofense_integration_submission_get_command(client: Client, args: Dict[str, str]) -> CommandResults:
+def cofense_integration_submission_get_command(client: Client, args: dict[str, str]) -> CommandResults:
"""
Retrieves integration submission based on the filter values provided in the command arguments.
@@ -1824,7 +1827,7 @@ def cofense_integration_submission_get_command(client: Client, args: Dict[str, s
)
-def cofense_reporter_list_command(client: Client, args: Dict[str, str]) -> CommandResults:
+def cofense_reporter_list_command(client: Client, args: dict[str, str]) -> CommandResults:
"""
Retrieves the reporters that match the provided parameters.
Reporters are employees of an organization who send, or report, suspicious emails to Cofense Triage.
@@ -1873,7 +1876,7 @@ def cofense_reporter_list_command(client: Client, args: Dict[str, str]) -> Comma
)
-def cofense_attachment_payload_list_command(client: Client, args: Dict[str, str]) -> CommandResults:
+def cofense_attachment_payload_list_command(client: Client, args: dict[str, str]) -> CommandResults:
"""
Retrieves attachment payloads based on the filter values provided in the command arguments.
Attachment payloads identify the MIME type and MD5 and SHA256 hash signatures of a reported email.
@@ -1922,7 +1925,7 @@ def cofense_attachment_payload_list_command(client: Client, args: Dict[str, str]
)
-def cofense_comment_list_command(client: Client, args: Dict[str, str]) -> CommandResults:
+def cofense_comment_list_command(client: Client, args: dict[str, str]) -> CommandResults:
"""
Retrieves comments based on the filter values provided in the command arguments.
@@ -1974,7 +1977,7 @@ def cofense_comment_list_command(client: Client, args: Dict[str, str]) -> Comman
)
-def cofense_cluster_list_command(client: Client, args: Dict[str, str]) -> CommandResults:
+def cofense_cluster_list_command(client: Client, args: dict[str, str]) -> CommandResults:
"""
List clusters from Cofense Triage.
@@ -2019,7 +2022,7 @@ def cofense_cluster_list_command(client: Client, args: Dict[str, str]) -> Comman
)
-def get_remote_data_command(client: Client, args: Dict[str, str]) -> GetRemoteDataResponse:
+def get_remote_data_command(client: Client, args: dict[str, str]) -> GetRemoteDataResponse:
"""
Get the updated incident data
@@ -2050,7 +2053,7 @@ def get_remote_data_command(client: Client, args: Dict[str, str]) -> GetRemoteDa
return GetRemoteDataResponse(result, [])
-def get_modified_remote_data_command(client: Client, args: Dict[str, str]) -> GetModifiedRemoteDataResponse:
+def get_modified_remote_data_command(client: Client, args: dict[str, str]) -> GetModifiedRemoteDataResponse:
"""
Queries for incidents that were modified since the last update.
@@ -2079,7 +2082,7 @@ def get_modified_remote_data_command(client: Client, args: Dict[str, str]) -> Ge
return GetModifiedRemoteDataResponse(modified_incident_ids)
-def cofense_threat_indicator_update_command(client: Client, args: Dict[str, str]) -> CommandResults:
+def cofense_threat_indicator_update_command(client: Client, args: dict[str, str]) -> CommandResults:
"""
Updates a threat indicator based on the values provided in the command arguments.
@@ -2130,7 +2133,7 @@ def main() -> None:
"""main function, parses params and runs command functions
"""
# Commands dictionary
- commands: Dict[str, Callable] = {
+ commands: dict[str, Callable] = {
'cofense-report-list': cofense_report_list_command,
'cofense-threat-indicator-list': cofense_threat_indicator_list_command,
'cofense-report-download': cofense_report_download_command,
@@ -2206,7 +2209,7 @@ def main() -> None:
# Log exceptions and return errors
except Exception as e:
demisto.error(traceback.format_exc()) # print the traceback
- return_error(f'Failed to execute {demisto.command()} command.\nError:\n{str(e)}')
+ return_error(f'Failed to execute {demisto.command()} command.\nError:\n{e!s}')
''' ENTRY POINT '''
diff --git a/Packs/CofenseTriage/Integrations/CofenseTriagev3/CofenseTriagev3_test.py b/Packs/CofenseTriage/Integrations/CofenseTriagev3/CofenseTriagev3_test.py
index b85e87745490..5c0cc40017c3 100644
--- a/Packs/CofenseTriage/Integrations/CofenseTriagev3/CofenseTriagev3_test.py
+++ b/Packs/CofenseTriage/Integrations/CofenseTriagev3/CofenseTriagev3_test.py
@@ -1,13 +1,13 @@
import json
-import time
import os
-import pytest
+import time
from unittest import mock
from unittest.mock import patch
-import dateparser
-from CommonServerPython import DemistoException
+import dateparser
+import pytest
from CofenseTriagev3 import MESSAGES
+from CommonServerPython import DemistoException
from test_data import input_data
BASE_URL = "https://triage.example.com"
@@ -27,7 +27,7 @@
def util_load_json(path: str) -> dict:
"""Load a json to python dict."""
- with open(path, mode='r', encoding='utf-8') as f:
+ with open(path, encoding='utf-8') as f:
return json.loads(f.read())
@@ -115,7 +115,7 @@ def test_get_api_token_when_not_found_in_integration_context(mocker_set_context,
api_token = client.get_api_token()
- assert api_token == bool(False)
+ assert api_token == False
@patch(MOCKER_HTTP_METHOD)
@@ -259,7 +259,7 @@ def test_cofense_threat_indicator_list_command_when_valid_response_is_returned(m
context_output = util_load_json(
os.path.join("test_data", "threat_indicator/threat_indicators_command_context.json"))
- with open(os.path.join("test_data", "threat_indicator/threat_indicators_command_readable_output.md"), 'r') as f:
+ with open(os.path.join("test_data", "threat_indicator/threat_indicators_command_readable_output.md")) as f:
readable_output = f.read()
# Execute
@@ -505,7 +505,7 @@ def test_cofense_url_list_command_when_valid_response_is_returned(mocked_client)
context_output = util_load_json(
os.path.join("test_data", "url/list_url_command_context.json"))
- with open(os.path.join("test_data", "url/list_url_command_readable_output.md"), 'r') as f:
+ with open(os.path.join("test_data", "url/list_url_command_readable_output.md")) as f:
readable_output = f.read()
# Execute
@@ -637,7 +637,7 @@ def test_cofense_threat_indicator_create_command_when_valid_response_is_returned
context_output = util_load_json(
os.path.join("test_data", "threat_indicator/threat_indicators_command_context.json"))
- with open(os.path.join("test_data", "threat_indicator/threat_indicators_command_readable_output.md"), 'r') as f:
+ with open(os.path.join("test_data", "threat_indicator/threat_indicators_command_readable_output.md")) as f:
readable_output = f.read()
# Execute
@@ -687,8 +687,7 @@ def test_cofense_integration_submission_get_command_when_valid_response_is_retur
context_output = util_load_json(
os.path.join("test_data", "integration_submission/integration_submission_context.json"))
- with open(os.path.join("test_data", "integration_submission/integration_submission_command_readable_output.md"),
- 'r') as f:
+ with open(os.path.join("test_data", "integration_submission/integration_submission_command_readable_output.md")) as f:
readable_output = f.read()
# Execute
@@ -740,7 +739,7 @@ def test_cofense_reporter_list_command_when_valid_response_is_returned(mocked_cl
context_output = util_load_json(
os.path.join("test_data", "reporter/reporter_list_context.json"))
- with open(os.path.join("test_data", "reporter/reporter_list.md"), 'r') as f:
+ with open(os.path.join("test_data", "reporter/reporter_list.md")) as f:
readable_output = f.read()
# Execute
@@ -796,7 +795,7 @@ def test_cofense_attachment_payload_list_command_when_valid_response_is_returned
context_output = util_load_json(
os.path.join("test_data", "attachment_payload/attachment_payload_list_context.json"))
- with open(os.path.join("test_data", "attachment_payload/attachment_payload_list.md"), 'r') as f:
+ with open(os.path.join("test_data", "attachment_payload/attachment_payload_list.md")) as f:
readable_output = f.read()
# Execute
@@ -916,7 +915,7 @@ def test_cofense_threat_indicator_update_command_when_valid_response_is_returned
context_output = util_load_json(
os.path.join("test_data", "threat_indicator/threat_indicators_command_context.json"))
- with open(os.path.join("test_data", "threat_indicator/threat_indicators_command_readable_output.md"), 'r') as f:
+ with open(os.path.join("test_data", "threat_indicator/threat_indicators_command_readable_output.md")) as f:
readable_output = f.read()
# Execute
@@ -1061,7 +1060,7 @@ def test_cofense_report_attachment_payload_list_command_when_valid_response_is_r
context_output = util_load_json(
os.path.join("test_data", "report_attachment_payload/report_attachment_payload_list_context.json"))
- with open(os.path.join("test_data", "report_attachment_payload/report_attachment_payload_list.md"), 'r') as f:
+ with open(os.path.join("test_data", "report_attachment_payload/report_attachment_payload_list.md")) as f:
readable_output = f.read()
# Execute
@@ -1145,7 +1144,7 @@ def test_cofense_report_attachment_list_command_when_valid_response_is_returned(
context_output = util_load_json(
os.path.join("test_data", os.path.join("report_attachment", "report_attachment_list_context.json")))
- with open(os.path.join("test_data", os.path.join("report_attachment", "report_attachment_list.md")), 'r') as f:
+ with open(os.path.join("test_data", os.path.join("report_attachment", "report_attachment_list.md"))) as f:
readable_output = f.read()
# Execute
@@ -1179,7 +1178,7 @@ def test_cofense_report_attachment_download_command_when_valid_args_are_provided
from CofenseTriagev3 import cofense_report_attachment_download_command
- with open(os.path.join("test_data", os.path.join("report_attachment", "report_attachment_download_response.xml")), 'r') as f:
+ with open(os.path.join("test_data", os.path.join("report_attachment", "report_attachment_download_response.xml"))) as f:
response = f.read()
# Mock response with the valid headers.
diff --git a/Packs/CofenseTriage/Integrations/CofenseTriagev3/test_data/input_data.py b/Packs/CofenseTriage/Integrations/CofenseTriagev3/test_data/input_data.py
index 7c908d00faaf..8889f54d009f 100644
--- a/Packs/CofenseTriage/Integrations/CofenseTriagev3/test_data/input_data.py
+++ b/Packs/CofenseTriage/Integrations/CofenseTriagev3/test_data/input_data.py
@@ -1,4 +1,5 @@
import time
+
import dateparser
MESSAGES = {
diff --git a/Packs/CofenseTriage/Scripts/CofenseTriageReportDownload/CofenseTriageReportDownload.py b/Packs/CofenseTriage/Scripts/CofenseTriageReportDownload/CofenseTriageReportDownload.py
index 7e986470b13f..6c051f165024 100644
--- a/Packs/CofenseTriage/Scripts/CofenseTriageReportDownload/CofenseTriageReportDownload.py
+++ b/Packs/CofenseTriage/Scripts/CofenseTriageReportDownload/CofenseTriageReportDownload.py
@@ -1,6 +1,5 @@
from CommonServerPython import *
-
''' STANDALONE FUNCTION '''
@@ -56,7 +55,7 @@ def main():
return_results(results)
except Exception as e:
demisto.error(traceback.format_exc()) # print the traceback
- return_error(f'Failed to execute CofenseTriageReportDownload. Error: {str(e)}')
+ return_error(f'Failed to execute CofenseTriageReportDownload. Error: {e!s}')
''' ENTRY POINT '''
diff --git a/Packs/CofenseTriage/Scripts/CofenseTriageReportDownload/CofenseTriageReportDownload_test.py b/Packs/CofenseTriage/Scripts/CofenseTriageReportDownload/CofenseTriageReportDownload_test.py
index 5d684e287a58..1760228d9468 100644
--- a/Packs/CofenseTriage/Scripts/CofenseTriageReportDownload/CofenseTriageReportDownload_test.py
+++ b/Packs/CofenseTriage/Scripts/CofenseTriageReportDownload/CofenseTriageReportDownload_test.py
@@ -1,5 +1,5 @@
-from unittest.mock import patch
import json
+from unittest.mock import patch
@patch('demistomock.executeCommand')
diff --git a/Packs/CofenseTriage/Scripts/CofenseTriageThreatEnrichment/CofenseTriageThreatEnrichment.py b/Packs/CofenseTriage/Scripts/CofenseTriageThreatEnrichment/CofenseTriageThreatEnrichment.py
index 922f086f83c8..b2da34685b28 100644
--- a/Packs/CofenseTriage/Scripts/CofenseTriageThreatEnrichment/CofenseTriageThreatEnrichment.py
+++ b/Packs/CofenseTriage/Scripts/CofenseTriageThreatEnrichment/CofenseTriageThreatEnrichment.py
@@ -1,6 +1,5 @@
from CommonServerPython import *
-
''' STANDALONE FUNCTION '''
@@ -33,7 +32,7 @@ def main():
return_results(get_threat_indicator_list(demisto.args()))
except Exception as e:
demisto.error(traceback.format_exc()) # print the traceback
- return_error(f'Failed to execute CofenseTriageThreatEnrichment. Error: {str(e)}')
+ return_error(f'Failed to execute CofenseTriageThreatEnrichment. Error: {e!s}')
''' ENTRY POINT '''
diff --git a/Packs/CofenseTriage/Scripts/CofenseTriageThreatEnrichment/CofenseTriageThreatEnrichment_test.py b/Packs/CofenseTriage/Scripts/CofenseTriageThreatEnrichment/CofenseTriageThreatEnrichment_test.py
index a069e3a2c754..87024aa32c57 100644
--- a/Packs/CofenseTriage/Scripts/CofenseTriageThreatEnrichment/CofenseTriageThreatEnrichment_test.py
+++ b/Packs/CofenseTriage/Scripts/CofenseTriageThreatEnrichment/CofenseTriageThreatEnrichment_test.py
@@ -1,5 +1,5 @@
-from unittest.mock import patch
import json
+from unittest.mock import patch
@patch('demistomock.executeCommand')
diff --git a/Packs/CommonScripts/Scripts/AddKeyToList/AddKeyToList.py b/Packs/CommonScripts/Scripts/AddKeyToList/AddKeyToList.py
index d52716e54f3e..71f26b2ff13a 100644
--- a/Packs/CommonScripts/Scripts/AddKeyToList/AddKeyToList.py
+++ b/Packs/CommonScripts/Scripts/AddKeyToList/AddKeyToList.py
@@ -1,5 +1,6 @@
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
+
"""AddKeyToList
Adds/Updates a Key to a JSON-backed List
"""
@@ -87,7 +88,7 @@ def main():
return_results(add_key_to_list_command(demisto.args()))
except Exception as ex:
demisto.error(traceback.format_exc()) # print the traceback
- return_error(f'Failed to execute AddKeyToList. Error: {str(ex)}')
+ return_error(f'Failed to execute AddKeyToList. Error: {ex!s}')
''' ENTRY POINT '''
diff --git a/Packs/CommonScripts/Scripts/AddKeyToList/AddKeyToList_test.py b/Packs/CommonScripts/Scripts/AddKeyToList/AddKeyToList_test.py
index 0bb033889d80..9f351549ff77 100644
--- a/Packs/CommonScripts/Scripts/AddKeyToList/AddKeyToList_test.py
+++ b/Packs/CommonScripts/Scripts/AddKeyToList/AddKeyToList_test.py
@@ -1,7 +1,8 @@
-from AddKeyToList import add_key_to_list_command
-import demistomock as demisto # noqa # pylint: disable=unused-wildcard-import
-from typing import Any
import json
+from typing import Any
+
+import demistomock as demisto # noqa # pylint: disable=unused-wildcard-import
+from AddKeyToList import add_key_to_list_command
MOCK_LIST_NAME = "TestList"
MOCK_KEY_NAME = "TestKey"
diff --git a/Packs/CommonScripts/Scripts/AnalyzeTimestampIntervals/AnalyzeTimestampIntervals.py b/Packs/CommonScripts/Scripts/AnalyzeTimestampIntervals/AnalyzeTimestampIntervals.py
index 30ea2fde6d04..5ebf9a7140a7 100644
--- a/Packs/CommonScripts/Scripts/AnalyzeTimestampIntervals/AnalyzeTimestampIntervals.py
+++ b/Packs/CommonScripts/Scripts/AnalyzeTimestampIntervals/AnalyzeTimestampIntervals.py
@@ -1,6 +1,7 @@
+import statistics
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-import statistics
def calculate_interval_differences(timestamps):
@@ -127,7 +128,7 @@ def main(): # pragma: no cover
return_results(command_results)
except Exception as e:
- return_error(f"An error occurred: {str(e)}")
+ return_error(f"An error occurred: {e!s}")
if __name__ in ('__main__', '__builtin__', 'builtins'):
diff --git a/Packs/CommonScripts/Scripts/AnalyzeTimestampIntervals/AnalyzeTimestampIntervals_test.py b/Packs/CommonScripts/Scripts/AnalyzeTimestampIntervals/AnalyzeTimestampIntervals_test.py
index 56cacf4662ca..039ea5d2d2fc 100644
--- a/Packs/CommonScripts/Scripts/AnalyzeTimestampIntervals/AnalyzeTimestampIntervals_test.py
+++ b/Packs/CommonScripts/Scripts/AnalyzeTimestampIntervals/AnalyzeTimestampIntervals_test.py
@@ -1,7 +1,7 @@
-import pytest
-from AnalyzeTimestampIntervals import analyze_intervals
import random
+import pytest
+from AnalyzeTimestampIntervals import analyze_intervals
# Consistent intervals (10,000 ms apart, i.e., 1 event every 10 seconds)
consistent_timestamps = [1609459200000 + i * 10000 for i in range(100)]
diff --git a/Packs/CommonScripts/Scripts/AppendindicatorFieldWrapper/AppendindicatorFieldWrapper.py b/Packs/CommonScripts/Scripts/AppendindicatorFieldWrapper/AppendindicatorFieldWrapper.py
index 7eed372d5d97..0099d2218bec 100644
--- a/Packs/CommonScripts/Scripts/AppendindicatorFieldWrapper/AppendindicatorFieldWrapper.py
+++ b/Packs/CommonScripts/Scripts/AppendindicatorFieldWrapper/AppendindicatorFieldWrapper.py
@@ -1,18 +1,18 @@
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
+
"""
A wrapper script to the 'AppendindicatorField' script, that enables adding tags to certain indicators.
Note: You can use this script as a layout button that allows adding tags to indicators.
"""
-from CommonServerUserPython import *
-from typing import List
+from CommonServerUserPython import *
''' COMMAND FUNCTION '''
-def run_append_indicator_field_script(indicators_values: List, tags: List) -> CommandResults:
+def run_append_indicator_field_script(indicators_values: list, tags: list) -> CommandResults:
"""
Run the 'appendIndicatorField' script in order to add the given tags to the given indicators.
Args:
@@ -53,7 +53,7 @@ def main():
return_results(run_append_indicator_field_script(indicators_values, tags))
except Exception as ex:
- return_error(f'Failed to execute AppendindicatorFieldWrapper. Error: {str(ex)}')
+ return_error(f'Failed to execute AppendindicatorFieldWrapper. Error: {ex!s}')
''' ENTRY POINT '''
diff --git a/Packs/CommonScripts/Scripts/AquatoneDiscoverV2/AquatoneDiscoverV2.py b/Packs/CommonScripts/Scripts/AquatoneDiscoverV2/AquatoneDiscoverV2.py
index 0a18bb73fb89..3e7af2774f53 100644
--- a/Packs/CommonScripts/Scripts/AquatoneDiscoverV2/AquatoneDiscoverV2.py
+++ b/Packs/CommonScripts/Scripts/AquatoneDiscoverV2/AquatoneDiscoverV2.py
@@ -1,8 +1,9 @@
+from subprocess import PIPE, Popen
+
import demistomock as demisto
from CommonServerPython import *
-from CommonServerUserPython import *
-from subprocess import Popen, PIPE
+from CommonServerUserPython import *
def main():
diff --git a/Packs/CommonScripts/Scripts/AquatoneDiscoverV2/AquatoneDiscoverV2_test.py b/Packs/CommonScripts/Scripts/AquatoneDiscoverV2/AquatoneDiscoverV2_test.py
index 4cd5dd4c0959..43b233e9b882 100644
--- a/Packs/CommonScripts/Scripts/AquatoneDiscoverV2/AquatoneDiscoverV2_test.py
+++ b/Packs/CommonScripts/Scripts/AquatoneDiscoverV2/AquatoneDiscoverV2_test.py
@@ -1,7 +1,8 @@
-from unittest.mock import patch, MagicMock, call
-import demistomock as demisto
import json
from subprocess import PIPE
+from unittest.mock import MagicMock, call, patch
+
+import demistomock as demisto
MOCK_DOMAIN = 'test.com'
expected_entry_result = {'Contents': 'hosts_json_test',
diff --git a/Packs/CommonScripts/Scripts/ArrayToCSV/ArrayToCSV.py b/Packs/CommonScripts/Scripts/ArrayToCSV/ArrayToCSV.py
index cb7df098715a..461464813773 100644
--- a/Packs/CommonScripts/Scripts/ArrayToCSV/ArrayToCSV.py
+++ b/Packs/CommonScripts/Scripts/ArrayToCSV/ArrayToCSV.py
@@ -1,6 +1,7 @@
+from traceback import format_exc
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-from traceback import format_exc
def arr_to_csv_command(array: list[str] | str) -> str:
diff --git a/Packs/CommonScripts/Scripts/AssignToMeButton/AssignToMeButton.py b/Packs/CommonScripts/Scripts/AssignToMeButton/AssignToMeButton.py
index 74db9f989078..32776b2d7c14 100644
--- a/Packs/CommonScripts/Scripts/AssignToMeButton/AssignToMeButton.py
+++ b/Packs/CommonScripts/Scripts/AssignToMeButton/AssignToMeButton.py
@@ -1,7 +1,6 @@
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-
# get incident id
incident_id = demisto.incidents()[0].get('id')
diff --git a/Packs/CommonScripts/Scripts/BMCTool/BMCTool.py b/Packs/CommonScripts/Scripts/BMCTool/BMCTool.py
index 66db986b4dbf..705dcb02d1b9 100644
--- a/Packs/CommonScripts/Scripts/BMCTool/BMCTool.py
+++ b/Packs/CommonScripts/Scripts/BMCTool/BMCTool.py
@@ -1,9 +1,9 @@
+# This tool was developed by "https://github.com/ANSSI-FR/bmc-tools" - Thank you for your hardwork!
+from struct import pack, unpack
from typing import AnyStr, Generic
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-# This tool was developed by "https://github.com/ANSSI-FR/bmc-tools" - Thank you for your hardwork!
-
-from struct import pack, unpack
class BMCContainer(Generic[AnyStr]):
@@ -496,7 +496,7 @@ def main():
return_results(results)
except Exception as e:
- return_error(f'Failed to parse BMC cache file. Problem: {str(e)}')
+ return_error(f'Failed to parse BMC cache file. Problem: {e!s}')
if __name__ in ('__builtin__', 'builtins', '__main__'):
diff --git a/Packs/CommonScripts/Scripts/BMCTool/BMCTool_test.py b/Packs/CommonScripts/Scripts/BMCTool/BMCTool_test.py
index c341839d56ce..bbdcd227564b 100644
--- a/Packs/CommonScripts/Scripts/BMCTool/BMCTool_test.py
+++ b/Packs/CommonScripts/Scripts/BMCTool/BMCTool_test.py
@@ -1,7 +1,7 @@
import demistomock as demisto # noqa: F401
import pytest
-from CommonServerPython import * # noqa: F401
from BMCTool import BMCContainer, main
+from CommonServerPython import * # noqa: F401
@pytest.mark.parametrize("container, expected_size",
diff --git a/Packs/CommonScripts/Scripts/Base64EncodeV2/Base64EncodeV2.py b/Packs/CommonScripts/Scripts/Base64EncodeV2/Base64EncodeV2.py
index aedabd23f482..b656d5f25ef2 100644
--- a/Packs/CommonScripts/Scripts/Base64EncodeV2/Base64EncodeV2.py
+++ b/Packs/CommonScripts/Scripts/Base64EncodeV2/Base64EncodeV2.py
@@ -1,8 +1,9 @@
+import base64
+
import demistomock as demisto
from CommonServerPython import *
-from CommonServerUserPython import *
-import base64
+from CommonServerUserPython import *
def encode(input):
diff --git a/Packs/CommonScripts/Scripts/Base64EncodeV2/Base64EncodeV2_test.py b/Packs/CommonScripts/Scripts/Base64EncodeV2/Base64EncodeV2_test.py
index 288da042499b..0955da425257 100644
--- a/Packs/CommonScripts/Scripts/Base64EncodeV2/Base64EncodeV2_test.py
+++ b/Packs/CommonScripts/Scripts/Base64EncodeV2/Base64EncodeV2_test.py
@@ -1,4 +1,5 @@
import unittest
+
from Base64EncodeV2 import encode
diff --git a/Packs/CommonScripts/Scripts/Base64ListToFile/Base64ListToFile.py b/Packs/CommonScripts/Scripts/Base64ListToFile/Base64ListToFile.py
index 2027c5c977da..fc31e4c20668 100644
--- a/Packs/CommonScripts/Scripts/Base64ListToFile/Base64ListToFile.py
+++ b/Packs/CommonScripts/Scripts/Base64ListToFile/Base64ListToFile.py
@@ -1,8 +1,9 @@
-import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
import base64
import zlib
+import demistomock as demisto # noqa: F401
+from CommonServerPython import * # noqa: F401
+
def base64_list_to_file(args):
# Output file name
diff --git a/Packs/CommonScripts/Scripts/Base64ListToFile/Base64ListToFile_test.py b/Packs/CommonScripts/Scripts/Base64ListToFile/Base64ListToFile_test.py
index 70e6f81f43f3..b94eef85719f 100644
--- a/Packs/CommonScripts/Scripts/Base64ListToFile/Base64ListToFile_test.py
+++ b/Packs/CommonScripts/Scripts/Base64ListToFile/Base64ListToFile_test.py
@@ -1,9 +1,9 @@
-import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
-
import base64
import zlib
+import demistomock as demisto # noqa: F401
+from CommonServerPython import * # noqa: F401
+
def test_valid_base64_file_in_list(mocker, tmp_path):
import Base64ListToFile
diff --git a/Packs/CommonScripts/Scripts/BreachConfirmationHTML/BreachConfirmationHTML.py b/Packs/CommonScripts/Scripts/BreachConfirmationHTML/BreachConfirmationHTML.py
index 94dc7b9b9c86..ba8e9eba1e14 100644
--- a/Packs/CommonScripts/Scripts/BreachConfirmationHTML/BreachConfirmationHTML.py
+++ b/Packs/CommonScripts/Scripts/BreachConfirmationHTML/BreachConfirmationHTML.py
@@ -25,7 +25,7 @@ def main():
})
except Exception as ex:
- return_error(f'Failed to execute calculate entropy script. Error: {str(ex)}')
+ return_error(f'Failed to execute calculate entropy script. Error: {ex!s}')
if __name__ in ('__main__', '__builtin__', 'builtins'):
diff --git a/Packs/CommonScripts/Scripts/BreachConfirmationHTML/BreachConfirmationHTML_test.py b/Packs/CommonScripts/Scripts/BreachConfirmationHTML/BreachConfirmationHTML_test.py
index 532b09a06379..b811ef3ee772 100644
--- a/Packs/CommonScripts/Scripts/BreachConfirmationHTML/BreachConfirmationHTML_test.py
+++ b/Packs/CommonScripts/Scripts/BreachConfirmationHTML/BreachConfirmationHTML_test.py
@@ -1,9 +1,8 @@
-from BreachConfirmationHTML import main
-import pytest
import demistomock as demisto
+import pytest
+from BreachConfirmationHTML import main
from CommonServerPython import *
-
ARGS_MAIN = [
([{}],
"
Pending Confirmation
"),
diff --git a/Packs/CommonScripts/Scripts/CVECVSSColor/CVECVSSColor.py b/Packs/CommonScripts/Scripts/CVECVSSColor/CVECVSSColor.py
index 4b2611a1cdbc..416f6a387430 100644
--- a/Packs/CommonScripts/Scripts/CVECVSSColor/CVECVSSColor.py
+++ b/Packs/CommonScripts/Scripts/CVECVSSColor/CVECVSSColor.py
@@ -1,7 +1,8 @@
-from CommonServerPython import *
import math
+from CommonServerPython import *
+
def get_color(cvss: int | float) -> str:
"""
diff --git a/Packs/CommonScripts/Scripts/CVECVSSColor/CVECVSSColor_test.py b/Packs/CommonScripts/Scripts/CVECVSSColor/CVECVSSColor_test.py
index 6d1e23963378..fcb64ed15a00 100644
--- a/Packs/CommonScripts/Scripts/CVECVSSColor/CVECVSSColor_test.py
+++ b/Packs/CommonScripts/Scripts/CVECVSSColor/CVECVSSColor_test.py
@@ -1,5 +1,5 @@
-import pytest
import demistomock as demisto
+import pytest
from CVECVSSColor import *
diff --git a/Packs/CommonScripts/Scripts/CVSSCalculator/CVSSCalculator.py b/Packs/CommonScripts/Scripts/CVSSCalculator/CVSSCalculator.py
index 9936c7dbd3bd..c857173ca1d0 100644
--- a/Packs/CommonScripts/Scripts/CVSSCalculator/CVSSCalculator.py
+++ b/Packs/CommonScripts/Scripts/CVSSCalculator/CVSSCalculator.py
@@ -1,9 +1,9 @@
+import math
+from typing import Any
+
import demistomock as demisto
from CommonServerPython import *
-import math
-from typing import Dict, Any
-
def round_up(n):
if n is None:
@@ -20,7 +20,7 @@ def main():
version = args.get('version', '3.1')
vector_string = f"CVSS:{version}/"
- values_map_options: Dict[str, Dict[str, Dict[str, Any]]] = {
+ values_map_options: dict[str, dict[str, dict[str, Any]]] = {
"3.0": {
"AV": {
"X": None,
@@ -237,7 +237,7 @@ def main():
if scope_changed:
multiplier = 1.08
calculated_value = multiplier * (impact + exploitability)
- base_score = calculated_value if calculated_value < 10.0 else 10.0
+ base_score = min(10.0, calculated_value)
base_score = round_up(base_score)
###########################################
@@ -259,8 +259,7 @@ def main():
* (1 - availability_requirement * modified_availability)
)
)
- modified_impact_sub_score = calculatedmodified_impact_sub_score if calculatedmodified_impact_sub_score < 0.915\
- else 0.915
+ modified_impact_sub_score = min(0.915, calculatedmodified_impact_sub_score)
if version in ['3.0', '3.1']:
if modified_scope_changed:
@@ -284,7 +283,7 @@ def main():
if modified_scope_changed:
exponential = 1.08
calculated_value = exponential * (modified_impact + modified_exploitability)
- calculated_value = calculated_value if calculated_value < 10 else 10
+ calculated_value = min(10, calculated_value)
calculated_value = round_up(calculated_value)
environmental_score = calculated_value * exploit_code_maturity * remediation_level * report_confidence
environmental_score = round_up(environmental_score)
diff --git a/Packs/CommonScripts/Scripts/CalculateEntropy/CalculateEntropy.py b/Packs/CommonScripts/Scripts/CalculateEntropy/CalculateEntropy.py
index 6504046ddb62..be74da1e01bf 100644
--- a/Packs/CommonScripts/Scripts/CalculateEntropy/CalculateEntropy.py
+++ b/Packs/CommonScripts/Scripts/CalculateEntropy/CalculateEntropy.py
@@ -1,8 +1,10 @@
+import math
+import string
+
import demistomock as demisto
from CommonServerPython import * # noqa: E402 lgtm [py/polluting-import]
+
from CommonServerUserPython import * # noqa: E402 lgtm [py/polluting-import]
-import math
-import string
def calculate_shannon_entropy(data, minimum_entropy):
@@ -20,7 +22,7 @@ def calculate_shannon_entropy(data, minimum_entropy):
# probability of event X
p_x = float(data.count(chr(char))) / len(data)
if p_x > 0:
- entropy += - p_x * math.log(p_x, 2)
+ entropy += - p_x * math.log2(p_x)
if entropy >= minimum_entropy:
human_readable = tableToMarkdown("Entropy results", {'Checked Value': data, 'Entropy': entropy},
headers=['Checked Value', 'Entropy'])
@@ -37,7 +39,7 @@ def main():
return_outputs(*calculate_shannon_entropy(data, minimum_entropy))
except Exception as ex:
- return_error(f'Failed to execute calculate entropy script. Error: {str(ex)}')
+ return_error(f'Failed to execute calculate entropy script. Error: {ex!s}')
if __name__ in ('__main__', '__builtin__', 'builtins'):
diff --git a/Packs/CommonScripts/Scripts/CalculateTimeDifference/CalculateTimeDifference.py b/Packs/CommonScripts/Scripts/CalculateTimeDifference/CalculateTimeDifference.py
index fff58b5d1530..86123e1bb892 100644
--- a/Packs/CommonScripts/Scripts/CalculateTimeDifference/CalculateTimeDifference.py
+++ b/Packs/CommonScripts/Scripts/CalculateTimeDifference/CalculateTimeDifference.py
@@ -1,5 +1,6 @@
import demistomock as demisto
from CommonServerPython import *
+
from CommonServerUserPython import *
start_time = demisto.args()['start_time'].replace('"', '')
@@ -13,7 +14,7 @@
time_diff = end_time_obj - start_time_obj
mins = round((time_diff.total_seconds() / 60), 2)
- hr = 'Calculated Time Difference: {} minutes.'.format(str(mins))
+ hr = f'Calculated Time Difference: {mins!s} minutes.'
context = {
"Time.Difference": mins,
"Time.Start": start_time,
diff --git a/Packs/CommonScripts/Scripts/CertificateExtract/CertificateExtract.py b/Packs/CommonScripts/Scripts/CertificateExtract/CertificateExtract.py
index a9c618a0b785..e653cd9bfbb8 100644
--- a/Packs/CommonScripts/Scripts/CertificateExtract/CertificateExtract.py
+++ b/Packs/CommonScripts/Scripts/CertificateExtract/CertificateExtract.py
@@ -1,21 +1,15 @@
+from typing import Any, cast
+
import demistomock as demisto
from CommonServerPython import * # noqa # pylint: disable=unused-wildcard-import
-from CommonServerUserPython import * # noqa # pylint: disable=unused-wildcard-import
+from cryptography import x509
+
# mypy: ignore-errors
from cryptography.hazmat import backends
-from cryptography.hazmat.primitives import (
- hashes,
- asymmetric,
- serialization
-)
-from cryptography import x509
-from cryptography.x509 import (
- oid,
- extensions,
- general_name,
- certificate_transparency
-)
-from typing import Any, cast
+from cryptography.hazmat.primitives import asymmetric, hashes, serialization
+from cryptography.x509 import certificate_transparency, extensions, general_name, oid
+
+from CommonServerUserPython import * # noqa # pylint: disable=unused-wildcard-import
_INSTANCE_TO_TYPE = {
general_name.OtherName: 'otherName',
@@ -472,7 +466,7 @@ def main():
try:
return_results(certificate_extract_command(demisto.args()))
except Exception as ex:
- return_error(f'Failed to execute CertificateExtract. Error: {str(ex)}')
+ return_error(f'Failed to execute CertificateExtract. Error: {ex!s}')
''' ENTRY POINT '''
diff --git a/Packs/CommonScripts/Scripts/CertificateReputation/CertificateReputation.py b/Packs/CommonScripts/Scripts/CertificateReputation/CertificateReputation.py
index a76beb9f1363..6ceb2ac9ce3c 100644
--- a/Packs/CommonScripts/Scripts/CertificateReputation/CertificateReputation.py
+++ b/Packs/CommonScripts/Scripts/CertificateReputation/CertificateReputation.py
@@ -1,12 +1,12 @@
-import demistomock as demisto
-from CommonServerPython import * # noqa # pylint: disable=unused-wildcard-import
-from CommonServerUserPython import * # noqa # pylint: disable=unused-wildcard-import
-
-import dateparser
from datetime import timedelta
from enum import Enum
from typing import Any
+import dateparser
+import demistomock as demisto
+from CommonServerPython import * # noqa # pylint: disable=unused-wildcard-import
+
+from CommonServerUserPython import * # noqa # pylint: disable=unused-wildcard-import
# Threshold defining "long expiration". When validity_not_after - validity_not_before is greater than
# this value the certificate will be marked as Long Expiration
@@ -317,7 +317,7 @@ def main():
try:
return_results(certificate_reputation_command(demisto.args()))
except Exception as ex:
- return_error(f'Failed to execute CertificateReputation. Error: {str(ex)}')
+ return_error(f'Failed to execute CertificateReputation. Error: {ex!s}')
''' ENTRY POINT '''
diff --git a/Packs/CommonScripts/Scripts/ChangeContext/ChangeContext.py b/Packs/CommonScripts/Scripts/ChangeContext/ChangeContext.py
index 3fe0bb9e2abe..b8b89940db0c 100644
--- a/Packs/CommonScripts/Scripts/ChangeContext/ChangeContext.py
+++ b/Packs/CommonScripts/Scripts/ChangeContext/ChangeContext.py
@@ -1,7 +1,7 @@
-from CommonServerPython import *
-
import json
+from CommonServerPython import *
+
def replace_context(args: dict) -> tuple:
context = args.get('input', '')
diff --git a/Packs/CommonScripts/Scripts/ChangeRemediationSLAOnSevChange/ChangeRemediationSLAOnSevChange.py b/Packs/CommonScripts/Scripts/ChangeRemediationSLAOnSevChange/ChangeRemediationSLAOnSevChange.py
index 26111ed49853..88622ba2df82 100644
--- a/Packs/CommonScripts/Scripts/ChangeRemediationSLAOnSevChange/ChangeRemediationSLAOnSevChange.py
+++ b/Packs/CommonScripts/Scripts/ChangeRemediationSLAOnSevChange/ChangeRemediationSLAOnSevChange.py
@@ -1,8 +1,8 @@
+from datetime import datetime, timedelta
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-from datetime import datetime, timedelta
-
# ##### Help #####
# This is an example script. The script is used to change the Remediation SLA of an incident,
# when the severity of the incident changes for any reason. Please copy this script and make changes to your liking.
diff --git a/Packs/CommonScripts/Scripts/ChangeRemediationSLAOnSevChange/ChangeRemediationSLAOnSevChange_test.py b/Packs/CommonScripts/Scripts/ChangeRemediationSLAOnSevChange/ChangeRemediationSLAOnSevChange_test.py
index 4e1778051986..dd36402ddaa4 100644
--- a/Packs/CommonScripts/Scripts/ChangeRemediationSLAOnSevChange/ChangeRemediationSLAOnSevChange_test.py
+++ b/Packs/CommonScripts/Scripts/ChangeRemediationSLAOnSevChange/ChangeRemediationSLAOnSevChange_test.py
@@ -1,6 +1,5 @@
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-
from freezegun import freeze_time
diff --git a/Packs/CommonScripts/Scripts/CheckContextValue/CheckContextValue.py b/Packs/CommonScripts/Scripts/CheckContextValue/CheckContextValue.py
index 9cfe6b059d16..55f2a98f1a28 100644
--- a/Packs/CommonScripts/Scripts/CheckContextValue/CheckContextValue.py
+++ b/Packs/CommonScripts/Scripts/CheckContextValue/CheckContextValue.py
@@ -1,4 +1,3 @@
-from typing import Dict
from CommonServerPython import *
@@ -13,7 +12,7 @@ def check_key(field_value, regex=None):
return False
-def poll_field(args: Dict[str, Any]) -> CommandResults:
+def poll_field(args: dict[str, Any]) -> CommandResults:
keys_list = args.get('key', '').split(".")
regex = args.get('regex')
ignore_case = argToBoolean(args.get('ignore_case', 'False'))
@@ -46,7 +45,7 @@ def main():
return_results(poll_field(demisto.args()))
except Exception as err:
demisto.error(traceback.format_exc()) # print the traceback
- return_error(f'Failed to execute CheckFieldValue script. Error: {str(err)}')
+ return_error(f'Failed to execute CheckFieldValue script. Error: {err!s}')
''' ENTRY POINT '''
diff --git a/Packs/CommonScripts/Scripts/CheckContextValue/CheckContextValue_test.py b/Packs/CommonScripts/Scripts/CheckContextValue/CheckContextValue_test.py
index 741ff6a50d93..5b6d8911f515 100644
--- a/Packs/CommonScripts/Scripts/CheckContextValue/CheckContextValue_test.py
+++ b/Packs/CommonScripts/Scripts/CheckContextValue/CheckContextValue_test.py
@@ -1,5 +1,5 @@
-from CommonServerPython import *
from CheckContextValue import poll_field
+from CommonServerPython import *
context = {
'id': 1,
diff --git a/Packs/CommonScripts/Scripts/CheckFieldValue/CheckFieldValue.py b/Packs/CommonScripts/Scripts/CheckFieldValue/CheckFieldValue.py
index d9b6f4418b08..83aabb06f4df 100644
--- a/Packs/CommonScripts/Scripts/CheckFieldValue/CheckFieldValue.py
+++ b/Packs/CommonScripts/Scripts/CheckFieldValue/CheckFieldValue.py
@@ -1,4 +1,3 @@
-from typing import Dict
from CommonServerPython import *
@@ -13,7 +12,7 @@ def check_field(field_value, regex=None):
return False
-def poll_field(args: Dict[str, Any]) -> CommandResults:
+def poll_field(args: dict[str, Any]) -> CommandResults:
field = args.get('field')
regex = args.get('regex')
ignore_case = argToBoolean(args.get('ignore_case', 'False'))
@@ -50,7 +49,7 @@ def main():
return_results(poll_field(demisto.args()))
except Exception as ex:
demisto.error(traceback.format_exc()) # print the traceback
- return_error(f'Failed to execute CheckFieldValue script. Error: {str(ex)}')
+ return_error(f'Failed to execute CheckFieldValue script. Error: {ex!s}')
''' ENTRY POINT '''
diff --git a/Packs/CommonScripts/Scripts/CheckFieldValue/CheckFieldValue_test.py b/Packs/CommonScripts/Scripts/CheckFieldValue/CheckFieldValue_test.py
index 167b527abeba..5f916512f72f 100644
--- a/Packs/CommonScripts/Scripts/CheckFieldValue/CheckFieldValue_test.py
+++ b/Packs/CommonScripts/Scripts/CheckFieldValue/CheckFieldValue_test.py
@@ -1,5 +1,5 @@
-from CommonServerPython import *
from CheckFieldValue import poll_field
+from CommonServerPython import *
incident_contains_field_in_custom_fields = {
'id': 1,
diff --git a/Packs/CommonScripts/Scripts/CheckIndicatorValue/CheckIndicatorValue.py b/Packs/CommonScripts/Scripts/CheckIndicatorValue/CheckIndicatorValue.py
index 0780d9692f07..8c143241aaad 100644
--- a/Packs/CommonScripts/Scripts/CheckIndicatorValue/CheckIndicatorValue.py
+++ b/Packs/CommonScripts/Scripts/CheckIndicatorValue/CheckIndicatorValue.py
@@ -1,8 +1,9 @@
-import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
import base64
import urllib.parse
-from typing import Any, Dict, Optional
+from typing import Any
+
+import demistomock as demisto # noqa: F401
+from CommonServerPython import * # noqa: F401
def exists_indicator(indicator: str) -> bool:
@@ -12,7 +13,7 @@ def exists_indicator(indicator: str) -> bool:
return False
-def decode_indicator(indicator: str, encoding: Optional[str]) -> str:
+def decode_indicator(indicator: str, encoding: str | None) -> str:
if not encoding or encoding == 'none':
return indicator
elif encoding == 'base64':
@@ -23,7 +24,7 @@ def decode_indicator(indicator: str, encoding: Optional[str]) -> str:
raise DemistoException(f'Unknown encoding mode: {encoding}')
-def check_indicators(indicators: List[str], encoding: str) -> List[Dict[str, Any]]:
+def check_indicators(indicators: List[str], encoding: str) -> List[dict[str, Any]]:
# Decode and dedup indicators
pairs = {decode_indicator(encoded_indicator, encoding): encoded_indicator for encoded_indicator in indicators}
@@ -52,7 +53,7 @@ def main():
raw_response=outputs
))
except Exception as e:
- return_error(f'Failed to execute CheckIndicatorValue. Error: {str(e)}')
+ return_error(f'Failed to execute CheckIndicatorValue. Error: {e!s}')
if __name__ in ('__main__', '__builtin__', 'builtins'):
diff --git a/Packs/CommonScripts/Scripts/CheckIndicatorValue/CheckIndicatorValue_test.py b/Packs/CommonScripts/Scripts/CheckIndicatorValue/CheckIndicatorValue_test.py
index 2a534a2895e6..e317eefdd172 100644
--- a/Packs/CommonScripts/Scripts/CheckIndicatorValue/CheckIndicatorValue_test.py
+++ b/Packs/CommonScripts/Scripts/CheckIndicatorValue/CheckIndicatorValue_test.py
@@ -1,7 +1,8 @@
+from typing import Any
+
import demistomock as demisto
-from CommonServerPython import * # noqa: F401
import pytest
-from typing import List, Dict, Any
+from CommonServerPython import * # noqa: F401
def equals_object(obj1, obj2) -> bool:
@@ -30,10 +31,10 @@ def equals_object(obj1, obj2) -> bool:
class GetIndicator:
- def __init__(self, indicators: List[str]):
+ def __init__(self, indicators: list[str]):
self.__indicators = indicators
- def get_indicator(self, cmd: str, params: Dict[str, Any]) -> list:
+ def get_indicator(self, cmd: str, params: dict[str, Any]) -> list:
indicator = params.get('value')
if indicator in self.__indicators:
return [{'value': indicator}]
diff --git a/Packs/CommonScripts/Scripts/CheckSenderDomainDistance/CheckSenderDomainDistance.py b/Packs/CommonScripts/Scripts/CheckSenderDomainDistance/CheckSenderDomainDistance.py
index 0eb404100dc2..abcf8ef707ec 100644
--- a/Packs/CommonScripts/Scripts/CheckSenderDomainDistance/CheckSenderDomainDistance.py
+++ b/Packs/CommonScripts/Scripts/CheckSenderDomainDistance/CheckSenderDomainDistance.py
@@ -8,8 +8,8 @@ def levenshtein(s1, s2):
matrix = [list(range(l1 + 1))] * (l2 + 1)
for zz in range(l2 + 1):
matrix[zz] = list(range(zz, zz + l1 + 1))
- for zz in range(0, l2):
- for sz in range(0, l1):
+ for zz in range(l2):
+ for sz in range(l1):
if s1[sz] == s2[zz]:
matrix[zz + 1][sz + 1] = min(matrix[zz + 1][sz] + 1, matrix[zz][sz + 1] + 1, matrix[zz][sz])
else:
@@ -30,7 +30,7 @@ def main():
if sender:
parts = sender.split('@')
if len(parts) == 2:
- if not parts[1] in domains:
+ if parts[1] not in domains:
distances = []
for domain in domains:
distance = levenshtein(domain, parts[1])
diff --git a/Packs/CommonScripts/Scripts/ClearUserSession/ClearUserSession.py b/Packs/CommonScripts/Scripts/ClearUserSession/ClearUserSession.py
index 46239d494c24..2b48f879480f 100644
--- a/Packs/CommonScripts/Scripts/ClearUserSession/ClearUserSession.py
+++ b/Packs/CommonScripts/Scripts/ClearUserSession/ClearUserSession.py
@@ -1,8 +1,7 @@
-import demistomock as demisto
-from CommonServerPython import *
-
from typing import Any
+import demistomock as demisto
+from CommonServerPython import *
OKTA_BRAND = "Okta v2"
MS_GRAPH_BRAND = "Microsoft Graph User"
@@ -446,7 +445,7 @@ def main():
return_results(command_results_list)
except Exception as e:
- return_error(f"Failed to execute clear-user-session. Error: {str(e)}")
+ return_error(f"Failed to execute clear-user-session. Error: {e!s}")
""" ENTRY POINT """
diff --git a/Packs/CommonScripts/Scripts/ClearUserSession/ClearUserSession_test.py b/Packs/CommonScripts/Scripts/ClearUserSession/ClearUserSession_test.py
index d99e219ebb14..656dca8bc5ff 100644
--- a/Packs/CommonScripts/Scripts/ClearUserSession/ClearUserSession_test.py
+++ b/Packs/CommonScripts/Scripts/ClearUserSession/ClearUserSession_test.py
@@ -1,20 +1,18 @@
-from pytest_mock import MockerFixture
-
import demistomock as demisto
-from CommonServerPython import *
-
from ClearUserSession import (
Command,
- prepare_human_readable,
- get_output_key,
- run_execute_command,
- remove_system_user,
+ clear_user_sessions,
extract_usernames_with_ids,
+ get_output_key,
get_user_data,
get_user_id,
- clear_user_sessions,
main,
+ prepare_human_readable,
+ remove_system_user,
+ run_execute_command,
)
+from CommonServerPython import *
+from pytest_mock import MockerFixture
def test_is_valid_args_with_valid_args():
diff --git a/Packs/CommonScripts/Scripts/CloseInvestigationAsDuplicate/CloseInvestigationAsDuplicate.py b/Packs/CommonScripts/Scripts/CloseInvestigationAsDuplicate/CloseInvestigationAsDuplicate.py
index b40c8c9f1a95..53e6f09f3526 100644
--- a/Packs/CommonScripts/Scripts/CloseInvestigationAsDuplicate/CloseInvestigationAsDuplicate.py
+++ b/Packs/CommonScripts/Scripts/CloseInvestigationAsDuplicate/CloseInvestigationAsDuplicate.py
@@ -1,5 +1,6 @@
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
+
current_incident_id = demisto.incidents()[0]['id']
duplicate_id = demisto.args()['duplicateId']
res = demisto.executeCommand("linkIncidents", {"incidentId": duplicate_id, "linkedIncidentIDs": current_incident_id,
diff --git a/Packs/CommonScripts/Scripts/CommandLineAnalysis/CommandLineAnalysis.py b/Packs/CommonScripts/Scripts/CommandLineAnalysis/CommandLineAnalysis.py
index bf9259559a0a..5a009779c247 100644
--- a/Packs/CommonScripts/Scripts/CommandLineAnalysis/CommandLineAnalysis.py
+++ b/Packs/CommonScripts/Scripts/CommandLineAnalysis/CommandLineAnalysis.py
@@ -1,11 +1,12 @@
-import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
import base64
-import re
import ipaddress
import json
+import re
from typing import Any
+import demistomock as demisto # noqa: F401
+from CommonServerPython import * # noqa: F401
+
def is_base64(possible_base64: str | bytes) -> bool:
"""
@@ -512,7 +513,7 @@ def extract_indicators(command_line: str) -> list[str]:
continue # Skip reserved IPs
extracted_indicators.append(value)
except Exception as e:
- demisto.debug(f"Failed to extract indicators: {str(e)}")
+ demisto.debug(f"Failed to extract indicators: {e!s}")
return extracted_indicators
diff --git a/Packs/CommonScripts/Scripts/CommandLineAnalysis/CommandLineAnalysis_test.py b/Packs/CommonScripts/Scripts/CommandLineAnalysis/CommandLineAnalysis_test.py
index e56f1c8db1f3..5bfb25936244 100644
--- a/Packs/CommonScripts/Scripts/CommandLineAnalysis/CommandLineAnalysis_test.py
+++ b/Packs/CommonScripts/Scripts/CommandLineAnalysis/CommandLineAnalysis_test.py
@@ -1,21 +1,20 @@
import pytest
from CommandLineAnalysis import (
- is_base64,
- remove_null_bytes,
- decode_base64,
- identify_and_decode_base64,
- reverse_command,
- check_malicious_commands,
- check_reconnaissance_temp,
- check_windows_temp_paths,
- check_suspicious_content,
+ analyze_command_line,
check_amsi,
+ check_malicious_commands,
check_mixed_case_powershell,
check_powershell_suspicious_patterns,
- analyze_command_line
+ check_reconnaissance_temp,
+ check_suspicious_content,
+ check_windows_temp_paths,
+ decode_base64,
+ identify_and_decode_base64,
+ is_base64,
+ remove_null_bytes,
+ reverse_command,
)
-
# Test data
DOUBLE_ENCODED_STRING = "cmVjdXJzaXZlIGRlY29kZSBaR1ZqYjJSbElGWkhhSEJqZVVKd1kzbENhRWxJVW14ak0xRm5Zek5TZVdGWE5XND0="
MALICIOUS_COMMAND_LINE = "wevtutil cl Security RG91YmxlIGVuY29kaW5nIFZHaHBjeUJwY3lCaElHeHBjM1JsYm1WeUtERXhMakV3TVM0eE1qUXVNaklw"
diff --git a/Packs/CommonScripts/Scripts/CompareIncidentsLabels/CompareIncidentsLabels.py b/Packs/CommonScripts/Scripts/CompareIncidentsLabels/CompareIncidentsLabels.py
index cdc3fe52f588..480be0cae45e 100644
--- a/Packs/CommonScripts/Scripts/CompareIncidentsLabels/CompareIncidentsLabels.py
+++ b/Packs/CommonScripts/Scripts/CompareIncidentsLabels/CompareIncidentsLabels.py
@@ -7,13 +7,13 @@
res = demisto.executeCommand("getIncidents", {'id': inc1})
if any(is_error(entry) for entry in res):
- return_error("Unable to fetch incident {}".format(inc1))
+ return_error(f"Unable to fetch incident {inc1}")
inc1_data = res[0].get('Contents').get('data')
res = demisto.executeCommand("getIncidents", {'id': inc2})
if any(is_error(entry) for entry in res):
- return_error("Unable to fetch incident {}".format(inc2))
+ return_error(f"Unable to fetch incident {inc2}")
inc2_data = res[0].get('Contents').get('data')
@@ -31,8 +31,8 @@
if label not in inc1_labels:
in2not1.append(label)
- md = tableToMarkdown("Labels of incident {} but not of incident {}".format(inc1, inc2), in1not2)
- md += "\n" + tableToMarkdown("Labels of incident {1} but not of incident {0}".format(inc1, inc2), in2not1)
+ md = tableToMarkdown(f"Labels of incident {inc1} but not of incident {inc2}", in1not2)
+ md += "\n" + tableToMarkdown(f"Labels of incident {inc2} but not of incident {inc1}", in2not1)
if not in2not1 and not in1not2:
md = "No different labels."
diff --git a/Packs/CommonScripts/Scripts/ContentPackInstaller/ContentPackInstaller.py b/Packs/CommonScripts/Scripts/ContentPackInstaller/ContentPackInstaller.py
index d99d0792f901..09cb72e300ba 100644
--- a/Packs/CommonScripts/Scripts/ContentPackInstaller/ContentPackInstaller.py
+++ b/Packs/CommonScripts/Scripts/ContentPackInstaller/ContentPackInstaller.py
@@ -1,7 +1,6 @@
import demistomock as demisto
from CommonServerPython import *
-
-from packaging.version import parse, Version
+from packaging.version import Version, parse
SCRIPT_NAME = 'ContentPackInstaller'
@@ -174,7 +173,7 @@ def install_packs(self, packs_to_install: List[Dict[str, str]]) -> None:
status, res = self._call_execute_command('core-api-install-packs', args)
if not status:
- demisto.error(f'{SCRIPT_NAME} - Failed to install the pack {pack_id} - {str(res)}')
+ demisto.error(f'{SCRIPT_NAME} - Failed to install the pack {pack_id} - {res!s}')
self.packs_failed[pack_id] = str(pack['version'])
else:
self.installed_packs[pack_id] = packs_names_versions[pack_id]
diff --git a/Packs/CommonScripts/Scripts/ContentPackInstaller/ContentPackInstaller_test.py b/Packs/CommonScripts/Scripts/ContentPackInstaller/ContentPackInstaller_test.py
index b2ed7a2ca160..00e9c2c8a381 100644
--- a/Packs/CommonScripts/Scripts/ContentPackInstaller/ContentPackInstaller_test.py
+++ b/Packs/CommonScripts/Scripts/ContentPackInstaller/ContentPackInstaller_test.py
@@ -1,7 +1,7 @@
import pytest
+from ContentPackInstaller import *
from Packs.CommonScripts.Scripts.ContentPackInstaller.ContentPackInstaller import ContentPackInstaller
-from ContentPackInstaller import *
def get_content_pack_installer(mocker):
diff --git a/Packs/CommonScripts/Scripts/ConvertCountryCodeCountryName/ConvertCountryCodeCountryName.py b/Packs/CommonScripts/Scripts/ConvertCountryCodeCountryName/ConvertCountryCodeCountryName.py
index f72f21903e35..e9d29d87a9b6 100644
--- a/Packs/CommonScripts/Scripts/ConvertCountryCodeCountryName/ConvertCountryCodeCountryName.py
+++ b/Packs/CommonScripts/Scripts/ConvertCountryCodeCountryName/ConvertCountryCodeCountryName.py
@@ -160,7 +160,7 @@ def main():
return_results(country_code)
except Exception as ex:
- return_error(f'Failed to execute ConvertCountryCodeCountryName. Error: {str(ex)}')
+ return_error(f'Failed to execute ConvertCountryCodeCountryName. Error: {ex!s}')
''' ENTRY POINT '''
diff --git a/Packs/CommonScripts/Scripts/ConvertCountryCodeCountryName/ConvertCountryCodeCountryName_test.py b/Packs/CommonScripts/Scripts/ConvertCountryCodeCountryName/ConvertCountryCodeCountryName_test.py
index c487cd37e165..3afd3b79e421 100644
--- a/Packs/CommonScripts/Scripts/ConvertCountryCodeCountryName/ConvertCountryCodeCountryName_test.py
+++ b/Packs/CommonScripts/Scripts/ConvertCountryCodeCountryName/ConvertCountryCodeCountryName_test.py
@@ -1,8 +1,6 @@
-import pytest
-
import ConvertCountryCodeCountryName
import demistomock as demisto
-
+import pytest
upper_country_code = ('IL', None, 'Israel')
lower_country_code = ('il', None, 'Israel')
diff --git a/Packs/CommonScripts/Scripts/ConvertDateToUTC/ConvertDateToUTC.py b/Packs/CommonScripts/Scripts/ConvertDateToUTC/ConvertDateToUTC.py
index cffad62add74..67b7257751bc 100644
--- a/Packs/CommonScripts/Scripts/ConvertDateToUTC/ConvertDateToUTC.py
+++ b/Packs/CommonScripts/Scripts/ConvertDateToUTC/ConvertDateToUTC.py
@@ -1,7 +1,6 @@
import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
import pytz
-
+from CommonServerPython import * # noqa: F401
''' MAIN FUNCTION '''
@@ -38,7 +37,7 @@ def main():
except Exception as exc:
demisto.error(traceback.format_exc()) # print the traceback
- return_error(f'Failed to execute ConvertDateToUTC. Error: {str(exc)}')
+ return_error(f'Failed to execute ConvertDateToUTC. Error: {exc!s}')
''' ENTRY POINT '''
diff --git a/Packs/CommonScripts/Scripts/ConvertFile/ConvertFile.py b/Packs/CommonScripts/Scripts/ConvertFile/ConvertFile.py
index 07fbdc292278..b69ea045cc56 100644
--- a/Packs/CommonScripts/Scripts/ConvertFile/ConvertFile.py
+++ b/Packs/CommonScripts/Scripts/ConvertFile/ConvertFile.py
@@ -1,13 +1,13 @@
-import demistomock as demisto
-from CommonServerPython import *
-
-import subprocess
import glob
import os
-import tempfile
import shutil
+import subprocess
+import tempfile
import traceback
+import demistomock as demisto
+from CommonServerPython import *
+
def find_zombie_processes():
"""find zombie proceses
diff --git a/Packs/CommonScripts/Scripts/ConvertFile/ConvertFile_test.py b/Packs/CommonScripts/Scripts/ConvertFile/ConvertFile_test.py
index 88bebe57e1fb..99bde3207dcd 100644
--- a/Packs/CommonScripts/Scripts/ConvertFile/ConvertFile_test.py
+++ b/Packs/CommonScripts/Scripts/ConvertFile/ConvertFile_test.py
@@ -1,11 +1,12 @@
+import glob
+import logging
+import os
import subprocess
-from ConvertFile import main, find_zombie_processes
+
import demistomock as demisto
-from CommonServerPython import entryTypes
-import logging
import pytest
-import glob
-import os
+from CommonServerPython import entryTypes
+from ConvertFile import find_zombie_processes, main
RETURN_ERROR_TARGET = 'ConvertFile.return_error'
diff --git a/Packs/CommonScripts/Scripts/ConvertTimezoneFromUTC/ConvertTimezoneFromUTC.py b/Packs/CommonScripts/Scripts/ConvertTimezoneFromUTC/ConvertTimezoneFromUTC.py
index d9a61aa71d8d..e9d91b320cee 100644
--- a/Packs/CommonScripts/Scripts/ConvertTimezoneFromUTC/ConvertTimezoneFromUTC.py
+++ b/Packs/CommonScripts/Scripts/ConvertTimezoneFromUTC/ConvertTimezoneFromUTC.py
@@ -1,7 +1,8 @@
+from traceback import format_exc
+
import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
import pytz
-from traceback import format_exc
+from CommonServerPython import * # noqa: F401
def determine_correct_format(time: str, fmt: str) -> datetime:
diff --git a/Packs/CommonScripts/Scripts/ConvertTimezoneFromUTC/ConvertTimezoneFromUTC_test.py b/Packs/CommonScripts/Scripts/ConvertTimezoneFromUTC/ConvertTimezoneFromUTC_test.py
index 2bf46ecfd894..874d62dc129b 100644
--- a/Packs/CommonScripts/Scripts/ConvertTimezoneFromUTC/ConvertTimezoneFromUTC_test.py
+++ b/Packs/CommonScripts/Scripts/ConvertTimezoneFromUTC/ConvertTimezoneFromUTC_test.py
@@ -1,7 +1,7 @@
-from ConvertTimezoneFromUTC import convert_UTC_Timezone_command
-from ConvertTimezoneFromUTC import determine_correct_format
from datetime import datetime
+from ConvertTimezoneFromUTC import convert_UTC_Timezone_command, determine_correct_format
+
def test_convert_UTC_Timezone_command():
"""
diff --git a/Packs/CommonScripts/Scripts/ConvertXmlFileToJson/ConvertXmlFileToJson.py b/Packs/CommonScripts/Scripts/ConvertXmlFileToJson/ConvertXmlFileToJson.py
index de14a60d4b3d..5d9d37613ed0 100644
--- a/Packs/CommonScripts/Scripts/ConvertXmlFileToJson/ConvertXmlFileToJson.py
+++ b/Packs/CommonScripts/Scripts/ConvertXmlFileToJson/ConvertXmlFileToJson.py
@@ -1,6 +1,6 @@
import demistomock as demisto
-from CommonServerPython import *
import xmltodict
+from CommonServerPython import *
def convert_file(entry_id: str, verbose: bool, context_key: str) -> None:
@@ -28,7 +28,7 @@ def main(): # pragma: no cover
try:
convert_file(entry_id, verbose, context_key)
except Exception as e:
- return_error(f"Convert XML File to Json Failed: Error: {str(e)}")
+ return_error(f"Convert XML File to Json Failed: Error: {e!s}")
if __name__ in ('__main__', '__builtin__', 'builtins'):
diff --git a/Packs/CommonScripts/Scripts/CopyNotesToIncident/CopyNotesToIncident.py b/Packs/CommonScripts/Scripts/CopyNotesToIncident/CopyNotesToIncident.py
index da0b6c1923fa..f5edf392bb02 100644
--- a/Packs/CommonScripts/Scripts/CopyNotesToIncident/CopyNotesToIncident.py
+++ b/Packs/CommonScripts/Scripts/CopyNotesToIncident/CopyNotesToIncident.py
@@ -55,7 +55,7 @@ def main():
return_results(copy_notes_to_target_incident(demisto.args()))
except Exception as ex:
demisto.error(traceback.format_exc()) # print the traceback
- return_error(f'Failed to execute CopyNotesToIncident. Error: {str(ex)}')
+ return_error(f'Failed to execute CopyNotesToIncident. Error: {ex!s}')
''' ENTRY POINT '''
diff --git a/Packs/CommonScripts/Scripts/CopyNotesToIncident/CopyNotesToIncident_test.py b/Packs/CommonScripts/Scripts/CopyNotesToIncident/CopyNotesToIncident_test.py
index 21818c2556d6..55cafef9fab6 100644
--- a/Packs/CommonScripts/Scripts/CopyNotesToIncident/CopyNotesToIncident_test.py
+++ b/Packs/CommonScripts/Scripts/CopyNotesToIncident/CopyNotesToIncident_test.py
@@ -1,7 +1,8 @@
-from CopyNotesToIncident import copy_notes_to_target_incident
-import demistomock as demisto # noqa # pylint: disable=unused-wildcard-import
-from typing import Any
import json
+from typing import Any
+
+import demistomock as demisto # noqa # pylint: disable=unused-wildcard-import
+from CopyNotesToIncident import copy_notes_to_target_incident
MOCK_TARGET_INCIDENT_ID = '99'
MOCK_TAG = 'Tag1'
diff --git a/Packs/CommonScripts/Scripts/CreateHash/CreateHash.py b/Packs/CommonScripts/Scripts/CreateHash/CreateHash.py
index 0874fed08ee3..3945abe76dd7 100644
--- a/Packs/CommonScripts/Scripts/CreateHash/CreateHash.py
+++ b/Packs/CommonScripts/Scripts/CreateHash/CreateHash.py
@@ -1,9 +1,9 @@
-import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
-
import hashlib
from hashlib import blake2b
+import demistomock as demisto # noqa: F401
+from CommonServerPython import * # noqa: F401
+
def create_hash(text, hashtype):
"""Create a hash from a given input and return it as a context outputs
diff --git a/Packs/CommonScripts/Scripts/CreateIndicatorsFromSTIX/CreateIndicatorsFromSTIX.py b/Packs/CommonScripts/Scripts/CreateIndicatorsFromSTIX/CreateIndicatorsFromSTIX.py
index 2e8d99ae9e81..5a7ffae99009 100644
--- a/Packs/CommonScripts/Scripts/CreateIndicatorsFromSTIX/CreateIndicatorsFromSTIX.py
+++ b/Packs/CommonScripts/Scripts/CreateIndicatorsFromSTIX/CreateIndicatorsFromSTIX.py
@@ -1,6 +1,7 @@
+import json
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-import json
def parse_indicators_using_stix_parser(entry_id):
diff --git a/Packs/CommonScripts/Scripts/CreateNewIndicatorsOnly/CreateNewIndicatorsOnly.py b/Packs/CommonScripts/Scripts/CreateNewIndicatorsOnly/CreateNewIndicatorsOnly.py
index c937c0b1ba91..ee242f550c7a 100644
--- a/Packs/CommonScripts/Scripts/CreateNewIndicatorsOnly/CreateNewIndicatorsOnly.py
+++ b/Packs/CommonScripts/Scripts/CreateNewIndicatorsOnly/CreateNewIndicatorsOnly.py
@@ -1,8 +1,8 @@
-import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
-from typing import Any
import time
+from typing import Any
+import demistomock as demisto # noqa: F401
+from CommonServerPython import * # noqa: F401
STATUS_NEW = 'new'
STATUS_EXISTING = 'existing'
@@ -54,7 +54,7 @@ def normalize_indicator_value(indicator_value: Any) -> str:
elif isinstance(indicator_value, str) and indicator_value:
return indicator_value
else:
- raise DemistoException(f'Invalid indicator value: {str(indicator_value)}')
+ raise DemistoException(f'Invalid indicator value: {indicator_value!s}')
def add_new_indicator(indicator_value: Any,
@@ -139,7 +139,7 @@ def main():
))
except Exception as e:
return_error(
- f'Failed to execute CreateNewIndicatorsOnly.\nError:\n{str(e)}')
+ f'Failed to execute CreateNewIndicatorsOnly.\nError:\n{e!s}')
if __name__ in ('__main__', '__builtin__', 'builtins'):
diff --git a/Packs/CommonScripts/Scripts/CreateNewIndicatorsOnly/CreateNewIndicatorsOnly_test.py b/Packs/CommonScripts/Scripts/CreateNewIndicatorsOnly/CreateNewIndicatorsOnly_test.py
index 5658fdcdd02a..98466c781ecb 100644
--- a/Packs/CommonScripts/Scripts/CreateNewIndicatorsOnly/CreateNewIndicatorsOnly_test.py
+++ b/Packs/CommonScripts/Scripts/CreateNewIndicatorsOnly/CreateNewIndicatorsOnly_test.py
@@ -1,8 +1,9 @@
-import demistomock as demisto
-from CommonServerPython import * # noqa: F401
-import CreateNewIndicatorsOnly
from typing import Any
+
+import CreateNewIndicatorsOnly
+import demistomock as demisto
import pytest
+from CommonServerPython import * # noqa: F401
def equals_object(obj1, obj2) -> bool:
diff --git a/Packs/CommonScripts/Scripts/DBotAverageScore/DBotAverageScore.py b/Packs/CommonScripts/Scripts/DBotAverageScore/DBotAverageScore.py
index c90e6ad45753..28312196cf51 100644
--- a/Packs/CommonScripts/Scripts/DBotAverageScore/DBotAverageScore.py
+++ b/Packs/CommonScripts/Scripts/DBotAverageScore/DBotAverageScore.py
@@ -1,8 +1,8 @@
+from collections import defaultdict
+
import demistomock as demisto
from CommonServerPython import *
-from collections import defaultdict
-
def calculate_all_average_scores(context_data: list[dict[str, Any]]) -> CommandResults:
"""
diff --git a/Packs/CommonScripts/Scripts/DBotAverageScore/DBotAverageScore_test.py b/Packs/CommonScripts/Scripts/DBotAverageScore/DBotAverageScore_test.py
index e6cb5cde0e68..cba506a61b47 100644
--- a/Packs/CommonScripts/Scripts/DBotAverageScore/DBotAverageScore_test.py
+++ b/Packs/CommonScripts/Scripts/DBotAverageScore/DBotAverageScore_test.py
@@ -1,9 +1,7 @@
-from CommonServerPython import *
-
from pathlib import Path
import pytest
-
+from CommonServerPython import *
from DBotAverageScore import *
diff --git a/Packs/CommonScripts/Scripts/DBotUpdateLogoURLPhishing/DBotUpdateLogoURLPhishing.py b/Packs/CommonScripts/Scripts/DBotUpdateLogoURLPhishing/DBotUpdateLogoURLPhishing.py
index 6a63dcda8571..6edd1f9c89ec 100644
--- a/Packs/CommonScripts/Scripts/DBotUpdateLogoURLPhishing/DBotUpdateLogoURLPhishing.py
+++ b/Packs/CommonScripts/Scripts/DBotUpdateLogoURLPhishing/DBotUpdateLogoURLPhishing.py
@@ -1,10 +1,12 @@
+import io
+import traceback
+
import demistomock as demisto
-from CommonServerPython import *
-from CommonServerUserPython import *
import dill
+from CommonServerPython import *
from PIL import Image
-import io
-import traceback
+
+from CommonServerUserPython import *
MAJOR_VERSION = 1
MINOR_DEFAULT_VERSION = 0
@@ -286,7 +288,7 @@ def main():
return msg_list
except Exception as ex:
demisto.error(traceback.format_exc()) # print the traceback
- return_error(f'Failed to execute URL Phishing script. Error: {str(ex)}')
+ return_error(f'Failed to execute URL Phishing script. Error: {ex!s}')
if __name__ in ['__main__', '__builtin__', 'builtins']:
diff --git a/Packs/CommonScripts/Scripts/DecodeMimeHeader/DecodeMimeHeader.py b/Packs/CommonScripts/Scripts/DecodeMimeHeader/DecodeMimeHeader.py
index d9906e607cdc..329bc953a9b4 100644
--- a/Packs/CommonScripts/Scripts/DecodeMimeHeader/DecodeMimeHeader.py
+++ b/Packs/CommonScripts/Scripts/DecodeMimeHeader/DecodeMimeHeader.py
@@ -1,6 +1,7 @@
+from email.header import decode_header
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-from email.header import decode_header
def decode(s):
diff --git a/Packs/CommonScripts/Scripts/Dig/Dig.py b/Packs/CommonScripts/Scripts/Dig/Dig.py
index 71602757021a..1a0299536d53 100644
--- a/Packs/CommonScripts/Scripts/Dig/Dig.py
+++ b/Packs/CommonScripts/Scripts/Dig/Dig.py
@@ -1,10 +1,10 @@
-import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
import re
import subprocess
import traceback
from typing import Any
+import demistomock as demisto # noqa: F401
+from CommonServerPython import * # noqa: F401
''' STANDALONE FUNCTION '''
@@ -165,7 +165,7 @@ def main(): # pragma: no cover
return_results(dig_command(demisto.args()))
except Exception as ex:
demisto.error(traceback.format_exc()) # print the traceback
- return_error(f'Failed to execute Dig. Error: {str(ex)}')
+ return_error(f'Failed to execute Dig. Error: {ex!s}')
''' ENTRY POINT '''
diff --git a/Packs/CommonScripts/Scripts/Dig/Dig_test.py b/Packs/CommonScripts/Scripts/Dig/Dig_test.py
index 7584491281b0..4baf45ddc82b 100644
--- a/Packs/CommonScripts/Scripts/Dig/Dig_test.py
+++ b/Packs/CommonScripts/Scripts/Dig/Dig_test.py
@@ -28,8 +28,9 @@ def test_dig_result(mocker):
Then:
- validate the output is as expected
"""
- import Dig
import subprocess
+
+ import Dig
from Dig import dig_result
mocker.patch.object(Dig, 'regex_result', return_value=(['0.0.0.0'], '1.1.1.1'))
mocker.patch.object(subprocess, 'check_output', return_value="OK")
@@ -46,8 +47,9 @@ def test_reverse_dig_result(mocker):
Then:
- validate the output is as expected
"""
- import Dig
import subprocess
+
+ import Dig
from Dig import reverse_dig_result
mocker.patch.object(Dig, 'regex_result', return_value=(['0.0.0.0'], '1.1.1.1'))
mocker.patch.object(subprocess, 'check_output', return_value="OK")
diff --git a/Packs/CommonScripts/Scripts/DisableUserWrapper/DisableUserWrapper.py b/Packs/CommonScripts/Scripts/DisableUserWrapper/DisableUserWrapper.py
index 3909624279c4..7062d494777c 100644
--- a/Packs/CommonScripts/Scripts/DisableUserWrapper/DisableUserWrapper.py
+++ b/Packs/CommonScripts/Scripts/DisableUserWrapper/DisableUserWrapper.py
@@ -1,8 +1,8 @@
+import traceback
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-import traceback
-
def create_commands(username: str) -> List[CommandRunner.Command]:
"""Create commands to disable user.
@@ -63,7 +63,7 @@ def main(): # pragma: no cover
try:
return_results(disable_user(demisto.args()))
except Exception as e:
- error_msg = f'Failed to execute DisableUserWrapper. Error: {str(e)}\n {traceback.format_exc()}'
+ error_msg = f'Failed to execute DisableUserWrapper. Error: {e!s}\n {traceback.format_exc()}'
if 'The commands that run are not supported in this Instance' in str(e):
error_msg = 'No disable-user supported integrations were found in this instance.'
diff --git a/Packs/CommonScripts/Scripts/DisableUserWrapper/DisableUserWrapper_test.py b/Packs/CommonScripts/Scripts/DisableUserWrapper/DisableUserWrapper_test.py
index 2081a0577849..0c104aa01d7a 100644
--- a/Packs/CommonScripts/Scripts/DisableUserWrapper/DisableUserWrapper_test.py
+++ b/Packs/CommonScripts/Scripts/DisableUserWrapper/DisableUserWrapper_test.py
@@ -1,6 +1,6 @@
+import pytest
from CommonServerPython import CommandRunner
from DisableUserWrapper import disable_user
-import pytest
def commands_are_equal(command1: CommandRunner.Command, command2: CommandRunner.Command) -> bool:
diff --git a/Packs/CommonScripts/Scripts/DisplayHTML/DisplayHTML.py b/Packs/CommonScripts/Scripts/DisplayHTML/DisplayHTML.py
index 6f6668c176b7..2c2130f5b93f 100644
--- a/Packs/CommonScripts/Scripts/DisplayHTML/DisplayHTML.py
+++ b/Packs/CommonScripts/Scripts/DisplayHTML/DisplayHTML.py
@@ -9,7 +9,7 @@ def main():
note = True if note and note.lower() == "true" else False
if header:
- html = "{0}
{1}".format(header, html)
+ html = f"{header}
{html}"
demisto.results({
'ContentsFormat': formats['html'],
diff --git a/Packs/CommonScripts/Scripts/DisplayHTMLWithImages/DisplayHTMLWithImages.py b/Packs/CommonScripts/Scripts/DisplayHTMLWithImages/DisplayHTMLWithImages.py
index 139d6b46a446..ca44c50e2e9c 100644
--- a/Packs/CommonScripts/Scripts/DisplayHTMLWithImages/DisplayHTMLWithImages.py
+++ b/Packs/CommonScripts/Scripts/DisplayHTMLWithImages/DisplayHTMLWithImages.py
@@ -1,7 +1,7 @@
-import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
import re
+import demistomock as demisto # noqa: F401
+from CommonServerPython import * # noqa: F401
IMG_FORMATS = ['jpeg', 'gif', 'bmp', 'png', 'jfif', 'tiff', 'eps', 'indd', 'jpg']
diff --git a/Packs/CommonScripts/Scripts/DockerHardeningCheck/DockerHardeningCheck.py b/Packs/CommonScripts/Scripts/DockerHardeningCheck/DockerHardeningCheck.py
index 83cd1f3ac6a4..5e74d2b0ef5d 100644
--- a/Packs/CommonScripts/Scripts/DockerHardeningCheck/DockerHardeningCheck.py
+++ b/Packs/CommonScripts/Scripts/DockerHardeningCheck/DockerHardeningCheck.py
@@ -1,16 +1,14 @@
-import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
-from pathlib import Path
-
-from multiprocessing import Process
-import resource
import re
-import time
+import resource
import subprocess
+import time
+from multiprocessing import Process
+from pathlib import Path
+import demistomock as demisto # noqa: F401
import requests
import urllib3
-
+from CommonServerPython import * # noqa: F401
urllib3.disable_warnings()
@@ -27,7 +25,7 @@ def big_string(size):
def mem_size_to_bytes(mem: str) -> int:
res = re.match(r'(\d+)\s*([gm])?b?', mem, re.IGNORECASE)
if not res:
- raise ValueError("Failed parsing memory string: {}".format(mem))
+ raise ValueError(f"Failed parsing memory string: {mem}")
b = int(res.group(1))
if res.group(2):
b = b * 1024 * 1024 # convert to mega byte
@@ -48,14 +46,14 @@ def check_memory(target_mem: str, check_type: str) -> str: # pragma: no cover
"""
size = mem_size_to_bytes(target_mem)
if check_type == "allocate":
- LOG("starting process to check memory of size: {}".format(size))
+ LOG(f"starting process to check memory of size: {size}")
p = Process(target=big_string, args=(size, ))
p.start()
p.join()
- LOG("memory intensive process status code: {}".format(p.exitcode))
+ LOG(f"memory intensive process status code: {p.exitcode}")
if p.exitcode == 0:
- return ("Succeeded allocating memory of size: {}. "
- "It seems that you haven't limited the available memory to the docker container.".format(target_mem))
+ return (f"Succeeded allocating memory of size: {target_mem}. "
+ "It seems that you haven't limited the available memory to the docker container.")
else:
cgroup_file_v1 = "/sys/fs/cgroup/memory/memory.limit_in_bytes"
cgroup_file_v2 = "/sys/fs/cgroup/memory.max"
@@ -68,7 +66,7 @@ def check_memory(target_mem: str, check_type: str) -> str: # pragma: no cover
' cgroup files found, verify cgroups is enabled.')
try:
- with open(cgroup_file, "r") as f:
+ with open(cgroup_file) as f:
mem_bytes = int(f.read().strip())
if mem_bytes > size:
return (f'According to memory cgroup configuration at: {cgroup_file}'
@@ -81,7 +79,7 @@ def check_memory(target_mem: str, check_type: str) -> str: # pragma: no cover
def check_pids(pid_num: int) -> str:
- LOG("Starting pid check for: {}".format(pid_num))
+ LOG(f"Starting pid check for: {pid_num}")
processes = [Process(target=time.sleep, args=(30, )) for i in range(pid_num)]
try:
for p in processes:
@@ -92,12 +90,12 @@ def check_pids(pid_num: int) -> str:
if p.is_alive():
alive += 1
if alive >= pid_num:
- return ("Succeeded creating processs of size: {}. "
- "It seems that you haven't limited the available pids to the docker container.".format(pid_num))
+ return (f"Succeeded creating processs of size: {pid_num}. "
+ "It seems that you haven't limited the available pids to the docker container.")
else:
LOG(f'Number of processes that are alive: {alive} is smaller than {pid_num}. All good.')
except Exception as ex:
- LOG("Pool startup failed (as expected): {}".format(ex))
+ LOG(f"Pool startup failed (as expected): {ex}")
finally:
for p in processes:
if p.is_alive():
@@ -109,17 +107,17 @@ def check_pids(pid_num: int) -> str:
def check_fd_limits(soft, hard) -> str:
s, h = resource.getrlimit(resource.RLIMIT_NOFILE)
if s > soft:
- return "FD soft limit: {} is above desired limt: {}.".format(s, soft)
+ return f"FD soft limit: {s} is above desired limt: {soft}."
if h > hard:
- return "FD hard limit: {} is above desired limit: {}.".format(h, hard)
+ return f"FD hard limit: {h} is above desired limit: {hard}."
return ""
def check_non_root():
uid = os.getuid()
if uid == 0:
- return ("Running as root with uid: {}."
- " It seems that you haven't set the docker container to run with a non-root internal user.".format(uid))
+ return (f"Running as root with uid: {uid}."
+ " It seems that you haven't set the docker container to run with a non-root internal user.")
return ""
@@ -141,7 +139,7 @@ def check_cpus(num_cpus: int) -> str:
for p in processes:
p.join()
runtime = time.time_ns() - start
- LOG("cpus check runtime for {} processes time: {}".format(num_cpus, runtime))
+ LOG(f"cpus check runtime for {num_cpus} processes time: {runtime}")
processes = [Process(target=intensive_calc, args=(iterval, )) for i in range(num_cpus * 2)]
start = time.time_ns()
for p in processes:
@@ -150,12 +148,12 @@ def check_cpus(num_cpus: int) -> str:
p.join()
runtime2 = time.time_ns() - start
# runtime 2 should be 2 times slower. But we give it a safty as the machine itself maybe loaded
- LOG("cpus check runtime for {} processes time: {}".format(num_cpus * 2, runtime2))
+ LOG(f"cpus check runtime for {num_cpus * 2} processes time: {runtime2}")
if runtime2 < runtime * 1.5:
return ("CPU processing power increased significantly when increasing processes "
- "from: {} (time: {}) to: {} (time: {}). "
+ f"from: {num_cpus} (time: {runtime}) to: {num_cpus * 2} (time: {runtime2}). "
"Note: this test may fail even if the proper configuration has been applied and"
- " the machine itself is loaded.".format(num_cpus, runtime, num_cpus * 2, runtime2))
+ " the machine itself is loaded.")
return ""
diff --git a/Packs/CommonScripts/Scripts/DockerHardeningCheck/DockerHardeningCheck_test.py b/Packs/CommonScripts/Scripts/DockerHardeningCheck/DockerHardeningCheck_test.py
index 96ce78043c18..8178ab903156 100644
--- a/Packs/CommonScripts/Scripts/DockerHardeningCheck/DockerHardeningCheck_test.py
+++ b/Packs/CommonScripts/Scripts/DockerHardeningCheck/DockerHardeningCheck_test.py
@@ -1,11 +1,17 @@
-from DockerHardeningCheck import (mem_size_to_bytes, check_pids, check_fd_limits,
- get_default_gateway, check_network, CLOUD_METADATA_URL)
-import os
import ipaddress
+import os
+
import requests_mock
+from DockerHardeningCheck import (
+ CLOUD_METADATA_URL,
+ check_fd_limits,
+ check_network,
+ check_pids,
+ get_default_gateway,
+ mem_size_to_bytes,
+)
from pytest_mock import MockerFixture
-
# NOTE: Should be fixed in future versions (related to CIAC-11476)
# def test_check_memory():
# if os.getenv("GITHUB_ACTIONS"):
diff --git a/Packs/CommonScripts/Scripts/DomainReputation/DomainReputation_test.py b/Packs/CommonScripts/Scripts/DomainReputation/DomainReputation_test.py
index c833b166f209..23a4c2ae6f74 100644
--- a/Packs/CommonScripts/Scripts/DomainReputation/DomainReputation_test.py
+++ b/Packs/CommonScripts/Scripts/DomainReputation/DomainReputation_test.py
@@ -1,6 +1,6 @@
import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
import pytest
+from CommonServerPython import * # noqa: F401
@pytest.mark.parametrize('contents', ({'Error': 'error'}, None))
diff --git a/Packs/CommonScripts/Scripts/DownloadAndArchivePythonLibrary/DownloadAndArchivePythonLibrary.py b/Packs/CommonScripts/Scripts/DownloadAndArchivePythonLibrary/DownloadAndArchivePythonLibrary.py
index bfecd7b56b8d..7a0bb6b6d2fd 100644
--- a/Packs/CommonScripts/Scripts/DownloadAndArchivePythonLibrary/DownloadAndArchivePythonLibrary.py
+++ b/Packs/CommonScripts/Scripts/DownloadAndArchivePythonLibrary/DownloadAndArchivePythonLibrary.py
@@ -1,11 +1,11 @@
-import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
-
-from pathlib import Path
import shlex
import subprocess
-from tempfile import mkdtemp
import zipfile
+from pathlib import Path
+from tempfile import mkdtemp
+
+import demistomock as demisto # noqa: F401
+from CommonServerPython import * # noqa: F401
def installLibrary(dir_path: Path, library_name: str) -> str:
@@ -47,7 +47,7 @@ def main():
return_results(result)
except Exception as e:
- return_error(f"An error occurred: {str(e)}")
+ return_error(f"An error occurred: {e!s}")
if __name__ in ('__builtin__', 'builtins'):
diff --git a/Packs/CommonScripts/Scripts/DownloadAndArchivePythonLibrary/DownloadAndArchivePythonLibrary_test.py b/Packs/CommonScripts/Scripts/DownloadAndArchivePythonLibrary/DownloadAndArchivePythonLibrary_test.py
index d27791b3f840..3884b92254de 100644
--- a/Packs/CommonScripts/Scripts/DownloadAndArchivePythonLibrary/DownloadAndArchivePythonLibrary_test.py
+++ b/Packs/CommonScripts/Scripts/DownloadAndArchivePythonLibrary/DownloadAndArchivePythonLibrary_test.py
@@ -1,8 +1,8 @@
+import subprocess
import unittest
-from unittest.mock import patch, MagicMock, mock_open
-from pathlib import Path
import zipfile
-import subprocess
+from pathlib import Path
+from unittest.mock import MagicMock, mock_open, patch
# Import the functions from the script
from DownloadAndArchivePythonLibrary import installLibrary, main
diff --git a/Packs/CommonScripts/Scripts/DumpJSON/DumpJSON.py b/Packs/CommonScripts/Scripts/DumpJSON/DumpJSON.py
index 64190e962a36..35c47dafeebb 100644
--- a/Packs/CommonScripts/Scripts/DumpJSON/DumpJSON.py
+++ b/Packs/CommonScripts/Scripts/DumpJSON/DumpJSON.py
@@ -1,6 +1,7 @@
+import json
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-import json
def main():
diff --git a/Packs/CommonScripts/Scripts/DumpJSON/DumpJSON_test.py b/Packs/CommonScripts/Scripts/DumpJSON/DumpJSON_test.py
index 81f219db8875..977d011140fd 100644
--- a/Packs/CommonScripts/Scripts/DumpJSON/DumpJSON_test.py
+++ b/Packs/CommonScripts/Scripts/DumpJSON/DumpJSON_test.py
@@ -1,7 +1,8 @@
-from DumpJSON import main
-import demistomock as demisto
import json
+import demistomock as demisto
+from DumpJSON import main
+
def test_dump_json(mocker):
"""
diff --git a/Packs/CommonScripts/Scripts/EditServerConfig/EditServerConfig.py b/Packs/CommonScripts/Scripts/EditServerConfig/EditServerConfig.py
index f0c2f0839272..c01b12eab9b2 100644
--- a/Packs/CommonScripts/Scripts/EditServerConfig/EditServerConfig.py
+++ b/Packs/CommonScripts/Scripts/EditServerConfig/EditServerConfig.py
@@ -1,7 +1,7 @@
-from CommonServerPython import *
-
-from typing import Any
import traceback
+from typing import Any
+
+from CommonServerPython import *
SERVER_SYSTEM_CONFIG_PATH = '/system/config'
''' STANDALONE FUNCTION '''
@@ -59,7 +59,7 @@ def main():
return_results(edit_server_config(demisto.args()))
except Exception as ex:
demisto.error(traceback.format_exc())
- return_error(f'Failed to execute EditServerConfig. Error: {str(ex)}')
+ return_error(f'Failed to execute EditServerConfig. Error: {ex!s}')
''' ENTRY POINT '''
diff --git a/Packs/CommonScripts/Scripts/EncodeToAscii/EncodeToAscii.py b/Packs/CommonScripts/Scripts/EncodeToAscii/EncodeToAscii.py
index 391f0c36e523..d17b33b6fe2f 100644
--- a/Packs/CommonScripts/Scripts/EncodeToAscii/EncodeToAscii.py
+++ b/Packs/CommonScripts/Scripts/EncodeToAscii/EncodeToAscii.py
@@ -12,7 +12,7 @@ def main():
try:
encoded_data = data.encode('ascii', 'ignore').decode("utf-8")
except Exception as e:
- return_error(f'There was an error encoding the data.\nError:\n{str(e)}')
+ return_error(f'There was an error encoding the data.\nError:\n{e!s}')
# Output the data and add results to war room
return_results(CommandResults(
diff --git a/Packs/CommonScripts/Scripts/EnrichExcludeButton/EnrichExcludeButton_test.py b/Packs/CommonScripts/Scripts/EnrichExcludeButton/EnrichExcludeButton_test.py
index 91a03a71e20f..84f312c9aa9b 100644
--- a/Packs/CommonScripts/Scripts/EnrichExcludeButton/EnrichExcludeButton_test.py
+++ b/Packs/CommonScripts/Scripts/EnrichExcludeButton/EnrichExcludeButton_test.py
@@ -1,7 +1,7 @@
-from EnrichExcludeButton import main
-
from unittest.mock import patch
+from EnrichExcludeButton import main
+
@patch('EnrichExcludeButton.return_error') # Mock the return_error function in the script module
def test_main(mock_return_error):
diff --git a/Packs/CommonScripts/Scripts/ExifRead/ExifRead_test.py b/Packs/CommonScripts/Scripts/ExifRead/ExifRead_test.py
index f9c9ba0c0968..484ef15f0329 100644
--- a/Packs/CommonScripts/Scripts/ExifRead/ExifRead_test.py
+++ b/Packs/CommonScripts/Scripts/ExifRead/ExifRead_test.py
@@ -1,4 +1,5 @@
import json
+
import demistomock as demisto
diff --git a/Packs/CommonScripts/Scripts/ExportAuditLogsToFile/ExportAuditLogsToFile.py b/Packs/CommonScripts/Scripts/ExportAuditLogsToFile/ExportAuditLogsToFile.py
index 082150889d3d..914bc8834ead 100644
--- a/Packs/CommonScripts/Scripts/ExportAuditLogsToFile/ExportAuditLogsToFile.py
+++ b/Packs/CommonScripts/Scripts/ExportAuditLogsToFile/ExportAuditLogsToFile.py
@@ -1,10 +1,11 @@
-import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
import csv
import io
import json
from datetime import date, timedelta
+import demistomock as demisto # noqa: F401
+from CommonServerPython import * # noqa: F401
+
def get_audit_logs(res: Dict):
diff --git a/Packs/CommonScripts/Scripts/ExportAuditLogsToFile/ExportAuditLogsToFile_test.py b/Packs/CommonScripts/Scripts/ExportAuditLogsToFile/ExportAuditLogsToFile_test.py
index 49b713c6c921..8ec18ca4ae8a 100644
--- a/Packs/CommonScripts/Scripts/ExportAuditLogsToFile/ExportAuditLogsToFile_test.py
+++ b/Packs/CommonScripts/Scripts/ExportAuditLogsToFile/ExportAuditLogsToFile_test.py
@@ -1,8 +1,8 @@
import demistomock as demisto
-import pytest
import ExportAuditLogsToFile
-from freezegun import freeze_time
+import pytest
from CommonServerPython import *
+from freezegun import freeze_time
def execute_command_side_effect(command: str, args: Dict):
diff --git a/Packs/CommonScripts/Scripts/ExportIncidentsToCSV/ExportIncidentsToCSV_test.py b/Packs/CommonScripts/Scripts/ExportIncidentsToCSV/ExportIncidentsToCSV_test.py
index b7c7e03c0398..4fe9e547e32f 100644
--- a/Packs/CommonScripts/Scripts/ExportIncidentsToCSV/ExportIncidentsToCSV_test.py
+++ b/Packs/CommonScripts/Scripts/ExportIncidentsToCSV/ExportIncidentsToCSV_test.py
@@ -1,6 +1,5 @@
-import pytest
-
import demistomock as demisto
+import pytest
from ExportIncidentsToCSV import main
diff --git a/Packs/CommonScripts/Scripts/ExportToXLSX/ExportToXLSX.py b/Packs/CommonScripts/Scripts/ExportToXLSX/ExportToXLSX.py
index 1a8d9bb07f2e..799efc6e6b01 100644
--- a/Packs/CommonScripts/Scripts/ExportToXLSX/ExportToXLSX.py
+++ b/Packs/CommonScripts/Scripts/ExportToXLSX/ExportToXLSX.py
@@ -1,12 +1,11 @@
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-from typing import List, Optional, Union
-
from xlsxwriter import Workbook
from xlsxwriter.format import Format
-def write_data(sheet: str, data_item: Union[dict, list], data_headers: Optional[list], workbook: Workbook, bold: Format,
+def write_data(sheet: str, data_item: dict | list, data_headers: list | None, workbook: Workbook, bold: Format,
border: Format):
if not isinstance(data_item, list):
data_item = [data_item]
@@ -36,7 +35,7 @@ def write_data(sheet: str, data_item: Union[dict, list], data_headers: Optional[
col += 1
-def parse_data(data: Union[str, dict, list], sheets: list):
+def parse_data(data: str | dict | list, sheets: list):
if isinstance(data, str): # Indicates that the data is a comma-separated list of context keys.
data_list = json.loads("[" + data + "]")
if len(sheets) != len(data_list):
@@ -86,7 +85,7 @@ def main():
bold, border = prepare_bold_and_border(workbook, is_bold, is_border)
- multi_header_list: List[Optional[List]] = []
+ multi_header_list: list[list | None] = []
if headers_list: # Can be 1 item in case there is one sheet, or multiple items in case there are multiple
# sheets
for header_list in headers_list:
@@ -99,7 +98,7 @@ def main():
return_results(file_result_existing_file(file_name))
except Exception as ex:
- return_error(f'Failed to execute ExportToXLSX script. Error: {str(ex)}')
+ return_error(f'Failed to execute ExportToXLSX script. Error: {ex!s}')
if __name__ in ('__main__', '__builtin__', 'builtins'):
diff --git a/Packs/CommonScripts/Scripts/ExportToXLSX/ExportToXLSX_test.py b/Packs/CommonScripts/Scripts/ExportToXLSX/ExportToXLSX_test.py
index 197dbaa021e0..9ddeb6e5be6f 100644
--- a/Packs/CommonScripts/Scripts/ExportToXLSX/ExportToXLSX_test.py
+++ b/Packs/CommonScripts/Scripts/ExportToXLSX/ExportToXLSX_test.py
@@ -1,7 +1,7 @@
-from ExportToXLSX import parse_data
-import pytest
from unittest.mock import patch
+import pytest
+from ExportToXLSX import parse_data
DATA_INPUT_SINGLE_DICT = {"key1": "val1", "key2": "val2"}
DATA_INPUT_MULTIPLE_DICTS = '{\"key1\":\"val1\",\"key2\":\"val2\"},{\"key1\":\"val3\",\"key2\":\"val4\"}'
@@ -118,8 +118,8 @@ def test_write_data(self):
Then:
- Checks that write function was called 4 times.
"""
- from ExportToXLSX import write_data
import xlsxwriter
+ from ExportToXLSX import write_data
workbook = xlsxwriter.Workbook()
format_arg = xlsxwriter.format.Format()
write_data("", DATA_INPUT_SINGLE_DICT, None, workbook, format_arg, format_arg)
diff --git a/Packs/CommonScripts/Scripts/ExtractAttackPattern/ExtractAttackPattern.py b/Packs/CommonScripts/Scripts/ExtractAttackPattern/ExtractAttackPattern.py
index 38b341e59e5f..b2ff69130735 100644
--- a/Packs/CommonScripts/Scripts/ExtractAttackPattern/ExtractAttackPattern.py
+++ b/Packs/CommonScripts/Scripts/ExtractAttackPattern/ExtractAttackPattern.py
@@ -1,7 +1,6 @@
import demistomock as demisto
-from CommonServerPython import *
-
import urllib3
+from CommonServerPython import *
# Disable insecure warnings
urllib3.disable_warnings()
@@ -23,10 +22,10 @@ def is_valid_attack_pattern(items) -> list:
'verify you have proper integration (MITRE ATTACK v2) enabled to support it. '
'This Is needed in order to auto extract MITRE IDs and translate them to Attack Pattern IOCs')
else:
- demisto.info(f'MITRE Attack formatting script, {str(e)}')
+ demisto.info(f'MITRE Attack formatting script, {e!s}')
return []
except Exception as e:
- demisto.info(f'MITRE Attack formatting script, {str(e)}')
+ demisto.info(f'MITRE Attack formatting script, {e!s}')
return []
diff --git a/Packs/CommonScripts/Scripts/ExtractAttackPattern/ExtractAttackPattern_test.py b/Packs/CommonScripts/Scripts/ExtractAttackPattern/ExtractAttackPattern_test.py
index 04c0c7a7a283..12a952415681 100644
--- a/Packs/CommonScripts/Scripts/ExtractAttackPattern/ExtractAttackPattern_test.py
+++ b/Packs/CommonScripts/Scripts/ExtractAttackPattern/ExtractAttackPattern_test.py
@@ -1,7 +1,6 @@
-from ExtractAttackPattern import is_valid_attack_pattern
-
-from CommonServerPython import *
import ExtractAttackPattern as eap
+from CommonServerPython import *
+from ExtractAttackPattern import is_valid_attack_pattern
def test_extract_existing_mitre_ids(mocker):
diff --git a/Packs/CommonScripts/Scripts/ExtractDomainAndFQDNFromUrlAndEmail/ExtractDomainAndFQDNFromUrlAndEmail.py b/Packs/CommonScripts/Scripts/ExtractDomainAndFQDNFromUrlAndEmail/ExtractDomainAndFQDNFromUrlAndEmail.py
index 7251aa953655..a3c90aa8ec32 100644
--- a/Packs/CommonScripts/Scripts/ExtractDomainAndFQDNFromUrlAndEmail/ExtractDomainAndFQDNFromUrlAndEmail.py
+++ b/Packs/CommonScripts/Scripts/ExtractDomainAndFQDNFromUrlAndEmail/ExtractDomainAndFQDNFromUrlAndEmail.py
@@ -1,8 +1,9 @@
+import re
+from urllib.parse import parse_qs, unquote, urlparse
+
import demistomock as demisto
from CommonServerPython import * # noqa: F401
-from tld import get_tld, Result
-from urllib.parse import urlparse, parse_qs, unquote
-import re
+from tld import Result, get_tld
PROOFPOINT_PREFIXES = ['https://urldefense.proofpoint.com/',
"https://urldefense.com/"]
@@ -139,7 +140,7 @@ def main():
except Exception as e:
return_error(
- f'Failed to execute the automation. Error: \n{str(e)}'
+ f'Failed to execute the automation. Error: \n{e!s}'
)
diff --git a/Packs/CommonScripts/Scripts/ExtractDomainAndFQDNFromUrlAndEmail/ExtractDomainAndFQDNFromUrlAndEmail_test.py b/Packs/CommonScripts/Scripts/ExtractDomainAndFQDNFromUrlAndEmail/ExtractDomainAndFQDNFromUrlAndEmail_test.py
index 40f0c5147e22..2ce6c20893f7 100644
--- a/Packs/CommonScripts/Scripts/ExtractDomainAndFQDNFromUrlAndEmail/ExtractDomainAndFQDNFromUrlAndEmail_test.py
+++ b/Packs/CommonScripts/Scripts/ExtractDomainAndFQDNFromUrlAndEmail/ExtractDomainAndFQDNFromUrlAndEmail_test.py
@@ -1,7 +1,7 @@
-from pytest_mock import MockFixture
import demistomock as demisto
-from ExtractDomainAndFQDNFromUrlAndEmail import extract_fqdn, main
import pytest
+from ExtractDomainAndFQDNFromUrlAndEmail import extract_fqdn, main
+from pytest_mock import MockFixture
@pytest.mark.parametrize('input,fqdn', [ # noqa: E501 disable-secrets-detection
diff --git a/Packs/CommonScripts/Scripts/ExtractDomainFromUrlFormat/ExtractDomainFromUrlFormat.py b/Packs/CommonScripts/Scripts/ExtractDomainFromUrlFormat/ExtractDomainFromUrlFormat.py
index 580f02ff97e5..954dfdf5fb70 100644
--- a/Packs/CommonScripts/Scripts/ExtractDomainFromUrlFormat/ExtractDomainFromUrlFormat.py
+++ b/Packs/CommonScripts/Scripts/ExtractDomainFromUrlFormat/ExtractDomainFromUrlFormat.py
@@ -1,9 +1,10 @@
+import re
+from urllib.parse import parse_qs, unquote, urlparse
+
import demistomock as demisto
from CommonServerPython import *
from tld import get_fld
from validate_email import validate_email
-from urllib.parse import urlparse, parse_qs, unquote
-import re
# ============================================================================================================== #
# This script is highly similar to 'ExtractFQDNFromUrlAndEmail', they are not unified due to run time performance.
diff --git a/Packs/CommonScripts/Scripts/ExtractDomainFromUrlFormat/ExtractDomainFromUrlFormat_test.py b/Packs/CommonScripts/Scripts/ExtractDomainFromUrlFormat/ExtractDomainFromUrlFormat_test.py
index ccde4e4368aa..b62a7fdde0b7 100644
--- a/Packs/CommonScripts/Scripts/ExtractDomainFromUrlFormat/ExtractDomainFromUrlFormat_test.py
+++ b/Packs/CommonScripts/Scripts/ExtractDomainFromUrlFormat/ExtractDomainFromUrlFormat_test.py
@@ -1,6 +1,5 @@
-from ExtractDomainFromUrlFormat import extract_domain
-from ExtractDomainFromUrlFormat import unescape_url
import pytest
+from ExtractDomainFromUrlFormat import extract_domain, unescape_url
@pytest.mark.parametrize('input,domain', [
diff --git a/Packs/CommonScripts/Scripts/ExtractEmailFormatting/ExtractEmailFormatting.py b/Packs/CommonScripts/Scripts/ExtractEmailFormatting/ExtractEmailFormatting.py
index 05c58783e627..ecefeea06c00 100644
--- a/Packs/CommonScripts/Scripts/ExtractEmailFormatting/ExtractEmailFormatting.py
+++ b/Packs/CommonScripts/Scripts/ExtractEmailFormatting/ExtractEmailFormatting.py
@@ -1,8 +1,8 @@
+import re
+
import demistomock as demisto
from CommonServerPython import * # lgtm [py/polluting-import]
-import re
-
# Negative lookahead - Verify the pattern does not end with the listed file extensions. Separated by |
COMMON_FILE_EXT = ("zip", "jpg", "jpeg", "csv", "png", "gif", "bmp", "txt", "pdf", "ppt", "pptx", "xls", "xlsx", "doc",
"docx", "eml", "msg")
@@ -110,7 +110,7 @@ def main():
except Exception as e:
return_error(
- f'Failed to execute the automation. Error: \n{str(e)}'
+ f'Failed to execute the automation. Error: \n{e!s}'
)
diff --git a/Packs/CommonScripts/Scripts/ExtractEmailFormatting/ExtractEmailFormatting_test.py b/Packs/CommonScripts/Scripts/ExtractEmailFormatting/ExtractEmailFormatting_test.py
index a30e1524415a..3b228e313374 100644
--- a/Packs/CommonScripts/Scripts/ExtractEmailFormatting/ExtractEmailFormatting_test.py
+++ b/Packs/CommonScripts/Scripts/ExtractEmailFormatting/ExtractEmailFormatting_test.py
@@ -1,8 +1,7 @@
-from pytest_mock import MockFixture
-from ExtractEmailFormatting import main, check_tld, extract_email, refang_email, extract_email_from_url_query
-import pytest
import demistomock as demisto
-
+import pytest
+from ExtractEmailFormatting import check_tld, extract_email, extract_email_from_url_query, main, refang_email
+from pytest_mock import MockFixture
defang_data = [
('xsoar@test[.]com', 'xsoar@test.com'), # disable-secrets-detection
diff --git a/Packs/CommonScripts/Scripts/ExtractFQDNFromUrlAndEmail/ExtractFQDNFromUrlAndEmail.py b/Packs/CommonScripts/Scripts/ExtractFQDNFromUrlAndEmail/ExtractFQDNFromUrlAndEmail.py
index a85faf52f7ff..f4aaef9cbada 100644
--- a/Packs/CommonScripts/Scripts/ExtractFQDNFromUrlAndEmail/ExtractFQDNFromUrlAndEmail.py
+++ b/Packs/CommonScripts/Scripts/ExtractFQDNFromUrlAndEmail/ExtractFQDNFromUrlAndEmail.py
@@ -1,9 +1,10 @@
+import re
+from urllib.parse import parse_qs, unquote, urlparse
+
import demistomock as demisto
from CommonServerPython import *
-from tld import get_tld, Result
+from tld import Result, get_tld
from validate_email import validate_email
-from urllib.parse import urlparse, parse_qs, unquote
-import re
# ============================================================================================================== #
# This script is highly similar to 'ExtractDomainFromUrlFormat', they are not unified due to run time performance.
diff --git a/Packs/CommonScripts/Scripts/ExtractFQDNFromUrlAndEmail/ExtractFQDNFromUrlAndEmail_test.py b/Packs/CommonScripts/Scripts/ExtractFQDNFromUrlAndEmail/ExtractFQDNFromUrlAndEmail_test.py
index 1423fe83ba9d..d66dfb26e87d 100644
--- a/Packs/CommonScripts/Scripts/ExtractFQDNFromUrlAndEmail/ExtractFQDNFromUrlAndEmail_test.py
+++ b/Packs/CommonScripts/Scripts/ExtractFQDNFromUrlAndEmail/ExtractFQDNFromUrlAndEmail_test.py
@@ -1,5 +1,5 @@
-from ExtractFQDNFromUrlAndEmail import extract_fqdn
import pytest
+from ExtractFQDNFromUrlAndEmail import extract_fqdn
@pytest.mark.parametrize(
diff --git a/Packs/CommonScripts/Scripts/ExtractHTMLTables/ExtractHTMLTables.py b/Packs/CommonScripts/Scripts/ExtractHTMLTables/ExtractHTMLTables.py
index 17b09a56bb78..b4de0b38398d 100644
--- a/Packs/CommonScripts/Scripts/ExtractHTMLTables/ExtractHTMLTables.py
+++ b/Packs/CommonScripts/Scripts/ExtractHTMLTables/ExtractHTMLTables.py
@@ -40,7 +40,7 @@ def extract_html_table(html, indexes):
if len(tables) > 0:
return ({
'Type': entryTypes['note'],
- 'Contents': 'Found {} tables in HTML.'.format(len(tables)),
+ 'Contents': f'Found {len(tables)} tables in HTML.',
'ContentsFormat': formats['text'],
'EntryContext': {'HTMLTables': tables if len(tables) > 1 else tables[0]}
})
diff --git a/Packs/CommonScripts/Scripts/ExtractHyperlinksFromOfficeFiles/ExtractHyperlinksFromOfficeFiles.py b/Packs/CommonScripts/Scripts/ExtractHyperlinksFromOfficeFiles/ExtractHyperlinksFromOfficeFiles.py
index 5eff5a864f1a..45268191a43c 100644
--- a/Packs/CommonScripts/Scripts/ExtractHyperlinksFromOfficeFiles/ExtractHyperlinksFromOfficeFiles.py
+++ b/Packs/CommonScripts/Scripts/ExtractHyperlinksFromOfficeFiles/ExtractHyperlinksFromOfficeFiles.py
@@ -1,12 +1,13 @@
+import zipfile
+
import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
import openpyxl
+import pandas as pd
+from CommonServerPython import * # noqa: F401
from docx import Document
+from docx.opc.constants import RELATIONSHIP_TYPE as RT
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE
-import zipfile
-import pandas as pd
-from docx.opc.constants import RELATIONSHIP_TYPE as RT
def extract_hyperlinks_from_xlsx(file_path: str) -> Set:
@@ -100,7 +101,7 @@ def main(): # pragma: no cover
os.rename(f'./{file_path}', file_name)
return_results(extract_hyperlink_by_file_type(file_name=file_name, file_path=os.path.realpath(file_name)))
except Exception as ex:
- return_error(f'Failed to execute ExtractHyperlinksFromOfficeFiles. Error: {str(ex)}')
+ return_error(f'Failed to execute ExtractHyperlinksFromOfficeFiles. Error: {ex!s}')
if __name__ in ('__main__', '__builtin__', 'builtins'):
diff --git a/Packs/CommonScripts/Scripts/ExtractIndicatorsFromTextFile/ExtractIndicatorsFromTextFile.py b/Packs/CommonScripts/Scripts/ExtractIndicatorsFromTextFile/ExtractIndicatorsFromTextFile.py
index a2fbdee5b005..8eb365d05f04 100644
--- a/Packs/CommonScripts/Scripts/ExtractIndicatorsFromTextFile/ExtractIndicatorsFromTextFile.py
+++ b/Packs/CommonScripts/Scripts/ExtractIndicatorsFromTextFile/ExtractIndicatorsFromTextFile.py
@@ -1,7 +1,9 @@
+import json
+
import demistomock as demisto
from CommonServerPython import *
+
from CommonServerUserPython import *
-import json
def string_to_markdown(indicators: str) -> str:
@@ -63,7 +65,7 @@ def extract_indicators_from_file(args):
# Extract indicators (omitting context output, letting auto-extract work)
indicators_hr = demisto.executeCommand("extractIndicators", {
- 'text': data})[0][u'Contents']
+ 'text': data})[0]['Contents']
return {
'Type': entryTypes['note'],
'ContentsFormat': formats['text'],
diff --git a/Packs/CommonScripts/Scripts/ExtractIndicatorsFromTextFile/ExtractIndicatorsFromTextFile_test.py b/Packs/CommonScripts/Scripts/ExtractIndicatorsFromTextFile/ExtractIndicatorsFromTextFile_test.py
index 9d32f4c2f91a..092515cc0c53 100644
--- a/Packs/CommonScripts/Scripts/ExtractIndicatorsFromTextFile/ExtractIndicatorsFromTextFile_test.py
+++ b/Packs/CommonScripts/Scripts/ExtractIndicatorsFromTextFile/ExtractIndicatorsFromTextFile_test.py
@@ -1,5 +1,4 @@
import pytest
-
from ExtractIndicatorsFromTextFile import *
diff --git a/Packs/CommonScripts/Scripts/ExtractIndicatorsFromWordFile/ExtractIndicatorsFromWordFile.py b/Packs/CommonScripts/Scripts/ExtractIndicatorsFromWordFile/ExtractIndicatorsFromWordFile.py
index b3c3281c2965..7ee19e547536 100644
--- a/Packs/CommonScripts/Scripts/ExtractIndicatorsFromWordFile/ExtractIndicatorsFromWordFile.py
+++ b/Packs/CommonScripts/Scripts/ExtractIndicatorsFromWordFile/ExtractIndicatorsFromWordFile.py
@@ -1,11 +1,13 @@
+import subprocess
+
import demistomock as demisto
from CommonServerPython import *
-from CommonServerUserPython import *
-import subprocess
from docx import Document
from docx.opc.constants import RELATIONSHIP_TYPE as RT
from docx.opc.exceptions import PackageNotFoundError
+from CommonServerUserPython import *
+
class WordParser:
@@ -38,7 +40,7 @@ def convert_doc_to_docx(self):
output = subprocess.check_output(
['soffice', '--headless', '-env:UserInstallation=file:///tmp/.config/extractindicators', '--convert-to',
'docx', self.file_path], stderr=subprocess.STDOUT)
- demisto.debug(f"soffice output: [{str(output)}]")
+ demisto.debug(f"soffice output: [{output!s}]")
# Requires office-utils docker image
output_file_name = self.file_name[0:self.file_name.rfind('.')] + '.docx'
self.file_path = self.file_path + ".docx"
diff --git a/Packs/CommonScripts/Scripts/ExtractIndicatorsFromWordFile/ExtractIndicatorsFromWordFile_test.py b/Packs/CommonScripts/Scripts/ExtractIndicatorsFromWordFile/ExtractIndicatorsFromWordFile_test.py
index a8d96abaf6ea..b9b5f7263bed 100644
--- a/Packs/CommonScripts/Scripts/ExtractIndicatorsFromWordFile/ExtractIndicatorsFromWordFile_test.py
+++ b/Packs/CommonScripts/Scripts/ExtractIndicatorsFromWordFile/ExtractIndicatorsFromWordFile_test.py
@@ -1,10 +1,11 @@
-import pytest
import os
import shutil
-from ExtractIndicatorsFromWordFile import WordParser, main
-import demistomock as demisto
from unittest.mock import MagicMock
+import demistomock as demisto
+import pytest
+from ExtractIndicatorsFromWordFile import WordParser, main
+
expected_partial_all_data = 'Lorem ipsum dolor sit amet, an quas nostro posidonium mei, pro choro vocent pericula et'
diff --git a/Packs/CommonScripts/Scripts/FeedRelatedIndicatorsWidget/FeedRelatedIndicatorsWidget.py b/Packs/CommonScripts/Scripts/FeedRelatedIndicatorsWidget/FeedRelatedIndicatorsWidget.py
index db26722a5e31..57f462565943 100644
--- a/Packs/CommonScripts/Scripts/FeedRelatedIndicatorsWidget/FeedRelatedIndicatorsWidget.py
+++ b/Packs/CommonScripts/Scripts/FeedRelatedIndicatorsWidget/FeedRelatedIndicatorsWidget.py
@@ -69,7 +69,7 @@ def main(args):
try:
return_results(feed_related_indicator(args))
except Exception as e:
- return_error(f'Failed to execute FeedRelatedIndicatorsWidget. Error: {str(e)}')
+ return_error(f'Failed to execute FeedRelatedIndicatorsWidget. Error: {e!s}')
if __name__ in ('__main__', '__builtin__', 'builtins'):
diff --git a/Packs/CommonScripts/Scripts/FeedRelatedIndicatorsWidget/FeedRelatedIndicatorsWidget_test.py b/Packs/CommonScripts/Scripts/FeedRelatedIndicatorsWidget/FeedRelatedIndicatorsWidget_test.py
index ba165cfb5780..dab1d1a48df7 100644
--- a/Packs/CommonScripts/Scripts/FeedRelatedIndicatorsWidget/FeedRelatedIndicatorsWidget_test.py
+++ b/Packs/CommonScripts/Scripts/FeedRelatedIndicatorsWidget/FeedRelatedIndicatorsWidget_test.py
@@ -1,5 +1,5 @@
-import pytest
import demistomock as demisto
+import pytest
FILE_INDICATOR = {'CustomFields': {
'campaign': ['pickaxe_play2'],
diff --git a/Packs/CommonScripts/Scripts/FetchIndicatorsFromFile/FetchIndicatorsFromFile.py b/Packs/CommonScripts/Scripts/FetchIndicatorsFromFile/FetchIndicatorsFromFile.py
index f5736ab09db6..0f09d640db52 100644
--- a/Packs/CommonScripts/Scripts/FetchIndicatorsFromFile/FetchIndicatorsFromFile.py
+++ b/Packs/CommonScripts/Scripts/FetchIndicatorsFromFile/FetchIndicatorsFromFile.py
@@ -1,12 +1,13 @@
+import csv
+import re
+import traceback
+
import demistomock as demisto
+import tldextract
+import xlrd
from CommonServerPython import *
-from CommonServerUserPython import *
-import re
-import xlrd
-import csv
-import tldextract
-import traceback
+from CommonServerUserPython import *
def csv_file_to_indicator_list(file_path, col_num, starting_row, auto_detect, default_type, type_col, limit, offset):
@@ -265,7 +266,7 @@ def main():
try:
return_outputs(*fetch_indicators_from_file(demisto.args()))
except Exception as ex:
- return_error(f'Failed to execute Fetch Indicators From File. Error: {str(ex)}',
+ return_error(f'Failed to execute Fetch Indicators From File. Error: {ex!s}',
error=traceback.format_exc())
diff --git a/Packs/CommonScripts/Scripts/FetchIndicatorsFromFile/FetchIndicatorsFromFile_test.py b/Packs/CommonScripts/Scripts/FetchIndicatorsFromFile/FetchIndicatorsFromFile_test.py
index dae42b1f2a03..a9b71d2f2a41 100644
--- a/Packs/CommonScripts/Scripts/FetchIndicatorsFromFile/FetchIndicatorsFromFile_test.py
+++ b/Packs/CommonScripts/Scripts/FetchIndicatorsFromFile/FetchIndicatorsFromFile_test.py
@@ -162,8 +162,8 @@ def test_main(mocker):
Then:
- Return results to War-Room
"""
- from FetchIndicatorsFromFile import main
import demistomock as demisto
+ from FetchIndicatorsFromFile import main
mocker.patch.object(demisto, "args", return_value={})
mocker.patch('FetchIndicatorsFromFile.fetch_indicators_from_file', return_value=("", {}, []))
main()
diff --git a/Packs/CommonScripts/Scripts/FileCreateAndUploadV2/FileCreateAndUploadV2_test.py b/Packs/CommonScripts/Scripts/FileCreateAndUploadV2/FileCreateAndUploadV2_test.py
index 779929f76998..13e12dcae4ca 100644
--- a/Packs/CommonScripts/Scripts/FileCreateAndUploadV2/FileCreateAndUploadV2_test.py
+++ b/Packs/CommonScripts/Scripts/FileCreateAndUploadV2/FileCreateAndUploadV2_test.py
@@ -2,19 +2,18 @@
import sys
from pathlib import Path
+import demistomock as demisto
import pytest
+from CommonServerPython import DemistoException
from FileCreateAndUploadV2 import (
EntryType,
decode_data,
+ get_data_entry,
get_data_from_file,
main,
- get_data_entry,
)
from pytest_mock import MockerFixture
-import demistomock as demisto
-from CommonServerPython import DemistoException
-
def side_effect_sys_exit(code):
pass
diff --git a/Packs/CommonScripts/Scripts/FileToBase64List/FileToBase64List.py b/Packs/CommonScripts/Scripts/FileToBase64List/FileToBase64List.py
index 0c9d9e1884f2..f3333c8ca239 100644
--- a/Packs/CommonScripts/Scripts/FileToBase64List/FileToBase64List.py
+++ b/Packs/CommonScripts/Scripts/FileToBase64List/FileToBase64List.py
@@ -1,8 +1,10 @@
+import base64
+import zlib
+
import demistomock as demisto
from CommonServerPython import *
+
from CommonServerUserPython import *
-import base64
-import zlib
def get_file_data(file_path: str, is_zip: bool = False):
diff --git a/Packs/CommonScripts/Scripts/FileToBase64List/file_to_base64_list_test.py b/Packs/CommonScripts/Scripts/FileToBase64List/file_to_base64_list_test.py
index 3dbbabc932b2..45d5eb61a66a 100644
--- a/Packs/CommonScripts/Scripts/FileToBase64List/file_to_base64_list_test.py
+++ b/Packs/CommonScripts/Scripts/FileToBase64List/file_to_base64_list_test.py
@@ -1,10 +1,12 @@
+import base64
+import os
+import zlib
+
import demistomock as demisto
from CommonServerPython import *
+from FileToBase64List import get_file_data, main
+
from CommonServerUserPython import *
-from FileToBase64List import main, get_file_data
-import os
-import base64
-import zlib
TEST_FILE_PATH = os.path.join('test_data', 'file.txt')
diff --git a/Packs/CommonScripts/Scripts/FilterByList/FilterByList.py b/Packs/CommonScripts/Scripts/FilterByList/FilterByList.py
index c39338a3555c..b4744ee3c2a1 100644
--- a/Packs/CommonScripts/Scripts/FilterByList/FilterByList.py
+++ b/Packs/CommonScripts/Scripts/FilterByList/FilterByList.py
@@ -1,5 +1,6 @@
import demistomock as demisto
from CommonServerPython import *
+
from CommonServerUserPython import *
diff --git a/Packs/CommonScripts/Scripts/FilterByList/FilterByList_test.py b/Packs/CommonScripts/Scripts/FilterByList/FilterByList_test.py
index c06db2645e66..20cfabb65408 100644
--- a/Packs/CommonScripts/Scripts/FilterByList/FilterByList_test.py
+++ b/Packs/CommonScripts/Scripts/FilterByList/FilterByList_test.py
@@ -1,4 +1,3 @@
-from __future__ import print_function
import pytest
from FilterByList import filter_list
diff --git a/Packs/CommonScripts/Scripts/FormatURL/FormatURL.py b/Packs/CommonScripts/Scripts/FormatURL/FormatURL.py
index ead80c05be7d..1781ebba53fd 100644
--- a/Packs/CommonScripts/Scripts/FormatURL/FormatURL.py
+++ b/Packs/CommonScripts/Scripts/FormatURL/FormatURL.py
@@ -1,6 +1,5 @@
import demistomock as demisto
from CommonServerPython import *
-
from FormatURLApiModule import * # noqa: E402
@@ -20,7 +19,7 @@ def main():
except Exception as e:
return_error(
- f'Failed to execute the automation. Error: \n{str(e)}'
+ f'Failed to execute the automation. Error: \n{e!s}'
)
diff --git a/Packs/CommonScripts/Scripts/GenerateAsBuilt/GenerateAsBuilt.py b/Packs/CommonScripts/Scripts/GenerateAsBuilt/GenerateAsBuilt.py
index c5bf4e8831dc..f8af96f2e8e8 100644
--- a/Packs/CommonScripts/Scripts/GenerateAsBuilt/GenerateAsBuilt.py
+++ b/Packs/CommonScripts/Scripts/GenerateAsBuilt/GenerateAsBuilt.py
@@ -1,7 +1,8 @@
import demistomock as demisto
+import jinja2
from CommonServerPython import *
+
from CommonServerUserPython import *
-import jinja2
"""
GenerateAsBuilt
diff --git a/Packs/CommonScripts/Scripts/GenerateAsBuilt/GenerateAsBuilt_test.py b/Packs/CommonScripts/Scripts/GenerateAsBuilt/GenerateAsBuilt_test.py
index 6756bd266d90..8f6860072f73 100644
--- a/Packs/CommonScripts/Scripts/GenerateAsBuilt/GenerateAsBuilt_test.py
+++ b/Packs/CommonScripts/Scripts/GenerateAsBuilt/GenerateAsBuilt_test.py
@@ -1,6 +1,6 @@
-from GenerateAsBuilt import TableData, SortedTableData
-import pytest
import demistomock as demisto
+import pytest
+from GenerateAsBuilt import SortedTableData, TableData
def test_as_html():
@@ -108,7 +108,7 @@ def test_get_open_incidents(mocker):
- all open incidents are returned
"""
import GenerateAsBuilt
- from GenerateAsBuilt import get_open_incidents, SingleFieldData
+ from GenerateAsBuilt import SingleFieldData, get_open_incidents
mocker.patch.object(GenerateAsBuilt, 'post_api_request', return_value={'total': 1000})
expected = SingleFieldData(f"Open Incidents {7} days", 1000)
res = get_open_incidents()
@@ -126,7 +126,7 @@ def test_get_closed_incidents(mocker):
- all closed incidents are returned
"""
import GenerateAsBuilt
- from GenerateAsBuilt import get_closed_incidents, SingleFieldData
+ from GenerateAsBuilt import SingleFieldData, get_closed_incidents
mocker.patch.object(GenerateAsBuilt, 'post_api_request', return_value={'total': 1000})
expected = SingleFieldData(f"Closed Incidents {7} days", 1000)
res = get_closed_incidents()
@@ -144,7 +144,7 @@ def test_get_enabled_integrations(mocker):
- all enabled integrations are returned
"""
import GenerateAsBuilt
- from GenerateAsBuilt import get_enabled_integrations, SortedTableData
+ from GenerateAsBuilt import SortedTableData, get_enabled_integrations
mocker.patch.object(GenerateAsBuilt, 'post_api_request', return_value={
'instances': [{'enabled': True, 'name': 'test'}]})
expected = SortedTableData([{'enabled': True, 'name': 'test'}], "Enabled Instances", "name")
@@ -164,7 +164,7 @@ def test_get_installed_packs(mocker, get_api_request_returned_value):
- all installed packs are returned
"""
import GenerateAsBuilt
- from GenerateAsBuilt import get_installed_packs, SortedTableData
+ from GenerateAsBuilt import SortedTableData, get_installed_packs
mocker.patch.object(GenerateAsBuilt, 'get_api_request', return_value=get_api_request_returned_value)
result = get_installed_packs()
@@ -184,7 +184,7 @@ def test_get_custom_playbooks(mocker):
- all custom playbooks are returned
"""
import GenerateAsBuilt
- from GenerateAsBuilt import get_custom_playbooks, SortedTableData
+ from GenerateAsBuilt import SortedTableData, get_custom_playbooks
mocker.patch.object(GenerateAsBuilt, 'post_api_request', return_value={
'playbooks': [{'name': 'test'}]})
expected = SortedTableData([{'name': 'test', 'TotalTasks': 0}], "Custom Playbooks", "name")
@@ -203,7 +203,7 @@ def test_get_custom_reports(mocker):
- all custom reports are returned
"""
import GenerateAsBuilt
- from GenerateAsBuilt import get_custom_reports, TableData
+ from GenerateAsBuilt import TableData, get_custom_reports
mocker.patch.object(GenerateAsBuilt, 'get_api_request', return_value=[{'name': 'test'}])
expected = TableData([{'name': 'test'}], 'Custom Reports')
res = get_custom_reports()
@@ -221,7 +221,7 @@ def test_get_custom_dashboards(mocker):
- all custom dashboards are returned
"""
import GenerateAsBuilt
- from GenerateAsBuilt import get_custom_dashboards, TableData
+ from GenerateAsBuilt import TableData, get_custom_dashboards
mocker.patch.object(GenerateAsBuilt, 'get_api_request', return_value={'dashboard': {'name': 'test'}})
expected = TableData([{'name': 'test'}], 'Custom dashboards')
res = get_custom_dashboards()
@@ -239,7 +239,7 @@ def test_get_all_playbooks(mocker):
- all available playbooks are returned
"""
import GenerateAsBuilt
- from GenerateAsBuilt import get_all_playbooks, TableData
+ from GenerateAsBuilt import TableData, get_all_playbooks
mocker.patch.object(GenerateAsBuilt, 'post_api_request', return_value={'playbooks': [{'name': 'test'}]})
expected = TableData([{'name': 'test', 'TotalTasks': 0}], 'All Playbooks')
res = get_all_playbooks()
@@ -257,7 +257,7 @@ def test_get_playbook_stats(mocker):
- all available playbooks stats are returned
"""
import GenerateAsBuilt
- from GenerateAsBuilt import get_playbook_stats, TableData
+ from GenerateAsBuilt import TableData, get_playbook_stats
mocker.patch.object(GenerateAsBuilt, 'get_all_incidents', return_value=[
{'name': 'test', 'TotalTasks': 0, 'playbookId': '000001'}])
@@ -278,7 +278,7 @@ def test_get_playbook_dependencies(mocker):
- all available playbooks dependencies are returned
"""
import GenerateAsBuilt
- from GenerateAsBuilt import get_playbook_dependencies, TableData
+ from GenerateAsBuilt import TableData, get_playbook_dependencies
mocker.patch.object(GenerateAsBuilt, 'get_all_playbooks', return_value=TableData(
[{'name': 'test', 'TotalTasks': 0, 'id': '000001'}], 'All Playbooks'))
mocker.patch.object(GenerateAsBuilt, 'post_api_request', return_value={'existing': {
@@ -299,7 +299,7 @@ def test_get_custom_automations(mocker):
- all custom automations are returned
"""
import GenerateAsBuilt
- from GenerateAsBuilt import get_custom_automations, TableData
+ from GenerateAsBuilt import TableData, get_custom_automations
mocker.patch.object(GenerateAsBuilt, 'post_api_request', return_value={'scripts': [{'name': 'test'}]})
expected = TableData([{'name': 'test'}], 'Custom Automations')
res = get_custom_automations()
@@ -317,7 +317,7 @@ def test_get_system_config(mocker):
- all system configurations are returned
"""
import GenerateAsBuilt
- from GenerateAsBuilt import get_system_config, TableData
+ from GenerateAsBuilt import TableData, get_system_config
mocker.patch.object(GenerateAsBuilt, 'get_api_request', return_value={'config': [{'name': 'test'}]})
expected = TableData([{'name': 'test'}], 'System Configuration')
res = get_system_config()
diff --git a/Packs/CommonScripts/Scripts/GenerateAsBuiltConfiguration/GenerateAsBuiltConfiguration.py b/Packs/CommonScripts/Scripts/GenerateAsBuiltConfiguration/GenerateAsBuiltConfiguration.py
index 8af1f449a779..73b53e75caa0 100644
--- a/Packs/CommonScripts/Scripts/GenerateAsBuiltConfiguration/GenerateAsBuiltConfiguration.py
+++ b/Packs/CommonScripts/Scripts/GenerateAsBuiltConfiguration/GenerateAsBuiltConfiguration.py
@@ -1,5 +1,6 @@
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
+
# Defining global variables
layouts: list = []
integrations: list = []
diff --git a/Packs/CommonScripts/Scripts/GeneratePassword/GeneratePassword.py b/Packs/CommonScripts/Scripts/GeneratePassword/GeneratePassword.py
index f288d40fa229..d1f9aa5f5712 100644
--- a/Packs/CommonScripts/Scripts/GeneratePassword/GeneratePassword.py
+++ b/Packs/CommonScripts/Scripts/GeneratePassword/GeneratePassword.py
@@ -1,11 +1,12 @@
-import demistomock as demisto
-from CommonServerPython import *
-from CommonServerUserPython import *
-
import random
import secrets
import string
+import demistomock as demisto
+from CommonServerPython import *
+
+from CommonServerUserPython import *
+
DEFAULT_MIN = 0
DEFAULT_MAX = 10
diff --git a/Packs/CommonScripts/Scripts/GeneratePassword/GeneratePassword_test.py b/Packs/CommonScripts/Scripts/GeneratePassword/GeneratePassword_test.py
index f410697e8099..8dfaff7bf925 100644
--- a/Packs/CommonScripts/Scripts/GeneratePassword/GeneratePassword_test.py
+++ b/Packs/CommonScripts/Scripts/GeneratePassword/GeneratePassword_test.py
@@ -1,6 +1,6 @@
import pytest
-from GeneratePassword import generate_password, SYMBOLS
from CommonServerPython import DemistoException
+from GeneratePassword import SYMBOLS, generate_password
def does_password_meet_requirement(
diff --git a/Packs/CommonScripts/Scripts/GenerateRandomString/GenerateRandomString.py b/Packs/CommonScripts/Scripts/GenerateRandomString/GenerateRandomString.py
index 98659e30569c..26b448ed0140 100644
--- a/Packs/CommonScripts/Scripts/GenerateRandomString/GenerateRandomString.py
+++ b/Packs/CommonScripts/Scripts/GenerateRandomString/GenerateRandomString.py
@@ -1,15 +1,15 @@
-import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
import random
import string
+import demistomock as demisto # noqa: F401
+from CommonServerPython import * # noqa: F401
MAX_LENGTH = 10000
def set_length(length):
if length <= 0:
- return_error("Length must be greater than 0. Maximum value is {}.".format(MAX_LENGTH))
+ return_error(f"Length must be greater than 0. Maximum value is {MAX_LENGTH}.")
return min(length, MAX_LENGTH)
@@ -27,7 +27,7 @@ def set_characters(characters: str, digits: bool, lowercase: bool, punctuation:
def create_password(characters, length):
password = ""
- for x in range(0, length):
+ for x in range(length):
password += random.SystemRandom(random.seed(time.time())).choice(characters) # type: ignore
entry_context = {'RandomString': password}
diff --git a/Packs/CommonScripts/Scripts/GenerateRandomUUID/GenerateRandomUUID.py b/Packs/CommonScripts/Scripts/GenerateRandomUUID/GenerateRandomUUID.py
index 155da843f2e5..519f440f94ac 100644
--- a/Packs/CommonScripts/Scripts/GenerateRandomUUID/GenerateRandomUUID.py
+++ b/Packs/CommonScripts/Scripts/GenerateRandomUUID/GenerateRandomUUID.py
@@ -34,7 +34,7 @@ def main():
return_results(generate_random_uuid_command())
except Exception as ex:
demisto.error(traceback.format_exc()) # print the traceback
- return_error(f'Failed to execute GenerateRandomUUID. Error: {str(ex)}')
+ return_error(f'Failed to execute GenerateRandomUUID. Error: {ex!s}')
''' ENTRY POINT '''
diff --git a/Packs/CommonScripts/Scripts/GenerateRandomUUID/GenerateRandomUUID_test.py b/Packs/CommonScripts/Scripts/GenerateRandomUUID/GenerateRandomUUID_test.py
index c3dd97022667..c2066c3a4291 100644
--- a/Packs/CommonScripts/Scripts/GenerateRandomUUID/GenerateRandomUUID_test.py
+++ b/Packs/CommonScripts/Scripts/GenerateRandomUUID/GenerateRandomUUID_test.py
@@ -1,6 +1,7 @@
-from GenerateRandomUUID import generate_random_uuid_command
import uuid
+from GenerateRandomUUID import generate_random_uuid_command
+
MOCK_UUID = 'dae756a4-304f-42ac-9287-a4546624b3ad'
MOCK_OUTPUTS = {
"GeneratedUUID": MOCK_UUID
diff --git a/Packs/CommonScripts/Scripts/GenerateSummaryReportButton/GenerateSummaryReportButton.py b/Packs/CommonScripts/Scripts/GenerateSummaryReportButton/GenerateSummaryReportButton.py
index 30b27b0c1912..151870f082e8 100644
--- a/Packs/CommonScripts/Scripts/GenerateSummaryReportButton/GenerateSummaryReportButton.py
+++ b/Packs/CommonScripts/Scripts/GenerateSummaryReportButton/GenerateSummaryReportButton.py
@@ -1,7 +1,6 @@
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-
# get incident id
incident_id = demisto.incidents()[0].get('id')
diff --git a/Packs/CommonScripts/Scripts/GetByIncidentId/GetByIncidentId.py b/Packs/CommonScripts/Scripts/GetByIncidentId/GetByIncidentId.py
index 2122230f2fd5..fb4ce43e19ee 100644
--- a/Packs/CommonScripts/Scripts/GetByIncidentId/GetByIncidentId.py
+++ b/Packs/CommonScripts/Scripts/GetByIncidentId/GetByIncidentId.py
@@ -1,7 +1,9 @@
+from functools import reduce
+
import demistomock as demisto
from CommonServerPython import *
+
from CommonServerUserPython import *
-from functools import reduce
def get_by_incident_id(incident_id, get_key, set_key=""):
@@ -12,7 +14,7 @@ def get_by_incident_id(incident_id, get_key, set_key=""):
context = demisto.executeCommand("getContext", {"id": incident_id})[0]['Contents']['context']
res = reduce(lambda x, y: x[y], keys, context)
except KeyError:
- error_msg = "Cannot find {} in incident #{}".format(get_key, incident_id)
+ error_msg = f"Cannot find {get_key} in incident #{incident_id}"
return_error(message=error_msg,
error='GetByIncidentId: ' + error_msg,
outputs={set_key: error_msg})
@@ -20,8 +22,7 @@ def get_by_incident_id(incident_id, get_key, set_key=""):
entry_context = {set_key: res}
return_outputs(
- readable_output="Key '{}' successfully retrieved and set into current incident at '{}'.".format(get_key,
- set_key),
+ readable_output=f"Key '{get_key}' successfully retrieved and set into current incident at '{set_key}'.",
outputs=entry_context)
diff --git a/Packs/CommonScripts/Scripts/GetByIncidentId/GetByIncidentId_test.py b/Packs/CommonScripts/Scripts/GetByIncidentId/GetByIncidentId_test.py
index da17cb65cbe5..9a4160f08e27 100644
--- a/Packs/CommonScripts/Scripts/GetByIncidentId/GetByIncidentId_test.py
+++ b/Packs/CommonScripts/Scripts/GetByIncidentId/GetByIncidentId_test.py
@@ -11,7 +11,7 @@ def execute_command(name, args=None):
"test3key1": {"test3key2": {"test3key3": {"test3key4": {"test3key5": {"test3value"}}}}}}}
}]
else:
- raise ValueError('Unimplemented command called: {}'.format(name))
+ raise ValueError(f'Unimplemented command called: {name}')
mocker.patch.object(demisto, 'args', return_value={'incident_id': '1', 'get_key': "test1key"})
mocker.patch.object(demisto, 'executeCommand', side_effect=execute_command)
@@ -35,7 +35,7 @@ def execute_command(name, args=None):
}
}]
else:
- raise ValueError('Unimplemented command called: {}'.format(name))
+ raise ValueError(f'Unimplemented command called: {name}')
mocker.patch.object(demisto, 'args', return_value={'incident_id': '1', 'get_key': "test2key1.test2key2"})
mocker.patch.object(demisto, 'executeCommand', side_effect=execute_command)
@@ -60,7 +60,7 @@ def execute_command(name, args=None):
}
}]
else:
- raise ValueError('Unimplemented command called: {}'.format(name))
+ raise ValueError(f'Unimplemented command called: {name}')
mocker.patch.object(demisto, 'args', return_value={'incident_id': '1', 'get_key':
'test3key1.test3key2.test3key3.test3key4.test3key5'})
@@ -83,7 +83,7 @@ def execute_command(name, args=None):
"test3key1": {"test3key2": {"test3key3": {"test3key4": {"test3key5": {"test3value"}}}}}}}
}]
else:
- raise ValueError('Unimplemented command called: {}'.format(name))
+ raise ValueError(f'Unimplemented command called: {name}')
mocker.patch.object(demisto, 'args', return_value={'incident_id': '1', 'get_key': "test1key"})
mocker.patch.object(demisto, 'executeCommand', side_effect=execute_command)
@@ -106,7 +106,7 @@ def execute_command(name, args=None):
"test3key1": {"test3key2": {"test3key3": {"test3key4": {"test3key5": {"test3value"}}}}}}}
}]
else:
- raise ValueError('Unimplemented command called: {}'.format(name))
+ raise ValueError(f'Unimplemented command called: {name}')
mocker.patch.object(demisto, 'args', return_value={'incident_id': '1', 'get_key': "test1key", 'set_key':
"testSet1"})
@@ -131,7 +131,7 @@ def execute_command(name, args=None):
"test3key1": {"test3key2": {"test3key3": {"test3key4": {"test3key5": {"test3value"}}}}}}}
}]
else:
- raise ValueError('Unimplemented command called: {}'.format(name))
+ raise ValueError(f'Unimplemented command called: {name}')
mocker.patch.object(demisto, 'args', return_value={'incident_id': '1', 'get_key': "test1key", 'set_key':
"testSet1.testSet2"})
@@ -156,7 +156,7 @@ def execute_command(name, args=None):
"test3key1": {"test3key2": {"test3key3": {"test3key4": {"test3key5": {"test3value"}}}}}}}
}]
else:
- raise ValueError('Unimplemented command called: {}'.format(name))
+ raise ValueError(f'Unimplemented command called: {name}')
mocker.patch.object(demisto, 'args', return_value={'incident_id': '1',
'get_key': "test1key",
@@ -181,7 +181,7 @@ def execute_command(name, args=None):
"test3key1": {"test3key2": {"test3key3": {"test3key4": {"test3key5": {"test3value"}}}}}}}
}]
else:
- raise ValueError('Unimplemented command called: {}'.format(name))
+ raise ValueError(f'Unimplemented command called: {name}')
mocker.patch.object(demisto, 'args', return_value={'incident_id': '1', 'get_key': "test2key1.test2key2", 'set_key':
"testSet1.testSet2"})
@@ -202,7 +202,7 @@ def execute_command(name, args=None):
if name == 'getContext':
return [{'Contents': {'context': {"test1key": ["testvalue1", "testvalue2", "testvalue3"]}}}]
else:
- raise ValueError('Unimplemented command called: {}'.format(name))
+ raise ValueError(f'Unimplemented command called: {name}')
mocker.patch.object(demisto, 'args', return_value={'incident_id': '1', 'get_key': "test1key"})
mocker.patch.object(demisto, 'executeCommand', side_effect=execute_command)
@@ -222,7 +222,7 @@ def execute_command(name, args=None):
if name == 'getContext':
return [{'Contents': {'context': {"test1key": {"testobjkey": "testobjval"}}}}]
else:
- raise ValueError('Unimplemented command called: {}'.format(name))
+ raise ValueError(f'Unimplemented command called: {name}')
mocker.patch.object(demisto, 'args', return_value={'incident_id': '1', 'get_key': "test1key"})
mocker.patch.object(demisto, 'executeCommand', side_effect=execute_command)
diff --git a/Packs/CommonScripts/Scripts/GetDataCollectionLink/GetDataCollectionLink.py b/Packs/CommonScripts/Scripts/GetDataCollectionLink/GetDataCollectionLink.py
index 9e7ec79f2502..bbf34b665778 100644
--- a/Packs/CommonScripts/Scripts/GetDataCollectionLink/GetDataCollectionLink.py
+++ b/Packs/CommonScripts/Scripts/GetDataCollectionLink/GetDataCollectionLink.py
@@ -1,8 +1,9 @@
-import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
from base64 import b64encode
-from typing import Any, Dict
from distutils.version import LooseVersion
+from typing import Any
+
+import demistomock as demisto # noqa: F401
+from CommonServerPython import * # noqa: F401
def is_machine_saas() -> bool:
@@ -43,7 +44,7 @@ def encode_string(value: str) -> str:
return b64.hex()
-def get_data_collection_url(task_id: str, users: List[str]) -> List[Dict[str, str]]:
+def get_data_collection_url(task_id: str, users: List[str]) -> List[dict[str, str]]:
demisto_urls = demisto.demistoUrls()
server_url = demisto_urls.get('server', '')
incident_id = demisto.incident().get('id')
@@ -63,7 +64,7 @@ def get_data_collection_url(task_id: str, users: List[str]) -> List[Dict[str, st
return urls
-def get_data_collection_url_command(args: Dict[str, Any]) -> CommandResults: # pragma: no cover
+def get_data_collection_url_command(args: dict[str, Any]) -> CommandResults: # pragma: no cover
task_id = args.get('task_id', None)
if not task_id:
raise ValueError('task_id not specified')
@@ -86,7 +87,7 @@ def main(): # pragma: no cover
try:
return_results(get_data_collection_url_command(demisto.args()))
except Exception as ex:
- return_error(f'Failed to execute GetDataCollectionLink. Error: {str(ex)}')
+ return_error(f'Failed to execute GetDataCollectionLink. Error: {ex!s}')
if __name__ in ('__main__', '__builtin__', 'builtins'):
diff --git a/Packs/CommonScripts/Scripts/GetDataCollectionLink/GetDataCollectionLink_test.py b/Packs/CommonScripts/Scripts/GetDataCollectionLink/GetDataCollectionLink_test.py
index 74b5104fe185..f17989f06a07 100644
--- a/Packs/CommonScripts/Scripts/GetDataCollectionLink/GetDataCollectionLink_test.py
+++ b/Packs/CommonScripts/Scripts/GetDataCollectionLink/GetDataCollectionLink_test.py
@@ -2,9 +2,9 @@
import pytest
from GetDataCollectionLink import (
encode_string,
+ generate_url,
get_data_collection_url,
is_machine_saas,
- generate_url,
)
diff --git a/Packs/CommonScripts/Scripts/GetDockerImageLatestTag/GetDockerImageLatestTag.py b/Packs/CommonScripts/Scripts/GetDockerImageLatestTag/GetDockerImageLatestTag.py
index 8f36e1a55030..aa2336d5c99a 100644
--- a/Packs/CommonScripts/Scripts/GetDockerImageLatestTag/GetDockerImageLatestTag.py
+++ b/Packs/CommonScripts/Scripts/GetDockerImageLatestTag/GetDockerImageLatestTag.py
@@ -1,10 +1,11 @@
+import re
+
import demistomock as demisto
-from CommonServerPython import *
-from CommonServerUserPython import *
import requests
-import re
+from CommonServerPython import *
from pkg_resources import parse_version
+from CommonServerUserPython import *
ACCEPT_HEADER = {
'Accept': "application/json, "
@@ -53,8 +54,7 @@ def docker_auth(image_name, verify_ssl=True, registry=DEFAULT_REGISTRY, gateway_
else:
demisto.info(f'Failed parsing www-authenticate header: {www_auth}')
else:
- demisto.info('Failed extracting www-authenticate header from registry: {}, final url: {}'.format(
- registry, res.url))
+ demisto.info(f'Failed extracting www-authenticate header from registry: {registry}, final url: {res.url}')
headers = ACCEPT_HEADER.copy()
if gateway_creds and registry != DEFAULT_REGISTRY:
headers['Authorization'] = f"Basic {gateway_creds}"
@@ -191,7 +191,7 @@ def main():
demisto.results(tag)
except Exception as ex:
- return_error(f"Failed getting tag for: {docker_full_name}. Err: {str(ex)}")
+ return_error(f"Failed getting tag for: {docker_full_name}. Err: {ex!s}")
# python2 uses __builtin__ python3 uses builtins
diff --git a/Packs/CommonScripts/Scripts/GetDockerImageLatestTag/GetDockerImageLatestTag_test.py b/Packs/CommonScripts/Scripts/GetDockerImageLatestTag/GetDockerImageLatestTag_test.py
index c197795f7f42..930280fdfd32 100644
--- a/Packs/CommonScripts/Scripts/GetDockerImageLatestTag/GetDockerImageLatestTag_test.py
+++ b/Packs/CommonScripts/Scripts/GetDockerImageLatestTag/GetDockerImageLatestTag_test.py
@@ -1,7 +1,7 @@
-import requests_mock
-from GetDockerImageLatestTag import main, find_latest_tag_by_date, lexical_find_latest_tag
import demistomock as demisto
import pytest
+import requests_mock
+from GetDockerImageLatestTag import find_latest_tag_by_date, lexical_find_latest_tag, main
RETURN_ERROR_TARGET = 'GetDockerImageLatestTag.return_error'
diff --git a/Packs/CommonScripts/Scripts/GetDomainDNSDetails/GetDomainDNSDetails.py b/Packs/CommonScripts/Scripts/GetDomainDNSDetails/GetDomainDNSDetails.py
index f298519d7bbf..b2eb540f6eb3 100644
--- a/Packs/CommonScripts/Scripts/GetDomainDNSDetails/GetDomainDNSDetails.py
+++ b/Packs/CommonScripts/Scripts/GetDomainDNSDetails/GetDomainDNSDetails.py
@@ -106,7 +106,7 @@ def main():
return_results(get_domain_dns_details_command(demisto.args()))
except Exception as ex:
demisto.error(traceback.format_exc()) # print the traceback
- return_error(f'Failed to execute GetDomainDNSDetails. Error: {str(ex)}')
+ return_error(f'Failed to execute GetDomainDNSDetails. Error: {ex!s}')
''' ENTRY POINT '''
diff --git a/Packs/CommonScripts/Scripts/GetDomainDNSDetails/GetDomainDNSDetails_test.py b/Packs/CommonScripts/Scripts/GetDomainDNSDetails/GetDomainDNSDetails_test.py
index c74012cee474..2371658ad205 100644
--- a/Packs/CommonScripts/Scripts/GetDomainDNSDetails/GetDomainDNSDetails_test.py
+++ b/Packs/CommonScripts/Scripts/GetDomainDNSDetails/GetDomainDNSDetails_test.py
@@ -1,8 +1,8 @@
-from GetDomainDNSDetails import make_query, get_domain_dns_details_command
-
-from typing import cast, List, TYPE_CHECKING
+from typing import TYPE_CHECKING, cast
import dns.rdatatype
+from GetDomainDNSDetails import get_domain_dns_details_command, make_query
+
if TYPE_CHECKING:
import dns.resolver
@@ -18,11 +18,11 @@ def to_text(self):
class MockAnswer:
- def __init__(self, rrset: List[MockRData]):
+ def __init__(self, rrset: list[MockRData]):
self.rrset = rrset
-class MockResolver():
+class MockResolver:
def __init__(self):
self.nameservers = []
diff --git a/Packs/CommonScripts/Scripts/GetEndpointData/GetEndpointData.py b/Packs/CommonScripts/Scripts/GetEndpointData/GetEndpointData.py
index a85e672f262a..bc7ac34c0539 100644
--- a/Packs/CommonScripts/Scripts/GetEndpointData/GetEndpointData.py
+++ b/Packs/CommonScripts/Scripts/GetEndpointData/GetEndpointData.py
@@ -1,7 +1,8 @@
-from CommonServerPython import *
-from typing import Any
from collections.abc import Callable
from itertools import zip_longest
+from typing import Any
+
+from CommonServerPython import *
class Command:
@@ -878,7 +879,7 @@ def main():
return_results(command_results_list)
except Exception as e:
- return_error(f"Failed to execute get-endpoint-data. Error: {str(e)}")
+ return_error(f"Failed to execute get-endpoint-data. Error: {e!s}")
""" ENTRY POINT """
diff --git a/Packs/CommonScripts/Scripts/GetEndpointData/GetEndpointData_test.py b/Packs/CommonScripts/Scripts/GetEndpointData/GetEndpointData_test.py
index fcc884960da5..9d3a154fd193 100644
--- a/Packs/CommonScripts/Scripts/GetEndpointData/GetEndpointData_test.py
+++ b/Packs/CommonScripts/Scripts/GetEndpointData/GetEndpointData_test.py
@@ -1,5 +1,5 @@
-import pytest
import demistomock as demisto
+import pytest
from CommonServerPython import CommandResults, EntryType
from GetEndpointData import *
diff --git a/Packs/CommonScripts/Scripts/GetEntries/GetEntries.py b/Packs/CommonScripts/Scripts/GetEntries/GetEntries.py
index 55a26aab0011..d6c4f48f67d0 100644
--- a/Packs/CommonScripts/Scripts/GetEntries/GetEntries.py
+++ b/Packs/CommonScripts/Scripts/GetEntries/GetEntries.py
@@ -42,7 +42,7 @@ def main():
raw_response=ents))
except Exception as e:
demisto.debug(traceback.format_exc())
- return_error(f'Failed to execute GetEntries.\nError:\n{type(e)}, {str(e)}')
+ return_error(f'Failed to execute GetEntries.\nError:\n{type(e)}, {e!s}')
if __name__ in ('__builtin__', 'builtins', '__main__'):
diff --git a/Packs/CommonScripts/Scripts/GetEntries/GetEntries_test.py b/Packs/CommonScripts/Scripts/GetEntries/GetEntries_test.py
index 3ac09c75b851..3348e86a4f62 100644
--- a/Packs/CommonScripts/Scripts/GetEntries/GetEntries_test.py
+++ b/Packs/CommonScripts/Scripts/GetEntries/GetEntries_test.py
@@ -1,7 +1,8 @@
-from CommonServerPython import *
+import json
+
import demistomock as demisto
+from CommonServerPython import *
from GetEntries import main
-import json
class SideEffectExecuteCommand:
diff --git a/Packs/CommonScripts/Scripts/GetErrorsFromEntry/GetErrorsFromEntry.py b/Packs/CommonScripts/Scripts/GetErrorsFromEntry/GetErrorsFromEntry.py
index 622b3108de2b..2bbc2c6b0674 100644
--- a/Packs/CommonScripts/Scripts/GetErrorsFromEntry/GetErrorsFromEntry.py
+++ b/Packs/CommonScripts/Scripts/GetErrorsFromEntry/GetErrorsFromEntry.py
@@ -1,7 +1,6 @@
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-
UNSUPPORTED_COMMAND_MSG = "Unsupported Command : getEntriesByIDs"
@@ -65,7 +64,7 @@ def main():
raw_response=error_messages,
))
except Exception as e:
- return_error(f'Failed to fetch errors for the given entry id(s). Problem: {str(e)}')
+ return_error(f'Failed to fetch errors for the given entry id(s). Problem: {e!s}')
if __name__ in ('__main__', '__builtin__', 'builtins'): # pragma: no cover
diff --git a/Packs/CommonScripts/Scripts/GetErrorsFromEntry/GetErrorsFromEntry_test.py b/Packs/CommonScripts/Scripts/GetErrorsFromEntry/GetErrorsFromEntry_test.py
index e95b093e534d..d6d319a50f1d 100644
--- a/Packs/CommonScripts/Scripts/GetErrorsFromEntry/GetErrorsFromEntry_test.py
+++ b/Packs/CommonScripts/Scripts/GetErrorsFromEntry/GetErrorsFromEntry_test.py
@@ -1,7 +1,7 @@
import demistomock as demisto # noqa: F401
-from CommonServerPython import entryTypes, CommandResults # noqa: F401
import GetErrorsFromEntry
import pytest
+from CommonServerPython import CommandResults, entryTypes # noqa: F401
ERROR_ENTRY_1 = [{'Contents': 'This is the error message 1', 'Type': entryTypes['error']}]
ERROR_ENTRY_2 = [{'Contents': 'This is the error message 2', 'Type': entryTypes['error']}]
diff --git a/Packs/CommonScripts/Scripts/GetFieldsByIncidentType/GetFieldsByIncidentType.py b/Packs/CommonScripts/Scripts/GetFieldsByIncidentType/GetFieldsByIncidentType.py
index 0868afe1fb44..7e30210d41c3 100644
--- a/Packs/CommonScripts/Scripts/GetFieldsByIncidentType/GetFieldsByIncidentType.py
+++ b/Packs/CommonScripts/Scripts/GetFieldsByIncidentType/GetFieldsByIncidentType.py
@@ -1,6 +1,7 @@
+from pprint import pformat
+
import demistomock as demisto
from CommonServerPython import *
-from pprint import pformat
def main():
diff --git a/Packs/CommonScripts/Scripts/GetFieldsByIncidentType/GetFieldsByIncidentType_test.py b/Packs/CommonScripts/Scripts/GetFieldsByIncidentType/GetFieldsByIncidentType_test.py
index b76185cf4dad..702dc04e5695 100644
--- a/Packs/CommonScripts/Scripts/GetFieldsByIncidentType/GetFieldsByIncidentType_test.py
+++ b/Packs/CommonScripts/Scripts/GetFieldsByIncidentType/GetFieldsByIncidentType_test.py
@@ -1,6 +1,7 @@
-import demistomock as demisto
import json
+import demistomock as demisto
+
def executeCommand(name, args=None):
if name == 'core-api-get' and args and 'uri' in args and args['uri'] == "/incidentfields":
diff --git a/Packs/CommonScripts/Scripts/GetIndicatorDBotScore/GetIndicatorDBotScore.py b/Packs/CommonScripts/Scripts/GetIndicatorDBotScore/GetIndicatorDBotScore.py
index e3c66473d0f8..1cdc542760a9 100644
--- a/Packs/CommonScripts/Scripts/GetIndicatorDBotScore/GetIndicatorDBotScore.py
+++ b/Packs/CommonScripts/Scripts/GetIndicatorDBotScore/GetIndicatorDBotScore.py
@@ -1,5 +1,6 @@
import demistomock as demisto
from CommonServerPython import *
+
from CommonServerUserPython import *
CONTEXT_PATH = 'DBotScore'
@@ -40,7 +41,7 @@ def iterate_indicator_entry(indicator, entry):
source = DEFAULT_SOURCE
dbot_score = get_dbot_score_data(indicator, indicator_type, source, data.get('score', entry["score"]))
command_results = CommandResults(
- readable_output=tableToMarkdown('Indicator DBot Score: {}'.format(indicator), dbot_score),
+ readable_output=tableToMarkdown(f'Indicator DBot Score: {indicator}', dbot_score),
outputs={CONTEXT_PATH: dbot_score}
).to_context()
context_entry_results = command_results.pop('EntryContext')[CONTEXT_PATH]
@@ -61,7 +62,7 @@ def main():
data = resp[0].get("Contents")
if not data:
- demisto.results("No results found for indicator {} .".format(indicator))
+ demisto.results(f"No results found for indicator {indicator} .")
continue
dbot_scores = []
diff --git a/Packs/CommonScripts/Scripts/GetIndicatorDBotScore/GetIndicatorDBotScore_test.py b/Packs/CommonScripts/Scripts/GetIndicatorDBotScore/GetIndicatorDBotScore_test.py
index 81a90681db9f..7c68f90faadc 100644
--- a/Packs/CommonScripts/Scripts/GetIndicatorDBotScore/GetIndicatorDBotScore_test.py
+++ b/Packs/CommonScripts/Scripts/GetIndicatorDBotScore/GetIndicatorDBotScore_test.py
@@ -1,7 +1,6 @@
-import pytest
-import demistomock as demisto
import CommonServerPython
-
+import demistomock as demisto
+import pytest
GetIndicatorDBotScoreFunc = 'GetIndicatorDBotScore.get_dbot_score_data'
@@ -35,7 +34,7 @@ def test_validate_indicator_type(indicator, indicator_type, expected):
Then:
- validating the dbotScoreType matches the correct indicator type
"""
- from GetIndicatorDBotScore import get_dbot_score_data, INDICATOR_TYPES
+ from GetIndicatorDBotScore import INDICATOR_TYPES, get_dbot_score_data
indicator_type_after_mapping = INDICATOR_TYPES.get(indicator_type, indicator_type).lower()
res = get_dbot_score_data(indicator, indicator_type_after_mapping, 'source', 0)
assert res.get('Type') == expected
diff --git a/Packs/CommonScripts/Scripts/GetIndicatorDBotScoreFromCache/GetIndicatorDBotScoreFromCache.py b/Packs/CommonScripts/Scripts/GetIndicatorDBotScoreFromCache/GetIndicatorDBotScoreFromCache.py
index dd699b70af49..0fe9100daa87 100644
--- a/Packs/CommonScripts/Scripts/GetIndicatorDBotScoreFromCache/GetIndicatorDBotScoreFromCache.py
+++ b/Packs/CommonScripts/Scripts/GetIndicatorDBotScoreFromCache/GetIndicatorDBotScoreFromCache.py
@@ -1,4 +1,5 @@
import contextlib
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
diff --git a/Packs/CommonScripts/Scripts/GetIndicatorDBotScoreFromCache/GetIndicatorDBotScoreFromCache_test.py b/Packs/CommonScripts/Scripts/GetIndicatorDBotScoreFromCache/GetIndicatorDBotScoreFromCache_test.py
index c42dd4492624..a8ee74a65846 100644
--- a/Packs/CommonScripts/Scripts/GetIndicatorDBotScoreFromCache/GetIndicatorDBotScoreFromCache_test.py
+++ b/Packs/CommonScripts/Scripts/GetIndicatorDBotScoreFromCache/GetIndicatorDBotScoreFromCache_test.py
@@ -1,5 +1,5 @@
-import GetIndicatorDBotScoreFromCache
import demistomock as demisto
+import GetIndicatorDBotScoreFromCache
import pytest
diff --git a/Packs/CommonScripts/Scripts/GetInstances/GetInstances.py b/Packs/CommonScripts/Scripts/GetInstances/GetInstances.py
index 20129d11d21e..db83f920b545 100644
--- a/Packs/CommonScripts/Scripts/GetInstances/GetInstances.py
+++ b/Packs/CommonScripts/Scripts/GetInstances/GetInstances.py
@@ -1,12 +1,12 @@
+from collections.abc import Iterator
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-from typing import Dict, Iterator
-
INTERNAL_MODULES_BRANDS = ['Scripts', 'Builtin', 'testmodule']
-def filter_config(module: Dict, filter_brand: Optional[List[str]] = None, instance_status: str = 'active'):
+def filter_config(module: dict, filter_brand: Optional[List[str]] = None, instance_status: str = 'active'):
brand = module.get('brand')
if brand in INTERNAL_MODULES_BRANDS:
return False
@@ -18,7 +18,7 @@ def filter_config(module: Dict, filter_brand: Optional[List[str]] = None, instan
return True
-def prepare_args(args: Dict):
+def prepare_args(args: dict):
if 'brand' in args:
args['filter_brand'] = argToList(args.pop('brand'))
@@ -28,7 +28,7 @@ def prepare_args(args: Dict):
return args
-def filter_instances(modules: Dict, **kwargs) -> Iterator[Dict]:
+def filter_instances(modules: dict, **kwargs) -> Iterator[dict]:
for instance, config in modules.items():
if filter_config(config, **kwargs):
config['name'] = instance
diff --git a/Packs/CommonScripts/Scripts/GetInstances/GetInstances_test.py b/Packs/CommonScripts/Scripts/GetInstances/GetInstances_test.py
index 00ef5ddc1b78..07c879a8738d 100644
--- a/Packs/CommonScripts/Scripts/GetInstances/GetInstances_test.py
+++ b/Packs/CommonScripts/Scripts/GetInstances/GetInstances_test.py
@@ -1,7 +1,6 @@
import pytest
from GetInstances import *
-
ARGS_SYSTEM_FILTER = {'instance_status': 'both'}
ARGS_BRAND_FILTER = {'brand': 'EWS v2, splunk', 'instance_status': 'both'}
ARGS_IS_ENABLED_FILTER = {'instance_status': 'active'}
@@ -13,7 +12,7 @@
def load_json_file(path):
- with open(path, 'r') as json_file:
+ with open(path) as json_file:
json_string = json_file.read()
return json.loads(json_string)
diff --git a/Packs/CommonScripts/Scripts/GetLicenseID/GetLicenseID_test.py b/Packs/CommonScripts/Scripts/GetLicenseID/GetLicenseID_test.py
index e68338b9bfd8..6345483237b0 100644
--- a/Packs/CommonScripts/Scripts/GetLicenseID/GetLicenseID_test.py
+++ b/Packs/CommonScripts/Scripts/GetLicenseID/GetLicenseID_test.py
@@ -1,5 +1,5 @@
-from GetLicenseID import get_license_id
import demistomock as demisto
+from GetLicenseID import get_license_id
def test_human_readable(mocker):
diff --git a/Packs/CommonScripts/Scripts/GetServerURL/GetServerURL.py b/Packs/CommonScripts/Scripts/GetServerURL/GetServerURL.py
index 2f54fd45ad93..b948daef0db3 100644
--- a/Packs/CommonScripts/Scripts/GetServerURL/GetServerURL.py
+++ b/Packs/CommonScripts/Scripts/GetServerURL/GetServerURL.py
@@ -1,6 +1,7 @@
+from urllib.parse import ParseResult, urlparse
+
import demistomock as demisto
from CommonServerPython import *
-from urllib.parse import urlparse, ParseResult
def main():
diff --git a/Packs/CommonScripts/Scripts/GetServerURL/GetServerURL_test.py b/Packs/CommonScripts/Scripts/GetServerURL/GetServerURL_test.py
index aba79bfd57ca..49190c1c1ad4 100644
--- a/Packs/CommonScripts/Scripts/GetServerURL/GetServerURL_test.py
+++ b/Packs/CommonScripts/Scripts/GetServerURL/GetServerURL_test.py
@@ -1,6 +1,6 @@
import demistomock as demisto
-from CommonServerPython import *
import GetServerURL
+from CommonServerPython import *
def test_get_url(mocker):
diff --git a/Packs/CommonScripts/Scripts/GetStringsDistance/GetStringsDistance.py b/Packs/CommonScripts/Scripts/GetStringsDistance/GetStringsDistance.py
index 33996f0224ed..23432bc5a923 100644
--- a/Packs/CommonScripts/Scripts/GetStringsDistance/GetStringsDistance.py
+++ b/Packs/CommonScripts/Scripts/GetStringsDistance/GetStringsDistance.py
@@ -8,8 +8,8 @@ def levenshtein(s1, s2):
matrix = [list(range(l1 + 1))] * (l2 + 1)
for zz in range(l2 + 1):
matrix[zz] = list(range(zz, zz + l1 + 1))
- for zz in range(0, l2):
- for sz in range(0, l1):
+ for zz in range(l2):
+ for sz in range(l1):
if s1[sz] == s2[zz]:
matrix[zz + 1][sz + 1] = min(matrix[zz + 1][sz] + 1, matrix[zz][sz + 1] + 1, matrix[zz][sz])
else:
diff --git a/Packs/CommonScripts/Scripts/GetUserData/GetUserData.py b/Packs/CommonScripts/Scripts/GetUserData/GetUserData.py
index 72625aa6df41..7f49c476079f 100644
--- a/Packs/CommonScripts/Scripts/GetUserData/GetUserData.py
+++ b/Packs/CommonScripts/Scripts/GetUserData/GetUserData.py
@@ -1,9 +1,9 @@
-import demistomock as demisto
-from CommonServerPython import *
-
import itertools
from typing import Any
+import demistomock as demisto
+from CommonServerPython import *
+
class Command:
def __init__(self, brand: str, name: str, args: dict) -> None:
@@ -948,7 +948,7 @@ def main():
)
return_results(command_results_list)
except Exception as e:
- return_error(f"Failed to execute get-user-data. Error: {str(e)}")
+ return_error(f"Failed to execute get-user-data. Error: {e!s}")
""" ENTRY POINT """
diff --git a/Packs/CommonScripts/Scripts/GetUserData/GetUserData_test.py b/Packs/CommonScripts/Scripts/GetUserData/GetUserData_test.py
index b86e497ee80a..c2e5c656b544 100644
--- a/Packs/CommonScripts/Scripts/GetUserData/GetUserData_test.py
+++ b/Packs/CommonScripts/Scripts/GetUserData/GetUserData_test.py
@@ -1,32 +1,30 @@
-from pytest_mock import MockerFixture
-
import demistomock as demisto
from CommonServerPython import *
-
from GetUserData import (
- Modules,
Command,
- is_valid_args,
+ Modules,
+ ad_get_user,
+ ad_get_user_manager,
+ aws_iam_get_user,
create_account,
- merge_accounts,
enrich_data_with_source,
- prepare_human_readable,
get_output_key,
get_outputs,
- run_execute_command,
+ iam_get_user_command,
identityiq_search_identities,
identitynow_get_accounts,
- ad_get_user,
- ad_get_user_manager,
- pingone_get_user,
- okta_get_user,
- aws_iam_get_user,
+ is_valid_args,
+ main,
+ merge_accounts,
msgraph_user_get,
msgraph_user_get_manager,
+ okta_get_user,
+ pingone_get_user,
+ prepare_human_readable,
+ run_execute_command,
xdr_list_risky_users,
- iam_get_user_command,
- main,
)
+from pytest_mock import MockerFixture
def test_modules_init_with_active_brands():
diff --git a/Packs/CommonScripts/Scripts/GridFieldSetup/GridFieldSetup.py b/Packs/CommonScripts/Scripts/GridFieldSetup/GridFieldSetup.py
index eb873a1cb4da..655d5edfb535 100644
--- a/Packs/CommonScripts/Scripts/GridFieldSetup/GridFieldSetup.py
+++ b/Packs/CommonScripts/Scripts/GridFieldSetup/GridFieldSetup.py
@@ -61,7 +61,7 @@ def main():
try:
return_results(grid_field_setup_command(demisto.args()))
except Exception as ex:
- return_error(f'Failed to execute GridFieldSetup. Error: {str(ex)}')
+ return_error(f'Failed to execute GridFieldSetup. Error: {ex!s}')
''' ENTRY POINT '''
diff --git a/Packs/CommonScripts/Scripts/GridFieldSetup/GridFieldSetup_test.py b/Packs/CommonScripts/Scripts/GridFieldSetup/GridFieldSetup_test.py
index 6fc37de6d85c..200fe4e73df8 100644
--- a/Packs/CommonScripts/Scripts/GridFieldSetup/GridFieldSetup_test.py
+++ b/Packs/CommonScripts/Scripts/GridFieldSetup/GridFieldSetup_test.py
@@ -1,5 +1,5 @@
-from GridFieldSetup import *
import pytest
+from GridFieldSetup import *
incident_contains_field_in_root = {
'field_name': 'Test',
diff --git a/Packs/CommonScripts/Scripts/HTMLtoMD/HTMLtoMD.py b/Packs/CommonScripts/Scripts/HTMLtoMD/HTMLtoMD.py
index 898bedb3507b..e068a23fdebb 100644
--- a/Packs/CommonScripts/Scripts/HTMLtoMD/HTMLtoMD.py
+++ b/Packs/CommonScripts/Scripts/HTMLtoMD/HTMLtoMD.py
@@ -36,7 +36,7 @@ def main():
'EntryContext': outputs
})
except Exception as expt:
- return_error(f'Failed to execute HTMLtoMD script. Error: {str(expt)}')
+ return_error(f'Failed to execute HTMLtoMD script. Error: {expt!s}')
if __name__ in ('__main__', '__builtin__', 'builtins'):
diff --git a/Packs/CommonScripts/Scripts/HTMLtoMD/HTMLtoMD_test.py b/Packs/CommonScripts/Scripts/HTMLtoMD/HTMLtoMD_test.py
index ab88019879ee..a83ecae889e0 100644
--- a/Packs/CommonScripts/Scripts/HTMLtoMD/HTMLtoMD_test.py
+++ b/Packs/CommonScripts/Scripts/HTMLtoMD/HTMLtoMD_test.py
@@ -1,6 +1,6 @@
-from HTMLtoMD import main
-from CommonServerPython import formats
import demistomock as demisto
+from CommonServerPython import formats
+from HTMLtoMD import main
def test_main(mocker):
diff --git a/Packs/CommonScripts/Scripts/HTTPListRedirects/HTTPListRedirects.py b/Packs/CommonScripts/Scripts/HTTPListRedirects/HTTPListRedirects.py
index 6403c28a316e..1fe6b669bb21 100644
--- a/Packs/CommonScripts/Scripts/HTTPListRedirects/HTTPListRedirects.py
+++ b/Packs/CommonScripts/Scripts/HTTPListRedirects/HTTPListRedirects.py
@@ -1,8 +1,9 @@
+import os
+
import demistomock as demisto
-from CommonServerPython import *
import requests
-import os
import urllib3
+from CommonServerPython import *
urllib3.disable_warnings()
@@ -52,7 +53,7 @@ def main():
demisto.results(create_command_result(history_urls=history_urls))
except Exception as e:
- return_error(f'Failed to execute script. Error:\n{str(e)}')
+ return_error(f'Failed to execute script. Error:\n{e!s}')
if __name__ in ('__builtin__', 'builtins', '__main__'):
diff --git a/Packs/CommonScripts/Scripts/HTTPListRedirects/HTTPListRedirects_test.py b/Packs/CommonScripts/Scripts/HTTPListRedirects/HTTPListRedirects_test.py
index c9009a8a8545..899580180d3d 100644
--- a/Packs/CommonScripts/Scripts/HTTPListRedirects/HTTPListRedirects_test.py
+++ b/Packs/CommonScripts/Scripts/HTTPListRedirects/HTTPListRedirects_test.py
@@ -1,12 +1,12 @@
-from typing import Union
+
import pytest
-import requests_mock
import requests
+import requests_mock
MOCK_ADDR = 'mock://'
-def custom_matcher(request: requests.Request) -> Union[requests.Response, None]:
+def custom_matcher(request: requests.Request) -> requests.Response | None:
if request.url == f'{MOCK_ADDR}http://example.com':
first_history = requests.Response()
first_history.url = 'http://example.com/'
@@ -126,7 +126,7 @@ def test_valid_command_result(history_urls):
- Validating the structure of the returned result to the user
"""
- from CommonServerPython import (formats, entryTypes, tableToMarkdown)
+ from CommonServerPython import entryTypes, formats, tableToMarkdown
from HTTPListRedirects import create_command_result
ec = {'URL(val.Data == obj.Data)': [{'Data': history_url['Data']} for history_url in history_urls]}
expected_command_result = {'ContentsFormat': formats['json'], 'Type': entryTypes['note'], 'Contents': history_urls,
@@ -156,8 +156,9 @@ def test_environment_variables(params):
- Validating that the specific environment variables got deleted
"""
- from HTTPListRedirects import delete_environment_variables
import os
+
+ from HTTPListRedirects import delete_environment_variables
use_system_proxy = params['use_system_proxy']
delete_environment_variables(use_system_proxy=use_system_proxy)
env_variables = ['HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy']
diff --git a/Packs/CommonScripts/Scripts/HttpV2/HttpV2.py b/Packs/CommonScripts/Scripts/HttpV2/HttpV2.py
index 97a8f18d4f77..505b9ebc3f29 100644
--- a/Packs/CommonScripts/Scripts/HttpV2/HttpV2.py
+++ b/Packs/CommonScripts/Scripts/HttpV2/HttpV2.py
@@ -1,9 +1,9 @@
+import json
+
import demistomock as demisto
from CommonServerPython import *
-from CommonServerUserPython import *
-from typing import Dict, List
-import json
+from CommonServerUserPython import *
CONTENT_TYPE_MAPPER = {
"json": "application/json",
@@ -70,8 +70,8 @@ def _generic_error_handler(res: requests.Response):
raise DemistoException(f"Bad gateway. Status code: {status_code}. Origin response from server: {res.text}")
-def create_headers(headers: Dict, request_content_type_header: str, response_content_type_header: str) \
- -> Dict[str, str]:
+def create_headers(headers: dict, request_content_type_header: str, response_content_type_header: str) \
+ -> dict[str, str]:
"""
Create a dictionary of headers. It will map the header if it exists in the CONTENT_TYPE_MAPPER.
Args:
@@ -105,11 +105,11 @@ def get_parsed_response(res, resp_type: str) -> Any:
res = res.text
return res
except ValueError as exception:
- raise DemistoException('Failed to parse json object from response: {}'
- .format(res.content), exception)
+ raise DemistoException(f'Failed to parse json object from response: {res.content}'
+ , exception)
-def format_status_list(status_list: list) -> List[int]:
+def format_status_list(status_list: list) -> list[int]:
"""
Get a status list and format it to a range of status numbers.
Example:
@@ -132,7 +132,7 @@ def format_status_list(status_list: list) -> List[int]:
return final_status_list
-def build_outputs(parsed_res, res: requests.Response) -> Dict:
+def build_outputs(parsed_res, res: requests.Response) -> dict:
return {'ParsedBody': parsed_res,
'Body': res.text,
'StatusCode': res.status_code,
@@ -141,7 +141,7 @@ def build_outputs(parsed_res, res: requests.Response) -> Dict:
'Headers': dict(res.headers)}
-def parse_headers(headers: str) -> Dict:
+def parse_headers(headers: str) -> dict:
"""
Parsing headers from str type to dict.
The allowed format are:
@@ -227,7 +227,7 @@ def main():
raw_response={'data': parsed_res}
)
except Exception as e:
- return_error(f'Failed to execute HttpV2 script. Error: {str(e)}')
+ return_error(f'Failed to execute HttpV2 script. Error: {e!s}')
if __name__ in ('__main__', '__builtin__', 'builtins'):
diff --git a/Packs/CommonScripts/Scripts/HttpV2/HttpV2_test.py b/Packs/CommonScripts/Scripts/HttpV2/HttpV2_test.py
index 5adf9371a3cb..cc5b48729445 100644
--- a/Packs/CommonScripts/Scripts/HttpV2/HttpV2_test.py
+++ b/Packs/CommonScripts/Scripts/HttpV2/HttpV2_test.py
@@ -1,11 +1,11 @@
import json
-import io
+
import pytest
from CommonServerPython import DemistoException
def util_load_json(path):
- with io.open(path, mode='r', encoding='utf-8') as f:
+ with open(path, encoding='utf-8') as f:
return json.loads(f.read())
diff --git a/Packs/CommonScripts/Scripts/IPNetwork/IPNetwork.py b/Packs/CommonScripts/Scripts/IPNetwork/IPNetwork.py
index a525e6661ccb..a7f1718d8707 100644
--- a/Packs/CommonScripts/Scripts/IPNetwork/IPNetwork.py
+++ b/Packs/CommonScripts/Scripts/IPNetwork/IPNetwork.py
@@ -1,14 +1,13 @@
-import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
# STD imports
import ipaddress
-from typing import Dict
+import demistomock as demisto # noqa: F401
+from CommonServerPython import * # noqa: F401
# Local imports
-def ip_cidr(cidr: str) -> Dict[str, str]:
+def ip_cidr(cidr: str) -> dict[str, str]:
""" Gather info regarding the supplied network
Args:
@@ -34,7 +33,7 @@ def ip_cidr(cidr: str) -> Dict[str, str]:
return {}
-def cidr_command(args: Dict[str, str]) -> CommandResults:
+def cidr_command(args: dict[str, str]) -> CommandResults:
""" Perform command on given IP/CIDR
Args:
@@ -59,7 +58,7 @@ def main():
try:
return_results(cidr_command(demisto.args()))
except Exception as ex:
- return_error(f'Failed to execute IPNetwork script. Error: {str(ex)}')
+ return_error(f'Failed to execute IPNetwork script. Error: {ex!s}')
if __name__ in ('__main__', '__builtin__', 'builtins'):
diff --git a/Packs/CommonScripts/Scripts/IPNetwork/IPNetwork_test.py b/Packs/CommonScripts/Scripts/IPNetwork/IPNetwork_test.py
index 694645ca9181..d982c6745e2a 100644
--- a/Packs/CommonScripts/Scripts/IPNetwork/IPNetwork_test.py
+++ b/Packs/CommonScripts/Scripts/IPNetwork/IPNetwork_test.py
@@ -1,6 +1,7 @@
-import pytest
import json
+import pytest
+
# About the drop some mean regex right now disable-secrets-detection-start
@pytest.mark.parametrize(argnames="cidr, expected_ec",
diff --git a/Packs/CommonScripts/Scripts/IPToHost/IPToHost.py b/Packs/CommonScripts/Scripts/IPToHost/IPToHost.py
index 6353bba62281..e1ed860e461f 100644
--- a/Packs/CommonScripts/Scripts/IPToHost/IPToHost.py
+++ b/Packs/CommonScripts/Scripts/IPToHost/IPToHost.py
@@ -1,6 +1,7 @@
+import socket
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-import socket
def ip_to_host(ip: str) -> CommandResults:
@@ -35,7 +36,7 @@ def main():
return_results(ip_to_host(ip))
except Exception as e:
demisto.error(traceback.format_exc())
- return_error(f'Couldn\'t get the IP host info. Error information: {str(e)}')
+ return_error(f'Couldn\'t get the IP host info. Error information: {e!s}')
if __name__ in ('__main__', '__builtin__', 'builtins'):
diff --git a/Packs/CommonScripts/Scripts/IdentifyAttachedEmail/IdentifyAttachedEmail.py b/Packs/CommonScripts/Scripts/IdentifyAttachedEmail/IdentifyAttachedEmail.py
index a2d047a32708..22592878c402 100644
--- a/Packs/CommonScripts/Scripts/IdentifyAttachedEmail/IdentifyAttachedEmail.py
+++ b/Packs/CommonScripts/Scripts/IdentifyAttachedEmail/IdentifyAttachedEmail.py
@@ -1,7 +1,6 @@
import demistomock as demisto
from CommonServerPython import *
-
# file info types which identify emails
CONFIDENT_EMAIL_INFOS = {
'cdfv2 microsoft outlook message',
diff --git a/Packs/CommonScripts/Scripts/IdentifyAttachedEmail/IdentifyAttachedEmail_test.py b/Packs/CommonScripts/Scripts/IdentifyAttachedEmail/IdentifyAttachedEmail_test.py
index a0ba9134f861..ea497026e6ee 100644
--- a/Packs/CommonScripts/Scripts/IdentifyAttachedEmail/IdentifyAttachedEmail_test.py
+++ b/Packs/CommonScripts/Scripts/IdentifyAttachedEmail/IdentifyAttachedEmail_test.py
@@ -1,6 +1,6 @@
-from IdentifyAttachedEmail import *
import IdentifyAttachedEmail
import pytest
+from IdentifyAttachedEmail import *
def execute_command(command, args):
diff --git a/Packs/CommonScripts/Scripts/IncidentFields/IncidentFields_test.py b/Packs/CommonScripts/Scripts/IncidentFields/IncidentFields_test.py
index 55cbee6e6d77..df59ebe2afef 100644
--- a/Packs/CommonScripts/Scripts/IncidentFields/IncidentFields_test.py
+++ b/Packs/CommonScripts/Scripts/IncidentFields/IncidentFields_test.py
@@ -1,6 +1,7 @@
-import demistomock as demisto
import json
+import demistomock as demisto
+
def executeCommand(name, args=None):
if name == 'core-api-get' and args and 'uri' in args and args['uri'] == "/incidentfields":
diff --git a/Packs/CommonScripts/Scripts/IndicatorMaliciousRatioCalculation/IndicatorMaliciousRatioCalculation.py b/Packs/CommonScripts/Scripts/IndicatorMaliciousRatioCalculation/IndicatorMaliciousRatioCalculation.py
index af861980c644..ad5ad905e310 100644
--- a/Packs/CommonScripts/Scripts/IndicatorMaliciousRatioCalculation/IndicatorMaliciousRatioCalculation.py
+++ b/Packs/CommonScripts/Scripts/IndicatorMaliciousRatioCalculation/IndicatorMaliciousRatioCalculation.py
@@ -1,13 +1,13 @@
-import demistomock as demisto
-from CommonServerPython import *
-from CommonServerUserPython import *
-
-import traceback
import hashlib
import json
+import traceback
+import demistomock as demisto
+from CommonServerPython import *
from dateutil import parser # type: ignore[import]
+from CommonServerUserPython import *
+
def get_incident_labels_map(labels):
if labels is None:
@@ -56,7 +56,7 @@ def parse_datetime(datetime_str):
def build_query_for_incidents_search(base_query, from_date):
if from_date:
- return '{} created:>="{}"'.format(base_query, parse_datetime(from_date))
+ return f'{base_query} created:>="{parse_datetime(from_date)}"'
else:
return base_query
diff --git a/Packs/CommonScripts/Scripts/IsIPPrivate/IsIPPrivate.py b/Packs/CommonScripts/Scripts/IsIPPrivate/IsIPPrivate.py
index 4de42ff7ffb3..81e8713c7a9e 100644
--- a/Packs/CommonScripts/Scripts/IsIPPrivate/IsIPPrivate.py
+++ b/Packs/CommonScripts/Scripts/IsIPPrivate/IsIPPrivate.py
@@ -1,14 +1,14 @@
-import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
from ipaddress import IPv4Address, IPv4Network
+import demistomock as demisto # noqa: F401
+from CommonServerPython import * # noqa: F401
DELIMITER = ","
def is_ip_internal(ip: str, ranges: List[str]) -> bool:
try:
- return any((IPv4Address(ip) in IPv4Network(cidr.split(DELIMITER)[0] if DELIMITER in cidr else cidr) for cidr in ranges))
+ return any(IPv4Address(ip) in IPv4Network(cidr.split(DELIMITER)[0] if DELIMITER in cidr else cidr) for cidr in ranges)
except ValueError as ve:
return return_error(f"One or more IP ranges or IPs are invalid. Please make sure the list is in the correct structure."
f"Error: {ve}")
diff --git a/Packs/CommonScripts/Scripts/IsInternalDomainName/IsInternalDomainName_test.py b/Packs/CommonScripts/Scripts/IsInternalDomainName/IsInternalDomainName_test.py
index 6658ceab5119..81ed43078ac2 100644
--- a/Packs/CommonScripts/Scripts/IsInternalDomainName/IsInternalDomainName_test.py
+++ b/Packs/CommonScripts/Scripts/IsInternalDomainName/IsInternalDomainName_test.py
@@ -1,5 +1,5 @@
-from IsInternalDomainName import check_sub_domains_in_domain, is_sub_domain_contained
import pytest
+from IsInternalDomainName import check_sub_domains_in_domain, is_sub_domain_contained
@pytest.mark.parametrize('domain_name, domain_to_check, expected_output', [
diff --git a/Packs/CommonScripts/Scripts/IsInternalHostName/IsInternalHostName.py b/Packs/CommonScripts/Scripts/IsInternalHostName/IsInternalHostName.py
index 5f5e97e17086..9fd3f45e9d30 100644
--- a/Packs/CommonScripts/Scripts/IsInternalHostName/IsInternalHostName.py
+++ b/Packs/CommonScripts/Scripts/IsInternalHostName/IsInternalHostName.py
@@ -1,6 +1,7 @@
+import re
+
import demistomock as demisto
from CommonServerPython import *
-import re
def main():
diff --git a/Packs/CommonScripts/Scripts/IsListExist/IsListExist_test.py b/Packs/CommonScripts/Scripts/IsListExist/IsListExist_test.py
index 4018cf5bada5..4c6f0250aacb 100644
--- a/Packs/CommonScripts/Scripts/IsListExist/IsListExist_test.py
+++ b/Packs/CommonScripts/Scripts/IsListExist/IsListExist_test.py
@@ -1,8 +1,6 @@
-from IsListExist import main
-
-import pytest
-
import demistomock as demisto
+import pytest
+from IsListExist import main
@pytest.mark.parametrize('list_name,get_list_res,expected', [
diff --git a/Packs/CommonScripts/Scripts/IsUrlPartOfDomain/IsUrlPartOfDomain.py b/Packs/CommonScripts/Scripts/IsUrlPartOfDomain/IsUrlPartOfDomain.py
index b5b9e6536a57..02cac135a72f 100644
--- a/Packs/CommonScripts/Scripts/IsUrlPartOfDomain/IsUrlPartOfDomain.py
+++ b/Packs/CommonScripts/Scripts/IsUrlPartOfDomain/IsUrlPartOfDomain.py
@@ -1,6 +1,6 @@
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-from typing import List, Dict
from CommonServerUserPython import *
@@ -18,7 +18,7 @@ def main(domains: str, urls: str) -> CommandResults:
urls = argToList(urls)
domains = set(argToList(domains))
- outputs: List[Dict] = list()
+ outputs: list[dict] = list()
for url in urls:
results = demisto.executeCommand('ExtractDomainFromUrlAndEmail', {'input': url.lower()})
if is_error(results):
diff --git a/Packs/CommonScripts/Scripts/IsolationAssetWrapper/IsolationAssetWrapper.py b/Packs/CommonScripts/Scripts/IsolationAssetWrapper/IsolationAssetWrapper.py
index 71506348c87a..81c93696d29e 100644
--- a/Packs/CommonScripts/Scripts/IsolationAssetWrapper/IsolationAssetWrapper.py
+++ b/Packs/CommonScripts/Scripts/IsolationAssetWrapper/IsolationAssetWrapper.py
@@ -1,4 +1,3 @@
-from typing import Tuple
from CommonServerPython import *
@@ -11,7 +10,7 @@
'unisolate': 'xdr-unisolate-endpoint'
}
-MSDE_ACTIONS: Dict[str, Tuple[str, Dict[str, str]]] = {
+MSDE_ACTIONS: Dict[str, tuple[str, Dict[str, str]]] = {
'isolate': ('microsoft-atp-isolate-machine', {'isolation_type': 'Full'}),
'unisolate': ('microsoft-atp-unisolate-machine', {})
}
@@ -81,7 +80,7 @@ def main(): # pragma: no cover
try:
return_results(run_isolation_action(device_ids, action))
except Exception as ex:
- return_error(f'Failed to execute IsolationAssetWrapper. Error: {str(ex)}')
+ return_error(f'Failed to execute IsolationAssetWrapper. Error: {ex!s}')
''' ENTRY POINT '''
diff --git a/Packs/CommonScripts/Scripts/IsolationAssetWrapper/IsolationAssetWrapper_test.py b/Packs/CommonScripts/Scripts/IsolationAssetWrapper/IsolationAssetWrapper_test.py
index bba79a12d0b5..fecf4ede9cea 100644
--- a/Packs/CommonScripts/Scripts/IsolationAssetWrapper/IsolationAssetWrapper_test.py
+++ b/Packs/CommonScripts/Scripts/IsolationAssetWrapper/IsolationAssetWrapper_test.py
@@ -19,8 +19,7 @@ def test_create_command_executers(mocker, action):
Ensure the right commands wrappers are being returned.
"""
- from IsolationAssetWrapper import demisto, create_commands, MSDE_ACTIONS, XDR_ACTIONS, \
- CROWDSTRIKE_ACTIONS
+ from IsolationAssetWrapper import CROWDSTRIKE_ACTIONS, MSDE_ACTIONS, XDR_ACTIONS, create_commands, demisto
device_ids = ['device1',
'device2',
'device3']
diff --git a/Packs/CommonScripts/Scripts/JSONFileToCSV/JSONFileToCSV.py b/Packs/CommonScripts/Scripts/JSONFileToCSV/JSONFileToCSV.py
index fb43da745556..fe305dbfddb0 100644
--- a/Packs/CommonScripts/Scripts/JSONFileToCSV/JSONFileToCSV.py
+++ b/Packs/CommonScripts/Scripts/JSONFileToCSV/JSONFileToCSV.py
@@ -1,9 +1,11 @@
+import csv
+import io
+import json
+
import demistomock as demisto
from CommonServerPython import *
+
from CommonServerUserPython import *
-import json
-import io
-import csv
def json_to_csv(data, delimiter):
@@ -30,12 +32,12 @@ def main(entry_id, out_filename, delimiter):
file_info = demisto.getFilePath(entry_id)
except Exception as e:
- return_error(f"Failed to get the file path for entry: {entry_id} the error message was {str(e)}")
+ return_error(f"Failed to get the file path for entry: {entry_id} the error message was {e!s}")
file_path = file_info.get("path")
# Open file and read data
- with open(file_path, "r") as f: # type: ignore
+ with open(file_path) as f: # type: ignore
dict_list = json.load(f)
csv_string = json_to_csv(dict_list, delimiter)
diff --git a/Packs/CommonScripts/Scripts/JSONFileToCSV/JSONFileToCSV_test.py b/Packs/CommonScripts/Scripts/JSONFileToCSV/JSONFileToCSV_test.py
index 05d7b4a65781..6d02f083c7a7 100644
--- a/Packs/CommonScripts/Scripts/JSONFileToCSV/JSONFileToCSV_test.py
+++ b/Packs/CommonScripts/Scripts/JSONFileToCSV/JSONFileToCSV_test.py
@@ -1,9 +1,8 @@
import os
-import demistomock as demisto
+import demistomock as demisto
from CommonServerPython import entryTypes
-
TEST_DATA_DIR = "test_data"
diff --git a/Packs/CommonScripts/Scripts/JSONtoCSV/JSONtoCSV.py b/Packs/CommonScripts/Scripts/JSONtoCSV/JSONtoCSV.py
index 1d0b0c262df6..7a9b737f1220 100644
--- a/Packs/CommonScripts/Scripts/JSONtoCSV/JSONtoCSV.py
+++ b/Packs/CommonScripts/Scripts/JSONtoCSV/JSONtoCSV.py
@@ -1,10 +1,10 @@
-import demistomock as demisto
-from CommonServerPython import *
-
-import io
import csv
+import io
import sys
+import demistomock as demisto
+from CommonServerPython import *
+
def main():
args = demisto.args()
diff --git a/Packs/CommonScripts/Scripts/JsonUnescape/JsonUnescape.py b/Packs/CommonScripts/Scripts/JsonUnescape/JsonUnescape.py
index 0b2729195e85..8d901c0e4fcd 100644
--- a/Packs/CommonScripts/Scripts/JsonUnescape/JsonUnescape.py
+++ b/Packs/CommonScripts/Scripts/JsonUnescape/JsonUnescape.py
@@ -1,11 +1,11 @@
-import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
import json
import traceback
-from typing import Dict, List, Union
+
+import demistomock as demisto # noqa: F401
+from CommonServerPython import * # noqa: F401
-def hook(obj: Dict) -> Dict:
+def hook(obj: dict) -> dict:
""" Hook to convert string to json if possible """
new_obj = {}
for k, v in obj.items():
@@ -16,7 +16,7 @@ def hook(obj: Dict) -> Dict:
return new_obj
-def unescape(args: Dict) -> Union[Dict, List]:
+def unescape(args: dict) -> dict | list:
""" Unescape json string """
json_str = json.dumps(args.get("value"))
return json.loads(json_str, object_hook=hook)
@@ -28,7 +28,7 @@ def main(): # noqa: F841
return_results(unescape(args))
except Exception as ex:
demisto.error(traceback.format_exc())
- return_error(f"Error: {str(ex)}")
+ return_error(f"Error: {ex!s}")
if __name__ in ("__main__", "__builtin__", "builtins"):
diff --git a/Packs/CommonScripts/Scripts/LinkIncidentsButton/LinkIncidentsButton.py b/Packs/CommonScripts/Scripts/LinkIncidentsButton/LinkIncidentsButton.py
index 3cbe6ea66bb3..2fc906142630 100644
--- a/Packs/CommonScripts/Scripts/LinkIncidentsButton/LinkIncidentsButton.py
+++ b/Packs/CommonScripts/Scripts/LinkIncidentsButton/LinkIncidentsButton.py
@@ -1,7 +1,6 @@
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-
action = demisto.getArg('action')
if action not in ['link', 'unlink']:
action = 'link'
diff --git a/Packs/CommonScripts/Scripts/ListUsedDockerImages/ListUsedDockerImages.py b/Packs/CommonScripts/Scripts/ListUsedDockerImages/ListUsedDockerImages.py
index 13383f7634cc..bac87f2e7216 100644
--- a/Packs/CommonScripts/Scripts/ListUsedDockerImages/ListUsedDockerImages.py
+++ b/Packs/CommonScripts/Scripts/ListUsedDockerImages/ListUsedDockerImages.py
@@ -1,5 +1,6 @@
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
+
"""ListUsedDockerImages Script for Cortex XSOAR (aka Demisto)
This is a script that list all the dockers images that are in ues in the integrations and automations
@@ -7,7 +8,6 @@
"""
import json
-from typing import Dict
'''REST API HTTP COMMANDS'''
POST_COMMAND = "POST"
@@ -41,7 +41,7 @@
''' HELPER FUNCTION '''
-def get_docker_from_conf(conf: Dict) -> str:
+def get_docker_from_conf(conf: dict) -> str:
"""
:type conf: ``json object``
:param conf: json represents integration configuration
@@ -60,7 +60,7 @@ def get_docker_from_conf(conf: Dict) -> str:
return docker_image
-def get_integration_conf(integration_search_json: Dict, instance_brand: str,
+def get_integration_conf(integration_search_json: dict, instance_brand: str,
ignore_deprecated: bool = False) -> Any:
""" returns the corresponding integration_configuration json object for the given instance_brand
Args:
@@ -206,7 +206,7 @@ def list_used_docker_images(export_to_context: bool = True,
active_docker_list_automation = {}
''' Examples for output: { 'demisto/python3:3.9.7.24076' : ['ListUsedDockerImage', 'VirusTotal',...]}'''
- result_dict: Dict[str, List[str]] = {}
+ result_dict: dict[str, List[str]] = {}
active_integration_instances = demisto.internalHttpRequest(POST_COMMAND, '/settings/integration/search',
'{\"size\":500}')
@@ -254,7 +254,7 @@ def main():
try:
return_results(list_used_docker_images(export_to_context, ignore_deprecated_automations))
except Exception as e:
- return_error(f'Failed to execute ListUserDockerImages Script. Error: {str(e)}')
+ return_error(f'Failed to execute ListUserDockerImages Script. Error: {e!s}')
''' ENTRY POINT '''
diff --git a/Packs/CommonScripts/Scripts/ListUsedDockerImages/ListUsedDockerImages_test.py b/Packs/CommonScripts/Scripts/ListUsedDockerImages/ListUsedDockerImages_test.py
index 89835e9b0f9a..ecdf13c3219b 100644
--- a/Packs/CommonScripts/Scripts/ListUsedDockerImages/ListUsedDockerImages_test.py
+++ b/Packs/CommonScripts/Scripts/ListUsedDockerImages/ListUsedDockerImages_test.py
@@ -252,8 +252,12 @@ def test_api_response_parsing():
"""
Tests REST API responses parsing content.
"""
- from ListUsedDockerImages import extract_dockers_from_automation_search_result, \
- extract_dockers_from_integration_search_result, merge_result, format_result_for_markdown
+ from ListUsedDockerImages import (
+ extract_dockers_from_automation_search_result,
+ extract_dockers_from_integration_search_result,
+ format_result_for_markdown,
+ merge_result,
+ )
integration_response = extract_dockers_from_integration_search_result(
INTEGRATION, False, True)
diff --git a/Packs/CommonScripts/Scripts/LoadJSON/LoadJSON.py b/Packs/CommonScripts/Scripts/LoadJSON/LoadJSON.py
index 9f2300f018aa..0bf6e580bca0 100644
--- a/Packs/CommonScripts/Scripts/LoadJSON/LoadJSON.py
+++ b/Packs/CommonScripts/Scripts/LoadJSON/LoadJSON.py
@@ -1,8 +1,8 @@
+import json
+
import demistomock as demisto
from CommonServerPython import *
-import json
-
def load_json(args):
json_str = args['input']
diff --git a/Packs/CommonScripts/Scripts/LoadJSON/LoadJSON_test.py b/Packs/CommonScripts/Scripts/LoadJSON/LoadJSON_test.py
index 637997849075..3574aca5cdf1 100644
--- a/Packs/CommonScripts/Scripts/LoadJSON/LoadJSON_test.py
+++ b/Packs/CommonScripts/Scripts/LoadJSON/LoadJSON_test.py
@@ -1,5 +1,5 @@
-from LoadJSON import load_json
import pytest
+from LoadJSON import load_json
@pytest.mark.parametrize('inputs, outputs', [
diff --git a/Packs/CommonScripts/Scripts/LoadJSONFileToContext/LoadJSONFileToContext.py b/Packs/CommonScripts/Scripts/LoadJSONFileToContext/LoadJSONFileToContext.py
index f8ea53c8f76f..61eba0875302 100644
--- a/Packs/CommonScripts/Scripts/LoadJSONFileToContext/LoadJSONFileToContext.py
+++ b/Packs/CommonScripts/Scripts/LoadJSONFileToContext/LoadJSONFileToContext.py
@@ -12,7 +12,7 @@
file_path = res.get('path')
# open the file, and try and load the JSON, error if it's invalid.
-with open(file_path, 'r') as f:
+with open(file_path) as f:
try:
data = json.load(f)
except ValueError as e:
diff --git a/Packs/CommonScripts/Scripts/LookupCSV/LookupCSV.py b/Packs/CommonScripts/Scripts/LookupCSV/LookupCSV.py
index bc23aab66e33..d076747d2e9e 100644
--- a/Packs/CommonScripts/Scripts/LookupCSV/LookupCSV.py
+++ b/Packs/CommonScripts/Scripts/LookupCSV/LookupCSV.py
@@ -2,9 +2,10 @@
Given a CSV file in the War Room by entry ID, searches based on column and value.
If the column is not present, simply parse the CSV into a list of lists or list of dicts (if header row supplied).
"""
-from CommonServerPython import *
import csv
+from CommonServerPython import *
+
def search_dicts(k, v, data):
"""
@@ -60,8 +61,7 @@ def main():
file_name = res['name']
if not file_name.lower().endswith('.csv'):
return_error(
- '"{}" is not in csv format. Please ensure the file is in correct format and has a ".csv" extension'.format(
- file_name))
+ f'"{file_name}" is not in csv format. Please ensure the file is in correct format and has a ".csv" extension')
csv_data: list = []
with open(file_path) as csv_file:
diff --git a/Packs/CommonScripts/Scripts/LookupCSV/LookupCSV_test.py b/Packs/CommonScripts/Scripts/LookupCSV/LookupCSV_test.py
index d6bab71ff8d8..7a0699c0c5c0 100644
--- a/Packs/CommonScripts/Scripts/LookupCSV/LookupCSV_test.py
+++ b/Packs/CommonScripts/Scripts/LookupCSV/LookupCSV_test.py
@@ -1,4 +1,5 @@
import json
+
import demistomock as demisto
import pytest
diff --git a/Packs/CommonScripts/Scripts/MITRENameByIDFormatter/MITRENameByIDFormatter.py b/Packs/CommonScripts/Scripts/MITRENameByIDFormatter/MITRENameByIDFormatter.py
index 7542205dd2ae..c3d8ea0648ab 100644
--- a/Packs/CommonScripts/Scripts/MITRENameByIDFormatter/MITRENameByIDFormatter.py
+++ b/Packs/CommonScripts/Scripts/MITRENameByIDFormatter/MITRENameByIDFormatter.py
@@ -45,7 +45,7 @@ def get_mitre_technique_name(mitre_id: str) -> dict[str, str]:
return technique_names
except Exception as e:
- demisto.debug(f"Error searching for Attack Pattern indicator: {str(e)}")
+ demisto.debug(f"Error searching for Attack Pattern indicator: {e!s}")
return {}
diff --git a/Packs/CommonScripts/Scripts/MITRENameByIDFormatter/MITRENameByIDFormatter_test.py b/Packs/CommonScripts/Scripts/MITRENameByIDFormatter/MITRENameByIDFormatter_test.py
index 563c64e7ca9a..287cecd58964 100644
--- a/Packs/CommonScripts/Scripts/MITRENameByIDFormatter/MITRENameByIDFormatter_test.py
+++ b/Packs/CommonScripts/Scripts/MITRENameByIDFormatter/MITRENameByIDFormatter_test.py
@@ -1,11 +1,10 @@
from unittest.mock import patch
-import pytest
-import MITRENameByIDFormatter
-from MITRENameByIDFormatter import main
-
import demistomock as demisto # noqa: F401
+import MITRENameByIDFormatter
+import pytest
from CommonServerPython import * # noqa: F401
+from MITRENameByIDFormatter import main
@pytest.mark.parametrize('input, expected_response', [
diff --git a/Packs/CommonScripts/Scripts/MarkAsNoteByTag/MarkAsNoteByTag_test.py b/Packs/CommonScripts/Scripts/MarkAsNoteByTag/MarkAsNoteByTag_test.py
index c60e96efc345..8184a557d953 100644
--- a/Packs/CommonScripts/Scripts/MarkAsNoteByTag/MarkAsNoteByTag_test.py
+++ b/Packs/CommonScripts/Scripts/MarkAsNoteByTag/MarkAsNoteByTag_test.py
@@ -1,6 +1,6 @@
import demistomock as demisto # noqa: F401
-from MarkAsNoteByTag import mark_as_note
import MarkAsNoteByTag
+from MarkAsNoteByTag import mark_as_note
ENTRIES = [
{
diff --git a/Packs/CommonScripts/Scripts/MatchRegexV2/MatchRegexV2.py b/Packs/CommonScripts/Scripts/MatchRegexV2/MatchRegexV2.py
index 9224f6bf4cb2..e9aa291ab38f 100644
--- a/Packs/CommonScripts/Scripts/MatchRegexV2/MatchRegexV2.py
+++ b/Packs/CommonScripts/Scripts/MatchRegexV2/MatchRegexV2.py
@@ -1,8 +1,7 @@
-import demistomock as demisto
-from CommonServerPython import *
-
import re
+import demistomock as demisto
+from CommonServerPython import *
LETTER_TO_REGEX_FLAGS = {
'i': re.IGNORECASE,
diff --git a/Packs/CommonScripts/Scripts/MatchRegexV2/MatchRegexV2_test.py b/Packs/CommonScripts/Scripts/MatchRegexV2/MatchRegexV2_test.py
index 0fef719fe529..f27b69ba4355 100644
--- a/Packs/CommonScripts/Scripts/MatchRegexV2/MatchRegexV2_test.py
+++ b/Packs/CommonScripts/Scripts/MatchRegexV2/MatchRegexV2_test.py
@@ -1,29 +1,29 @@
import re
-import pytest
-from MatchRegexV2 import parse_regex_flags, main
+import pytest
+from MatchRegexV2 import main, parse_regex_flags
class TestParseRegexFlags:
@staticmethod
def test__sanity():
flags, multiple_matches = parse_regex_flags()
- assert re.I in flags
- assert re.M in flags
+ assert re.IGNORECASE in flags
+ assert re.MULTILINE in flags
assert multiple_matches
@staticmethod
def test__custom_flags():
flags, multiple_matches = parse_regex_flags('gi')
- assert re.I in flags
- assert re.M not in flags
+ assert re.IGNORECASE in flags
+ assert re.MULTILINE not in flags
assert multiple_matches
@staticmethod
def test__custom_flags_without_multiple_match():
flags, multiple_matches = parse_regex_flags('i')
- assert re.I in flags
- assert re.M not in flags
+ assert re.IGNORECASE in flags
+ assert re.MULTILINE not in flags
assert not multiple_matches
@staticmethod
diff --git a/Packs/CommonScripts/Scripts/NumberOfPhishingAttemptPerUser/NumberOfPhishingAttemptPerUser.py b/Packs/CommonScripts/Scripts/NumberOfPhishingAttemptPerUser/NumberOfPhishingAttemptPerUser.py
index 9aba07903344..4c88dbef74d3 100644
--- a/Packs/CommonScripts/Scripts/NumberOfPhishingAttemptPerUser/NumberOfPhishingAttemptPerUser.py
+++ b/Packs/CommonScripts/Scripts/NumberOfPhishingAttemptPerUser/NumberOfPhishingAttemptPerUser.py
@@ -1,4 +1,3 @@
-from typing import Tuple
from CommonServerPython import *
@@ -16,7 +15,7 @@ def get_default_from_date(date_range: str) -> str:
return str_from_date
-def get_relevant_incidents(email_to, email_from, from_date) -> Tuple[int, int]:
+def get_relevant_incidents(email_to, email_from, from_date) -> tuple[int, int]:
"""
Gets a email to and from addresses, and a date from string.
:param email_to: string
@@ -68,7 +67,7 @@ def create_widget_entry(email_to, email_from, email_to_total, email_from_total)
],
"groups": None,
"name": str(email_to),
- "label": f"To: {str(email_to)}",
+ "label": f"To: {email_to!s}",
"color": "rgb(255, 23, 68)"
},
{
@@ -77,7 +76,7 @@ def create_widget_entry(email_to, email_from, email_to_total, email_from_total)
],
"groups": None,
"name": str(email_from),
- "label": f"From: {str(email_from)}",
+ "label": f"From: {email_from!s}",
"color": "rgb(255, 144, 0)"
}
],
diff --git a/Packs/CommonScripts/Scripts/NumberOfPhishingAttemptPerUser/NumberOfPhishingAttemptPerUser_test.py b/Packs/CommonScripts/Scripts/NumberOfPhishingAttemptPerUser/NumberOfPhishingAttemptPerUser_test.py
index 265bac15b56b..a5ab4eedeeb8 100644
--- a/Packs/CommonScripts/Scripts/NumberOfPhishingAttemptPerUser/NumberOfPhishingAttemptPerUser_test.py
+++ b/Packs/CommonScripts/Scripts/NumberOfPhishingAttemptPerUser/NumberOfPhishingAttemptPerUser_test.py
@@ -1,6 +1,5 @@
-from NumberOfPhishingAttemptPerUser import get_relevant_incidents
-
from CommonServerPython import *
+from NumberOfPhishingAttemptPerUser import get_relevant_incidents
incident = [
{'ModuleName': 'InnerServicesModule', 'Brand': 'Builtin', 'Category': 'Builtin', 'ID': '', 'Version': 0, 'Type': 1,
diff --git a/Packs/CommonScripts/Scripts/OnionURLReputation/OnionURLReputation_test.py b/Packs/CommonScripts/Scripts/OnionURLReputation/OnionURLReputation_test.py
index ac12aaf38942..a08f3e5328d7 100644
--- a/Packs/CommonScripts/Scripts/OnionURLReputation/OnionURLReputation_test.py
+++ b/Packs/CommonScripts/Scripts/OnionURLReputation/OnionURLReputation_test.py
@@ -1,5 +1,5 @@
-from OnionURLReputation import main
import demistomock as demisto
+from OnionURLReputation import main
# the onion urls used in the unittests are not a valid ones so they would not be caught as an Onion URL in XSOAR.
ARGS = {
diff --git a/Packs/CommonScripts/Scripts/PDFUnlocker/PDFUnlocker.py b/Packs/CommonScripts/Scripts/PDFUnlocker/PDFUnlocker.py
index 75da152f44da..2b22ce6fb70a 100644
--- a/Packs/CommonScripts/Scripts/PDFUnlocker/PDFUnlocker.py
+++ b/Packs/CommonScripts/Scripts/PDFUnlocker/PDFUnlocker.py
@@ -1,6 +1,6 @@
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-from pikepdf import Pdf, PasswordError
+from pikepdf import PasswordError, Pdf
def unlock_pdf(args: dict):
diff --git a/Packs/CommonScripts/Scripts/ParseCSV/ParseCSV.py b/Packs/CommonScripts/Scripts/ParseCSV/ParseCSV.py
index 44ed5dbd78b7..d54e5d3af6db 100644
--- a/Packs/CommonScripts/Scripts/ParseCSV/ParseCSV.py
+++ b/Packs/CommonScripts/Scripts/ParseCSV/ParseCSV.py
@@ -148,8 +148,7 @@ def main():
file_name = res['name']
if not file_name.lower().endswith('.csv'):
return_error(
- '"{}" is not in csv format. Please ensure the file is in correct format and has a ".csv" extension'.format(
- file_name))
+ f'"{file_name}" is not in csv format. Please ensure the file is in correct format and has a ".csv" extension')
if parse_all:
all_csv = []
diff --git a/Packs/CommonScripts/Scripts/ParseCSV/ParseCSV_test.py b/Packs/CommonScripts/Scripts/ParseCSV/ParseCSV_test.py
index b7d63a324c21..a99f6ac14e73 100644
--- a/Packs/CommonScripts/Scripts/ParseCSV/ParseCSV_test.py
+++ b/Packs/CommonScripts/Scripts/ParseCSV/ParseCSV_test.py
@@ -1,6 +1,7 @@
import json
-import pytest
+
import demistomock as demisto
+import pytest
class TestParseCSV:
diff --git a/Packs/CommonScripts/Scripts/ParseEmailFilesV2/ParseEmailFilesV2_test.py b/Packs/CommonScripts/Scripts/ParseEmailFilesV2/ParseEmailFilesV2_test.py
index a0acedc98ab1..5c9c53775304 100644
--- a/Packs/CommonScripts/Scripts/ParseEmailFilesV2/ParseEmailFilesV2_test.py
+++ b/Packs/CommonScripts/Scripts/ParseEmailFilesV2/ParseEmailFilesV2_test.py
@@ -1,8 +1,7 @@
-import pytest
-
import demistomock as demisto
+import pytest
from CommonServerPython import *
-from ParseEmailFilesV2 import main, data_to_md, parse_nesting_level
+from ParseEmailFilesV2 import data_to_md, main, parse_nesting_level
def exec_command_for_file(
@@ -381,14 +380,14 @@ def test_md_output_empty_body_text():
'Text': None
}
expected = '### Results:\n' \
- u'* From:\temail2@paloaltonetworks.com\n' \
- u'* To:\temail1@paloaltonetworks.com\n' \
- u'* CC:\t\n' \
- u'* BCC:\t\n' \
- u'* Subject:\t\n' \
- u'* Attachments:\t\n\n\n' \
- u'### HeadersMap\n' \
- u'**No entries.**\n'
+ '* From:\temail2@paloaltonetworks.com\n' \
+ '* To:\temail1@paloaltonetworks.com\n' \
+ '* CC:\t\n' \
+ '* BCC:\t\n' \
+ '* Subject:\t\n' \
+ '* Attachments:\t\n\n\n' \
+ '### HeadersMap\n' \
+ '**No entries.**\n'
md = data_to_md(email_data)
assert expected == md
@@ -398,14 +397,14 @@ def test_md_output_empty_body_text():
'From': 'email2@paloaltonetworks.com',
}
expected = '### Results:\n' \
- u'* From:\temail2@paloaltonetworks.com\n' \
- u'* To:\temail1@paloaltonetworks.com\n' \
- u'* CC:\t\n' \
- u'* BCC:\t\n' \
- u'* Subject:\t\n' \
- u'* Attachments:\t\n\n\n' \
- u'### HeadersMap\n' \
- u'**No entries.**\n'
+ '* From:\temail2@paloaltonetworks.com\n' \
+ '* To:\temail1@paloaltonetworks.com\n' \
+ '* CC:\t\n' \
+ '* BCC:\t\n' \
+ '* Subject:\t\n' \
+ '* Attachments:\t\n\n\n' \
+ '### HeadersMap\n' \
+ '**No entries.**\n'
md = data_to_md(email_data)
assert expected == md
@@ -428,15 +427,15 @@ def test_md_output_with_body_text():
'Text': ''
}
expected = '### Results:\n' \
- u'* From:\temail2@paloaltonetworks.com\n' \
- u'* To:\temail1@paloaltonetworks.com\n' \
- u'* CC:\t\n' \
- u'* BCC:\t\n' \
- u'* Subject:\t\n' \
- u'* Body/Text:\t[email text]\n' \
- u'* Attachments:\t\n\n\n' \
- u'### HeadersMap\n' \
- u'**No entries.**\n'
+ '* From:\temail2@paloaltonetworks.com\n' \
+ '* To:\temail1@paloaltonetworks.com\n' \
+ '* CC:\t\n' \
+ '* BCC:\t\n' \
+ '* Subject:\t\n' \
+ '* Body/Text:\t[email text]\n' \
+ '* Attachments:\t\n\n\n' \
+ '### HeadersMap\n' \
+ '**No entries.**\n'
md = data_to_md(email_data)
assert expected == md
diff --git a/Packs/CommonScripts/Scripts/ParseExcel/ParseExcel_test.py b/Packs/CommonScripts/Scripts/ParseExcel/ParseExcel_test.py
index 817f1fcfeb4f..ad6f70d5695d 100644
--- a/Packs/CommonScripts/Scripts/ParseExcel/ParseExcel_test.py
+++ b/Packs/CommonScripts/Scripts/ParseExcel/ParseExcel_test.py
@@ -1,4 +1,5 @@
import json
+
import demistomock as demisto
diff --git a/Packs/CommonScripts/Scripts/ParseHTMLIndicators/ParseHTMLIndicators.py b/Packs/CommonScripts/Scripts/ParseHTMLIndicators/ParseHTMLIndicators.py
index 9c4992ee18bc..5d913790640d 100644
--- a/Packs/CommonScripts/Scripts/ParseHTMLIndicators/ParseHTMLIndicators.py
+++ b/Packs/CommonScripts/Scripts/ParseHTMLIndicators/ParseHTMLIndicators.py
@@ -1,9 +1,9 @@
-import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
import re
+import demistomock as demisto # noqa: F401
import requests
from bs4 import BeautifulSoup
+from CommonServerPython import * # noqa: F401
from tld import get_tld
diff --git a/Packs/CommonScripts/Scripts/ParseWordDoc/ParseWordDoc.py b/Packs/CommonScripts/Scripts/ParseWordDoc/ParseWordDoc.py
index cb5307c5b270..aad8fb4f79ed 100644
--- a/Packs/CommonScripts/Scripts/ParseWordDoc/ParseWordDoc.py
+++ b/Packs/CommonScripts/Scripts/ParseWordDoc/ParseWordDoc.py
@@ -1,10 +1,11 @@
+import zipfile
+from xml.etree.ElementTree import XML
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
from docx import Document
-from docx.opc.exceptions import PackageNotFoundError
from docx.opc.constants import RELATIONSHIP_TYPE as RT
-import zipfile
-from xml.etree.ElementTree import XML
+from docx.opc.exceptions import PackageNotFoundError
def extract_urls_xml(file_path):
diff --git a/Packs/CommonScripts/Scripts/ParseYAML/ParseYAML.py b/Packs/CommonScripts/Scripts/ParseYAML/ParseYAML.py
index 311533793595..64df60e1299c 100644
--- a/Packs/CommonScripts/Scripts/ParseYAML/ParseYAML.py
+++ b/Packs/CommonScripts/Scripts/ParseYAML/ParseYAML.py
@@ -54,7 +54,7 @@ def main():
return_results(load_and_parse_yaml_command(demisto.args()))
except Exception as e:
demisto.error(traceback.format_exc())
- return_error(f"Failed to execute ParseYAML script. Error: {str(e)}")
+ return_error(f"Failed to execute ParseYAML script. Error: {e!s}")
if __name__ in ("__main__", "__builtin__", "builtins"):
diff --git a/Packs/CommonScripts/Scripts/PcapHTTPExtractor/PcapHTTPExtractor.py b/Packs/CommonScripts/Scripts/PcapHTTPExtractor/PcapHTTPExtractor.py
index b258616331af..a6d2d8e3a192 100644
--- a/Packs/CommonScripts/Scripts/PcapHTTPExtractor/PcapHTTPExtractor.py
+++ b/Packs/CommonScripts/Scripts/PcapHTTPExtractor/PcapHTTPExtractor.py
@@ -1,13 +1,15 @@
-from CommonServerPython import *
-from CommonServerUserPython import *
-import zlib
-import pyshark
-from datetime import datetime
import re
import sys
import traceback
+import zlib
+from datetime import datetime
from io import StringIO
+import pyshark
+from CommonServerPython import *
+
+from CommonServerUserPython import *
+
serr = sys.stderr
sys.stderr = StringIO()
@@ -415,7 +417,7 @@ def main():
"EntryContext": {"PcapHTTPFlows": context_output}})
except Exception as e:
demisto.error(traceback.format_exc()) # print the traceback
- return_error(f'Failed to execute PcapHTTPExtractor Script. Error: {str(e)}')
+ return_error(f'Failed to execute PcapHTTPExtractor Script. Error: {e!s}')
finally:
sys.stderr = serr
diff --git a/Packs/CommonScripts/Scripts/Ping/Ping.py b/Packs/CommonScripts/Scripts/Ping/Ping.py
index 5d2d39ea7e96..21062b757c07 100644
--- a/Packs/CommonScripts/Scripts/Ping/Ping.py
+++ b/Packs/CommonScripts/Scripts/Ping/Ping.py
@@ -1,7 +1,8 @@
+import re
+import subprocess
+
import demistomock as demisto
from CommonServerPython import *
-import subprocess
-import re
def main():
diff --git a/Packs/CommonScripts/Scripts/Ping/Ping_test.py b/Packs/CommonScripts/Scripts/Ping/Ping_test.py
index 36c13403e494..a07a1faf3e7d 100644
--- a/Packs/CommonScripts/Scripts/Ping/Ping_test.py
+++ b/Packs/CommonScripts/Scripts/Ping/Ping_test.py
@@ -1,9 +1,10 @@
+import os
+import re
+
import demistomock as demisto
+import pytest
from CommonServerPython import entryTypes
from Ping import main
-import re
-import pytest
-import os
# To run the tests in an editor see: test_data/ping
diff --git a/Packs/CommonScripts/Scripts/PopulateCriticalAssets/PopulateCriticalAssets.py b/Packs/CommonScripts/Scripts/PopulateCriticalAssets/PopulateCriticalAssets.py
index d19b7c7b4c02..9cea4c3e15fe 100644
--- a/Packs/CommonScripts/Scripts/PopulateCriticalAssets/PopulateCriticalAssets.py
+++ b/Packs/CommonScripts/Scripts/PopulateCriticalAssets/PopulateCriticalAssets.py
@@ -1,5 +1,6 @@
import demistomock as demisto
from CommonServerPython import *
+
from CommonServerUserPython import *
field_cli_name = "criticalassets"
diff --git a/Packs/CommonScripts/Scripts/PortListenCheck/PortListenCheck.py b/Packs/CommonScripts/Scripts/PortListenCheck/PortListenCheck.py
index 6a4b71de9d36..bd5f675fd1b1 100644
--- a/Packs/CommonScripts/Scripts/PortListenCheck/PortListenCheck.py
+++ b/Packs/CommonScripts/Scripts/PortListenCheck/PortListenCheck.py
@@ -1,6 +1,7 @@
+import socket
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-import socket
def port_listen_check(port: int, host: str) -> CommandResults:
diff --git a/Packs/CommonScripts/Scripts/PositiveDetectionsVSDetectionEngines/PositiveDetectionsVSDetectionEngines.py b/Packs/CommonScripts/Scripts/PositiveDetectionsVSDetectionEngines/PositiveDetectionsVSDetectionEngines.py
index 4f631a9ad651..f5755a55ac15 100644
--- a/Packs/CommonScripts/Scripts/PositiveDetectionsVSDetectionEngines/PositiveDetectionsVSDetectionEngines.py
+++ b/Packs/CommonScripts/Scripts/PositiveDetectionsVSDetectionEngines/PositiveDetectionsVSDetectionEngines.py
@@ -1,5 +1,6 @@
import demistomock as demisto
from CommonServerPython import *
+
from CommonServerUserPython import *
diff --git a/Packs/CommonScripts/Scripts/PositiveDetectionsVSDetectionEngines/PositiveDetectionsVSDetectionEngines_test.py b/Packs/CommonScripts/Scripts/PositiveDetectionsVSDetectionEngines/PositiveDetectionsVSDetectionEngines_test.py
index 31d39a076564..cfe48ecd8263 100644
--- a/Packs/CommonScripts/Scripts/PositiveDetectionsVSDetectionEngines/PositiveDetectionsVSDetectionEngines_test.py
+++ b/Packs/CommonScripts/Scripts/PositiveDetectionsVSDetectionEngines/PositiveDetectionsVSDetectionEngines_test.py
@@ -1,4 +1,5 @@
from typing import Any
+
import pytest
from PositiveDetectionsVSDetectionEngines import extract_engines_data_from_indicator
diff --git a/Packs/CommonScripts/Scripts/PreProcessImage/PreProcessImage.py b/Packs/CommonScripts/Scripts/PreProcessImage/PreProcessImage.py
index 5989488329c1..5eac3bceaccb 100644
--- a/Packs/CommonScripts/Scripts/PreProcessImage/PreProcessImage.py
+++ b/Packs/CommonScripts/Scripts/PreProcessImage/PreProcessImage.py
@@ -1,9 +1,10 @@
+import io
+
+import cv2 # noqa: F401
import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
-import cv2 # noqa: F401
import numpy as np
+from CommonServerPython import * # noqa: F401
from PIL import Image
-import io
def sharpened(image: np.ndarray) -> np.ndarray:
@@ -94,7 +95,7 @@ def main():
try:
return_results(action_wrap(demisto.args()))
except Exception as e:
- return_error(f'Failed to pre-process an image file. Problem: {str(e)}')
+ return_error(f'Failed to pre-process an image file. Problem: {e!s}')
if __name__ in ["__builtin__", "builtins", '__main__']:
diff --git a/Packs/CommonScripts/Scripts/PreProcessImage/PreProcessImage_test.py b/Packs/CommonScripts/Scripts/PreProcessImage/PreProcessImage_test.py
index cab29da7ca8f..a540c610ff08 100644
--- a/Packs/CommonScripts/Scripts/PreProcessImage/PreProcessImage_test.py
+++ b/Packs/CommonScripts/Scripts/PreProcessImage/PreProcessImage_test.py
@@ -1,9 +1,9 @@
-from CommonServerPython import *
-import pytest
-from PIL import Image
import io
-import cv2
+import cv2
+import pytest
+from CommonServerPython import *
+from PIL import Image
IMAGE_NAME_JPG = 'test_picture_jpg.jpg'
IMAGE_PATH_JPG = 'test_data/test_picture_jpg.jpg'
@@ -59,9 +59,10 @@ def test_get_file_details(mocker, entry_id, path, name, width, height, format_im
Then:
- Validate file details returned as expected
"""
- from PreProcessImage import get_file_details
from unittest import mock
+ from PreProcessImage import get_file_details
+
def mock_file(_id):
return {
'path': path,
@@ -106,8 +107,8 @@ def test_grayscale(mocker, image_path, image_name, format_img):
Then:
- Ensure the function successfully converts the image to grayscale.
"""
- from PreProcessImage import action_wrap
import PreProcessImage
+ from PreProcessImage import action_wrap
# Arrange
args = {
'action': 'grayscale',
@@ -153,8 +154,9 @@ def test_sharpened(mocker, image_path, image_name, format_img):
Then:
- Ensure the function successfully sharpens the image.
"""
- import PreProcessImage
import io
+
+ import PreProcessImage
# Arrange
args = {
'action': 'sharpened',
@@ -202,8 +204,9 @@ def test_original(mocker, image_path, image_name, format_img):
Then:
- Ensure the function successfully returns the original image (and not preforms sharpening or grayscale).
"""
- import PreProcessImage
from unittest import mock
+
+ import PreProcessImage
# Arrange
args = {
'action': 'original',
diff --git a/Packs/CommonScripts/Scripts/PrettyPrint/PrettyPrint.py b/Packs/CommonScripts/Scripts/PrettyPrint/PrettyPrint.py
index f3e3dc96fabc..e661b36dce4f 100644
--- a/Packs/CommonScripts/Scripts/PrettyPrint/PrettyPrint.py
+++ b/Packs/CommonScripts/Scripts/PrettyPrint/PrettyPrint.py
@@ -1,6 +1,7 @@
-import demistomock as demisto
from pprint import pformat
+import demistomock as demisto
+
def main():
value = demisto.args()['value']
diff --git a/Packs/CommonScripts/Scripts/PrintContext/PrintContext_test.py b/Packs/CommonScripts/Scripts/PrintContext/PrintContext_test.py
index ef40087ed15d..90a16fa98a55 100644
--- a/Packs/CommonScripts/Scripts/PrintContext/PrintContext_test.py
+++ b/Packs/CommonScripts/Scripts/PrintContext/PrintContext_test.py
@@ -1,6 +1,5 @@
-import pytest
-
import demistomock as demisto # noqa: F401
+import pytest
from CommonServerPython import * # noqa: F401
from PrintContext import print_context
diff --git a/Packs/CommonScripts/Scripts/PrintToAlert/PrintToAlert.py b/Packs/CommonScripts/Scripts/PrintToAlert/PrintToAlert.py
index 77ae224561a9..08873a893e13 100644
--- a/Packs/CommonScripts/Scripts/PrintToAlert/PrintToAlert.py
+++ b/Packs/CommonScripts/Scripts/PrintToAlert/PrintToAlert.py
@@ -35,7 +35,7 @@ def main(): # pragma: no cover
alert_id=alert_id,
)
except Exception as ex:
- return_error(f"Failed to execute PrintToAlert. Error: {str(ex)}")
+ return_error(f"Failed to execute PrintToAlert. Error: {ex!s}")
if __name__ in ("__main__", "__builtin__", "builtins"):
diff --git a/Packs/CommonScripts/Scripts/PrintToAlert/PrintToAlert_test.py b/Packs/CommonScripts/Scripts/PrintToAlert/PrintToAlert_test.py
index 275e4ff12e18..0ba0b06980b8 100644
--- a/Packs/CommonScripts/Scripts/PrintToAlert/PrintToAlert_test.py
+++ b/Packs/CommonScripts/Scripts/PrintToAlert/PrintToAlert_test.py
@@ -1,7 +1,7 @@
-import pytest
-from pytest_mock import MockerFixture
import demistomock as demisto
+import pytest
from CommonServerPython import EntryType
+from pytest_mock import MockerFixture
def test_print_to_alert(mocker: MockerFixture):
diff --git a/Packs/CommonScripts/Scripts/PrintToIncident/PrintToIncident.py b/Packs/CommonScripts/Scripts/PrintToIncident/PrintToIncident.py
index 1199462f7e8d..df04f221596a 100644
--- a/Packs/CommonScripts/Scripts/PrintToIncident/PrintToIncident.py
+++ b/Packs/CommonScripts/Scripts/PrintToIncident/PrintToIncident.py
@@ -35,7 +35,7 @@ def main(): # pragma: no cover
incident_id=incident_id,
)
except Exception as ex:
- return_error(f"Failed to execute PrintToIncident. Error: {str(ex)}")
+ return_error(f"Failed to execute PrintToIncident. Error: {ex!s}")
if __name__ in ("__main__", "__builtin__", "builtins"):
diff --git a/Packs/CommonScripts/Scripts/PrintToIncident/PrintToIncident_test.py b/Packs/CommonScripts/Scripts/PrintToIncident/PrintToIncident_test.py
index 4645325be2d8..2d991f99a675 100644
--- a/Packs/CommonScripts/Scripts/PrintToIncident/PrintToIncident_test.py
+++ b/Packs/CommonScripts/Scripts/PrintToIncident/PrintToIncident_test.py
@@ -1,7 +1,7 @@
-import pytest
-from pytest_mock import MockerFixture
import demistomock as demisto
+import pytest
from CommonServerPython import EntryType
+from pytest_mock import MockerFixture
def test_print_to_incident(mocker: MockerFixture):
diff --git a/Packs/CommonScripts/Scripts/PrintToParentIncident/PrintToParentIncident.py b/Packs/CommonScripts/Scripts/PrintToParentIncident/PrintToParentIncident.py
index 58f2f700cad9..f5cbcfb6aa31 100644
--- a/Packs/CommonScripts/Scripts/PrintToParentIncident/PrintToParentIncident.py
+++ b/Packs/CommonScripts/Scripts/PrintToParentIncident/PrintToParentIncident.py
@@ -56,7 +56,7 @@ def main(): # pragma: no cover
parent_incident_id=parent_incident_id,
)
except Exception as ex:
- return_error(f"Failed to execute PrintToParentIncident. Error: {str(ex)}")
+ return_error(f"Failed to execute PrintToParentIncident. Error: {ex!s}")
if __name__ in ("__main__", "__builtin__", "builtins"):
diff --git a/Packs/CommonScripts/Scripts/PrintToParentIncident/PrintToParentIncident_test.py b/Packs/CommonScripts/Scripts/PrintToParentIncident/PrintToParentIncident_test.py
index 73fa22ba5d98..87dce2bc7cde 100644
--- a/Packs/CommonScripts/Scripts/PrintToParentIncident/PrintToParentIncident_test.py
+++ b/Packs/CommonScripts/Scripts/PrintToParentIncident/PrintToParentIncident_test.py
@@ -1,7 +1,7 @@
+import demistomock as demisto
import pytest
+from CommonServerPython import DemistoException, EntryType
from pytest_mock import MockerFixture
-import demistomock as demisto
-from CommonServerPython import EntryType, DemistoException
def test_print_to_parent_incident(mocker: MockerFixture):
diff --git a/Packs/CommonScripts/Scripts/ProvidesCommand/ProvidesCommand.py b/Packs/CommonScripts/Scripts/ProvidesCommand/ProvidesCommand.py
index 93f351db7330..00b9dacac6de 100644
--- a/Packs/CommonScripts/Scripts/ProvidesCommand/ProvidesCommand.py
+++ b/Packs/CommonScripts/Scripts/ProvidesCommand/ProvidesCommand.py
@@ -1,6 +1,7 @@
+import sys
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-import sys
def main():
diff --git a/Packs/CommonScripts/Scripts/ProvidesCommand/ProvidesCommand_test.py b/Packs/CommonScripts/Scripts/ProvidesCommand/ProvidesCommand_test.py
index fd4f71845f2c..0f63dadd0541 100644
--- a/Packs/CommonScripts/Scripts/ProvidesCommand/ProvidesCommand_test.py
+++ b/Packs/CommonScripts/Scripts/ProvidesCommand/ProvidesCommand_test.py
@@ -1,6 +1,7 @@
-import demistomock as demisto
import json
+import demistomock as demisto
+
def executeCommand(name, args=None):
if name == 'core-api-get' and args and 'uri' in args and args['uri'] == "/settings/integration-commands":
diff --git a/Packs/CommonScripts/Scripts/ReadFile/ReadFile.py b/Packs/CommonScripts/Scripts/ReadFile/ReadFile.py
index 0307d317417e..61d3177af970 100644
--- a/Packs/CommonScripts/Scripts/ReadFile/ReadFile.py
+++ b/Packs/CommonScripts/Scripts/ReadFile/ReadFile.py
@@ -1,7 +1,9 @@
-import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
import base64
import os
+
+import demistomock as demisto # noqa: F401
+from CommonServerPython import * # noqa: F401
+
from CommonServerUserPython import *
diff --git a/Packs/CommonScripts/Scripts/ReadPDFFileV2/ReadPDFFileV2.py b/Packs/CommonScripts/Scripts/ReadPDFFileV2/ReadPDFFileV2.py
index 1fe5b8780aa5..4d013dc1e43b 100644
--- a/Packs/CommonScripts/Scripts/ReadPDFFileV2/ReadPDFFileV2.py
+++ b/Packs/CommonScripts/Scripts/ReadPDFFileV2/ReadPDFFileV2.py
@@ -1,18 +1,18 @@
-import demistomock as demisto
-from CommonServerPython import *
-
-import PyPDF2
-import subprocess
+import contextlib
import glob
+import html
+import io
+import json
import os
-import stat
import re
import shutil
-import json
-from pikepdf import Pdf, PasswordError
-import contextlib
-import io
-import html
+import stat
+import subprocess
+
+import demistomock as demisto
+import PyPDF2
+from CommonServerPython import *
+from pikepdf import PasswordError, Pdf
URL_EXTRACTION_REGEX = (
r"(?:(?:https?|ftp|hxxps?):\/\/|www\[?\.\]?|ftp\[?\.\]?)(?:[-\w\d]+\[?\.\]?)+"
@@ -264,7 +264,7 @@ def build_readpdf_entry_object(entry_id: str, metadata: dict, text: str, urls: l
md += "\n### URLs\n"
md += "* " if urls else ""
- md += "\n* ".join([f'{str(k["Data"])}' for k in urls])
+ md += "\n* ".join([f'{k["Data"]!s}' for k in urls])
md += "\n### Text"
md += f"\n{text}"
@@ -679,7 +679,7 @@ def main(): # pragma: no cover
except ShellException as e:
file_name = demisto.getFilePath(entry_id).get('name')
mark_suspicious(
- suspicious_reason=f'The script {INTEGRATION_NAME} failed due to an error\n{str(e)}',
+ suspicious_reason=f'The script {INTEGRATION_NAME} failed due to an error\n{e!s}',
entry_id=entry_id,
path=path,
file_name=file_name,
diff --git a/Packs/CommonScripts/Scripts/ReadPDFFileV2/ReadPDFFileV2_test.py b/Packs/CommonScripts/Scripts/ReadPDFFileV2/ReadPDFFileV2_test.py
index e1b00dd9ed62..a972a8e62783 100644
--- a/Packs/CommonScripts/Scripts/ReadPDFFileV2/ReadPDFFileV2_test.py
+++ b/Packs/CommonScripts/Scripts/ReadPDFFileV2/ReadPDFFileV2_test.py
@@ -1,8 +1,8 @@
-from pytest_mock import MockerFixture
-import demistomock as demisto
import os
+import demistomock as demisto
import pytest
+from pytest_mock import MockerFixture
from ReadPDFFileV2 import PdfInvalidCredentialsException, PdfPermissionsException
CWD = os.getcwd() if os.getcwd().endswith('test_data') else f'{os.getcwd()}/test_data'
@@ -279,7 +279,7 @@ def test_get_pdf_text_without_encrypted(tmp_path):
def test_get_pdf_htmls_content_with_encrypted(mocker, tmp_path):
mocker.patch.object(demisto, 'args', return_value={'userPassword': '1234'})
- from ReadPDFFileV2 import get_pdf_htmls_content, get_images_paths_in_path, handling_pdf_credentials
+ from ReadPDFFileV2 import get_images_paths_in_path, get_pdf_htmls_content, handling_pdf_credentials
file_path = f'{CWD}/encrypted.pdf'
dec_file_path = f'{CWD}/decrypted.pdf'
dec_file_path = handling_pdf_credentials(cpy_file_path=file_path, user_password='1234',
@@ -297,7 +297,7 @@ def test_get_pdf_htmls_content_with_encrypted(mocker, tmp_path):
def test_get_pdf_htmls_content_without_encrypted(tmp_path):
- from ReadPDFFileV2 import get_pdf_htmls_content, get_images_paths_in_path
+ from ReadPDFFileV2 import get_images_paths_in_path, get_pdf_htmls_content
try:
get_pdf_htmls_content(f'{CWD}/encrypted.pdf', tmp_path)
raise Exception("Incorrect password exception should've been thrown")
@@ -316,7 +316,7 @@ def test_get_urls_from_binary_file():
def test_build_readpdf_entry_object_empty_extract(mocker):
- from ReadPDFFileV2 import build_readpdf_entry_object, DEFAULT_NUM_IMAGES
+ from ReadPDFFileV2 import DEFAULT_NUM_IMAGES, build_readpdf_entry_object
mocker.patch.object(demisto, 'executeCommand', return_value=[{'Contents': ''}])
res = build_readpdf_entry_object('test', {}, '', [], [], [], DEFAULT_NUM_IMAGES)
assert res[0]['HumanReadable'] == '### Metadata\n\n### URLs\n\n### Text\n'
diff --git a/Packs/CommonScripts/Scripts/ReadQRCode/ReadQRCode_test.py b/Packs/CommonScripts/Scripts/ReadQRCode/ReadQRCode_test.py
index b1bde1235612..3b13eba4ac3d 100644
--- a/Packs/CommonScripts/Scripts/ReadQRCode/ReadQRCode_test.py
+++ b/Packs/CommonScripts/Scripts/ReadQRCode/ReadQRCode_test.py
@@ -1,5 +1,5 @@
-import pytest
import demistomock as demisto
+import pytest
from CommonServerPython import *
from pytest_mock import MockerFixture
diff --git a/Packs/CommonScripts/Scripts/RemoveKeyFromList/RemoveKeyFromList.py b/Packs/CommonScripts/Scripts/RemoveKeyFromList/RemoveKeyFromList.py
index dee54e3d3e0e..93ffe57be258 100644
--- a/Packs/CommonScripts/Scripts/RemoveKeyFromList/RemoveKeyFromList.py
+++ b/Packs/CommonScripts/Scripts/RemoveKeyFromList/RemoveKeyFromList.py
@@ -1,5 +1,6 @@
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
+
"""RemoveKeyFromList
Removes a Key from a JSON-backed List
"""
@@ -68,7 +69,7 @@ def main():
return_results(remove_key_from_list_command(demisto.args()))
except Exception as ex:
demisto.error(traceback.format_exc()) # print the traceback
- return_error(f'Failed to execute RemoveKeyFromList. Error: {str(ex)}')
+ return_error(f'Failed to execute RemoveKeyFromList. Error: {ex!s}')
''' ENTRY POINT '''
diff --git a/Packs/CommonScripts/Scripts/RemoveKeyFromList/RemoveKeyFromList_test.py b/Packs/CommonScripts/Scripts/RemoveKeyFromList/RemoveKeyFromList_test.py
index b9a9a445a0e3..98f335761380 100644
--- a/Packs/CommonScripts/Scripts/RemoveKeyFromList/RemoveKeyFromList_test.py
+++ b/Packs/CommonScripts/Scripts/RemoveKeyFromList/RemoveKeyFromList_test.py
@@ -1,7 +1,8 @@
-from RemoveKeyFromList import remove_key_from_list_command
-import demistomock as demisto # noqa # pylint: disable=unused-wildcard-import
-from typing import Any
import json
+from typing import Any
+
+import demistomock as demisto # noqa # pylint: disable=unused-wildcard-import
+from RemoveKeyFromList import remove_key_from_list_command
MOCK_LIST_NAME = "TestList"
MOCK_KEY_NAME = "TestKey"
diff --git a/Packs/CommonScripts/Scripts/ReplaceMatchGroup/ReplaceMatchGroup.py b/Packs/CommonScripts/Scripts/ReplaceMatchGroup/ReplaceMatchGroup.py
index bdeea89eadbb..a82cf143308b 100644
--- a/Packs/CommonScripts/Scripts/ReplaceMatchGroup/ReplaceMatchGroup.py
+++ b/Packs/CommonScripts/Scripts/ReplaceMatchGroup/ReplaceMatchGroup.py
@@ -1,6 +1,7 @@
+import re
+
import demistomock as demisto
from CommonServerPython import *
-import re
def main(args):
diff --git a/Packs/CommonScripts/Scripts/ReplaceMatchGroup/ReplaceMatchGroup_test.py b/Packs/CommonScripts/Scripts/ReplaceMatchGroup/ReplaceMatchGroup_test.py
index a0696ac402d2..506ddf97e278 100644
--- a/Packs/CommonScripts/Scripts/ReplaceMatchGroup/ReplaceMatchGroup_test.py
+++ b/Packs/CommonScripts/Scripts/ReplaceMatchGroup/ReplaceMatchGroup_test.py
@@ -1,7 +1,6 @@
import pytest
from CommonServerPython import DemistoException
-
test_data = [
('[{"Sha1Hash"},{"437"},{"Sha1Hash"}]', r'\{".*?"(\},\{)".*?"\}', '@@@', '[{"Sha1Hash"@@@"437"},{"Sha1Hash"}]'),
('{"1"},{"2"},{"3"},{"4"}', r'\{".*?"\}(,)\{".*?"\}', ':', '{"1"}:{"2"},{"3"}:{"4"}'),
diff --git a/Packs/CommonScripts/Scripts/RepopulateFiles/RepopulateFiles.py b/Packs/CommonScripts/Scripts/RepopulateFiles/RepopulateFiles.py
index e88f461e5c00..804e6d20da5b 100644
--- a/Packs/CommonScripts/Scripts/RepopulateFiles/RepopulateFiles.py
+++ b/Packs/CommonScripts/Scripts/RepopulateFiles/RepopulateFiles.py
@@ -1,8 +1,9 @@
+import hashlib
+import os
+from typing import Any
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-import os
-import hashlib
-from typing import List, Dict, Optional, Any
def parse_attachment_entries(entries):
@@ -35,7 +36,7 @@ def parse_attachment_entries(entries):
return entry_context
-def find_attachment_entry(file_ents: List[Dict[str, Any]], attachment_ent: Dict[str, Any]) -> Optional[Dict[str, Any]]:
+def find_attachment_entry(file_ents: list[dict[str, Any]], attachment_ent: dict[str, Any]) -> dict[str, Any] | None:
"""
Find an incident attachment entry
diff --git a/Packs/CommonScripts/Scripts/RepopulateFiles/RepopulateFiles_test.py b/Packs/CommonScripts/Scripts/RepopulateFiles/RepopulateFiles_test.py
index 057142aaac9c..e2ff8b0d0deb 100644
--- a/Packs/CommonScripts/Scripts/RepopulateFiles/RepopulateFiles_test.py
+++ b/Packs/CommonScripts/Scripts/RepopulateFiles/RepopulateFiles_test.py
@@ -1,7 +1,8 @@
-import demistomock as demisto
-from RepopulateFiles import parse_attachment_entries, find_attachment_entry, main
from unittest import mock
+import demistomock as demisto
+from RepopulateFiles import find_attachment_entry, main, parse_attachment_entries
+
class TestRepopulateFiles:
def test_parse_attachment_entries(self):
diff --git a/Packs/CommonScripts/Scripts/ResolveShortenedURL/ResolveShortenedURL.py b/Packs/CommonScripts/Scripts/ResolveShortenedURL/ResolveShortenedURL.py
index 8a4b96670aec..cac78fda6ab8 100644
--- a/Packs/CommonScripts/Scripts/ResolveShortenedURL/ResolveShortenedURL.py
+++ b/Packs/CommonScripts/Scripts/ResolveShortenedURL/ResolveShortenedURL.py
@@ -1,12 +1,11 @@
-import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
-import urllib3
from abc import ABCMeta
-from typing import NamedTuple, Type
+from typing import NamedTuple
+import demistomock as demisto # noqa: F401
+import urllib3
+from CommonServerPython import * # noqa: F401
from requests import Response
-
urllib3.disable_warnings() # Disable insecure warnings
DEFAULT_SERVICE = "unshorten.me"
@@ -127,7 +126,7 @@ def hit_redirect_limit(self, redirect_history: list) -> bool:
return len(redirect_history) >= self.redirect_limit
@staticmethod
- def find_matching_service(service_name: str) -> Type["URLUnshortingService"]:
+ def find_matching_service(service_name: str) -> type["URLUnshortingService"]:
"""
Finds a matching service class by name.
@@ -154,7 +153,6 @@ def resolve_url(self, url: str) -> URLUnshorteningData: # pragma: no cover
Returns:
URLUnshorteningData: A NamedTuple containing the data for the resolved URL.
"""
- pass
class LongurlInService(URLUnshortingService):
@@ -392,7 +390,7 @@ def main(): # pragma: no cover
return_results(result)
except Exception as e:
- return_error(f"Error: {str(e)}")
+ return_error(f"Error: {e!s}")
if __name__ in ("__main__", "__builtin__", "builtins"): # pragma: no cover
diff --git a/Packs/CommonScripts/Scripts/ResolveShortenedURL/ResolveShortenedURL_test.py b/Packs/CommonScripts/Scripts/ResolveShortenedURL/ResolveShortenedURL_test.py
index c14f318a5947..ab9d2be699ad 100644
--- a/Packs/CommonScripts/Scripts/ResolveShortenedURL/ResolveShortenedURL_test.py
+++ b/Packs/CommonScripts/Scripts/ResolveShortenedURL/ResolveShortenedURL_test.py
@@ -2,7 +2,6 @@
import pytest
from requests import Response
-
from ResolveShortenedURL import *
@@ -17,7 +16,7 @@ def load_test_data(folder: str, file_name: str) -> dict:
Returns:
dict: Dictionary data loaded from the json file.
"""
- with open(Path("test_data") / folder / f"{file_name}.json", "r") as f:
+ with open(Path("test_data") / folder / f"{file_name}.json") as f:
return json.load(f)
diff --git a/Packs/CommonScripts/Scripts/RunDockerCommand/RunDockerCommand.py b/Packs/CommonScripts/Scripts/RunDockerCommand/RunDockerCommand.py
index 446c2173e5e9..c873e574ab02 100644
--- a/Packs/CommonScripts/Scripts/RunDockerCommand/RunDockerCommand.py
+++ b/Packs/CommonScripts/Scripts/RunDockerCommand/RunDockerCommand.py
@@ -1,6 +1,7 @@
+import subprocess
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-import subprocess
def main():
diff --git a/Packs/CommonScripts/Scripts/RunDockerCommand/RunDockerCommand_test.py b/Packs/CommonScripts/Scripts/RunDockerCommand/RunDockerCommand_test.py
index 21727bb0988f..f90ca8debd3c 100644
--- a/Packs/CommonScripts/Scripts/RunDockerCommand/RunDockerCommand_test.py
+++ b/Packs/CommonScripts/Scripts/RunDockerCommand/RunDockerCommand_test.py
@@ -1,7 +1,8 @@
import subprocess
-from RunDockerCommand import main
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
+from RunDockerCommand import main
def test_run_docker_command(mocker):
diff --git a/Packs/CommonScripts/Scripts/RunPollingCommand/RunPollingCommand.py b/Packs/CommonScripts/Scripts/RunPollingCommand/RunPollingCommand.py
index 21955b88d8e0..491003201ba0 100644
--- a/Packs/CommonScripts/Scripts/RunPollingCommand/RunPollingCommand.py
+++ b/Packs/CommonScripts/Scripts/RunPollingCommand/RunPollingCommand.py
@@ -13,8 +13,7 @@ def prepare_arg_dict(ids_arg_name, ids, additional_arg_names, additional_arg_val
if len(args_names) != len(args_values):
raise ValueError('arg names and arg values lists does not match, please check your inputs:\n'
- 'arg names ({}): {}\narg values ({}): {}'.format(len(args_names), args_names,
- len(args_values), args_values)
+ f'arg names ({len(args_names)}): {args_names}\narg values ({len(args_values)}): {args_values}'
)
args = dict(zip(args_names, args_values))
@@ -45,7 +44,7 @@ def main(args): # pragma: no cover
demisto.results(demisto.executeCommand(demisto.getArg('pollingCommand'), args))
except Exception as exp:
- return_error('An error occurred: {}'.format(exp), error=exp)
+ return_error(f'An error occurred: {exp}', error=exp)
if __name__ in ['__main__', 'builtin', 'builtins']:
diff --git a/Packs/CommonScripts/Scripts/RunPollingCommand/RunPollingCommand_test.py b/Packs/CommonScripts/Scripts/RunPollingCommand/RunPollingCommand_test.py
index 7ff9750948a7..6fae4181ac7f 100644
--- a/Packs/CommonScripts/Scripts/RunPollingCommand/RunPollingCommand_test.py
+++ b/Packs/CommonScripts/Scripts/RunPollingCommand/RunPollingCommand_test.py
@@ -1,4 +1,3 @@
-# coding=utf-8
import pytest
from RunPollingCommand import prepare_arg_dict
@@ -21,17 +20,17 @@
),
# extra args
(
- ('ids', ['a', 'b', 'c'], u'arg1', u'value1'),
+ ('ids', ['a', 'b', 'c'], 'arg1', 'value1'),
{'ids': 'a,b,c', 'arg1': 'value1'},
),
# extra args as unicode lists
(
- ('ids', ['a', 'b', 'c'], [u'arg1', u'arg2'], [u'value1', u'value2']),
+ ('ids', ['a', 'b', 'c'], ['arg1', 'arg2'], ['value1', 'value2']),
{'ids': 'a,b,c', 'arg1': 'value1', 'arg2': 'value2'},
),
# extra args as chane of unicode
(
- ('ids', ['a', 'b', 'c'], u'arg1, arg2,arg3', [u'value1', u'value2', u'value3']),
+ ('ids', ['a', 'b', 'c'], 'arg1, arg2,arg3', ['value1', 'value2', 'value3']),
{'ids': 'a,b,c', 'arg1': 'value1', 'arg2': 'value2', 'arg3': 'value3'},
),
# extra args as string
@@ -55,4 +54,4 @@ def test_prepare_arg_dict(inputs, expected_args):
def test_prepare_arg_dict__error():
with pytest.raises(ValueError):
- prepare_arg_dict('ids', 'a', u'arg1', None)
+ prepare_arg_dict('ids', 'a', 'arg1', None)
diff --git a/Packs/CommonScripts/Scripts/SCPPullFiles/SCPPullFiles_test.py b/Packs/CommonScripts/Scripts/SCPPullFiles/SCPPullFiles_test.py
index 8ce40d8c5407..e43296baa604 100644
--- a/Packs/CommonScripts/Scripts/SCPPullFiles/SCPPullFiles_test.py
+++ b/Packs/CommonScripts/Scripts/SCPPullFiles/SCPPullFiles_test.py
@@ -3,7 +3,7 @@
def test_scp_pull_files(mocker):
- with open('./test_data/json_file.json', 'r') as file:
+ with open('./test_data/json_file.json') as file:
json_file = file.read()
mocker.patch.object(demisto, 'get', return_value=json_file)
mocker.patch.object(demisto, 'executeCommand', return_value=['copy-from response'])
@@ -11,7 +11,7 @@ def test_scp_pull_files(mocker):
def test_scp_pull_files_error_in_file(mocker):
- with open('./test_data/not_dict_json_file.json', 'r') as file:
+ with open('./test_data/not_dict_json_file.json') as file:
txt_file = file.read()
mocker.patch.object(demisto, 'get', return_value=txt_file)
assert scp_pull_files({}) == {'Type': 4, 'ContentsFormat': 'text',
diff --git a/Packs/CommonScripts/Scripts/SSDeepSimilarity/SSDeepSimilarity.py b/Packs/CommonScripts/Scripts/SSDeepSimilarity/SSDeepSimilarity.py
index 70f0eed55035..88e48fbc769f 100644
--- a/Packs/CommonScripts/Scripts/SSDeepSimilarity/SSDeepSimilarity.py
+++ b/Packs/CommonScripts/Scripts/SSDeepSimilarity/SSDeepSimilarity.py
@@ -1,8 +1,8 @@
-import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
+import tempfile
import traceback
-import tempfile
+import demistomock as demisto # noqa: F401
+from CommonServerPython import * # noqa: F401
HEADERS = "ssdeep,1.1--blocksize:hash:hash,filename\n"
@@ -106,7 +106,7 @@ def main():
except Exception as ex:
demisto.error(traceback.format_exc()) # print the traceback
- return_error(f'Failed to compare ssdeep hashes. Error: {str(ex)}')
+ return_error(f'Failed to compare ssdeep hashes. Error: {ex!s}')
if __name__ in ('__main__', '__builtin__', 'builtins'):
diff --git a/Packs/CommonScripts/Scripts/SSDeepSimilarity/SSDeepSimilarity_test.py b/Packs/CommonScripts/Scripts/SSDeepSimilarity/SSDeepSimilarity_test.py
index 94bc2fd9c03d..845c1b5de9c1 100644
--- a/Packs/CommonScripts/Scripts/SSDeepSimilarity/SSDeepSimilarity_test.py
+++ b/Packs/CommonScripts/Scripts/SSDeepSimilarity/SSDeepSimilarity_test.py
@@ -1,5 +1,5 @@
-import pytest
import demistomock as demisto # noqa: F401
+import pytest
CASE_ANCHOR_EMPTY = {'ssdeep_hash': '',
'ssdeep_hashes_to_compare': '3:AXGBicFlIHBGcL6wCrFQEv:AXGH6xLsr2C'}
diff --git a/Packs/CommonScripts/Scripts/ScheduleGenericPolling/ScheduleGenericPolling.py b/Packs/CommonScripts/Scripts/ScheduleGenericPolling/ScheduleGenericPolling.py
index f84e9d70e292..3a4fe77a2e45 100644
--- a/Packs/CommonScripts/Scripts/ScheduleGenericPolling/ScheduleGenericPolling.py
+++ b/Packs/CommonScripts/Scripts/ScheduleGenericPolling/ScheduleGenericPolling.py
@@ -1,6 +1,7 @@
+import uuid
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-import uuid
# Constant to verify the minimum build number and version for the new polling feature (stopScheduleEntry feature).
# MINIMUM_XSIAM_VERSION = '8.3.0'
diff --git a/Packs/CommonScripts/Scripts/ScheduleGenericPolling/ScheduleGenericPolling_test.py b/Packs/CommonScripts/Scripts/ScheduleGenericPolling/ScheduleGenericPolling_test.py
index c8ff08f8328b..ef65b9ed7f01 100644
--- a/Packs/CommonScripts/Scripts/ScheduleGenericPolling/ScheduleGenericPolling_test.py
+++ b/Packs/CommonScripts/Scripts/ScheduleGenericPolling/ScheduleGenericPolling_test.py
@@ -1,9 +1,15 @@
import demistomock as demisto
-from freezegun import freeze_time
import pytest
-from ScheduleGenericPolling import calculate_end_time, get_command_string, is_command_sanitized, is_value_sanitized, main, \
- parseIds
+from freezegun import freeze_time
+from ScheduleGenericPolling import (
+ calculate_end_time,
+ get_command_string,
+ is_command_sanitized,
+ is_value_sanitized,
+ main,
+ parseIds,
+)
@pytest.mark.parametrize('value, expected_result',
diff --git a/Packs/CommonScripts/Scripts/SearchIncidentsSummary/SearchIncidentsSummary.py b/Packs/CommonScripts/Scripts/SearchIncidentsSummary/SearchIncidentsSummary.py
index 09eb19d438a9..74d6d0e10028 100644
--- a/Packs/CommonScripts/Scripts/SearchIncidentsSummary/SearchIncidentsSummary.py
+++ b/Packs/CommonScripts/Scripts/SearchIncidentsSummary/SearchIncidentsSummary.py
@@ -1,12 +1,11 @@
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-from typing import Dict, List
-
special = ['n', 't', '\\', '"', '\'', '7', 'r']
-def check_if_found_incident(res: List):
+def check_if_found_incident(res: list):
if res and isinstance(res, list) and isinstance(res[0].get('Contents'), dict):
if 'data' not in res[0]['Contents']:
raise DemistoException(res[0].get('Contents'))
@@ -17,9 +16,9 @@ def check_if_found_incident(res: List):
raise DemistoException(f'failed to get incidents from xsoar.\nGot: {res}')
-def is_valid_args(args: Dict):
- array_args: List[str] = ['id', 'name', 'status', 'notstatus', 'reason', 'level', 'owner', 'type', 'query']
- error_msg: List[str] = []
+def is_valid_args(args: dict):
+ array_args: list[str] = ['id', 'name', 'status', 'notstatus', 'reason', 'level', 'owner', 'type', 'query']
+ error_msg: list[str] = []
for _key, value in args.items():
if _key in array_args:
try:
@@ -34,7 +33,7 @@ def is_valid_args(args: Dict):
_ = bytes(value, "utf-8").decode("unicode_escape")
except UnicodeDecodeError as ex:
error_msg.append(f'Error while parsing the argument: "{_key}" '
- f'\nError:\n- "{str(ex)}"')
+ f'\nError:\n- "{ex!s}"')
if len(error_msg) != 0:
raise DemistoException('\n'.join(error_msg))
@@ -42,7 +41,7 @@ def is_valid_args(args: Dict):
return True
-def apply_filters(incidents: List, args: Dict):
+def apply_filters(incidents: list, args: dict):
names_to_filter = set(argToList(args.get('name')))
types_to_filter = set(argToList(args.get('type')))
filtered_incidents = []
@@ -64,7 +63,7 @@ def apply_filters(incidents: List, args: Dict):
return filtered_incidents
-def add_incidents_link(data: List):
+def add_incidents_link(data: list):
server_url = demisto.demistoUrls().get('server')
for incident in data:
incident_link = urljoin(server_url, f'#/Details/{incident.get("id")}')
@@ -72,7 +71,7 @@ def add_incidents_link(data: List):
return data
-def search_incidents(args: Dict): # pragma: no cover
+def search_incidents(args: dict): # pragma: no cover
if not is_valid_args(args):
return
@@ -90,23 +89,23 @@ def search_incidents(args: Dict): # pragma: no cover
if args.get('id'):
args['id'] = ','.join(argToList(args.get('id'), transform=str))
- res: List = execute_command('getIncidents', args, extract_contents=False)
+ res: list = execute_command('getIncidents', args, extract_contents=False)
incident_found: bool = check_if_found_incident(res)
if incident_found is False:
return 'Incidents not found.', {}, {}
data = apply_filters(res[0]['Contents']['data'], args)
data = add_incidents_link(data)
- headers: List[str] = ['id', 'name', 'severity', 'status', 'owner', 'created', 'closed', 'incidentLink']
+ headers: list[str] = ['id', 'name', 'severity', 'status', 'owner', 'created', 'closed', 'incidentLink']
if args.get("add_fields_to_context"):
- add_headers: List[str] = args.get("add_fields_to_context", '').split(",")
+ add_headers: list[str] = args.get("add_fields_to_context", '').split(",")
headers = headers + add_headers
md: str = tableToMarkdown(name="Incidents found", t=data, headers=headers)
return md, data, res
def main(): # pragma: no cover
- args: Dict = demisto.args()
+ args: dict = demisto.args()
try:
readable_output, outputs, raw_response = search_incidents(args)
if search_results_label := args.get('searchresultslabel'):
diff --git a/Packs/CommonScripts/Scripts/SearchIncidentsSummary/SearchIncidentsSummary_test.py b/Packs/CommonScripts/Scripts/SearchIncidentsSummary/SearchIncidentsSummary_test.py
index 2448825ff076..2fd85ffdc6bc 100644
--- a/Packs/CommonScripts/Scripts/SearchIncidentsSummary/SearchIncidentsSummary_test.py
+++ b/Packs/CommonScripts/Scripts/SearchIncidentsSummary/SearchIncidentsSummary_test.py
@@ -1,4 +1,4 @@
-from SearchIncidentsSummary import check_if_found_incident, is_valid_args, apply_filters, add_incidents_link
+from SearchIncidentsSummary import add_incidents_link, apply_filters, check_if_found_incident, is_valid_args
def test_check_if_found_incident():
diff --git a/Packs/CommonScripts/Scripts/SearchIncidentsV2/SearchIncidentsV2.py b/Packs/CommonScripts/Scripts/SearchIncidentsV2/SearchIncidentsV2.py
index 566514b1daaa..df75118c246b 100644
--- a/Packs/CommonScripts/Scripts/SearchIncidentsV2/SearchIncidentsV2.py
+++ b/Packs/CommonScripts/Scripts/SearchIncidentsV2/SearchIncidentsV2.py
@@ -1,6 +1,7 @@
+from enum import Enum
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-from enum import Enum
special = ['n', 't', '\\', '"', '\'', '7', 'r']
DEFAULT_LIMIT = 100
@@ -52,7 +53,7 @@ def is_valid_args(args: Dict):
_ = bytes(value, "utf-8").decode("unicode_escape")
except UnicodeDecodeError as ex:
error_msg.append(f'Error while parsing the argument: "{_key}" '
- f'\nError:\n- "{str(ex)}"')
+ f'\nError:\n- "{ex!s}"')
if len(error_msg) != 0:
raise DemistoException('\n'.join(error_msg))
diff --git a/Packs/CommonScripts/Scripts/SearchIncidentsV2/SearchIncidentsV2_test.py b/Packs/CommonScripts/Scripts/SearchIncidentsV2/SearchIncidentsV2_test.py
index f0f1e71b37df..370fcc9249b1 100644
--- a/Packs/CommonScripts/Scripts/SearchIncidentsV2/SearchIncidentsV2_test.py
+++ b/Packs/CommonScripts/Scripts/SearchIncidentsV2/SearchIncidentsV2_test.py
@@ -1,7 +1,8 @@
-from SearchIncidentsV2 import *
-import pytest
import datetime as dt
+import pytest
+from SearchIncidentsV2 import *
+
data_test_check_if_found_incident = [
([], 'failed to get incidents from xsoar.\nGot: []'),
(None, 'failed to get incidents from xsoar.\nGot: None'),
diff --git a/Packs/CommonScripts/Scripts/SendEmailOnSLABreach/SendEmailOnSLABreach.py b/Packs/CommonScripts/Scripts/SendEmailOnSLABreach/SendEmailOnSLABreach.py
index 15c5d9bc0918..1336cd72b152 100644
--- a/Packs/CommonScripts/Scripts/SendEmailOnSLABreach/SendEmailOnSLABreach.py
+++ b/Packs/CommonScripts/Scripts/SendEmailOnSLABreach/SendEmailOnSLABreach.py
@@ -18,8 +18,8 @@ def get_owner_email():
demisto.results({
"Type": entryTypes["error"],
"ContentsFormat": formats["text"],
- "Contents": "Could not retrieve user email. Maybe the user has no associated email to it.\
- Error: {}".format(ex)
+ "Contents": f"Could not retrieve user email. Maybe the user has no associated email to it.\
+ Error: {ex}"
})
return
@@ -34,7 +34,7 @@ def get_owner_email():
def get_subject():
incident_name = demisto.incidents()[0].get("name")
incident_id = demisto.incidents()[0].get("id")
- subject = "SLA Breached in incident \"{}\" #{}".format(incident_name, incident_id)
+ subject = f"SLA Breached in incident \"{incident_name}\" #{incident_id}"
return subject
diff --git a/Packs/CommonScripts/Scripts/ServerLogs/ServerLogs.py b/Packs/CommonScripts/Scripts/ServerLogs/ServerLogs.py
index 8c6fa49dc934..3993b5d4e897 100644
--- a/Packs/CommonScripts/Scripts/ServerLogs/ServerLogs.py
+++ b/Packs/CommonScripts/Scripts/ServerLogs/ServerLogs.py
@@ -1,6 +1,7 @@
+import re
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-import re
def execute_ssh_command():
diff --git a/Packs/CommonScripts/Scripts/ServerLogs/ServerLogs_test.py b/Packs/CommonScripts/Scripts/ServerLogs/ServerLogs_test.py
index 506f3bc27b21..29df337819bd 100644
--- a/Packs/CommonScripts/Scripts/ServerLogs/ServerLogs_test.py
+++ b/Packs/CommonScripts/Scripts/ServerLogs/ServerLogs_test.py
@@ -1,5 +1,5 @@
-import pytest
import demistomock as demisto
+import pytest
def test_main(mocker):
diff --git a/Packs/CommonScripts/Scripts/SetDateField/SetDateField.py b/Packs/CommonScripts/Scripts/SetDateField/SetDateField.py
index 0f4bd0d59499..5165c7db92b2 100644
--- a/Packs/CommonScripts/Scripts/SetDateField/SetDateField.py
+++ b/Packs/CommonScripts/Scripts/SetDateField/SetDateField.py
@@ -1,6 +1,7 @@
+from time import strftime
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-from time import strftime
def main():
diff --git a/Packs/CommonScripts/Scripts/SetGridField/SetGridField.py b/Packs/CommonScripts/Scripts/SetGridField/SetGridField.py
index 5b9c1d6b1efd..12cd900c2600 100644
--- a/Packs/CommonScripts/Scripts/SetGridField/SetGridField.py
+++ b/Packs/CommonScripts/Scripts/SetGridField/SetGridField.py
@@ -1,10 +1,13 @@
-import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
# STD Libraries
from typing import Any
+
+import demistomock as demisto # noqa: F401
+
# 3-rd party libraries
import pandas as pd
import phrases_case
+from CommonServerPython import * # noqa: F401
+
# Local packages
from CommonServerUserPython import *
@@ -408,7 +411,7 @@ def main(): # pragma: no cover
return_results(f'Set grid {grid_id} using {context_path} successfully.')
except Exception as exc:
- return_error(f'Failed to execute setGridField. Error: {str(exc)}', error=traceback.format_exc())
+ return_error(f'Failed to execute setGridField. Error: {exc!s}', error=traceback.format_exc())
if __name__ in ('__main__', '__builtin__', 'builtins'):
diff --git a/Packs/CommonScripts/Scripts/SetGridField/SetGridField_test.py b/Packs/CommonScripts/Scripts/SetGridField/SetGridField_test.py
index 5eab0b1f3798..b9d9f4d049a8 100644
--- a/Packs/CommonScripts/Scripts/SetGridField/SetGridField_test.py
+++ b/Packs/CommonScripts/Scripts/SetGridField/SetGridField_test.py
@@ -1,6 +1,7 @@
import json
-import pytest
+
import demistomock as demisto
+import pytest
def util_load_json(path):
@@ -82,8 +83,8 @@ def test_build_grid(mocker, keys: list, columns: list, dt_response_json: str, ex
Then
- Validate that the grid was created with the correct column names
"""
- import SetGridField
import pandas as pd
+ import SetGridField
mocker.patch.object(SetGridField, 'demisto')
SetGridField.demisto.dt.return_value = util_load_json(dt_response_json)
@@ -115,6 +116,7 @@ def test_build_grid_command(mocker, keys: list[str], columns: list[str], unpack_
- Validate that the grid was created with the correct column names
"""
import json
+
import SetGridField
mocker.patch.object(SetGridField, 'get_current_table', return_value=[])
mocker.patch.object(SetGridField, 'demisto')
@@ -146,6 +148,7 @@ def test_build_grid_command_with_sort_by(mocker, keys: list[str], columns: list[
- Validate that the grid was created with the correct column names and sorted correctly
"""
import json
+
import SetGridField
mocker.patch.object(SetGridField, 'get_current_table', return_value=[])
mocker.patch.object(SetGridField, 'demisto')
@@ -179,6 +182,7 @@ def test_build_grid_command_with_multi_sort_by(mocker, keys: list[str], columns:
- Validate that the grid was created with the correct column names and sorted correctly
"""
import json
+
import SetGridField
mocker.patch.object(SetGridField, 'get_current_table', return_value=[])
mocker.patch.object(SetGridField, 'demisto')
diff --git a/Packs/CommonScripts/Scripts/SetIndicatorGridField/SetIndicatorGridField.py b/Packs/CommonScripts/Scripts/SetIndicatorGridField/SetIndicatorGridField.py
index 756ffdfae64b..cd7b39cb72b6 100644
--- a/Packs/CommonScripts/Scripts/SetIndicatorGridField/SetIndicatorGridField.py
+++ b/Packs/CommonScripts/Scripts/SetIndicatorGridField/SetIndicatorGridField.py
@@ -111,7 +111,7 @@ def main() -> None:
return_error('Rows must be a list of lists.')
except Exception as e:
return_error(
- f'Invalid format for rows input. Expected format: [[1,2],[3,4]] or a valid dictionary structure. Error: {str(e)}')
+ f'Invalid format for rows input. Expected format: [[1,2],[3,4]] or a valid dictionary structure. Error: {e!s}')
# Validate that headers are a list of strings
if not all(isinstance(header, str) for header in headers):
diff --git a/Packs/CommonScripts/Scripts/SetIndicatorGridField/SetIndicatorGridField_test.py b/Packs/CommonScripts/Scripts/SetIndicatorGridField/SetIndicatorGridField_test.py
index 0d835283467d..ba4105a826f6 100644
--- a/Packs/CommonScripts/Scripts/SetIndicatorGridField/SetIndicatorGridField_test.py
+++ b/Packs/CommonScripts/Scripts/SetIndicatorGridField/SetIndicatorGridField_test.py
@@ -1,8 +1,9 @@
-import pytest
-import demistomock as demisto
from unittest.mock import patch
+
+import demistomock as demisto
+import pytest
import SetIndicatorGridField
-from SetIndicatorGridField import parse_rows, main, get_existing_grid_records
+from SetIndicatorGridField import get_existing_grid_records, main, parse_rows
VALID_ROWS_STR = '[[192.168.1.1,"example.com"], [192.168.1.2, ""], ["", "example.net"]]'
INVALID_ROWS_STR = '[[192.168.1.1, "example.com"],[192.168.1.2],[""]]}'
diff --git a/Packs/CommonScripts/Scripts/SetMultipleValues/SetMultipleValues_test.py b/Packs/CommonScripts/Scripts/SetMultipleValues/SetMultipleValues_test.py
index 964f9e59a511..4190189921fb 100644
--- a/Packs/CommonScripts/Scripts/SetMultipleValues/SetMultipleValues_test.py
+++ b/Packs/CommonScripts/Scripts/SetMultipleValues/SetMultipleValues_test.py
@@ -1,7 +1,7 @@
import demistomock as demisto # noqa: F401
+import pytest
from CommonServerPython import * # noqa: F401
from SetMultipleValues import main
-import pytest
def test_main(mocker):
diff --git a/Packs/CommonScripts/Scripts/SetTime/SetTime.py b/Packs/CommonScripts/Scripts/SetTime/SetTime.py
index aa9e8505b2c4..d050d9c391e8 100644
--- a/Packs/CommonScripts/Scripts/SetTime/SetTime.py
+++ b/Packs/CommonScripts/Scripts/SetTime/SetTime.py
@@ -1,6 +1,7 @@
+from datetime import datetime
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-from datetime import datetime
def set_time():
diff --git a/Packs/CommonScripts/Scripts/SetWithTemplate/SetWithTemplate.py b/Packs/CommonScripts/Scripts/SetWithTemplate/SetWithTemplate.py
index ed80a6b336cf..d2d1a8172a41 100644
--- a/Packs/CommonScripts/Scripts/SetWithTemplate/SetWithTemplate.py
+++ b/Packs/CommonScripts/Scripts/SetWithTemplate/SetWithTemplate.py
@@ -1,10 +1,12 @@
+from collections.abc import Callable
+from typing import Any
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-from typing import Any, Callable, Dict, Optional, Tuple
class ContextData:
- def __init__(self, context: Optional[Dict[str, Any]] = None):
+ def __init__(self, context: dict[str, Any] | None = None):
self.__context = context or demisto.context()
def __get_inputs_value(self, key: str) -> Any:
@@ -41,7 +43,7 @@ def __get_lists_value(self, key: str) -> Any:
pass
return val
- def get(self, key: Optional[str] = None) -> Any:
+ def get(self, key: str | None = None) -> Any:
""" Get the context value
:param key: The dt expressions (string within ${}).
@@ -85,12 +87,10 @@ def __is_end_mark(source: str, ci: int, end_marker: str) -> bool:
def __extract(self,
source: str,
- extractor: Optional[Callable[[str,
- Optional[ContextData]],
- Any]],
- dx: Optional[ContextData],
+ extractor: Callable[[str, ContextData | None], Any] | None,
+ dx: ContextData | None,
si: int,
- markers: Optional[Tuple[str, str]]) -> Tuple[Any, Optional[int]]:
+ markers: tuple[str, str] | None) -> tuple[Any, int | None]:
""" Extract a template text, or an enclosed value within starting and ending marks
:param source: The template text, or the enclosed value starts with the next charactor of a start marker
@@ -153,10 +153,8 @@ def __extract(self,
def build(self,
template: Any,
- extractor: Optional[Callable[[str,
- Optional[ContextData]],
- Any]],
- dx: Optional[ContextData]) -> Any:
+ extractor: Callable[[str, ContextData | None], Any] | None,
+ dx: ContextData | None) -> Any:
""" Format a text from a template including DT expressions
:param template: The template.
@@ -176,7 +174,7 @@ def build(self,
return template
-def extract_dt(dtstr: str, dx: Optional[ContextData]) -> Any:
+def extract_dt(dtstr: str, dx: ContextData | None) -> Any:
""" Extract dt expression
:param dtstr: The dt expressions (string within ${}).
diff --git a/Packs/CommonScripts/Scripts/SetWithTemplate/SetWithTemplate_test.py b/Packs/CommonScripts/Scripts/SetWithTemplate/SetWithTemplate_test.py
index b4010c0f8da3..99de23e30ede 100644
--- a/Packs/CommonScripts/Scripts/SetWithTemplate/SetWithTemplate_test.py
+++ b/Packs/CommonScripts/Scripts/SetWithTemplate/SetWithTemplate_test.py
@@ -1,6 +1,7 @@
+import json
+
import demistomock as demisto
from SetWithTemplate import main
-import json
class SideEffectExecuteCommand:
@@ -46,7 +47,7 @@ def __side_effect_demisto_dt(self, obj, dt):
return demisto.get(obj, dt)
def test_main(self, mocker):
- with open('./test_data/test.json', 'r') as f:
+ with open('./test_data/test.json') as f:
test_list = json.load(f)
mocker.patch.object(demisto, 'dt', side_effect=self.__side_effect_demisto_dt)
diff --git a/Packs/CommonScripts/Scripts/ShowIncidentIndicators/ShowIncidentIndicators_test.py b/Packs/CommonScripts/Scripts/ShowIncidentIndicators/ShowIncidentIndicators_test.py
index 74d88e804a16..afd4fc7ce015 100644
--- a/Packs/CommonScripts/Scripts/ShowIncidentIndicators/ShowIncidentIndicators_test.py
+++ b/Packs/CommonScripts/Scripts/ShowIncidentIndicators/ShowIncidentIndicators_test.py
@@ -1,5 +1,5 @@
import demistomock as demisto
-from ShowIncidentIndicators import group_by_type, get_indicators_from_incident
+from ShowIncidentIndicators import get_indicators_from_incident, group_by_type
def test_group_by_type():
diff --git a/Packs/CommonScripts/Scripts/ShowLocationOnMap/ShowLocationOnMap_test.py b/Packs/CommonScripts/Scripts/ShowLocationOnMap/ShowLocationOnMap_test.py
index efb3b4a8c56a..1cfcbd260be5 100644
--- a/Packs/CommonScripts/Scripts/ShowLocationOnMap/ShowLocationOnMap_test.py
+++ b/Packs/CommonScripts/Scripts/ShowLocationOnMap/ShowLocationOnMap_test.py
@@ -1,8 +1,8 @@
-import pytest
import sys
import CommonServerPython
import demistomock as demisto
+import pytest
LOC_VALID = ['41.40338,2.17403', '41.40338,2.17403 ', ' 41.40338 , 2.17403 ', '32.0868197,34.7810571',
'41.40338:2.17403']
diff --git a/Packs/CommonScripts/Scripts/StixCreator/StixCreator.py b/Packs/CommonScripts/Scripts/StixCreator/StixCreator.py
index 3bd7becf1a51..ae58637edb7d 100644
--- a/Packs/CommonScripts/Scripts/StixCreator/StixCreator.py
+++ b/Packs/CommonScripts/Scripts/StixCreator/StixCreator.py
@@ -1,16 +1,28 @@
+import dateparser
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-import dateparser
-
''' IMPORTS '''
import json
-from stix2 import Bundle, ExternalReference, Indicator, Vulnerability
-from stix2 import AttackPattern, Campaign, Malware, Infrastructure, IntrusionSet, Report, ThreatActor
-from stix2 import Tool, CourseOfAction
-from stix2.exceptions import InvalidValueError, MissingPropertiesError
-from typing import Any
from collections.abc import Callable
+from typing import Any
+
+from stix2 import (
+ AttackPattern,
+ Bundle,
+ Campaign,
+ CourseOfAction,
+ ExternalReference,
+ Indicator,
+ Infrastructure,
+ IntrusionSet,
+ Malware,
+ Report,
+ ThreatActor,
+ Tool,
+ Vulnerability,
+)
+from stix2.exceptions import InvalidValueError, MissingPropertiesError
SCOs: dict[str, str] = { # pragma: no cover
"md5": "file:hashes.md5",
diff --git a/Packs/CommonScripts/Scripts/StixCreator/StixCreator_test.py b/Packs/CommonScripts/Scripts/StixCreator/StixCreator_test.py
index b820497855ac..94708b398152 100644
--- a/Packs/CommonScripts/Scripts/StixCreator/StixCreator_test.py
+++ b/Packs/CommonScripts/Scripts/StixCreator/StixCreator_test.py
@@ -1,7 +1,7 @@
import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
import pytest
-from StixCreator import main, guess_indicator_type, add_file_fields_to_indicator, create_stix_sco_indicator
+from CommonServerPython import * # noqa: F401
+from StixCreator import add_file_fields_to_indicator, create_stix_sco_indicator, guess_indicator_type, main
FILE_INDICATOR = \
{
diff --git a/Packs/CommonScripts/Scripts/StopTimeToAssignOnOwnerChange/StopTimeToAssignOnOwnerChange.py b/Packs/CommonScripts/Scripts/StopTimeToAssignOnOwnerChange/StopTimeToAssignOnOwnerChange.py
index 636b58c9590f..5b5259666039 100644
--- a/Packs/CommonScripts/Scripts/StopTimeToAssignOnOwnerChange/StopTimeToAssignOnOwnerChange.py
+++ b/Packs/CommonScripts/Scripts/StopTimeToAssignOnOwnerChange/StopTimeToAssignOnOwnerChange.py
@@ -1,7 +1,6 @@
import demistomock as demisto
from CommonServerPython import * # noqa: F401
-
# ##### Help #####
# This is an example script. The script is used to stop the Time to Assignment SLA field,
# once an owner was set to an incident. If you want to use this script, you should go to
diff --git a/Packs/CommonScripts/Scripts/StopTimeToAssignOnOwnerChange/StopTimeToAssignOnOwnerChange_test.py b/Packs/CommonScripts/Scripts/StopTimeToAssignOnOwnerChange/StopTimeToAssignOnOwnerChange_test.py
index 70ebfb8d5482..44c28c4fd508 100644
--- a/Packs/CommonScripts/Scripts/StopTimeToAssignOnOwnerChange/StopTimeToAssignOnOwnerChange_test.py
+++ b/Packs/CommonScripts/Scripts/StopTimeToAssignOnOwnerChange/StopTimeToAssignOnOwnerChange_test.py
@@ -1,5 +1,5 @@
-import pytest
import demistomock as demisto
+import pytest
@pytest.mark.parametrize('args, expected_results', [
diff --git a/Packs/CommonScripts/Scripts/StringSimilarity/StringSimilarity.py b/Packs/CommonScripts/Scripts/StringSimilarity/StringSimilarity.py
index 13d0d2584861..414eb2f5b483 100644
--- a/Packs/CommonScripts/Scripts/StringSimilarity/StringSimilarity.py
+++ b/Packs/CommonScripts/Scripts/StringSimilarity/StringSimilarity.py
@@ -1,6 +1,7 @@
+import difflib
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-import difflib
def stringSimilarity(first_array: str, second_array: str, similarity_threshold: float):
@@ -49,7 +50,7 @@ def main():
results = stringSimilarity(first_array, second_array, similarity_threshold)
return_results(results)
except Exception as e:
- return_error(f'Failed to check string similarity. Problem: {str(e)}')
+ return_error(f'Failed to check string similarity. Problem: {e!s}')
if __name__ in ["__builtin__", "builtins", '__main__']:
diff --git a/Packs/CommonScripts/Scripts/StringSimilarity/StringSimilarity_test.py b/Packs/CommonScripts/Scripts/StringSimilarity/StringSimilarity_test.py
index e06c9391d54a..3bc19f9a4caf 100644
--- a/Packs/CommonScripts/Scripts/StringSimilarity/StringSimilarity_test.py
+++ b/Packs/CommonScripts/Scripts/StringSimilarity/StringSimilarity_test.py
@@ -1,8 +1,9 @@
-import pytest
-import demistomock as demisto
-from StringSimilarity import stringSimilarity, main
from unittest.mock import patch
+import demistomock as demisto
+import pytest
+from StringSimilarity import main, stringSimilarity
+
@pytest.mark.parametrize("first_string, second_string, similarity_threshold, expected_result", [
(["hello"], ["hello"], 0.9, [{
diff --git a/Packs/CommonScripts/Scripts/Strings/Strings.py b/Packs/CommonScripts/Scripts/Strings/Strings.py
index 570a05c77bb6..cb8034dde803 100644
--- a/Packs/CommonScripts/Scripts/Strings/Strings.py
+++ b/Packs/CommonScripts/Scripts/Strings/Strings.py
@@ -1,8 +1,9 @@
-import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
import re
import string
+import demistomock as demisto # noqa: F401
+from CommonServerPython import * # noqa: F401
+
def strings(args):
# Optional arguments and default values
@@ -14,11 +15,11 @@ def strings(args):
size = int(args['size'])
regex = None
if 'filter' in args:
- regex = re.compile(args['filter'], re.I)
+ regex = re.compile(args['filter'], re.IGNORECASE)
fEntry = demisto.executeCommand('getFilePath', {'id': args['entry']})[0]
if not isError(fEntry):
matches = []
- with open(demisto.get(fEntry, 'Contents.path'), 'r', 1024 * 1024, errors='ignore') as f:
+ with open(demisto.get(fEntry, 'Contents.path'), 1024 * 1024, errors='ignore') as f:
buff = ''
c = f.read(1)
while c != '':
diff --git a/Packs/CommonScripts/Scripts/TextFromHTML/TextFromHTML.py b/Packs/CommonScripts/Scripts/TextFromHTML/TextFromHTML.py
index 5c7f0aef601e..05e4f408d70c 100644
--- a/Packs/CommonScripts/Scripts/TextFromHTML/TextFromHTML.py
+++ b/Packs/CommonScripts/Scripts/TextFromHTML/TextFromHTML.py
@@ -1,14 +1,13 @@
+import re
+
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-import re
-
-
def get_plain_text(html: str, replace_line_breaks: bool, trim_result: bool):
data = ''
if html:
- data = re.sub(r'<\/?br\s?\/?>', '\n', html, flags=re.I) if replace_line_breaks else html
+ data = re.sub(r'<\/?br\s?\/?>', '\n', html, flags=re.IGNORECASE) if replace_line_breaks else html
data = re.sub(r'<.*?>', '', data)
entities = {'quot': '"', 'amp': '&', 'apos': "'", 'lt': '<', 'gt': '>', 'nbsp': ' ',
@@ -25,7 +24,7 @@ def get_plain_text(html: str, replace_line_breaks: bool, trim_result: bool):
def get_body(html: str, html_tag: str, allow_fallback: bool = False):
if html and html_tag:
- body = re.search(fr'<{html_tag}.*/{html_tag}>', html, re.M + re.S + re.I + re.U)
+ body = re.search(fr'<{html_tag}.*/{html_tag}>', html, re.MULTILINE + re.DOTALL + re.IGNORECASE + re.UNICODE)
if body and body.group(0):
return body.group(0)
diff --git a/Packs/CommonScripts/Scripts/TimeStampCompare/TimeStampCompare.py b/Packs/CommonScripts/Scripts/TimeStampCompare/TimeStampCompare.py
index 5122bee7123b..83b618edc2a8 100644
--- a/Packs/CommonScripts/Scripts/TimeStampCompare/TimeStampCompare.py
+++ b/Packs/CommonScripts/Scripts/TimeStampCompare/TimeStampCompare.py
@@ -1,9 +1,8 @@
+import dateparser
import demistomock as demisto
from CommonServerPython import * # noqa: E402 lgtm [py/polluting-import]
-from CommonServerUserPython import * # noqa: E402 lgtm [py/polluting-import]
-
-import dateparser
+from CommonServerUserPython import * # noqa: E402 lgtm [py/polluting-import]
EQUAL = 'equal'
BEFORE = 'before'
@@ -68,7 +67,7 @@ def main():
try:
return_outputs(*time_stamp_compare_command(demisto.args()))
except Exception as exc:
- return_error(f'Failed to execute TimeStampCompare. Error: {str(exc)}')
+ return_error(f'Failed to execute TimeStampCompare. Error: {exc!s}')
if __name__ in ('__main__', '__builtin__', 'builtins'):
diff --git a/Packs/CommonScripts/Scripts/TimeStampCompare/TimeStampCompare_test.py b/Packs/CommonScripts/Scripts/TimeStampCompare/TimeStampCompare_test.py
index 13427618b7e6..a6233bd88af2 100644
--- a/Packs/CommonScripts/Scripts/TimeStampCompare/TimeStampCompare_test.py
+++ b/Packs/CommonScripts/Scripts/TimeStampCompare/TimeStampCompare_test.py
@@ -1,4 +1,4 @@
-from TimeStampCompare import compare_times, time_stamp_compare_command, EQUAL, BEFORE, AFTER, DT_STRING, dateparser
+from TimeStampCompare import AFTER, BEFORE, DT_STRING, EQUAL, compare_times, dateparser, time_stamp_compare_command
def test_compare_times():
diff --git a/Packs/CommonScripts/Scripts/TopMaliciousRatioIndicators/TopMaliciousRatioIndicators_test.py b/Packs/CommonScripts/Scripts/TopMaliciousRatioIndicators/TopMaliciousRatioIndicators_test.py
index eb1011079a66..f722169461c8 100644
--- a/Packs/CommonScripts/Scripts/TopMaliciousRatioIndicators/TopMaliciousRatioIndicators_test.py
+++ b/Packs/CommonScripts/Scripts/TopMaliciousRatioIndicators/TopMaliciousRatioIndicators_test.py
@@ -1,7 +1,8 @@
-import demistomock as demisto
-from TopMaliciousRatioIndicators import main, find_indicators_with_mal_ratio
import json
+import demistomock as demisto
+from TopMaliciousRatioIndicators import find_indicators_with_mal_ratio, main
+
def util_load_json(path):
with open(path, encoding='utf-8') as f:
diff --git a/Packs/CommonScripts/Scripts/URLNumberOfAds/URLNumberOfAds.py b/Packs/CommonScripts/Scripts/URLNumberOfAds/URLNumberOfAds.py
index 719b898a2726..ee01b65324f3 100644
--- a/Packs/CommonScripts/Scripts/URLNumberOfAds/URLNumberOfAds.py
+++ b/Packs/CommonScripts/Scripts/URLNumberOfAds/URLNumberOfAds.py
@@ -1,10 +1,9 @@
-import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
import re
+from functools import reduce
+import demistomock as demisto # noqa: F401
import requests
-
-from functools import reduce
+from CommonServerPython import * # noqa: F401
def ads(html, termlist):
diff --git a/Packs/CommonScripts/Scripts/URLReputation/URLReputation_test.py b/Packs/CommonScripts/Scripts/URLReputation/URLReputation_test.py
index c8bb391c9b9a..ef358282ddb6 100644
--- a/Packs/CommonScripts/Scripts/URLReputation/URLReputation_test.py
+++ b/Packs/CommonScripts/Scripts/URLReputation/URLReputation_test.py
@@ -1,6 +1,6 @@
import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
import pytest
+from CommonServerPython import * # noqa: F401
@pytest.mark.parametrize('contents', ({'Error': 'error'}, None))
diff --git a/Packs/CommonScripts/Scripts/URLSSLVerification/URLSSLVerification.py b/Packs/CommonScripts/Scripts/URLSSLVerification/URLSSLVerification.py
index 170e0e478702..404fee26b228 100644
--- a/Packs/CommonScripts/Scripts/URLSSLVerification/URLSSLVerification.py
+++ b/Packs/CommonScripts/Scripts/URLSSLVerification/URLSSLVerification.py
@@ -1,7 +1,6 @@
import demistomock as demisto # noqa: F401
-from CommonServerPython import * # noqa: F401
import requests
-
+from CommonServerPython import * # noqa: F401
NON_SSL_PREFIX = "http"
SSL_PREFIX = "https"
diff --git a/Packs/CommonScripts/Scripts/URLSSLVerification/URLSSLVerification_test.py b/Packs/CommonScripts/Scripts/URLSSLVerification/URLSSLVerification_test.py
index 2b369b84f59d..63ef5bf8ca2d 100644
--- a/Packs/CommonScripts/Scripts/URLSSLVerification/URLSSLVerification_test.py
+++ b/Packs/CommonScripts/Scripts/URLSSLVerification/URLSSLVerification_test.py
@@ -1,5 +1,5 @@
import pytest
-from URLSSLVerification import mark_http_as_suspicious, arg_to_list_with_regex
+from URLSSLVerification import arg_to_list_with_regex, mark_http_as_suspicious
@pytest.mark.parametrize('arg, expected_result', [
diff --git a/Packs/CommonScripts/Scripts/UnzipFile/UnzipFile.py b/Packs/CommonScripts/Scripts/UnzipFile/UnzipFile.py
index af78503ec8c3..41f754d5933d 100644
--- a/Packs/CommonScripts/Scripts/UnzipFile/UnzipFile.py
+++ b/Packs/CommonScripts/Scripts/UnzipFile/UnzipFile.py
@@ -1,16 +1,16 @@
-import demistomock as demisto
-from CommonServerPython import *
-from CommonServerUserPython import *
-
import os
-import sys
-from os.path import isdir
-from os.path import isfile
-from subprocess import Popen, PIPE
-from tempfile import mkdtemp
-import shutil
import shlex
+import shutil
+import sys
import zipfile as z
+from os.path import isdir, isfile
+from subprocess import PIPE, Popen
+from tempfile import mkdtemp
+
+import demistomock as demisto
+from CommonServerPython import *
+
+from CommonServerUserPython import *
MAX_FILENAME_SIZE_BYTES = 255
SLICE_FILENAME_SIZE_BYTES = 235
diff --git a/Packs/CommonScripts/Scripts/UnzipFile/UnzipFile_test.py b/Packs/CommonScripts/Scripts/UnzipFile/UnzipFile_test.py
index eaa3e6af3321..e2c1d31aae68 100644
--- a/Packs/CommonScripts/Scripts/UnzipFile/UnzipFile_test.py
+++ b/Packs/CommonScripts/Scripts/UnzipFile/UnzipFile_test.py
@@ -1,7 +1,8 @@
-from tempfile import mkdtemp
-from UnzipFile import *
import os
+from tempfile import mkdtemp
+
import pytest
+from UnzipFile import *
data_test_unzip_no_password = ['testZip.yml', 'ScanSummary.txt', 'item.png']
diff --git a/Packs/CommonScripts/Scripts/VerdictResult/VerdictResult_test.py b/Packs/CommonScripts/Scripts/VerdictResult/VerdictResult_test.py
index 2d4fbac08092..cc006c90fc78 100644
--- a/Packs/CommonScripts/Scripts/VerdictResult/VerdictResult_test.py
+++ b/Packs/CommonScripts/Scripts/VerdictResult/VerdictResult_test.py
@@ -1,6 +1,6 @@
-from VerdictResult import main
import demistomock as demisto
import pytest
+from VerdictResult import main
@pytest.mark.parametrize(
diff --git a/Packs/CommonScripts/Scripts/VerifyCIDR/VerifyCIDR.py b/Packs/CommonScripts/Scripts/VerifyCIDR/VerifyCIDR.py
index a588a176ff33..caf453754397 100644
--- a/Packs/CommonScripts/Scripts/VerifyCIDR/VerifyCIDR.py
+++ b/Packs/CommonScripts/Scripts/VerifyCIDR/VerifyCIDR.py
@@ -1,7 +1,7 @@
-import demistomock as demisto
-from CommonServerPython import *
import ipaddress
+import demistomock as demisto
+from CommonServerPython import *
''' STANDALONE FUNCTION '''
@@ -36,7 +36,7 @@ def main():
return_results('')
except Exception as e:
- return_error(f'Failed to execute VerifyCIDR. Error: {str(e)}')
+ return_error(f'Failed to execute VerifyCIDR. Error: {e!s}')
''' ENTRY POINT '''
diff --git a/Packs/CommonScripts/Scripts/VerifyCIDR/VerifyCIDR_test.py b/Packs/CommonScripts/Scripts/VerifyCIDR/VerifyCIDR_test.py
index c5e323667b10..bd0329997c9b 100644
--- a/Packs/CommonScripts/Scripts/VerifyCIDR/VerifyCIDR_test.py
+++ b/Packs/CommonScripts/Scripts/VerifyCIDR/VerifyCIDR_test.py
@@ -1,6 +1,5 @@
-import pytest
-
import demistomock as demisto
+import pytest
from VerifyCIDR import is_valid_cidr, main
invalid_host_bit = ('190.0.0.0/1', False)
diff --git a/Packs/CommonScripts/Scripts/VerifyIPv6Indicator/VerifyIPv6Indicator.py b/Packs/CommonScripts/Scripts/VerifyIPv6Indicator/VerifyIPv6Indicator.py
index 2534c0b85701..e5142dc0aa4a 100644
--- a/Packs/CommonScripts/Scripts/VerifyIPv6Indicator/VerifyIPv6Indicator.py
+++ b/Packs/CommonScripts/Scripts/VerifyIPv6Indicator/VerifyIPv6Indicator.py
@@ -1,6 +1,7 @@
+from ipaddress import IPv6Address
+
import demistomock as demisto
from CommonServerPython import *
-from ipaddress import IPv6Address
def is_valid_ipv6_address(address):
@@ -21,7 +22,7 @@ def main():
demisto.info(f'Got IPv6 {item}')
item = re.sub('[^a-f0-9:%th.]+', '', item)
- demisto.info(f'Changed item to {str(item)}')
+ demisto.info(f'Changed item to {item!s}')
if is_valid_ipv6_address(item):
entries_list.append(item)
diff --git a/Packs/CommonScripts/Scripts/VerifyIPv6Indicator/VerifyIPv6Indicator_test.py b/Packs/CommonScripts/Scripts/VerifyIPv6Indicator/VerifyIPv6Indicator_test.py
index 11335f90665d..ec499cb1d5ca 100644
--- a/Packs/CommonScripts/Scripts/VerifyIPv6Indicator/VerifyIPv6Indicator_test.py
+++ b/Packs/CommonScripts/Scripts/VerifyIPv6Indicator/VerifyIPv6Indicator_test.py
@@ -1,7 +1,6 @@
+import demistomock as demisto
import pytest
from hypothesis import HealthCheck, given, settings, strategies
-
-import demistomock as demisto
from VerifyIPv6Indicator import is_valid_ipv6_address, main
diff --git a/Packs/CommonScripts/Scripts/ZipFile/ZipFile.py b/Packs/CommonScripts/Scripts/ZipFile/ZipFile.py
index f6fbc25e4d9e..e89140a1a1cb 100644
--- a/Packs/CommonScripts/Scripts/ZipFile/ZipFile.py
+++ b/Packs/CommonScripts/Scripts/ZipFile/ZipFile.py
@@ -1,12 +1,13 @@
-import demistomock as demisto
-from CommonServerPython import *
-from CommonServerUserPython import *
-
import re
import shutil
-import pyzipper
from os.path import isfile
+import demistomock as demisto
+import pyzipper
+from CommonServerPython import *
+
+from CommonServerUserPython import *
+
ESCAPE_CHARACTERS = r'[/\<>"|?*]'
diff --git a/Packs/CommonScripts/Scripts/ZipFile/ZipFile_test.py b/Packs/CommonScripts/Scripts/ZipFile/ZipFile_test.py
index d62e3fe08a27..f5b059fc551d 100644
--- a/Packs/CommonScripts/Scripts/ZipFile/ZipFile_test.py
+++ b/Packs/CommonScripts/Scripts/ZipFile/ZipFile_test.py
@@ -1,8 +1,9 @@
import os
+import tempfile
+
import pytest
import pyzipper
-from ZipFile import escape_illegal_characters_in_file_name, compress_multiple
-import tempfile
+from ZipFile import compress_multiple, escape_illegal_characters_in_file_name
ESCAPE_CHARACTERS_PACK = [
('/Users/user/Downloads/b/a/testingfile.txt', '-Users-user-Downloads-b-a-testingfile.txt'),
diff --git a/Packs/CommonScripts/Scripts/ZipStringsArrays/ZipStringsArrays.py b/Packs/CommonScripts/Scripts/ZipStringsArrays/ZipStringsArrays.py
index cb1935ac7b0c..86e96e446910 100644
--- a/Packs/CommonScripts/Scripts/ZipStringsArrays/ZipStringsArrays.py
+++ b/Packs/CommonScripts/Scripts/ZipStringsArrays/ZipStringsArrays.py
@@ -24,7 +24,7 @@ def main(): # pragma: no cover
return_results(mapper_command(demisto.args()))
except Exception as ex:
demisto.error(traceback.format_exc()) # print the traceback
- return_error(f'Failed to execute BaseScript. Error: {str(ex)}')
+ return_error(f'Failed to execute BaseScript. Error: {ex!s}')
''' ENTRY POINT '''
diff --git a/Packs/CommonScripts/Scripts/diplayMappedFields/diplayMappedFields.py b/Packs/CommonScripts/Scripts/diplayMappedFields/diplayMappedFields.py
index f522ee9973a5..1b21d1b2b9a2 100644
--- a/Packs/CommonScripts/Scripts/diplayMappedFields/diplayMappedFields.py
+++ b/Packs/CommonScripts/Scripts/diplayMappedFields/diplayMappedFields.py
@@ -1,7 +1,6 @@
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
-
# List of empty values that we want to filter out.
EMPTY_VALUES = ["{}", "[{}]", "[{}, {}]", "[{}, {}, {}]", "0001-01-01T00:00:00Z", "containmentsla", "remediationsla",
"detectionsla", "triagesla"]