import runpy import unittest from pathlib import Path from unittest.mock import patch from switch_bundle_common import main class _FakeVaultV2(object): def __init__(self, switch_bundle='1'): self.calls = [] self.switch_bundle = switch_bundle def read_secret_version(self, **kwargs): self.calls.append(kwargs) return {'data': {'data': {'switchBundle': self.switch_bundle}}} class _FakeClient(object): def __init__(self, authenticated=True, switch_bundle='1'): self.authenticated = authenticated self.v2 = _FakeVaultV2(switch_bundle) self.secrets = self self.kv = self def is_authenticated(self): return self.authenticated class SwitchBundleCommonTests(unittest.TestCase): def test_main_passes_vault_options_and_environment_to_publish(self): client = _FakeClient() publish_calls = [] main( ['switchBundle.py', 'project', '123!@#', 'release', 'production'], 's3://web-h5game-test/internal/', 'ap-east-1', client_factory=lambda **kwargs: client, publish=lambda *args: publish_calls.append(args), ) self.assertEqual( client.v2.calls[0]['path'], 'release', ) self.assertEqual( client.v2.calls[0]['mount_point'], 'production', ) self.assertEqual( publish_calls, [('project', 's3://web-h5game-test/internal/', 'ap-east-1')], ) def test_main_skips_publish_when_password_is_invalid(self): client_calls = [] publish_calls = [] main( ['switchBundle.py', 'project', 'wrong-password'], 's3://web-h5game-test/internal/', 'ap-east-1', client_factory=lambda **kwargs: client_calls.append(kwargs), publish=lambda *args: publish_calls.append(args), ) self.assertEqual(client_calls, []) self.assertEqual(publish_calls, []) def test_main_skips_publish_when_vault_does_not_allow_it(self): for authenticated, switch_bundle in [(False, '1'), (True, '0')]: with self.subTest(authenticated=authenticated, switch_bundle=switch_bundle): client = _FakeClient(authenticated, switch_bundle) publish_calls = [] main( ['switchBundle.py', 'project', '123!@#'], 's3://web-h5game-test/internal/', 'ap-east-1', client_factory=lambda **kwargs: client, publish=lambda *args: publish_calls.append(args), ) self.assertEqual(publish_calls, []) self.assertEqual(len(client.v2.calls), int(authenticated)) def test_entry_points_keep_their_publish_destinations(self): environments = [ ('switchBundle.py', 's3://web-h5game-test/internal/', 'ap-east-1'), ('switchBundleR.py', 's3://web-h5game-prod/internal/', 'eu-west-3'), ] for filename, destination, region in environments: with self.subTest(filename=filename): script = str(Path(__file__).with_name(filename)) argv = [script, 'project', '123!@#', 'release', 'production'] with patch('sys.argv', argv), patch('switch_bundle_common.main') as entry: runpy.run_path(script, run_name='__main__') entry.assert_called_once_with(argv, destination, region) if __name__ == '__main__': unittest.main()