diff --git a/docs/index.md b/docs/index.md index acdf5e788..da0750c34 100644 --- a/docs/index.md +++ b/docs/index.md @@ -241,7 +241,7 @@ fmt.Println(format.Object(theThingYouWantToPrint, 1)) - `format.TruncatedDiff = true`: Gomega will truncate long strings and only show where they differ. You can set this to `false` if you want to see the full strings. -You can also register your own custom formatter using `format.RegisterCustomFormatter(f)`. Custom formatters must be of type `type CustomFormatter func(value interface{}) (string, bool)`. Gomega will pass in any objects to be formatted to each registered custom formatter. A custom formatter signals that it will handle the passed-in object by returning a formatted string and `true`. If it does not handle the object it should return `"", false`. Strings returned by custom formatters will _not_ be truncated (though they may be truncated if the object being formatted is within another struct). Custom formatters take precedence of `GomegaStringer` and `format.UseStringerRepresentation`. +You can also register your own custom formatter using `format.RegisterCustomFormatter(f)`. Custom formatters must be of type `type CustomFormatter func(value any) (string, bool)`. Gomega will pass in any objects to be formatted to each registered custom formatter. A custom formatter signals that it will handle the passed-in object by returning a formatted string and `true`. If it does not handle the object it should return `"", false`. Strings returned by custom formatters will _not_ be truncated (though they may be truncated if the object being formatted is within another struct). Custom formatters take precedence of `GomegaStringer` and `format.UseStringerRepresentation`. `format.RegisterCustomFormatter` returns a key that can be used to unregister the custom formatter: @@ -576,7 +576,7 @@ Told to stop trying after Just like functions being polled, matchers can also indicate if `Eventually`/`Consistently` should stop polling. Matchers implement a `Match` method with the following signature: ```go -Match(actual interface{}) (success bool, err error) +Match(actual any) (success bool, err error) ``` If a matcher returns `StopTrying` for `error`, or calls `StopTrying(...).Now()`, `Eventually` and `Consistently` will stop polling and fail: `StopTrying` **always** signifies a failure. @@ -694,7 +694,7 @@ When using Go toolchain of version 1.23 or later, certain matchers as documented ### Asserting Equivalence -#### Equal(expected interface{}) +#### Equal(expected any) ```go Ω(ACTUAL).Should(Equal(EXPECTED)) @@ -710,7 +710,7 @@ When both `ACTUAL` and `EXPECTED` are a very long strings, it will attempt to pr > For asserting equality between numbers of different types, you'll want to use the [`BeNumerically()`](#benumericallycomparator-string-compareto-interface) matcher. -#### BeComparableTo(expected interface{}, options ...cmp.Option) +#### BeComparableTo(expected any, options ...cmp.Option) ```go Ω(ACTUAL).Should(BeComparableTo(EXPECTED, options ...cmp.Option)) @@ -718,7 +718,7 @@ When both `ACTUAL` and `EXPECTED` are a very long strings, it will attempt to pr uses [`gocmp.Equal`](http://github.com/google/go-cmp) from `github.com/google/go-cmp` to compare `ACTUAL` with `EXPECTED`. This performs a deep object comparison like `reflect.DeepEqual` but offers a few additional configuration options. Learn more at the [go-cmp godocs](https://pkg.go.dev/github.com/google/go-cmp). -#### BeEquivalentTo(expected interface{}) +#### BeEquivalentTo(expected any) ```go Ω(ACTUAL).Should(BeEquivalentTo(EXPECTED)) @@ -748,7 +748,7 @@ As a rule, you **should not** use `BeEquivalentTo` with numbers. Both of the fo the first assertion passes because 5.1 will be cast to an integer and will get rounded down! Such false positives are terrible and should be avoided. Use [`BeNumerically()`](#benumericallycomparator-string-compareto-interface) to compare numbers instead. -#### BeIdenticalTo(expected interface{}) +#### BeIdenticalTo(expected any) ```go Ω(ACTUAL).Should(BeIdenticalTo(EXPECTED)) @@ -861,7 +861,7 @@ succeeds if `ACTUAL` is `nil`. The intended usage is where `FUNCTION()` is a function call that returns an error-type as its *first or only* return value. See [Handling Errors](#handling-errors) for a more detailed discussion. -#### MatchError(expected interface{}) +#### MatchError(expected any) ```go Ω(ACTUAL).Should(MatchError(EXPECTED, )) @@ -960,7 +960,7 @@ Eventually(bagelChan).Should(Receive(&receivedBagel, HaveField("Kind", "sesame") Finally, `Receive` *never* blocks. `Eventually(c).Should(Receive())` repeatedly polls `c` in a non-blocking fashion. That means that you cannot use this pattern to verify that a *non-blocking send* has occurred on the channel - [more details at this GitHub issue](https://github.com/onsi/gomega/issues/82). -#### BeSent(value interface{}) +#### BeSent(value any) ```go Ω(ACTUAL).Should(BeSent(VALUE)) @@ -1012,7 +1012,7 @@ succeeds IFF a file is located at `ACTUAL` exists and is a directory. ### Working with Strings, JSON and YAML -#### ContainSubstring(substr string, args ...interface{}) +#### ContainSubstring(substr string, args ...any) ```go Ω(ACTUAL).Should(ContainSubstring(STRING, ARGS...)) @@ -1028,7 +1028,7 @@ fmt.Sprintf(STRING, ARGS...) > Note, of course, that the `ARGS...` are not required. They are simply a convenience to allow you to build up strings programmatically inline in the matcher. -#### HavePrefix(prefix string, args ...interface{}) +#### HavePrefix(prefix string, args ...any) ```go Ω(ACTUAL).Should(HavePrefix(STRING, ARGS...)) @@ -1044,7 +1044,7 @@ fmt.Sprintf(STRING, ARGS...) > Note, of course, that the `ARGS...` are not required. They are simply a convenience to allow you to build up strings programmatically inline in the matcher. -#### HaveSuffix(suffix string, args ...interface{}) +#### HaveSuffix(suffix string, args ...any) ```go Ω(ACTUAL).Should(HaveSuffix(STRING, ARGS...)) @@ -1060,7 +1060,7 @@ fmt.Sprintf(STRING, ARGS...) > Note, of course, that the `ARGS...` are not required. They are simply a convenience to allow you to build up strings programmatically inline in the matcher. -#### MatchRegexp(regexp string, args ...interface{}) +#### MatchRegexp(regexp string, args ...any) ```go Ω(ACTUAL).Should(MatchRegexp(STRING, ARGS...)) @@ -1076,7 +1076,7 @@ fmt.Sprintf(STRING, ARGS...) > Note, of course, that the `ARGS...` are not required. They are simply a convenience to allow you to build up strings programmatically inline in the matcher. -#### MatchJSON(json interface{}) +#### MatchJSON(json any) ```go Ω(ACTUAL).Should(MatchJSON(EXPECTED)) @@ -1088,7 +1088,7 @@ It is an error for either `ACTUAL` or `EXPECTED` to be invalid JSON. In some cases it is useful to match two JSON strings while ignoring list order. For this you can use the community maintained [MatchUnorderedJSON](https://github.com/Benjamintf1/Expanded-Unmarshalled-Matchers) matcher. -#### MatchXML(xml interface{}) +#### MatchXML(xml any) ```go Ω(ACTUAL).Should(MatchXML(EXPECTED)) @@ -1098,7 +1098,7 @@ Both `ACTUAL` and `EXPECTED` must be a `string`, `[]byte` or a `Stringer`. `Mat It is an error for either `ACTUAL` or `EXPECTED` to be invalid XML. -#### MatchYAML(yaml interface{}) +#### MatchYAML(yaml any) ```go Ω(ACTUAL).Should(MatchYAML(EXPECTED)) @@ -1134,7 +1134,7 @@ succeeds if the length of `ACTUAL` is `INT`. `ACTUAL` must be of type `string`, succeeds if the capacity of `ACTUAL` is `INT`. `ACTUAL` must be of type `array`, `chan`, or `slice`. It is an error for it to have any other type. -#### ContainElement(element interface{}) +#### ContainElement(element any) ```go Ω(ACTUAL).Should(ContainElement(ELEMENT)) @@ -1206,7 +1206,7 @@ var findings map[int]string Ω(it).Should(ContainElement(HasPrefix("ba"), &findings)) ``` -#### ContainElements(element ...interface{}) +#### ContainElements(element ...any) ```go Ω(ACTUAL).Should(ContainElements(ELEMENT1, ELEMENT2, ELEMENT3, ...)) @@ -1236,13 +1236,13 @@ is the only element passed in to `ContainElements`: Ω([]string{"Foo", "FooBar"}).Should(ContainElements([]string{"FooBar", "Foo"})) ``` -Note that Go's type system does not allow you to write this as `ContainElements([]string{"FooBar", "Foo"}...)` as `[]string` and `[]interface{}` are different types - hence the need for this special rule. +Note that Go's type system does not allow you to write this as `ContainElements([]string{"FooBar", "Foo"}...)` as `[]string` and `[]any` are different types - hence the need for this special rule. Starting with Go 1.23, you can also pass in an iterator assignable to `iter.Seq` (but not `iter.Seq2`) as the only element to `ConsistOf`. The difference between the `ContainElements` and `ConsistOf` matchers is that the latter is more restrictive because the `ConsistOf` matcher checks additionally that the `ACTUAL` elements and the elements passed into the matcher have the same length. -#### BeElementOf(elements ...interface{}) +#### BeElementOf(elements ...any) ```go Ω(ACTUAL).Should(BeElementOf(ELEMENT1, ELEMENT2, ELEMENT3, ...)) @@ -1250,7 +1250,7 @@ The difference between the `ContainElements` and `ConsistOf` matchers is that th succeeds if `ACTUAL` equals one of the elements passed into the matcher. When a single element `ELEMENT` of type `array` or `slice` is passed into the matcher, `BeElementOf` succeeds if `ELEMENT` contains an element that equals `ACTUAL` (reverse of `ContainElement`). `BeElementOf` always uses the `Equal()` matcher under the hood to assert equality. -#### BeKeyOf(m interface{}) +#### BeKeyOf(m any) ```go Ω(ACTUAL).Should(BeKeyOf(MAP)) @@ -1273,7 +1273,7 @@ Expect(projects).To(ContainElement(HaveField("Name", BeKeyOf(names)), &canaries) Expect(canaries).To(HaveLen(len(names))) ``` -#### ConsistOf(element ...interface{}) +#### ConsistOf(element ...any) ```go Ω(ACTUAL).Should(ConsistOf(ELEMENT1, ELEMENT2, ELEMENT3, ...)) @@ -1303,11 +1303,11 @@ You typically pass variadic arguments to `ConsistOf` (as in the examples above). Ω([]string{"Foo", "FooBar"}).Should(ConsistOf([]string{"FooBar", "Foo"})) ``` -Note that Go's type system does not allow you to write this as `ConsistOf([]string{"FooBar", "Foo"}...)` as `[]string` and `[]interface{}` are different types - hence the need for this special rule. +Note that Go's type system does not allow you to write this as `ConsistOf([]string{"FooBar", "Foo"}...)` as `[]string` and `[]any` are different types - hence the need for this special rule. Starting with Go 1.23, you can also pass in an iterator assignable to `iter.Seq` (but not `iter.Seq2`) as the only element to `ConsistOf`. -#### HaveExactElements(element ...interface{}) +#### HaveExactElements(element ...any) ```go Expect(ACTUAL).To(HaveExactElements(ELEMENT1, ELEMENT2, ELEMENT3, ...)) @@ -1338,9 +1338,9 @@ is the only element passed in to `HaveExactElements`: Expect([]string{"Foo", "FooBar"}).To(HaveExactElements([]string{"FooBar", "Foo"})) ``` -Note that Go's type system does not allow you to write this as `HaveExactElements([]string{"FooBar", "Foo"}...)` as `[]string` and `[]interface{}` are different types - hence the need for this special rule. +Note that Go's type system does not allow you to write this as `HaveExactElements([]string{"FooBar", "Foo"}...)` as `[]string` and `[]any` are different types - hence the need for this special rule. -#### HaveEach(element interface{}) +#### HaveEach(element any) ```go Ω(ACTUAL).Should(HaveEach(ELEMENT)) @@ -1356,7 +1356,7 @@ By default `HaveEach()` uses the `Equal()` matcher under the hood to assert equa Ω([]string{"Foo", "FooBar"}).Should(HaveEach(ContainSubstring("Foo"))) ``` -#### HaveKey(key interface{}) +#### HaveKey(key any) ```go Ω(ACTUAL).Should(HaveKey(KEY)) @@ -1370,7 +1370,7 @@ By default `HaveKey()` uses the `Equal()` matcher under the hood to assert equal Ω(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKey(MatchRegexp(`.+Foo$`))) ``` -#### HaveKeyWithValue(key interface{}, value interface{}) +#### HaveKeyWithValue(key any, value any) ```go Ω(ACTUAL).Should(HaveKeyWithValue(KEY, VALUE)) @@ -1386,7 +1386,7 @@ By default `HaveKeyWithValue()` uses the `Equal()` matcher under the hood to ass ### Working with Structs -#### HaveField(field interface{}, value interface{}) +#### HaveField(field any, value any) ```go Ω(ACTUAL).Should(HaveField(FIELD, VALUE)) @@ -1427,7 +1427,7 @@ and an instance book `var book = Book{...}` - you can use `HaveField` to make as If you want to make lots of complex assertions against the fields of a struct take a look at the [`gstruct`package](#codegstructcode-testing-complex-data-types) documented below. -#### HaveExistingField(field interface{}) +#### HaveExistingField(field any) While `HaveField()` considers a missing field to be an error (instead of non-success), combining it with `HaveExistingField()` allows `HaveField()` to be reused in test contexts other than assertions: for instance, as filters to [`ContainElement(ELEMENT, )`](#containelementelement-interface) or in detecting resource leaks (like leaked file descriptors). @@ -1445,7 +1445,7 @@ To assert a particular field value, but only if such a field exists in an `ACTUA ### Working with Numbers and Times -#### BeNumerically(comparator string, compareTo ...interface{}) +#### BeNumerically(comparator string, compareTo ...any) ```go Ω(ACTUAL).Should(BeNumerically(COMPARATOR_STRING, EXPECTED, )) @@ -1533,7 +1533,7 @@ Or(BeNil(), Not(HaveValue(...))) ### Working with HTTP responses -#### HaveHTTPStatus(expected interface{}) +#### HaveHTTPStatus(expected any) ```go Expect(ACTUAL).To(HaveHTTPStatus(EXPECTED, ...)) @@ -1555,7 +1555,7 @@ Here are some examples: - `Expect(resp).To(HaveHTTPStatus("404 Not Found"))`: asserts that `resp.Status == "404 Not Found"`. -#### HaveHTTPBody(expected interface{}) +#### HaveHTTPBody(expected any) ```go Expect(ACTUAL).To(HaveHTTPBody(EXPECTED)) @@ -1581,7 +1581,7 @@ Here are some examples: Note that the body is an `io.ReadCloser` and the `HaveHTTPBody()` will read it and the close it. This means that subsequent attempts to read the body may have unexpected results. -#### HaveHTTPHeaderWithValue(key string, value interface{}) +#### HaveHTTPHeaderWithValue(key string, value any) ```go Expect(ACTUAL).To(HaveHTTPHeaderWithValue(KEY, VALUE)) @@ -1705,7 +1705,7 @@ Tests the given matchers in order, returning immediately if one succeeds, withou succeeds if `ACTUAL` does **not** satisfy the specified matcher (similar to a logical NOT). -#### WithTransform(transform interface{}, matcher GomegaMatcher) +#### WithTransform(transform any, matcher GomegaMatcher) ```go Ω(ACTUAL).Should(WithTransform(TRANSFORM, MATCHER)) @@ -1743,7 +1743,7 @@ The following lightweight matcher expects to be used either on a `Sprocket` valu // either a Sprocket or a *Sprocket, having the specified name. func HaveSprocketName(name string) GomegaMatcher { return WithTransform( - func(actual interface{}) (string, error) { + func(actual any) (string, error) { switch sprocket := actual.(type) { case *Sprocket: return Sprocket.Name, nil @@ -1758,7 +1758,7 @@ func HaveSprocketName(name string) GomegaMatcher { Ω(element).Should(HaveSprocketName("gomega"))) ``` -#### Satisfy(predicate interface{}) +#### Satisfy(predicate any) ```go Ω(ACTUAL).Should(Satisfy(PREDICATE)) @@ -1778,9 +1778,9 @@ A matcher, in Gomega, is any type that satisfies the `GomegaMatcher` interface: ```go type GomegaMatcher interface { - Match(actual interface{}) (success bool, err error) - FailureMessage(actual interface{}) (message string) - NegatedFailureMessage(actual interface{}) (message string) + Match(actual any) (success bool, err error) + FailureMessage(actual any) (message string) + NegatedFailureMessage(actual any) (message string) } ``` @@ -1790,7 +1790,7 @@ In addition to composition, however, it is fairly straightforward to build domai Let's work through an example and illustrate both approaches. -### A Custom Matcher: RepresentJSONifiedObject(EXPECTED interface{}) +### A Custom Matcher: RepresentJSONifiedObject(EXPECTED any) Say you're working on a JSON API and you want to assert that your server returns the correct JSON representation. Rather than marshal/unmarshal JSON in your tests, you want to write an expressive matcher that checks that the received response is a JSON representation for the object in question. This is what the `RepresentJSONifiedObject` matcher could look like: @@ -1806,17 +1806,17 @@ import ( "reflect" ) -func RepresentJSONifiedObject(expected interface{}) types.GomegaMatcher { +func RepresentJSONifiedObject(expected any) types.GomegaMatcher { return &representJSONMatcher{ expected: expected, } } type representJSONMatcher struct { - expected interface{} + expected any } -func (matcher *representJSONMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *representJSONMatcher) Match(actual any) (success bool, err error) { response, ok := actual.(*http.Response) if !ok { return false, fmt.Errorf("RepresentJSONifiedObject matcher expects an http.Response") @@ -1834,18 +1834,18 @@ func (matcher *representJSONMatcher) Match(actual interface{}) (success bool, er return reflect.DeepEqual(decodedObject, matcher.expected), nil } -func (matcher *representJSONMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *representJSONMatcher) FailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n\t%#v\nto contain the JSON representation of\n\t%#v", actual, matcher.expected) } -func (matcher *representJSONMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *representJSONMatcher) NegatedFailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n\t%#v\nnot to contain the JSON representation of\n\t%#v", actual, matcher.expected) } ``` Let's break this down: -- Most matchers have a constructor function that returns an instance of the matcher. In this case we've created `RepresentJSONifiedObject`. Where possible, your constructor function should take explicit types or interfaces. For our use case, however, we need to accept any possible expected type so `RepresentJSONifiedObject` takes an argument with the generic `interface{}` type. +- Most matchers have a constructor function that returns an instance of the matcher. In this case we've created `RepresentJSONifiedObject`. Where possible, your constructor function should take explicit types or interfaces. For our use case, however, we need to accept any possible expected type so `RepresentJSONifiedObject` takes an argument with the generic `any` type. - The constructor function then initializes and returns an instance of our matcher: the `representJSONMatcher`. These rarely need to be exported outside of your matcher package. - The `representJSONMatcher` must satisfy the `GomegaMatcher` interface. It does this by implementing the `Match`, `FailureMessage`, and `NegatedFailureMessage` method: - If the `GomegaMatcher` receives invalid inputs `Match` returns a non-nil error explaining the problems with the input. This allows Gomega to fail the assertion whether the assertion is for the positive or negative case. @@ -1874,7 +1874,7 @@ import ( "reflect" ) -func RepresentJSONifiedObject(expected interface{}) types.GomegaMatcher { +func RepresentJSONifiedObject(expected any) types.GomegaMatcher { return gcustom.MakeMatcher(func(response *http.Response) (bool, err) { pointerToObjectOfExpectedType := reflect.New(reflect.TypeOf(matcher.expected)).Interface() err = json.NewDecoder(response.Body).Decode(pointerToObjectOfExpectedType) @@ -2015,7 +2015,7 @@ Eventually(myChannel).Should(Receive(Equal("bar"))) To get around this, a matcher can optionally implement: ```go -MatchMayChangeInTheFuture(actual interface{}) bool +MatchMayChangeInTheFuture(actual any) bool ``` This is not part of the `GomegaMatcher` interface and, in general, most matchers do not need to implement `MatchMayChangeInTheFuture`. @@ -2063,7 +2063,7 @@ type gomegaWrapper struct { func (g *gomegaWrapper) Inner() gomega.Gomega { return g.inner } -func (g *gomegaWrapper) Ω(actual interface{}, extra ...interface{}) types.Assertion { +func (g *gomegaWrapper) Ω(actual any, extra ...any) types.Assertion { // You now have an opportunity to add a random delay to help identify any timing // dependencies in your tests or can add additional logging. return g.inner.Ω(actual, extra...) @@ -2834,7 +2834,7 @@ actual := []string{ "B: once upon a time", "C: the end", } -id := func(element interface{}) string { +id := func(element any) string { return string(element.(string)[0]) } Expect(actual).To(MatchAllElements(id, Elements{ @@ -2868,7 +2868,7 @@ Expect(actual).To(MatchElements(id, IgnoreMissing, Elements{ You can also use the flag `AllowDuplicates` to permit multiple elements in your slice to map to a single key and matcher in your fields (this flag is not meaningful when applied to structs). ```go -everyElementID := func(element interface{}) string { +everyElementID := func(element any) string { return "a constant" // Every element will map to the same key in this case; you can group them into multiple keys, however. } Expect(actual).To(MatchElements(everyElementID, AllowDuplicates, Elements{ @@ -2889,7 +2889,7 @@ actual := []string{ "B: once upon a time", "C: the end", } -id := func(index int, _ interface{}) string { +id := func(index int, _ any) string { return strconv.Itoa(index) } Expect(actual).To(MatchAllElementsWithIndex(id, Elements{ @@ -2952,7 +2952,7 @@ The `gstruct` matchers are intended to be composable, and can be combined to app Example: ```go -coreID := func(element interface{}) string { +coreID := func(element any) string { return strconv.Itoa(element.(CoreStats).Index) } Expect(actual).To(MatchAllFields(Fields{ @@ -3031,7 +3031,7 @@ Finally, `gmeasure` provides a mechanism to cache `Experiment`s to disk with a s ### Measuring Values -`Experiment`s can record arbitrary `float64` values. You can do this by directly providing a `float64` via `experiment.RecordValue(measurementName string, value float64, decorators ...interface{})` or by providing a callback that returns a float64 via `experiment.MeasureValue(measurementName string, callback func() float64, decorators ...interface{})`. +`Experiment`s can record arbitrary `float64` values. You can do this by directly providing a `float64` via `experiment.RecordValue(measurementName string, value float64, decorators ...any)` or by providing a callback that returns a float64 via `experiment.MeasureValue(measurementName string, callback func() float64, decorators ...any)`. You can apply `Units`, `Style`, and `Precision` decorators to control the appearance of the `Measurement` when reports are generated. These decorators must be applied when the first data point is recorded but can be elided thereafter. You can also associate an `Annotation` decoration with any recorded data point. @@ -3039,7 +3039,7 @@ You can apply `Units`, `Style`, and `Precision` decorators to control the appear ### Measuring Durations -`Experiment`s can record arbitrary `time.Duration` durations. You can do this by directly providing a `time.Duration` via `experiment.RecordDuration(measurementName string, duration time.Duration, decorators ...interface{})` or by providing a callback via `experiment.MeasureDuration(measurementName string, callback func(), decorators ...interface{})`. `gmeasure` will run the callback and measure how long it takes to complete. +`Experiment`s can record arbitrary `time.Duration` durations. You can do this by directly providing a `time.Duration` via `experiment.RecordDuration(measurementName string, duration time.Duration, decorators ...any)` or by providing a callback via `experiment.MeasureDuration(measurementName string, callback func(), decorators ...any)`. `gmeasure` will run the callback and measure how long it takes to complete. You can apply `Style` and `Precision` decorators to control the appearance of the `Measurement` when reports are generated. These decorators must be applied when the first data point is recorded but can be elided thereafter. You can also associate an `Annotation` decoration with any recorded data point. @@ -3067,10 +3067,10 @@ The basic sampling method is `experiment.Sample(callback func(idx int), sampling A common use-case, however, is to invoke a callback repeatedly to measure its duration or record its returned value and thereby generate an ensemble of data-points. This is supported via the `SampleX` family of methods built on top of `Sample`: ```go -experiment.SampleValue(measurementName string, callback func(idx int) float64, samplingConfig SamplingConfig, decorations ...interface{}) -experiment.SampleDuration(measurementName string, callback func(idx int), samplingConfig SamplingConfig, decorations ...interface{}) -experiment.SampleAnnotatedValue(measurementName string, callback func(idx int) (float64, Annotation), samplingConfig SamplingConfig, decorations ...interface{}) -experiment.SampleAnnotatedDuration(measurementName string, callback func(idx int) Annotation, samplingConfig SamplingConfig, decorations ...interface{}) +experiment.SampleValue(measurementName string, callback func(idx int) float64, samplingConfig SamplingConfig, decorations ...any) +experiment.SampleDuration(measurementName string, callback func(idx int), samplingConfig SamplingConfig, decorations ...any) +experiment.SampleAnnotatedValue(measurementName string, callback func(idx int) (float64, Annotation), samplingConfig SamplingConfig, decorations ...any) +experiment.SampleAnnotatedDuration(measurementName string, callback func(idx int) Annotation, samplingConfig SamplingConfig, decorations ...any) ``` each of these will contribute data points to the `Measurement` with name `measurementName`. `SampleValue` records the `float64` values returned by its callback. `SampleDuration` times each invocation of its callback and records the measured duration. `SampleAnnotatedValue` and `SampleAnnotatedDuration` expect their callbacks to return `Annotation`s. These are attached to each generated data point. diff --git a/format/format.go b/format/format.go index ee2f1c377..96f04b210 100644 --- a/format/format.go +++ b/format/format.go @@ -73,7 +73,7 @@ If the CustomFormatter does not want to handle the object it should return ("", Strings returned by CustomFormatters are not truncated */ -type CustomFormatter func(value interface{}) (string, bool) +type CustomFormatter func(value any) (string, bool) type CustomFormatterKey uint var customFormatterKey CustomFormatterKey = 1 @@ -125,7 +125,7 @@ If expected is omitted, then the message looks like: */ -func Message(actual interface{}, message string, expected ...interface{}) string { +func Message(actual any, message string, expected ...any) string { if len(expected) == 0 { return fmt.Sprintf("Expected\n%s\n%s", Object(actual, 1), message) } @@ -255,7 +255,7 @@ recursing into the object. Set PrintContextObjects to true to print the content of objects implementing context.Context */ -func Object(object interface{}, indentation uint) string { +func Object(object any, indentation uint) string { indent := strings.Repeat(Indent, int(indentation)) value := reflect.ValueOf(object) commonRepresentation := "" @@ -392,7 +392,7 @@ func formatValue(value reflect.Value, indentation uint) string { } } -func formatString(object interface{}, indentation uint) string { +func formatString(object any, indentation uint) string { if indentation == 1 { s := fmt.Sprintf("%s", object) components := strings.Split(s, "\n") diff --git a/format/format_test.go b/format/format_test.go index b0a6a1126..0482c7951 100644 --- a/format/format_test.go +++ b/format/format_test.go @@ -62,7 +62,7 @@ type SecretiveStruct struct { byteArrValue [3]byte mapValue map[string]int structValue AStruct - interfaceValue interface{} + interfaceValue any } type CustomFormatted struct { @@ -84,7 +84,7 @@ func (c *CustomError) Error() string { return c.Details } -func customFormatter(obj interface{}) (string, bool) { +func customFormatter(obj any) (string, bool) { cf, ok := obj.(CustomFormatted) if !ok { return "", false @@ -132,14 +132,14 @@ func (g gomegaStringerMultiline) GomegaString() string { } var _ = Describe("Format", func() { - match := func(typeRepresentation string, valueRepresentation string, args ...interface{}) types.GomegaMatcher { + match := func(typeRepresentation string, valueRepresentation string, args ...any) types.GomegaMatcher { if len(args) > 0 { valueRepresentation = fmt.Sprintf(valueRepresentation, args...) } return Equal(fmt.Sprintf("%s<%s>: %s", Indent, typeRepresentation, valueRepresentation)) } - matchRegexp := func(typeRepresentation string, valueRepresentation string, args ...interface{}) types.GomegaMatcher { + matchRegexp := func(typeRepresentation string, valueRepresentation string, args ...any) types.GomegaMatcher { if len(args) > 0 { valueRepresentation = fmt.Sprintf(valueRepresentation, args...) } @@ -599,18 +599,18 @@ var _ = Describe("Format", func() { }) }) - Describe("formatting nested interface{} types", func() { + Describe("formatting nested any types", func() { It("should print out the types of the container and value", func() { - Expect(Object([]interface{}{"foo"}, 1)). + Expect(Object([]any{"foo"}, 1)). To(match("[]interface {} | len:1, cap:1", `["foo"]`)) - Expect(Object(map[string]interface{}{"foo": true}, 1)). + Expect(Object(map[string]any{"foo": true}, 1)). To(match("map[string]interface {} | len:1", `{"foo": true}`)) - Expect(Object(struct{ A interface{} }{A: 1}, 1)). + Expect(Object(struct{ A any }{A: 1}, 1)). To(match("struct { A interface {} }", "{A: 1}")) - v := struct{ A interface{} }{A: struct{ B string }{B: "foo"}} + v := struct{ A any }{A: struct{ B string }{B: "foo"}} Expect(Object(v, 1)).To(match(`struct { A interface {} }`, `{ A: {B: "foo"}, }`)) @@ -694,7 +694,7 @@ var _ = Describe("Format", func() { Describe("Handling interfaces", func() { It("should unpack the interface", func() { - outerHash := map[string]interface{}{} + outerHash := map[string]any{} innerHash := map[string]int{} innerHash["inner"] = 3 @@ -708,7 +708,7 @@ var _ = Describe("Format", func() { Describe("Handling recursive things", func() { It("should not go crazy...", func() { - m := map[string]interface{}{} + m := map[string]any{} m["integer"] = 2 m["map"] = m Expect(Object(m, 1)).Should(ContainSubstring("...")) @@ -716,11 +716,11 @@ var _ = Describe("Format", func() { It("really should not go crazy...", func() { type complexKey struct { - Value map[interface{}]int + Value map[any]int } complexObject := complexKey{} - complexObject.Value = make(map[interface{}]int) + complexObject.Value = make(map[any]int) complexObject.Value[&complexObject] = 2 Expect(Object(complexObject, 1)).Should(ContainSubstring("...")) @@ -784,7 +784,7 @@ var _ = Describe("Format", func() { It("indents CustomFormatter output correctly", func() { cf := CustomFormatted{"hey\nbob", 17} - DeferCleanup(UnregisterCustomFormatter, RegisterCustomFormatter(func(value interface{}) (string, bool) { + DeferCleanup(UnregisterCustomFormatter, RegisterCustomFormatter(func(value any) (string, bool) { cf, ok := value.(CustomFormatted) if !ok { return "", false diff --git a/gbytes/buffer.go b/gbytes/buffer.go index 6f77b2371..df34e552c 100644 --- a/gbytes/buffer.go +++ b/gbytes/buffer.go @@ -7,7 +7,6 @@ Subsequent matches against the buffer will only operate against data that appear The read cursor is an opaque implementation detail that you cannot access. You should use the Say matcher to sift through the buffer. You can always access the entire buffer's contents with Contents(). - */ package gbytes @@ -29,7 +28,7 @@ type Buffer struct { contents []byte readCursor uint64 lock *sync.Mutex - detectCloser chan interface{} + detectCloser chan any closed bool } @@ -167,19 +166,25 @@ You could do something like: select { case <-buffer.Detect("You are not logged in"): + //log in + case <-buffer.Detect("Success"): + //carry on + case <-time.After(time.Second): - //welp -} + + //welp + } + buffer.CancelDetects() You should always call CancelDetects after using Detect. This will close any channels that have not detected and clean up the goroutines that were spawned to support them. Finally, you can pass detect a format string followed by variadic arguments. This will construct the regexp using fmt.Sprintf. */ -func (b *Buffer) Detect(desired string, args ...interface{}) chan bool { +func (b *Buffer) Detect(desired string, args ...any) chan bool { formattedRegexp := desired if len(args) > 0 { formattedRegexp = fmt.Sprintf(desired, args...) @@ -190,7 +195,7 @@ func (b *Buffer) Detect(desired string, args ...interface{}) chan bool { defer b.lock.Unlock() if b.detectCloser == nil { - b.detectCloser = make(chan interface{}) + b.detectCloser = make(chan any) } closer := b.detectCloser diff --git a/gbytes/say_matcher.go b/gbytes/say_matcher.go index 0763f5e2d..2861a9c20 100644 --- a/gbytes/say_matcher.go +++ b/gbytes/say_matcher.go @@ -9,7 +9,7 @@ import ( "github.com/onsi/gomega/format" ) -//Objects satisfying the BufferProvider can be used with the Say matcher. +// Objects satisfying the BufferProvider can be used with the Say matcher. type BufferProvider interface { Buffer() *Buffer } @@ -37,7 +37,7 @@ In such cases, Say simply operates on the *gbytes.Buffer returned by Buffer() If the buffer is closed, the Say matcher will tell Eventually to abort. */ -func Say(expected string, args ...interface{}) *sayMatcher { +func Say(expected string, args ...any) *sayMatcher { if len(args) > 0 { expected = fmt.Sprintf(expected, args...) } @@ -51,7 +51,7 @@ type sayMatcher struct { receivedSayings []byte } -func (m *sayMatcher) buffer(actual interface{}) (*Buffer, bool) { +func (m *sayMatcher) buffer(actual any) (*Buffer, bool) { var buffer *Buffer switch x := actual.(type) { @@ -66,7 +66,7 @@ func (m *sayMatcher) buffer(actual interface{}) (*Buffer, bool) { return buffer, true } -func (m *sayMatcher) Match(actual interface{}) (success bool, err error) { +func (m *sayMatcher) Match(actual any) (success bool, err error) { buffer, ok := m.buffer(actual) if !ok { return false, fmt.Errorf("Say must be passed a *gbytes.Buffer or BufferProvider. Got:\n%s", format.Object(actual, 1)) @@ -78,7 +78,7 @@ func (m *sayMatcher) Match(actual interface{}) (success bool, err error) { return didSay, nil } -func (m *sayMatcher) FailureMessage(actual interface{}) (message string) { +func (m *sayMatcher) FailureMessage(actual any) (message string) { return fmt.Sprintf( "Got stuck at:\n%s\nWaiting for:\n%s", format.IndentString(string(m.receivedSayings), 1), @@ -86,7 +86,7 @@ func (m *sayMatcher) FailureMessage(actual interface{}) (message string) { ) } -func (m *sayMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (m *sayMatcher) NegatedFailureMessage(actual any) (message string) { return fmt.Sprintf( "Saw:\n%s\nWhich matches the unexpected:\n%s", format.IndentString(string(m.receivedSayings), 1), @@ -94,7 +94,7 @@ func (m *sayMatcher) NegatedFailureMessage(actual interface{}) (message string) ) } -func (m *sayMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { +func (m *sayMatcher) MatchMayChangeInTheFuture(actual any) bool { switch x := actual.(type) { case *Buffer: return !x.Closed() diff --git a/gcustom/make_matcher.go b/gcustom/make_matcher.go index 9ea7fcfd9..ca556ceb0 100644 --- a/gcustom/make_matcher.go +++ b/gcustom/make_matcher.go @@ -12,7 +12,7 @@ import ( "github.com/onsi/gomega/format" ) -var interfaceType = reflect.TypeOf((*interface{})(nil)).Elem() +var interfaceType = reflect.TypeOf((*any)(nil)).Elem() var errInterface = reflect.TypeOf((*error)(nil)).Elem() var defaultTemplate = template.Must(ParseTemplate("{{if .Failure}}Custom matcher failed for:{{else}}Custom matcher succeeded (but was expected to fail) for:{{end}}\n{{.FormattedActual}}")) diff --git a/gexec/exit_matcher.go b/gexec/exit_matcher.go index 6e70de68d..11fa004b7 100644 --- a/gexec/exit_matcher.go +++ b/gexec/exit_matcher.go @@ -43,7 +43,7 @@ type Exiter interface { ExitCode() int } -func (m *exitMatcher) Match(actual interface{}) (success bool, err error) { +func (m *exitMatcher) Match(actual any) (success bool, err error) { exiter, ok := actual.(Exiter) if !ok { return false, fmt.Errorf("Exit must be passed a gexec.Exiter (Missing method ExitCode() int) Got:\n%s", format.Object(actual, 1)) @@ -61,14 +61,14 @@ func (m *exitMatcher) Match(actual interface{}) (success bool, err error) { return m.exitCode == m.actualExitCode, nil } -func (m *exitMatcher) FailureMessage(actual interface{}) (message string) { +func (m *exitMatcher) FailureMessage(actual any) (message string) { if m.actualExitCode == -1 { return "Expected process to exit. It did not." } return format.Message(m.actualExitCode, "to match exit code:", m.exitCode) } -func (m *exitMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (m *exitMatcher) NegatedFailureMessage(actual any) (message string) { if m.actualExitCode == -1 { return "you really shouldn't be able to see this!" } else { @@ -79,7 +79,7 @@ func (m *exitMatcher) NegatedFailureMessage(actual interface{}) (message string) } } -func (m *exitMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { +func (m *exitMatcher) MatchMayChangeInTheFuture(actual any) bool { session, ok := actual.(*Session) if ok { return session.ExitCode() == -1 diff --git a/gexec/session.go b/gexec/session.go index be4877ac9..1e381df1c 100644 --- a/gexec/session.go +++ b/gexec/session.go @@ -140,7 +140,7 @@ will wait for the command to exit then return the entirety of Out's contents. Wait uses eventually under the hood and accepts the same timeout/polling intervals that eventually does. */ -func (s *Session) Wait(timeout ...interface{}) *Session { +func (s *Session) Wait(timeout ...any) *Session { EventuallyWithOffset(1, s, timeout...).Should(Exit()) return s } @@ -225,7 +225,7 @@ The timeout specified is applied to each process killed. If any of the processes already exited, KillAndWait returns silently. */ -func KillAndWait(timeout ...interface{}) { +func KillAndWait(timeout ...any) { trackedSessionsMutex.Lock() defer trackedSessionsMutex.Unlock() for _, session := range trackedSessions { @@ -240,7 +240,7 @@ The timeout specified is applied to each process killed. If any of the processes already exited, TerminateAndWait returns silently. */ -func TerminateAndWait(timeout ...interface{}) { +func TerminateAndWait(timeout ...any) { trackedSessionsMutex.Lock() defer trackedSessionsMutex.Unlock() for _, session := range trackedSessions { diff --git a/ghttp/handlers.go b/ghttp/handlers.go index f9303603a..00a3b8508 100644 --- a/ghttp/handlers.go +++ b/ghttp/handlers.go @@ -45,7 +45,7 @@ func CombineHandlers(handlers ...http.HandlerFunc) http.HandlerFunc { // // For path, you may pass in a string, in which case strict equality will be applied // Alternatively you can pass in a matcher (ContainSubstring("/foo") and MatchRegexp("/foo/[a-f0-9]+") for example) -func (g GHTTPWithGomega) VerifyRequest(method string, path interface{}, rawQuery ...string) http.HandlerFunc { +func (g GHTTPWithGomega) VerifyRequest(method string, path any, rawQuery ...string) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { g.gomega.Expect(req.Method).Should(Equal(method), "Method mismatch") switch p := path.(type) { @@ -118,7 +118,7 @@ func (g GHTTPWithGomega) VerifyHeaderKV(key string, values ...string) http.Handl // Host is a special header in net/http, which is not set on the request.Header but rather on the Request itself // // Host may be a string or a matcher -func (g GHTTPWithGomega) VerifyHost(host interface{}) http.HandlerFunc { +func (g GHTTPWithGomega) VerifyHost(host any) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { switch p := host.(type) { case types.GomegaMatcher: @@ -161,7 +161,7 @@ func (g GHTTPWithGomega) VerifyJSON(expectedJSON string) http.HandlerFunc { // VerifyJSONRepresenting is similar to VerifyJSON. Instead of taking a JSON string, however, it // takes an arbitrary JSON-encodable object and verifies that the requests's body is a JSON representation // that matches the object -func (g GHTTPWithGomega) VerifyJSONRepresenting(object interface{}) http.HandlerFunc { +func (g GHTTPWithGomega) VerifyJSONRepresenting(object any) http.HandlerFunc { data, err := json.Marshal(object) g.gomega.Expect(err).ShouldNot(HaveOccurred()) return CombineHandlers( @@ -231,7 +231,7 @@ Body may be a string or []byte Also, RespondWith can be given an optional http.Header. The headers defined therein will be added to the response headers. */ -func (g GHTTPWithGomega) RespondWith(statusCode int, body interface{}, optionalHeader ...http.Header) http.HandlerFunc { +func (g GHTTPWithGomega) RespondWith(statusCode int, body any, optionalHeader ...http.Header) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { if len(optionalHeader) == 1 { copyHeader(optionalHeader[0], w.Header()) @@ -257,7 +257,7 @@ to share the same setup but specify different status codes and bodies. Also, RespondWithPtr can be given an optional http.Header. The headers defined therein will be added to the response headers. Since the http.Header can be mutated after the fact you don't need to pass in a pointer. */ -func (g GHTTPWithGomega) RespondWithPtr(statusCode *int, body interface{}, optionalHeader ...http.Header) http.HandlerFunc { +func (g GHTTPWithGomega) RespondWithPtr(statusCode *int, body any, optionalHeader ...http.Header) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { if len(optionalHeader) == 1 { copyHeader(optionalHeader[0], w.Header()) @@ -282,7 +282,7 @@ containing the JSON-encoding of the passed in object Also, RespondWithJSONEncoded can be given an optional http.Header. The headers defined therein will be added to the response headers. */ -func (g GHTTPWithGomega) RespondWithJSONEncoded(statusCode int, object interface{}, optionalHeader ...http.Header) http.HandlerFunc { +func (g GHTTPWithGomega) RespondWithJSONEncoded(statusCode int, object any, optionalHeader ...http.Header) http.HandlerFunc { data, err := json.Marshal(object) g.gomega.Expect(err).ShouldNot(HaveOccurred()) @@ -308,7 +308,7 @@ objects. Also, RespondWithJSONEncodedPtr can be given an optional http.Header. The headers defined therein will be added to the response headers. Since the http.Header can be mutated after the fact you don't need to pass in a pointer. */ -func (g GHTTPWithGomega) RespondWithJSONEncodedPtr(statusCode *int, object interface{}, optionalHeader ...http.Header) http.HandlerFunc { +func (g GHTTPWithGomega) RespondWithJSONEncodedPtr(statusCode *int, object any, optionalHeader ...http.Header) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { data, err := json.Marshal(object) g.gomega.Expect(err).ShouldNot(HaveOccurred()) @@ -352,7 +352,7 @@ func (g GHTTPWithGomega) RespondWithProto(statusCode int, message protoadapt.Mes } } -func VerifyRequest(method string, path interface{}, rawQuery ...string) http.HandlerFunc { +func VerifyRequest(method string, path any, rawQuery ...string) http.HandlerFunc { return NewGHTTPWithGomega(gomega.Default).VerifyRequest(method, path, rawQuery...) } @@ -376,7 +376,7 @@ func VerifyHeaderKV(key string, values ...string) http.HandlerFunc { return NewGHTTPWithGomega(gomega.Default).VerifyHeaderKV(key, values...) } -func VerifyHost(host interface{}) http.HandlerFunc { +func VerifyHost(host any) http.HandlerFunc { return NewGHTTPWithGomega(gomega.Default).VerifyHost(host) } @@ -388,7 +388,7 @@ func VerifyJSON(expectedJSON string) http.HandlerFunc { return NewGHTTPWithGomega(gomega.Default).VerifyJSON(expectedJSON) } -func VerifyJSONRepresenting(object interface{}) http.HandlerFunc { +func VerifyJSONRepresenting(object any) http.HandlerFunc { return NewGHTTPWithGomega(gomega.Default).VerifyJSONRepresenting(object) } @@ -404,19 +404,19 @@ func VerifyProtoRepresenting(expected protoiface.MessageV1) http.HandlerFunc { return NewGHTTPWithGomega(gomega.Default).VerifyProtoRepresenting(expected) } -func RespondWith(statusCode int, body interface{}, optionalHeader ...http.Header) http.HandlerFunc { +func RespondWith(statusCode int, body any, optionalHeader ...http.Header) http.HandlerFunc { return NewGHTTPWithGomega(gomega.Default).RespondWith(statusCode, body, optionalHeader...) } -func RespondWithPtr(statusCode *int, body interface{}, optionalHeader ...http.Header) http.HandlerFunc { +func RespondWithPtr(statusCode *int, body any, optionalHeader ...http.Header) http.HandlerFunc { return NewGHTTPWithGomega(gomega.Default).RespondWithPtr(statusCode, body, optionalHeader...) } -func RespondWithJSONEncoded(statusCode int, object interface{}, optionalHeader ...http.Header) http.HandlerFunc { +func RespondWithJSONEncoded(statusCode int, object any, optionalHeader ...http.Header) http.HandlerFunc { return NewGHTTPWithGomega(gomega.Default).RespondWithJSONEncoded(statusCode, object, optionalHeader...) } -func RespondWithJSONEncodedPtr(statusCode *int, object interface{}, optionalHeader ...http.Header) http.HandlerFunc { +func RespondWithJSONEncodedPtr(statusCode *int, object any, optionalHeader ...http.Header) http.HandlerFunc { return NewGHTTPWithGomega(gomega.Default).RespondWithJSONEncodedPtr(statusCode, object, optionalHeader...) } diff --git a/ghttp/protobuf/simple_message.pb.go b/ghttp/protobuf/simple_message.pb.go index 5ea008f5a..86c9d2569 100644 --- a/ghttp/protobuf/simple_message.pb.go +++ b/ghttp/protobuf/simple_message.pb.go @@ -111,7 +111,7 @@ func file_ghttp_protobuf_simple_message_proto_rawDescGZIP() []byte { } var file_ghttp_protobuf_simple_message_proto_msgTypes = make([]protoimpl.MessageInfo, 1) -var file_ghttp_protobuf_simple_message_proto_goTypes = []interface{}{ +var file_ghttp_protobuf_simple_message_proto_goTypes = []any{ (*SimpleMessage)(nil), // 0: protobuf.SimpleMessage } var file_ghttp_protobuf_simple_message_proto_depIdxs = []int32{ @@ -128,7 +128,7 @@ func file_ghttp_protobuf_simple_message_proto_init() { return } if !protoimpl.UnsafeEnabled { - file_ghttp_protobuf_simple_message_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + file_ghttp_protobuf_simple_message_proto_msgTypes[0].Exporter = func(v any, i int) any { switch v := v.(*SimpleMessage); i { case 0: return &v.state diff --git a/ghttp/test_server.go b/ghttp/test_server.go index dfde0a427..67dbf13b7 100644 --- a/ghttp/test_server.go +++ b/ghttp/test_server.go @@ -292,7 +292,7 @@ func (s *Server) ReceivedRequests() []*http.Request { // the passed in method and path. // // The path may be either a string object or a *regexp.Regexp. -func (s *Server) RouteToHandler(method string, path interface{}, handler http.HandlerFunc) { +func (s *Server) RouteToHandler(method string, path any, handler http.HandlerFunc) { s.rwMutex.Lock() defer s.rwMutex.Unlock() diff --git a/gleak/have_leaked_matcher.go b/gleak/have_leaked_matcher.go index 91df3913b..7d16100e0 100644 --- a/gleak/have_leaked_matcher.go +++ b/gleak/have_leaked_matcher.go @@ -124,7 +124,7 @@ var standardFilters = []types.GomegaMatcher{ // IgnoringTopFunction("foo.bar [chan receive]") // IgnoringGoroutines(expectedGoroutines) // IgnoringInBacktrace("foo.bar.baz") -func HaveLeaked(ignoring ...interface{}) types.GomegaMatcher { +func HaveLeaked(ignoring ...any) types.GomegaMatcher { m := &HaveLeakedMatcher{filters: standardFilters} for _, ign := range ignoring { switch ign := ign.(type) { @@ -154,7 +154,7 @@ var gsT = reflect.TypeOf([]Goroutine{}) // Match succeeds if actual is an array or slice of Goroutine // information and still contains goroutines after filtering out all expected // goroutines that were specified when creating the matcher. -func (matcher *HaveLeakedMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveLeakedMatcher) Match(actual any) (success bool, err error) { val := reflect.ValueOf(actual) switch val.Kind() { case reflect.Array, reflect.Slice: @@ -180,12 +180,12 @@ func (matcher *HaveLeakedMatcher) Match(actual interface{}) (success bool, err e } // FailureMessage returns a failure message if there are leaked goroutines. -func (matcher *HaveLeakedMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveLeakedMatcher) FailureMessage(actual any) (message string) { return fmt.Sprintf("Expected to leak %d goroutines:\n%s", len(matcher.leaked), matcher.listGoroutines(matcher.leaked, 1)) } // NegatedFailureMessage returns a negated failure message if there aren't any leaked goroutines. -func (matcher *HaveLeakedMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveLeakedMatcher) NegatedFailureMessage(actual any) (message string) { return fmt.Sprintf("Expected not to leak %d goroutines:\n%s", len(matcher.leaked), matcher.listGoroutines(matcher.leaked, 1)) } diff --git a/gleak/ignoring_creator.go b/gleak/ignoring_creator.go index 66bc45549..ce7fbdfe8 100644 --- a/gleak/ignoring_creator.go +++ b/gleak/ignoring_creator.go @@ -36,7 +36,7 @@ type ignoringCreator struct { // Match succeeds if an actual goroutine's creator function in the backtrace // matches the specified function name or function name prefix. -func (matcher *ignoringCreator) Match(actual interface{}) (success bool, err error) { +func (matcher *ignoringCreator) Match(actual any) (success bool, err error) { g, err := G(actual, "IgnoringCreator") if err != nil { return false, err @@ -50,14 +50,14 @@ func (matcher *ignoringCreator) Match(actual interface{}) (success bool, err err // FailureMessage returns a failure message if the actual goroutine doesn't have // the specified function name/prefix (and optional state) at the top of the // backtrace. -func (matcher *ignoringCreator) FailureMessage(actual interface{}) (message string) { +func (matcher *ignoringCreator) FailureMessage(actual any) (message string) { return format.Message(actual, matcher.message()) } // NegatedFailureMessage returns a failure message if the actual goroutine has // the specified function name/prefix (and optional state) at the top of the // backtrace. -func (matcher *ignoringCreator) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *ignoringCreator) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not "+matcher.message()) } diff --git a/gleak/ignoring_goroutines.go b/gleak/ignoring_goroutines.go index 1750536e9..2e313a3ad 100644 --- a/gleak/ignoring_goroutines.go +++ b/gleak/ignoring_goroutines.go @@ -28,7 +28,7 @@ type ignoringGoroutinesMatcher struct { // Match succeeds if actual is a Goroutine and its ID is in the set of // goroutine IDs to expect and thus to ignore in leak checks. -func (matcher *ignoringGoroutinesMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *ignoringGoroutinesMatcher) Match(actual any) (success bool, err error) { g, err := G(actual, "IgnoringGoroutines") if err != nil { return false, err @@ -39,13 +39,13 @@ func (matcher *ignoringGoroutinesMatcher) Match(actual interface{}) (success boo // FailureMessage returns a failure message if the actual goroutine isn't in the // set of goroutines to be ignored. -func (matcher *ignoringGoroutinesMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *ignoringGoroutinesMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be contained in the list of expected goroutine IDs", matcher.expectedGoids()) } // NegatedFailureMessage returns a negated failure message if the actual // goroutine actually is in the set of goroutines to be ignored. -func (matcher *ignoringGoroutinesMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *ignoringGoroutinesMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to be contained in the list of expected goroutine IDs", matcher.expectedGoids()) } diff --git a/gleak/ignoring_in_backtrace.go b/gleak/ignoring_in_backtrace.go index 9372a5ee4..900e8feac 100644 --- a/gleak/ignoring_in_backtrace.go +++ b/gleak/ignoring_in_backtrace.go @@ -19,7 +19,7 @@ type ignoringInBacktraceMatcher struct { } // Match succeeds if actual's backtrace contains the specified function name. -func (matcher *ignoringInBacktraceMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *ignoringInBacktraceMatcher) Match(actual any) (success bool, err error) { g, err := G(actual, "IgnoringInBacktrace") if err != nil { return false, err @@ -29,12 +29,12 @@ func (matcher *ignoringInBacktraceMatcher) Match(actual interface{}) (success bo // FailureMessage returns a failure message if the actual's backtrace does not // contain the specified function name. -func (matcher *ignoringInBacktraceMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *ignoringInBacktraceMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, fmt.Sprintf("to contain %q in the goroutine's backtrace", matcher.fname)) } // NegatedFailureMessage returns a failure message if the actual's backtrace // does contain the specified function name. -func (matcher *ignoringInBacktraceMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *ignoringInBacktraceMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, fmt.Sprintf("not to contain %q in the goroutine's backtrace", matcher.fname)) } diff --git a/gleak/ignoring_top_function.go b/gleak/ignoring_top_function.go index 1591e6937..849ff740f 100644 --- a/gleak/ignoring_top_function.go +++ b/gleak/ignoring_top_function.go @@ -54,7 +54,7 @@ type ignoringTopFunctionMatcher struct { // Match succeeds if an actual goroutine's top function in the backtrace matches // the specified function name or function name prefix, or name and goroutine // state. -func (matcher *ignoringTopFunctionMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *ignoringTopFunctionMatcher) Match(actual any) (success bool, err error) { g, err := G(actual, "IgnoringTopFunction") if err != nil { return false, err @@ -74,14 +74,14 @@ func (matcher *ignoringTopFunctionMatcher) Match(actual interface{}) (success bo // FailureMessage returns a failure message if the actual goroutine doesn't have // the specified function name/prefix (and optional state) at the top of the // backtrace. -func (matcher *ignoringTopFunctionMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *ignoringTopFunctionMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, matcher.message()) } // NegatedFailureMessage returns a failure message if the actual goroutine has // the specified function name/prefix (and optional state) at the top of the // backtrace. -func (matcher *ignoringTopFunctionMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *ignoringTopFunctionMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not "+matcher.message()) } diff --git a/gleak/util.go b/gleak/util.go index f03a21da3..08ed52872 100644 --- a/gleak/util.go +++ b/gleak/util.go @@ -13,7 +13,7 @@ import ( // possible. It returns an error if actual isn't of either type Goroutine or a // pointer to it. G is intended to be mainly used by goroutine-related Gomega // matchers, such as IgnoringTopFunction, et cetera. -func G(actual interface{}, matchername string) (Goroutine, error) { +func G(actual any, matchername string) (Goroutine, error) { if actual != nil { switch actual := actual.(type) { case Goroutine: diff --git a/gmeasure/experiment.go b/gmeasure/experiment.go index 8cd865b79..9bf4b3b43 100644 --- a/gmeasure/experiment.go +++ b/gmeasure/experiment.go @@ -117,7 +117,7 @@ type PrecisionBundle struct { // e.RecordValue("length", 2.71) // e.RecordDuration("cooking time", 3214 * time.Millisecond, gmeasure.Precision(100*time.Millisecond)) // e.RecordDuration("cooking time", 2623 * time.Millisecond) -func Precision(p interface{}) PrecisionBundle { +func Precision(p any) PrecisionBundle { out := DefaultPrecisionBundle switch reflect.TypeOf(p) { case reflect.TypeOf(time.Duration(0)): @@ -143,7 +143,7 @@ type extractedDecorations struct { style Style } -func extractDecorations(args []interface{}) extractedDecorations { +func extractDecorations(args []any) extractedDecorations { var out extractedDecorations out.precisionBundle = DefaultPrecisionBundle @@ -248,7 +248,7 @@ RecordNote records a Measurement of type MeasurementTypeNote - this is simply a RecordNote supports the Style() decoration. */ -func (e *Experiment) RecordNote(note string, args ...interface{}) { +func (e *Experiment) RecordNote(note string, args ...any) { decorations := extractDecorations(args) e.lock.Lock() @@ -266,7 +266,7 @@ RecordDuration records the passed-in duration on a Duration Measurement with the RecordDuration supports the Style(), Precision(), and Annotation() decorations. */ -func (e *Experiment) RecordDuration(name string, duration time.Duration, args ...interface{}) { +func (e *Experiment) RecordDuration(name string, duration time.Duration, args ...any) { decorations := extractDecorations(args) e.recordDuration(name, duration, decorations) } @@ -276,7 +276,7 @@ MeasureDuration runs the passed-in callback and times how long it takes to compl MeasureDuration supports the Style(), Precision(), and Annotation() decorations. */ -func (e *Experiment) MeasureDuration(name string, callback func(), args ...interface{}) time.Duration { +func (e *Experiment) MeasureDuration(name string, callback func(), args ...any) time.Duration { t := time.Now() callback() duration := time.Since(t) @@ -292,7 +292,7 @@ The callback is given a zero-based index that increments by one between samples. SampleDuration supports the Style(), Precision(), and Annotation() decorations. When passed an Annotation() the same annotation is applied to all sample measurements. */ -func (e *Experiment) SampleDuration(name string, callback func(idx int), samplingConfig SamplingConfig, args ...interface{}) { +func (e *Experiment) SampleDuration(name string, callback func(idx int), samplingConfig SamplingConfig, args ...any) { decorations := extractDecorations(args) e.Sample(func(idx int) { t := time.Now() @@ -312,7 +312,7 @@ The callback is given a zero-based index that increments by one between samples. SampleAnnotatedDuration supports the Style() and Precision() decorations. */ -func (e *Experiment) SampleAnnotatedDuration(name string, callback func(idx int) Annotation, samplingConfig SamplingConfig, args ...interface{}) { +func (e *Experiment) SampleAnnotatedDuration(name string, callback func(idx int) Annotation, samplingConfig SamplingConfig, args ...any) { decorations := extractDecorations(args) e.Sample(func(idx int) { t := time.Now() @@ -359,7 +359,7 @@ RecordValue records the passed-in value on a Value Measurement with the passed-i RecordValue supports the Style(), Units(), Precision(), and Annotation() decorations. */ -func (e *Experiment) RecordValue(name string, value float64, args ...interface{}) { +func (e *Experiment) RecordValue(name string, value float64, args ...any) { decorations := extractDecorations(args) e.recordValue(name, value, decorations) } @@ -369,7 +369,7 @@ MeasureValue runs the passed-in callback and records the return value on a Value MeasureValue supports the Style(), Units(), Precision(), and Annotation() decorations. */ -func (e *Experiment) MeasureValue(name string, callback func() float64, args ...interface{}) float64 { +func (e *Experiment) MeasureValue(name string, callback func() float64, args ...any) float64 { value := callback() e.RecordValue(name, value, args...) return value @@ -382,7 +382,7 @@ The callback is given a zero-based index that increments by one between samples. SampleValue supports the Style(), Units(), Precision(), and Annotation() decorations. When passed an Annotation() the same annotation is applied to all sample measurements. */ -func (e *Experiment) SampleValue(name string, callback func(idx int) float64, samplingConfig SamplingConfig, args ...interface{}) { +func (e *Experiment) SampleValue(name string, callback func(idx int) float64, samplingConfig SamplingConfig, args ...any) { decorations := extractDecorations(args) e.Sample(func(idx int) { value := callback(idx) @@ -399,7 +399,7 @@ The callback is given a zero-based index that increments by one between samples. SampleValue supports the Style(), Units(), and Precision() decorations. */ -func (e *Experiment) SampleAnnotatedValue(name string, callback func(idx int) (float64, Annotation), samplingConfig SamplingConfig, args ...interface{}) { +func (e *Experiment) SampleAnnotatedValue(name string, callback func(idx int) (float64, Annotation), samplingConfig SamplingConfig, args ...any) { decorations := extractDecorations(args) e.Sample(func(idx int) { var value float64 diff --git a/gmeasure/stopwatch.go b/gmeasure/stopwatch.go index 634f11f2a..0da22f863 100644 --- a/gmeasure/stopwatch.go +++ b/gmeasure/stopwatch.go @@ -44,17 +44,17 @@ Record takes all the decorators that experiment.RecordDuration takes (e.g. Annot Note that Record does not Reset the Stopwatch. It does, however, return the Stopwatch so the following pattern is common: - stopwatch := experiment.NewStopwatch() - // first expensive operation - stopwatch.Record("first operation").Reset() //records the duration of the first operation and resets the stopwatch. - // second expensive operation - stopwatch.Record("second operation").Reset() //records the duration of the second operation and resets the stopwatch. + stopwatch := experiment.NewStopwatch() + // first expensive operation + stopwatch.Record("first operation").Reset() //records the duration of the first operation and resets the stopwatch. + // second expensive operation + stopwatch.Record("second operation").Reset() //records the duration of the second operation and resets the stopwatch. omitting the Reset() after the first operation would cause the duration recorded for the second operation to include the time elapsed by both the first _and_ second operations. The Stopwatch must be running (i.e. not paused) when Record is called. */ -func (s *Stopwatch) Record(name string, args ...interface{}) *Stopwatch { +func (s *Stopwatch) Record(name string, args ...any) *Stopwatch { if !s.running { panic("stopwatch is not running - call Resume or Reset before calling Record") } @@ -80,16 +80,15 @@ Note: You must call Resume() before you can Record() subsequent measurements. For example: - stopwatch := experiment.NewStopwatch() - // first expensive operation - stopwatch.Record("first operation").Reset() - // second expensive operation - part 1 - stopwatch.Pause() - // something expensive that we don't care about - stopwatch.Resume() - // second expensive operation - part 2 - stopwatch.Record("second operation").Reset() // the recorded duration captures the time elapsed during parts 1 and 2 of the second expensive operation, but not the bit in between - + stopwatch := experiment.NewStopwatch() + // first expensive operation + stopwatch.Record("first operation").Reset() + // second expensive operation - part 1 + stopwatch.Pause() + // something expensive that we don't care about + stopwatch.Resume() + // second expensive operation - part 2 + stopwatch.Record("second operation").Reset() // the recorded duration captures the time elapsed during parts 1 and 2 of the second expensive operation, but not the bit in between The Stopwatch must be running when Pause is called. */ diff --git a/gmeasure/table/table.go b/gmeasure/table/table.go index c65dcaf98..0a0df3b7a 100644 --- a/gmeasure/table/table.go +++ b/gmeasure/table/table.go @@ -24,7 +24,7 @@ type Row struct { Style string } -func R(args ...interface{}) *Row { +func R(args ...any) *Row { r := &Row{ Divider: "-", } @@ -94,7 +94,7 @@ type Cell struct { Align AlignType } -func C(contents string, args ...interface{}) Cell { +func C(contents string, args ...any) Cell { c := Cell{ Contents: strings.Split(contents, "\n"), } @@ -354,4 +354,3 @@ func sum(s []int) int { } return out } - diff --git a/gomega_dsl.go b/gomega_dsl.go index 508d23e14..dc05cb675 100644 --- a/gomega_dsl.go +++ b/gomega_dsl.go @@ -191,7 +191,7 @@ func ensureDefaultGomegaIsConfigured() { // Will succeed only if `MyAmazingThing()` returns `(3, nil)` // // Ω and Expect are identical -func Ω(actual interface{}, extra ...interface{}) Assertion { +func Ω(actual any, extra ...any) Assertion { ensureDefaultGomegaIsConfigured() return Default.Ω(actual, extra...) } @@ -217,7 +217,7 @@ func Ω(actual interface{}, extra ...interface{}) Assertion { // Will succeed only if `MyAmazingThing()` returns `(3, nil)` // // Expect and Ω are identical -func Expect(actual interface{}, extra ...interface{}) Assertion { +func Expect(actual any, extra ...any) Assertion { ensureDefaultGomegaIsConfigured() return Default.Expect(actual, extra...) } @@ -233,7 +233,7 @@ func Expect(actual interface{}, extra ...interface{}) Assertion { // This is most useful in helper functions that make assertions. If you want Gomega's // error message to refer to the calling line in the test (as opposed to the line in the helper function) // set the first argument of `ExpectWithOffset` appropriately. -func ExpectWithOffset(offset int, actual interface{}, extra ...interface{}) Assertion { +func ExpectWithOffset(offset int, actual any, extra ...any) Assertion { ensureDefaultGomegaIsConfigured() return Default.ExpectWithOffset(offset, actual, extra...) } @@ -390,7 +390,7 @@ is equivalent to Eventually(...).WithTimeout(10*time.Second).WithPolling(2*time.Second).WithContext(ctx).Should(...) */ -func Eventually(actualOrCtx interface{}, args ...interface{}) AsyncAssertion { +func Eventually(actualOrCtx any, args ...any) AsyncAssertion { ensureDefaultGomegaIsConfigured() return Default.Eventually(actualOrCtx, args...) } @@ -404,7 +404,7 @@ func Eventually(actualOrCtx interface{}, args ...interface{}) AsyncAssertion { // `EventuallyWithOffset` specifying a timeout interval (and an optional polling interval) are // the same as `Eventually(...).WithOffset(...).WithTimeout` or // `Eventually(...).WithOffset(...).WithTimeout(...).WithPolling`. -func EventuallyWithOffset(offset int, actualOrCtx interface{}, args ...interface{}) AsyncAssertion { +func EventuallyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertion { ensureDefaultGomegaIsConfigured() return Default.EventuallyWithOffset(offset, actualOrCtx, args...) } @@ -424,7 +424,7 @@ Consistently is useful in cases where you want to assert that something *does no This will block for 200 milliseconds and repeatedly check the channel and ensure nothing has been received. */ -func Consistently(actualOrCtx interface{}, args ...interface{}) AsyncAssertion { +func Consistently(actualOrCtx any, args ...any) AsyncAssertion { ensureDefaultGomegaIsConfigured() return Default.Consistently(actualOrCtx, args...) } @@ -435,7 +435,7 @@ func Consistently(actualOrCtx interface{}, args ...interface{}) AsyncAssertion { // // `ConsistentlyWithOffset` is the same as `Consistently(...).WithOffset` and // optional `WithTimeout` and `WithPolling`. -func ConsistentlyWithOffset(offset int, actualOrCtx interface{}, args ...interface{}) AsyncAssertion { +func ConsistentlyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertion { ensureDefaultGomegaIsConfigured() return Default.ConsistentlyWithOffset(offset, actualOrCtx, args...) } diff --git a/gstruct/elements.go b/gstruct/elements.go index 43681e786..4a6114ab8 100644 --- a/gstruct/elements.go +++ b/gstruct/elements.go @@ -17,7 +17,7 @@ import ( // MatchAllElements succeeds if every element of a slice matches the element matcher it maps to // through the id function, and every element matcher is matched. // -// idFn := func(element interface{}) string { +// idFn := func(element any) string { // return fmt.Sprintf("%v", element) // } // @@ -35,7 +35,7 @@ func MatchAllElements(identifier Identifier, elements Elements) types.GomegaMatc // MatchAllElementsWithIndex succeeds if every element of a slice matches the element matcher it maps to // through the id with index function, and every element matcher is matched. // -// idFn := func(index int, element interface{}) string { +// idFn := func(index int, element any) string { // return strconv.Itoa(index) // } // @@ -53,7 +53,7 @@ func MatchAllElementsWithIndex(identifier IdentifierWithIndex, elements Elements // MatchElements succeeds if each element of a slice matches the element matcher it maps to // through the id function. It can ignore extra elements and/or missing elements. // -// idFn := func(element interface{}) string { +// idFn := func(element any) string { // return fmt.Sprintf("%v", element) // } // @@ -80,7 +80,7 @@ func MatchElements(identifier Identifier, options Options, elements Elements) ty // MatchElementsWithIndex succeeds if each element of a slice matches the element matcher it maps to // through the id with index function. It can ignore extra elements and/or missing elements. // -// idFn := func(index int, element interface{}) string { +// idFn := func(index int, element any) string { // return strconv.Itoa(index) // } // @@ -128,35 +128,35 @@ type ElementsMatcher struct { type Elements map[string]types.GomegaMatcher // Function for identifying (mapping) elements. -type Identifier func(element interface{}) string +type Identifier func(element any) string // Calls the underlying function with the provided params. // Identifier drops the index. -func (i Identifier) WithIndexAndElement(index int, element interface{}) string { +func (i Identifier) WithIndexAndElement(index int, element any) string { return i(element) } // Uses the index and element to generate an element name -type IdentifierWithIndex func(index int, element interface{}) string +type IdentifierWithIndex func(index int, element any) string // Calls the underlying function with the provided params. // IdentifierWithIndex uses the index. -func (i IdentifierWithIndex) WithIndexAndElement(index int, element interface{}) string { +func (i IdentifierWithIndex) WithIndexAndElement(index int, element any) string { return i(index, element) } // Interface for identifying the element type Identify interface { - WithIndexAndElement(i int, element interface{}) string + WithIndexAndElement(i int, element any) string } // IndexIdentity is a helper function for using an index as // the key in the element map -func IndexIdentity(index int, _ interface{}) string { +func IndexIdentity(index int, _ any) string { return strconv.Itoa(index) } -func (m *ElementsMatcher) Match(actual interface{}) (success bool, err error) { +func (m *ElementsMatcher) Match(actual any) (success bool, err error) { if reflect.TypeOf(actual).Kind() != reflect.Slice { return false, fmt.Errorf("%v is type %T, expected slice", actual, actual) } @@ -168,7 +168,7 @@ func (m *ElementsMatcher) Match(actual interface{}) (success bool, err error) { return true, nil } -func (m *ElementsMatcher) matchElements(actual interface{}) (errs []error) { +func (m *ElementsMatcher) matchElements(actual any) (errs []error) { // Provide more useful error messages in the case of a panic. defer func() { if err := recover(); err != nil { @@ -221,12 +221,12 @@ func (m *ElementsMatcher) matchElements(actual interface{}) (errs []error) { return errs } -func (m *ElementsMatcher) FailureMessage(actual interface{}) (message string) { +func (m *ElementsMatcher) FailureMessage(actual any) (message string) { failure := errorsutil.AggregateError(m.failures) return format.Message(actual, fmt.Sprintf("to match elements: %v", failure)) } -func (m *ElementsMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (m *ElementsMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to match elements") } diff --git a/gstruct/elements_test.go b/gstruct/elements_test.go index 8976c82e5..24a32b16a 100644 --- a/gstruct/elements_test.go +++ b/gstruct/elements_test.go @@ -80,7 +80,7 @@ var _ = Describe("Slice", func() { }) Context("with elements that share a key", func() { - nonUniqueID := func(element interface{}) string { + nonUniqueID := func(element any) string { return element.(string)[0:1] } @@ -171,6 +171,6 @@ var _ = Describe("Slice", func() { }) }) -func id(element interface{}) string { +func id(element any) string { return element.(string) } diff --git a/gstruct/fields.go b/gstruct/fields.go index faf07b1a2..bf4c0ae10 100644 --- a/gstruct/fields.go +++ b/gstruct/fields.go @@ -14,51 +14,53 @@ import ( "github.com/onsi/gomega/types" ) -//MatchAllFields succeeds if every field of a struct matches the field matcher associated with -//it, and every element matcher is matched. -// actual := struct{ -// A int -// B []bool -// C string -// }{ -// A: 5, -// B: []bool{true, false}, -// C: "foo", -// } +// MatchAllFields succeeds if every field of a struct matches the field matcher associated with +// it, and every element matcher is matched. // -// Expect(actual).To(MatchAllFields(Fields{ -// "A": Equal(5), -// "B": ConsistOf(true, false), -// "C": Equal("foo"), -// })) +// actual := struct{ +// A int +// B []bool +// C string +// }{ +// A: 5, +// B: []bool{true, false}, +// C: "foo", +// } +// +// Expect(actual).To(MatchAllFields(Fields{ +// "A": Equal(5), +// "B": ConsistOf(true, false), +// "C": Equal("foo"), +// })) func MatchAllFields(fields Fields) types.GomegaMatcher { return &FieldsMatcher{ Fields: fields, } } -//MatchFields succeeds if each element of a struct matches the field matcher associated with -//it. It can ignore extra fields and/or missing fields. -// actual := struct{ -// A int -// B []bool -// C string -// }{ -// A: 5, -// B: []bool{true, false}, -// C: "foo", -// } +// MatchFields succeeds if each element of a struct matches the field matcher associated with +// it. It can ignore extra fields and/or missing fields. +// +// actual := struct{ +// A int +// B []bool +// C string +// }{ +// A: 5, +// B: []bool{true, false}, +// C: "foo", +// } // -// Expect(actual).To(MatchFields(IgnoreExtras, Fields{ -// "A": Equal(5), -// "B": ConsistOf(true, false), -// })) -// Expect(actual).To(MatchFields(IgnoreMissing, Fields{ -// "A": Equal(5), -// "B": ConsistOf(true, false), -// "C": Equal("foo"), -// "D": Equal("extra"), -// })) +// Expect(actual).To(MatchFields(IgnoreExtras, Fields{ +// "A": Equal(5), +// "B": ConsistOf(true, false), +// })) +// Expect(actual).To(MatchFields(IgnoreMissing, Fields{ +// "A": Equal(5), +// "B": ConsistOf(true, false), +// "C": Equal("foo"), +// "D": Equal("extra"), +// })) func MatchFields(options Options, fields Fields) types.GomegaMatcher { return &FieldsMatcher{ Fields: fields, @@ -83,7 +85,7 @@ type FieldsMatcher struct { // Field name to matcher. type Fields map[string]types.GomegaMatcher -func (m *FieldsMatcher) Match(actual interface{}) (success bool, err error) { +func (m *FieldsMatcher) Match(actual any) (success bool, err error) { if reflect.TypeOf(actual).Kind() != reflect.Struct { return false, fmt.Errorf("%v is type %T, expected struct", actual, actual) } @@ -95,7 +97,7 @@ func (m *FieldsMatcher) Match(actual interface{}) (success bool, err error) { return true, nil } -func (m *FieldsMatcher) matchFields(actual interface{}) (errs []error) { +func (m *FieldsMatcher) matchFields(actual any) (errs []error) { val := reflect.ValueOf(actual) typ := val.Type() fields := map[string]bool{} @@ -147,7 +149,7 @@ func (m *FieldsMatcher) matchFields(actual interface{}) (errs []error) { return errs } -func (m *FieldsMatcher) FailureMessage(actual interface{}) (message string) { +func (m *FieldsMatcher) FailureMessage(actual any) (message string) { failures := make([]string, len(m.failures)) for i := range m.failures { failures[i] = m.failures[i].Error() @@ -156,7 +158,7 @@ func (m *FieldsMatcher) FailureMessage(actual interface{}) (message string) { fmt.Sprintf("to match fields: {\n%v\n}\n", strings.Join(failures, "\n"))) } -func (m *FieldsMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (m *FieldsMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to match fields") } diff --git a/gstruct/ignore.go b/gstruct/ignore.go index 4396573e4..c8238d58f 100644 --- a/gstruct/ignore.go +++ b/gstruct/ignore.go @@ -6,17 +6,19 @@ import ( "github.com/onsi/gomega/types" ) -//Ignore ignores the actual value and always succeeds. -// Expect(nil).To(Ignore()) -// Expect(true).To(Ignore()) +// Ignore ignores the actual value and always succeeds. +// +// Expect(nil).To(Ignore()) +// Expect(true).To(Ignore()) func Ignore() types.GomegaMatcher { return &IgnoreMatcher{true} } -//Reject ignores the actual value and always fails. It can be used in conjunction with IgnoreMissing -//to catch problematic elements, or to verify tests are running. -// Expect(nil).NotTo(Reject()) -// Expect(true).NotTo(Reject()) +// Reject ignores the actual value and always fails. It can be used in conjunction with IgnoreMissing +// to catch problematic elements, or to verify tests are running. +// +// Expect(nil).NotTo(Reject()) +// Expect(true).NotTo(Reject()) func Reject() types.GomegaMatcher { return &IgnoreMatcher{false} } @@ -26,14 +28,14 @@ type IgnoreMatcher struct { Succeed bool } -func (m *IgnoreMatcher) Match(actual interface{}) (bool, error) { +func (m *IgnoreMatcher) Match(actual any) (bool, error) { return m.Succeed, nil } -func (m *IgnoreMatcher) FailureMessage(_ interface{}) (message string) { +func (m *IgnoreMatcher) FailureMessage(_ any) (message string) { return "Unconditional failure" } -func (m *IgnoreMatcher) NegatedFailureMessage(_ interface{}) (message string) { +func (m *IgnoreMatcher) NegatedFailureMessage(_ any) (message string) { return "Unconditional success" } diff --git a/gstruct/keys.go b/gstruct/keys.go index 56aed4bab..807a450b6 100644 --- a/gstruct/keys.go +++ b/gstruct/keys.go @@ -41,9 +41,9 @@ type KeysMatcher struct { failures []error } -type Keys map[interface{}]types.GomegaMatcher +type Keys map[any]types.GomegaMatcher -func (m *KeysMatcher) Match(actual interface{}) (success bool, err error) { +func (m *KeysMatcher) Match(actual any) (success bool, err error) { if reflect.TypeOf(actual).Kind() != reflect.Map { return false, fmt.Errorf("%v is type %T, expected map", actual, actual) } @@ -55,9 +55,9 @@ func (m *KeysMatcher) Match(actual interface{}) (success bool, err error) { return true, nil } -func (m *KeysMatcher) matchKeys(actual interface{}) (errs []error) { +func (m *KeysMatcher) matchKeys(actual any) (errs []error) { actualValue := reflect.ValueOf(actual) - keys := map[interface{}]bool{} + keys := map[any]bool{} for _, keyValue := range actualValue.MapKeys() { key := keyValue.Interface() keys[key] = true @@ -108,7 +108,7 @@ func (m *KeysMatcher) matchKeys(actual interface{}) (errs []error) { return errs } -func (m *KeysMatcher) FailureMessage(actual interface{}) (message string) { +func (m *KeysMatcher) FailureMessage(actual any) (message string) { failures := make([]string, len(m.failures)) for i := range m.failures { failures[i] = m.failures[i].Error() @@ -117,7 +117,7 @@ func (m *KeysMatcher) FailureMessage(actual interface{}) (message string) { fmt.Sprintf("to match keys: {\n%v\n}\n", strings.Join(failures, "\n"))) } -func (m *KeysMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (m *KeysMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to match keys") } diff --git a/gstruct/pointer.go b/gstruct/pointer.go index cc828a325..54c9557fe 100644 --- a/gstruct/pointer.go +++ b/gstruct/pointer.go @@ -10,10 +10,11 @@ import ( "github.com/onsi/gomega/types" ) -//PointTo applies the given matcher to the value pointed to by actual. It fails if the pointer is -//nil. -// actual := 5 -// Expect(&actual).To(PointTo(Equal(5))) +// PointTo applies the given matcher to the value pointed to by actual. It fails if the pointer is +// nil. +// +// actual := 5 +// Expect(&actual).To(PointTo(Equal(5))) func PointTo(matcher types.GomegaMatcher) types.GomegaMatcher { return &PointerMatcher{ Matcher: matcher, @@ -27,7 +28,7 @@ type PointerMatcher struct { failure string } -func (m *PointerMatcher) Match(actual interface{}) (bool, error) { +func (m *PointerMatcher) Match(actual any) (bool, error) { val := reflect.ValueOf(actual) // return error if actual type is not a pointer @@ -49,10 +50,10 @@ func (m *PointerMatcher) Match(actual interface{}) (bool, error) { return match, err } -func (m *PointerMatcher) FailureMessage(_ interface{}) (message string) { +func (m *PointerMatcher) FailureMessage(_ any) (message string) { return m.failure } -func (m *PointerMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (m *PointerMatcher) NegatedFailureMessage(actual any) (message string) { return m.Matcher.NegatedFailureMessage(actual) } diff --git a/internal/assertion.go b/internal/assertion.go index 08356a610..cc846e7ce 100644 --- a/internal/assertion.go +++ b/internal/assertion.go @@ -9,19 +9,19 @@ import ( ) type Assertion struct { - actuals []interface{} // actual value plus all extra values - actualIndex int // value to pass to the matcher - vet vetinari // the vet to call before calling Gomega matcher + actuals []any // actual value plus all extra values + actualIndex int // value to pass to the matcher + vet vetinari // the vet to call before calling Gomega matcher offset int g *Gomega } // ...obligatory discworld reference, as "vetineer" doesn't sound ... quite right. -type vetinari func(assertion *Assertion, optionalDescription ...interface{}) bool +type vetinari func(assertion *Assertion, optionalDescription ...any) bool -func NewAssertion(actualInput interface{}, g *Gomega, offset int, extra ...interface{}) *Assertion { +func NewAssertion(actualInput any, g *Gomega, offset int, extra ...any) *Assertion { return &Assertion{ - actuals: append([]interface{}{actualInput}, extra...), + actuals: append([]any{actualInput}, extra...), actualIndex: 0, vet: (*Assertion).vetActuals, offset: offset, @@ -44,37 +44,37 @@ func (assertion *Assertion) Error() types.Assertion { } } -func (assertion *Assertion) Should(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { +func (assertion *Assertion) Should(matcher types.GomegaMatcher, optionalDescription ...any) bool { assertion.g.THelper() vetOptionalDescription("Assertion", optionalDescription...) return assertion.vet(assertion, optionalDescription...) && assertion.match(matcher, true, optionalDescription...) } -func (assertion *Assertion) ShouldNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { +func (assertion *Assertion) ShouldNot(matcher types.GomegaMatcher, optionalDescription ...any) bool { assertion.g.THelper() vetOptionalDescription("Assertion", optionalDescription...) return assertion.vet(assertion, optionalDescription...) && assertion.match(matcher, false, optionalDescription...) } -func (assertion *Assertion) To(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { +func (assertion *Assertion) To(matcher types.GomegaMatcher, optionalDescription ...any) bool { assertion.g.THelper() vetOptionalDescription("Assertion", optionalDescription...) return assertion.vet(assertion, optionalDescription...) && assertion.match(matcher, true, optionalDescription...) } -func (assertion *Assertion) ToNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { +func (assertion *Assertion) ToNot(matcher types.GomegaMatcher, optionalDescription ...any) bool { assertion.g.THelper() vetOptionalDescription("Assertion", optionalDescription...) return assertion.vet(assertion, optionalDescription...) && assertion.match(matcher, false, optionalDescription...) } -func (assertion *Assertion) NotTo(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { +func (assertion *Assertion) NotTo(matcher types.GomegaMatcher, optionalDescription ...any) bool { assertion.g.THelper() vetOptionalDescription("Assertion", optionalDescription...) return assertion.vet(assertion, optionalDescription...) && assertion.match(matcher, false, optionalDescription...) } -func (assertion *Assertion) buildDescription(optionalDescription ...interface{}) string { +func (assertion *Assertion) buildDescription(optionalDescription ...any) string { switch len(optionalDescription) { case 0: return "" @@ -86,7 +86,7 @@ func (assertion *Assertion) buildDescription(optionalDescription ...interface{}) return fmt.Sprintf(optionalDescription[0].(string), optionalDescription[1:]...) + "\n" } -func (assertion *Assertion) match(matcher types.GomegaMatcher, desiredMatch bool, optionalDescription ...interface{}) bool { +func (assertion *Assertion) match(matcher types.GomegaMatcher, desiredMatch bool, optionalDescription ...any) bool { actualInput := assertion.actuals[assertion.actualIndex] matches, err := matcher.Match(actualInput) assertion.g.THelper() @@ -113,7 +113,7 @@ func (assertion *Assertion) match(matcher types.GomegaMatcher, desiredMatch bool // vetActuals vets the actual values, with the (optional) exception of a // specific value, such as the first value in case non-error assertions, or the // last value in case of Error()-based assertions. -func (assertion *Assertion) vetActuals(optionalDescription ...interface{}) bool { +func (assertion *Assertion) vetActuals(optionalDescription ...any) bool { success, message := vetActuals(assertion.actuals, assertion.actualIndex) if success { return true @@ -129,7 +129,7 @@ func (assertion *Assertion) vetActuals(optionalDescription ...interface{}) bool // the final error value is non-zero. Otherwise, it doesn't vet the actual // values, as these are allowed to take on any values unless there is a non-zero // error value. -func (assertion *Assertion) vetError(optionalDescription ...interface{}) bool { +func (assertion *Assertion) vetError(optionalDescription ...any) bool { if err := assertion.actuals[assertion.actualIndex]; err != nil { // Go error result idiom: all other actual values must be zero values. return assertion.vetActuals(optionalDescription...) @@ -139,7 +139,7 @@ func (assertion *Assertion) vetError(optionalDescription ...interface{}) bool { // vetActuals vets a slice of actual values, optionally skipping a particular // value slice element, such as the first or last value slice element. -func vetActuals(actuals []interface{}, skipIndex int) (bool, string) { +func vetActuals(actuals []any, skipIndex int) (bool, string) { for i, actual := range actuals { if i == skipIndex { continue diff --git a/internal/assertion_test.go b/internal/assertion_test.go index 6bf14913e..425da19cc 100644 --- a/internal/assertion_test.go +++ b/internal/assertion_test.go @@ -14,17 +14,17 @@ var _ = Describe("Making Synchronous Assertions", func() { var IT_PASSES = true var IT_FAILS = false - Extras := func(extras ...interface{}) []interface{} { + Extras := func(extras ...any) []any { return extras } - OptionalDescription := func(optionalDescription ...interface{}) []interface{} { + OptionalDescription := func(optionalDescription ...any) []any { return optionalDescription } DescribeTable( "the various cases", - func(actual interface{}, extras []interface{}, optionalDescription []interface{}, isPositiveAssertion bool, expectedFailureMessage string, expectedReturnValue bool) { + func(actual any, extras []any, optionalDescription []any, isPositiveAssertion bool, expectedFailureMessage string, expectedReturnValue bool) { if isPositiveAssertion { ig := NewInstrumentedGomega() returnValue := ig.G.Expect(actual, extras...).To(SpecMatch(), optionalDescription...) diff --git a/internal/async_assertion.go b/internal/async_assertion.go index fe856b107..9932640ef 100644 --- a/internal/async_assertion.go +++ b/internal/async_assertion.go @@ -69,8 +69,8 @@ type AsyncAssertion struct { asyncType AsyncAssertionType actualIsFunc bool - actual interface{} - argsToForward []interface{} + actual any + argsToForward []any timeoutInterval time.Duration pollingInterval time.Duration @@ -80,7 +80,7 @@ type AsyncAssertion struct { g *Gomega } -func NewAsyncAssertion(asyncType AsyncAssertionType, actualInput interface{}, g *Gomega, timeoutInterval time.Duration, pollingInterval time.Duration, mustPassRepeatedly int, ctx context.Context, offset int) *AsyncAssertion { +func NewAsyncAssertion(asyncType AsyncAssertionType, actualInput any, g *Gomega, timeoutInterval time.Duration, pollingInterval time.Duration, mustPassRepeatedly int, ctx context.Context, offset int) *AsyncAssertion { out := &AsyncAssertion{ asyncType: asyncType, timeoutInterval: timeoutInterval, @@ -129,7 +129,7 @@ func (assertion *AsyncAssertion) WithContext(ctx context.Context) types.AsyncAss return assertion } -func (assertion *AsyncAssertion) WithArguments(argsToForward ...interface{}) types.AsyncAssertion { +func (assertion *AsyncAssertion) WithArguments(argsToForward ...any) types.AsyncAssertion { assertion.argsToForward = argsToForward return assertion } @@ -139,19 +139,19 @@ func (assertion *AsyncAssertion) MustPassRepeatedly(count int) types.AsyncAssert return assertion } -func (assertion *AsyncAssertion) Should(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { +func (assertion *AsyncAssertion) Should(matcher types.GomegaMatcher, optionalDescription ...any) bool { assertion.g.THelper() vetOptionalDescription("Asynchronous assertion", optionalDescription...) return assertion.match(matcher, true, optionalDescription...) } -func (assertion *AsyncAssertion) ShouldNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { +func (assertion *AsyncAssertion) ShouldNot(matcher types.GomegaMatcher, optionalDescription ...any) bool { assertion.g.THelper() vetOptionalDescription("Asynchronous assertion", optionalDescription...) return assertion.match(matcher, false, optionalDescription...) } -func (assertion *AsyncAssertion) buildDescription(optionalDescription ...interface{}) string { +func (assertion *AsyncAssertion) buildDescription(optionalDescription ...any) string { switch len(optionalDescription) { case 0: return "" @@ -163,7 +163,7 @@ func (assertion *AsyncAssertion) buildDescription(optionalDescription ...interfa return fmt.Sprintf(optionalDescription[0].(string), optionalDescription[1:]...) + "\n" } -func (assertion *AsyncAssertion) processReturnValues(values []reflect.Value) (interface{}, error) { +func (assertion *AsyncAssertion) processReturnValues(values []reflect.Value) (any, error) { if len(values) == 0 { return nil, &asyncPolledActualError{ message: fmt.Sprintf("The function passed to %s did not return any values", assertion.asyncType), @@ -237,9 +237,9 @@ You can learn more at https://onsi.github.io/gomega/#eventually `, assertion.asyncType, reason) } -func (assertion *AsyncAssertion) buildActualPoller() (func() (interface{}, error), error) { +func (assertion *AsyncAssertion) buildActualPoller() (func() (any, error), error) { if !assertion.actualIsFunc { - return func() (interface{}, error) { return assertion.actual, nil }, nil + return func() (any, error) { return assertion.actual, nil }, nil } actualValue := reflect.ValueOf(assertion.actual) actualType := reflect.TypeOf(assertion.actual) @@ -301,7 +301,7 @@ func (assertion *AsyncAssertion) buildActualPoller() (func() (interface{}, error return nil, assertion.invalidMustPassRepeatedlyError("parameter can't be < 1") } - return func() (actual interface{}, err error) { + return func() (actual any, err error) { var values []reflect.Value assertionFailure = nil defer func() { @@ -354,14 +354,14 @@ func (assertion *AsyncAssertion) afterPolling() <-chan time.Time { } } -func (assertion *AsyncAssertion) matcherSaysStopTrying(matcher types.GomegaMatcher, value interface{}) bool { +func (assertion *AsyncAssertion) matcherSaysStopTrying(matcher types.GomegaMatcher, value any) bool { if assertion.actualIsFunc || types.MatchMayChangeInTheFuture(matcher, value) { return false } return true } -func (assertion *AsyncAssertion) pollMatcher(matcher types.GomegaMatcher, value interface{}) (matches bool, err error) { +func (assertion *AsyncAssertion) pollMatcher(matcher types.GomegaMatcher, value any) (matches bool, err error) { defer func() { if e := recover(); e != nil { if _, isAsyncError := AsPollingSignalError(e); isAsyncError { @@ -377,13 +377,13 @@ func (assertion *AsyncAssertion) pollMatcher(matcher types.GomegaMatcher, value return } -func (assertion *AsyncAssertion) match(matcher types.GomegaMatcher, desiredMatch bool, optionalDescription ...interface{}) bool { +func (assertion *AsyncAssertion) match(matcher types.GomegaMatcher, desiredMatch bool, optionalDescription ...any) bool { timer := time.Now() timeout := assertion.afterTimeout() lock := sync.Mutex{} var matches, hasLastValidActual bool - var actual, lastValidActual interface{} + var actual, lastValidActual any var actualErr, matcherErr error var oracleMatcherSaysStop bool diff --git a/internal/async_assertion_test.go b/internal/async_assertion_test.go index 0c496336d..8df7e062d 100644 --- a/internal/async_assertion_test.go +++ b/internal/async_assertion_test.go @@ -30,7 +30,7 @@ func (q quickMatcher) NegatedFailureMessage(actual any) (message string) { return fmt.Sprintf("QM negated failure message: %v", actual) } -func (q quickMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { +func (q quickMatcher) MatchMayChangeInTheFuture(actual any) bool { if q.oracleFunc == nil { return true } @@ -756,7 +756,7 @@ var _ = Describe("Asynchronous Assertions", func() { It("correctly handles the case (in concert with Ginkgo) when an assertion fails in a goroutine", func() { count := 0 ig.G.Eventually(func(g Gomega) { - c := make(chan interface{}) + c := make(chan any) go func() { defer GinkgoRecover() defer close(c) diff --git a/internal/duration_bundle.go b/internal/duration_bundle.go index 2e026c336..1019deb88 100644 --- a/internal/duration_bundle.go +++ b/internal/duration_bundle.go @@ -49,7 +49,7 @@ func durationFromEnv(key string, defaultDuration time.Duration) time.Duration { return duration } -func toDuration(input interface{}) (time.Duration, error) { +func toDuration(input any) (time.Duration, error) { duration, ok := input.(time.Duration) if ok { return duration, nil diff --git a/internal/gomega.go b/internal/gomega.go index 9951545e1..66dfe7d04 100644 --- a/internal/gomega.go +++ b/internal/gomega.go @@ -40,39 +40,39 @@ func (g *Gomega) ConfigureWithT(t types.GomegaTestingT) *Gomega { return g } -func (g *Gomega) Ω(actual interface{}, extra ...interface{}) types.Assertion { +func (g *Gomega) Ω(actual any, extra ...any) types.Assertion { return g.ExpectWithOffset(0, actual, extra...) } -func (g *Gomega) Expect(actual interface{}, extra ...interface{}) types.Assertion { +func (g *Gomega) Expect(actual any, extra ...any) types.Assertion { return g.ExpectWithOffset(0, actual, extra...) } -func (g *Gomega) ExpectWithOffset(offset int, actual interface{}, extra ...interface{}) types.Assertion { +func (g *Gomega) ExpectWithOffset(offset int, actual any, extra ...any) types.Assertion { return NewAssertion(actual, g, offset, extra...) } -func (g *Gomega) Eventually(actualOrCtx interface{}, args ...interface{}) types.AsyncAssertion { +func (g *Gomega) Eventually(actualOrCtx any, args ...any) types.AsyncAssertion { return g.makeAsyncAssertion(AsyncAssertionTypeEventually, 0, actualOrCtx, args...) } -func (g *Gomega) EventuallyWithOffset(offset int, actualOrCtx interface{}, args ...interface{}) types.AsyncAssertion { +func (g *Gomega) EventuallyWithOffset(offset int, actualOrCtx any, args ...any) types.AsyncAssertion { return g.makeAsyncAssertion(AsyncAssertionTypeEventually, offset, actualOrCtx, args...) } -func (g *Gomega) Consistently(actualOrCtx interface{}, args ...interface{}) types.AsyncAssertion { +func (g *Gomega) Consistently(actualOrCtx any, args ...any) types.AsyncAssertion { return g.makeAsyncAssertion(AsyncAssertionTypeConsistently, 0, actualOrCtx, args...) } -func (g *Gomega) ConsistentlyWithOffset(offset int, actualOrCtx interface{}, args ...interface{}) types.AsyncAssertion { +func (g *Gomega) ConsistentlyWithOffset(offset int, actualOrCtx any, args ...any) types.AsyncAssertion { return g.makeAsyncAssertion(AsyncAssertionTypeConsistently, offset, actualOrCtx, args...) } -func (g *Gomega) makeAsyncAssertion(asyncAssertionType AsyncAssertionType, offset int, actualOrCtx interface{}, args ...interface{}) types.AsyncAssertion { +func (g *Gomega) makeAsyncAssertion(asyncAssertionType AsyncAssertionType, offset int, actualOrCtx any, args ...any) types.AsyncAssertion { baseOffset := 3 timeoutInterval := -time.Duration(1) pollingInterval := -time.Duration(1) - intervals := []interface{}{} + intervals := []any{} var ctx context.Context actual := actualOrCtx diff --git a/internal/internal_suite_test.go b/internal/internal_suite_test.go index d072b62be..c52175345 100644 --- a/internal/internal_suite_test.go +++ b/internal/internal_suite_test.go @@ -51,7 +51,7 @@ var TEST_MATCHER_ERR = errors.New("spec matcher error") type SpecMatcher struct{} -func (matcher SpecMatcher) Match(actual interface{}) (bool, error) { +func (matcher SpecMatcher) Match(actual any) (bool, error) { switch actual { case MATCH: return true, nil @@ -63,11 +63,11 @@ func (matcher SpecMatcher) Match(actual interface{}) (bool, error) { return false, fmt.Errorf("unknown actual %v", actual) } -func (matcher SpecMatcher) FailureMessage(actual interface{}) string { +func (matcher SpecMatcher) FailureMessage(actual any) string { return fmt.Sprintf("positive: %s", actual) } -func (matcher SpecMatcher) NegatedFailureMessage(actual interface{}) string { +func (matcher SpecMatcher) NegatedFailureMessage(actual any) string { return fmt.Sprintf("negative: %s", actual) } @@ -85,6 +85,6 @@ func (f *FakeGomegaTestingT) Helper() { f.CalledHelper = true } -func (f *FakeGomegaTestingT) Fatalf(s string, args ...interface{}) { +func (f *FakeGomegaTestingT) Fatalf(s string, args ...any) { f.CalledFatalf = fmt.Sprintf(s, args...) } diff --git a/internal/polling_signal_error.go b/internal/polling_signal_error.go index 3a4f7ddd9..450c40333 100644 --- a/internal/polling_signal_error.go +++ b/internal/polling_signal_error.go @@ -100,7 +100,7 @@ func (s *PollingSignalErrorImpl) TryAgainDuration() time.Duration { return s.duration } -func AsPollingSignalError(actual interface{}) (*PollingSignalErrorImpl, bool) { +func AsPollingSignalError(actual any) (*PollingSignalErrorImpl, bool) { if actual == nil { return nil, false } diff --git a/internal/vetoptdesc.go b/internal/vetoptdesc.go index f29587641..b748de41f 100644 --- a/internal/vetoptdesc.go +++ b/internal/vetoptdesc.go @@ -10,7 +10,7 @@ import ( // Gomega matcher at the beginning it panics. This allows for rendering Gomega // matchers as part of an optional Description, as long as they're not in the // first slot. -func vetOptionalDescription(assertion string, optionalDescription ...interface{}) { +func vetOptionalDescription(assertion string, optionalDescription ...any) { if len(optionalDescription) == 0 { return } diff --git a/matchers.go b/matchers.go index b7fc55e4d..10b6693fd 100644 --- a/matchers.go +++ b/matchers.go @@ -12,7 +12,7 @@ import ( // Equal uses reflect.DeepEqual to compare actual with expected. Equal is strict about // types when performing comparisons. // It is an error for both actual and expected to be nil. Use BeNil() instead. -func Equal(expected interface{}) types.GomegaMatcher { +func Equal(expected any) types.GomegaMatcher { return &matchers.EqualMatcher{ Expected: expected, } @@ -22,7 +22,7 @@ func Equal(expected interface{}) types.GomegaMatcher { // This is done by converting actual to have the type of expected before // attempting equality with reflect.DeepEqual. // It is an error for actual and expected to be nil. Use BeNil() instead. -func BeEquivalentTo(expected interface{}) types.GomegaMatcher { +func BeEquivalentTo(expected any) types.GomegaMatcher { return &matchers.BeEquivalentToMatcher{ Expected: expected, } @@ -31,7 +31,7 @@ func BeEquivalentTo(expected interface{}) types.GomegaMatcher { // BeComparableTo uses gocmp.Equal from github.com/google/go-cmp (instead of reflect.DeepEqual) to perform a deep comparison. // You can pass cmp.Option as options. // It is an error for actual and expected to be nil. Use BeNil() instead. -func BeComparableTo(expected interface{}, opts ...cmp.Option) types.GomegaMatcher { +func BeComparableTo(expected any, opts ...cmp.Option) types.GomegaMatcher { return &matchers.BeComparableToMatcher{ Expected: expected, Options: opts, @@ -41,7 +41,7 @@ func BeComparableTo(expected interface{}, opts ...cmp.Option) types.GomegaMatche // BeIdenticalTo uses the == operator to compare actual with expected. // BeIdenticalTo is strict about types when performing comparisons. // It is an error for both actual and expected to be nil. Use BeNil() instead. -func BeIdenticalTo(expected interface{}) types.GomegaMatcher { +func BeIdenticalTo(expected any) types.GomegaMatcher { return &matchers.BeIdenticalToMatcher{ Expected: expected, } @@ -139,7 +139,7 @@ func Succeed() types.GomegaMatcher { // Error interface // // The optional second argument is a description of the error function, if used. This is required when passing a function but is ignored in all other cases. -func MatchError(expected interface{}, functionErrorDescription ...any) types.GomegaMatcher { +func MatchError(expected any, functionErrorDescription ...any) types.GomegaMatcher { return &matchers.MatchErrorMatcher{ Expected: expected, FuncErrDescription: functionErrorDescription, @@ -206,7 +206,7 @@ func BeClosed() types.GomegaMatcher { // // var myThing thing // Eventually(thingChan).Should(Receive(&myThing, ContainSubstring("bar"))) -func Receive(args ...interface{}) types.GomegaMatcher { +func Receive(args ...any) types.GomegaMatcher { return &matchers.ReceiveMatcher{ Args: args, } @@ -224,7 +224,7 @@ func Receive(args ...interface{}) types.GomegaMatcher { // // Of course, the value is actually sent to the channel. The point of `BeSent` is less to make an assertion about the availability of the channel (which is typically an implementation detail that your test should not be concerned with). // Rather, the point of `BeSent` is to make it possible to easily and expressively write tests that can timeout on blocked channel sends. -func BeSent(arg interface{}) types.GomegaMatcher { +func BeSent(arg any) types.GomegaMatcher { return &matchers.BeSentMatcher{ Arg: arg, } @@ -233,7 +233,7 @@ func BeSent(arg interface{}) types.GomegaMatcher { // MatchRegexp succeeds if actual is a string or stringer that matches the // passed-in regexp. Optional arguments can be provided to construct a regexp // via fmt.Sprintf(). -func MatchRegexp(regexp string, args ...interface{}) types.GomegaMatcher { +func MatchRegexp(regexp string, args ...any) types.GomegaMatcher { return &matchers.MatchRegexpMatcher{ Regexp: regexp, Args: args, @@ -243,7 +243,7 @@ func MatchRegexp(regexp string, args ...interface{}) types.GomegaMatcher { // ContainSubstring succeeds if actual is a string or stringer that contains the // passed-in substring. Optional arguments can be provided to construct the substring // via fmt.Sprintf(). -func ContainSubstring(substr string, args ...interface{}) types.GomegaMatcher { +func ContainSubstring(substr string, args ...any) types.GomegaMatcher { return &matchers.ContainSubstringMatcher{ Substr: substr, Args: args, @@ -253,7 +253,7 @@ func ContainSubstring(substr string, args ...interface{}) types.GomegaMatcher { // HavePrefix succeeds if actual is a string or stringer that contains the // passed-in string as a prefix. Optional arguments can be provided to construct // via fmt.Sprintf(). -func HavePrefix(prefix string, args ...interface{}) types.GomegaMatcher { +func HavePrefix(prefix string, args ...any) types.GomegaMatcher { return &matchers.HavePrefixMatcher{ Prefix: prefix, Args: args, @@ -263,7 +263,7 @@ func HavePrefix(prefix string, args ...interface{}) types.GomegaMatcher { // HaveSuffix succeeds if actual is a string or stringer that contains the // passed-in string as a suffix. Optional arguments can be provided to construct // via fmt.Sprintf(). -func HaveSuffix(suffix string, args ...interface{}) types.GomegaMatcher { +func HaveSuffix(suffix string, args ...any) types.GomegaMatcher { return &matchers.HaveSuffixMatcher{ Suffix: suffix, Args: args, @@ -273,7 +273,7 @@ func HaveSuffix(suffix string, args ...interface{}) types.GomegaMatcher { // MatchJSON succeeds if actual is a string or stringer of JSON that matches // the expected JSON. The JSONs are decoded and the resulting objects are compared via // reflect.DeepEqual so things like key-ordering and whitespace shouldn't matter. -func MatchJSON(json interface{}) types.GomegaMatcher { +func MatchJSON(json any) types.GomegaMatcher { return &matchers.MatchJSONMatcher{ JSONToMatch: json, } @@ -282,7 +282,7 @@ func MatchJSON(json interface{}) types.GomegaMatcher { // MatchXML succeeds if actual is a string or stringer of XML that matches // the expected XML. The XMLs are decoded and the resulting objects are compared via // reflect.DeepEqual so things like whitespaces shouldn't matter. -func MatchXML(xml interface{}) types.GomegaMatcher { +func MatchXML(xml any) types.GomegaMatcher { return &matchers.MatchXMLMatcher{ XMLToMatch: xml, } @@ -291,7 +291,7 @@ func MatchXML(xml interface{}) types.GomegaMatcher { // MatchYAML succeeds if actual is a string or stringer of YAML that matches // the expected YAML. The YAML's are decoded and the resulting objects are compared via // reflect.DeepEqual so things like key-ordering and whitespace shouldn't matter. -func MatchYAML(yaml interface{}) types.GomegaMatcher { +func MatchYAML(yaml any) types.GomegaMatcher { return &matchers.MatchYAMLMatcher{ YAMLToMatch: yaml, } @@ -338,7 +338,7 @@ func BeZero() types.GomegaMatcher { // // var findings []string // Expect([]string{"Foo", "FooBar"}).Should(ContainElement(ContainSubString("Bar", &findings))) -func ContainElement(element interface{}, result ...interface{}) types.GomegaMatcher { +func ContainElement(element any, result ...any) types.GomegaMatcher { return &matchers.ContainElementMatcher{ Element: element, Result: result, @@ -358,7 +358,7 @@ func ContainElement(element interface{}, result ...interface{}) types.GomegaMatc // Expect(2).Should(BeElementOf(1, 2)) // // Actual must be typed. -func BeElementOf(elements ...interface{}) types.GomegaMatcher { +func BeElementOf(elements ...any) types.GomegaMatcher { return &matchers.BeElementOfMatcher{ Elements: elements, } @@ -368,7 +368,7 @@ func BeElementOf(elements ...interface{}) types.GomegaMatcher { // BeKeyOf() always uses Equal() to perform the match between actual and the map keys. // // Expect("foo").Should(BeKeyOf(map[string]bool{"foo": true, "bar": false})) -func BeKeyOf(element interface{}) types.GomegaMatcher { +func BeKeyOf(element any) types.GomegaMatcher { return &matchers.BeKeyOfMatcher{ Map: element, } @@ -388,8 +388,8 @@ func BeKeyOf(element interface{}) types.GomegaMatcher { // // Expect([]string{"Foo", "FooBar"}).Should(ConsistOf([]string{"FooBar", "Foo"})) // -// Note that Go's type system does not allow you to write this as ConsistOf([]string{"FooBar", "Foo"}...) as []string and []interface{} are different types - hence the need for this special rule. -func ConsistOf(elements ...interface{}) types.GomegaMatcher { +// Note that Go's type system does not allow you to write this as ConsistOf([]string{"FooBar", "Foo"}...) as []string and []any are different types - hence the need for this special rule. +func ConsistOf(elements ...any) types.GomegaMatcher { return &matchers.ConsistOfMatcher{ Elements: elements, } @@ -403,7 +403,7 @@ func ConsistOf(elements ...interface{}) types.GomegaMatcher { // Expect([]string{"Foo", "FooBar"}).Should(HaveExactElements(ContainSubstring("Foo"), ContainSubstring("Foo"))) // // Actual must be an array or slice. -func HaveExactElements(elements ...interface{}) types.GomegaMatcher { +func HaveExactElements(elements ...any) types.GomegaMatcher { return &matchers.HaveExactElementsMatcher{ Elements: elements, } @@ -417,7 +417,7 @@ func HaveExactElements(elements ...interface{}) types.GomegaMatcher { // // Actual must be an array, slice or map. // For maps, ContainElements searches through the map's values. -func ContainElements(elements ...interface{}) types.GomegaMatcher { +func ContainElements(elements ...any) types.GomegaMatcher { return &matchers.ContainElementsMatcher{ Elements: elements, } @@ -432,7 +432,7 @@ func ContainElements(elements ...interface{}) types.GomegaMatcher { // // Actual must be an array, slice or map. // For maps, HaveEach searches through the map's values. -func HaveEach(element interface{}) types.GomegaMatcher { +func HaveEach(element any) types.GomegaMatcher { return &matchers.HaveEachMatcher{ Element: element, } @@ -443,7 +443,7 @@ func HaveEach(element interface{}) types.GomegaMatcher { // matcher can be passed in instead: // // Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKey(MatchRegexp(`.+Foo$`))) -func HaveKey(key interface{}) types.GomegaMatcher { +func HaveKey(key any) types.GomegaMatcher { return &matchers.HaveKeyMatcher{ Key: key, } @@ -455,7 +455,7 @@ func HaveKey(key interface{}) types.GomegaMatcher { // // Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue("Foo", "Bar")) // Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue(MatchRegexp(`.+Foo$`), "Bar")) -func HaveKeyWithValue(key interface{}, value interface{}) types.GomegaMatcher { +func HaveKeyWithValue(key any, value any) types.GomegaMatcher { return &matchers.HaveKeyWithValueMatcher{ Key: key, Value: value, @@ -483,7 +483,7 @@ func HaveKeyWithValue(key interface{}, value interface{}) types.GomegaMatcher { // Expect(book).To(HaveField("Title", ContainSubstring("Les")) // Expect(book).To(HaveField("Author.FirstName", Equal("Victor")) // Expect(book).To(HaveField("Author.DOB.Year()", BeNumerically("<", 1900)) -func HaveField(field string, expected interface{}) types.GomegaMatcher { +func HaveField(field string, expected any) types.GomegaMatcher { return &matchers.HaveFieldMatcher{ Field: field, Expected: expected, @@ -535,7 +535,7 @@ func HaveValue(matcher types.GomegaMatcher) types.GomegaMatcher { // Expect(1.0).Should(BeNumerically(">=", 1.0)) // Expect(1.0).Should(BeNumerically("<", 3)) // Expect(1.0).Should(BeNumerically("<=", 1.0)) -func BeNumerically(comparator string, compareTo ...interface{}) types.GomegaMatcher { +func BeNumerically(comparator string, compareTo ...any) types.GomegaMatcher { return &matchers.BeNumericallyMatcher{ Comparator: comparator, CompareTo: compareTo, @@ -562,7 +562,7 @@ func BeTemporally(comparator string, compareTo time.Time, threshold ...time.Dura // Expect(5).Should(BeAssignableToTypeOf(-1)) // different values same type // Expect("foo").Should(BeAssignableToTypeOf("bar")) // different values same type // Expect(struct{ Foo string }{}).Should(BeAssignableToTypeOf(struct{ Foo string }{})) -func BeAssignableToTypeOf(expected interface{}) types.GomegaMatcher { +func BeAssignableToTypeOf(expected any) types.GomegaMatcher { return &matchers.AssignableToTypeOfMatcher{ Expected: expected, } @@ -581,7 +581,7 @@ func Panic() types.GomegaMatcher { // matcher can be passed in instead: // // Expect(fn).Should(PanicWith(MatchRegexp(`.+Foo$`))) -func PanicWith(expected interface{}) types.GomegaMatcher { +func PanicWith(expected any) types.GomegaMatcher { return &matchers.PanicMatcher{Expected: expected} } @@ -610,7 +610,7 @@ func BeADirectory() types.GomegaMatcher { // Expect(resp).Should(HaveHTTPStatus(http.StatusOK)) // asserts that resp.StatusCode == 200 // Expect(resp).Should(HaveHTTPStatus("404 Not Found")) // asserts that resp.Status == "404 Not Found" // Expect(resp).Should(HaveHTTPStatus(http.StatusOK, http.StatusNoContent)) // asserts that resp.StatusCode == 200 || resp.StatusCode == 204 -func HaveHTTPStatus(expected ...interface{}) types.GomegaMatcher { +func HaveHTTPStatus(expected ...any) types.GomegaMatcher { return &matchers.HaveHTTPStatusMatcher{Expected: expected} } @@ -618,7 +618,7 @@ func HaveHTTPStatus(expected ...interface{}) types.GomegaMatcher { // Actual must be either a *http.Response or *httptest.ResponseRecorder. // Expected must be a string header name, followed by a header value which // can be a string, or another matcher. -func HaveHTTPHeaderWithValue(header string, value interface{}) types.GomegaMatcher { +func HaveHTTPHeaderWithValue(header string, value any) types.GomegaMatcher { return &matchers.HaveHTTPHeaderWithValueMatcher{ Header: header, Value: value, @@ -628,7 +628,7 @@ func HaveHTTPHeaderWithValue(header string, value interface{}) types.GomegaMatch // HaveHTTPBody matches if the body matches. // Actual must be either a *http.Response or *httptest.ResponseRecorder. // Expected must be either a string, []byte, or other matcher -func HaveHTTPBody(expected interface{}) types.GomegaMatcher { +func HaveHTTPBody(expected any) types.GomegaMatcher { return &matchers.HaveHTTPBodyMatcher{Expected: expected} } @@ -687,7 +687,7 @@ func Not(matcher types.GomegaMatcher) types.GomegaMatcher { // Expect(1).To(WithTransform(failingplus1, Equal(2))) // // And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions. -func WithTransform(transform interface{}, matcher types.GomegaMatcher) types.GomegaMatcher { +func WithTransform(transform any, matcher types.GomegaMatcher) types.GomegaMatcher { return matchers.NewWithTransformMatcher(transform, matcher) } @@ -696,6 +696,6 @@ func WithTransform(transform interface{}, matcher types.GomegaMatcher) types.Gom // // var isEven = func(i int) bool { return i%2 == 0 } // Expect(2).To(Satisfy(isEven)) -func Satisfy(predicate interface{}) types.GomegaMatcher { +func Satisfy(predicate any) types.GomegaMatcher { return matchers.NewSatisfyMatcher(predicate) } diff --git a/matchers/and.go b/matchers/and.go index 6bd826adc..db48e90b3 100644 --- a/matchers/and.go +++ b/matchers/and.go @@ -14,7 +14,7 @@ type AndMatcher struct { firstFailedMatcher types.GomegaMatcher } -func (m *AndMatcher) Match(actual interface{}) (success bool, err error) { +func (m *AndMatcher) Match(actual any) (success bool, err error) { m.firstFailedMatcher = nil for _, matcher := range m.Matchers { success, err := matcher.Match(actual) @@ -26,16 +26,16 @@ func (m *AndMatcher) Match(actual interface{}) (success bool, err error) { return true, nil } -func (m *AndMatcher) FailureMessage(actual interface{}) (message string) { +func (m *AndMatcher) FailureMessage(actual any) (message string) { return m.firstFailedMatcher.FailureMessage(actual) } -func (m *AndMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (m *AndMatcher) NegatedFailureMessage(actual any) (message string) { // not the most beautiful list of matchers, but not bad either... return format.Message(actual, fmt.Sprintf("To not satisfy all of these matchers: %s", m.Matchers)) } -func (m *AndMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { +func (m *AndMatcher) MatchMayChangeInTheFuture(actual any) bool { /* Example with 3 matchers: A, B, C diff --git a/matchers/assignable_to_type_of_matcher.go b/matchers/assignable_to_type_of_matcher.go index be4839520..a100e5c07 100644 --- a/matchers/assignable_to_type_of_matcher.go +++ b/matchers/assignable_to_type_of_matcher.go @@ -10,10 +10,10 @@ import ( ) type AssignableToTypeOfMatcher struct { - Expected interface{} + Expected any } -func (matcher *AssignableToTypeOfMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *AssignableToTypeOfMatcher) Match(actual any) (success bool, err error) { if actual == nil && matcher.Expected == nil { return false, fmt.Errorf("Refusing to compare to .\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") } else if matcher.Expected == nil { @@ -28,10 +28,10 @@ func (matcher *AssignableToTypeOfMatcher) Match(actual interface{}) (success boo return actualType.AssignableTo(expectedType), nil } -func (matcher *AssignableToTypeOfMatcher) FailureMessage(actual interface{}) string { +func (matcher *AssignableToTypeOfMatcher) FailureMessage(actual any) string { return format.Message(actual, fmt.Sprintf("to be assignable to the type: %T", matcher.Expected)) } -func (matcher *AssignableToTypeOfMatcher) NegatedFailureMessage(actual interface{}) string { +func (matcher *AssignableToTypeOfMatcher) NegatedFailureMessage(actual any) string { return format.Message(actual, fmt.Sprintf("not to be assignable to the type: %T", matcher.Expected)) } diff --git a/matchers/be_a_directory.go b/matchers/be_a_directory.go index 93d4497c7..1d8236048 100644 --- a/matchers/be_a_directory.go +++ b/matchers/be_a_directory.go @@ -24,11 +24,11 @@ func (t notADirectoryError) Error() string { } type BeADirectoryMatcher struct { - expected interface{} + expected any err error } -func (matcher *BeADirectoryMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeADirectoryMatcher) Match(actual any) (success bool, err error) { actualFilename, ok := actual.(string) if !ok { return false, fmt.Errorf("BeADirectoryMatcher matcher expects a file path") @@ -47,10 +47,10 @@ func (matcher *BeADirectoryMatcher) Match(actual interface{}) (success bool, err return true, nil } -func (matcher *BeADirectoryMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeADirectoryMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, fmt.Sprintf("to be a directory: %s", matcher.err)) } -func (matcher *BeADirectoryMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeADirectoryMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not be a directory") } diff --git a/matchers/be_a_regular_file.go b/matchers/be_a_regular_file.go index 8fefc4deb..3e53d6285 100644 --- a/matchers/be_a_regular_file.go +++ b/matchers/be_a_regular_file.go @@ -24,11 +24,11 @@ func (t notARegularFileError) Error() string { } type BeARegularFileMatcher struct { - expected interface{} + expected any err error } -func (matcher *BeARegularFileMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeARegularFileMatcher) Match(actual any) (success bool, err error) { actualFilename, ok := actual.(string) if !ok { return false, fmt.Errorf("BeARegularFileMatcher matcher expects a file path") @@ -47,10 +47,10 @@ func (matcher *BeARegularFileMatcher) Match(actual interface{}) (success bool, e return true, nil } -func (matcher *BeARegularFileMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeARegularFileMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, fmt.Sprintf("to be a regular file: %s", matcher.err)) } -func (matcher *BeARegularFileMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeARegularFileMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not be a regular file") } diff --git a/matchers/be_an_existing_file.go b/matchers/be_an_existing_file.go index e2bdd2811..04f156db3 100644 --- a/matchers/be_an_existing_file.go +++ b/matchers/be_an_existing_file.go @@ -10,10 +10,10 @@ import ( ) type BeAnExistingFileMatcher struct { - expected interface{} + expected any } -func (matcher *BeAnExistingFileMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeAnExistingFileMatcher) Match(actual any) (success bool, err error) { actualFilename, ok := actual.(string) if !ok { return false, fmt.Errorf("BeAnExistingFileMatcher matcher expects a file path") @@ -31,10 +31,10 @@ func (matcher *BeAnExistingFileMatcher) Match(actual interface{}) (success bool, return true, nil } -func (matcher *BeAnExistingFileMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeAnExistingFileMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to exist") } -func (matcher *BeAnExistingFileMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeAnExistingFileMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to exist") } diff --git a/matchers/be_closed_matcher.go b/matchers/be_closed_matcher.go index f13c24490..4319dde45 100644 --- a/matchers/be_closed_matcher.go +++ b/matchers/be_closed_matcher.go @@ -12,7 +12,7 @@ import ( type BeClosedMatcher struct { } -func (matcher *BeClosedMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeClosedMatcher) Match(actual any) (success bool, err error) { if !isChan(actual) { return false, fmt.Errorf("BeClosed matcher expects a channel. Got:\n%s", format.Object(actual, 1)) } @@ -39,10 +39,10 @@ func (matcher *BeClosedMatcher) Match(actual interface{}) (success bool, err err return closed, nil } -func (matcher *BeClosedMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeClosedMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be closed") } -func (matcher *BeClosedMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeClosedMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "to be open") } diff --git a/matchers/be_comparable_to_matcher.go b/matchers/be_comparable_to_matcher.go index 4e3897858..532fc3744 100644 --- a/matchers/be_comparable_to_matcher.go +++ b/matchers/be_comparable_to_matcher.go @@ -9,11 +9,11 @@ import ( ) type BeComparableToMatcher struct { - Expected interface{} + Expected any Options cmp.Options } -func (matcher *BeComparableToMatcher) Match(actual interface{}) (success bool, matchErr error) { +func (matcher *BeComparableToMatcher) Match(actual any) (success bool, matchErr error) { if actual == nil && matcher.Expected == nil { return false, fmt.Errorf("Refusing to compare to .\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") } @@ -40,10 +40,10 @@ func (matcher *BeComparableToMatcher) Match(actual interface{}) (success bool, m return cmp.Equal(actual, matcher.Expected, matcher.Options...), nil } -func (matcher *BeComparableToMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeComparableToMatcher) FailureMessage(actual any) (message string) { return fmt.Sprint("Expected object to be comparable, diff: ", cmp.Diff(actual, matcher.Expected, matcher.Options...)) } -func (matcher *BeComparableToMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeComparableToMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to be comparable to", matcher.Expected) } diff --git a/matchers/be_element_of_matcher.go b/matchers/be_element_of_matcher.go index 9ee75a5d5..406fe5484 100644 --- a/matchers/be_element_of_matcher.go +++ b/matchers/be_element_of_matcher.go @@ -10,10 +10,10 @@ import ( ) type BeElementOfMatcher struct { - Elements []interface{} + Elements []any } -func (matcher *BeElementOfMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeElementOfMatcher) Match(actual any) (success bool, err error) { if reflect.TypeOf(actual) == nil { return false, fmt.Errorf("BeElement matcher expects actual to be typed") } @@ -34,10 +34,10 @@ func (matcher *BeElementOfMatcher) Match(actual interface{}) (success bool, err return false, lastError } -func (matcher *BeElementOfMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeElementOfMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be an element of", presentable(matcher.Elements)) } -func (matcher *BeElementOfMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeElementOfMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to be an element of", presentable(matcher.Elements)) } diff --git a/matchers/be_element_of_matcher_test.go b/matchers/be_element_of_matcher_test.go index 7110aebc3..79da0b0c0 100644 --- a/matchers/be_element_of_matcher_test.go +++ b/matchers/be_element_of_matcher_test.go @@ -44,7 +44,7 @@ var _ = Describe("BeElementOf", func() { When("passed an unsupported type", func() { It("should error", func() { - success, err := (&BeElementOfMatcher{Elements: []interface{}{0}}).Match(nil) + success, err := (&BeElementOfMatcher{Elements: []any{0}}).Match(nil) Expect(success).Should(BeFalse()) Expect(err).Should(HaveOccurred()) diff --git a/matchers/be_empty_matcher.go b/matchers/be_empty_matcher.go index bd7f0b96e..e9e0644f3 100644 --- a/matchers/be_empty_matcher.go +++ b/matchers/be_empty_matcher.go @@ -13,7 +13,7 @@ import ( type BeEmptyMatcher struct { } -func (matcher *BeEmptyMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeEmptyMatcher) Match(actual any) (success bool, err error) { // short-circuit the iterator case, as we only need to see the first // element, if any. if miter.IsIter(actual) { @@ -34,10 +34,10 @@ func (matcher *BeEmptyMatcher) Match(actual interface{}) (success bool, err erro return length == 0, nil } -func (matcher *BeEmptyMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeEmptyMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be empty") } -func (matcher *BeEmptyMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeEmptyMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to be empty") } diff --git a/matchers/be_equivalent_to_matcher.go b/matchers/be_equivalent_to_matcher.go index 263627f40..37b3080ba 100644 --- a/matchers/be_equivalent_to_matcher.go +++ b/matchers/be_equivalent_to_matcher.go @@ -10,10 +10,10 @@ import ( ) type BeEquivalentToMatcher struct { - Expected interface{} + Expected any } -func (matcher *BeEquivalentToMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeEquivalentToMatcher) Match(actual any) (success bool, err error) { if actual == nil && matcher.Expected == nil { return false, fmt.Errorf("Both actual and expected must not be nil.") } @@ -27,10 +27,10 @@ func (matcher *BeEquivalentToMatcher) Match(actual interface{}) (success bool, e return reflect.DeepEqual(convertedActual, matcher.Expected), nil } -func (matcher *BeEquivalentToMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeEquivalentToMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be equivalent to", matcher.Expected) } -func (matcher *BeEquivalentToMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeEquivalentToMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to be equivalent to", matcher.Expected) } diff --git a/matchers/be_false_matcher.go b/matchers/be_false_matcher.go index 8ee2b1c51..55e869515 100644 --- a/matchers/be_false_matcher.go +++ b/matchers/be_false_matcher.go @@ -12,7 +12,7 @@ type BeFalseMatcher struct { Reason string } -func (matcher *BeFalseMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeFalseMatcher) Match(actual any) (success bool, err error) { if !isBool(actual) { return false, fmt.Errorf("Expected a boolean. Got:\n%s", format.Object(actual, 1)) } @@ -20,7 +20,7 @@ func (matcher *BeFalseMatcher) Match(actual interface{}) (success bool, err erro return actual == false, nil } -func (matcher *BeFalseMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeFalseMatcher) FailureMessage(actual any) (message string) { if matcher.Reason == "" { return format.Message(actual, "to be false") } else { @@ -28,7 +28,7 @@ func (matcher *BeFalseMatcher) FailureMessage(actual interface{}) (message strin } } -func (matcher *BeFalseMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeFalseMatcher) NegatedFailureMessage(actual any) (message string) { if matcher.Reason == "" { return format.Message(actual, "not to be false") } else { diff --git a/matchers/be_identical_to.go b/matchers/be_identical_to.go index 631ce11e3..579aa41b3 100644 --- a/matchers/be_identical_to.go +++ b/matchers/be_identical_to.go @@ -10,10 +10,10 @@ import ( ) type BeIdenticalToMatcher struct { - Expected interface{} + Expected any } -func (matcher *BeIdenticalToMatcher) Match(actual interface{}) (success bool, matchErr error) { +func (matcher *BeIdenticalToMatcher) Match(actual any) (success bool, matchErr error) { if actual == nil && matcher.Expected == nil { return false, fmt.Errorf("Refusing to compare to .\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") } @@ -30,10 +30,10 @@ func (matcher *BeIdenticalToMatcher) Match(actual interface{}) (success bool, ma return actual == matcher.Expected, nil } -func (matcher *BeIdenticalToMatcher) FailureMessage(actual interface{}) string { +func (matcher *BeIdenticalToMatcher) FailureMessage(actual any) string { return format.Message(actual, "to be identical to", matcher.Expected) } -func (matcher *BeIdenticalToMatcher) NegatedFailureMessage(actual interface{}) string { +func (matcher *BeIdenticalToMatcher) NegatedFailureMessage(actual any) string { return format.Message(actual, "not to be identical to", matcher.Expected) } diff --git a/matchers/be_key_of_matcher.go b/matchers/be_key_of_matcher.go index 449a291ef..3fff3df78 100644 --- a/matchers/be_key_of_matcher.go +++ b/matchers/be_key_of_matcher.go @@ -8,10 +8,10 @@ import ( ) type BeKeyOfMatcher struct { - Map interface{} + Map any } -func (matcher *BeKeyOfMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeKeyOfMatcher) Match(actual any) (success bool, err error) { if !isMap(matcher.Map) { return false, fmt.Errorf("BeKeyOf matcher needs expected to be a map type") } @@ -36,10 +36,10 @@ func (matcher *BeKeyOfMatcher) Match(actual interface{}) (success bool, err erro return false, lastError } -func (matcher *BeKeyOfMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeKeyOfMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be a key of", presentable(valuesOf(matcher.Map))) } -func (matcher *BeKeyOfMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeKeyOfMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to be a key of", presentable(valuesOf(matcher.Map))) } diff --git a/matchers/be_key_of_matcher_test.go b/matchers/be_key_of_matcher_test.go index f3f120134..c26067382 100644 --- a/matchers/be_key_of_matcher_test.go +++ b/matchers/be_key_of_matcher_test.go @@ -32,7 +32,7 @@ var _ = Describe("BeKeyOf", func() { When("passed an unsupported type", func() { It("should error", func() { - success, err := (&BeKeyOfMatcher{Map: []interface{}{0}}).Match(nil) + success, err := (&BeKeyOfMatcher{Map: []any{0}}).Match(nil) Expect(success).Should(BeFalse()) Expect(err).Should(HaveOccurred()) diff --git a/matchers/be_nil_matcher.go b/matchers/be_nil_matcher.go index 551d99d74..cab37f4f9 100644 --- a/matchers/be_nil_matcher.go +++ b/matchers/be_nil_matcher.go @@ -7,14 +7,14 @@ import "github.com/onsi/gomega/format" type BeNilMatcher struct { } -func (matcher *BeNilMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeNilMatcher) Match(actual any) (success bool, err error) { return isNil(actual), nil } -func (matcher *BeNilMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeNilMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be nil") } -func (matcher *BeNilMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeNilMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to be nil") } diff --git a/matchers/be_numerically_matcher.go b/matchers/be_numerically_matcher.go index 100735de3..7e6ce154e 100644 --- a/matchers/be_numerically_matcher.go +++ b/matchers/be_numerically_matcher.go @@ -11,18 +11,18 @@ import ( type BeNumericallyMatcher struct { Comparator string - CompareTo []interface{} + CompareTo []any } -func (matcher *BeNumericallyMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeNumericallyMatcher) FailureMessage(actual any) (message string) { return matcher.FormatFailureMessage(actual, false) } -func (matcher *BeNumericallyMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeNumericallyMatcher) NegatedFailureMessage(actual any) (message string) { return matcher.FormatFailureMessage(actual, true) } -func (matcher *BeNumericallyMatcher) FormatFailureMessage(actual interface{}, negated bool) (message string) { +func (matcher *BeNumericallyMatcher) FormatFailureMessage(actual any, negated bool) (message string) { if len(matcher.CompareTo) == 1 { message = fmt.Sprintf("to be %s", matcher.Comparator) } else { @@ -34,7 +34,7 @@ func (matcher *BeNumericallyMatcher) FormatFailureMessage(actual interface{}, ne return format.Message(actual, message, matcher.CompareTo[0]) } -func (matcher *BeNumericallyMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeNumericallyMatcher) Match(actual any) (success bool, err error) { if len(matcher.CompareTo) == 0 || len(matcher.CompareTo) > 2 { return false, fmt.Errorf("BeNumerically requires 1 or 2 CompareTo arguments. Got:\n%s", format.Object(matcher.CompareTo, 1)) } diff --git a/matchers/be_numerically_matcher_test.go b/matchers/be_numerically_matcher_test.go index 9002d90a8..3d34740aa 100644 --- a/matchers/be_numerically_matcher_test.go +++ b/matchers/be_numerically_matcher_test.go @@ -132,7 +132,7 @@ var _ = Describe("BeNumerically", func() { When("passed a non-number", func() { It("should error", func() { - success, err := (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{5}}).Match("foo") + success, err := (&BeNumericallyMatcher{Comparator: "==", CompareTo: []any{5}}).Match("foo") Expect(success).Should(BeFalse()) Expect(err).Should(HaveOccurred()) @@ -140,24 +140,24 @@ var _ = Describe("BeNumerically", func() { Expect(success).Should(BeFalse()) Expect(err).Should(HaveOccurred()) - success, err = (&BeNumericallyMatcher{Comparator: "~", CompareTo: []interface{}{3.0, "foo"}}).Match(5.0) + success, err = (&BeNumericallyMatcher{Comparator: "~", CompareTo: []any{3.0, "foo"}}).Match(5.0) Expect(success).Should(BeFalse()) Expect(err).Should(HaveOccurred()) Expect(err.Error()).Should(ContainSubstring("foo")) - success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{"bar"}}).Match(5) + success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []any{"bar"}}).Match(5) Expect(success).Should(BeFalse()) Expect(err).Should(HaveOccurred()) - success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{"bar"}}).Match("foo") + success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []any{"bar"}}).Match("foo") Expect(success).Should(BeFalse()) Expect(err).Should(HaveOccurred()) - success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{nil}}).Match(0) + success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []any{nil}}).Match(0) Expect(success).Should(BeFalse()) Expect(err).Should(HaveOccurred()) - success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{0}}).Match(nil) + success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []any{0}}).Match(nil) Expect(success).Should(BeFalse()) Expect(err).Should(HaveOccurred()) }) @@ -165,7 +165,7 @@ var _ = Describe("BeNumerically", func() { When("passed an unsupported comparator", func() { It("should error", func() { - success, err := (&BeNumericallyMatcher{Comparator: "!=", CompareTo: []interface{}{5}}).Match(4) + success, err := (&BeNumericallyMatcher{Comparator: "!=", CompareTo: []any{5}}).Match(4) Expect(success).Should(BeFalse()) Expect(err).Should(HaveOccurred()) }) diff --git a/matchers/be_sent_matcher.go b/matchers/be_sent_matcher.go index cf582a3fc..14ffbf6c4 100644 --- a/matchers/be_sent_matcher.go +++ b/matchers/be_sent_matcher.go @@ -10,11 +10,11 @@ import ( ) type BeSentMatcher struct { - Arg interface{} + Arg any channelClosed bool } -func (matcher *BeSentMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeSentMatcher) Match(actual any) (success bool, err error) { if !isChan(actual) { return false, fmt.Errorf("BeSent expects a channel. Got:\n%s", format.Object(actual, 1)) } @@ -56,15 +56,15 @@ func (matcher *BeSentMatcher) Match(actual interface{}) (success bool, err error return didSend, nil } -func (matcher *BeSentMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeSentMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to send:", matcher.Arg) } -func (matcher *BeSentMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeSentMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to send:", matcher.Arg) } -func (matcher *BeSentMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { +func (matcher *BeSentMatcher) MatchMayChangeInTheFuture(actual any) bool { if !isChan(actual) { return false } diff --git a/matchers/be_temporally_matcher.go b/matchers/be_temporally_matcher.go index dec4db024..edb647c6f 100644 --- a/matchers/be_temporally_matcher.go +++ b/matchers/be_temporally_matcher.go @@ -15,17 +15,17 @@ type BeTemporallyMatcher struct { Threshold []time.Duration } -func (matcher *BeTemporallyMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeTemporallyMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, fmt.Sprintf("to be %s", matcher.Comparator), matcher.CompareTo) } -func (matcher *BeTemporallyMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeTemporallyMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, fmt.Sprintf("not to be %s", matcher.Comparator), matcher.CompareTo) } -func (matcher *BeTemporallyMatcher) Match(actual interface{}) (bool, error) { +func (matcher *BeTemporallyMatcher) Match(actual any) (bool, error) { // predicate to test for time.Time type - isTime := func(t interface{}) bool { + isTime := func(t any) bool { _, ok := t.(time.Time) return ok } diff --git a/matchers/be_true_matcher.go b/matchers/be_true_matcher.go index 3576aac88..a010bec5a 100644 --- a/matchers/be_true_matcher.go +++ b/matchers/be_true_matcher.go @@ -12,7 +12,7 @@ type BeTrueMatcher struct { Reason string } -func (matcher *BeTrueMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeTrueMatcher) Match(actual any) (success bool, err error) { if !isBool(actual) { return false, fmt.Errorf("Expected a boolean. Got:\n%s", format.Object(actual, 1)) } @@ -20,7 +20,7 @@ func (matcher *BeTrueMatcher) Match(actual interface{}) (success bool, err error return actual.(bool), nil } -func (matcher *BeTrueMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeTrueMatcher) FailureMessage(actual any) (message string) { if matcher.Reason == "" { return format.Message(actual, "to be true") } else { @@ -28,7 +28,7 @@ func (matcher *BeTrueMatcher) FailureMessage(actual interface{}) (message string } } -func (matcher *BeTrueMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeTrueMatcher) NegatedFailureMessage(actual any) (message string) { if matcher.Reason == "" { return format.Message(actual, "not to be true") } else { diff --git a/matchers/be_zero_matcher.go b/matchers/be_zero_matcher.go index 26196f168..f5f5d7f7d 100644 --- a/matchers/be_zero_matcher.go +++ b/matchers/be_zero_matcher.go @@ -9,7 +9,7 @@ import ( type BeZeroMatcher struct { } -func (matcher *BeZeroMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeZeroMatcher) Match(actual any) (success bool, err error) { if actual == nil { return true, nil } @@ -19,10 +19,10 @@ func (matcher *BeZeroMatcher) Match(actual interface{}) (success bool, err error } -func (matcher *BeZeroMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeZeroMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be zero-valued") } -func (matcher *BeZeroMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeZeroMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to be zero-valued") } diff --git a/matchers/consist_of.go b/matchers/consist_of.go index a11188182..05c751b66 100644 --- a/matchers/consist_of.go +++ b/matchers/consist_of.go @@ -12,12 +12,12 @@ import ( ) type ConsistOfMatcher struct { - Elements []interface{} - missingElements []interface{} - extraElements []interface{} + Elements []any + missingElements []any + extraElements []any } -func (matcher *ConsistOfMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *ConsistOfMatcher) Match(actual any) (success bool, err error) { if !isArrayOrSlice(actual) && !isMap(actual) && !miter.IsIter(actual) { return false, fmt.Errorf("ConsistOf matcher expects an array/slice/map/iter.Seq/iter.Seq2. Got:\n%s", format.Object(actual, 1)) } @@ -35,19 +35,19 @@ func (matcher *ConsistOfMatcher) Match(actual interface{}) (success bool, err er return true, nil } - var missingMatchers []interface{} + var missingMatchers []any matcher.extraElements, missingMatchers = bipartiteGraph.FreeLeftRight(edges) matcher.missingElements = equalMatchersToElements(missingMatchers) return false, nil } -func neighbours(value, matcher interface{}) (bool, error) { +func neighbours(value, matcher any) (bool, error) { match, err := matcher.(omegaMatcher).Match(value) return match && err == nil, nil } -func equalMatchersToElements(matchers []interface{}) (elements []interface{}) { +func equalMatchersToElements(matchers []any) (elements []any) { for _, matcher := range matchers { if equalMatcher, ok := matcher.(*EqualMatcher); ok { elements = append(elements, equalMatcher.Expected) @@ -60,7 +60,7 @@ func equalMatchersToElements(matchers []interface{}) (elements []interface{}) { return } -func flatten(elems []interface{}) []interface{} { +func flatten(elems []any) []any { if len(elems) != 1 || !(isArrayOrSlice(elems[0]) || (miter.IsIter(elems[0]) && !miter.IsSeq2(elems[0]))) { @@ -77,14 +77,14 @@ func flatten(elems []interface{}) []interface{} { } value := reflect.ValueOf(elems[0]) - flattened := make([]interface{}, value.Len()) + flattened := make([]any, value.Len()) for i := 0; i < value.Len(); i++ { flattened[i] = value.Index(i).Interface() } return flattened } -func matchers(expectedElems []interface{}) (matchers []interface{}) { +func matchers(expectedElems []any) (matchers []any) { for _, e := range flatten(expectedElems) { if e == nil { matchers = append(matchers, &BeNilMatcher{}) @@ -97,11 +97,11 @@ func matchers(expectedElems []interface{}) (matchers []interface{}) { return } -func presentable(elems []interface{}) interface{} { +func presentable(elems []any) any { elems = flatten(elems) if len(elems) == 0 { - return []interface{}{} + return []any{} } sv := reflect.ValueOf(elems) @@ -125,9 +125,9 @@ func presentable(elems []interface{}) interface{} { return ss.Interface() } -func valuesOf(actual interface{}) []interface{} { +func valuesOf(actual any) []any { value := reflect.ValueOf(actual) - values := []interface{}{} + values := []any{} if miter.IsIter(actual) { if miter.IsSeq2(actual) { miter.IterateKV(actual, func(k, v reflect.Value) bool { @@ -154,7 +154,7 @@ func valuesOf(actual interface{}) []interface{} { return values } -func (matcher *ConsistOfMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *ConsistOfMatcher) FailureMessage(actual any) (message string) { message = format.Message(actual, "to consist of", presentable(matcher.Elements)) message = appendMissingElements(message, matcher.missingElements) if len(matcher.extraElements) > 0 { @@ -164,7 +164,7 @@ func (matcher *ConsistOfMatcher) FailureMessage(actual interface{}) (message str return } -func appendMissingElements(message string, missingElements []interface{}) string { +func appendMissingElements(message string, missingElements []any) string { if len(missingElements) == 0 { return message } @@ -172,6 +172,6 @@ func appendMissingElements(message string, missingElements []interface{}) string format.Object(presentable(missingElements), 1)) } -func (matcher *ConsistOfMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *ConsistOfMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to consist of", presentable(matcher.Elements)) } diff --git a/matchers/consist_of_test.go b/matchers/consist_of_test.go index 8ad696e45..052752c5c 100644 --- a/matchers/consist_of_test.go +++ b/matchers/consist_of_test.go @@ -63,7 +63,7 @@ var _ = Describe("ConsistOf", func() { When("a matcher errors", func() { It("should soldier on", func() { Expect([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf(BeFalse(), "foo", "bar")) - Expect([]interface{}{"foo", "bar", false}).Should(ConsistOf(BeFalse(), ContainSubstring("foo"), "bar")) + Expect([]any{"foo", "bar", false}).Should(ConsistOf(BeFalse(), ContainSubstring("foo"), "bar")) }) }) }) @@ -173,9 +173,9 @@ the extra elements were }) When("the expected values are different types", func() { - It("uses interface{} for the expectation slice", func() { + It("uses any for the expectation slice", func() { failures := InterceptGomegaFailures(func() { - Expect([]interface{}{1, true}).To(ConsistOf(1, "C")) + Expect([]any{1, true}).To(ConsistOf(1, "C")) }) expected := `to consist of @@ -187,9 +187,9 @@ the extra elements were Expect(failures).To(ConsistOf(MatchRegexp(expected))) }) - It("uses interface{} for the negated expectation slice", func() { + It("uses any for the negated expectation slice", func() { failures := InterceptGomegaFailures(func() { - Expect([]interface{}{1, "B"}).NotTo(ConsistOf(1, "B")) + Expect([]any{1, "B"}).NotTo(ConsistOf(1, "B")) }) expected := `not to consist of\n\s*<\[\]interface {} \| len:2, cap:2>: \[1, "B"\]` diff --git a/matchers/contain_element_matcher.go b/matchers/contain_element_matcher.go index a657ff07e..8337a5261 100644 --- a/matchers/contain_element_matcher.go +++ b/matchers/contain_element_matcher.go @@ -12,11 +12,11 @@ import ( ) type ContainElementMatcher struct { - Element interface{} - Result []interface{} + Element any + Result []any } -func (matcher *ContainElementMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *ContainElementMatcher) Match(actual any) (success bool, err error) { if !isArrayOrSlice(actual) && !isMap(actual) && !miter.IsIter(actual) { return false, fmt.Errorf("ContainElement matcher expects an array/slice/map/iterator. Got:\n%s", format.Object(actual, 1)) } @@ -132,14 +132,14 @@ func (matcher *ContainElementMatcher) Match(actual interface{}) (success bool, e var lastError error if !miter.IsIter(actual) { - var valueAt func(int) interface{} + var valueAt func(int) any var foundAt func(int) // We're dealing with an array/slice/map, so in all cases we can iterate // over the elements in actual using indices (that can be considered // keys in case of maps). if isMap(actual) { keys := value.MapKeys() - valueAt = func(i int) interface{} { + valueAt = func(i int) any { return value.MapIndex(keys[i]).Interface() } if result.Kind() != reflect.Invalid { @@ -150,7 +150,7 @@ func (matcher *ContainElementMatcher) Match(actual interface{}) (success bool, e } } } else { - valueAt = func(i int) interface{} { + valueAt = func(i int) any { return value.Index(i).Interface() } if result.Kind() != reflect.Invalid { @@ -284,10 +284,10 @@ func (matcher *ContainElementMatcher) Match(actual interface{}) (success bool, e return true, nil } -func (matcher *ContainElementMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *ContainElementMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to contain element matching", matcher.Element) } -func (matcher *ContainElementMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *ContainElementMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to contain element matching", matcher.Element) } diff --git a/matchers/contain_element_matcher_test.go b/matchers/contain_element_matcher_test.go index 85753c2ce..9c2a2936a 100644 --- a/matchers/contain_element_matcher_test.go +++ b/matchers/contain_element_matcher_test.go @@ -39,11 +39,11 @@ var _ = Describe("ContainElement", func() { }) It("should power through even if the matcher ever fails", func() { - Expect([]interface{}{1, 2, "3", 4}).Should(ContainElement(BeNumerically(">=", 3))) + Expect([]any{1, 2, "3", 4}).Should(ContainElement(BeNumerically(">=", 3))) }) It("should fail if the matcher fails", func() { - actual := []interface{}{1, 2, "3", "4"} + actual := []any{1, 2, "3", "4"} success, err := (&ContainElementMatcher{Element: BeNumerically(">=", 3)}).Match(actual) Expect(success).Should(BeFalse()) Expect(err).Should(HaveOccurred()) @@ -157,27 +157,27 @@ var _ = Describe("ContainElement", func() { Expect(ContainElement("foo", &arrstash).Match(actual)).Error().To(HaveOccurred()) }) - It("should error for actual []interface{}, return reference T", func() { - actual := []interface{}{"foo", 42} + It("should error for actual []any, return reference T", func() { + actual := []any{"foo", 42} var stash int Expect(ContainElement(Not(BeZero()), &stash).Match(actual)).Error().To( MatchError(MatchRegexp(`cannot return findings\. Need \*interface.+, got \*int`))) }) - It("should error for actual []interface{}, return reference []T", func() { - actual := []interface{}{"foo", 42} + It("should error for actual []any, return reference []T", func() { + actual := []any{"foo", 42} var stash []string Expect(ContainElement(Not(BeZero()), &stash).Match(actual)).Error().To( MatchError(MatchRegexp(`cannot return findings\. Need \*\[\]interface.+, got \*\[\]string`))) }) - It("should error for actual map[T]T, return reference map[T]interface{}", func() { + It("should error for actual map[T]T, return reference map[T]any", func() { actual := map[string]string{ "foo": "foo", "bar": "bar", "baz": "baz", } - var stash map[string]interface{} + var stash map[string]any Expect(ContainElement(Not(BeZero()), &stash).Match(actual)).Error().To( MatchError(MatchRegexp(`cannot return findings\. Need \*map\[string\]string, got \*map\[string\]interface`))) }) @@ -224,8 +224,8 @@ var _ = Describe("ContainElement", func() { When("the matcher errors", func() { It("should report last matcher error", func() { - actual := []interface{}{"bar", 42} - var stash []interface{} + actual := []any{"bar", 42} + var stash []any Expect(ContainElement(HaveField("yeehaw", 42), &stash).Match(actual)).Error().To(MatchError(MatchRegexp(`HaveField encountered:\n.*: 42\nWhich is not a struct`))) }) }) @@ -282,7 +282,7 @@ var _ = Describe("ContainElement", func() { }) It("should fail if the matcher fails", func() { - elements := []interface{}{1, 2, "3", "4"} + elements := []any{1, 2, "3", "4"} it := func(yield func(any) bool) { for _, element := range elements { if !yield(element) { @@ -397,8 +397,8 @@ var _ = Describe("ContainElement", func() { Expect(ContainElement("foo", &arrstash).Match(universalIter2)).Error().To(HaveOccurred()) }) - It("should error for actual map[T1]T2, return reference map[T1]interface{}", func() { - var stash map[int]interface{} + It("should error for actual map[T1]T2, return reference map[T1]any", func() { + var stash map[int]any Expect(ContainElement(Not(BeZero()), &stash).Match(universalIter2)).Error().To( MatchError(MatchRegexp(`cannot return findings\. Need \*map\[int\]string, got \*map\[int\]interface`))) }) @@ -426,7 +426,7 @@ var _ = Describe("ContainElement", func() { When("the matcher errors", func() { It("should report last matcher error", func() { - var stash []interface{} + var stash []any Expect(ContainElement(HaveField("yeehaw", 42), &stash).Match(universalIter)).Error().To(MatchError(MatchRegexp(`HaveField encountered:\n.*: baz\nWhich is not a struct`))) }) }) diff --git a/matchers/contain_elements_matcher.go b/matchers/contain_elements_matcher.go index d9fcb8b80..ce3041892 100644 --- a/matchers/contain_elements_matcher.go +++ b/matchers/contain_elements_matcher.go @@ -9,11 +9,11 @@ import ( ) type ContainElementsMatcher struct { - Elements []interface{} - missingElements []interface{} + Elements []any + missingElements []any } -func (matcher *ContainElementsMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *ContainElementsMatcher) Match(actual any) (success bool, err error) { if !isArrayOrSlice(actual) && !isMap(actual) && !miter.IsIter(actual) { return false, fmt.Errorf("ContainElements matcher expects an array/slice/map/iter.Seq/iter.Seq2. Got:\n%s", format.Object(actual, 1)) } @@ -35,11 +35,11 @@ func (matcher *ContainElementsMatcher) Match(actual interface{}) (success bool, return false, nil } -func (matcher *ContainElementsMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *ContainElementsMatcher) FailureMessage(actual any) (message string) { message = format.Message(actual, "to contain elements", presentable(matcher.Elements)) return appendMissingElements(message, matcher.missingElements) } -func (matcher *ContainElementsMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *ContainElementsMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to contain elements", presentable(matcher.Elements)) } diff --git a/matchers/contain_elements_matcher_test.go b/matchers/contain_elements_matcher_test.go index 48bd9ef8e..bb12d2342 100644 --- a/matchers/contain_elements_matcher_test.go +++ b/matchers/contain_elements_matcher_test.go @@ -62,7 +62,7 @@ var _ = Describe("ContainElements", func() { Context("when a matcher errors", func() { It("should soldier on", func() { Expect([]string{"foo", "bar", "baz"}).ShouldNot(ContainElements(BeFalse(), "foo", "bar")) - Expect([]interface{}{"foo", "bar", false}).Should(ContainElements(BeFalse(), ContainSubstring("foo"), "bar")) + Expect([]any{"foo", "bar", false}).Should(ContainElements(BeFalse(), ContainSubstring("foo"), "bar")) }) }) }) @@ -128,9 +128,9 @@ the missing elements were }) When("the expected values are different types", func() { - It("uses interface{} for the expectation slice", func() { + It("uses any for the expectation slice", func() { failures := InterceptGomegaFailures(func() { - Expect([]interface{}{1, true}).To(ContainElements(1, "C")) + Expect([]any{1, true}).To(ContainElements(1, "C")) }) expected := `to contain elements @@ -140,9 +140,9 @@ the missing elements were Expect(failures).To(ConsistOf(MatchRegexp(expected))) }) - It("uses interface{} for the negated expectation slice", func() { + It("uses any for the negated expectation slice", func() { failures := InterceptGomegaFailures(func() { - Expect([]interface{}{1, "B"}).NotTo(ContainElements(1, "B")) + Expect([]any{1, "B"}).NotTo(ContainElements(1, "B")) }) expected := `not to contain elements\n\s*<\[\]interface {} \| len:2, cap:2>: \[1, "B"\]` diff --git a/matchers/contain_substring_matcher.go b/matchers/contain_substring_matcher.go index e725f8c27..d9980ee26 100644 --- a/matchers/contain_substring_matcher.go +++ b/matchers/contain_substring_matcher.go @@ -11,10 +11,10 @@ import ( type ContainSubstringMatcher struct { Substr string - Args []interface{} + Args []any } -func (matcher *ContainSubstringMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *ContainSubstringMatcher) Match(actual any) (success bool, err error) { actualString, ok := toString(actual) if !ok { return false, fmt.Errorf("ContainSubstring matcher requires a string or stringer. Got:\n%s", format.Object(actual, 1)) @@ -31,10 +31,10 @@ func (matcher *ContainSubstringMatcher) stringToMatch() string { return stringToMatch } -func (matcher *ContainSubstringMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *ContainSubstringMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to contain substring", matcher.stringToMatch()) } -func (matcher *ContainSubstringMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *ContainSubstringMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to contain substring", matcher.stringToMatch()) } diff --git a/matchers/equal_matcher.go b/matchers/equal_matcher.go index befb7bdfd..4ad166157 100644 --- a/matchers/equal_matcher.go +++ b/matchers/equal_matcher.go @@ -9,10 +9,10 @@ import ( ) type EqualMatcher struct { - Expected interface{} + Expected any } -func (matcher *EqualMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *EqualMatcher) Match(actual any) (success bool, err error) { if actual == nil && matcher.Expected == nil { return false, fmt.Errorf("Refusing to compare to .\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") } @@ -27,7 +27,7 @@ func (matcher *EqualMatcher) Match(actual interface{}) (success bool, err error) return reflect.DeepEqual(actual, matcher.Expected), nil } -func (matcher *EqualMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *EqualMatcher) FailureMessage(actual any) (message string) { actualString, actualOK := actual.(string) expectedString, expectedOK := matcher.Expected.(string) if actualOK && expectedOK { @@ -37,6 +37,6 @@ func (matcher *EqualMatcher) FailureMessage(actual interface{}) (message string) return format.Message(actual, "to equal", matcher.Expected) } -func (matcher *EqualMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *EqualMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to equal", matcher.Expected) } diff --git a/matchers/have_cap_matcher.go b/matchers/have_cap_matcher.go index 9856752f1..a4fcfc425 100644 --- a/matchers/have_cap_matcher.go +++ b/matchers/have_cap_matcher.go @@ -12,7 +12,7 @@ type HaveCapMatcher struct { Count int } -func (matcher *HaveCapMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveCapMatcher) Match(actual any) (success bool, err error) { length, ok := capOf(actual) if !ok { return false, fmt.Errorf("HaveCap matcher expects a array/channel/slice. Got:\n%s", format.Object(actual, 1)) @@ -21,10 +21,10 @@ func (matcher *HaveCapMatcher) Match(actual interface{}) (success bool, err erro return length == matcher.Count, nil } -func (matcher *HaveCapMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveCapMatcher) FailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\nto have capacity %d", format.Object(actual, 1), matcher.Count) } -func (matcher *HaveCapMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveCapMatcher) NegatedFailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\nnot to have capacity %d", format.Object(actual, 1), matcher.Count) } diff --git a/matchers/have_each_matcher.go b/matchers/have_each_matcher.go index 4111f2b86..4c45063bd 100644 --- a/matchers/have_each_matcher.go +++ b/matchers/have_each_matcher.go @@ -9,10 +9,10 @@ import ( ) type HaveEachMatcher struct { - Element interface{} + Element any } -func (matcher *HaveEachMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveEachMatcher) Match(actual any) (success bool, err error) { if !isArrayOrSlice(actual) && !isMap(actual) && !miter.IsIter(actual) { return false, fmt.Errorf("HaveEach matcher expects an array/slice/map/iter.Seq/iter.Seq2. Got:\n%s", format.Object(actual, 1)) @@ -61,14 +61,14 @@ func (matcher *HaveEachMatcher) Match(actual interface{}) (success bool, err err format.Object(actual, 1)) } - var valueAt func(int) interface{} + var valueAt func(int) any if isMap(actual) { keys := value.MapKeys() - valueAt = func(i int) interface{} { + valueAt = func(i int) any { return value.MapIndex(keys[i]).Interface() } } else { - valueAt = func(i int) interface{} { + valueAt = func(i int) any { return value.Index(i).Interface() } } @@ -89,11 +89,11 @@ func (matcher *HaveEachMatcher) Match(actual interface{}) (success bool, err err } // FailureMessage returns a suitable failure message. -func (matcher *HaveEachMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveEachMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to contain element matching", matcher.Element) } // NegatedFailureMessage returns a suitable negated failure message. -func (matcher *HaveEachMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveEachMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to contain element matching", matcher.Element) } diff --git a/matchers/have_each_matcher_test.go b/matchers/have_each_matcher_test.go index 1f2ef4017..ccb0cc493 100644 --- a/matchers/have_each_matcher_test.go +++ b/matchers/have_each_matcher_test.go @@ -42,14 +42,14 @@ var _ = Describe("HaveEach", func() { }) It("should not power through if the matcher ever fails", func() { - actual := []interface{}{1, 2, "3", 4} + actual := []any{1, 2, "3", 4} success, err := (&HaveEachMatcher{Element: BeNumerically(">=", 1)}).Match(actual) Expect(success).Should(BeFalse()) Expect(err).Should(HaveOccurred()) }) It("should fail if the matcher fails", func() { - actual := []interface{}{1, 2, "3", "4"} + actual := []any{1, 2, "3", "4"} success, err := (&HaveEachMatcher{Element: BeNumerically(">=", 1)}).Match(actual) Expect(success).Should(BeFalse()) Expect(err).Should(HaveOccurred()) diff --git a/matchers/have_exact_elements.go b/matchers/have_exact_elements.go index 23799f1c6..8b2d297c5 100644 --- a/matchers/have_exact_elements.go +++ b/matchers/have_exact_elements.go @@ -14,13 +14,13 @@ type mismatchFailure struct { } type HaveExactElementsMatcher struct { - Elements []interface{} + Elements []any mismatchFailures []mismatchFailure missingIndex int extraIndex int } -func (matcher *HaveExactElementsMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveExactElementsMatcher) Match(actual any) (success bool, err error) { matcher.resetState() if isMap(actual) || miter.IsSeq2(actual) { @@ -108,7 +108,7 @@ func (matcher *HaveExactElementsMatcher) Match(actual interface{}) (success bool return success, nil } -func (matcher *HaveExactElementsMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveExactElementsMatcher) FailureMessage(actual any) (message string) { message = format.Message(actual, "to have exact elements with", presentable(matcher.Elements)) if matcher.missingIndex > 0 { message = fmt.Sprintf("%s\nthe missing elements start from index %d", message, matcher.missingIndex) @@ -125,7 +125,7 @@ func (matcher *HaveExactElementsMatcher) FailureMessage(actual interface{}) (mes return } -func (matcher *HaveExactElementsMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveExactElementsMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to contain elements", presentable(matcher.Elements)) } diff --git a/matchers/have_exact_elements_test.go b/matchers/have_exact_elements_test.go index bb938a033..b373c2f6c 100644 --- a/matchers/have_exact_elements_test.go +++ b/matchers/have_exact_elements_test.go @@ -57,7 +57,7 @@ var _ = Describe("HaveExactElements", func() { When("a matcher errors", func() { It("should soldier on", func() { Expect([]string{"foo", "bar", "baz"}).ShouldNot(HaveExactElements(BeFalse(), "bar", "baz")) - Expect([]interface{}{"foo", "bar", false}).Should(HaveExactElements(ContainSubstring("foo"), "bar", BeFalse())) + Expect([]any{"foo", "bar", false}).Should(HaveExactElements(ContainSubstring("foo"), "bar", BeFalse())) }) It("should include the error message, not the failure message", func() { diff --git a/matchers/have_existing_field_matcher.go b/matchers/have_existing_field_matcher.go index b57018745..a5a028e9a 100644 --- a/matchers/have_existing_field_matcher.go +++ b/matchers/have_existing_field_matcher.go @@ -11,7 +11,7 @@ type HaveExistingFieldMatcher struct { Field string } -func (matcher *HaveExistingFieldMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveExistingFieldMatcher) Match(actual any) (success bool, err error) { // we don't care about the field's actual value, just about any error in // trying to find the field (or method). _, err = extractField(actual, matcher.Field, "HaveExistingField") @@ -27,10 +27,10 @@ func (matcher *HaveExistingFieldMatcher) Match(actual interface{}) (success bool return false, err } -func (matcher *HaveExistingFieldMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveExistingFieldMatcher) FailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\nto have field '%s'", format.Object(actual, 1), matcher.Field) } -func (matcher *HaveExistingFieldMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveExistingFieldMatcher) NegatedFailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\nnot to have field '%s'", format.Object(actual, 1), matcher.Field) } diff --git a/matchers/have_field.go b/matchers/have_field.go index 293457e85..d9fbeaf75 100644 --- a/matchers/have_field.go +++ b/matchers/have_field.go @@ -17,7 +17,7 @@ func (e missingFieldError) Error() string { return string(e) } -func extractField(actual interface{}, field string, matchername string) (any, error) { +func extractField(actual any, field string, matchername string) (any, error) { fields := strings.SplitN(field, ".", 2) actualValue := reflect.ValueOf(actual) @@ -68,7 +68,7 @@ func extractField(actual interface{}, field string, matchername string) (any, er type HaveFieldMatcher struct { Field string - Expected interface{} + Expected any } func (matcher *HaveFieldMatcher) expectedMatcher() omegaMatcher { @@ -80,7 +80,7 @@ func (matcher *HaveFieldMatcher) expectedMatcher() omegaMatcher { return expectedMatcher } -func (matcher *HaveFieldMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveFieldMatcher) Match(actual any) (success bool, err error) { extractedField, err := extractField(actual, matcher.Field, "HaveField") if err != nil { return false, err @@ -89,7 +89,7 @@ func (matcher *HaveFieldMatcher) Match(actual interface{}) (success bool, err er return matcher.expectedMatcher().Match(extractedField) } -func (matcher *HaveFieldMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveFieldMatcher) FailureMessage(actual any) (message string) { extractedField, err := extractField(actual, matcher.Field, "HaveField") if err != nil { // this really shouldn't happen @@ -101,7 +101,7 @@ func (matcher *HaveFieldMatcher) FailureMessage(actual interface{}) (message str return message } -func (matcher *HaveFieldMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveFieldMatcher) NegatedFailureMessage(actual any) (message string) { extractedField, err := extractField(actual, matcher.Field, "HaveField") if err != nil { // this really shouldn't happen diff --git a/matchers/have_field_test.go b/matchers/have_field_test.go index 4bc1edffe..8f6b8a305 100644 --- a/matchers/have_field_test.go +++ b/matchers/have_field_test.go @@ -71,7 +71,7 @@ var _ = Describe("HaveField", func() { }) DescribeTable("traversing the struct works", - func(field string, expected interface{}) { + func(field string, expected any) { Ω(book).Should(HaveField(field, expected)) }, Entry("Top-level field with default submatcher", "Title", "Les Miserables"), @@ -84,7 +84,7 @@ var _ = Describe("HaveField", func() { ) DescribeTable("negation works", - func(field string, expected interface{}) { + func(field string, expected any) { Ω(book).ShouldNot(HaveField(field, expected)) }, Entry("Top-level field with default submatcher", "Title", "Les Mis"), @@ -163,7 +163,7 @@ var _ = Describe("HaveField", func() { Describe("receiver lookup", func() { DescribeTable("(pointer) receiver lookup on book pointer works", - func(field string, expected interface{}) { + func(field string, expected any) { Ω(&book).Should(HaveField(field, expected)) }, Entry("non-pointer receiver", "ReceiverTitle()", "Les Miserables"), diff --git a/matchers/have_http_body_matcher.go b/matchers/have_http_body_matcher.go index d14d9e5fc..2d561b9a2 100644 --- a/matchers/have_http_body_matcher.go +++ b/matchers/have_http_body_matcher.go @@ -11,12 +11,12 @@ import ( ) type HaveHTTPBodyMatcher struct { - Expected interface{} - cachedResponse interface{} + Expected any + cachedResponse any cachedBody []byte } -func (matcher *HaveHTTPBodyMatcher) Match(actual interface{}) (bool, error) { +func (matcher *HaveHTTPBodyMatcher) Match(actual any) (bool, error) { body, err := matcher.body(actual) if err != nil { return false, err @@ -34,7 +34,7 @@ func (matcher *HaveHTTPBodyMatcher) Match(actual interface{}) (bool, error) { } } -func (matcher *HaveHTTPBodyMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveHTTPBodyMatcher) FailureMessage(actual any) (message string) { body, err := matcher.body(actual) if err != nil { return fmt.Sprintf("failed to read body: %s", err) @@ -52,7 +52,7 @@ func (matcher *HaveHTTPBodyMatcher) FailureMessage(actual interface{}) (message } } -func (matcher *HaveHTTPBodyMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveHTTPBodyMatcher) NegatedFailureMessage(actual any) (message string) { body, err := matcher.body(actual) if err != nil { return fmt.Sprintf("failed to read body: %s", err) @@ -73,7 +73,7 @@ func (matcher *HaveHTTPBodyMatcher) NegatedFailureMessage(actual interface{}) (m // body returns the body. It is cached because once we read it in Match() // the Reader is closed and it is not readable again in FailureMessage() // or NegatedFailureMessage() -func (matcher *HaveHTTPBodyMatcher) body(actual interface{}) ([]byte, error) { +func (matcher *HaveHTTPBodyMatcher) body(actual any) ([]byte, error) { if matcher.cachedResponse == actual && matcher.cachedBody != nil { return matcher.cachedBody, nil } diff --git a/matchers/have_http_header_with_value_matcher.go b/matchers/have_http_header_with_value_matcher.go index c256f452e..756722659 100644 --- a/matchers/have_http_header_with_value_matcher.go +++ b/matchers/have_http_header_with_value_matcher.go @@ -11,10 +11,10 @@ import ( type HaveHTTPHeaderWithValueMatcher struct { Header string - Value interface{} + Value any } -func (matcher *HaveHTTPHeaderWithValueMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveHTTPHeaderWithValueMatcher) Match(actual any) (success bool, err error) { headerValue, err := matcher.extractHeader(actual) if err != nil { return false, err @@ -28,7 +28,7 @@ func (matcher *HaveHTTPHeaderWithValueMatcher) Match(actual interface{}) (succes return headerMatcher.Match(headerValue) } -func (matcher *HaveHTTPHeaderWithValueMatcher) FailureMessage(actual interface{}) string { +func (matcher *HaveHTTPHeaderWithValueMatcher) FailureMessage(actual any) string { headerValue, err := matcher.extractHeader(actual) if err != nil { panic(err) // protected by Match() @@ -43,7 +43,7 @@ func (matcher *HaveHTTPHeaderWithValueMatcher) FailureMessage(actual interface{} return fmt.Sprintf("HTTP header %q:\n%s", matcher.Header, diff) } -func (matcher *HaveHTTPHeaderWithValueMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveHTTPHeaderWithValueMatcher) NegatedFailureMessage(actual any) (message string) { headerValue, err := matcher.extractHeader(actual) if err != nil { panic(err) // protected by Match() @@ -69,7 +69,7 @@ func (matcher *HaveHTTPHeaderWithValueMatcher) getSubMatcher() (types.GomegaMatc } } -func (matcher *HaveHTTPHeaderWithValueMatcher) extractHeader(actual interface{}) (string, error) { +func (matcher *HaveHTTPHeaderWithValueMatcher) extractHeader(actual any) (string, error) { switch r := actual.(type) { case *http.Response: return r.Header.Get(matcher.Header), nil diff --git a/matchers/have_http_status_matcher.go b/matchers/have_http_status_matcher.go index 0f66e46ec..8b25b3a9f 100644 --- a/matchers/have_http_status_matcher.go +++ b/matchers/have_http_status_matcher.go @@ -12,10 +12,10 @@ import ( ) type HaveHTTPStatusMatcher struct { - Expected []interface{} + Expected []any } -func (matcher *HaveHTTPStatusMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveHTTPStatusMatcher) Match(actual any) (success bool, err error) { var resp *http.Response switch a := actual.(type) { case *http.Response: @@ -48,11 +48,11 @@ func (matcher *HaveHTTPStatusMatcher) Match(actual interface{}) (success bool, e return false, nil } -func (matcher *HaveHTTPStatusMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveHTTPStatusMatcher) FailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\n%s\n%s", formatHttpResponse(actual), "to have HTTP status", matcher.expectedString()) } -func (matcher *HaveHTTPStatusMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveHTTPStatusMatcher) NegatedFailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\n%s\n%s", formatHttpResponse(actual), "not to have HTTP status", matcher.expectedString()) } @@ -64,7 +64,7 @@ func (matcher *HaveHTTPStatusMatcher) expectedString() string { return strings.Join(lines, "\n") } -func formatHttpResponse(input interface{}) string { +func formatHttpResponse(input any) string { var resp *http.Response switch r := input.(type) { case *http.Response: diff --git a/matchers/have_key_matcher.go b/matchers/have_key_matcher.go index b62ee93cb..9e16dcf5d 100644 --- a/matchers/have_key_matcher.go +++ b/matchers/have_key_matcher.go @@ -11,10 +11,10 @@ import ( ) type HaveKeyMatcher struct { - Key interface{} + Key any } -func (matcher *HaveKeyMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveKeyMatcher) Match(actual any) (success bool, err error) { if !isMap(actual) && !miter.IsSeq2(actual) { return false, fmt.Errorf("HaveKey matcher expects a map/iter.Seq2. Got:%s", format.Object(actual, 1)) } @@ -52,7 +52,7 @@ func (matcher *HaveKeyMatcher) Match(actual interface{}) (success bool, err erro return false, nil } -func (matcher *HaveKeyMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveKeyMatcher) FailureMessage(actual any) (message string) { switch matcher.Key.(type) { case omegaMatcher: return format.Message(actual, "to have key matching", matcher.Key) @@ -61,7 +61,7 @@ func (matcher *HaveKeyMatcher) FailureMessage(actual interface{}) (message strin } } -func (matcher *HaveKeyMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveKeyMatcher) NegatedFailureMessage(actual any) (message string) { switch matcher.Key.(type) { case omegaMatcher: return format.Message(actual, "not to have key matching", matcher.Key) diff --git a/matchers/have_key_with_value_matcher.go b/matchers/have_key_with_value_matcher.go index 3d608f63e..1c53f1e56 100644 --- a/matchers/have_key_with_value_matcher.go +++ b/matchers/have_key_with_value_matcher.go @@ -11,11 +11,11 @@ import ( ) type HaveKeyWithValueMatcher struct { - Key interface{} - Value interface{} + Key any + Value any } -func (matcher *HaveKeyWithValueMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveKeyWithValueMatcher) Match(actual any) (success bool, err error) { if !isMap(actual) && !miter.IsSeq2(actual) { return false, fmt.Errorf("HaveKeyWithValue matcher expects a map/iter.Seq2. Got:%s", format.Object(actual, 1)) } @@ -70,7 +70,7 @@ func (matcher *HaveKeyWithValueMatcher) Match(actual interface{}) (success bool, return false, nil } -func (matcher *HaveKeyWithValueMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveKeyWithValueMatcher) FailureMessage(actual any) (message string) { str := "to have {key: value}" if _, ok := matcher.Key.(omegaMatcher); ok { str += " matching" @@ -78,12 +78,12 @@ func (matcher *HaveKeyWithValueMatcher) FailureMessage(actual interface{}) (mess str += " matching" } - expect := make(map[interface{}]interface{}, 1) + expect := make(map[any]any, 1) expect[matcher.Key] = matcher.Value return format.Message(actual, str, expect) } -func (matcher *HaveKeyWithValueMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveKeyWithValueMatcher) NegatedFailureMessage(actual any) (message string) { kStr := "not to have key" if _, ok := matcher.Key.(omegaMatcher); ok { kStr = "not to have key matching" diff --git a/matchers/have_len_matcher.go b/matchers/have_len_matcher.go index ca25713fe..c334d4c0a 100644 --- a/matchers/have_len_matcher.go +++ b/matchers/have_len_matcher.go @@ -10,7 +10,7 @@ type HaveLenMatcher struct { Count int } -func (matcher *HaveLenMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveLenMatcher) Match(actual any) (success bool, err error) { length, ok := lengthOf(actual) if !ok { return false, fmt.Errorf("HaveLen matcher expects a string/array/map/channel/slice/iterator. Got:\n%s", format.Object(actual, 1)) @@ -19,10 +19,10 @@ func (matcher *HaveLenMatcher) Match(actual interface{}) (success bool, err erro return length == matcher.Count, nil } -func (matcher *HaveLenMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveLenMatcher) FailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\nto have length %d", format.Object(actual, 1), matcher.Count) } -func (matcher *HaveLenMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveLenMatcher) NegatedFailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\nnot to have length %d", format.Object(actual, 1), matcher.Count) } diff --git a/matchers/have_occurred_matcher.go b/matchers/have_occurred_matcher.go index 22a1b6730..a240f1a1c 100644 --- a/matchers/have_occurred_matcher.go +++ b/matchers/have_occurred_matcher.go @@ -11,7 +11,7 @@ import ( type HaveOccurredMatcher struct { } -func (matcher *HaveOccurredMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveOccurredMatcher) Match(actual any) (success bool, err error) { // is purely nil? if actual == nil { return false, nil @@ -26,10 +26,10 @@ func (matcher *HaveOccurredMatcher) Match(actual interface{}) (success bool, err return !isNil(actual), nil } -func (matcher *HaveOccurredMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveOccurredMatcher) FailureMessage(actual any) (message string) { return fmt.Sprintf("Expected an error to have occurred. Got:\n%s", format.Object(actual, 1)) } -func (matcher *HaveOccurredMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveOccurredMatcher) NegatedFailureMessage(actual any) (message string) { return fmt.Sprintf("Unexpected error:\n%s\n%s", format.Object(actual, 1), "occurred") } diff --git a/matchers/have_prefix_matcher.go b/matchers/have_prefix_matcher.go index 1d8e80270..7987d41f7 100644 --- a/matchers/have_prefix_matcher.go +++ b/matchers/have_prefix_matcher.go @@ -8,10 +8,10 @@ import ( type HavePrefixMatcher struct { Prefix string - Args []interface{} + Args []any } -func (matcher *HavePrefixMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HavePrefixMatcher) Match(actual any) (success bool, err error) { actualString, ok := toString(actual) if !ok { return false, fmt.Errorf("HavePrefix matcher requires a string or stringer. Got:\n%s", format.Object(actual, 1)) @@ -27,10 +27,10 @@ func (matcher *HavePrefixMatcher) prefix() string { return matcher.Prefix } -func (matcher *HavePrefixMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HavePrefixMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to have prefix", matcher.prefix()) } -func (matcher *HavePrefixMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HavePrefixMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to have prefix", matcher.prefix()) } diff --git a/matchers/have_suffix_matcher.go b/matchers/have_suffix_matcher.go index 40a3526eb..2aa4ceacb 100644 --- a/matchers/have_suffix_matcher.go +++ b/matchers/have_suffix_matcher.go @@ -8,10 +8,10 @@ import ( type HaveSuffixMatcher struct { Suffix string - Args []interface{} + Args []any } -func (matcher *HaveSuffixMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveSuffixMatcher) Match(actual any) (success bool, err error) { actualString, ok := toString(actual) if !ok { return false, fmt.Errorf("HaveSuffix matcher requires a string or stringer. Got:\n%s", format.Object(actual, 1)) @@ -27,10 +27,10 @@ func (matcher *HaveSuffixMatcher) suffix() string { return matcher.Suffix } -func (matcher *HaveSuffixMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveSuffixMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to have suffix", matcher.suffix()) } -func (matcher *HaveSuffixMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveSuffixMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to have suffix", matcher.suffix()) } diff --git a/matchers/have_value.go b/matchers/have_value.go index f67252835..4c39e0db0 100644 --- a/matchers/have_value.go +++ b/matchers/have_value.go @@ -12,10 +12,10 @@ const maxIndirections = 31 type HaveValueMatcher struct { Matcher types.GomegaMatcher // the matcher to apply to the "resolved" actual value. - resolvedActual interface{} // the ("resolved") value. + resolvedActual any // the ("resolved") value. } -func (m *HaveValueMatcher) Match(actual interface{}) (bool, error) { +func (m *HaveValueMatcher) Match(actual any) (bool, error) { val := reflect.ValueOf(actual) for allowedIndirs := maxIndirections; allowedIndirs > 0; allowedIndirs-- { // return an error if value isn't valid. Please note that we cannot @@ -45,10 +45,10 @@ func (m *HaveValueMatcher) Match(actual interface{}) (bool, error) { return false, errors.New(format.Message(actual, "too many indirections")) } -func (m *HaveValueMatcher) FailureMessage(_ interface{}) (message string) { +func (m *HaveValueMatcher) FailureMessage(_ any) (message string) { return m.Matcher.FailureMessage(m.resolvedActual) } -func (m *HaveValueMatcher) NegatedFailureMessage(_ interface{}) (message string) { +func (m *HaveValueMatcher) NegatedFailureMessage(_ any) (message string) { return m.Matcher.NegatedFailureMessage(m.resolvedActual) } diff --git a/matchers/match_error_matcher.go b/matchers/match_error_matcher.go index c539dd389..f9d313772 100644 --- a/matchers/match_error_matcher.go +++ b/matchers/match_error_matcher.go @@ -71,14 +71,14 @@ func (matcher *MatchErrorMatcher) Match(actual any) (success bool, err error) { format.Object(expected, 1)) } -func (matcher *MatchErrorMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *MatchErrorMatcher) FailureMessage(actual any) (message string) { if matcher.isFunc { return format.Message(actual, fmt.Sprintf("to match error function %s", matcher.FuncErrDescription[0])) } return format.Message(actual, "to match error", matcher.Expected) } -func (matcher *MatchErrorMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *MatchErrorMatcher) NegatedFailureMessage(actual any) (message string) { if matcher.isFunc { return format.Message(actual, fmt.Sprintf("not to match error function %s", matcher.FuncErrDescription[0])) } diff --git a/matchers/match_json_matcher.go b/matchers/match_json_matcher.go index f962f139f..331f289ab 100644 --- a/matchers/match_json_matcher.go +++ b/matchers/match_json_matcher.go @@ -9,18 +9,18 @@ import ( ) type MatchJSONMatcher struct { - JSONToMatch interface{} - firstFailurePath []interface{} + JSONToMatch any + firstFailurePath []any } -func (matcher *MatchJSONMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *MatchJSONMatcher) Match(actual any) (success bool, err error) { actualString, expectedString, err := matcher.prettyPrint(actual) if err != nil { return false, err } - var aval interface{} - var eval interface{} + var aval any + var eval any // this is guarded by prettyPrint json.Unmarshal([]byte(actualString), &aval) @@ -30,17 +30,17 @@ func (matcher *MatchJSONMatcher) Match(actual interface{}) (success bool, err er return equal, nil } -func (matcher *MatchJSONMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *MatchJSONMatcher) FailureMessage(actual any) (message string) { actualString, expectedString, _ := matcher.prettyPrint(actual) return formattedMessage(format.Message(actualString, "to match JSON of", expectedString), matcher.firstFailurePath) } -func (matcher *MatchJSONMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *MatchJSONMatcher) NegatedFailureMessage(actual any) (message string) { actualString, expectedString, _ := matcher.prettyPrint(actual) return formattedMessage(format.Message(actualString, "not to match JSON of", expectedString), matcher.firstFailurePath) } -func (matcher *MatchJSONMatcher) prettyPrint(actual interface{}) (actualFormatted, expectedFormatted string, err error) { +func (matcher *MatchJSONMatcher) prettyPrint(actual any) (actualFormatted, expectedFormatted string, err error) { actualString, ok := toString(actual) if !ok { return "", "", fmt.Errorf("MatchJSONMatcher matcher requires a string, stringer, or []byte. Got actual:\n%s", format.Object(actual, 1)) diff --git a/matchers/match_regexp_matcher.go b/matchers/match_regexp_matcher.go index adac5db6b..779be683e 100644 --- a/matchers/match_regexp_matcher.go +++ b/matchers/match_regexp_matcher.go @@ -9,10 +9,10 @@ import ( type MatchRegexpMatcher struct { Regexp string - Args []interface{} + Args []any } -func (matcher *MatchRegexpMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *MatchRegexpMatcher) Match(actual any) (success bool, err error) { actualString, ok := toString(actual) if !ok { return false, fmt.Errorf("RegExp matcher requires a string or stringer.\nGot:%s", format.Object(actual, 1)) @@ -26,11 +26,11 @@ func (matcher *MatchRegexpMatcher) Match(actual interface{}) (success bool, err return match, nil } -func (matcher *MatchRegexpMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *MatchRegexpMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to match regular expression", matcher.regexp()) } -func (matcher *MatchRegexpMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *MatchRegexpMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to match regular expression", matcher.regexp()) } diff --git a/matchers/match_xml_matcher.go b/matchers/match_xml_matcher.go index 5c815f5af..f7dcaf6fd 100644 --- a/matchers/match_xml_matcher.go +++ b/matchers/match_xml_matcher.go @@ -15,10 +15,10 @@ import ( ) type MatchXMLMatcher struct { - XMLToMatch interface{} + XMLToMatch any } -func (matcher *MatchXMLMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *MatchXMLMatcher) Match(actual any) (success bool, err error) { actualString, expectedString, err := matcher.formattedPrint(actual) if err != nil { return false, err @@ -37,17 +37,17 @@ func (matcher *MatchXMLMatcher) Match(actual interface{}) (success bool, err err return reflect.DeepEqual(aval, eval), nil } -func (matcher *MatchXMLMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *MatchXMLMatcher) FailureMessage(actual any) (message string) { actualString, expectedString, _ := matcher.formattedPrint(actual) return fmt.Sprintf("Expected\n%s\nto match XML of\n%s", actualString, expectedString) } -func (matcher *MatchXMLMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *MatchXMLMatcher) NegatedFailureMessage(actual any) (message string) { actualString, expectedString, _ := matcher.formattedPrint(actual) return fmt.Sprintf("Expected\n%s\nnot to match XML of\n%s", actualString, expectedString) } -func (matcher *MatchXMLMatcher) formattedPrint(actual interface{}) (actualString, expectedString string, err error) { +func (matcher *MatchXMLMatcher) formattedPrint(actual any) (actualString, expectedString string, err error) { var ok bool actualString, ok = toString(actual) if !ok { diff --git a/matchers/match_yaml_matcher.go b/matchers/match_yaml_matcher.go index 2cb6b47db..95057c26c 100644 --- a/matchers/match_yaml_matcher.go +++ b/matchers/match_yaml_matcher.go @@ -9,18 +9,18 @@ import ( ) type MatchYAMLMatcher struct { - YAMLToMatch interface{} - firstFailurePath []interface{} + YAMLToMatch any + firstFailurePath []any } -func (matcher *MatchYAMLMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *MatchYAMLMatcher) Match(actual any) (success bool, err error) { actualString, expectedString, err := matcher.toStrings(actual) if err != nil { return false, err } - var aval interface{} - var eval interface{} + var aval any + var eval any if err := yaml.Unmarshal([]byte(actualString), &aval); err != nil { return false, fmt.Errorf("Actual '%s' should be valid YAML, but it is not.\nUnderlying error:%s", actualString, err) @@ -34,23 +34,23 @@ func (matcher *MatchYAMLMatcher) Match(actual interface{}) (success bool, err er return equal, nil } -func (matcher *MatchYAMLMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *MatchYAMLMatcher) FailureMessage(actual any) (message string) { actualString, expectedString, _ := matcher.toNormalisedStrings(actual) return formattedMessage(format.Message(actualString, "to match YAML of", expectedString), matcher.firstFailurePath) } -func (matcher *MatchYAMLMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *MatchYAMLMatcher) NegatedFailureMessage(actual any) (message string) { actualString, expectedString, _ := matcher.toNormalisedStrings(actual) return formattedMessage(format.Message(actualString, "not to match YAML of", expectedString), matcher.firstFailurePath) } -func (matcher *MatchYAMLMatcher) toNormalisedStrings(actual interface{}) (actualFormatted, expectedFormatted string, err error) { +func (matcher *MatchYAMLMatcher) toNormalisedStrings(actual any) (actualFormatted, expectedFormatted string, err error) { actualString, expectedString, err := matcher.toStrings(actual) return normalise(actualString), normalise(expectedString), err } func normalise(input string) string { - var val interface{} + var val any err := yaml.Unmarshal([]byte(input), &val) if err != nil { panic(err) // unreachable since Match already calls Unmarshal @@ -62,7 +62,7 @@ func normalise(input string) string { return strings.TrimSpace(string(output)) } -func (matcher *MatchYAMLMatcher) toStrings(actual interface{}) (actualFormatted, expectedFormatted string, err error) { +func (matcher *MatchYAMLMatcher) toStrings(actual any) (actualFormatted, expectedFormatted string, err error) { actualString, ok := toString(actual) if !ok { return "", "", fmt.Errorf("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got actual:\n%s", format.Object(actual, 1)) diff --git a/matchers/not.go b/matchers/not.go index 78b71910d..c598b7899 100644 --- a/matchers/not.go +++ b/matchers/not.go @@ -8,7 +8,7 @@ type NotMatcher struct { Matcher types.GomegaMatcher } -func (m *NotMatcher) Match(actual interface{}) (bool, error) { +func (m *NotMatcher) Match(actual any) (bool, error) { success, err := m.Matcher.Match(actual) if err != nil { return false, err @@ -16,14 +16,14 @@ func (m *NotMatcher) Match(actual interface{}) (bool, error) { return !success, nil } -func (m *NotMatcher) FailureMessage(actual interface{}) (message string) { +func (m *NotMatcher) FailureMessage(actual any) (message string) { return m.Matcher.NegatedFailureMessage(actual) // works beautifully } -func (m *NotMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (m *NotMatcher) NegatedFailureMessage(actual any) (message string) { return m.Matcher.FailureMessage(actual) // works beautifully } -func (m *NotMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { +func (m *NotMatcher) MatchMayChangeInTheFuture(actual any) bool { return types.MatchMayChangeInTheFuture(m.Matcher, actual) // just return m.Matcher's value } diff --git a/matchers/or.go b/matchers/or.go index 841ae26ab..6578404b0 100644 --- a/matchers/or.go +++ b/matchers/or.go @@ -14,7 +14,7 @@ type OrMatcher struct { firstSuccessfulMatcher types.GomegaMatcher } -func (m *OrMatcher) Match(actual interface{}) (success bool, err error) { +func (m *OrMatcher) Match(actual any) (success bool, err error) { m.firstSuccessfulMatcher = nil for _, matcher := range m.Matchers { success, err := matcher.Match(actual) @@ -29,16 +29,16 @@ func (m *OrMatcher) Match(actual interface{}) (success bool, err error) { return false, nil } -func (m *OrMatcher) FailureMessage(actual interface{}) (message string) { +func (m *OrMatcher) FailureMessage(actual any) (message string) { // not the most beautiful list of matchers, but not bad either... return format.Message(actual, fmt.Sprintf("To satisfy at least one of these matchers: %s", m.Matchers)) } -func (m *OrMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (m *OrMatcher) NegatedFailureMessage(actual any) (message string) { return m.firstSuccessfulMatcher.NegatedFailureMessage(actual) } -func (m *OrMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { +func (m *OrMatcher) MatchMayChangeInTheFuture(actual any) bool { /* Example with 3 matchers: A, B, C diff --git a/matchers/panic_matcher.go b/matchers/panic_matcher.go index adc8cee63..8be5a7ccf 100644 --- a/matchers/panic_matcher.go +++ b/matchers/panic_matcher.go @@ -8,11 +8,11 @@ import ( ) type PanicMatcher struct { - Expected interface{} - object interface{} + Expected any + object any } -func (matcher *PanicMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *PanicMatcher) Match(actual any) (success bool, err error) { if actual == nil { return false, fmt.Errorf("PanicMatcher expects a non-nil actual.") } @@ -52,7 +52,7 @@ func (matcher *PanicMatcher) Match(actual interface{}) (success bool, err error) return } -func (matcher *PanicMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *PanicMatcher) FailureMessage(actual any) (message string) { if matcher.Expected == nil { // We wanted any panic to occur, but none did. return format.Message(actual, "to panic") @@ -91,7 +91,7 @@ func (matcher *PanicMatcher) FailureMessage(actual interface{}) (message string) } } -func (matcher *PanicMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *PanicMatcher) NegatedFailureMessage(actual any) (message string) { if matcher.Expected == nil { // We didn't want any panic to occur, but one did. return format.Message(actual, fmt.Sprintf("not to panic, but panicked with\n%s", format.Object(matcher.object, 1))) diff --git a/matchers/receive_matcher.go b/matchers/receive_matcher.go index 948164eaf..1d9f61d63 100644 --- a/matchers/receive_matcher.go +++ b/matchers/receive_matcher.go @@ -11,12 +11,12 @@ import ( ) type ReceiveMatcher struct { - Args []interface{} + Args []any receivedValue reflect.Value channelClosed bool } -func (matcher *ReceiveMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *ReceiveMatcher) Match(actual any) (success bool, err error) { if !isChan(actual) { return false, fmt.Errorf("ReceiveMatcher expects a channel. Got:\n%s", format.Object(actual, 1)) } @@ -30,7 +30,7 @@ func (matcher *ReceiveMatcher) Match(actual interface{}) (success bool, err erro var subMatcher omegaMatcher var hasSubMatcher bool - var resultReference interface{} + var resultReference any // Valid arg formats are as follows, always with optional POINTER before // optional MATCHER: @@ -115,8 +115,8 @@ func (matcher *ReceiveMatcher) Match(actual interface{}) (success bool, err erro return false, nil } -func (matcher *ReceiveMatcher) FailureMessage(actual interface{}) (message string) { - var matcherArg interface{} +func (matcher *ReceiveMatcher) FailureMessage(actual any) (message string) { + var matcherArg any if len(matcher.Args) > 0 { matcherArg = matcher.Args[len(matcher.Args)-1] } @@ -136,8 +136,8 @@ func (matcher *ReceiveMatcher) FailureMessage(actual interface{}) (message strin return format.Message(actual, "to receive something."+closedAddendum) } -func (matcher *ReceiveMatcher) NegatedFailureMessage(actual interface{}) (message string) { - var matcherArg interface{} +func (matcher *ReceiveMatcher) NegatedFailureMessage(actual any) (message string) { + var matcherArg any if len(matcher.Args) > 0 { matcherArg = matcher.Args[len(matcher.Args)-1] } @@ -157,7 +157,7 @@ func (matcher *ReceiveMatcher) NegatedFailureMessage(actual interface{}) (messag return format.Message(actual, "not to receive anything."+closedAddendum) } -func (matcher *ReceiveMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { +func (matcher *ReceiveMatcher) MatchMayChangeInTheFuture(actual any) bool { if !isChan(actual) { return false } diff --git a/matchers/receive_matcher_test.go b/matchers/receive_matcher_test.go index 7f530d386..6a4daa649 100644 --- a/matchers/receive_matcher_test.go +++ b/matchers/receive_matcher_test.go @@ -61,7 +61,7 @@ var _ = Describe("ReceiveMatcher", func() { channel <- true - success, err := (&ReceiveMatcher{Args: []interface{}{ + success, err := (&ReceiveMatcher{Args: []any{ &actual, Equal(true), 42, @@ -78,7 +78,7 @@ var _ = Describe("ReceiveMatcher", func() { channel <- true - success, err := (&ReceiveMatcher{Args: []interface{}{ + success, err := (&ReceiveMatcher{Args: []any{ Equal(true), &actual, }}).Match(channel) @@ -167,12 +167,12 @@ var _ = Describe("ReceiveMatcher", func() { var incorrectType bool - success, err := (&ReceiveMatcher{Args: []interface{}{&incorrectType}}).Match(channel) + success, err := (&ReceiveMatcher{Args: []any{&incorrectType}}).Match(channel) Expect(success).Should(BeFalse()) Expect(err).Should(HaveOccurred()) var notAPointer int - success, err = (&ReceiveMatcher{Args: []interface{}{notAPointer}}).Match(channel) + success, err = (&ReceiveMatcher{Args: []any{notAPointer}}).Match(channel) Expect(success).Should(BeFalse()) Expect(err).Should(HaveOccurred()) }) @@ -225,7 +225,7 @@ var _ = Describe("ReceiveMatcher", func() { It("should error", func() { channel := make(chan int, 1) channel <- 3 - success, err := (&ReceiveMatcher{Args: []interface{}{ContainSubstring("three")}}).Match(channel) + success, err := (&ReceiveMatcher{Args: []any{ContainSubstring("three")}}).Match(channel) Expect(success).Should(BeFalse()) Expect(err).Should(HaveOccurred()) }) @@ -234,7 +234,7 @@ var _ = Describe("ReceiveMatcher", func() { Context("if nothing is received", func() { It("should fail", func() { channel := make(chan int, 1) - success, err := (&ReceiveMatcher{Args: []interface{}{Equal(1)}}).Match(channel) + success, err := (&ReceiveMatcher{Args: []any{Equal(1)}}).Match(channel) Expect(success).Should(BeFalse()) Expect(err).ShouldNot(HaveOccurred()) }) diff --git a/matchers/satisfy_matcher.go b/matchers/satisfy_matcher.go index ec68fe8b6..2adc4825a 100644 --- a/matchers/satisfy_matcher.go +++ b/matchers/satisfy_matcher.go @@ -8,13 +8,13 @@ import ( ) type SatisfyMatcher struct { - Predicate interface{} + Predicate any // cached type predicateArgType reflect.Type } -func NewSatisfyMatcher(predicate interface{}) *SatisfyMatcher { +func NewSatisfyMatcher(predicate any) *SatisfyMatcher { if predicate == nil { panic("predicate cannot be nil") } @@ -35,7 +35,7 @@ func NewSatisfyMatcher(predicate interface{}) *SatisfyMatcher { } } -func (m *SatisfyMatcher) Match(actual interface{}) (success bool, err error) { +func (m *SatisfyMatcher) Match(actual any) (success bool, err error) { // prepare a parameter to pass to the predicate var param reflect.Value if actual != nil && reflect.TypeOf(actual).AssignableTo(m.predicateArgType) { @@ -57,10 +57,10 @@ func (m *SatisfyMatcher) Match(actual interface{}) (success bool, err error) { return result[0].Bool(), nil } -func (m *SatisfyMatcher) FailureMessage(actual interface{}) (message string) { +func (m *SatisfyMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to satisfy predicate", m.Predicate) } -func (m *SatisfyMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (m *SatisfyMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "to not satisfy predicate", m.Predicate) } diff --git a/matchers/satisfy_matcher_test.go b/matchers/satisfy_matcher_test.go index f49515a46..ec511609e 100644 --- a/matchers/satisfy_matcher_test.go +++ b/matchers/satisfy_matcher_test.go @@ -12,7 +12,7 @@ var _ = Describe("SatisfyMatcher", func() { var isEven = func(x int) bool { return x%2 == 0 } Context("Panic if predicate is invalid", func() { - panicsWithPredicate := func(predicate interface{}) { + panicsWithPredicate := func(predicate any) { Expect(func() { Satisfy(predicate) }).WithOffset(1).To(Panic()) } It("nil", func() { diff --git a/matchers/semi_structured_data_support.go b/matchers/semi_structured_data_support.go index 1369c1e87..30dd58f4a 100644 --- a/matchers/semi_structured_data_support.go +++ b/matchers/semi_structured_data_support.go @@ -8,7 +8,7 @@ import ( "strings" ) -func formattedMessage(comparisonMessage string, failurePath []interface{}) string { +func formattedMessage(comparisonMessage string, failurePath []any) string { var diffMessage string if len(failurePath) == 0 { diffMessage = "" @@ -18,7 +18,7 @@ func formattedMessage(comparisonMessage string, failurePath []interface{}) strin return fmt.Sprintf("%s%s", comparisonMessage, diffMessage) } -func formattedFailurePath(failurePath []interface{}) string { +func formattedFailurePath(failurePath []any) string { formattedPaths := []string{} for i := len(failurePath) - 1; i >= 0; i-- { switch p := failurePath[i].(type) { @@ -34,33 +34,33 @@ func formattedFailurePath(failurePath []interface{}) string { return strings.Join(formattedPaths, "") } -func deepEqual(a interface{}, b interface{}) (bool, []interface{}) { - var errorPath []interface{} +func deepEqual(a any, b any) (bool, []any) { + var errorPath []any if reflect.TypeOf(a) != reflect.TypeOf(b) { return false, errorPath } switch a.(type) { - case []interface{}: - if len(a.([]interface{})) != len(b.([]interface{})) { + case []any: + if len(a.([]any)) != len(b.([]any)) { return false, errorPath } - for i, v := range a.([]interface{}) { - elementEqual, keyPath := deepEqual(v, b.([]interface{})[i]) + for i, v := range a.([]any) { + elementEqual, keyPath := deepEqual(v, b.([]any)[i]) if !elementEqual { return false, append(keyPath, i) } } return true, errorPath - case map[interface{}]interface{}: - if len(a.(map[interface{}]interface{})) != len(b.(map[interface{}]interface{})) { + case map[any]any: + if len(a.(map[any]any)) != len(b.(map[any]any)) { return false, errorPath } - for k, v1 := range a.(map[interface{}]interface{}) { - v2, ok := b.(map[interface{}]interface{})[k] + for k, v1 := range a.(map[any]any) { + v2, ok := b.(map[any]any)[k] if !ok { return false, errorPath } @@ -71,13 +71,13 @@ func deepEqual(a interface{}, b interface{}) (bool, []interface{}) { } return true, errorPath - case map[string]interface{}: - if len(a.(map[string]interface{})) != len(b.(map[string]interface{})) { + case map[string]any: + if len(a.(map[string]any)) != len(b.(map[string]any)) { return false, errorPath } - for k, v1 := range a.(map[string]interface{}) { - v2, ok := b.(map[string]interface{})[k] + for k, v1 := range a.(map[string]any) { + v2, ok := b.(map[string]any)[k] if !ok { return false, errorPath } diff --git a/matchers/succeed_matcher.go b/matchers/succeed_matcher.go index 327350f7b..f0b2c4aa6 100644 --- a/matchers/succeed_matcher.go +++ b/matchers/succeed_matcher.go @@ -14,7 +14,7 @@ type formattedGomegaError interface { type SucceedMatcher struct { } -func (matcher *SucceedMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *SucceedMatcher) Match(actual any) (success bool, err error) { // is purely nil? if actual == nil { return true, nil @@ -29,7 +29,7 @@ func (matcher *SucceedMatcher) Match(actual interface{}) (success bool, err erro return isNil(actual), nil } -func (matcher *SucceedMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *SucceedMatcher) FailureMessage(actual any) (message string) { var fgErr formattedGomegaError if errors.As(actual.(error), &fgErr) { return fgErr.FormattedGomegaError() @@ -37,6 +37,6 @@ func (matcher *SucceedMatcher) FailureMessage(actual interface{}) (message strin return fmt.Sprintf("Expected success, but got an error:\n%s", format.Object(actual, 1)) } -func (matcher *SucceedMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *SucceedMatcher) NegatedFailureMessage(actual any) (message string) { return "Expected failure, but got no error." } diff --git a/matchers/support/goraph/bipartitegraph/bipartitegraph.go b/matchers/support/goraph/bipartitegraph/bipartitegraph.go index 830e30827..0d78779d4 100644 --- a/matchers/support/goraph/bipartitegraph/bipartitegraph.go +++ b/matchers/support/goraph/bipartitegraph/bipartitegraph.go @@ -11,7 +11,7 @@ type BipartiteGraph struct { Edges EdgeSet } -func NewBipartiteGraph(leftValues, rightValues []interface{}, neighbours func(interface{}, interface{}) (bool, error)) (*BipartiteGraph, error) { +func NewBipartiteGraph(leftValues, rightValues []any, neighbours func(any, any) (bool, error)) (*BipartiteGraph, error) { left := NodeOrderedSet{} for i, v := range leftValues { left = append(left, Node{ID: i, Value: v}) @@ -41,7 +41,7 @@ func NewBipartiteGraph(leftValues, rightValues []interface{}, neighbours func(in // FreeLeftRight returns left node values and right node values // of the BipartiteGraph's nodes which are not part of the given edges. -func (bg *BipartiteGraph) FreeLeftRight(edges EdgeSet) (leftValues, rightValues []interface{}) { +func (bg *BipartiteGraph) FreeLeftRight(edges EdgeSet) (leftValues, rightValues []any) { for _, node := range bg.Left { if edges.Free(node) { leftValues = append(leftValues, node.Value) diff --git a/matchers/support/goraph/bipartitegraph/bipartitegraph_test.go b/matchers/support/goraph/bipartitegraph/bipartitegraph_test.go index d93438a57..dd8266048 100644 --- a/matchers/support/goraph/bipartitegraph/bipartitegraph_test.go +++ b/matchers/support/goraph/bipartitegraph/bipartitegraph_test.go @@ -13,11 +13,11 @@ import ( var _ = Describe("Bipartitegraph", func() { Context("tiny graphs", func() { var ( - empty, _ = NewBipartiteGraph([]interface{}{}, []interface{}{}, func(x, y interface{}) (bool, error) { return true, nil }) - oneLeft, _ = NewBipartiteGraph([]interface{}{1}, []interface{}{}, func(x, y interface{}) (bool, error) { return true, nil }) - oneRight, _ = NewBipartiteGraph([]interface{}{}, []interface{}{1}, func(x, y interface{}) (bool, error) { return true, nil }) - twoSeparate, _ = NewBipartiteGraph([]interface{}{1}, []interface{}{1}, func(x, y interface{}) (bool, error) { return false, nil }) - twoConnected, _ = NewBipartiteGraph([]interface{}{1}, []interface{}{1}, func(x, y interface{}) (bool, error) { return true, nil }) + empty, _ = NewBipartiteGraph([]any{}, []any{}, func(x, y any) (bool, error) { return true, nil }) + oneLeft, _ = NewBipartiteGraph([]any{1}, []any{}, func(x, y any) (bool, error) { return true, nil }) + oneRight, _ = NewBipartiteGraph([]any{}, []any{1}, func(x, y any) (bool, error) { return true, nil }) + twoSeparate, _ = NewBipartiteGraph([]any{1}, []any{1}, func(x, y any) (bool, error) { return false, nil }) + twoConnected, _ = NewBipartiteGraph([]any{1}, []any{1}, func(x, y any) (bool, error) { return true, nil }) ) It("Computes the correct largest matching", func() { @@ -32,7 +32,7 @@ var _ = Describe("Bipartitegraph", func() { Context("small yet complex graphs", func() { var ( - neighbours = func(x, y interface{}) (bool, error) { + neighbours = func(x, y any) (bool, error) { switch x.(string) + y.(string) { case "aw", "bw", "bx", "cy", "cz", "dx", "ew": return true, nil @@ -41,8 +41,8 @@ var _ = Describe("Bipartitegraph", func() { } } graph, _ = NewBipartiteGraph( - []interface{}{"a", "b", "c", "d", "e"}, - []interface{}{"w", "x", "y", "z"}, + []any{"a", "b", "c", "d", "e"}, + []any{"w", "x", "y", "z"}, neighbours, ) ) @@ -73,12 +73,12 @@ var _ = Describe("Bipartitegraph", func() { When("node values are unhashable types", func() { var ( - neighbours = func(x, y interface{}) (bool, error) { + neighbours = func(x, y any) (bool, error) { return reflect.DeepEqual(x, y), nil } graph, _ = NewBipartiteGraph( - []interface{}{[]int{1, 2}, []int{3, 4}}, - []interface{}{[]int{1, 2}}, + []any{[]int{1, 2}, []int{3, 4}}, + []any{[]int{1, 2}}, neighbours, ) ) @@ -95,10 +95,10 @@ var _ = Describe("Bipartitegraph", func() { Context("large yet simple graphs", func() { var ( - half = make([]interface{}, 100) - discreteNeighbours = func(x, y interface{}) (bool, error) { return false, nil } - completeNeighbours = func(x, y interface{}) (bool, error) { return true, nil } - bijectionNeighbours = func(x, y interface{}) (bool, error) { + half = make([]any, 100) + discreteNeighbours = func(x, y any) (bool, error) { return false, nil } + completeNeighbours = func(x, y any) (bool, error) { return true, nil } + bijectionNeighbours = func(x, y any) (bool, error) { return x.(int) == y.(int), nil } discrete, complete, bijection *BipartiteGraph @@ -122,8 +122,8 @@ var _ = Describe("Bipartitegraph", func() { Context("large graphs that are unpleasant for the algorithm", func() { var ( - half = make([]interface{}, 100) - neighbours1 = func(x, y interface{}) (bool, error) { + half = make([]any, 100) + neighbours1 = func(x, y any) (bool, error) { if x.(int) < 33 { return x.(int) == y.(int), nil } else if x.(int) < 66 { @@ -132,7 +132,7 @@ var _ = Describe("Bipartitegraph", func() { return false, nil } } - neighbours2 = func(x, y interface{}) (bool, error) { + neighbours2 = func(x, y any) (bool, error) { if x.(int) == 50 { return true, nil } else if x.(int) < 90 { @@ -141,7 +141,7 @@ var _ = Describe("Bipartitegraph", func() { return false, nil } } - neighbours3 = func(x, y interface{}) (bool, error) { + neighbours3 = func(x, y any) (bool, error) { if y.(int) < x.(int)-20 { return true, nil } else { @@ -185,11 +185,11 @@ var _ = Describe("Bipartitegraph", func() { "5A": true, } - edgesFunc := func(l, r interface{}) (bool, error) { + edgesFunc := func(l, r any) (bool, error) { return knownEdges[fmt.Sprintf("%v%v", l, r)], nil } - vertices := []interface{}{"1", "2", "3", "4", "5", "A", "B", "C", "D", "E"} + vertices := []any{"1", "2", "3", "4", "5", "A", "B", "C", "D", "E"} leftPart := vertices[:5] rightPart := vertices[5:] diff --git a/matchers/support/goraph/node/node.go b/matchers/support/goraph/node/node.go index cd597a2f2..66d3578d5 100644 --- a/matchers/support/goraph/node/node.go +++ b/matchers/support/goraph/node/node.go @@ -2,7 +2,7 @@ package node type Node struct { ID int - Value interface{} + Value any } type NodeOrderedSet []Node diff --git a/matchers/type_support.go b/matchers/type_support.go index b9440ac7a..d020dedc3 100644 --- a/matchers/type_support.go +++ b/matchers/type_support.go @@ -20,16 +20,16 @@ import ( ) type omegaMatcher interface { - Match(actual interface{}) (success bool, err error) - FailureMessage(actual interface{}) (message string) - NegatedFailureMessage(actual interface{}) (message string) + Match(actual any) (success bool, err error) + FailureMessage(actual any) (message string) + NegatedFailureMessage(actual any) (message string) } -func isBool(a interface{}) bool { +func isBool(a any) bool { return reflect.TypeOf(a).Kind() == reflect.Bool } -func isNumber(a interface{}) bool { +func isNumber(a any) bool { if a == nil { return false } @@ -37,22 +37,22 @@ func isNumber(a interface{}) bool { return reflect.Int <= kind && kind <= reflect.Float64 } -func isInteger(a interface{}) bool { +func isInteger(a any) bool { kind := reflect.TypeOf(a).Kind() return reflect.Int <= kind && kind <= reflect.Int64 } -func isUnsignedInteger(a interface{}) bool { +func isUnsignedInteger(a any) bool { kind := reflect.TypeOf(a).Kind() return reflect.Uint <= kind && kind <= reflect.Uint64 } -func isFloat(a interface{}) bool { +func isFloat(a any) bool { kind := reflect.TypeOf(a).Kind() return reflect.Float32 <= kind && kind <= reflect.Float64 } -func toInteger(a interface{}) int64 { +func toInteger(a any) int64 { if isInteger(a) { return reflect.ValueOf(a).Int() } else if isUnsignedInteger(a) { @@ -63,7 +63,7 @@ func toInteger(a interface{}) int64 { panic(fmt.Sprintf("Expected a number! Got <%T> %#v", a, a)) } -func toUnsignedInteger(a interface{}) uint64 { +func toUnsignedInteger(a any) uint64 { if isInteger(a) { return uint64(reflect.ValueOf(a).Int()) } else if isUnsignedInteger(a) { @@ -74,7 +74,7 @@ func toUnsignedInteger(a interface{}) uint64 { panic(fmt.Sprintf("Expected a number! Got <%T> %#v", a, a)) } -func toFloat(a interface{}) float64 { +func toFloat(a any) float64 { if isInteger(a) { return float64(reflect.ValueOf(a).Int()) } else if isUnsignedInteger(a) { @@ -85,26 +85,26 @@ func toFloat(a interface{}) float64 { panic(fmt.Sprintf("Expected a number! Got <%T> %#v", a, a)) } -func isError(a interface{}) bool { +func isError(a any) bool { _, ok := a.(error) return ok } -func isChan(a interface{}) bool { +func isChan(a any) bool { if isNil(a) { return false } return reflect.TypeOf(a).Kind() == reflect.Chan } -func isMap(a interface{}) bool { +func isMap(a any) bool { if a == nil { return false } return reflect.TypeOf(a).Kind() == reflect.Map } -func isArrayOrSlice(a interface{}) bool { +func isArrayOrSlice(a any) bool { if a == nil { return false } @@ -116,14 +116,14 @@ func isArrayOrSlice(a interface{}) bool { } } -func isString(a interface{}) bool { +func isString(a any) bool { if a == nil { return false } return reflect.TypeOf(a).Kind() == reflect.String } -func toString(a interface{}) (string, bool) { +func toString(a any) (string, bool) { aString, isString := a.(string) if isString { return aString, true @@ -147,7 +147,7 @@ func toString(a interface{}) (string, bool) { return "", false } -func lengthOf(a interface{}) (int, bool) { +func lengthOf(a any) (int, bool) { if a == nil { return 0, false } @@ -169,7 +169,7 @@ func lengthOf(a interface{}) (int, bool) { return 0, false } } -func capOf(a interface{}) (int, bool) { +func capOf(a any) (int, bool) { if a == nil { return 0, false } @@ -181,7 +181,7 @@ func capOf(a interface{}) (int, bool) { } } -func isNil(a interface{}) bool { +func isNil(a any) bool { if a == nil { return true } diff --git a/matchers/with_transform.go b/matchers/with_transform.go index 6f743b1b3..6231c3b47 100644 --- a/matchers/with_transform.go +++ b/matchers/with_transform.go @@ -9,20 +9,20 @@ import ( type WithTransformMatcher struct { // input - Transform interface{} // must be a function of one parameter that returns one value and an optional error + Transform any // must be a function of one parameter that returns one value and an optional error Matcher types.GomegaMatcher // cached value transformArgType reflect.Type // state - transformedValue interface{} + transformedValue any } // reflect.Type for error var errorT = reflect.TypeOf((*error)(nil)).Elem() -func NewWithTransformMatcher(transform interface{}, matcher types.GomegaMatcher) *WithTransformMatcher { +func NewWithTransformMatcher(transform any, matcher types.GomegaMatcher) *WithTransformMatcher { if transform == nil { panic("transform function cannot be nil") } @@ -43,7 +43,7 @@ func NewWithTransformMatcher(transform interface{}, matcher types.GomegaMatcher) } } -func (m *WithTransformMatcher) Match(actual interface{}) (bool, error) { +func (m *WithTransformMatcher) Match(actual any) (bool, error) { // prepare a parameter to pass to the Transform function var param reflect.Value if actual != nil && reflect.TypeOf(actual).AssignableTo(m.transformArgType) { @@ -72,15 +72,15 @@ func (m *WithTransformMatcher) Match(actual interface{}) (bool, error) { return m.Matcher.Match(m.transformedValue) } -func (m *WithTransformMatcher) FailureMessage(_ interface{}) (message string) { +func (m *WithTransformMatcher) FailureMessage(_ any) (message string) { return m.Matcher.FailureMessage(m.transformedValue) } -func (m *WithTransformMatcher) NegatedFailureMessage(_ interface{}) (message string) { +func (m *WithTransformMatcher) NegatedFailureMessage(_ any) (message string) { return m.Matcher.NegatedFailureMessage(m.transformedValue) } -func (m *WithTransformMatcher) MatchMayChangeInTheFuture(_ interface{}) bool { +func (m *WithTransformMatcher) MatchMayChangeInTheFuture(_ any) bool { // TODO: Maybe this should always just return true? (Only an issue for non-deterministic transformers.) // // Querying the next matcher is fine if the transformer always will return the same value. diff --git a/matchers/with_transform_test.go b/matchers/with_transform_test.go index 7c3c8fb24..861bdaee2 100644 --- a/matchers/with_transform_test.go +++ b/matchers/with_transform_test.go @@ -13,7 +13,7 @@ var _ = Describe("WithTransformMatcher", func() { var plus1 = func(i int) int { return i + 1 } Context("Panic if transform function invalid", func() { - panicsWithTransformer := func(transform interface{}) { + panicsWithTransformer := func(transform any) { Expect(func() { WithTransform(transform, nil) }).WithOffset(1).To(Panic()) } It("nil", func() { @@ -37,7 +37,7 @@ var _ = Describe("WithTransformMatcher", func() { }) Context("Invalid number of return values, but correct number of arguments", func() { It("Two return values, but second return value not an error", func() { - panicsWithTransformer(func(interface{}) (int, int) { return 5, 6 }) + panicsWithTransformer(func(any) (int, int) { return 5, 6 }) }) }) }) diff --git a/types/types.go b/types/types.go index 476863ec7..da39b3611 100644 --- a/types/types.go +++ b/types/types.go @@ -10,20 +10,20 @@ type GomegaFailHandler func(message string, callerSkip ...int) // A simple *testing.T interface wrapper type GomegaTestingT interface { Helper() - Fatalf(format string, args ...interface{}) + Fatalf(format string, args ...any) } // Gomega represents an object that can perform synchronous and asynchronous assertions with Gomega matchers type Gomega interface { - Ω(actual interface{}, extra ...interface{}) Assertion - Expect(actual interface{}, extra ...interface{}) Assertion - ExpectWithOffset(offset int, actual interface{}, extra ...interface{}) Assertion + Ω(actual any, extra ...any) Assertion + Expect(actual any, extra ...any) Assertion + ExpectWithOffset(offset int, actual any, extra ...any) Assertion - Eventually(actualOrCtx interface{}, args ...interface{}) AsyncAssertion - EventuallyWithOffset(offset int, actualOrCtx interface{}, args ...interface{}) AsyncAssertion + Eventually(actualOrCtx any, args ...any) AsyncAssertion + EventuallyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertion - Consistently(actualOrCtx interface{}, args ...interface{}) AsyncAssertion - ConsistentlyWithOffset(offset int, actualOrCtx interface{}, args ...interface{}) AsyncAssertion + Consistently(actualOrCtx any, args ...any) AsyncAssertion + ConsistentlyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertion SetDefaultEventuallyTimeout(time.Duration) SetDefaultEventuallyPollingInterval(time.Duration) @@ -37,9 +37,9 @@ type Gomega interface { // // For details on writing custom matchers, check out: http://onsi.github.io/gomega/#adding-your-own-matchers type GomegaMatcher interface { - Match(actual interface{}) (success bool, err error) - FailureMessage(actual interface{}) (message string) - NegatedFailureMessage(actual interface{}) (message string) + Match(actual any) (success bool, err error) + FailureMessage(actual any) (message string) + NegatedFailureMessage(actual any) (message string) } /* @@ -52,10 +52,10 @@ For example, a process' exit code can never change. So, gexec's Exit matcher re for `MatchMayChangeInTheFuture` until the process exits, at which point it returns `false` forevermore. */ type OracleMatcher interface { - MatchMayChangeInTheFuture(actual interface{}) bool + MatchMayChangeInTheFuture(actual any) bool } -func MatchMayChangeInTheFuture(matcher GomegaMatcher, value interface{}) bool { +func MatchMayChangeInTheFuture(matcher GomegaMatcher, value any) bool { oracleMatcher, ok := matcher.(OracleMatcher) if !ok { return true @@ -67,8 +67,8 @@ func MatchMayChangeInTheFuture(matcher GomegaMatcher, value interface{}) bool { // AsyncAssertions are returned by Eventually and Consistently and enable matchers to be polled repeatedly to ensure // they are eventually satisfied type AsyncAssertion interface { - Should(matcher GomegaMatcher, optionalDescription ...interface{}) bool - ShouldNot(matcher GomegaMatcher, optionalDescription ...interface{}) bool + Should(matcher GomegaMatcher, optionalDescription ...any) bool + ShouldNot(matcher GomegaMatcher, optionalDescription ...any) bool WithOffset(offset int) AsyncAssertion WithTimeout(interval time.Duration) AsyncAssertion @@ -76,18 +76,18 @@ type AsyncAssertion interface { Within(timeout time.Duration) AsyncAssertion ProbeEvery(interval time.Duration) AsyncAssertion WithContext(ctx context.Context) AsyncAssertion - WithArguments(argsToForward ...interface{}) AsyncAssertion + WithArguments(argsToForward ...any) AsyncAssertion MustPassRepeatedly(count int) AsyncAssertion } // Assertions are returned by Ω and Expect and enable assertions against Gomega matchers type Assertion interface { - Should(matcher GomegaMatcher, optionalDescription ...interface{}) bool - ShouldNot(matcher GomegaMatcher, optionalDescription ...interface{}) bool + Should(matcher GomegaMatcher, optionalDescription ...any) bool + ShouldNot(matcher GomegaMatcher, optionalDescription ...any) bool - To(matcher GomegaMatcher, optionalDescription ...interface{}) bool - ToNot(matcher GomegaMatcher, optionalDescription ...interface{}) bool - NotTo(matcher GomegaMatcher, optionalDescription ...interface{}) bool + To(matcher GomegaMatcher, optionalDescription ...any) bool + ToNot(matcher GomegaMatcher, optionalDescription ...any) bool + NotTo(matcher GomegaMatcher, optionalDescription ...any) bool WithOffset(offset int) Assertion