Skip to content

Commit 442e6e7

Browse files
ppcadkmeinerz
andauthored
Prevent auto rule tester from loading rules defined inside config (#809)
* Prevent auto rule tester from loading rules directly defined inside the config * Appease mypy * Update CHANGELOG.md Co-authored-by: kmeinerz <meinerzkai@gmail.com> --------- Co-authored-by: kmeinerz <meinerzkai@gmail.com>
1 parent 5c7a81a commit 442e6e7

File tree

3 files changed

+27
-20
lines changed

3 files changed

+27
-20
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
- Fixed logging error in _revoke_callback() by adding error handling
1313
- Fixed endless loading in logprep test config
14+
- prevent the auto rule tester from loading rules directly defined inside the config, since they break the auto rule tester and can't have tests anyways
1415

1516
## 16.1.0
1617
### Deprecations

logprep/util/auto_rule_tester/auto_rule_tester.py

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@
5757
from os import path
5858
from pathlib import Path
5959
from pprint import pprint
60-
from typing import TYPE_CHECKING, Union
60+
from typing import TYPE_CHECKING, Union, Any
6161

6262
from logprep.util.ansi import Fore
6363
from more_itertools import nth
@@ -89,8 +89,8 @@ class ProcessorExtensions:
8989

9090
@staticmethod
9191
def _get_errors(processor: "Processor", extra_output: list):
92-
pd_errors = []
93-
pd_warnings = []
92+
pd_errors: list[str] = []
93+
pd_warnings: list[str] = []
9494
if isinstance(processor, PreDetector):
9595
if not extra_output:
9696
return pd_errors, pd_warnings
@@ -204,7 +204,8 @@ def color_based_print(item):
204204
else:
205205
print_fcolor(Fore.CYAN, item)
206206

207-
def load_json_or_yaml(self, file_path) -> Union[list, dict]:
207+
@staticmethod
208+
def load_json_or_yaml(file_path) -> Union[list, dict]:
208209
"""load json or yaml depending on suffix
209210
210211
Parameters
@@ -250,14 +251,14 @@ def __init__(self, config_path: str):
250251

251252
self._success = True
252253

253-
self._result = {
254+
self._result: dict[str, Union[int, float]] = {
254255
"+ Successful Tests": 0,
255256
"- Failed Tests": 0,
256257
"~ Warning": 0,
257258
"Rule Test Coverage": 0.0,
258259
"Total Tests": 0,
259260
}
260-
self._problems = {"warnings": [], "errors": []}
261+
self._problems: dict[str, list] = {"warnings": [], "errors": []}
261262

262263
self._pd_extra = ProcessorExtensions()
263264
self._gpr = GrokPatternReplacer(self._config_yml)
@@ -313,7 +314,7 @@ def _run_tests_for_rules(self, rules_pn: dict) -> None:
313314
self._check_which_rule_files_miss_tests(rules_pn)
314315
processors_no_ct = self._get_processors()
315316
self.check_run_rule_tests(processors_no_ct, rules_pn)
316-
self._result["~ Warning"] += len(self._problems.get("warnings"))
317+
self._result["~ Warning"] += len(self._problems["warnings"])
317318
self._pd_extra.print_rules(self._result)
318319

319320
if not self._success:
@@ -456,24 +457,24 @@ def _eval_file_rule_test(self, rule_test: dict, processor: "Processor", r_idx: i
456457

457458
if (
458459
print_diff
459-
or nth(self._problems.get("warnings"), self._rule_cnt) is not None
460+
or nth(self._problems["warnings"], self._rule_cnt) is not None
460461
or nth(self._problems.get("errors"), self._rule_cnt) is not None
461462
):
462463
self._pd_extra.color_based_print(
463464
f"> RULE FILE {rule_test['file']} & "
464465
f"RULE TEST {t_idx + 1}/{len(rule_test['tests'])}:"
465466
)
466-
if nth(self._problems.get("warnings"), self._rule_cnt) is not None:
467+
if nth(self._problems["warnings"], self._rule_cnt) is not None:
467468
self._pd_extra.color_based_print(
468-
f"~ {self._problems.get('warnings')[self._result['~ Warning']]}"
469+
f"~ {self._problems['warnings'][int(self._result['~ Warning'])]}"
469470
)
470471

471472
if print_diff or nth(self._problems.get("errors"), self._rule_cnt) is not None:
472473
if nth(self._problems.get("errors"), self._rule_cnt) is not None:
473474
self._pd_extra.color_based_print(
474-
f"- {self._problems.get('errors')[self._result['- Failed Tests']]}"
475+
f"- {self._problems['errors'][int(self._result['- Failed Tests'])]}"
475476
)
476-
self._pd_extra.print_diff_test("", diff) # print_rules({"DIFF": diff})
477+
self._pd_extra.print_diff_test("", diff)
477478
self._success = False
478479
self._result["- Failed Tests"] += 1
479480

@@ -534,7 +535,7 @@ def _check_which_rule_files_miss_tests(self, rules_pn) -> None:
534535
rules_pn : dict
535536
accumulated rules for each processor to operate on
536537
"""
537-
rule_tests = {"with tests": [], "without tests": []}
538+
rule_tests: dict[str, list] = {"with tests": [], "without tests": []}
538539
for _, processor_test_cfg in rules_pn.items():
539540
rules = processor_test_cfg["rules"]
540541

@@ -591,7 +592,7 @@ def _set_rules_dirs_to_empty(self) -> None:
591592
processor_cfg["rules"] = self._empty_rules_dirs
592593

593594
def _get_rules_per_processor_name(self, rules_dirs: dict) -> defaultdict:
594-
rules_pn = defaultdict(dict)
595+
rules_pn: defaultdict[Any, dict] = defaultdict(dict)
595596

596597
for processor_name, proc_rules_dirs in rules_dirs.items():
597598
self._get_rules_for_processor(processor_name, proc_rules_dirs, rules_pn)
@@ -648,7 +649,7 @@ def _get_rule_dict(self, file, root, processor_name, rules_pn) -> None:
648649
Exception
649650
Target_rule_idx is now mandatory, throw exception if not found for each rule
650651
"""
651-
rule_tests = []
652+
rule_tests: list[Any] | dict[Any, Any] = []
652653
test_path = path.join(root, "".join([file.rsplit(".", maxsplit=1)[0], "_test.json"]))
653654

654655
if path.isfile(test_path):
@@ -691,7 +692,7 @@ def _is_valid_rule_name(file_name: str) -> bool:
691692
)
692693

693694
def _get_rule_dirs_by_processor_name(self) -> defaultdict:
694-
rules_dirs = defaultdict(dict)
695+
rules_dirs: defaultdict[Any, dict] = defaultdict(dict)
695696
for processor in self._config_yml["pipeline"]:
696697
processor_name, processor_cfg = next(iter(processor.items()))
697698

@@ -729,8 +730,8 @@ def _get_rules_to_add(processor_cfg) -> list:
729730
"""
730731
rules_to_add = []
731732

732-
rule_path_lists = processor_cfg.get("rules")
733-
if rule_path_lists:
734-
for rule_path_list in rule_path_lists:
735-
rules_to_add.append(rule_path_list)
733+
rules_list = processor_cfg.get("rules")
734+
rules_path_list = (rule_path for rule_path in rules_list if isinstance(rule_path, str))
735+
for rule_path_list in rules_path_list:
736+
rules_to_add.append(rule_path_list)
736737
return rules_to_add

tests/testdata/config/config-auto-tests.yml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@ pipeline:
2525
type: dropper
2626
rules:
2727
- tests/testdata/auto_tests/dropper/rules
28+
- filter: "test_dropper"
29+
dropper:
30+
drop:
31+
- drop_me
32+
description: "..."
2833
- pre_detector:
2934
type: pre_detector
3035
rules:

0 commit comments

Comments
 (0)