update go-pkgz/rest, stretchr/testify, three stdlib modules
This commit is contained in:
committed by
Umputun
parent
3c90f6ae61
commit
26476db95d
+1
-3
@@ -17,8 +17,6 @@ import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// Cache defines cache interface
|
||||
@@ -73,7 +71,7 @@ func NewCache(options ...Option) (Cache, error) {
|
||||
|
||||
for _, opt := range options {
|
||||
if err := opt(&res); err != nil {
|
||||
return nil, errors.Wrap(err, "failed to set cache option")
|
||||
return nil, fmt.Errorf("failed to set cache option: %w", err)
|
||||
}
|
||||
}
|
||||
return &res, nil
|
||||
|
||||
+22
-1
@@ -123,7 +123,28 @@ a request does not satisfy the maybeFn logic.
|
||||
|
||||
Benchmarks middleware allows to measure the time of request handling, number of request per second and report aggregated metrics. This middleware keeps track of the request in the memory and keep up to 900 points (15 minutes, data-point per second).
|
||||
|
||||
In order to retrieve the data user should call `Stats(d duration)` method. duration is the time window for which the benchmark data should be returned. It can be any duration from 1s to 15m.
|
||||
In order to retrieve the data user should call `Stats(d duration)` method. duration is the time window for which the benchmark data should be returned. It can be any duration from 1s to 15m. Note: all the time data is in microseconds.
|
||||
|
||||
example with chi router:
|
||||
|
||||
```go
|
||||
router := chi.NewRouter()
|
||||
bench = rest.NewBenchmarks()
|
||||
router.Use(bench.Middleware)
|
||||
...
|
||||
router.Get("/bench", func(w http.ResponseWriter, r *http.Request) {
|
||||
resp := struct {
|
||||
OneMin rest.BenchmarkStats `json:"1min"`
|
||||
FiveMin rest.BenchmarkStats `json:"5min"`
|
||||
FifteenMin rest.BenchmarkStats `json:"15min"`
|
||||
}{
|
||||
bench.Stats(time.Minute),
|
||||
bench.Stats(time.Minute * 5),
|
||||
bench.Stats(time.Minute * 15),
|
||||
}
|
||||
render.JSON(w, r, resp)
|
||||
})
|
||||
```
|
||||
|
||||
## Helpers
|
||||
|
||||
|
||||
+29
-16
@@ -7,16 +7,17 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
var maxTimeRange = time.Duration(15) * time.Minute
|
||||
var maxTimeRangeDefault = time.Duration(15) * time.Minute
|
||||
|
||||
// Benchmarks is a basic benchmarking middleware collecting and reporting performance metrics
|
||||
// It keeps track of the requests speeds and counts in 1s benchData buckets ,limiting the number of buckets
|
||||
// to maxTimeRange. User can request the benchmark for any time duration. This is intended to be used
|
||||
// for retrieving the benchmark data for the last minute, 5 minutes and up to maxTimeRange.
|
||||
type Benchmarks struct {
|
||||
st time.Time
|
||||
data *list.List
|
||||
lock sync.RWMutex
|
||||
st time.Time
|
||||
data *list.List
|
||||
lock sync.RWMutex
|
||||
maxTimeRange time.Duration
|
||||
|
||||
nowFn func() time.Time // for testing only
|
||||
}
|
||||
@@ -32,23 +33,35 @@ type benchData struct {
|
||||
|
||||
// BenchmarkStats holds the stats for a given interval
|
||||
type BenchmarkStats struct {
|
||||
Requests int `json:"total_requests"`
|
||||
RequestsSec float64 `json:"total_requests_sec"`
|
||||
AverageRespTime float64 `json:"average_resp_time"`
|
||||
MinRespTime float64 `json:"min_resp_time"`
|
||||
MaxRespTime float64 `json:"max_resp_time"`
|
||||
Requests int `json:"requests"`
|
||||
RequestsSec float64 `json:"requests_sec"`
|
||||
AverageRespTime int64 `json:"average_resp_time"`
|
||||
MinRespTime int64 `json:"min_resp_time"`
|
||||
MaxRespTime int64 `json:"max_resp_time"`
|
||||
}
|
||||
|
||||
// NewBenchmarks creates a new benchmark middleware
|
||||
func NewBenchmarks() *Benchmarks {
|
||||
res := &Benchmarks{
|
||||
st: time.Now(),
|
||||
data: list.New(),
|
||||
nowFn: time.Now,
|
||||
st: time.Now(),
|
||||
data: list.New(),
|
||||
nowFn: time.Now,
|
||||
maxTimeRange: maxTimeRangeDefault,
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// WithTimeRange sets the maximum time range for the benchmark to keep data for.
|
||||
// Default is 15 minutes. The increase of this range will change memory utilization as each second of the range
|
||||
// kept as benchData aggregate. The default means 15*60 = 900 seconds of data aggregate.
|
||||
// Larger range allows for longer time periods to be benchmarked.
|
||||
func (b *Benchmarks) WithTimeRange(max time.Duration) *Benchmarks {
|
||||
b.lock.Lock()
|
||||
defer b.lock.Unlock()
|
||||
b.maxTimeRange = max
|
||||
return b
|
||||
}
|
||||
|
||||
// Handler calculates 1/5/10m request per second and allows to access those values
|
||||
func (b *Benchmarks) Handler(next http.Handler) http.Handler {
|
||||
|
||||
@@ -70,7 +83,7 @@ func (b *Benchmarks) update(reqDuration time.Duration) {
|
||||
|
||||
// keep maxTimeRange in the list, drop the rest
|
||||
for e := b.data.Front(); e != nil; e = e.Next() {
|
||||
if b.data.Front().Value.(benchData).ts.After(b.nowFn().Add(-maxTimeRange)) {
|
||||
if b.data.Front().Value.(benchData).ts.After(b.nowFn().Add(-b.maxTimeRange)) {
|
||||
break
|
||||
}
|
||||
b.data.Remove(b.data.Front())
|
||||
@@ -139,8 +152,8 @@ func (b *Benchmarks) Stats(interval time.Duration) BenchmarkStats {
|
||||
return BenchmarkStats{
|
||||
Requests: requests,
|
||||
RequestsSec: float64(requests) / (fnInterval.Sub(stInterval).Seconds()),
|
||||
AverageRespTime: respTime.Seconds() / float64(requests),
|
||||
MinRespTime: minRespTime.Seconds(),
|
||||
MaxRespTime: maxRespTime.Seconds(),
|
||||
AverageRespTime: respTime.Microseconds() / int64(requests),
|
||||
MinRespTime: minRespTime.Microseconds(),
|
||||
MaxRespTime: maxRespTime.Microseconds(),
|
||||
}
|
||||
}
|
||||
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
language: go
|
||||
go:
|
||||
- "1.10.x"
|
||||
- "1.11.x"
|
||||
- "1.12.x"
|
||||
- master
|
||||
|
||||
matrix:
|
||||
allow_failures:
|
||||
- go: master
|
||||
fast_finish: true
|
||||
|
||||
env:
|
||||
global:
|
||||
- CC_TEST_REPORTER_ID=68feaa3410049ce73e145287acbcdacc525087a30627f96f04e579e75bd71c00
|
||||
|
||||
before_script:
|
||||
- curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
|
||||
- chmod +x ./cc-test-reporter
|
||||
- ./cc-test-reporter before-build
|
||||
|
||||
install:
|
||||
- curl -sL https://taskfile.dev/install.sh | sh
|
||||
|
||||
script:
|
||||
- diff -u <(echo -n) <(./bin/task lint)
|
||||
- ./bin/task test-coverage
|
||||
|
||||
after_script:
|
||||
- ./cc-test-reporter after-build --exit-code $TRAVIS_TEST_RESULT
|
||||
+27
-9
@@ -116,9 +116,15 @@ func getKey(s string) (string, string) {
|
||||
func access(current interface{}, selector string, value interface{}, isSet bool) interface{} {
|
||||
thisSel, nextSel := getKey(selector)
|
||||
|
||||
index := -1
|
||||
if strings.Contains(thisSel, "[") {
|
||||
indexes := []int{}
|
||||
for strings.Contains(thisSel, "[") {
|
||||
prevSel := thisSel
|
||||
index := -1
|
||||
index, thisSel = getIndex(thisSel)
|
||||
indexes = append(indexes, index)
|
||||
if prevSel == thisSel {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if curMap, ok := current.(Map); ok {
|
||||
@@ -134,7 +140,11 @@ func access(current interface{}, selector string, value interface{}, isSet bool)
|
||||
}
|
||||
|
||||
_, ok := curMSI[thisSel].(map[string]interface{})
|
||||
if (curMSI[thisSel] == nil || !ok) && index == -1 && isSet {
|
||||
if !ok {
|
||||
_, ok = curMSI[thisSel].(Map)
|
||||
}
|
||||
|
||||
if (curMSI[thisSel] == nil || !ok) && len(indexes) == 0 && isSet {
|
||||
curMSI[thisSel] = map[string]interface{}{}
|
||||
}
|
||||
|
||||
@@ -144,15 +154,23 @@ func access(current interface{}, selector string, value interface{}, isSet bool)
|
||||
}
|
||||
|
||||
// do we need to access the item of an array?
|
||||
if index > -1 {
|
||||
if array, ok := interSlice(current); ok {
|
||||
if index < len(array) {
|
||||
current = array[index]
|
||||
} else {
|
||||
current = nil
|
||||
if len(indexes) > 0 {
|
||||
num := len(indexes)
|
||||
for num > 0 {
|
||||
num--
|
||||
index := indexes[num]
|
||||
indexes = indexes[:num]
|
||||
if array, ok := interSlice(current); ok {
|
||||
if index < len(array) {
|
||||
current = array[index]
|
||||
} else {
|
||||
current = nil
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if nextSel != "" {
|
||||
current = access(current, nextSel, value, isSet)
|
||||
}
|
||||
|
||||
+22
-35
@@ -92,6 +92,18 @@ func MustFromJSON(jsonString string) Map {
|
||||
return o
|
||||
}
|
||||
|
||||
// MustFromJSONSlice creates a new slice of Map containing the data specified in the
|
||||
// jsonString. Works with jsons with a top level array
|
||||
//
|
||||
// Panics if the JSON is invalid.
|
||||
func MustFromJSONSlice(jsonString string) []Map {
|
||||
slice, err := FromJSONSlice(jsonString)
|
||||
if err != nil {
|
||||
panic("objx: MustFromJSONSlice failed with error: " + err.Error())
|
||||
}
|
||||
return slice
|
||||
}
|
||||
|
||||
// FromJSON creates a new Map containing the data specified in the
|
||||
// jsonString.
|
||||
//
|
||||
@@ -102,45 +114,20 @@ func FromJSON(jsonString string) (Map, error) {
|
||||
if err != nil {
|
||||
return Nil, err
|
||||
}
|
||||
m.tryConvertFloat64()
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (m Map) tryConvertFloat64() {
|
||||
for k, v := range m {
|
||||
switch v.(type) {
|
||||
case float64:
|
||||
f := v.(float64)
|
||||
if float64(int(f)) == f {
|
||||
m[k] = int(f)
|
||||
}
|
||||
case map[string]interface{}:
|
||||
t := New(v)
|
||||
t.tryConvertFloat64()
|
||||
m[k] = t
|
||||
case []interface{}:
|
||||
m[k] = tryConvertFloat64InSlice(v.([]interface{}))
|
||||
}
|
||||
// FromJSONSlice creates a new slice of Map containing the data specified in the
|
||||
// jsonString. Works with jsons with a top level array
|
||||
//
|
||||
// Returns an error if the JSON is invalid.
|
||||
func FromJSONSlice(jsonString string) ([]Map, error) {
|
||||
var slice []Map
|
||||
err := json.Unmarshal([]byte(jsonString), &slice)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func tryConvertFloat64InSlice(s []interface{}) []interface{} {
|
||||
for k, v := range s {
|
||||
switch v.(type) {
|
||||
case float64:
|
||||
f := v.(float64)
|
||||
if float64(int(f)) == f {
|
||||
s[k] = int(f)
|
||||
}
|
||||
case map[string]interface{}:
|
||||
t := New(v)
|
||||
t.tryConvertFloat64()
|
||||
s[k] = t
|
||||
case []interface{}:
|
||||
s[k] = tryConvertFloat64InSlice(v.([]interface{}))
|
||||
}
|
||||
}
|
||||
return s
|
||||
return slice, nil
|
||||
}
|
||||
|
||||
// FromBase64 creates a new Obj containing the data specified
|
||||
|
||||
+10
@@ -385,6 +385,11 @@ func (v *Value) Int(optionalDefault ...int) int {
|
||||
if s, ok := v.data.(int); ok {
|
||||
return s
|
||||
}
|
||||
if s, ok := v.data.(float64); ok {
|
||||
if float64(int(s)) == s {
|
||||
return int(s)
|
||||
}
|
||||
}
|
||||
if len(optionalDefault) == 1 {
|
||||
return optionalDefault[0]
|
||||
}
|
||||
@@ -395,6 +400,11 @@ func (v *Value) Int(optionalDefault ...int) int {
|
||||
//
|
||||
// Panics if the object is not a int.
|
||||
func (v *Value) MustInt() int {
|
||||
if s, ok := v.data.(float64); ok {
|
||||
if float64(int(s)) == s {
|
||||
return int(s)
|
||||
}
|
||||
}
|
||||
return v.data.(int)
|
||||
}
|
||||
|
||||
|
||||
+23
-1
@@ -1,6 +1,7 @@
|
||||
package assert
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"time"
|
||||
@@ -32,7 +33,8 @@ var (
|
||||
|
||||
stringType = reflect.TypeOf("")
|
||||
|
||||
timeType = reflect.TypeOf(time.Time{})
|
||||
timeType = reflect.TypeOf(time.Time{})
|
||||
bytesType = reflect.TypeOf([]byte{})
|
||||
)
|
||||
|
||||
func compare(obj1, obj2 interface{}, kind reflect.Kind) (CompareType, bool) {
|
||||
@@ -323,6 +325,26 @@ func compare(obj1, obj2 interface{}, kind reflect.Kind) (CompareType, bool) {
|
||||
|
||||
return compare(timeObj1.UnixNano(), timeObj2.UnixNano(), reflect.Int64)
|
||||
}
|
||||
case reflect.Slice:
|
||||
{
|
||||
// We only care about the []byte type.
|
||||
if !canConvert(obj1Value, bytesType) {
|
||||
break
|
||||
}
|
||||
|
||||
// []byte can be compared!
|
||||
bytesObj1, ok := obj1.([]byte)
|
||||
if !ok {
|
||||
bytesObj1 = obj1Value.Convert(bytesType).Interface().([]byte)
|
||||
|
||||
}
|
||||
bytesObj2, ok := obj2.([]byte)
|
||||
if !ok {
|
||||
bytesObj2 = obj2Value.Convert(bytesType).Interface().([]byte)
|
||||
}
|
||||
|
||||
return CompareType(bytes.Compare(bytesObj1, bytesObj2)), true
|
||||
}
|
||||
}
|
||||
|
||||
return compareEqual, false
|
||||
|
||||
Generated
Vendored
+1
-1
@@ -9,7 +9,7 @@ package assert
|
||||
|
||||
import "reflect"
|
||||
|
||||
// Wrapper around reflect.Value.CanConvert, for compatability
|
||||
// Wrapper around reflect.Value.CanConvert, for compatibility
|
||||
// reasons.
|
||||
func canConvert(value reflect.Value, to reflect.Type) bool {
|
||||
return value.CanConvert(to)
|
||||
|
||||
+10
@@ -736,6 +736,16 @@ func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta tim
|
||||
return WithinDuration(t, expected, actual, delta, append([]interface{}{msg}, args...)...)
|
||||
}
|
||||
|
||||
// WithinRangef asserts that a time is within a time range (inclusive).
|
||||
//
|
||||
// assert.WithinRangef(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted")
|
||||
func WithinRangef(t TestingT, actual time.Time, start time.Time, end time.Time, msg string, args ...interface{}) bool {
|
||||
if h, ok := t.(tHelper); ok {
|
||||
h.Helper()
|
||||
}
|
||||
return WithinRange(t, actual, start, end, append([]interface{}{msg}, args...)...)
|
||||
}
|
||||
|
||||
// YAMLEqf asserts that two YAML strings are equivalent.
|
||||
func YAMLEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) bool {
|
||||
if h, ok := t.(tHelper); ok {
|
||||
|
||||
+20
@@ -1461,6 +1461,26 @@ func (a *Assertions) WithinDurationf(expected time.Time, actual time.Time, delta
|
||||
return WithinDurationf(a.t, expected, actual, delta, msg, args...)
|
||||
}
|
||||
|
||||
// WithinRange asserts that a time is within a time range (inclusive).
|
||||
//
|
||||
// a.WithinRange(time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second))
|
||||
func (a *Assertions) WithinRange(actual time.Time, start time.Time, end time.Time, msgAndArgs ...interface{}) bool {
|
||||
if h, ok := a.t.(tHelper); ok {
|
||||
h.Helper()
|
||||
}
|
||||
return WithinRange(a.t, actual, start, end, msgAndArgs...)
|
||||
}
|
||||
|
||||
// WithinRangef asserts that a time is within a time range (inclusive).
|
||||
//
|
||||
// a.WithinRangef(time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted")
|
||||
func (a *Assertions) WithinRangef(actual time.Time, start time.Time, end time.Time, msg string, args ...interface{}) bool {
|
||||
if h, ok := a.t.(tHelper); ok {
|
||||
h.Helper()
|
||||
}
|
||||
return WithinRangef(a.t, actual, start, end, msg, args...)
|
||||
}
|
||||
|
||||
// YAMLEq asserts that two YAML strings are equivalent.
|
||||
func (a *Assertions) YAMLEq(expected string, actual string, msgAndArgs ...interface{}) bool {
|
||||
if h, ok := a.t.(tHelper); ok {
|
||||
|
||||
+68
-10
@@ -8,6 +8,7 @@ import (
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"runtime"
|
||||
@@ -144,7 +145,8 @@ func CallerInfo() []string {
|
||||
if len(parts) > 1 {
|
||||
dir := parts[len(parts)-2]
|
||||
if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" {
|
||||
callers = append(callers, fmt.Sprintf("%s:%d", file, line))
|
||||
path, _ := filepath.Abs(file)
|
||||
callers = append(callers, fmt.Sprintf("%s:%d", path, line))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -563,16 +565,17 @@ func isEmpty(object interface{}) bool {
|
||||
|
||||
switch objValue.Kind() {
|
||||
// collection types are empty when they have no element
|
||||
case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
|
||||
case reflect.Chan, reflect.Map, reflect.Slice:
|
||||
return objValue.Len() == 0
|
||||
// pointers are empty if nil or if the value they point to is empty
|
||||
// pointers are empty if nil or if the value they point to is empty
|
||||
case reflect.Ptr:
|
||||
if objValue.IsNil() {
|
||||
return true
|
||||
}
|
||||
deref := objValue.Elem().Interface()
|
||||
return isEmpty(deref)
|
||||
// for all other types, compare against the zero value
|
||||
// for all other types, compare against the zero value
|
||||
// array types are empty when they match their zero-initialized state
|
||||
default:
|
||||
zero := reflect.Zero(objValue.Type())
|
||||
return reflect.DeepEqual(object, zero.Interface())
|
||||
@@ -815,7 +818,6 @@ func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok
|
||||
return true // we consider nil to be equal to the nil set
|
||||
}
|
||||
|
||||
subsetValue := reflect.ValueOf(subset)
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
ok = false
|
||||
@@ -825,14 +827,32 @@ func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok
|
||||
listKind := reflect.TypeOf(list).Kind()
|
||||
subsetKind := reflect.TypeOf(subset).Kind()
|
||||
|
||||
if listKind != reflect.Array && listKind != reflect.Slice {
|
||||
if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map {
|
||||
return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
|
||||
}
|
||||
|
||||
if subsetKind != reflect.Array && subsetKind != reflect.Slice {
|
||||
if subsetKind != reflect.Array && subsetKind != reflect.Slice && listKind != reflect.Map {
|
||||
return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
|
||||
}
|
||||
|
||||
subsetValue := reflect.ValueOf(subset)
|
||||
if subsetKind == reflect.Map && listKind == reflect.Map {
|
||||
listValue := reflect.ValueOf(list)
|
||||
subsetKeys := subsetValue.MapKeys()
|
||||
|
||||
for i := 0; i < len(subsetKeys); i++ {
|
||||
subsetKey := subsetKeys[i]
|
||||
subsetElement := subsetValue.MapIndex(subsetKey).Interface()
|
||||
listElement := listValue.MapIndex(subsetKey).Interface()
|
||||
|
||||
if !ObjectsAreEqual(subsetElement, listElement) {
|
||||
return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", list, subsetElement), msgAndArgs...)
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
for i := 0; i < subsetValue.Len(); i++ {
|
||||
element := subsetValue.Index(i).Interface()
|
||||
ok, found := containsElement(list, element)
|
||||
@@ -859,7 +879,6 @@ func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{})
|
||||
return Fail(t, "nil is the empty set which is a subset of every set", msgAndArgs...)
|
||||
}
|
||||
|
||||
subsetValue := reflect.ValueOf(subset)
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
ok = false
|
||||
@@ -869,14 +888,32 @@ func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{})
|
||||
listKind := reflect.TypeOf(list).Kind()
|
||||
subsetKind := reflect.TypeOf(subset).Kind()
|
||||
|
||||
if listKind != reflect.Array && listKind != reflect.Slice {
|
||||
if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map {
|
||||
return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
|
||||
}
|
||||
|
||||
if subsetKind != reflect.Array && subsetKind != reflect.Slice {
|
||||
if subsetKind != reflect.Array && subsetKind != reflect.Slice && listKind != reflect.Map {
|
||||
return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
|
||||
}
|
||||
|
||||
subsetValue := reflect.ValueOf(subset)
|
||||
if subsetKind == reflect.Map && listKind == reflect.Map {
|
||||
listValue := reflect.ValueOf(list)
|
||||
subsetKeys := subsetValue.MapKeys()
|
||||
|
||||
for i := 0; i < len(subsetKeys); i++ {
|
||||
subsetKey := subsetKeys[i]
|
||||
subsetElement := subsetValue.MapIndex(subsetKey).Interface()
|
||||
listElement := listValue.MapIndex(subsetKey).Interface()
|
||||
|
||||
if !ObjectsAreEqual(subsetElement, listElement) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
|
||||
}
|
||||
|
||||
for i := 0; i < subsetValue.Len(); i++ {
|
||||
element := subsetValue.Index(i).Interface()
|
||||
ok, found := containsElement(list, element)
|
||||
@@ -1109,6 +1146,27 @@ func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration,
|
||||
return true
|
||||
}
|
||||
|
||||
// WithinRange asserts that a time is within a time range (inclusive).
|
||||
//
|
||||
// assert.WithinRange(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second))
|
||||
func WithinRange(t TestingT, actual, start, end time.Time, msgAndArgs ...interface{}) bool {
|
||||
if h, ok := t.(tHelper); ok {
|
||||
h.Helper()
|
||||
}
|
||||
|
||||
if end.Before(start) {
|
||||
return Fail(t, "Start should be before end", msgAndArgs...)
|
||||
}
|
||||
|
||||
if actual.Before(start) {
|
||||
return Fail(t, fmt.Sprintf("Time %v expected to be in time range %v to %v, but is before the range", actual, start, end), msgAndArgs...)
|
||||
} else if actual.After(end) {
|
||||
return Fail(t, fmt.Sprintf("Time %v expected to be in time range %v to %v, but is after the range", actual, start, end), msgAndArgs...)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func toFloat(x interface{}) (float64, bool) {
|
||||
var xf float64
|
||||
xok := true
|
||||
|
||||
+117
-35
@@ -70,6 +70,9 @@ type Call struct {
|
||||
// if the PanicMsg is set to a non nil string the function call will panic
|
||||
// irrespective of other settings
|
||||
PanicMsg *string
|
||||
|
||||
// Calls which must be satisfied before this call can be
|
||||
requires []*Call
|
||||
}
|
||||
|
||||
func newCall(parent *Mock, methodName string, callerInfo []string, methodArguments ...interface{}) *Call {
|
||||
@@ -199,6 +202,64 @@ func (c *Call) On(methodName string, arguments ...interface{}) *Call {
|
||||
return c.Parent.On(methodName, arguments...)
|
||||
}
|
||||
|
||||
// Unset removes a mock handler from being called.
|
||||
// test.On("func", mock.Anything).Unset()
|
||||
func (c *Call) Unset() *Call {
|
||||
var unlockOnce sync.Once
|
||||
|
||||
for _, arg := range c.Arguments {
|
||||
if v := reflect.ValueOf(arg); v.Kind() == reflect.Func {
|
||||
panic(fmt.Sprintf("cannot use Func in expectations. Use mock.AnythingOfType(\"%T\")", arg))
|
||||
}
|
||||
}
|
||||
|
||||
c.lock()
|
||||
defer unlockOnce.Do(c.unlock)
|
||||
|
||||
foundMatchingCall := false
|
||||
|
||||
for i, call := range c.Parent.ExpectedCalls {
|
||||
if call.Method == c.Method {
|
||||
_, diffCount := call.Arguments.Diff(c.Arguments)
|
||||
if diffCount == 0 {
|
||||
foundMatchingCall = true
|
||||
// Remove from ExpectedCalls
|
||||
c.Parent.ExpectedCalls = append(c.Parent.ExpectedCalls[:i], c.Parent.ExpectedCalls[i+1:]...)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !foundMatchingCall {
|
||||
unlockOnce.Do(c.unlock)
|
||||
c.Parent.fail("\n\nmock: Could not find expected call\n-----------------------------\n\n%s\n\n",
|
||||
callString(c.Method, c.Arguments, true),
|
||||
)
|
||||
}
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
// NotBefore indicates that the mock should only be called after the referenced
|
||||
// calls have been called as expected. The referenced calls may be from the
|
||||
// same mock instance and/or other mock instances.
|
||||
//
|
||||
// Mock.On("Do").Return(nil).Notbefore(
|
||||
// Mock.On("Init").Return(nil)
|
||||
// )
|
||||
func (c *Call) NotBefore(calls ...*Call) *Call {
|
||||
c.lock()
|
||||
defer c.unlock()
|
||||
|
||||
for _, call := range calls {
|
||||
if call.Parent == nil {
|
||||
panic("not before calls must be created with Mock.On()")
|
||||
}
|
||||
}
|
||||
|
||||
c.requires = append(c.requires, calls...)
|
||||
return c
|
||||
}
|
||||
|
||||
// Mock is the workhorse used to track activity on another object.
|
||||
// For an example of its usage, refer to the "Example Usage" section at the top
|
||||
// of this document.
|
||||
@@ -232,7 +293,6 @@ func (m *Mock) String() string {
|
||||
// TestData holds any data that might be useful for testing. Testify ignores
|
||||
// this data completely allowing you to do whatever you like with it.
|
||||
func (m *Mock) TestData() objx.Map {
|
||||
|
||||
if m.testData == nil {
|
||||
m.testData = make(objx.Map)
|
||||
}
|
||||
@@ -354,7 +414,6 @@ func (m *Mock) findClosestCall(method string, arguments ...interface{}) (*Call,
|
||||
}
|
||||
|
||||
func callString(method string, arguments Arguments, includeArgumentValues bool) string {
|
||||
|
||||
var argValsString string
|
||||
if includeArgumentValues {
|
||||
var argVals []string
|
||||
@@ -378,10 +437,10 @@ func (m *Mock) Called(arguments ...interface{}) Arguments {
|
||||
panic("Couldn't get the caller information")
|
||||
}
|
||||
functionPath := runtime.FuncForPC(pc).Name()
|
||||
//Next four lines are required to use GCCGO function naming conventions.
|
||||
//For Ex: github_com_docker_libkv_store_mock.WatchTree.pN39_github_com_docker_libkv_store_mock.Mock
|
||||
//uses interface information unlike golang github.com/docker/libkv/store/mock.(*Mock).WatchTree
|
||||
//With GCCGO we need to remove interface information starting from pN<dd>.
|
||||
// Next four lines are required to use GCCGO function naming conventions.
|
||||
// For Ex: github_com_docker_libkv_store_mock.WatchTree.pN39_github_com_docker_libkv_store_mock.Mock
|
||||
// uses interface information unlike golang github.com/docker/libkv/store/mock.(*Mock).WatchTree
|
||||
// With GCCGO we need to remove interface information starting from pN<dd>.
|
||||
re := regexp.MustCompile("\\.pN\\d+_")
|
||||
if re.MatchString(functionPath) {
|
||||
functionPath = re.Split(functionPath, -1)[0]
|
||||
@@ -397,7 +456,7 @@ func (m *Mock) Called(arguments ...interface{}) Arguments {
|
||||
// If Call.WaitFor is set, blocks until the channel is closed or receives a message.
|
||||
func (m *Mock) MethodCalled(methodName string, arguments ...interface{}) Arguments {
|
||||
m.mutex.Lock()
|
||||
//TODO: could combine expected and closes in single loop
|
||||
// TODO: could combine expected and closes in single loop
|
||||
found, call := m.findExpectedCall(methodName, arguments...)
|
||||
|
||||
if found < 0 {
|
||||
@@ -427,6 +486,25 @@ func (m *Mock) MethodCalled(methodName string, arguments ...interface{}) Argumen
|
||||
}
|
||||
}
|
||||
|
||||
for _, requirement := range call.requires {
|
||||
if satisfied, _ := requirement.Parent.checkExpectation(requirement); !satisfied {
|
||||
m.mutex.Unlock()
|
||||
m.fail("mock: Unexpected Method Call\n-----------------------------\n\n%s\n\nMust not be called before%s:\n\n%s",
|
||||
callString(call.Method, call.Arguments, true),
|
||||
func() (s string) {
|
||||
if requirement.totalCalls > 0 {
|
||||
s = " another call of"
|
||||
}
|
||||
if call.Parent != requirement.Parent {
|
||||
s += " method from another mock instance"
|
||||
}
|
||||
return
|
||||
}(),
|
||||
callString(requirement.Method, requirement.Arguments, true),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if call.Repeatability == 1 {
|
||||
call.Repeatability = -1
|
||||
} else if call.Repeatability > 1 {
|
||||
@@ -484,9 +562,9 @@ func AssertExpectationsForObjects(t TestingT, testObjects ...interface{}) bool {
|
||||
h.Helper()
|
||||
}
|
||||
for _, obj := range testObjects {
|
||||
if m, ok := obj.(Mock); ok {
|
||||
if m, ok := obj.(*Mock); ok {
|
||||
t.Logf("Deprecated mock.AssertExpectationsForObjects(myMock.Mock) use mock.AssertExpectationsForObjects(myMock)")
|
||||
obj = &m
|
||||
obj = m
|
||||
}
|
||||
m := obj.(assertExpectationser)
|
||||
if !m.AssertExpectations(t) {
|
||||
@@ -503,34 +581,36 @@ func (m *Mock) AssertExpectations(t TestingT) bool {
|
||||
if h, ok := t.(tHelper); ok {
|
||||
h.Helper()
|
||||
}
|
||||
|
||||
m.mutex.Lock()
|
||||
defer m.mutex.Unlock()
|
||||
var somethingMissing bool
|
||||
var failedExpectations int
|
||||
|
||||
// iterate through each expectation
|
||||
expectedCalls := m.expectedCalls()
|
||||
for _, expectedCall := range expectedCalls {
|
||||
if !expectedCall.optional && !m.methodWasCalled(expectedCall.Method, expectedCall.Arguments) && expectedCall.totalCalls == 0 {
|
||||
somethingMissing = true
|
||||
satisfied, reason := m.checkExpectation(expectedCall)
|
||||
if !satisfied {
|
||||
failedExpectations++
|
||||
t.Logf("FAIL:\t%s(%s)\n\t\tat: %s", expectedCall.Method, expectedCall.Arguments.String(), expectedCall.callerInfo)
|
||||
} else {
|
||||
if expectedCall.Repeatability > 0 {
|
||||
somethingMissing = true
|
||||
failedExpectations++
|
||||
t.Logf("FAIL:\t%s(%s)\n\t\tat: %s", expectedCall.Method, expectedCall.Arguments.String(), expectedCall.callerInfo)
|
||||
} else {
|
||||
t.Logf("PASS:\t%s(%s)", expectedCall.Method, expectedCall.Arguments.String())
|
||||
}
|
||||
}
|
||||
t.Logf(reason)
|
||||
}
|
||||
|
||||
if somethingMissing {
|
||||
if failedExpectations != 0 {
|
||||
t.Errorf("FAIL: %d out of %d expectation(s) were met.\n\tThe code you are testing needs to make %d more call(s).\n\tat: %s", len(expectedCalls)-failedExpectations, len(expectedCalls), failedExpectations, assert.CallerInfo())
|
||||
}
|
||||
|
||||
return !somethingMissing
|
||||
return failedExpectations == 0
|
||||
}
|
||||
|
||||
func (m *Mock) checkExpectation(call *Call) (bool, string) {
|
||||
if !call.optional && !m.methodWasCalled(call.Method, call.Arguments) && call.totalCalls == 0 {
|
||||
return false, fmt.Sprintf("FAIL:\t%s(%s)\n\t\tat: %s", call.Method, call.Arguments.String(), call.callerInfo)
|
||||
}
|
||||
if call.Repeatability > 0 {
|
||||
return false, fmt.Sprintf("FAIL:\t%s(%s)\n\t\tat: %s", call.Method, call.Arguments.String(), call.callerInfo)
|
||||
}
|
||||
return true, fmt.Sprintf("PASS:\t%s(%s)", call.Method, call.Arguments.String())
|
||||
}
|
||||
|
||||
// AssertNumberOfCalls asserts that the method was called expectedCalls times.
|
||||
@@ -781,12 +861,12 @@ func (args Arguments) Is(objects ...interface{}) bool {
|
||||
//
|
||||
// Returns the diff string and number of differences found.
|
||||
func (args Arguments) Diff(objects []interface{}) (string, int) {
|
||||
//TODO: could return string as error and nil for No difference
|
||||
// TODO: could return string as error and nil for No difference
|
||||
|
||||
var output = "\n"
|
||||
output := "\n"
|
||||
var differences int
|
||||
|
||||
var maxArgCount = len(args)
|
||||
maxArgCount := len(args)
|
||||
if len(objects) > maxArgCount {
|
||||
maxArgCount = len(objects)
|
||||
}
|
||||
@@ -812,21 +892,28 @@ func (args Arguments) Diff(objects []interface{}) (string, int) {
|
||||
}
|
||||
|
||||
if matcher, ok := expected.(argumentMatcher); ok {
|
||||
if matcher.Matches(actual) {
|
||||
var matches bool
|
||||
func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
actualFmt = fmt.Sprintf("panic in argument matcher: %v", r)
|
||||
}
|
||||
}()
|
||||
matches = matcher.Matches(actual)
|
||||
}()
|
||||
if matches {
|
||||
output = fmt.Sprintf("%s\t%d: PASS: %s matched by %s\n", output, i, actualFmt, matcher)
|
||||
} else {
|
||||
differences++
|
||||
output = fmt.Sprintf("%s\t%d: FAIL: %s not matched by %s\n", output, i, actualFmt, matcher)
|
||||
}
|
||||
} else if reflect.TypeOf(expected) == reflect.TypeOf((*AnythingOfTypeArgument)(nil)).Elem() {
|
||||
|
||||
// type checking
|
||||
if reflect.TypeOf(actual).Name() != string(expected.(AnythingOfTypeArgument)) && reflect.TypeOf(actual).String() != string(expected.(AnythingOfTypeArgument)) {
|
||||
// not match
|
||||
differences++
|
||||
output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, expected, reflect.TypeOf(actual).Name(), actualFmt)
|
||||
}
|
||||
|
||||
} else if reflect.TypeOf(expected) == reflect.TypeOf((*IsTypeArgument)(nil)) {
|
||||
t := expected.(*IsTypeArgument).t
|
||||
if reflect.TypeOf(t) != reflect.TypeOf(actual) {
|
||||
@@ -834,7 +921,6 @@ func (args Arguments) Diff(objects []interface{}) (string, int) {
|
||||
output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, reflect.TypeOf(t).Name(), reflect.TypeOf(actual).Name(), actualFmt)
|
||||
}
|
||||
} else {
|
||||
|
||||
// normal checking
|
||||
|
||||
if assert.ObjectsAreEqual(expected, Anything) || assert.ObjectsAreEqual(actual, Anything) || assert.ObjectsAreEqual(actual, expected) {
|
||||
@@ -854,7 +940,6 @@ func (args Arguments) Diff(objects []interface{}) (string, int) {
|
||||
}
|
||||
|
||||
return output, differences
|
||||
|
||||
}
|
||||
|
||||
// Assert compares the arguments with the specified objects and fails if
|
||||
@@ -876,7 +961,6 @@ func (args Arguments) Assert(t TestingT, objects ...interface{}) bool {
|
||||
t.Errorf("%sArguments do not match.", assert.CallerInfo())
|
||||
|
||||
return false
|
||||
|
||||
}
|
||||
|
||||
// String gets the argument at the specified index. Panics if there is no argument, or
|
||||
@@ -885,7 +969,6 @@ func (args Arguments) Assert(t TestingT, objects ...interface{}) bool {
|
||||
// If no index is provided, String() returns a complete string representation
|
||||
// of the arguments.
|
||||
func (args Arguments) String(indexOrNil ...int) string {
|
||||
|
||||
if len(indexOrNil) == 0 {
|
||||
// normal String() method - return a string representation of the args
|
||||
var argsStr []string
|
||||
@@ -895,7 +978,7 @@ func (args Arguments) String(indexOrNil ...int) string {
|
||||
return strings.Join(argsStr, ",")
|
||||
} else if len(indexOrNil) == 1 {
|
||||
// Index has been specified - get the argument at that index
|
||||
var index = indexOrNil[0]
|
||||
index := indexOrNil[0]
|
||||
var s string
|
||||
var ok bool
|
||||
if s, ok = args.Get(index).(string); !ok {
|
||||
@@ -905,7 +988,6 @@ func (args Arguments) String(indexOrNil ...int) string {
|
||||
}
|
||||
|
||||
panic(fmt.Sprintf("assert: arguments: Wrong number of arguments passed to String. Must be 0 or 1, not %d", len(indexOrNil)))
|
||||
|
||||
}
|
||||
|
||||
// Int gets the argument at the specified index. Panics if there is no argument, or
|
||||
|
||||
+26
@@ -1864,6 +1864,32 @@ func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta tim
|
||||
t.FailNow()
|
||||
}
|
||||
|
||||
// WithinRange asserts that a time is within a time range (inclusive).
|
||||
//
|
||||
// assert.WithinRange(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second))
|
||||
func WithinRange(t TestingT, actual time.Time, start time.Time, end time.Time, msgAndArgs ...interface{}) {
|
||||
if h, ok := t.(tHelper); ok {
|
||||
h.Helper()
|
||||
}
|
||||
if assert.WithinRange(t, actual, start, end, msgAndArgs...) {
|
||||
return
|
||||
}
|
||||
t.FailNow()
|
||||
}
|
||||
|
||||
// WithinRangef asserts that a time is within a time range (inclusive).
|
||||
//
|
||||
// assert.WithinRangef(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted")
|
||||
func WithinRangef(t TestingT, actual time.Time, start time.Time, end time.Time, msg string, args ...interface{}) {
|
||||
if h, ok := t.(tHelper); ok {
|
||||
h.Helper()
|
||||
}
|
||||
if assert.WithinRangef(t, actual, start, end, msg, args...) {
|
||||
return
|
||||
}
|
||||
t.FailNow()
|
||||
}
|
||||
|
||||
// YAMLEq asserts that two YAML strings are equivalent.
|
||||
func YAMLEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) {
|
||||
if h, ok := t.(tHelper); ok {
|
||||
|
||||
+20
@@ -1462,6 +1462,26 @@ func (a *Assertions) WithinDurationf(expected time.Time, actual time.Time, delta
|
||||
WithinDurationf(a.t, expected, actual, delta, msg, args...)
|
||||
}
|
||||
|
||||
// WithinRange asserts that a time is within a time range (inclusive).
|
||||
//
|
||||
// a.WithinRange(time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second))
|
||||
func (a *Assertions) WithinRange(actual time.Time, start time.Time, end time.Time, msgAndArgs ...interface{}) {
|
||||
if h, ok := a.t.(tHelper); ok {
|
||||
h.Helper()
|
||||
}
|
||||
WithinRange(a.t, actual, start, end, msgAndArgs...)
|
||||
}
|
||||
|
||||
// WithinRangef asserts that a time is within a time range (inclusive).
|
||||
//
|
||||
// a.WithinRangef(time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted")
|
||||
func (a *Assertions) WithinRangef(actual time.Time, start time.Time, end time.Time, msg string, args ...interface{}) {
|
||||
if h, ok := a.t.(tHelper); ok {
|
||||
h.Helper()
|
||||
}
|
||||
WithinRangef(a.t, actual, start, end, msg, args...)
|
||||
}
|
||||
|
||||
// YAMLEq asserts that two YAML strings are equivalent.
|
||||
func (a *Assertions) YAMLEq(expected string, actual string, msgAndArgs ...interface{}) {
|
||||
if h, ok := a.t.(tHelper); ok {
|
||||
|
||||
Reference in New Issue
Block a user