21_test_command_wrappers.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # vim: set fileencoding=utf-8 :
  2. """Test L{gbp.command_wrappers.Command}'s tarball unpack"""
  3. import unittest
  4. import mock
  5. import functools
  6. from gbp.command_wrappers import Command, CommandExecFailed
  7. from . testutils import GbpLogTester
  8. def patch_popen(stdout='', stderr='', returncode=1):
  9. """Decorator to easily set the return value of popen.communicate()"""
  10. def patch_popen_decorator(func):
  11. @functools.wraps(func)
  12. def wrap(self):
  13. with mock.patch('subprocess.Popen') as create_mock:
  14. popen_mock = mock.Mock(**{'returncode': returncode,
  15. 'communicate.return_value': (stdout, stderr)})
  16. create_mock.return_value = popen_mock
  17. return func(self, create_mock)
  18. return wrap
  19. return patch_popen_decorator
  20. class TestCommandWrapperFailures(unittest.TestCase, GbpLogTester):
  21. def setUp(self):
  22. self.false = Command('/does/not/matter')
  23. self.log_tester = GbpLogTester()
  24. self.log_tester._capture_log(True)
  25. def tearDown(self):
  26. self.log_tester._capture_log(False)
  27. @patch_popen(stdout='', stderr='', returncode=1)
  28. def test_log_default_error_msg(self, create_mock):
  29. with self.assertRaises(CommandExecFailed):
  30. self.false.__call__()
  31. self.log_tester._check_log(0, "gbp:error: '/does/not/matter' failed: it exited with 1")
  32. self.assertEqual(self.false.retcode, 1)
  33. self.assertEqual(self.false.stderr, '')
  34. self.assertEqual(self.false.stdout, '')
  35. @patch_popen(stdout='', stderr='we have a problem', returncode=1)
  36. def test_log_use_stderr_for_err_message(self, create_mock):
  37. self.false.capture_stderr = True
  38. self.false.run_error = "Erpel {stderr}"
  39. with self.assertRaises(CommandExecFailed):
  40. self.false.__call__()
  41. self.log_tester._check_log(0, "gbp:error: Erpel we have a problem")
  42. self.assertEqual(self.false.retcode, 1)
  43. self.assertEqual(self.false.stderr, 'we have a problem')
  44. self.assertEqual(self.false.stdout, '')
  45. @patch_popen(stdout='we have a problem', stderr='', returncode=1)
  46. def test_log_use_stdout_for_err_message(self, create_mock):
  47. self.false.capture_stdout = True
  48. self.false.run_error = "Erpel {stdout}"
  49. with self.assertRaises(CommandExecFailed):
  50. self.false.__call__()
  51. self.log_tester._check_log(0, "gbp:error: Erpel we have a problem")
  52. self.assertEqual(self.false.retcode, 1)
  53. self.assertEqual(self.false.stderr, '')
  54. self.assertEqual(self.false.stdout, 'we have a problem')
  55. @patch_popen(returncode=0)
  56. def test_no_log_on_success(self, create_mock):
  57. self.false.__call__()
  58. self.log_tester._check_log_empty()
  59. self.assertEqual(self.false.retcode, 0)