Update project description and enhance documentation for clarity

- Revised the project description in `pyproject.toml` to better reflect the functionality of the `oxipy` client.
- Improved the README.md by adding detailed explanations of the project structure, installation instructions, and usage examples.
- Updated documentation files to enhance clarity and organization, including sections on extending models and writing TTP templates.
- Adjusted various TTP templates to ensure consistency and accuracy in the parsing of device configurations.
This commit is contained in:
IluaAir
2026-05-25 16:01:38 +03:00
parent e8c33b0e64
commit 41c4cc48e9
17 changed files with 524 additions and 642 deletions

View File

@@ -1,46 +1,49 @@
# Расширение и переопределение моделей устройств
# Extending Device Models
oxipy предоставляет гибкий механизм расширения через наследование от `BaseDevice`. После того как TTP-шаблон разобрал конфигурацию в сырой словарь `self.raw`, данные проходят через три метода экземпляра — `system()`, `interfaces()`, `vlans()` — перед тем как попасть в контракт. Переопределяя эти методы, можно трансформировать, фильтровать и обогащать данные без изменения шаблона или контракта.
`oxipy` parses an Oxidized configuration in two stages. A TTP template first
extracts raw dictionaries from the text, then a device model normalizes those
dictionaries before Pydantic validates them against the public contract.
## Содержание
Device models extend `BaseDevice`. Override `system()`, `interfaces()`, or
`vlans()` when the raw TTP result needs vendor-specific cleanup.
- [Архитектура: путь данных](#архитектура-путь-данных)
- [Регистрация нового устройства](#регистрация-нового-устройства)
- [Переопределение методов (monkey patching)](#переопределение-методов-monkey-patching)
## Contents
- [Data Flow](#data-flow)
- [Registering a Device](#registering-a-device)
- [Method Overrides](#method-overrides)
- [interfaces()](#interfaces)
- [vlans()](#vlans)
- [system()](#system)
- [Полный пример: новое устройство](#полный-пример-новое-устройство)
- [Контракт: ожидаемые структуры](#контракт-ожидаемые-структуры)
- [Complete Example](#complete-example)
- [Expected Contract](#expected-contract)
---
## Data Flow
## Архитектура: путь данных
```
текст конфигурации
TTP-шаблон (.ttp)
│ парсит в сырой словарь
```text
configuration text
|
v
TTP template (.ttp)
|
v
self.raw: dict
├──► system() dict
├──► interfaces() list[dict]
└──► vlans() list[dict]
_validate_contract()
│ создаёт Pydantic-модели
Device(system, interfaces, vlans)
|
+--> system() -> dict
+--> interfaces() -> list[dict]
+--> vlans() -> list[dict]
|
v
Pydantic validation
|
v
Device(system, interfaces, vlans)
```
Методы `system()`, `interfaces()`, `vlans()` — это точки расширения. Базовая реализация просто возвращает данные из `self.raw`:
The extension methods are intentionally small. The base implementation returns
data directly from `self.raw`:
```python
# BaseDevice (упрощённо)
def interfaces(self) -> list[dict]:
return self.raw.get("interfaces", [])
@@ -51,18 +54,16 @@ def system(self) -> dict:
return self.raw.get("system", None)
```
---
## Registering a Device
## Регистрация нового устройства
To add support for a new vendor:
Чтобы добавить поддержку нового вендора:
1. Создайте файл в `oxi/interfaces/models/`, например `cisco.py`.
2. Создайте шаблон `oxi/interfaces/models/templates/cisco.ttp`.
3. Унаследуйте класс от `BaseDevice` и зарегистрируйте его декоратором `@register_parser`.
1. Create a Python file in `oxi/interfaces/models/`, for example `cisco.py`.
2. Create a template in `oxi/interfaces/models/templates/`, for example
`cisco.ttp`.
3. Subclass `BaseDevice` and register it with `@register_parser`.
```python
# oxi/interfaces/models/cisco.py
from oxi.interfaces import register_parser
from oxi.interfaces.base import BaseDevice
@@ -72,26 +73,26 @@ class CiscoIOS(BaseDevice):
template = "cisco.ttp"
```
Декоратор `@register_parser` принимает список строк — это ключи, по которым устройство ищется в реестре. Поле `model` от API сравнивается с этими ключами без учёта регистра.
`@register_parser` accepts a string or a list of strings. These values are the
registry keys used to match the Oxidized node `model` field. Matching is
case-insensitive.
После добавления файла он автоматически импортируется через `pkgutil` при старте приложения — явно импортировать не нужно.
Model modules are imported automatically through `pkgutil` when
`oxi.interfaces` is loaded, so you do not need to import your model class
manually.
---
## Переопределение методов (monkey patching)
## Method Overrides
### interfaces()
Используйте переопределение, когда нужно:
Override `interfaces()` when you need to:
- Преобразовать формат IP-адреса (например, `netmask``prefix_length`).
- Декодировать escape-последовательности в описаниях.
- Переименовать ключи, не совпадающие с контрактом.
- Фильтровать служебные интерфейсы.
- Convert dotted decimal netmasks to prefix lengths.
- Decode escaped descriptions.
- Rename keys that do not match the contract.
- Filter service-only interfaces.
**Пример: конвертация маски подсети в префикс**
TTP возвращает `netmask` как `255.255.255.0`, а контракт `Interfaces` ожидает `mask` как целое число (prefix length):
Example: convert a netmask to a prefix length.
```python
from ipaddress import ip_interface
@@ -114,19 +115,17 @@ class MyVendor(BaseDevice):
return result
```
**Пример: фильтрация служебных интерфейсов**
Example: filter management interfaces.
```python
def interfaces(self) -> list[dict]:
return [
item for item in self.raw.get("interfaces", [])
if not item.get("name", "").startswith("lo")
if not item.get("interface", "").startswith("Mgmt")
]
```
**Пример: декодирование Unicode escape-последовательностей**
Некоторые устройства (например, Keenetic) хранят кириллические описания как `\xd0\xb8\xd0\xbc\xd1\x8f`:
Example: decode escaped UTF-8 descriptions.
```python
def _decode_utf(self, text: str) -> str:
@@ -140,6 +139,7 @@ def _decode_utf(self, text: str) -> str:
)
return text
def interfaces(self) -> list[dict]:
interfaces = self.raw.get("interfaces", [])
for item in interfaces:
@@ -148,75 +148,83 @@ def interfaces(self) -> list[dict]:
return interfaces
```
---
### vlans()
Аналогично `interfaces()`. Используйте для нормализации ID, декодирования названий, обогащения данными из других секций.
Override `vlans()` to normalize VLAN IDs, expand compressed ranges, decode
names, or merge details from multiple template groups.
**Пример: добавление префикса к имени VLAN**
Example: add a generated VLAN name.
```python
def vlans(self) -> list[dict]:
result = []
for item in self.raw.get("vlans", []):
item["description"] = f"VLAN_{item.get('id', '?')}"
item["description"] = f"VLAN_{item.get('vlan_id', '?')}"
result.append(item)
return result
```
**Пример: объединение данных из нескольких секций**
Example: merge data from another raw group.
```python
def vlans(self) -> list[dict]:
vlans = {v["id"]: v for v in self.raw.get("vlans", [])}
# обогащаем данными из другой секции, если она есть
vlans = {item["vlan_id"]: item for item in self.raw.get("vlans", [])}
for extra in self.raw.get("vlan_details", []):
vlan_id = extra.get("id")
vlan_id = extra.get("vlan_id")
if vlan_id in vlans:
vlans[vlan_id].update(extra)
return list(vlans.values())
```
---
Example: expand a comma-separated VLAN range.
```python
def _expand_vlan_range(value: str) -> list[str]:
result = []
for part in value.split(","):
if "-" not in part:
result.append(part.strip())
continue
start, end = (int(item) for item in part.split("-", 1))
result.extend(str(vlan_id) for vlan_id in range(start, end + 1))
return result
```
### system()
Переопределяйте, если структура системной секции отличается от ожидаемой контрактом, или нужно вычислить поля:
Override `system()` when the system section needs computed fields or data from
another raw group.
**Пример: собрать серийный номер из нескольких полей**
Example: assemble a serial number from two fields.
```python
def system(self) -> dict:
raw_system = self.raw.get("system", {})
# Устройство возвращает серийный номер в двух частях
part1 = raw_system.get("serial_part1", "")
part2 = raw_system.get("serial_part2", "")
raw_system["serial_number"] = f"{part1}-{part2}"
return raw_system
```
**Пример: нормализация строки версии**
Example: normalize a version string.
```python
def system(self) -> dict:
raw_system = self.raw.get("system", {})
# Убираем лишнее из "7.12.1 (stable)" → "7.12.1"
version = raw_system.get("version", "")
raw_system["version"] = version.split()[0] if version else version
return raw_system
```
---
## Complete Example
## Полный пример: новое устройство
Assume a Cisco IOS-like device where:
Допустим, нужно добавить поддержку Cisco IOS, где:
- IP-адрес и маска разделены пробелом в конфигурации (`ip address 10.0.0.1 255.255.255.0`).
- Описание интерфейса может содержать несколько слов.
- Серийный номер разделён дефисом в двух строках.
- IP address and netmask are separated by a space.
- Interface descriptions can contain several words.
- System fields are present in separate lines.
**Шаблон** (`oxi/interfaces/models/templates/cisco.ttp`):
Template: `oxi/interfaces/models/templates/cisco.ttp`
```xml
<vars>
@@ -240,12 +248,12 @@ interface {{ interface | _start_ }}
</group>
<group name="vlans">
vlan {{ id | _start_ }}
name {{ description }}
vlan {{ vlan_id | _start_ }}
name {{ name | ORPHRASE }}
</group>
```
**Класс устройства** (`oxi/interfaces/models/cisco.py`):
Device model: `oxi/interfaces/models/cisco.py`
```python
from ipaddress import ip_interface
@@ -260,12 +268,10 @@ class CiscoIOS(BaseDevice):
def interfaces(self) -> list[dict]:
result = []
for item in self.raw.get("interfaces", []):
# Конвертируем маску подсети в длину префикса
if item.get("ip_address") and item.get("netmask"):
iface = ip_interface(f"{item['ip_address']}/{item['netmask']}")
item["mask"] = iface.network.prefixlen
item.pop("netmask", None)
# Фильтруем интерфейсы управления
if item.get("interface", "").startswith("Mgmt"):
continue
result.append(item)
@@ -273,53 +279,48 @@ class CiscoIOS(BaseDevice):
def system(self) -> dict:
raw_system = self.raw.get("system", {})
# Нормализуем версию: "15.2(4)M3" → оставляем как есть
# Убираем лишние пробелы в модели
if raw_system.get("model"):
raw_system["model"] = raw_system["model"].strip()
return raw_system
```
---
## Expected Contract
## Контракт: ожидаемые структуры
Methods must return structures accepted by `oxi.interfaces.contract`.
Методы должны возвращать данные в следующем формате. Контракт жёстко проверяется Pydantic.
### `system()` → `dict`
### `system() -> dict`
```python
{
"model": "RB951Ui-2nD", # str, обязательно
"serial_number": "B88C0B31117B", # str, обязательно
"version": "7.12.1", # str, обязательно
"model": "RB951Ui-2nD",
"serial_number": "B88C0B31117B",
"version": "7.12.1",
}
```
### `interfaces()` → `list[dict]`
### `interfaces() -> list[dict]`
```python
[
{
"interface": "ether1", # str, обязательно (alias для поля name)
"ip_address": "192.168.1.1", # str | None
"mask": 24, # int | None (длина префикса)
"description": "LAN", # str | None
"interface": "ether1",
"ip_address": "192.168.1.1",
"mask": 24,
"description": "LAN",
},
...
]
```
### `vlans()` → `list[dict]`
### `vlans() -> list[dict]`
```python
[
{
"id": 10, # int, обязательно (alias для поля vlan_id)
"description": "MGMT", # str | None (alias для поля name)
"vlan_id": 10,
"description": "MGMT",
},
...
]
```
> Если имя ключа в словаре совпадает с **alias** поля Pydantic-модели, а не с именем атрибута — используйте alias. Модели сконфигурированы с `populate_by_name=True`, поэтому принимаются оба варианта.
The Pydantic models use `populate_by_name=True` for aliased models, so both
field names and aliases are accepted where aliases exist.

View File

@@ -1,86 +1,86 @@
# Написание TTP-шаблонов
# Writing TTP Templates
oxipy использует библиотеку [TTP (Template Text Parser)](https://ttp.readthedocs.io/) для парсинга конфигураций сетевых устройств в структурированные данные. Шаблоны хранятся в директории `oxi/interfaces/models/templates/`.
`oxipy` uses [TTP (Template Text Parser)](https://ttp.readthedocs.io/) to turn
network device configurations fetched from Oxidized into structured data.
Templates are stored in `oxi/interfaces/models/templates/`.
## Содержание
## Contents
- [Структура шаблона](#структура-шаблона)
- [Обязательные группы](#обязательные-группы)
- [Секция system](#секция-system)
- [Секция interfaces](#секция-interfaces)
- [Секция vlans](#секция-vlans)
- [TTP: основные возможности](#ttp-основные-возможности)
- [Переменные по умолчанию](#переменные-по-умолчанию)
- [Практические примеры](#практические-примеры)
- [Валидация шаблона](#валидация-шаблона)
- [Template Structure](#template-structure)
- [Required Groups](#required-groups)
- [The system Group](#the-system-group)
- [The interfaces Group](#the-interfaces-group)
- [The vlans Group](#the-vlans-group)
- [Useful TTP Features](#useful-ttp-features)
- [Default Variables](#default-variables)
- [Full Example](#full-example)
- [Validation](#validation)
---
## Template Structure
## Структура шаблона
Каждый шаблон — это `.ttp`-файл, состоящий из следующих блоков:
Each template is a `.ttp` file with a small set of conventional blocks:
```xml
<doc>
Описание шаблона (опционально)
Optional template documentation.
</doc>
<vars>
<!-- Переменные по умолчанию для групп -->
<!-- Default values for groups. -->
</vars>
<group name="system">
<!-- Правила для системной информации -->
<!-- Rules for system information. -->
</group>
<group name="interfaces">
<!-- Правила для интерфейсов -->
<!-- Rules for interfaces. -->
</group>
<group name="vlans">
<!-- Правила для VLAN (опционально) -->
<!-- Optional rules for VLANs. -->
</group>
```
Файл-заготовка находится в `oxi/interfaces/models/templates/_template.ttp`.
Use `oxi/interfaces/models/templates/_template.ttp` as the starting point for a
new parser.
---
## Required Groups
## Обязательные группы
The framework requires two groups in every template:
Фреймворк требует наличия в шаблоне **двух обязательных групп**:
| Group | Required | Description |
| --- | --- | --- |
| `system` | Yes | Device system information. |
| `interfaces` | Yes | Interface configuration. |
| `vlans` | No | VLAN configuration. |
| Группа | Обязательна | Описание |
|--------------|-------------|-------------------------------|
| `system` | Да | Системная информация |
| `interfaces` | Да | Конфигурация интерфейсов |
| `vlans` | Нет | Конфигурация VLAN |
If a required group is missing from the template or from the TTP result,
`BaseDevice` raises `ValueError`.
Если обязательная группа отсутствует в шаблоне или TTP не вернул её данные, будет выброшено `ValueError`.
If a template declares an optional `vlans` group, `oxipy` expects TTP to return
that group. Omit the group completely for devices where VLAN parsing is not
implemented.
---
## The system Group
## Секция system
The `system` group must return one dictionary with these fields:
Должна возвращать словарь со следующими полями:
| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `model` | `str` | Yes | Device model. |
| `serial_number` | `str` | Yes | Device serial number. |
| `version` | `str` | Yes | Firmware, software, or build version chosen by the parser. |
| Поле | Тип | Обязательное | Описание |
|-----------------|------|--------------|---------------------|
| `model` | str | Да | Модель устройства |
| `serial_number` | str | Да | Серийный номер |
| `version` | str | Да | Версия прошивки |
Example for MikroTik:
**Пример (MikroTik):**
Конфигурация:
```
```text
# version: 7.12.1 (stable)
# model = RB951Ui-2nD
# serial number = B88C0B31117B
```
Шаблон:
```
```xml
<group name="system">
# version: {{ version }}{{ ignore('.*') }}
# model = {{ model }}
@@ -88,17 +88,15 @@ oxipy использует библиотеку [TTP (Template Text Parser)](htt
</group>
```
**Пример (Keenetic):**
Example for Keenetic:
Конфигурация:
```
```text
! release: 4.1.7.1-1
! model: Keenetic Extra
! hw_version: F02B4E7A1C90
```
Шаблон:
```
```xml
<group name="system">
! release: {{ version }}
! model: {{ model | ORPHRASE }}
@@ -106,34 +104,34 @@ oxipy использует библиотеку [TTP (Template Text Parser)](htt
</group>
```
---
## The interfaces Group
## Секция interfaces
The `interfaces` group must return a list of dictionaries. Each dictionary
describes one interface.
Должна возвращать список словарей. Каждый словарь описывает один интерфейс.
The `Interfaces` contract expects these fields:
Поля, которые ожидает контракт `Interfaces`:
| Contract field | TTP name / alias | Type | Required |
| --- | --- | --- | --- |
| `name` | `interface` | `str` | Yes |
| `ip_address` | `ip_address` | `IPv4Address | None` | No |
| `mask` | `mask` | `int | None` | No |
| `description` | `description` | `str | None` | No |
| Поле | TTP-имя / alias | Тип | Обязательное |
|---------------|-----------------|------------------|--------------|
| `name` | `interface` | str | Да |
| `ip_address` | `ip_address` | IPv4Address | Нет |
| `mask` | `mask` | int (prefix len) | Нет |
| `description` | `description` | str | Нет |
The Pydantic field `name` has the alias `interface`, so templates should usually
emit `interface`. You can also emit `name` because the models allow population
by field name, or you can normalize keys in the device class by overriding
`interfaces()`.
> **Важно:** поле `name` в Pydantic-модели имеет алиас `interface`, поэтому в шаблоне переменную нужно называть именно `interface` **или** переопределить метод `interfaces()` в классе модели (см. [Расширение моделей](extending-models.md)).
Example for MikroTik:
**Пример (MikroTik):**
Конфигурация:
```
```text
/ip address
add address=192.168.1.1/24 interface=ether1 network=192.168.1.0
add address=10.0.0.1/30 comment="WAN link" interface=ether2 network=10.0.0.0
```
Шаблон:
```
```xml
<group name="interfaces">
/ip address
add address={{ ip_address | _start_ }}/{{ mask }} interface={{ interface }} network={{ network }}
@@ -141,108 +139,104 @@ add address={{ ip_address | _start_ }}/{{ mask }} comment={{ description | ORPHR
</group>
```
**Пример (Keenetic):**
Example for CLI-style devices:
Конфигурация:
```
interface GigabitEthernet0/0
description "WAN"
ip address 10.0.0.2 255.255.255.252
interface GigabitEthernet0/1
ip address 192.168.1.1 255.255.255.0
```text
interface Vlanif120
description SSH
ip address 10.26.196.254 255.255.255.0
```
Шаблон:
```
```xml
<group name="interfaces">
interface {{ name | _start_ | exclude("Vlan") }}
description {{ description | ORPHRASE }}
ip address {{ ip_address }} {{ netmask }}
interface {{ interface | _start_ }}
description {{ description | ORPHRASE }}
ip address {{ ip_address }} {{ mask | to_cidr }}
</group>
```
Здесь переменная называется `name`, а не `interface` — это покрывается переопределением метода `interfaces()` в классе `Keenetic`.
Use TTP's `to_cidr` formatter when the device uses dotted decimal masks.
---
## The vlans Group
## Секция vlans
The `vlans` group is optional. If it is declared, it must return a list of VLAN
dictionaries.
Необязательная группа. Если объявлена в шаблоне, фреймворк ожидает её наличия в результате TTP.
The `Vlans` contract expects these fields:
Поля контракта `Vlans`:
| Contract field | Alias | Type | Required |
| --- | --- | --- | --- |
| `vlan_id` | none | `int` | Yes |
| `name` | `description` | `str | None` | No |
| Поле | TTP-имя / alias | Тип | Обязательное |
|-----------|-----------------|------|--------------|
| `vlan_id` | `id` | int | Да |
| `name` | `description` | str | Нет |
`name` has the alias `description`, so either key is accepted. Existing parsers
use both forms depending on the vendor format.
> `vlan_id` имеет алиас `id`, поэтому в шаблоне переменная должна называться `id` либо переименовываться в методе `vlans()`.
Example:
**Пример (Keenetic):**
Конфигурация:
```
interface Bridge0/Vlan10
description "MGMT"
interface Bridge0/Vlan20
description "SERVERS"
```text
vlan 10
name MGMT
```
Шаблон:
```
```xml
<group name="vlans">
interface {{ ignore }}/Vlan{{ id }}
description {{ description | ORPHRASE | strip('"') }}
vlan {{ vlan_id | _start_ }}
name {{ name | ORPHRASE }}
</group>
```
---
For compressed vendor syntax such as `vlan batch 101 to 103 110`, parse the raw
range in the template and normalize it in the device class when needed.
## TTP: основные возможности
## Useful TTP Features
### Маркеры строк
### Line markers
| Маркер | Описание |
|-------------|---------------------------------------------------------------|
| `_start_` | Строка с этой переменной считается началом нового совпадения |
| `_end_` | Строка с этой переменной завершает совпадение группы |
| Marker | Description |
| --- | --- |
| `_start_` | Starts a new group match from the current line. |
| `_end_` | Ends the current group match. |
```
add address={{ ip_address | _start_ }}/{{ mask }} interface={{ name }}
```xml
interface {{ interface | _start_ }}
```
### Модификаторы переменных
### Variable modifiers
| Модификатор | Описание |
|------------------------|-----------------------------------------------------------|
| `ORPHRASE` | Захватывает одно слово или фразу (до конца строки) |
| `exclude("pattern")` | Пропускает строку, если захваченное значение содержит паттерн |
| `strip('"')` | Удаляет символ из начала и конца захваченного значения |
| `replace("old","new")` | Заменяет подстроку в захваченном значении |
| `re("pattern")` | Принимает значение, только если оно соответствует regex |
| `ignore` | Захватывает, но игнорирует значение (не включает в результат) |
| `ignore('.*')` | Игнорирует всё до конца строки |
| Modifier | Description |
| --- | --- |
| `ORPHRASE` | Captures a word or phrase to the end of the line. |
| `exclude("pattern")` | Skips the match when the captured value contains the pattern. |
| `strip('"')` | Removes a character from both ends of the captured value. |
| `replace("old","new")` | Replaces text inside the captured value. |
| `re("pattern")` | Accepts the value only if it matches the regex. |
| `ignore` | Captures and discards the value. |
| `ignore('.*')` | Discards the rest of the line. |
| `to_cidr` | Converts a dotted decimal netmask to a prefix length. |
| `unrange("-", ",")` | Expands ranges such as `10-12` using a comma separator. |
| `split(",")` | Splits a captured string into a list. |
### Комментарии в шаблоне
### Template comments
Строки, начинающиеся с `##`, — это комментарии TTP и не влияют на парсинг:
Lines beginning with `##` are TTP comments:
```
```xml
## disabled no comment
add address={{ ip_address | _start_ }}/{{ mask }} interface={{ name }}
add address={{ ip_address | _start_ }}/{{ mask }} interface={{ interface }}
```
---
## Default Variables
## Переменные по умолчанию
Блок `<vars>` позволяет задавать значения по умолчанию для группы через атрибут `default`:
The `<vars>` block can define default values for a group through the group's
`default` attribute:
```xml
<vars>
default_system = {
"model": "",
"serial_number": ""
"serial_number": "",
"version": ""
}
</vars>
@@ -253,17 +247,16 @@ default_system = {
</group>
```
Если шаблон не нашёл совпадений для группы, будет возвращён словарь из `default_system`.
If the group does not match anything, TTP returns the default dictionary.
---
## Full Example
## Практические примеры
### Полный шаблон для нового устройства (пример: Cisco IOS)
This simplified Cisco IOS-style example shows the expected shape of a complete
template:
```xml
<doc>
Шаблон для парсинга Cisco IOS running-config
Cisco IOS running-config parser.
</doc>
<vars>
@@ -283,24 +276,24 @@ System serial number : {{ serial_number }}
<group name="interfaces">
interface {{ interface | _start_ }}
description {{ description | ORPHRASE }}
ip address {{ ip_address }} {{ netmask }}
shutdown {{ shutdown | set("True") }}
ip address {{ ip_address }} {{ mask | to_cidr }}
</group>
<group name="vlans">
vlan {{ id | _start_ }}
name {{ description }}
vlan {{ vlan_id | _start_ }}
name {{ name | ORPHRASE }}
</group>
```
---
## Validation
## Валидация шаблона
`BaseDevice` performs two validation passes:
Фреймворк автоматически выполняет два уровня проверки:
1. Template structure validation checks that the template declares the required
`system` and `interfaces` groups.
2. Parse result validation checks that TTP actually returned the required groups
for the given configuration.
1. **Валидация структуры шаблона** — при создании объекта устройства парсятся XML-теги `<group>` и проверяется наличие обязательных секций (`system`, `interfaces`).
2. **Валидация результата парсинга** — после запуска TTP проверяется, что обязательные группы действительно присутствуют в результате (т.е. конфигурация содержала соответствующие строки).
При нарушении любого условия выбрасывается `ValueError` с подробным описанием проблемы.
After that, parsed data is validated by Pydantic models from
`oxi.interfaces.contract`. Invalid structures raise the original Pydantic
validation error.