Iomatex_OS/offline/test_bootstrap_fallback.py

53 lines
2.8 KiB
Python

import io
import os
from pathlib import Path
import socket
import ssl
import sys
import tempfile
import unittest
from unittest.mock import patch, Mock
from urllib.error import URLError, HTTPError
ROOT = Path(__file__).resolve().parents[1]
SOURCE = (ROOT/'install_iomatex_edge.sh').read_text().split("<<'PYTHON'\n", 1)[1].split('\nPYTHON', 1)[0]
BRANCH = b'{"commit":{"id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}'
class BootstrapFallbackTest(unittest.TestCase):
def run_bootstrap(self, responses, host='git.it-screen.com'):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
destination = Path(temp.name)/'git_delivery.py'
opener = Mock()
opener.open.side_effect = responses
with patch('urllib.request.build_opener', return_value=opener), patch.dict(os.environ, {'IOMATEX_GIT_USERNAME':'user','IOMATEX_GIT_PASSWORD':'secret'}), patch.object(sys, 'argv', ['-', 'https://'+host+'/An-J/Iomatex_OS.git', 'ci-cd', str(destination)]):
exec(compile(SOURCE, 'bootstrap', 'exec'), {})
return destination, opener
def test_dns_failure_selects_alternative_and_persists_source(self):
dest, opener = self.run_bootstrap([URLError(socket.gaierror(-3, 'DNS failure')), io.BytesIO(BRANCH), io.BytesIO(b'loader')])
self.assertEqual(b'loader', dest.read_bytes())
self.assertEqual('https://git.iomatex.com/An-J/Iomatex_OS.git', Path(str(dest)+'.source').read_text())
self.assertEqual(3, opener.open.call_count)
self.assertIn('git.iomatex.com', opener.open.call_args.args[0].full_url)
def test_payload_timeout_keeps_same_commit_on_alternate(self):
_, opener = self.run_bootstrap([io.BytesIO(BRANCH), socket.timeout(), io.BytesIO(b'loader')])
self.assertIn('git.iomatex.com', opener.open.call_args.args[0].full_url)
self.assertTrue(opener.open.call_args.args[0].full_url.endswith('a'*40))
def test_explicit_alternate_is_tried_first(self):
_, opener = self.run_bootstrap([io.BytesIO(BRANCH), io.BytesIO(b'loader')], 'git.iomatex.com')
self.assertIn('git.iomatex.com', opener.open.call_args_list[0].args[0].full_url)
self.assertEqual('IomatexOS-Updater/1.0', opener.open.call_args_list[0].args[0].get_header('User-agent'))
def test_auth_and_tls_fail_without_switch(self):
for error in [HTTPError('url', 401, 'Unauthorized', {}, None), URLError(ssl.SSLCertVerificationError('invalid certificate'))]:
with self.subTest(error=type(error).__name__):
with self.assertRaises(SystemExit):
self.run_bootstrap([error, AssertionError('Must not switch')])
def test_both_domains_unreachable_reports_failure(self):
with self.assertRaisesRegex(SystemExit, 'Both Git domains are unreachable'):
self.run_bootstrap([URLError(socket.gaierror()), socket.timeout()])