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