import importlib.util from pathlib import Path import subprocess import unittest from unittest.mock import MagicMock, patch path = Path(__file__).resolve().parents[2] / 'scripts/network-sandbox-isolation-host.py' spec = importlib.util.spec_from_file_location('sandbox_isolation', path) isolation = importlib.util.module_from_spec(spec) spec.loader.exec_module(isolation) class IsolationExercisesTest(unittest.TestCase): def probe(self, results): listener = MagicMock() listener.stdout.readline.return_value = '45678\n' listener.poll.return_value = None with patch.object(isolation.subprocess, 'Popen', return_value=listener), \ patch.object(isolation.select, 'select', return_value=([listener.stdout], [], [])), \ patch.object(isolation, 'udp_connect', side_effect=results): result = isolation.udp_probe(10, 20, '172.29.220.107') listener.terminate.assert_called_once() return result def test_peer_silence_requires_successful_control(self): success = subprocess.CompletedProcess([], 0, stdout='', stderr='') timeout = subprocess.CompletedProcess([], 1, stdout='UDP_ERROR: timed out\n', stderr='') self.assertIn('positive control', self.probe([success, timeout])) self.assertIn('inconclusive', self.probe([timeout])) def test_udp_reply_is_failure(self): success = subprocess.CompletedProcess([], 0, stdout='', stderr='') self.assertTrue(self.probe([success, success]).startswith('failed:')) def test_execution_failure_is_inconclusive(self): success = subprocess.CompletedProcess([], 0, stdout='', stderr='') failure = subprocess.CompletedProcess([], 1, stdout='', stderr='nsenter failed') self.assertTrue(self.probe([success, failure]).startswith('inconclusive:')) def test_gateway_dns_requires_a_valid_response(self): reply = subprocess.CompletedProcess([], 0, stdout='DNS_RESPONSE: rcode=0\n', stderr='') failure = subprocess.CompletedProcess([], 1, stdout='DNS_ERROR: timed out\n', stderr='') with patch.object(isolation.subprocess, 'run', return_value=reply): self.assertTrue(isolation.gateway_dns(10, '172.29.210.1').startswith('reachable:')) with patch.object(isolation.subprocess, 'run', return_value=failure): self.assertIn('inconclusive', isolation.gateway_dns(10, '172.29.210.1'))