store.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package gock
  2. import (
  3. "sync"
  4. )
  5. // storeMutex is used interally for store synchronization.
  6. var storeMutex = sync.RWMutex{}
  7. // mocks is internally used to store registered mocks.
  8. var mocks = []Mock{}
  9. // Register registers a new mock in the current mocks stack.
  10. func Register(mock Mock) {
  11. if Exists(mock) {
  12. return
  13. }
  14. // Make ops thread safe
  15. mutex.Lock()
  16. defer mutex.Unlock()
  17. // Expose mock in request/response for delegation
  18. mock.Request().Mock = mock
  19. mock.Response().Mock = mock
  20. // Registers the mock in the global store
  21. mocks = append(mocks, mock)
  22. }
  23. // GetAll returns the current stack of registed mocks.
  24. func GetAll() []Mock {
  25. storeMutex.RLock()
  26. defer storeMutex.RUnlock()
  27. return mocks
  28. }
  29. // Exists checks if the given Mock is already registered.
  30. func Exists(m Mock) bool {
  31. storeMutex.RLock()
  32. defer storeMutex.RUnlock()
  33. for _, mock := range mocks {
  34. if mock == m {
  35. return true
  36. }
  37. }
  38. return false
  39. }
  40. // Remove removes a registered mock by reference.
  41. func Remove(m Mock) {
  42. for i, mock := range mocks {
  43. if mock == m {
  44. storeMutex.Lock()
  45. mocks = append(mocks[:i], mocks[i+1:]...)
  46. storeMutex.Unlock()
  47. }
  48. }
  49. }
  50. // Flush flushes the current stack of registered mocks.
  51. func Flush() {
  52. storeMutex.Lock()
  53. defer storeMutex.Unlock()
  54. mocks = []Mock{}
  55. }
  56. // Pending returns an slice of pending mocks.
  57. func Pending() []Mock {
  58. Clean()
  59. storeMutex.RLock()
  60. defer storeMutex.RUnlock()
  61. return mocks
  62. }
  63. // IsDone returns true if all the registered mocks has been triggered successfully.
  64. func IsDone() bool {
  65. return !IsPending()
  66. }
  67. // IsPending returns true if there are pending mocks.
  68. func IsPending() bool {
  69. return len(Pending()) > 0
  70. }
  71. // Clean cleans the mocks store removing disabled or obsolete mocks.
  72. func Clean() {
  73. storeMutex.Lock()
  74. defer storeMutex.Unlock()
  75. buf := []Mock{}
  76. for _, mock := range mocks {
  77. if mock.Done() {
  78. continue
  79. }
  80. buf = append(buf, mock)
  81. }
  82. mocks = buf
  83. }