Add artifact.whitelist_expiration/tests/test_core.py

This commit is contained in:
Mika 2026-02-22 12:32:35 +00:00
parent e30a561801
commit af446f409b

View file

@ -0,0 +1,83 @@
import json
import pytest
from datetime import datetime, timedelta
from pathlib import Path
import artifact_whitelist_expiration.core as core
@pytest.fixture
def sample_whitelist_entry(tmp_path):
entry_file = tmp_path / 'data' / 'unknown_whitelist.json'
entry_file.parent.mkdir(parents=True, exist_ok=True)
entry_data = [{
"entry_id": "abc123",
"expires_at": (datetime.utcnow() + timedelta(days=1)).isoformat(),
"reason_code": "TEST_REASON"
}]
with open(entry_file, 'w', encoding='utf-8') as f:
json.dump(entry_data, f)
return entry_file
def test_whitelist_entry_is_expired_behavior():
entry = core.WhitelistEntry(
entry_id="e1",
expires_at=datetime.utcnow() - timedelta(days=1),
reason_code="X"
)
assert entry.is_expired() is True
entry2 = core.WhitelistEntry(
entry_id="e2",
expires_at=datetime.utcnow() + timedelta(days=1),
reason_code="Y"
)
assert entry2.is_expired() is False
def test_whitelist_entry_renew_increases_expiration():
old_exp = datetime.utcnow()
entry = core.WhitelistEntry(entry_id="e3", expires_at=old_exp, reason_code="Z")
entry.renew(5)
assert (entry.expires_at - old_exp).days == 5
def test_set_expiration_creates_updated_file(tmp_path, sample_whitelist_entry, monkeypatch):
input_file = sample_whitelist_entry
output_file = tmp_path / 'output' / 'unknown_whitelist_updated.json'
output_file.parent.mkdir(parents=True, exist_ok=True)
# patch paths if needed depending on implementation detail
monkeypatch.setattr(core, 'Path', Path)
# Call the function
core.set_expiration('abc123', 7)
# Verify file existence or updated values
assert output_file.exists() or input_file.exists()
with open(input_file if input_file.exists() else output_file, 'r', encoding='utf-8') as f:
entries = json.load(f)
match = next((e for e in entries if e['entry_id'] == 'abc123'), None)
assert match is not None
expires_at = datetime.fromisoformat(match['expires_at'])
assert expires_at > datetime.utcnow()
def test_renew_entry_logic(sample_whitelist_entry, tmp_path, monkeypatch):
input_file = sample_whitelist_entry
monkeypatch.setattr(core, 'Path', Path)
renewed = core.renew_entry('abc123')
assert isinstance(renewed, bool)
assert renewed in (True, False)
# After renew, check updated expiration date increased
with open(input_file, 'r', encoding='utf-8') as f:
entries = json.load(f)
renewed_entry = next((e for e in entries if e['entry_id'] == 'abc123'), None)
assert renewed_entry is not None
exp_date = datetime.fromisoformat(renewed_entry['expires_at'])
# expiration should be at least current time
assert exp_date > datetime.utcnow() - timedelta(days=1)