feat(config-revisions): declare a device's own configuration history
driver / lint (pull_request) Successful in 13s
driver / standard (pull_request) Successful in 16s
driver / types (pull_request) Successful in 1m3s
driver / test (3.13) (pull_request) Successful in 1m12s
driver / test (3.12) (pull_request) Successful in 1m18s
driver / lowest (pull_request) Successful in 47s
driver / build (pull_request) Successful in 34s
driver / security (pull_request) Successful in 3m34s
CI / driver (pull_request) Successful in 5m2s
driver / publish (pull_request) Skipped

Some devices keep a copy of their configuration for every save and can
go back to one. An application restores a configuration there by
reverting to the revision that holds it; on OPNsense that is the only
way, since its API takes no uploaded config.xml (NetOrk/netork#2511).

ConfigRevisionsMixin declares get_config_revisions() (newest first, as
ConfigRevisionDict) and get_config_revision(revision_id).
revert_config_revision(revision_id) is a template over the driver's
_revert_to_config_revision step: it refuses an id that is not in the
history (UnknownConfigRevision), reads the revision before the revert
can rotate it out, and afterwards checks that the newest revision holds
its configuration (ConfigRevertFailed otherwise), since a device may
report a revert it did not make. config_revision_content(text) is the
hook where a driver leaves out what its device stamps into every save,
so revisions with the same configuration compare equal.

Refs NetOrk/netork#2511
This commit is contained in:
christianmanivong committed 2026-11-13 22:28:30 +01:00
1 parent 241acef6c1
commit 43e0210ff6
5 files changed
+349

No files matched your search

+172
View File
@@ -0,0 +1,172 @@
"""ConfigRevisionsMixin: a device's own configuration history (NetOrk/netork#2511).
Some devices keep their earlier configurations themselves. An application restores a
configuration there by reverting to the revision that holds it -- on OPNsense the only
way, since no API takes an uploaded config.xml. Listing and reading are declared only,
so ``callable(getattr(driver, "get_config_revisions", None))`` is the truthful answer;
``revert_config_revision`` is a template: it refuses an id that is not in the history,
lets the driver revert, and checks that the configuration in place now is the
revision's.
"""
from __future__ import annotations
import inspect
from typing import get_type_hints
import pytest
from napalm_device_types import (
ConfigRevertFailed,
ConfigRevisionDict,
ConfigRevisionsMixin,
DeviceTypeDriver,
FirewallDriver,
OSDriver,
SwitchDriver,
UnknownConfigRevision,
)
def test_the_shape():
assert get_type_hints(ConfigRevisionDict) == {
"id": str,
"time": str | None,
"description": str | None,
"user": str | None,
"size": int | None,
}
def test_no_role_demands_it():
for role in (FirewallDriver, OSDriver, SwitchDriver, DeviceTypeDriver):
assert not issubclass(role, ConfigRevisionsMixin)
def test_listing_and_reading_are_declared_not_implemented():
assert not hasattr(ConfigRevisionsMixin, "get_config_revisions")
assert not hasattr(ConfigRevisionsMixin, "get_config_revision")
source = inspect.getsource(ConfigRevisionsMixin)
assert "def get_config_revisions(self) -> list[ConfigRevisionDict]" in source
assert "def get_config_revision(self, revision_id: str) -> str" in source
assert "def _revert_to_config_revision(self, revision_id: str) -> None" in source
def test_an_unknown_revision_is_a_value_error_that_names_it():
error = UnknownConfigRevision("r9")
assert isinstance(error, ValueError)
assert "'r9'" in str(error)
def test_a_failed_revert_is_a_runtime_error():
assert issubclass(ConfigRevertFailed, RuntimeError)
def _revision(revision_id: str, time: str) -> ConfigRevisionDict:
return {"id": revision_id, "time": time, "description": None, "user": None, "size": None}
class _Device(ConfigRevisionsMixin):
"""A device that keeps its history in memory, newest first, and saves a revert as a
new newest revision with a stamp of its own on the first line."""
def __init__(self) -> None:
self.history = [
(_revision("r3", "2026-11-13T21:00:00+00:00"), "#saved 3\nb\n"),
(_revision("r2", "2026-11-12T21:00:00+00:00"), "#saved 2\na\n"),
(_revision("r1", "2026-11-11T21:00:00+00:00"), "#saved 1\na\n"),
]
self.calls: list[str] = []
def get_config_revisions(self) -> list[ConfigRevisionDict]:
self.calls.append("list")
return [revision for revision, _ in self.history]
def get_config_revision(self, revision_id: str) -> str:
self.calls.append(f"read {revision_id}")
for revision, text in self.history:
if revision["id"] == revision_id:
return text
raise UnknownConfigRevision(revision_id)
def _revert_to_config_revision(self, revision_id: str) -> None:
self.calls.append(f"revert {revision_id}")
body = self.get_config_revision(revision_id).split("\n", 1)[1]
self.history.insert(0, (_revision("r4", "2026-11-14T08:00:00+00:00"), f"#saved 4\n{body}"))
def config_revision_content(self, text: str) -> str:
return text.split("\n", 1)[1]
class TestRevertConfigRevision:
def test_reverts_and_answers_with_the_revision_now_in_place(self):
device = _Device()
now = device.revert_config_revision("r1")
assert now["id"] == "r4"
assert device.calls == ["list", "read r1", "revert r1", "read r1", "list", "read r4"]
def test_the_revision_is_read_before_the_revert_which_may_rotate_it_out(self):
class Rotating(_Device):
def _revert_to_config_revision(self, revision_id: str) -> None:
super()._revert_to_config_revision(revision_id)
self.history.pop() # the oldest, r1, drops out
assert Rotating().revert_config_revision("r1")["id"] == "r4"
def test_a_revision_not_in_the_history_is_refused_before_anything_changes(self):
device = _Device()
with pytest.raises(UnknownConfigRevision, match="r9"):
device.revert_config_revision("r9")
assert device.calls == ["list"]
def test_a_revert_the_device_did_not_take_fails(self):
# OPNsense answers "reverted" even when it fell back to the previous file.
class Deaf(_Device):
def _revert_to_config_revision(self, revision_id: str) -> None:
self.calls.append(f"revert {revision_id}")
with pytest.raises(ConfigRevertFailed, match="r1"):
Deaf().revert_config_revision("r1")
def test_a_history_that_is_empty_afterwards_fails(self):
class Forgetful(_Device):
def _revert_to_config_revision(self, revision_id: str) -> None:
self.history.clear()
with pytest.raises(ConfigRevertFailed):
Forgetful().revert_config_revision("r1")
def test_what_a_save_stamps_anew_does_not_count(self):
# r2 and r1 differ only in their stamp: reverting to r2 leaves r1's content.
device = _Device()
assert device.revert_config_revision("r2")["id"] == "r4"
def test_a_refusal_of_the_device_reaches_the_caller(self):
class Refusing(_Device):
def _revert_to_config_revision(self, revision_id: str) -> None:
raise ConfigRevertFailed("read-only user")
with pytest.raises(ConfigRevertFailed, match="read-only"):
Refusing().revert_config_revision("r1")
class TestConfigRevisionContent:
def test_by_default_the_whole_text(self):
class Plain(ConfigRevisionsMixin):
pass
assert Plain().config_revision_content("a\nb\n") == "a\nb\n"
def test_without_a_stamp_every_save_differs(self):
class Plain(_Device):
def config_revision_content(self, text: str) -> str:
return ConfigRevisionsMixin.config_revision_content(self, text)
with pytest.raises(ConfigRevertFailed):
Plain().revert_config_revision("r1")