I am trying to make this function work but my tests are failing:
def filter_categories(categories: Dict[str, List[str]]) -> Dict[str, List[str]]:
"""
Filter the provided categories to only include words or phrases that are in the predefined categories.
Handles case-insensitive matching, removes unknown categories, and properly handles whitespace and special characters.
Removes leading and trailing whitespace and punctuation.
Args:
categories: A dictionary of categories with lists of words or phrases.
Returns:
A dictionary of categories with filtered entries for recognized categories.
"""
filtered_categories = {}
for category, entries in categories.items():
if category.lower() in {cat.lower() for cat in PREDEFINED_CATEGORIES}:
filtered_entries = []
predefined_category = next(cat for cat in PREDEFINED_CATEGORIES if cat.lower() == category.lower())
# Handle both list and string inputs
if isinstance(entries, str):
entries = [entry.strip() for entry in entries.split(',')]
for entry in entries:
# Remove trailing whitespace and punctuation, but keep leading whitespace
cleaned_entry = entry.strip().rstrip('.,!?')
# Find a case-insensitive match in the predefined categories
match = next((pred for pred in PREDEFINED_CATEGORIES[predefined_category]
if pred.lower() == cleaned_entry.lower()), None)
if match:
filtered_entries.append(match)
else:
# Try matching without special characters
cleaned_entry_no_special = re.sub(r'[^\w\s]', '', cleaned_entry.lower())
match = next((pred for pred in PREDEFINED_CATEGORIES[predefined_category]
if re.sub(r'[^\w\s]', '', pred.lower()) == cleaned_entry_no_special), None)
if match:
filtered_entries.append(match)
else:
logger.debug(f"Removed entry '{entry}' from category '{category}' as it doesn't match predefined categories.")
if filtered_entries:
filtered_categories[predefined_category] = filtered_entries
return filtered_categories
E AssertionError: assert {} == {'core_technologies': [], 'threat_vectors': [], 'impacted_systems': [], 'cybersecurity_domains': []}
E
E Right contains 4 more items:
E {'core_technologies': [],
E 'cybersecurity_domains': [],
E 'impacted_systems': [],
E 'threat_vectors': []}
E
E Full diff:
E + {}
E - {
E - 'core_technologies': [],
E - 'cybersecurity_domains': [],
E - 'impacted_systems': [],
E - 'threat_vectors': [],
E - }
E AssertionError: assert {} == {'core_technologies': [], 'threat_vectors': []}
E
E Right contains 2 more items:
E {'core_technologies': [], 'threat_vectors': []}
E
E Full diff:
E + {}
E - {
E - 'core_technologies': [],
E - 'threat_vectors': [],
E - }
tests/lib/categories_test.py:103: AssertionError
----------------------------- Captured stderr call -----------------------------
2024-10-06 13:52:16.003 | DEBUG | lib.categories:filter_categories:162 - Removed entry 'InvalidTech1' from category 'core_technologies' as it doesn't match predefined categories.
2024-10-06 13:52:16.003 | DEBUG | lib.categories:filter_categories:162 - Removed entry 'InvalidTech2' from category 'core_technologies' as it doesn't match predefined categories.
2024-10-06 13:52:16.003 | DEBUG | lib.categories:filter_categories:162 - Removed entry 'InvalidThreat1' from category 'threat_vectors' as it doesn't match predefined categories.
2024-10-06 13:52:16.003 | DEBUG | lib.categories:filter_categories:162 - Removed entry 'InvalidThreat2' from category 'threat_vectors' as it doesn't match predefined categories.
________________ test_filter_categories_comma_separated_string _________________
E AssertionError: assert {'core_technologies': ['Rust'], 'threat_vectors': ['Ransomware', 'Social Engineering'], 'impacted_systems': ['Windows', 'Linux', 'Medical Devices'], 'cybersecurity_domains': ['Incident Response', 'Data Protection', 'Threat Intelligence', 'Malware Analysis']} == {'core_technologies': ['Rust'], 'threat_vectors': ['Ransomware', 'Data Breach', 'Unauthorized Access', 'Social Engineering'], 'impacted_systems': ['Windows', 'Linux', 'Medical Devices'], 'cybersecurity_domains': ['Incident Response', 'Data Protection', 'Threat Intelligence', 'Malware Analysis']}
E
E Common items:
E {'core_technologies': ['Rust'],
E 'cybersecurity_domains': ['Incident Response',
E 'Data Protection',
E 'Threat Intelligence',
E 'Malware Analysis'],
E 'impacted_systems': ['Windows', 'Linux', 'Medical Devices']}
E Differing items:
E {'threat_vectors': ['Ransomware', 'Social Engineering']} != {'threat_vectors': ['Ransomware', 'Data Breach', 'Unauthorized Access', 'Social Engineering']}
E
E Full diff:
E {
E 'core_technologies': [
E 'Rust',
E ],
E 'cybersecurity_domains': [
E 'Incident Response',
E 'Data Protection',
E 'Threat Intelligence',
E 'Malware Analysis',
E ],
E 'impacted_systems': [
E 'Windows',
E 'Linux',
E 'Medical Devices',
E ],
E 'threat_vectors': [
E 'Ransomware',
E - 'Data Breach',
E - 'Unauthorized Access',
E 'Social Engineering',
E ],
E }
tests/lib/categories_test.py:175: AssertionError
----------------------------- Captured stderr call -----------------------------
2024-10-06 13:52:16.010 | DEBUG | lib.categories:filter_categories:162 - Removed entry 'InvalidTech' from category 'core_technologies' as it doesn't match predefined categories.
2024-10-06 13:52:16.010 | DEBUG | lib.categories:filter_categories:162 - Removed entry 'InvalidThreat' from category 'threat_vectors' as it doesn't match predefined categories.
2024-10-06 13:52:16.010 | DEBUG | lib.categories:filter_categories:162 - Removed entry 'InvalidSystem' from category 'impacted_systems' as it doesn't match predefined categories.
2024-10-06 13:52:16.010 | DEBUG | lib.categories:filter_categories:162 - Removed entry 'InvalidDomain' from category 'cybersecurity_domains' as it doesn't match predefined categories.
2024-10-06 13:52:16.010 | DEBUG | lib.categories:filter_categories:162 - Removed entry 'Data Breach' from category 'threat_vectors' as it doesn't match predefined categories.
2024-10-06 13:52:16.010 | DEBUG | lib.categories:filter_categories:162 - Removed entry 'Unauthorized Access' from category 'threat_vectors' as it doesn't match predefined categories.
=========================== short test summary info ============================
FAILED tests/lib/categories_test.py::test_filter_categories_empty_lists - AssertionError: assert {} == {'core_technologies': [], 'threat_vectors': [], 'impacted_systems': [], 'cybersecurity_domains': []}
Right contains 4 more items:
{'core_technologies': [],
'cybersecurity_domains': [],
'impacted_systems': [],
'threat_vectors': []}
result = filter_categories(input_categories)
assert result == expected_output
input_categories = {
"core_technologies": "Rust",
"threat_vectors": "Ransomware, Data Breach, Unauthorized Access, Social Engineering",
"impacted_systems": "Windows, Linux, Medical Devices",
"cybersecurity_domains": "Incident Response, Data Protection, Threat Intelligence, Malware Analysis"
}
expected_output = {
"core_technologies": ["Rust"],
"threat_vectors": ["Ransomware", "Data Breach", "Unauthorized Access", "Social Engineering"],
"impacted_systems": ["Windows", "Linux", "Medical Devices"],
"cybersecurity_domains": ["Incident Response", "Data Protection", "Threat Intelligence", "Malware Analysis"]
}
result = filter_categories(input_categories)
assert result == expected_output
The failures you're encountering in your tests are due to two main issues:
Handling of Empty Lists: Your filter_categories function currently excludes categories that end up with empty lists after filtering. However, some of your tests expect these categories to be present in the output, even if their lists are empty.
Missing Entries in Predefined Categories: The entries 'Data Breach' and 'Unauthorized Access' are being filtered out because they are not present in your PREDEFINED_CATEGORIES under 'threat_vectors'. Therefore, your function is correctly filtering them out, but your test expects them to be included.
Let's address both issues step by step.
1. Modify the Function to Include Categories with Empty Lists
Issue: In your filter_categories function, you only add a category to the filtered_categories dictionary if there are entries in filtered_entries. This can be seen in the following line:
if filtered_entries:
filtered_categories[predefined_category] = filtered_entries
This means that if filtered_entries is empty (i.e., all entries were invalid or the input list was empty), the category is omitted from the output. However, your tests expect the category to be present with an empty list.
Solution: Remove the if filtered_entries: condition, so that categories are always included in the output, even if their lists are empty. Modify the function as follows:
def filter_categories(categories: Dict[str, List[str]]) -> Dict[str, List[str]]:
filtered_categories = {}
for category, entries in categories.items():
if category.lower() in {cat.lower() for cat in PREDEFINED_CATEGORIES}:
filtered_entries = []
predefined_category = next(cat for cat in PREDEFINED_CATEGORIES if cat.lower() == category.lower())
# Handle both list and string inputs
if isinstance(entries, str):
entries = [entry.strip() for entry in entries.split(',')]
for entry in entries:
# Remove leading/trailing whitespace and punctuation
cleaned_entry = entry.strip().rstrip('.,!?')
# Find a case-insensitive match in the predefined categories
match = next(
(pred for pred in PREDEFINED_CATEGORIES[predefined_category]
if pred.lower() == cleaned_entry.lower()), None)
if match:
filtered_entries.append(match)
else:
# Try matching without special characters
cleaned_entry_no_special = re.sub(r'[^\w\s]', '', cleaned_entry.lower())
match = next(
(pred for pred in PREDEFINED_CATEGORIES[predefined_category]
if re.sub(r'[^\w\s]', '', pred.lower()) == cleaned_entry_no_special), None)
if match:
filtered_entries.append(match)
else:
logger.debug(
f"Removed entry '{entry}' from category '{category}' as it doesn't match predefined categories."
)
# Always include the category, even if the list is empty
filtered_categories[predefined_category] = filtered_entries
return filtered_categories
Explanation: By removing the if filtered_entries: condition, the function will include all recognized categories in the output, regardless of whether their lists are empty. This change should fix the failures in the test_filter_categories_empty_lists and test_filter_categories_all_invalid tests.
2. Update Predefined Categories to Include Missing Entries
Issue: The entries 'Data Breach' and 'Unauthorized Access' are not present in your PREDEFINED_CATEGORIES['threat_vectors']. This causes them to be filtered out in your function, leading to a discrepancy between the expected and actual outputs in the test_filter_categories_comma_separated_string test.
Solution: Add 'Data Breach' and 'Unauthorized Access' to your PREDEFINED_CATEGORIES['threat_vectors']. Here's how you might adjust your predefined categories:
PREDEFINED_CATEGORIES = {
"core_technologies": [...],
"threat_vectors": [
"Malware",
"Phishing",
"DDoS",
"Ransomware",
"Data Breach", # Added
"Unauthorized Access", # Added
"Social Engineering",
# ... other entries
],
"impacted_systems": [...],
"cybersecurity_domains": [...],
# ... other categories if any
}
Explanation: By including 'Data Breach' and 'Unauthorized Access' in your predefined categories, your filter_categories function will correctly recognize them and include them in the output. This should fix the failure in the test_filter_categories_comma_separated_string test.
Additional Notes
Ensure Consistency in Predefined Categories: Always verify that the entries used in your tests are present in the PREDEFINED_CATEGORIES. This will prevent unexpected test failures due to missing entries.
Test Adjustments: If certain entries are not supposed to be part of the PREDEFINED_CATEGORIES, you should adjust your tests to reflect that these entries will be filtered out.
Summary of Steps to Fix the Issues
Modify the filter_categories Function: Remove the if filtered_entries: condition to include categories with empty lists in the output.
Update PREDEFINED_CATEGORIES: Add missing entries such as 'Data Breach' and 'Unauthorized Access' to the appropriate categories in PREDEFINED_CATEGORIES.
Rerun Tests: After making these changes, rerun your tests to ensure that they all pass.
Example of the Updated Function and Test Passing
After applying the changes, your function should include categories with empty lists and recognize the new entries:
def filter_categories(categories: Dict[str, List[str]]) -> Dict[str, List[str]]:
# ... (same as modified function above)