Generalize OCI device setup and remove unused catalog hashes

This commit is contained in:
MacRimi
2026-09-26 01:22:37 +02:00
parent 88acceb8ef
commit f7266e7b44
26 changed files with 689 additions and 487 deletions
+58
View File
@@ -5,6 +5,7 @@ import sys
import tempfile
import unittest
from unittest.mock import patch
from subprocess import CompletedProcess
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'remote'))
@@ -35,6 +36,63 @@ class MountTests(unittest.TestCase):
class ProposalTests(unittest.TestCase):
def test_note_only_comparison_keeps_other_lxc_settings_strict(self):
marker = '11111111-1111-1111-1111-111111111111'
before = f'description: Old proxmenux-instance={marker}\ncores: 2\n'.encode()
record = {'installation_id': marker, 'observed': {'config': before.decode()}}
updated = f'description: New proxmenux-instance={marker}\ncores: 2\n'.encode()
self.assertTrue(reconcile.instances.same_config_except_notes(record, updated))
self.assertFalse(reconcile.instances.same_config_except_notes(record, updated.replace(b'cores: 2', b'cores: 4')))
self.assertFalse(reconcile.instances.same_config_except_notes(record, b'description: Other instance\ncores: 2\n'))
def test_replacement_restores_user_notes_verbatim(self):
marker = '11111111-1111-1111-1111-111111111111'
notes = f'<p>Nota personal: no borrar</p><!-- proxmenux-instance={marker} -->'
state = {'record': {'installation_id': marker}, 'original_description': notes}
with patch.object(reconcile.transaction, 'run') as run:
reconcile.transaction.restore_description(200, state)
run.assert_called_once_with('pct', 'set', '200', '--description', notes)
state.pop('original_description')
state['before_config'] = f'description: {notes.replace("%", "%25").replace("<", "%3C").replace(">", "%3E")}\n'
self.assertEqual(reconcile.transaction.original_description(state), notes)
def test_restoring_notes_does_not_log_their_contents(self):
notes = '<p>Nota privada del usuario</p>'
with (patch.object(reconcile.transaction, 'log') as log,
patch.object(reconcile.transaction.subprocess, 'run',
return_value=CompletedProcess([], 0, b'', b'')) as command):
reconcile.transaction.run('pct', 'set', '200', '--description', notes)
command.assert_called_once()
self.assertNotIn(notes, str(log.call_args))
def test_notes_only_change_does_not_require_adoption_or_block_update(self):
marker = '11111111-1111-1111-1111-111111111111'
config = f'description: Old notes proxmenux-instance={marker}\n'.encode()
updated = f'description: New notes proxmenux-instance={marker}\n'.encode()
record = {
'vmid': 200, 'status': 'installed', 'installation_id': marker,
'deployment': {'mounts': [], 'devices': []},
'observed': {'config': config.decode(), 'config_sha256': sha(config)},
}
self.assertIsNone(reconcile.propose(record, updated))
self.assertEqual(reconcile.transaction.external_changes(record, updated), {})
def test_notes_cannot_hide_identity_or_network_changes(self):
marker = '11111111-1111-1111-1111-111111111111'
config = f'description: Old notes proxmenux-instance={marker}\n'.encode()
record = {
'vmid': 200, 'status': 'installed', 'installation_id': marker,
'deployment': {'mounts': [], 'devices': []},
'observed': {'config': config.decode(), 'config_sha256': sha(config)},
}
with self.assertRaises(ValueError):
reconcile.propose(record, b'description: Different instance\n')
changed = f'description: New notes proxmenux-instance={marker}\nnet0: name=eth0,bridge=vmbr1\n'.encode()
with self.assertRaises(ValueError):
reconcile.propose(record, changed)
with self.assertRaises(ValueError):
reconcile.transaction.external_changes(record, changed)
def test_new_volume_requires_confirmation_before_contract_changes(self):
config = b'description: proxmenux-instance=11111111-1111-1111-1111-111111111111\n'
added = config + b'mp2: local-lvm:vm-200-disk-3,mp=/media,size=8G,backup=1\n'
+11
View File
@@ -29,10 +29,13 @@ class DescriptionTests(unittest.TestCase):
self.assertIn('Image: <code>adguard/adguardhome:latest</code> ', notes)
self.assertIn('>Image</a> &middot; ', notes)
self.assertIn('>App</a>', notes)
self.assertNotIn('>App docs</a>', notes)
self.assertNotIn('>Repository</a>', notes)
self.assertIn('href="http://192.168.0.42:3000/" target="_blank" rel="noopener noreferrer">Setup (first run)</a>', notes)
self.assertIn('>http://192.168.0.42:3000/</a>', notes)
self.assertIn('href="http://192.168.0.42:80/" target="_blank" rel="noopener noreferrer">Web UI (after setup)</a>', notes)
self.assertIn('>http://192.168.0.42:80/</a>', notes)
self.assertEqual(notes.count('&#127760; '), 2)
def test_missing_ip_does_not_publish_placeholder_links(self):
template = json.loads((CATALOG / 'adguard-home.json').read_text())
@@ -40,6 +43,14 @@ class DescriptionTests(unittest.TestCase):
self.assertNotIn('http://:3000', notes)
self.assertIn('proxmenux-instance=' + INSTANCE, notes)
def test_chromium_notes_keep_only_image_and_app_links(self):
template = json.loads((CATALOG / 'chromium.json').read_text())
notes = render(template, '', INSTANCE, '192.168.0.37')
self.assertIn('>Image</a>', notes)
self.assertIn('>App</a>', notes)
self.assertNotIn('>App docs</a>', notes)
self.assertNotIn('>Repository</a>', notes)
def test_untrusted_title_is_escaped(self):
template = {'id': 'example', 'catalog_ui': {'title': {'en_US': '<script>x</script>'}},
'container_contract': {'image': {'reference': 'example:latest'}}}
+69
View File
@@ -0,0 +1,69 @@
"""Regression tests for catalog options added after an OCI installation."""
import copy
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'src'))
from proxmenux_oci.catalog import Catalog
from proxmenux_oci.recreation import refresh_template
class ConfirmingUI:
def confirm(self, _message, _default=False):
return True
def info(self, _message):
pass
def ask(self, _message, default=''):
return default
class RecreationCatalogTests(unittest.TestCase):
def test_catalog_index_has_no_unused_template_hashes(self):
applications = Catalog(ROOT).load_index()['applications']
self.assertTrue(applications)
self.assertTrue(all('content_hash' not in item for item in applications))
def test_internal_template_id_resolves_current_catalog_template(self):
catalog = Catalog(ROOT)
previous = catalog.load_template('chromium', generate_if_missing=False)
self.assertEqual(previous['id'], 'linuxserver-chromium')
previous = copy.deepcopy(previous)
previous['catalog_ui']['title']['en_US'] = 'Old Chromium'
candidate = {'template': previous, 'deployment': {
'rootfs': {'storage': 'local-lvm'},
'mounts': [{'container_path': '/config'}],
'environment': [{'name': item['name'], 'value': item.get('example') or 'value',
'sensitive': item['sensitive']}
for item in previous['container_contract']['environment']
if item['required']],
'security': {},
}}
refresh_template(candidate, ConfirmingUI())
self.assertEqual(candidate['template']['catalog_ui']['title']['en_US'],
catalog.compose('chromium')['catalog_ui']['title']['en_US'])
def test_navidrome_baseurl_is_optional(self):
catalog = Catalog(ROOT)
template = catalog.compose('navidrome')
base_url = next(item for item in template['container_contract']['environment']
if item['name'] == 'ND_BASEURL')
self.assertFalse(base_url['required'])
self.assertEqual(base_url['example'], '')
regenerated = copy.deepcopy(template)
target = next(item for item in regenerated['container_contract']['environment']
if item['name'] == 'ND_BASEURL')
target['required'] = True
catalog._preserve_optional_environment('navidrome', regenerated)
self.assertFalse(target['required'])
if __name__ == '__main__':
unittest.main()
+104
View File
@@ -0,0 +1,104 @@
"""Shared wizard navigation and device choices do not depend on app overlays."""
from pathlib import Path
import sys
import unittest
from unittest.mock import patch
from subprocess import CompletedProcess
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'src'))
from proxmenux_oci.extra_devices import (ask_extra_devices, ask_stack_extra_devices,
device_permissions)
from proxmenux_oci.ui import BackRequested, BacktrackUI, DialogUI, RestartWizard
class SequenceUI:
def __init__(self, answers):
self.answers = iter(answers)
self.back_enabled = False
def ask(self, *_args, **_kwargs):
result = next(self.answers)
if result == 'back':
raise BackRequested()
return result
def confirm(self, *_args, **_kwargs):
return next(self.answers)
def choose(self, *_args, **_kwargs):
return next(self.answers)
def checklist(self, *_args, **_kwargs):
return next(self.answers)
def info(self, _text):
pass
class WizardTests(unittest.TestCase):
def test_back_returns_to_previous_answer_without_reasking_first(self):
base = SequenceUI(['first', 'second', 'back', 'corrected', 'third'])
wizard = BacktrackUI(base)
try:
self.assertEqual(wizard.ask('first'), 'first')
self.assertEqual(wizard.ask('second'), 'second')
with self.assertRaises(RestartWizard):
wizard.ask('third')
wizard.restart()
self.assertEqual(wizard.ask('first'), 'first')
self.assertEqual(wizard.ask('second'), 'corrected')
self.assertEqual(wizard.ask('third'), 'third')
finally:
wizard.close()
self.assertFalse(base.back_enabled)
def test_back_from_review_reopens_last_question(self):
class ReviewUI(SequenceUI):
def review(self, *_args, **_kwargs):
raise BackRequested()
wizard = BacktrackUI(ReviewUI(['value', 'replacement']))
try:
self.assertEqual(wizard.ask('value'), 'value')
with self.assertRaises(RestartWizard):
wizard.review('summary')
wizard.restart()
self.assertEqual(wizard.ask('value'), 'replacement')
finally:
wizard.close()
def test_manual_usb_is_available_without_profile(self):
ui = SequenceUI([True, 'usb', '/dev/ttyACM0', False])
devices = ask_extra_devices(ui, [], True)
self.assertEqual(devices[0]['host_path'], '/dev/ttyACM0')
self.assertEqual(devices[0]['container_path'], '/dev/ttyACM0')
def test_linuxserver_device_permissions_are_generic(self):
permissions = device_permissions('lscr.io/linuxserver/chromium:latest',
[{'kind': 'character-device'}])
self.assertEqual(permissions['strategy'], 'linuxserver-native-init')
def test_stack_device_goes_only_to_selected_member(self):
ui = SequenceUI([True, 'usb', '/dev/ttyACM0', False, ['server']])
services = [
{'name': name, 'main': name == 'server',
'template': {'container_contract': {'image': {'reference': 'example/app:latest'}}},
'deployment': {'devices': [], 'security': {'unprivileged': True}}}
for name in ('database', 'server')
]
ask_stack_extra_devices(ui, services)
self.assertEqual(services[0]['deployment']['devices'], [])
self.assertEqual(services[1]['deployment']['devices'][0]['host_path'], '/dev/ttyACM0')
def test_dialog_back_button_is_only_on_wizard_inputs(self):
ui = DialogUI(back_enabled=True)
with patch('proxmenux_oci.ui.subprocess.run', return_value=CompletedProcess([], 3, '', '')) as run:
with self.assertRaises(BackRequested):
ui._run(['--inputbox', 'Name', '10', '50', ''])
self.assertIn('--extra-button', run.call_args.args[0])
if __name__ == '__main__':
unittest.main()