test_installer.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import importlib.util
  2. import tempfile
  3. import unittest
  4. from pathlib import Path
  5. from unittest.mock import patch
  6. import yaml
  7. spec = importlib.util.spec_from_file_location('bridge_installer', Path(__file__).parents[3] / 'scripts/install-hermes-bridge.py')
  8. installer = importlib.util.module_from_spec(spec)
  9. spec.loader.exec_module(installer)
  10. class InstallerTests(unittest.TestCase):
  11. def setUp(self):
  12. self.temp = tempfile.TemporaryDirectory()
  13. self.root = Path(self.temp.name)
  14. self.source = self.root / 'source'; self.source.mkdir()
  15. (self.source / 'plugin.yaml').write_text('name: yaoyao-bot-bridge\nversion: 1.2.0\n')
  16. self.home = self.root / 'hermes'; self.home.mkdir()
  17. self.config = self.home / 'config.yaml'
  18. self.config.write_text('model:\n default: keep-model\nplugins:\n enabled: [existing]\n')
  19. self.target = self.home / 'plugins' / 'yaoyao-bot-bridge'
  20. self.target.mkdir(parents=True)
  21. (self.target / 'old').write_text('previous-plugin')
  22. def tearDown(self):
  23. self.temp.cleanup()
  24. def test_upgrade_backs_up_plugin_and_preserves_unrelated_config(self):
  25. original = self.config.read_bytes()
  26. result = installer.install(self.home, 'default', self.source)
  27. self.assertEqual((Path(result['backup']) / 'config.yaml').read_bytes(), original)
  28. self.assertEqual((Path(result['backup']) / 'yaoyao-bot-bridge' / 'old').read_text(), 'previous-plugin')
  29. config = yaml.safe_load(self.config.read_text())
  30. self.assertEqual(config['model']['default'], 'keep-model')
  31. self.assertEqual(config['plugins']['enabled'], ['existing', 'yaoyao-bot-bridge'])
  32. def test_preserves_an_explicitly_disabled_plugin(self):
  33. self.config.write_text('plugins:\n disabled: [yaoyao-bot-bridge]\n')
  34. result = installer.install(self.home, 'default', self.source)
  35. self.assertTrue(result['disabled'])
  36. self.assertNotIn('yaoyao-bot-bridge', yaml.safe_load(self.config.read_text())['plugins'].get('enabled', []))
  37. def test_failed_copy_or_config_write_preserves_original_installation(self):
  38. for function in ['shutil.copytree', 'yaml.safe_dump']:
  39. with self.subTest(function=function):
  40. original = self.config.read_bytes()
  41. with patch.object(installer.shutil if function.startswith('shutil') else installer.yaml,
  42. function.split('.')[1], side_effect=RuntimeError('fixture-failure')):
  43. with self.assertRaises(RuntimeError): installer.install(self.home, 'default', self.source)
  44. self.assertEqual(self.config.read_bytes(), original)
  45. self.assertEqual((self.target / 'old').read_text(), 'previous-plugin')
  46. if __name__ == '__main__':
  47. unittest.main()