Skip to main content
Panther Knowledge Base

How can I write unit tests for Panther detections that use relative time?

QUESTION

If I have a detection that uses relative time for logic (such as 'check if the event is older than a week'), how can I write a unit test?

ANSWER

To test, you can use extreme values. If you want the event to be really old, set p_event_time = '0000-00-00T00:00:00Z'. Likewise, if the event should be young, set the event time to the distant future: p_event_time = '3000-00-00T00:00:00Z'

Example

Suppose we have the following detection:

MAX_EVENT_AGE = datetime.timedelta(days=7) # Event must not be older than 1 week

def rule(event):
    return datetime.utcnow() - event['p_event_time'] < MAX_EVENT_AGE

The detection triggers if the event occurred within the past week. Since this detection uses datetime.utcnow(), the 'age' of any test event will be different each time the test is run. How do you ensure that a test event will always pass or always fail, if the age of the event changes over time?

The solution is to let p_event_time be set to extreme values.

  • If you want to make a test event that is always older than 7 days, set p_event_time in the distant past.
  • If you want an event to always be younger than 7 days, set p_event_time to sometime in the future.

For example, this event will always return True:

{
    p_event_time: '3022-09-14T00:00:00Z'
}

And this one will always return False:

{
    p_event_time: '1022-09-14T00:00:00Z'
}