File: store.go

package info (click to toggle)
golang-gopkg-h2non-gock.v1 1.1.2-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 364 kB
  • sloc: makefile: 2
file content (100 lines) | stat: -rw-r--r-- 1,936 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package gock

import (
	"sync"
)

// storeMutex is used interally for store synchronization.
var storeMutex = sync.RWMutex{}

// mocks is internally used to store registered mocks.
var mocks = []Mock{}

// Register registers a new mock in the current mocks stack.
func Register(mock Mock) {
	if Exists(mock) {
		return
	}

	// Make ops thread safe
	storeMutex.Lock()
	defer storeMutex.Unlock()

	// Expose mock in request/response for delegation
	mock.Request().Mock = mock
	mock.Response().Mock = mock

	// Registers the mock in the global store
	mocks = append(mocks, mock)
}

// GetAll returns the current stack of registed mocks.
func GetAll() []Mock {
	storeMutex.RLock()
	defer storeMutex.RUnlock()
	return mocks
}

// Exists checks if the given Mock is already registered.
func Exists(m Mock) bool {
	storeMutex.RLock()
	defer storeMutex.RUnlock()
	for _, mock := range mocks {
		if mock == m {
			return true
		}
	}
	return false
}

// Remove removes a registered mock by reference.
func Remove(m Mock) {
	for i, mock := range mocks {
		if mock == m {
			storeMutex.Lock()
			mocks = append(mocks[:i], mocks[i+1:]...)
			storeMutex.Unlock()
		}
	}
}

// Flush flushes the current stack of registered mocks.
func Flush() {
	storeMutex.Lock()
	defer storeMutex.Unlock()
	mocks = []Mock{}
}

// Pending returns an slice of pending mocks.
func Pending() []Mock {
	Clean()
	storeMutex.RLock()
	defer storeMutex.RUnlock()
	return mocks
}

// IsDone returns true if all the registered mocks has been triggered successfully.
func IsDone() bool {
	return !IsPending()
}

// IsPending returns true if there are pending mocks.
func IsPending() bool {
	return len(Pending()) > 0
}

// Clean cleans the mocks store removing disabled or obsolete mocks.
func Clean() {
	storeMutex.Lock()
	defer storeMutex.Unlock()

	buf := []Mock{}
	for _, mock := range mocks {
		if mock.Done() {
			continue
		}
		buf = append(buf, mock)
	}

	mocks = buf
}