Merge pull request #102913 from pacoxu/upgrade-promotheus-common

upgrade prometheus/common to v0.28.0
This commit is contained in:
Kubernetes Prow Robot
2021-08-09 08:03:31 -07:00
committed by GitHub
127 changed files with 165811 additions and 27046 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -42,6 +42,8 @@ const (
CustomOps = 1 << iota
// AggregatedList will generated a method for AggregatedList().
AggregatedList = 1 << iota
// ListUsable will generate a method for ListUsable().
ListUsable = 1 << iota
// ReadOnly specifies that the given resource is read-only and should not
// have insert() or delete() methods generated for the wrapper.
@@ -99,6 +101,14 @@ var AllServices = []*ServiceInfo{
keyType: Global,
serviceType: reflect.TypeOf(&alpha.GlobalAddressesService{}),
},
{
Object: "Address",
Service: "GlobalAddresses",
Resource: "addresses",
version: VersionBeta,
keyType: Global,
serviceType: reflect.TypeOf(&beta.GlobalAddressesService{}),
},
{
Object: "Address",
Service: "GlobalAddresses",
@@ -116,7 +126,9 @@ var AllServices = []*ServiceInfo{
"GetHealth",
"Patch",
"Update",
"SetSecurityPolicy",
},
options: AggregatedList,
},
{
Object: "BackendService",
@@ -129,6 +141,7 @@ var AllServices = []*ServiceInfo{
"Update",
"SetSecurityPolicy",
},
options: AggregatedList,
},
{
Object: "BackendService",
@@ -141,6 +154,7 @@ var AllServices = []*ServiceInfo{
"Update",
"SetSecurityPolicy",
},
options: AggregatedList,
},
{
Object: "BackendService",
@@ -513,6 +527,50 @@ var AllServices = []*ServiceInfo{
options: ReadOnly,
serviceType: reflect.TypeOf(&ga.RegionsService{}),
},
{
Object: "Router",
Service: "Routers",
Resource: "routers",
keyType: Regional,
version: VersionAlpha,
options: AggregatedList,
serviceType: reflect.TypeOf(&alpha.RoutersService{}),
additionalMethods: []string{
"Patch",
"Preview",
"GetRouterStatus",
"TestIamPermissions",
},
},
{
Object: "Router",
Service: "Routers",
Resource: "routers",
keyType: Regional,
version: VersionBeta,
options: AggregatedList,
serviceType: reflect.TypeOf(&beta.RoutersService{}),
additionalMethods: []string{
"Patch",
"Preview",
"GetRouterStatus",
"TestIamPermissions",
},
},
{
Object: "Router",
Service: "Routers",
Resource: "routers",
keyType: Regional,
version: VersionGA,
options: AggregatedList,
serviceType: reflect.TypeOf(&ga.RoutersService{}),
additionalMethods: []string{
"Patch",
"Preview",
"GetRouterStatus",
},
},
{
Object: "Route",
Service: "Routes",
@@ -535,6 +593,28 @@ var AllServices = []*ServiceInfo{
"RemoveRule",
},
},
{
Object: "ServiceAttachment",
Service: "ServiceAttachments",
Resource: "serviceAttachments",
version: VersionBeta,
keyType: Regional,
serviceType: reflect.TypeOf(&beta.ServiceAttachmentsService{}),
additionalMethods: []string{
"Patch",
},
},
{
Object: "ServiceAttachment",
Service: "ServiceAttachments",
Resource: "serviceAttachments",
version: VersionAlpha,
keyType: Regional,
serviceType: reflect.TypeOf(&alpha.ServiceAttachmentsService{}),
additionalMethods: []string{
"Patch",
},
},
{
Object: "SslCertificate",
Service: "SslCertificates",
@@ -597,6 +677,7 @@ var AllServices = []*ServiceInfo{
version: VersionAlpha,
keyType: Regional,
serviceType: reflect.TypeOf(&alpha.SubnetworksService{}),
options: ListUsable,
},
{
Object: "Subnetwork",
@@ -605,6 +686,7 @@ var AllServices = []*ServiceInfo{
version: VersionBeta,
keyType: Regional,
serviceType: reflect.TypeOf(&alpha.SubnetworksService{}),
options: ListUsable,
},
{
Object: "Subnetwork",
@@ -613,6 +695,7 @@ var AllServices = []*ServiceInfo{
version: VersionGA,
keyType: Regional,
serviceType: reflect.TypeOf(&alpha.SubnetworksService{}),
options: ListUsable,
},
{
Object: "TargetHttpProxy",
@@ -699,6 +782,7 @@ var AllServices = []*ServiceInfo{
keyType: Global,
serviceType: reflect.TypeOf(&alpha.TargetHttpsProxiesService{}),
additionalMethods: []string{
"SetCertificateMap",
"SetSslCertificates",
"SetSslPolicy",
"SetUrlMap",
@@ -764,6 +848,28 @@ var AllServices = []*ServiceInfo{
"RemoveInstance",
},
},
{
Object: "TargetTcpProxy",
Service: "TargetTcpProxies",
Resource: "targetTcpProxies",
version: VersionAlpha,
keyType: Global,
serviceType: reflect.TypeOf(&alpha.TargetTcpProxiesService{}),
additionalMethods: []string{
"SetBackendService",
},
},
{
Object: "TargetTcpProxy",
Service: "TargetTcpProxies",
Resource: "targetTcpProxies",
version: VersionBeta,
keyType: Global,
serviceType: reflect.TypeOf(&beta.TargetTcpProxiesService{}),
additionalMethods: []string{
"SetBackendService",
},
},
{
Object: "UrlMap",
Service: "UrlMaps",

View File

@@ -99,6 +99,16 @@ func (i *ServiceInfo) ObjectAggregatedListType() string {
return fmt.Sprintf("%v.%vAggregatedList", i.Version(), i.Object)
}
// ObjectListUsableType is the compute List type for the object (contains Items field).
func (i *ServiceInfo) ObjectListUsableType() string {
return fmt.Sprintf("%v.Usable%vAggregatedList", i.version, i.Service)
}
// FQObjectType is fully qualified name of the object (e.g. compute.Instance).
func (i *ServiceInfo) FQListUsableObjectType() string {
return fmt.Sprintf("%v.Usable%v", i.Version(), i.Object)
}
// MockWrapType is the name of the concrete mock for this type.
func (i *ServiceInfo) MockWrapType() string {
return "Mock" + i.WrapType()
@@ -221,6 +231,10 @@ func (i *ServiceInfo) AggregatedListField() string {
return i.aggregatedListField
}
func (i *ServiceInfo) ListUsable() bool {
return i.options&ListUsable != 0
}
// ServiceGroup is a grouping of the same service but at different API versions.
type ServiceGroup struct {
Alpha *ServiceInfo

View File

@@ -559,14 +559,14 @@ func UpdateRegionBackendServiceHook(ctx context.Context, key *meta.Key, obj *ga.
// UpdateRegionBackendServiceHook defines the hook for updating a Region
// BackendsService. It replaces the object with the same key in the mock with
// the updated object.
func UpdateAlphaRegionBackendServiceHook(ctx context.Context, key *meta.Key, obj *ga.BackendService, m *cloud.MockAlphaRegionBackendServices) error {
func UpdateAlphaRegionBackendServiceHook(ctx context.Context, key *meta.Key, obj *alpha.BackendService, m *cloud.MockAlphaRegionBackendServices) error {
_, err := m.Get(ctx, key)
if err != nil {
return err
}
obj.Name = key.Name
projectID := m.ProjectRouter.ProjectID(ctx, "ga", "backendServices")
projectID := m.ProjectRouter.ProjectID(ctx, "alpha", "backendServices")
obj.SelfLink = cloud.SelfLink(meta.VersionAlpha, projectID, "backendServices", key)
m.Objects[*key] = &cloud.MockRegionBackendServicesObj{Obj: obj}
@@ -576,14 +576,14 @@ func UpdateAlphaRegionBackendServiceHook(ctx context.Context, key *meta.Key, obj
// UpdateBetaRegionBackendServiceHook defines the hook for updating a Region
// BackendsService. It replaces the object with the same key in the mock with
// the updated object.
func UpdateBetaRegionBackendServiceHook(ctx context.Context, key *meta.Key, obj *ga.BackendService, m *cloud.MockBetaRegionBackendServices) error {
func UpdateBetaRegionBackendServiceHook(ctx context.Context, key *meta.Key, obj *beta.BackendService, m *cloud.MockBetaRegionBackendServices) error {
_, err := m.Get(ctx, key)
if err != nil {
return err
}
obj.Name = key.Name
projectID := m.ProjectRouter.ProjectID(ctx, "ga", "backendServices")
projectID := m.ProjectRouter.ProjectID(ctx, "beta", "backendServices")
obj.SelfLink = cloud.SelfLink(meta.VersionAlpha, projectID, "backendServices", key)
m.Objects[*key] = &cloud.MockRegionBackendServicesObj{Obj: obj}
@@ -704,15 +704,15 @@ func UpdateAlphaRegionURLMapHook(ctx context.Context, key *meta.Key, obj *alpha.
// UpdateBetaRegionURLMapHook defines the hook for updating an alpha UrlMap.
// It replaces the object with the same key in the mock with the updated object.
func UpdateBetaRegionURLMapHook(ctx context.Context, key *meta.Key, obj *alpha.UrlMap, m *cloud.MockBetaRegionUrlMaps) error {
func UpdateBetaRegionURLMapHook(ctx context.Context, key *meta.Key, obj *beta.UrlMap, m *cloud.MockBetaRegionUrlMaps) error {
_, err := m.Get(ctx, key)
if err != nil {
return err
}
obj.Name = key.Name
projectID := m.ProjectRouter.ProjectID(ctx, "alpha", "urlMaps")
obj.SelfLink = cloud.SelfLink(meta.VersionAlpha, projectID, "urlMaps", key)
projectID := m.ProjectRouter.ProjectID(ctx, "beta", "urlMaps")
obj.SelfLink = cloud.SelfLink(meta.VersionBeta, projectID, "urlMaps", key)
m.Objects[*key] = &cloud.MockRegionUrlMapsObj{Obj: obj}
return nil
@@ -768,7 +768,7 @@ func SetTargetAlphaForwardingRuleHook(ctx context.Context, key *meta.Key, obj *a
}
// SetTargetBetaForwardingRuleHook defines the hook for setting the target proxy for an Alpha ForwardingRule.
func SetTargetBetaForwardingRuleHook(ctx context.Context, key *meta.Key, obj *alpha.TargetReference, m *cloud.MockBetaForwardingRules) error {
func SetTargetBetaForwardingRuleHook(ctx context.Context, key *meta.Key, obj *beta.TargetReference, m *cloud.MockBetaForwardingRules) error {
fw, err := m.Get(ctx, key)
if err != nil {
return err
@@ -811,7 +811,7 @@ func SetURLMapTargetHTTPProxyHook(ctx context.Context, key *meta.Key, ref *ga.Ur
return nil
}
// SetURLMapTargetHTTPProxyHook defines the hook for setting the url map for a TargetHttpProxy.
// SetURLMapTargetHTTPSProxyHook defines the hook for setting the url map for a TargetHttpsProxy.
func SetURLMapTargetHTTPSProxyHook(ctx context.Context, key *meta.Key, ref *ga.UrlMapReference, m *cloud.MockTargetHttpsProxies) error {
tp, err := m.Get(ctx, key)
if err != nil {
@@ -822,7 +822,7 @@ func SetURLMapTargetHTTPSProxyHook(ctx context.Context, key *meta.Key, ref *ga.U
return nil
}
// SetURLMapTargetHTTPProxyHook defines the hook for setting the url map for a TargetHttpProxy.
// SetURLMapAlphaRegionTargetHTTPSProxyHook defines the hook for setting the url map for a TargetHttpsProxy.
func SetURLMapAlphaRegionTargetHTTPSProxyHook(ctx context.Context, key *meta.Key, ref *alpha.UrlMapReference, m *cloud.MockAlphaRegionTargetHttpsProxies) error {
tp, err := m.Get(ctx, key)
if err != nil {
@@ -833,8 +833,8 @@ func SetURLMapAlphaRegionTargetHTTPSProxyHook(ctx context.Context, key *meta.Key
return nil
}
// SetURLMapBetaRegionTargetHTTPProxyHook defines the hook for setting the url map for a TargetHttpProxy.
func SetURLMapBetaRegionTargetHTTPSProxyHook(ctx context.Context, key *meta.Key, ref *alpha.UrlMapReference, m *cloud.MockBetaRegionTargetHttpsProxies) error {
// SetURLMapBetaRegionTargetHTTPSProxyHook defines the hook for setting the url map for a TargetHttpsProxy.
func SetURLMapBetaRegionTargetHTTPSProxyHook(ctx context.Context, key *meta.Key, ref *beta.UrlMapReference, m *cloud.MockBetaRegionTargetHttpsProxies) error {
tp, err := m.Get(ctx, key)
if err != nil {
return err
@@ -844,7 +844,7 @@ func SetURLMapBetaRegionTargetHTTPSProxyHook(ctx context.Context, key *meta.Key,
return nil
}
// SetURLMapRegionTargetHTTPProxyHook defines the hook for setting the url map for a TargetHttpProxy.
// SetURLMapRegionTargetHTTPSProxyHook defines the hook for setting the url map for a TargetHttpsProxy.
func SetURLMapRegionTargetHTTPSProxyHook(ctx context.Context, key *meta.Key, ref *ga.UrlMapReference, m *cloud.MockRegionTargetHttpsProxies) error {
tp, err := m.Get(ctx, key)
if err != nil {
@@ -900,7 +900,7 @@ func SetURLMapAlphaRegionTargetHTTPProxyHook(ctx context.Context, key *meta.Key,
}
// SetURLMapBetaRegionTargetHTTPProxyHook defines the hook for setting the url map for a TargetHttpProxy.
func SetURLMapBetaRegionTargetHTTPProxyHook(ctx context.Context, key *meta.Key, ref *alpha.UrlMapReference, m *cloud.MockBetaRegionTargetHttpProxies) error {
func SetURLMapBetaRegionTargetHTTPProxyHook(ctx context.Context, key *meta.Key, ref *beta.UrlMapReference, m *cloud.MockBetaRegionTargetHttpProxies) error {
tp, err := m.Get(ctx, key)
if err != nil {
return err
@@ -921,6 +921,28 @@ func SetURLMapRegionTargetHTTPProxyHook(ctx context.Context, key *meta.Key, ref
return nil
}
// SetBackendServiceAlphaTargetTCPProxyHook defines the hook for setting the backend service for an alpha TargetTcpProxy.
func SetBackendServiceAlphaTargetTCPProxyHook(ctx context.Context, key *meta.Key, ref *alpha.TargetTcpProxiesSetBackendServiceRequest, m *cloud.MockAlphaTargetTcpProxies) error {
tp, err := m.Get(ctx, key)
if err != nil {
return err
}
tp.Service = ref.Service
return nil
}
// SetBackendServiceBetaTargetTCPProxyHook defines the hook for setting the backend service for a beta TargetTcpProxy.
func SetBackendServiceBetaTargetTCPProxyHook(ctx context.Context, key *meta.Key, ref *beta.TargetTcpProxiesSetBackendServiceRequest, m *cloud.MockBetaTargetTcpProxies) error {
tp, err := m.Get(ctx, key)
if err != nil {
return err
}
tp.Service = ref.Service
return nil
}
// SetSslCertificateTargetHTTPSProxyHook defines the hook for setting ssl certificates on a TargetHttpsProxy.
func SetSslCertificateTargetHTTPSProxyHook(ctx context.Context, key *meta.Key, req *ga.TargetHttpsProxiesSetSslCertificatesRequest, m *cloud.MockTargetHttpsProxies) error {
tp, err := m.Get(ctx, key)
@@ -942,7 +964,7 @@ func SetSslCertificateAlphaTargetHTTPSProxyHook(ctx context.Context, key *meta.K
return nil
}
// SetSslCertificateAlphaTargetHTTPSProxyHook defines the hook for setting ssl certificates on a TargetHttpsProxy.
// SetSslCertificateBetaTargetHTTPSProxyHook defines the hook for setting ssl certificates on a TargetHttpsProxy.
func SetSslCertificateBetaTargetHTTPSProxyHook(ctx context.Context, key *meta.Key, req *beta.TargetHttpsProxiesSetSslCertificatesRequest, m *cloud.MockBetaTargetHttpsProxies) error {
tp, err := m.Get(ctx, key)
if err != nil {
@@ -953,7 +975,7 @@ func SetSslCertificateBetaTargetHTTPSProxyHook(ctx context.Context, key *meta.Ke
}
// SetSslCertificateAlphaRegionTargetHTTPSProxyHook defines the hook for setting ssl certificates on a TargetHttpsProxy.
func SetSslCertificateAlphaRegionTargetHTTPSProxyHook(ctx context.Context, key *meta.Key, req *alpha.TargetHttpsProxiesSetSslCertificatesRequest, m *cloud.MockAlphaRegionTargetHttpsProxies) error {
func SetSslCertificateAlphaRegionTargetHTTPSProxyHook(ctx context.Context, key *meta.Key, req *alpha.RegionTargetHttpsProxiesSetSslCertificatesRequest, m *cloud.MockAlphaRegionTargetHttpsProxies) error {
tp, err := m.Get(ctx, key)
if err != nil {
return err
@@ -964,7 +986,7 @@ func SetSslCertificateAlphaRegionTargetHTTPSProxyHook(ctx context.Context, key *
}
// SetSslCertificateBetaRegionTargetHTTPSProxyHook defines the hook for setting ssl certificates on a TargetHttpsProxy.
func SetSslCertificateBetaRegionTargetHTTPSProxyHook(ctx context.Context, key *meta.Key, req *alpha.TargetHttpsProxiesSetSslCertificatesRequest, m *cloud.MockBetaRegionTargetHttpsProxies) error {
func SetSslCertificateBetaRegionTargetHTTPSProxyHook(ctx context.Context, key *meta.Key, req *beta.RegionTargetHttpsProxiesSetSslCertificatesRequest, m *cloud.MockBetaRegionTargetHttpsProxies) error {
tp, err := m.Get(ctx, key)
if err != nil {
return err
@@ -975,7 +997,7 @@ func SetSslCertificateBetaRegionTargetHTTPSProxyHook(ctx context.Context, key *m
}
// SetSslCertificateRegionTargetHTTPSProxyHook defines the hook for setting ssl certificates on a TargetHttpsProxy.
func SetSslCertificateRegionTargetHTTPSProxyHook(ctx context.Context, key *meta.Key, req *ga.TargetHttpsProxiesSetSslCertificatesRequest, m *cloud.MockRegionTargetHttpsProxies) error {
func SetSslCertificateRegionTargetHTTPSProxyHook(ctx context.Context, key *meta.Key, req *ga.RegionTargetHttpsProxiesSetSslCertificatesRequest, m *cloud.MockRegionTargetHttpsProxies) error {
tp, err := m.Get(ctx, key)
if err != nil {
return err
@@ -985,7 +1007,7 @@ func SetSslCertificateRegionTargetHTTPSProxyHook(ctx context.Context, key *meta.
return nil
}
// SetSslCertificateTargetHTTPSProxyHook defines the hook for setting ssl certificates on a TargetHttpsProxy.
// SetSslPolicyTargetHTTPSProxyHook defines the hook for setting ssl certificates on a TargetHttpsProxy.
func SetSslPolicyTargetHTTPSProxyHook(ctx context.Context, key *meta.Key, ref *ga.SslPolicyReference, m *cloud.MockTargetHttpsProxies) error {
tp, err := m.Get(ctx, key)
if err != nil {
@@ -996,7 +1018,7 @@ func SetSslPolicyTargetHTTPSProxyHook(ctx context.Context, key *meta.Key, ref *g
return nil
}
// SetSslCertificateAlphaTargetHTTPSProxyHook defines the hook for setting ssl certificates on a TargetHttpsProxy.
// SetSslPolicyAlphaTargetHTTPSProxyHook defines the hook for setting ssl certificates on a TargetHttpsProxy.
func SetSslPolicyAlphaTargetHTTPSProxyHook(ctx context.Context, key *meta.Key, ref *alpha.SslPolicyReference, m *cloud.MockAlphaTargetHttpsProxies) error {
tp, err := m.Get(ctx, key)
if err != nil {
@@ -1006,7 +1028,7 @@ func SetSslPolicyAlphaTargetHTTPSProxyHook(ctx context.Context, key *meta.Key, r
return nil
}
// SetSslCertificateAlphaTargetHTTPSProxyHook defines the hook for setting ssl certificates on a TargetHttpsProxy.
// SetSslPolicyBetaTargetHTTPSProxyHook defines the hook for setting ssl certificates on a TargetHttpsProxy.
func SetSslPolicyBetaTargetHTTPSProxyHook(ctx context.Context, key *meta.Key, ref *beta.SslPolicyReference, m *cloud.MockBetaTargetHttpsProxies) error {
tp, err := m.Get(ctx, key)
if err != nil {

View File

@@ -39,16 +39,20 @@ type ResourceID struct {
// Equal returns true if two resource IDs are equal.
func (r *ResourceID) Equal(other *ResourceID) bool {
if r.ProjectID != other.ProjectID || r.Resource != other.Resource {
return false
switch {
case r == nil && other == nil:
return true
case r == nil || other == nil:
return false
case r.ProjectID != other.ProjectID || r.Resource != other.Resource:
return false
case r.Key != nil && other.Key != nil:
return *r.Key == *other.Key
case r.Key == nil && other.Key == nil:
return true
default:
return false
}
if r.Key != nil && other.Key != nil {
return *r.Key == *other.Key
}
if r.Key == nil && other.Key == nil {
return true
}
return false
}
// RelativeResourceName returns the relative resource name string

View File

@@ -63,6 +63,9 @@ func newCall(t TestHelper, receiver interface{}, method string, methodType refle
}
}
// callerInfo's skip should be updated if the number of calls between the user's test
// and this line changes, i.e. this code is wrapped in another anonymous function.
// 0 is us, 1 is RecordCallWithMethodType(), 2 is the generated recorder, and 3 is the user's test.
origin := callerInfo(3)
actions := []func([]interface{}) []interface{}{func([]interface{}) []interface{} {
// Synthesize the zero value for each of the return args' types.
@@ -301,14 +304,9 @@ func (c *Call) matches(args []interface{}) error {
for i, m := range c.args {
if !m.Matches(args[i]) {
got := fmt.Sprintf("%v", args[i])
if gs, ok := m.(GotFormatter); ok {
got = gs.Got(args[i])
}
return fmt.Errorf(
"expected call at %s doesn't match the argument at index %d.\nGot: %v\nWant: %v",
c.origin, i, got, m,
c.origin, i, formatGottenArg(m, args[i]), m,
)
}
}
@@ -331,7 +329,7 @@ func (c *Call) matches(args []interface{}) error {
// Non-variadic args
if !m.Matches(args[i]) {
return fmt.Errorf("expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
c.origin, strconv.Itoa(i), args[i], m)
c.origin, strconv.Itoa(i), formatGottenArg(m, args[i]), m)
}
continue
}
@@ -373,9 +371,9 @@ func (c *Call) matches(args []interface{}) error {
// Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD, matcherE)
// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, matcherC, matcherD)
// Got Foo(a, b, c) want Foo(matcherA, matcherB)
return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
c.origin, strconv.Itoa(i), args[i:], c.args[i])
return fmt.Errorf("expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
c.origin, strconv.Itoa(i), formatGottenArg(m, args[i:]), c.args[i])
}
}
@@ -425,3 +423,11 @@ func setSlice(arg interface{}, v reflect.Value) {
func (c *Call) addAction(action func([]interface{}) []interface{}) {
c.actions = append(c.actions, action)
}
func formatGottenArg(m Matcher, arg interface{}) string {
got := fmt.Sprintf("%v", arg)
if gs, ok := m.(GotFormatter); ok {
got = gs.Got(arg)
}
return got
}

View File

@@ -84,7 +84,11 @@ func (cs callSet) FindMatch(receiver interface{}, method string, args []interfac
for _, call := range exhausted {
if err := call.matches(args); err != nil {
_, _ = fmt.Fprintf(&callsErrors, "\n%v", err)
continue
}
_, _ = fmt.Fprintf(
&callsErrors, "all expected calls for method %q have been exhausted", method,
)
}
if len(expected)+len(exhausted) == 0 {

View File

@@ -50,9 +50,6 @@
// mockObj.EXPECT().SomeMethod(2, "second"),
// mockObj.EXPECT().SomeMethod(3, "third"),
// )
//
// TODO:
// - Handle different argument/return types (e.g. ..., chan, map, interface).
package gomock
import (
@@ -77,6 +74,15 @@ type TestHelper interface {
Helper()
}
// cleanuper is used to check if TestHelper also has the `Cleanup` method. A
// common pattern is to pass in a `*testing.T` to
// `NewController(t TestReporter)`. In Go 1.14+, `*testing.T` has a cleanup
// method. This can be utilized to call `Finish()` so the caller of this library
// does not have to.
type cleanuper interface {
Cleanup(func())
}
// A Controller represents the top-level control of a mock ecosystem. It
// defines the scope and lifetime of mock objects, as well as their
// expectations. It is safe to call Controller's methods from multiple
@@ -115,29 +121,43 @@ type Controller struct {
// NewController returns a new Controller. It is the preferred way to create a
// Controller.
//
// New in go1.14+, if you are passing a *testing.T into this function you no
// longer need to call ctrl.Finish() in your test methods
func NewController(t TestReporter) *Controller {
h, ok := t.(TestHelper)
if !ok {
h = nopTestHelper{t}
h = &nopTestHelper{t}
}
return &Controller{
ctrl := &Controller{
T: h,
expectedCalls: newCallSet(),
}
if c, ok := isCleanuper(ctrl.T); ok {
c.Cleanup(func() {
ctrl.T.Helper()
ctrl.finish(true, nil)
})
}
return ctrl
}
type cancelReporter struct {
TestHelper
t TestHelper
cancel func()
}
func (r *cancelReporter) Errorf(format string, args ...interface{}) {
r.TestHelper.Errorf(format, args...)
r.t.Errorf(format, args...)
}
func (r *cancelReporter) Fatalf(format string, args ...interface{}) {
defer r.cancel()
r.TestHelper.Fatalf(format, args...)
r.t.Fatalf(format, args...)
}
func (r *cancelReporter) Helper() {
r.t.Helper()
}
// WithContext returns a new Controller and a Context, which is cancelled on any
@@ -145,15 +165,22 @@ func (r *cancelReporter) Fatalf(format string, args ...interface{}) {
func WithContext(ctx context.Context, t TestReporter) (*Controller, context.Context) {
h, ok := t.(TestHelper)
if !ok {
h = nopTestHelper{t}
h = &nopTestHelper{t: t}
}
ctx, cancel := context.WithCancel(ctx)
return NewController(&cancelReporter{h, cancel}), ctx
return NewController(&cancelReporter{t: h, cancel: cancel}), ctx
}
type nopTestHelper struct {
TestReporter
t TestReporter
}
func (h *nopTestHelper) Errorf(format string, args ...interface{}) {
h.t.Errorf(format, args...)
}
func (h *nopTestHelper) Fatalf(format string, args ...interface{}) {
h.t.Fatalf(format, args...)
}
func (h nopTestHelper) Helper() {}
@@ -197,7 +224,10 @@ func (ctrl *Controller) Call(receiver interface{}, method string, args ...interf
expected, err := ctrl.expectedCalls.FindMatch(receiver, method, args)
if err != nil {
origin := callerInfo(2)
// callerInfo's skip should be updated if the number of calls between the user's test
// and this line changes, i.e. this code is wrapped in another anonymous function.
// 0 is us, 1 is controller.Call(), 2 is the generated mock, and 3 is the user's test.
origin := callerInfo(3)
ctrl.T.Fatalf("Unexpected call to %T.%v(%v) at %s because: %s", receiver, method, args, origin, err)
}
@@ -230,20 +260,29 @@ func (ctrl *Controller) Call(receiver interface{}, method string, args ...interf
// were called. It should be invoked for each Controller. It is not idempotent
// and therefore can only be invoked once.
func (ctrl *Controller) Finish() {
// If we're currently panicking, probably because this is a deferred call.
// This must be recovered in the deferred function.
err := recover()
ctrl.finish(false, err)
}
func (ctrl *Controller) finish(cleanup bool, panicErr interface{}) {
ctrl.T.Helper()
ctrl.mu.Lock()
defer ctrl.mu.Unlock()
if ctrl.finished {
ctrl.T.Fatalf("Controller.Finish was called more than once. It has to be called exactly once.")
if _, ok := isCleanuper(ctrl.T); !ok {
ctrl.T.Fatalf("Controller.Finish was called more than once. It has to be called exactly once.")
}
return
}
ctrl.finished = true
// If we're currently panicking, probably because this is a deferred call,
// pass through the panic.
if err := recover(); err != nil {
panic(err)
// Short-circuit, pass through the panic.
if panicErr != nil {
panic(panicErr)
}
// Check that all remaining expected calls are satisfied.
@@ -252,13 +291,43 @@ func (ctrl *Controller) Finish() {
ctrl.T.Errorf("missing call(s) to %v", call)
}
if len(failures) != 0 {
ctrl.T.Fatalf("aborting test due to missing call(s)")
if !cleanup {
ctrl.T.Fatalf("aborting test due to missing call(s)")
return
}
ctrl.T.Errorf("aborting test due to missing call(s)")
}
}
// callerInfo returns the file:line of the call site. skip is the number
// of stack frames to skip when reporting. 0 is callerInfo's call site.
func callerInfo(skip int) string {
if _, file, line, ok := runtime.Caller(skip + 1); ok {
return fmt.Sprintf("%s:%d", file, line)
}
return "unknown file"
}
// isCleanuper checks it if t's base TestReporter has a Cleanup method.
func isCleanuper(t TestReporter) (cleanuper, bool) {
tr := unwrapTestReporter(t)
c, ok := tr.(cleanuper)
return c, ok
}
// unwrapTestReporter unwraps TestReporter to the base implementation.
func unwrapTestReporter(t TestReporter) TestReporter {
tr := t
switch nt := t.(type) {
case *cancelReporter:
tr = nt.t
if h, check := tr.(*nopTestHelper); check {
tr = h.t
}
case *nopTestHelper:
tr = nt.t
default:
// not wrapped
}
return tr
}

View File

@@ -102,7 +102,21 @@ type eqMatcher struct {
}
func (e eqMatcher) Matches(x interface{}) bool {
return reflect.DeepEqual(e.x, x)
// In case, some value is nil
if e.x == nil || x == nil {
return reflect.DeepEqual(e.x, x)
}
// Check if types assignable and convert them to common type
x1Val := reflect.ValueOf(e.x)
x2Val := reflect.ValueOf(x)
if x1Val.Type().AssignableTo(x2Val.Type()) {
x1ValConverted := x1Val.Convert(x2Val.Type())
return reflect.DeepEqual(x1ValConverted.Interface(), x2Val.Interface())
}
return false
}
func (e eqMatcher) String() string {
@@ -245,7 +259,7 @@ func Not(x interface{}) Matcher {
// AssignableToTypeOf(s).Matches(time.Second) // returns true
// AssignableToTypeOf(s).Matches(99) // returns false
//
// var ctx = reflect.TypeOf((*context.Context)).Elem()
// var ctx = reflect.TypeOf((*context.Context)(nil)).Elem()
// AssignableToTypeOf(ctx).Matches(context.Background()) // returns true
func AssignableToTypeOf(x interface{}) Matcher {
if xt, ok := x.(reflect.Type); ok {