Publish Platina Linux source base for Xiaomi Mi 8 Lite

This commit is contained in:
Sukecz
2026-10-23 11:10:29 +02:00
commit b7eb4289b7
95 changed files with 275710 additions and 0 deletions
+47
View File
@@ -0,0 +1,47 @@
"""Verify the Tianma candidate matches the retained stock initialization data."""
import json
from pathlib import Path
import re
import unittest
ROOT = Path(__file__).resolve().parents[1]
class DisplayCandidateTests(unittest.TestCase):
def test_init_packets_and_delays_match_stock_panel(self):
reference = json.loads((ROOT / 'project/display/tianma-reference.json').read_text())
raw = bytes.fromhex(reference['on_command_hex'])
expected = []
offset = 0
while offset < len(raw):
header = raw[offset:offset + 7]
size = int.from_bytes(header[5:7], 'big')
payload = raw[offset + 7:offset + 7 + size]
self.assertEqual(len(payload), size)
# Downstream encodes a dummy second byte for DCS no-param packets.
if header[0] == 0x05:
self.assertEqual(payload[1:], b'\0')
payload = payload[:1]
expected.append(('generic' if header[0] == 0x29 else 'dcs', payload))
if header[4]:
expected.append(('delay', header[4]))
offset += 7 + size
self.assertEqual(offset, len(raw))
patch = (ROOT / 'ports/candidate/linux-postmarketos-qcom-sdm660/0030-platina-tianma-panel.patch').read_text()
added = '\n'.join(line[1:] for line in patch.splitlines()
if line.startswith('+') and not line.startswith('+++'))
init = added.split('static void platina_tianma_init_cmds', 1)[1].split('\n}', 1)[0]
actual = []
for line in init.splitlines():
write = re.search(r'mipi_dsi_(generic|dcs)_write_seq_multi\(dsi_ctx, (.*?)\);', line)
delay = re.search(r'mipi_dsi_msleep\(dsi_ctx, (\d+)\);', line)
if write:
actual.append((write[1], bytes(int(v.strip(), 16) for v in write[2].split(','))))
elif delay:
actual.append(('delay', int(delay[1])))
self.assertEqual(len([v for v in expected if v[0] != 'delay']), 180)
self.assertEqual(actual, expected)
if __name__ == '__main__':
unittest.main()
+91
View File
@@ -0,0 +1,91 @@
"""Offline power-order, cleanup and image roundtrip tests for the native panel path."""
import importlib.util
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch, MagicMock, call
ROOT = Path(__file__).resolve().parents[1]
def load(name, script):
spec = importlib.util.spec_from_file_location(name, ROOT / 'scripts' / script)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
control = load('display_control', 'phone-display.py')
splash = load('display_splash', 'phone-splash.py')
class ControlTests(unittest.TestCase):
def test_powerdown_clears_backlight_before_drm(self):
events = MagicMock()
with patch.object(control, 'brightness', events.brightness), \
patch.object(control.fcntl, 'ioctl', events.ioctl):
control.off(12)
self.assertEqual(events.mock_calls, [call.brightness(0), call.ioctl(12, control.FBIOBLANK, 4)])
def test_renderer_failure_still_powers_down(self):
helper = {'load_frame': lambda _: ({'version': '0.1.1'}, b'frame'),
'geometry': MagicMock(side_effect=ValueError('bad framebuffer'))}
with patch.object(control.runpy, 'run_path', return_value=helper), \
patch.object(control, 'Path') as path, \
patch.object(control.fcntl, 'ioctl'), \
patch.object(control, 'off') as off:
path.return_value.read_text.return_value = 'boot-id'
with self.assertRaisesRegex(ValueError, 'bad framebuffer'):
control.show(12, ROOT, 1, 25)
off.assert_called_once_with(12)
def test_brightness_scales_and_zero_is_exact(self):
with tempfile.TemporaryDirectory() as temp, patch.object(control, 'BACKLIGHT', Path(temp)):
(Path(temp) / 'max_brightness').write_text('4095')
for percent, expected in [(0, 0), (1, 40), (25, 1023), (100, 4095)]:
control.brightness(percent)
self.assertEqual(int((Path(temp) / 'brightness').read_text()), expected)
with self.assertRaises(ValueError):
control.brightness(101)
def test_old_driver_rejected_before_any_device_changes(self):
with patch.object(control, 'Path') as path, patch.object(control, 'DRIVER') as driver:
path.return_value.read_bytes.return_value = b'xiaomi,platina\0'
driver.resolve.return_value.name = 'panel-simple-dsi'
with self.assertRaisesRegex(ValueError, 'Integrated Tianma'):
control.validate()
def test_status_never_opens_framebuffer(self):
with patch.object(control.os, 'open', side_effect=AssertionError('device opened')), \
patch.object(control, 'Path') as path, \
patch.object(control, 'DRIVER') as driver, \
patch.object(control, 'BACKLIGHT') as backlight:
path.return_value.exists.return_value = False
driver.exists.return_value = False
backlight.__truediv__.return_value.exists.return_value = False
self.assertIsNone(control.status()['driver'])
def test_custom_frame_roundtrip(self):
try:
from PIL import Image
except ImportError:
self.skipTest('Host-only image preparation needs Pillow')
frame = load('prepare_frame', 'prepare-display-frame.py')
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
source = root / 'image.png'
Image.new('RGB', (100, 100), 'red').save(source)
output = frame.build(source, root / 'frame')
manifest, raw = splash.load_frame(output)
self.assertEqual(manifest['purpose'], 'custom-display-frame')
self.assertEqual(len(raw), 1080 * 2280 * 4)
self.assertEqual(raw[:4], b'\0\0\0\0') # black letterbox
center = (1140 * 1080 + 540) * 4
self.assertEqual(raw[center:center + 4], b'\0\0\xff\0')
with self.assertRaisesRegex(ValueError, 'immutable'):
frame.build(source, output)
if __name__ == '__main__':
unittest.main()
+47
View File
@@ -0,0 +1,47 @@
"""Verify rejection of bad DCS replies and cleanup on a failed renderer."""
import importlib.util
from pathlib import Path
import tempfile
import unittest
from unittest.mock import MagicMock, patch
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location('display_session', ROOT / 'scripts/phone-display-session.py')
session = importlib.util.module_from_spec(spec)
spec.loader.exec_module(session)
class DisplaySessionTests(unittest.TestCase):
def test_only_valid_awake_panel_is_accepted(self):
with tempfile.TemporaryDirectory() as temp:
params = Path(temp)
values = dict(io_enabled=1, read_result=1, wake_result=0, power_after=0x9c)
for name, value in values.items():
(params / name).write_text(str(value))
self.assertEqual(session.check_panel(params), values)
for field, bad in [('power_after', 0x08), ('read_result', -110),
('wake_result', -5), ('io_enabled', 0)]:
(params / field).write_text(str(bad))
with self.assertRaises(ValueError):
session.check_panel(params)
(params / field).write_text(str(values[field]))
def test_renderer_failure_still_releases_owned_power(self):
params = MagicMock()
params.exists.side_effect = [False, True]
fake_path = MagicMock()
with patch.object(session, 'PARAMS', params), \
patch.object(session, 'Path', return_value=fake_path), \
patch.object(session.fcntl, 'flock'), \
patch.object(session, 'validate', return_value='/verified/module.ko'), \
patch.object(session, 'check_panel', return_value={}), \
patch.object(session.subprocess, 'run') as run, \
patch.object(session.subprocess, 'Popen', side_effect=OSError('renderer unavailable')):
with self.assertRaises(OSError):
session.session(['--seconds', '7'])
self.assertEqual(run.call_args_list[-1].args[0], ['rmmod', 'platina_panel_dcs'])
fake_path.write_text.assert_called_once_with('0\n')
if __name__ == '__main__':
unittest.main()
+53
View File
@@ -0,0 +1,53 @@
"""Check deterministic local firmware packaging without distributing firmware payloads."""
import importlib.util
from pathlib import Path
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
def load(name, path):
spec = importlib.util.spec_from_file_location(name, ROOT / path)
result = importlib.util.module_from_spec(spec)
spec.loader.exec_module(result)
return result
firmware = load('prepare_firmware', 'scripts/prepare-firmware.py')
class FirmwarePackagingTests(unittest.TestCase):
def test_archive_does_not_depend_on_host_mtime(self):
import os
with tempfile.TemporaryDirectory() as temp:
path = Path(temp)
source = path / 'example'
source.write_bytes(b'fixture')
first = firmware.archive_files(path, 'modem')
os.utime(source, (1, 1))
self.assertEqual(first, firmware.archive_files(path, 'modem'))
def test_public_board_helper_indexes_aliases_and_rejects_empty_input(self):
relative = Path('ports/candidate/firmware-xiaomi-platina/gen-board-2.py')
overlay = Path('project/public/files') / relative
if (ROOT / overlay).exists():
relative = overlay
if not (ROOT / relative).exists():
self.skipTest('Public packaging helper is tested in the public export')
helper = load('board_index', relative)
with tempfile.TemporaryDirectory() as temp:
path = Path(temp)
with self.assertRaises(ValueError):
helper.index(path)
for name in ('bdwlan.bin', 'bdwlan.b33', 'bdwlan.102', 'bdwlan.unknown'):
(path / name).write_bytes(b'fixture')
indexed = {row['data']: row['names'] for row in helper.index(path)}
self.assertEqual(indexed['bdwlan.b33'], ['bus=snoc,qmi-board-id=33'])
self.assertEqual(indexed['bdwlan.102'], ['bus=snoc,qmi-board-id=102'])
self.assertEqual(indexed['bdwlan.bin'], ['bus=snoc', 'bus=snoc,qmi-board-id=ff', 'bus=snoc,qmi-board-id=0'])
self.assertNotIn('bdwlan.unknown', indexed)
if __name__ == '__main__':
unittest.main()
+74
View File
@@ -0,0 +1,74 @@
"""Protect kernel/cmdline identity and reject unsafe boot/archive inputs."""
import gzip
import hashlib
import importlib.util
from pathlib import Path
import stat
import struct
import unittest
from unittest.mock import patch
spec = importlib.util.spec_from_file_location('scope_initramfs', Path(__file__).resolve().parents[1] / 'scripts/scope-initramfs-modules.py')
scope = importlib.util.module_from_spec(spec)
spec.loader.exec_module(scope)
def boot_image(ramdisk=b'old ramdisk'):
kernel = b'kernel and appended device tree'
header = bytearray(4096)
header[:8] = b'ANDROID!'
struct.pack_into('<10I', header, 8, len(kernel), 32768, len(ramdisk), 16777216, 0, 15728640, 256, 4096, 0, 0)
cmdline = b'console=ttyMSM0'
header[64:64 + len(cmdline)] = cmdline
header[576:596] = hashlib.sha1(kernel + struct.pack('<I', len(kernel)) + ramdisk + struct.pack('<I', len(ramdisk)) + b'\0' * 4).digest()
return bytes(header) + kernel.ljust(4096, b'\0') + ramdisk.ljust((len(ramdisk) + 4095) // 4096 * 4096, b'\0')
class BootTests(unittest.TestCase):
def test_replacement_preserves_kernel_and_cmdline(self):
before = boot_image()
changed = scope.replace_ramdisk(before, b'new ramdisk' * 900)
kernel, ramdisk, _ = scope.parts(changed)
self.assertEqual(kernel, scope.parts(before)[0])
self.assertEqual(ramdisk, b'new ramdisk' * 900)
self.assertEqual(changed[64:576], before[64:576])
self.assertEqual(changed[608:1632], before[608:1632])
def test_corrupt_payload_rejected(self):
bad = bytearray(boot_image())
bad[4096] ^= 1
with self.assertRaisesRegex(ValueError, 'hash mismatch'):
scope.replace_ramdisk(bad, b'new')
def test_unknown_trailer_rejected(self):
with self.assertRaisesRegex(ValueError, 'trailer'):
scope.parts(boot_image() + b'unknown footer')
def test_unsupported_header_rejected(self):
bad = bytearray(boot_image())
struct.pack_into('<I', bad, 40, 4)
with self.assertRaisesRegex(ValueError, 'layout'):
scope.parts(bad)
def test_unsafe_archive_path_rejected(self):
record = ('../escape', [0, stat.S_IFREG | 0o600, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], b'data')
with self.assertRaisesRegex(ValueError, 'Unsafe'):
scope.unpack(scope.pack([record]))
def test_scoped_index_must_match_actual_modules(self):
prefix = 'lib/modules/7.2.12-sdm660/'
fields = [0, stat.S_IFREG | 0o644, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]
records = [(prefix + 'kernel/fixture.ko.zst', fields, b'fixture')]
boot = boot_image(gzip.compress(scope.pack(records)))
def wrong_index(command, **kwargs):
target = Path(command[4]) / 'lib/modules/7.2.12-sdm660'
(target / 'modules.dep').write_text('kernel/absent.ko.zst:\n')
with patch.object(scope.subprocess, 'run', side_effect=wrong_index):
with self.assertRaisesRegex(ValueError, 'differs'):
scope.scope(boot, '7.2.12-sdm660')
if __name__ == '__main__':
unittest.main()
+65
View File
@@ -0,0 +1,65 @@
"""Exercise public-index checks against accidentally staged local files and credentials."""
import contextlib
import importlib.util
import io
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location('public_tree', ROOT / 'scripts/check-public-tree.py')
public = importlib.util.module_from_spec(spec)
spec.loader.exec_module(public)
class PublicBoundaryTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
subprocess.run(['git', 'init', '-q', str(self.root)], check=True)
def stage(self, name, content='fixture\n'):
path = self.root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content)
subprocess.run(['git', '-C', str(self.root), 'add', '--', name], check=True)
def check(self):
with contextlib.redirect_stdout(io.StringIO()):
public.check(self.root)
def test_plain_source_is_allowed(self):
self.stage('scripts/example.py', 'print("hello")\n')
self.check()
def test_nested_agent_instructions_rejected(self):
self.stage('docs/AGENTS.md')
with self.assertRaisesRegex(ValueError, 'path'):
self.check()
def test_notes_and_configuration_rejected(self):
for name in ('notes.txt', 'config/phone.conf', 'backups/backup.md'):
with self.subTest(name=name):
self.stage(name)
with self.assertRaisesRegex(ValueError, 'path'):
self.check()
subprocess.run(['git', '-C', str(self.root), 'rm', '--cached', '-q', name], check=True)
def test_accidental_token_value_rejected_without_echoing_it(self):
value = 'ghp_' + 'x' * 36
self.stage('README.md', 'credential: ' + value)
with self.assertRaisesRegex(ValueError, 'suppressed') as caught:
self.check()
self.assertNotIn(value, str(caught.exception))
def test_external_symlink_rejected(self):
(self.root / 'external').symlink_to(self.root.parent / 'other')
subprocess.run(['git', '-C', str(self.root), 'add', '--', 'external'], check=True)
with self.assertRaisesRegex(ValueError, 'symlink'):
self.check()
if __name__ == '__main__':
unittest.main()
+97
View File
@@ -0,0 +1,97 @@
"""Offline checks for release versions, decoded assets and padded fbdev rows."""
import gzip
import hashlib
import importlib.util
import json
from pathlib import Path
import struct
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
def module(name, path):
spec = importlib.util.spec_from_file_location(name, ROOT / path)
result = importlib.util.module_from_spec(spec)
spec.loader.exec_module(result)
return result
release = module('platina_release', 'scripts/platina-release.py')
splash = module('platina_splash', 'scripts/phone-splash.py')
class VersionTests(unittest.TestCase):
def test_semantic_bumps(self):
self.assertEqual(release.next_version('0.1.9', 'patch'), '0.1.10')
self.assertEqual(release.next_version('0.1.9', 'minor'), '0.2.0')
self.assertEqual(release.next_version('0.1.9', 'major'), '1.0.0')
def test_bad_versions_rejected(self):
for value in ('01.2.3', '1.2', '../1.2.3', '1.2.3\n', '1.2.3;reboot'):
with self.subTest(value=value), self.assertRaises(ValueError):
release.version_tuple(value)
def test_canonical_identity(self):
self.assertEqual(release.load_release()['name'], 'Platina Linux')
class FramebufferTests(unittest.TestCase):
def layout(self):
variable = [0] * 40
variable[:7] = [1080, 2280, 1080, 4560, 0, 2280, 32]
variable[8:10], variable[11:13], variable[14:16] = [16, 8], [8, 8], [0, 8]
fixed = bytearray(80)
struct.pack_into('=I', fixed, 24, 4352 * 4560)
struct.pack_into('=I', fixed, 48, 4352)
return variable, fixed
def test_stride_and_virtual_page_offset(self):
variable, fixed = self.layout()
result = splash.geometry(struct.pack('=40I', *variable), fixed)
self.assertEqual(result, (1080, 2280, 4352, 4352 * 2280, 4352 * 4560))
def test_wrong_pixel_order_rejected(self):
variable, fixed = self.layout()
variable[8] = 0
with self.assertRaises(ValueError):
splash.geometry(struct.pack('=40I', *variable), fixed)
def test_too_small_mapping_rejected(self):
variable, fixed = self.layout()
struct.pack_into('=I', fixed, 24, 1024)
with self.assertRaises(ValueError):
splash.geometry(struct.pack('=40I', *variable), fixed)
def test_row_padding_and_outside_viewport_preserved(self):
target = bytearray(b'x' * 40)
splash.paint(target, b'abcdEFGH', (1, 2, 8, 8, 40))
self.assertEqual(target[8:12], b'abcd')
self.assertEqual(target[16:20], b'EFGH')
self.assertEqual(target[12:16], b'xxxx')
self.assertEqual(target[:8], b'x' * 8)
def test_real_bundle_valid_and_version_matches(self):
directory = ROOT / ('artifacts/platina-linux-' + release.load_release()['version'])
if not directory.exists():
self.skipTest('Local generated release bundle is not part of clean source checkouts')
manifest, raw = splash.load_frame(directory)
self.assertEqual(manifest['version'], release.load_release()['version'])
self.assertEqual(len(raw), 1080 * 2280 * 4)
def test_corrupt_frame_rejected_before_hardware_access(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
manifest = {'schema': 1, 'name': 'Platina Linux', 'display': {
'width': 1080, 'height': 2280, 'format': 'BGRX8888',
'frame': 'frame.bgrx.gz', 'raw_bytes': 1080 * 2280 * 4,
'compressed_sha256': '0' * 64, 'raw_sha256': '0' * 64}}
(root / 'release.json').write_text(json.dumps(manifest))
(root / 'frame.bgrx.gz').write_bytes(gzip.compress(b'wrong'))
with self.assertRaisesRegex(ValueError, 'checksum'):
splash.load_frame(root)
if __name__ == '__main__':
unittest.main()
+177
View File
@@ -0,0 +1,177 @@
"""Offline regression tests for artifact integrity and isolated build preparation."""
import contextlib
import hashlib
import importlib.util
import io
import json
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch
spec = importlib.util.spec_from_file_location('project_workflow', Path(__file__).resolve().parents[1] / 'scripts/project.py')
workflow = importlib.util.module_from_spec(spec)
spec.loader.exec_module(workflow)
class ArtifactTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.bundle = self.root / 'bundle'
self.bundle.mkdir()
self.payload = b'audited boot payload'
(self.bundle / 'boot.img').write_bytes(self.payload)
self.row = {'file': 'boot.img', 'bytes': len(self.payload),
'sha256': hashlib.sha256(self.payload).hexdigest()}
def verify(self, rows=None):
(self.bundle / 'manifest.json').write_text(json.dumps({'files': rows if rows is not None else [self.row]}))
with contextlib.redirect_stdout(io.StringIO()):
workflow.verify(self.bundle)
def test_valid_bundle(self):
self.verify()
def test_same_length_corruption(self):
(self.bundle / 'boot.img').write_bytes(b'X' * len(self.payload))
with self.assertRaisesRegex(ValueError, 'verification failed'):
self.verify()
def test_wrong_length(self):
self.row['bytes'] += 1
with self.assertRaisesRegex(ValueError, 'verification failed'):
self.verify()
def test_path_traversal(self):
self.row['file'] = '../boot.img'
with self.assertRaisesRegex(ValueError, 'Unsafe'):
self.verify()
def test_absolute_path(self):
self.row['file'] = str(self.bundle / 'boot.img')
with self.assertRaisesRegex(ValueError, 'Unsafe'):
self.verify()
def test_symlink(self):
(self.bundle / 'alias.img').symlink_to('boot.img')
self.row['file'] = 'alias.img'
with self.assertRaisesRegex(ValueError, 'symlink'):
self.verify()
def test_duplicate_files(self):
with self.assertRaisesRegex(ValueError, 'Duplicate'):
self.verify([self.row, self.row])
def test_empty_manifest(self):
with self.assertRaisesRegex(ValueError, 'nonempty'):
self.verify([])
def test_missing_file(self):
(self.bundle / 'boot.img').unlink()
with self.assertRaisesRegex(ValueError, 'Missing'):
self.verify()
class PrepareTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.patch = patch.object(workflow, 'ROOT', self.root)
self.patch.start()
self.addCleanup(self.patch.stop)
self.source = self.root / 'sources/pmaports-server'
self.source.mkdir(parents=True)
self.git('init', '-q')
(self.source / 'upstream.txt').write_text('original\n')
self.git('add', 'upstream.txt')
self.git('-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', 'commit', '-qm', 'fixture')
commit = self.git('rev-parse', 'HEAD').strip()
# Preserve both staged and unstaged edits, like the actual working source.
(self.source / 'upstream.txt').write_text('staged\n')
self.git('add', 'upstream.txt')
(self.source / 'upstream.txt').write_text('unstaged\n')
self.initial_index = self.git('diff', '--cached')
self.initial_work = self.git('diff')
(self.root / 'config/firmware').mkdir(parents=True)
(self.root / 'config/admin-test.pub').write_text('fixture public key\n')
(self.root / 'project').mkdir()
for name in workflow.RECIPES:
directory = self.root / 'ports/candidate' / name
directory.mkdir(parents=True)
(directory / 'input.txt').write_text(name)
checksum = workflow.digest(directory / 'input.txt', 'sha512')
(directory / 'APKBUILD').write_text('sha512sums="\n' + checksum + ' input.txt\n"\n')
blob = self.root / 'config/firmware/local.tar.gz'
blob.write_bytes(b'local fixture firmware')
recipe = self.root / 'ports/candidate/firmware-xiaomi-platina/APKBUILD'
recipe.write_text(recipe.read_text().replace('\n"\n', '\n' + workflow.digest(blob, 'sha512') + ' local.tar.gz\n"\n'))
data = {'schema': 1, 'repositories': {
'pmbootstrap': {'path': 'sources/pmaports-server', 'commit': commit, 'url': 'unused'},
'pmaports': {'commit': commit, 'channels_commit': commit, 'url': 'unused'}},
'profiles': {'candidate': {'ports': 'ports/candidate'}}, 'local_firmware': ['local.tar.gz']}
(self.root / 'project/sources.lock.json').write_text(json.dumps(data))
def git(self, *args):
return subprocess.check_output(['git', '-C', str(self.source), *args], text=True)
def test_prepare_preserves_existing_tree_and_generates_absolute_config(self):
with contextlib.redirect_stdout(io.StringIO()):
workflow.prepare('candidate', False)
self.assertEqual(self.git('diff', '--cached'), self.initial_index)
self.assertEqual(self.git('diff'), self.initial_work)
cfg = workflow.config_path('candidate').read_text()
self.assertIn(str(self.root / 'sources/pmaports-managed-candidate'), cfg)
self.assertIn(str(self.root / 'work/pmbootstrap-managed-candidate'), cfg)
self.assertEqual((self.root / 'sources/pmaports-managed-candidate/upstream.txt').read_text(), 'original\n')
managed = str(self.root / 'sources/pmaports-managed-candidate')
self.assertEqual(subprocess.check_output(['git', '-C', managed, 'remote', 'get-url', 'origin'], text=True).strip(), 'unused')
self.assertEqual(subprocess.check_output(['git', '-C', managed, 'rev-parse', 'origin/main'], text=True).strip(), self.git('rev-parse', 'HEAD').strip())
with self.assertRaisesRegex(ValueError, 'already exists'):
workflow.prepare('candidate', False)
def test_missing_blob_fails_before_checkout(self):
(self.root / 'config/firmware/local.tar.gz').unlink()
with self.assertRaisesRegex(ValueError, 'firmware'):
workflow.prepare('candidate', False)
self.assertFalse((self.root / 'sources/pmaports-managed-candidate').exists())
def test_changed_recipe_fails_before_checkout(self):
(self.root / 'ports/candidate/device-xiaomi-platina/input.txt').write_text('modified')
with self.assertRaisesRegex(ValueError, 'Recipe input'):
workflow.prepare('candidate', False)
self.assertFalse((self.root / 'sources/pmaports-managed-candidate').exists())
def test_sync_refuses_to_overwrite_local_edits(self):
with contextlib.redirect_stdout(io.StringIO()):
workflow.prepare('candidate', False)
target = self.root / 'sources/pmaports-managed-candidate/device/testing/device-xiaomi-platina/input.txt'
target.write_text('important local change')
with self.assertRaisesRegex(ValueError, 'edited locally'):
workflow.sync('candidate')
self.assertEqual(target.read_text(), 'important local change')
def test_sync_applies_verified_snapshot_change(self):
with contextlib.redirect_stdout(io.StringIO()):
workflow.prepare('candidate', False)
source = self.root / 'ports/candidate/device-xiaomi-platina/input.txt'
source.write_text('reviewed update')
(source.parent / 'APKBUILD').write_text('sha512sums="\n' + workflow.digest(source, 'sha512') + ' input.txt\n"\n')
with contextlib.redirect_stdout(io.StringIO()):
workflow.sync('candidate')
target = self.root / 'sources/pmaports-managed-candidate/device/testing/device-xiaomi-platina/input.txt'
self.assertEqual(target.read_text(), 'reviewed update')
self.assertEqual(self.git('diff', '--cached'), self.initial_index)
def test_concurrent_build_rejected(self):
with workflow.build_slot():
with self.assertRaisesRegex(ValueError, 'running'):
with workflow.build_slot():
self.fail('Concurrent build accepted')
if __name__ == '__main__':
unittest.main()