exit_matcher.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package gexec
  2. import (
  3. "fmt"
  4. "github.com/onsi/gomega/format"
  5. )
  6. /*
  7. The Exit matcher operates on a session:
  8. Expect(session).Should(Exit(<optional status code>))
  9. Exit passes if the session has already exited.
  10. If no status code is provided, then Exit will succeed if the session has exited regardless of exit code.
  11. Otherwise, Exit will only succeed if the process has exited with the provided status code.
  12. Note that the process must have already exited. To wait for a process to exit, use Eventually:
  13. Eventually(session, 3).Should(Exit(0))
  14. */
  15. func Exit(optionalExitCode ...int) *exitMatcher {
  16. exitCode := -1
  17. if len(optionalExitCode) > 0 {
  18. exitCode = optionalExitCode[0]
  19. }
  20. return &exitMatcher{
  21. exitCode: exitCode,
  22. }
  23. }
  24. type exitMatcher struct {
  25. exitCode int
  26. didExit bool
  27. actualExitCode int
  28. }
  29. type Exiter interface {
  30. ExitCode() int
  31. }
  32. func (m *exitMatcher) Match(actual interface{}) (success bool, err error) {
  33. exiter, ok := actual.(Exiter)
  34. if !ok {
  35. return false, fmt.Errorf("Exit must be passed a gexec.Exiter (Missing method ExitCode() int) Got:\n%s", format.Object(actual, 1))
  36. }
  37. m.actualExitCode = exiter.ExitCode()
  38. if m.actualExitCode == -1 {
  39. return false, nil
  40. }
  41. if m.exitCode == -1 {
  42. return true, nil
  43. }
  44. return m.exitCode == m.actualExitCode, nil
  45. }
  46. func (m *exitMatcher) FailureMessage(actual interface{}) (message string) {
  47. if m.actualExitCode == -1 {
  48. return "Expected process to exit. It did not."
  49. }
  50. return format.Message(m.actualExitCode, "to match exit code:", m.exitCode)
  51. }
  52. func (m *exitMatcher) NegatedFailureMessage(actual interface{}) (message string) {
  53. if m.actualExitCode == -1 {
  54. return "you really shouldn't be able to see this!"
  55. } else {
  56. if m.exitCode == -1 {
  57. return "Expected process not to exit. It did."
  58. }
  59. return format.Message(m.actualExitCode, "not to match exit code:", m.exitCode)
  60. }
  61. }
  62. func (m *exitMatcher) MatchMayChangeInTheFuture(actual interface{}) bool {
  63. session, ok := actual.(*Session)
  64. if ok {
  65. return session.ExitCode() == -1
  66. }
  67. return true
  68. }