Files
sigma-rules/tests/base.py
T

76 lines
2.4 KiB
Python
Raw Normal View History

# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
# or more contributor license agreements. Licensed under the Elastic License
# 2.0; you may not use this file except in compliance with the Elastic License
# 2.0.
"""Shared resources for tests."""
import unittest
2023-03-07 14:40:41 -09:00
from functools import lru_cache
from typing import Union
2021-03-24 10:24:32 -06:00
from detection_rules.rule import TOMLRule
from detection_rules.rule_loader import DeprecatedCollection, DeprecatedRule, RuleCollection, production_filter
RULE_LOADER_FAIL = False
RULE_LOADER_FAIL_MSG = None
RULE_LOADER_FAIL_RAISED = False
2023-03-07 14:40:41 -09:00
@lru_cache
def default_rules() -> RuleCollection:
return RuleCollection.default()
@lru_cache
def default_bbr() -> RuleCollection:
return RuleCollection.default_bbr()
class BaseRuleTest(unittest.TestCase):
"""Base class for shared test cases which need to load rules"""
2023-03-07 14:40:41 -09:00
RULE_LOADER_FAIL = False
RULE_LOADER_FAIL_MSG = None
RULE_LOADER_FAIL_RAISED = False
@classmethod
def setUpClass(cls):
global RULE_LOADER_FAIL, RULE_LOADER_FAIL_MSG
2023-03-07 14:40:41 -09:00
# too noisy; refactor
# os.environ["DR_NOTIFY_INTEGRATION_UPDATE_AVAILABLE"] = "1"
if not RULE_LOADER_FAIL:
2023-03-07 14:40:41 -09:00
try:
rc = default_rules()
rc_bbr = default_bbr()
2023-03-07 14:40:41 -09:00
cls.all_rules = rc.rules
cls.rule_lookup = rc.id_map
cls.production_rules = rc.filter(production_filter)
cls.bbr = rc_bbr.rules
2023-03-07 14:40:41 -09:00
cls.deprecated_rules: DeprecatedCollection = rc.deprecated
except Exception as e:
RULE_LOADER_FAIL = True
RULE_LOADER_FAIL_MSG = str(e)
@staticmethod
2023-03-07 14:40:41 -09:00
def rule_str(rule: Union[DeprecatedRule, TOMLRule], trailer=' ->') -> str:
return f'{rule.id} - {rule.name}{trailer or ""}'
2023-03-07 14:40:41 -09:00
def setUp(self) -> None:
global RULE_LOADER_FAIL, RULE_LOADER_FAIL_MSG, RULE_LOADER_FAIL_RAISED
if RULE_LOADER_FAIL:
2023-03-07 14:40:41 -09:00
# limit the loader failure to just one run
# raise a dedicated test failure for the loader
if not RULE_LOADER_FAIL_RAISED:
RULE_LOADER_FAIL_RAISED = True
2023-03-07 14:40:41 -09:00
with self.subTest('Test that the rule loader loaded with no validation or other failures.'):
self.fail(f'Rule loader failure: \n{RULE_LOADER_FAIL_MSG}')
2023-03-07 14:40:41 -09:00
self.skipTest('Rule loader failure')
else:
super().setUp()