How to use CollectError method of ctxerr Package

Best Go-testdeep code snippet using ctxerr.CollectError

equal.go

Source:equal.go Github

copy

Full Screen

...79 }80 err.Got = got81 }82 err.Message = "values differ"83 return ctx.CollectError(&err)84}85func isCustomEqual(a, b reflect.Value) (bool, bool) {86 aType, bType := a.Type(), b.Type()87 equal, ok := aType.MethodByName("Equal")88 if ok {89 ft := equal.Type90 if !ft.IsVariadic() &&91 ft.NumIn() == 2 &&92 ft.NumOut() == 1 &&93 ft.In(0).AssignableTo(ft.In(1)) &&94 ft.Out(0) == types.Bool &&95 bType.AssignableTo(ft.In(1)) {96 return true, equal.Func.Call([]reflect.Value{a, b})[0].Bool()97 }98 }99 return false, false100}101// resolveAnchor does the same as ctx.Anchors.ResolveAnchor but checks102// whether v is valid and not already a TestDeep operator first.103func resolveAnchor(ctx ctxerr.Context, v reflect.Value) (reflect.Value, bool) {104 if !v.IsValid() || v.Type().Implements(testDeeper) {105 return v, false106 }107 return ctx.Anchors.ResolveAnchor(v)108}109func deepValueEqual(ctx ctxerr.Context, got, expected reflect.Value) (err *ctxerr.Error) {110 // got must not implement testDeeper111 if got.IsValid() && got.Type().Implements(testDeeper) {112 panic(color.Bad("Found a TestDeep operator in got param, " +113 "can only use it in expected one!"))114 }115 // Try to see if a TestDeep operator is anchored in expected116 if op, ok := resolveAnchor(ctx, expected); ok {117 expected = op118 }119 if !got.IsValid() || !expected.IsValid() {120 if got.IsValid() == expected.IsValid() {121 return122 }123 return nilHandler(ctx, got, expected)124 }125 // Check if a Smuggle hook matches got type126 if handled, e := ctx.Hooks.Smuggle(&got); handled {127 if e != nil {128 // ctx.BooleanError is always false here as hooks cannot be set globally129 return ctx.CollectError(&ctxerr.Error{130 Message: e.Error(),131 Got: got,132 Expected: expected,133 })134 }135 }136 // Check if a Cmp hook matches got & expected types137 if handled, e := ctx.Hooks.Cmp(got, expected); handled {138 if e == nil {139 return140 }141 // ctx.BooleanError is always false here as hooks cannot be set globally142 return ctx.CollectError(&ctxerr.Error{143 Message: e.Error(),144 Got: got,145 Expected: expected,146 })147 }148 // Look for an Equal() method149 if ctx.UseEqual || ctx.Hooks.UseEqual(got.Type()) {150 hasEqual, isEqual := isCustomEqual(got, expected)151 if hasEqual {152 if isEqual {153 return154 }155 if ctx.BooleanError {156 return ctxerr.BooleanError157 }158 return ctx.CollectError(&ctxerr.Error{159 Message: "got.Equal(expected) failed",160 Got: got,161 Expected: expected,162 })163 }164 }165 if got.Type() != expected.Type() {166 if expected.Type().Implements(testDeeper) {167 curOperator := dark.MustGetInterface(expected).(TestDeep)168 // Resolve interface169 if got.Kind() == reflect.Interface {170 got = got.Elem()171 if !got.IsValid() {172 return nilHandler(ctx, got, expected)173 }174 }175 ctx.CurOperator = curOperator176 return curOperator.Match(ctx, got)177 }178 // expected is not a TestDeep operator179 if got.Type() == recvKindType || expected.Type() == recvKindType {180 if ctx.BooleanError {181 return ctxerr.BooleanError182 }183 return ctx.CollectError(&ctxerr.Error{184 Message: "values differ",185 Got: got,186 Expected: expected,187 })188 }189 if ctx.BeLax && types.IsConvertible(expected, got.Type()) {190 return deepValueEqual(ctx, got, expected.Convert(got.Type()))191 }192 // If got is an interface, try to see what is behind before failing193 // Used by Set/Bag Match method in such cases:194 // []any{123, "foo"} → Bag("foo", 123)195 // Interface kind -^-----^ but String-^ and ^- Int kinds196 if got.Kind() == reflect.Interface {197 return deepValueEqual(ctx, got.Elem(), expected)198 }199 if ctx.BooleanError {200 return ctxerr.BooleanError201 }202 return ctx.CollectError(ctxerr.TypeMismatch(got.Type(), expected.Type()))203 }204 // if ctx.Depth > 10 { panic("deepValueEqual") } // for debugging205 // Avoid looping forever on cyclic references206 if ctx.Visited.Record(got, expected) {207 return208 }209 switch got.Kind() {210 case reflect.Array:211 for i, l := 0, got.Len(); i < l; i++ {212 err = deepValueEqual(ctx.AddArrayIndex(i),213 got.Index(i), expected.Index(i))214 if err != nil {215 return216 }217 }218 return219 case reflect.Slice:220 if got.IsNil() != expected.IsNil() {221 if ctx.BooleanError {222 return ctxerr.BooleanError223 }224 return ctx.CollectError(&ctxerr.Error{225 Message: "nil slice",226 Got: isNilStr(got.IsNil()),227 Expected: isNilStr(expected.IsNil()),228 })229 }230 var (231 gotLen = got.Len()232 expectedLen = expected.Len()233 )234 if gotLen != expectedLen {235 // Shortcut in boolean context236 if ctx.BooleanError {237 return ctxerr.BooleanError238 }239 } else {240 if got.Pointer() == expected.Pointer() {241 return242 }243 }244 var maxLen int245 if gotLen >= expectedLen {246 maxLen = expectedLen247 } else {248 maxLen = gotLen249 }250 // Special case for internal tuple type: it is clearer to read251 // TUPLE instead of DATA when an error occurs when using this type252 if got.Type() == tupleType &&253 ctx.Path.Len() == 1 && ctx.Path.String() == contextDefaultRootName {254 ctx = ctx.ResetPath("TUPLE")255 }256 for i := 0; i < maxLen; i++ {257 err = deepValueEqual(ctx.AddArrayIndex(i),258 got.Index(i), expected.Index(i))259 if err != nil {260 return261 }262 }263 if gotLen != expectedLen {264 res := tdSetResult{265 Kind: itemsSetResult,266 // do not sort Extra/Mising here267 }268 if gotLen > expectedLen {269 res.Extra = make([]reflect.Value, gotLen-expectedLen)270 for i := expectedLen; i < gotLen; i++ {271 res.Extra[i-expectedLen] = got.Index(i)272 }273 } else {274 res.Missing = make([]reflect.Value, expectedLen-gotLen)275 for i := gotLen; i < expectedLen; i++ {276 res.Missing[i-gotLen] = expected.Index(i)277 }278 }279 return ctx.CollectError(&ctxerr.Error{280 Message: fmt.Sprintf("comparing slices, from index #%d", maxLen),281 Summary: res.Summary(),282 })283 }284 return285 case reflect.Interface:286 return deepValueEqual(ctx, got.Elem(), expected.Elem())287 case reflect.Ptr:288 if got.Pointer() == expected.Pointer() {289 return290 }291 return deepValueEqual(ctx.AddPtr(1), got.Elem(), expected.Elem())292 case reflect.Struct:293 sType := got.Type()294 ignoreUnexported := ctx.IgnoreUnexported || ctx.Hooks.IgnoreUnexported(sType)295 for i, n := 0, got.NumField(); i < n; i++ {296 field := sType.Field(i)297 if ignoreUnexported && field.PkgPath != "" {298 continue299 }300 err = deepValueEqual(ctx.AddField(field.Name),301 got.Field(i), expected.Field(i))302 if err != nil {303 return304 }305 }306 return307 case reflect.Map:308 if got.IsNil() != expected.IsNil() {309 if ctx.BooleanError {310 return ctxerr.BooleanError311 }312 return ctx.CollectError(&ctxerr.Error{313 Message: "nil map",314 Got: isNilStr(got.IsNil()),315 Expected: isNilStr(expected.IsNil()),316 })317 }318 // Shortcut in boolean context319 if ctx.BooleanError && got.Len() != expected.Len() {320 return ctxerr.BooleanError321 }322 if got.Pointer() == expected.Pointer() {323 return324 }325 var notFoundKeys []reflect.Value326 foundKeys := map[any]bool{}327 for _, vkey := range tdutil.MapSortedKeys(expected) {328 gotValue := got.MapIndex(vkey)329 if !gotValue.IsValid() {330 notFoundKeys = append(notFoundKeys, vkey)331 continue332 }333 err = deepValueEqual(ctx.AddMapKey(vkey),334 gotValue, expected.MapIndex(vkey))335 if err != nil {336 return337 }338 foundKeys[dark.MustGetInterface(vkey)] = true339 }340 if got.Len() == len(foundKeys) {341 if len(notFoundKeys) == 0 {342 return343 }344 return ctx.CollectError(&ctxerr.Error{345 Message: "comparing map",346 Summary: (tdSetResult{347 Kind: keysSetResult,348 Missing: notFoundKeys,349 Sort: true,350 }).Summary(),351 })352 }353 if ctx.BooleanError {354 return ctxerr.BooleanError355 }356 // Retrieve extra keys357 res := tdSetResult{358 Kind: keysSetResult,359 Missing: notFoundKeys,360 Extra: make([]reflect.Value, 0, got.Len()-len(foundKeys)),361 Sort: true,362 }363 for _, vkey := range tdutil.MapSortedKeys(got) {364 if !foundKeys[dark.MustGetInterface(vkey)] {365 res.Extra = append(res.Extra, vkey)366 }367 }368 return ctx.CollectError(&ctxerr.Error{369 Message: "comparing map",370 Summary: res.Summary(),371 })372 case reflect.Func:373 if got.IsNil() && expected.IsNil() {374 return375 }376 if ctx.BooleanError {377 return ctxerr.BooleanError378 }379 // Can't do better than this:380 return ctx.CollectError(&ctxerr.Error{381 Message: "functions mismatch",382 Summary: ctxerr.NewSummary("<can not be compared>"),383 })384 default:385 // Normal equality suffices386 if dark.MustGetInterface(got) == dark.MustGetInterface(expected) {387 return388 }389 if ctx.BooleanError {390 return ctxerr.BooleanError391 }392 return ctx.CollectError(&ctxerr.Error{393 Message: "values differ",394 Got: got,395 Expected: expected,396 })397 }398}399func deepValueEqualOK(got, expected reflect.Value) bool {400 return deepValueEqualFinal(newBooleanContext(), got, expected) == nil401}402// EqDeeply returns true if got matches expected. expected can403// be the same type as got is, or contains some [TestDeep] operators.404//405// got := "foobar"406// td.EqDeeply(got, "foobar") // returns true...

Full Screen

Full Screen

context_test.go

Source:context_test.go Github

copy

Full Screen

...98 if thirdErr.Next != nil {99 t.Error("ctx.MergeErrors() third error has a non-nil Next!")100 }101}102func TestContextCollectError(t *testing.T) {103 //104 // Only one error kept105 ctx := ctxerr.Context{}106 if ctx.CollectError(nil) != nil {107 t.Error("ctx.CollectError(nil) returned non-nil *Error")108 }109 err := ctxerr.Context{BooleanError: true}.CollectError(&ctxerr.Error{})110 if err != ctxerr.BooleanError {111 t.Error("boolean-ctx.CollectError(X) did not return BooleanError")112 }113 // !err.Location.IsInitialized() + ctx.CurOperator == nil114 origErr := &ctxerr.Error{}115 err = ctx.CollectError(origErr)116 if err != origErr {117 t.Error("ctx.CollectError(err) != err")118 }119 // !err.Location.IsInitialized() + ctx.CurOperator != nil120 ctx.CurOperator = MyGetLocationer{}121 origErr = &ctxerr.Error{}122 err = ctx.CollectError(origErr)123 if err != origErr {124 t.Error("ctx.CollectError(err) != err")125 }126 test.EqualInt(t, err.Location.Line, 42, // see MyGetLocationer.GetLocation()127 "ctx.CollectError(err) initialized err.Location")128 // err.Location.IsInitialized()129 origErr = &ctxerr.Error{130 Location: location.Location{131 File: "zz.go",132 Func: "ErrFunc",133 Line: 24,134 },135 }136 err = ctx.CollectError(origErr)137 if err != origErr {138 t.Error("ctx.CollectError(err) != err")139 }140 test.EqualInt(t, err.Location.Line, 24,141 "ctx.CollectError(err) did not touch err.Location")142 //143 // 2 errors kept max144 errors := []*ctxerr.Error{}145 ctx = ctxerr.Context{146 Errors: &errors,147 MaxErrors: 2,148 }149 origErr = &ctxerr.Error{}150 if ctx.CollectError(origErr) != nil { // 1st error is accumulated151 t.Error("ctx.CollectError(err) != nil")152 return153 }154 secondErr := &ctxerr.Error{}155 if ctx.CollectError(secondErr) != origErr {156 t.Error("ctx.CollectError(err) != origErr")157 return158 }159 if origErr.Next != secondErr {160 t.Error("origErr.Next != secondErr")161 return162 }163 if secondErr.Next != ctxerr.ErrTooManyErrors {164 t.Error("secondErr.Next != ErrTooManyErrors")165 return166 }167 //168 // All errors kept169 errors = nil170 ctx = ctxerr.Context{171 Errors: &errors,172 MaxErrors: -1,173 }174 for i := 0; i < 100; i++ {175 if ctx.CollectError(&ctxerr.Error{}) != nil { // 1st error is accumulated176 t.Errorf("#%d: ctx.CollectError(err) != nil", i)177 return178 }179 }180 if len(errors) != 100 {181 t.Errorf("Only %d errors accumulated instead of 100", len(errors))182 }183}184func TestCannotCompareError(t *testing.T) {185 ctx := ctxerr.Context{BooleanError: true}186 err := ctx.CannotCompareError()187 if err != ctxerr.BooleanError {188 t.Error("CannotCompareError does not return ctxerr.BooleanError")189 }190 ctx = ctxerr.Context{}...

Full Screen

Full Screen

td_nan.go

Source:td_nan.go Github

copy

Full Screen

...33 case reflect.Float32, reflect.Float64:34 if math.IsNaN(got.Float()) {35 return nil36 }37 return ctx.CollectError(&ctxerr.Error{38 Message: "values differ",39 Got: got,40 Expected: n,41 })42 }43 return ctx.CollectError(&ctxerr.Error{44 Message: "type mismatch",45 Got: types.RawString(got.Type().String()),46 Expected: types.RawString("float32 OR float64"),47 })48}49func (n *tdNaN) String() string {50 return "NaN"51}52type tdNotNaN struct {53 base54}55var _ TestDeep = &tdNotNaN{}56// summary(NotNaN): checks a floating number is not [`math.NaN`]57// input(NotNaN): float58// NotNaN operator checks that data is a float and is not not-a-number.59//60// got := math.NaN()61// td.Cmp(t, got, td.NotNaN()) // fails62// td.Cmp(t, 4.2, td.NotNaN()) // succeeds63// td.Cmp(t, 4, td.NotNaN()) // fails, as 4 is not a float64//65// See also [NaN].66func NotNaN() TestDeep {67 return &tdNotNaN{68 base: newBase(3),69 }70}71func (n *tdNotNaN) Match(ctx ctxerr.Context, got reflect.Value) *ctxerr.Error {72 switch got.Kind() {73 case reflect.Float32, reflect.Float64:74 if !math.IsNaN(got.Float()) {75 return nil76 }77 return ctx.CollectError(&ctxerr.Error{78 Message: "values differ",79 Got: got,80 Expected: n,81 })82 }83 return ctx.CollectError(&ctxerr.Error{84 Message: "type mismatch",85 Got: types.RawString(got.Type().String()),86 Expected: types.RawString("float32 OR float64"),87 })88}89func (n *tdNotNaN) String() string {90 return "not NaN"91}...

Full Screen

Full Screen

CollectError

Using AI Code Generation

copy

Full Screen

1func (e *ctxerr) Error() string {2 return e.err.Error()3}4func (e *ctxerr) CollectError(err error) {5 if err != nil {6 }7}8func (e *ctxerr) GetError() error {9}10func main() {11 e := &ctxerr{}12 e.CollectError(errors.New("error1"))13 e.CollectError(errors.New("error2"))14 e.CollectError(errors.New("error3"))15 fmt.Println(e.GetError())16}

Full Screen

Full Screen

CollectError

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 err := golctxerr.CollectError(fmt.Errorf("error1"), "error2", "error3")4 fmt.Println("error: ", err)5}6error: error1; error2; error3

Full Screen

Full Screen

CollectError

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := ctxerr.NewContext()4 err := ctxerr.NewError(ctx, "Error1")5 ctxerr.CollectError(ctx, ctxerr.NewError(ctx, "Error2"))6 ctxerr.CollectError(ctx, ctxerr.NewError(ctx, "Error3"))7 fmt.Println(ctxerr.GetError(ctx))8}

Full Screen

Full Screen

CollectError

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := ctxerr.NewContext()4 ctx.CollectError(ctxerr.NewError("Error 1"))5 ctx.CollectError(ctxerr.NewError("Error 2"))6 ctx.CollectError(ctxerr.NewError("Error 3"))7 fmt.Println(ctx.GetErrors())8}

Full Screen

Full Screen

CollectError

Using AI Code Generation

copy

Full Screen

1import ( 2func main() { 3 err := ctxerr.New(“Error occured”)4 err = err.CollectError(fmt.Errorf(“Error 1”))5 err = err.CollectError(fmt.Errorf(“Error 2”))6 err = err.CollectError(fmt.Errorf(“Error 3”))7 err = err.CollectError(fmt.Errorf(“Error 4”))8 fmt.Println(err)9}10import ( 11func main() { 12 err := ctxerr.New(“Error occured”)13 err = err.WrapError(fmt.Errorf(“Error 1”))14 err = err.WrapError(fmt.Errorf(“Error 2”))15 err = err.WrapError(fmt.Errorf(“Error 3”))16 err = err.WrapError(fmt.Errorf(“Error 4”))17 fmt.Println(err)18}19import ( 20func main() { 21 err := ctxerr.New(“Error occured”)22 err = err.CollectError(fmt.Errorf(“Error 1”))23 err = err.CollectError(fmt.Errorf(“Error 2”))24 err = err.CollectError(fmt.Errorf(“Error 3”))25 err = err.CollectError(fmt.Errorf(“Error 4”))26 fmt.Println(err)27}28import ( 29func main() { 30 err := ctxerr.New(“Error occured”)31 err = err.WrapError(fmt.Errorf(

Full Screen

Full Screen

CollectError

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 err := ctxerr.New("error occurred").WithCode("ERR-001")4 err = err.CollectError(ctxerr.New("error occurred").WithCode("ERR-002"))5 err = err.CollectError(ctxerr.New("error occurred").WithCode("ERR-003"))6 fmt.Println(err)7}8import (9func main() {10 CollectError(ctxerr.New("error occurred").WithCode("ERR-003"))11 fmt.Println(err)12}13import (14func main() {15 WithCode("ERR-003")))16 fmt.Println(err)17}18import (19func main() {20 CollectError(ctxerr.New("

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful