test_utils.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/env python
  2. #
  3. # Copyright (C) 2011, 2012 Google Inc.
  4. #
  5. # This file is part of YouCompleteMe.
  6. #
  7. # YouCompleteMe is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # YouCompleteMe is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
  19. from mock import MagicMock
  20. import sys
  21. # One-and only instance of mocked Vim object. The first 'import vim' that is
  22. # executed binds the vim module to the instance of MagicMock that is created,
  23. # and subsquent assignments to sys.modules[ 'vim' ] don't retrospectively update
  24. # them. The result is that while running the tests, we must assign only one
  25. # instance of MagicMock to sys.modules[ 'vim' ] and always return it.
  26. #
  27. # More explanation is available:
  28. # https://github.com/Valloric/YouCompleteMe/pull/1694
  29. VIM_MOCK = MagicMock()
  30. def MockVimModule():
  31. """The 'vim' module is something that is only present when running inside the
  32. Vim Python interpreter, so we replace it with a MagicMock for tests. If you
  33. need to add additional mocks to vim module functions, then use 'patch' from
  34. mock module, to ensure that the state of the vim mock is returned before the
  35. next test. That is:
  36. from ycm.test_utils import MockVimModule
  37. from mock import patch
  38. # Do this once
  39. MockVimModule()
  40. @patch( 'vim.eval', return_value='test' )
  41. @patch( 'vim.command', side_effect=ValueError )
  42. def test( vim_command, vim_eval ):
  43. # use vim.command via vim_command, e.g.:
  44. vim_command.assert_has_calls( ... )
  45. Failure to use this approach may lead to unexpected failures in other
  46. tests."""
  47. def VimEval( value ):
  48. if value == "g:ycm_min_num_of_chars_for_completion":
  49. return 0
  50. return ''
  51. VIM_MOCK.eval = MagicMock( side_effect = VimEval )
  52. sys.modules[ 'vim' ] = VIM_MOCK
  53. return VIM_MOCK