scm_mock.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # Copyright (c) 2024 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. from __future__ import annotations
  5. import os
  6. import sys
  7. import threading
  8. from typing import Iterable
  9. from unittest import mock
  10. import unittest
  11. # This is to be able to import scm from the root of the repo.
  12. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  13. import scm
  14. def GIT(
  15. test: unittest.TestCase,
  16. *,
  17. branchref: str | None = None,
  18. system_config: dict[str, list[str]] | None = None
  19. ) -> Iterable[tuple[str, list[str]]]:
  20. """Installs fakes/mocks for scm.GIT so that:
  21. * GetBranch will just return a fake branchname starting with the value of
  22. branchref.
  23. * git_new_branch.create_new_branch will be mocked to update the value
  24. returned by GetBranch.
  25. If provided, `system_config` allows you to set the 'system' scoped
  26. git-config which will be visible as the immutable base configuration layer
  27. for all git config scopes.
  28. NOTE: The dependency on git_new_branch.create_new_branch seems pretty
  29. circular - this functionality should probably move to scm.GIT?
  30. """
  31. _branchref = [branchref or 'refs/heads/main']
  32. global_lock = threading.Lock()
  33. global_state = {}
  34. def _newBranch(branchref):
  35. _branchref[0] = branchref
  36. patches: list[mock._patch] = [
  37. mock.patch('scm.GIT._new_config_state',
  38. side_effect=lambda _: scm.GitConfigStateTest(
  39. global_lock, global_state, system_state=system_config)),
  40. mock.patch('scm.GIT.GetBranchRef', side_effect=lambda _: _branchref[0]),
  41. mock.patch('git_new_branch.create_new_branch', side_effect=_newBranch)
  42. ]
  43. for p in patches:
  44. p.start()
  45. test.addCleanup(p.stop)
  46. test.addCleanup(scm.GIT.drop_config_cache)
  47. return global_state.items()