59 lines
2.3 KiB
Python
59 lines
2.3 KiB
Python
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
import unittest
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
@unittest.skipUnless(sys.platform.startswith('linux') and shutil.which('cc'), 'Linux C compiler required')
|
|
class RuntimeHelpers(unittest.TestCase):
|
|
def setUp(self):
|
|
self.temp = tempfile.TemporaryDirectory()
|
|
self.addCleanup(self.temp.cleanup)
|
|
self.directory = Path(self.temp.name)
|
|
|
|
def compile(self, name, flags=()):
|
|
output = self.directory / name
|
|
subprocess.run(['cc', '-O2', '-Wall', '-Wextra', '-Werror', *flags,
|
|
str(ROOT / 'packages/olsr/src' / (name + '.c')), '-o', str(output)], check=True)
|
|
return output
|
|
|
|
def test_log_ring_is_bounded_and_preserves_newest_bytes(self):
|
|
binary = self.compile('log-ring', ['-DLOG_ROOT="' + str(self.directory) + '/"'])
|
|
output = self.directory / 'log'
|
|
content = bytes(range(256)) * 1024
|
|
subprocess.run([binary, output], input=content, check=True)
|
|
self.assertEqual(output.read_bytes(), content[-32768:])
|
|
self.assertFalse(output.with_suffix('.tmp').exists())
|
|
result = subprocess.run([binary, '/unapproved-output'], input=b'test')
|
|
self.assertEqual(result.returncode, 2)
|
|
|
|
def test_child_terminates_when_supervisor_dies(self):
|
|
binary = self.compile('run-child')
|
|
supervisor = subprocess.Popen([sys.executable, '-c',
|
|
'import subprocess,sys,time; p=subprocess.Popen([sys.argv[1],"/bin/sleep","60"]); '
|
|
'print(p.pid,flush=True); time.sleep(60)', str(binary)], stdout=subprocess.PIPE, text=True)
|
|
self.addCleanup(lambda: supervisor.poll() is None and supervisor.kill())
|
|
pid = int(supervisor.stdout.readline())
|
|
time.sleep(0.1)
|
|
supervisor.terminate()
|
|
supervisor.wait(timeout=2)
|
|
stopped = False
|
|
for _ in range(30):
|
|
try:
|
|
state = Path(f'/proc/{pid}/stat').read_text().split(') ',1)[1].split()[0]
|
|
stopped = state == 'Z'
|
|
except FileNotFoundError:
|
|
stopped = True
|
|
if stopped:
|
|
break
|
|
time.sleep(0.1)
|
|
if not stopped:
|
|
os.kill(pid, 9)
|
|
self.assertTrue(stopped, 'Child outlived its supervisor')
|