How to use AddAnchorableStructType method of anchors Package

Best Go-testdeep code snippet using anchors.AddAnchorableStructType

t_anchor.go

Source:t_anchor.go Github

copy

Full Screen

...12)13// Anchors are stored globally by testing.TB.Name().14var allAnchors = map[string]*anchors.Info{}15var allAnchorsMu sync.Mutex16// AddAnchorableStructType declares a struct type as anchorable. fn17// is a function allowing to return a unique and identifiable instance18// of the struct type.19//20// fn has to have the following signature:21//22// func (nextAnchor int) TYPE23//24// TYPE is the struct type to make anchorable and nextAnchor is an25// index to allow to differentiate several instances of the same type.26//27// For example, the [time.Time] type which is anchorable by default,28// could be declared as:29//30// AddAnchorableStructType(func (nextAnchor int) time.Time {31// return time.Unix(int64(math.MaxInt64-1000424443-nextAnchor), 42)32// })33//34// Just as a note, the 1000424443 constant allows to avoid to flirt35// with the math.MaxInt64 extreme limit and so avoid possible36// collision with real world values.37//38// It panics if the provided fn is not a function or if it has not the39// expected signature (see above).40//41// See also [T.Anchor], [T.AnchorsPersistTemporarily],42// [T.DoAnchorsPersist], [T.ResetAnchors] and [T.SetAnchorsPersist].43func AddAnchorableStructType(fn any) {44 err := anchors.AddAnchorableStructType(fn)45 if err != nil {46 panic(color.Bad(err.Error()))47 }48}49// Anchor returns a typed value allowing to anchor the TestDeep50// operator operator in a go classic literal like a struct, slice,51// array or map value.52//53// If the TypeBehind method of operator returns non-nil, model can be54// omitted (like with [Between] operator in the example55// below). Otherwise, model should contain only one value56// corresponding to the returning type. It can be:57// - a go value: returning type is the type of the value,58// whatever the value is;59// - a [reflect.Type].60//61// It returns a typed value ready to be embed in a go data structure to62// be compared using [T.Cmp] or [T.CmpLax]:63//64// import (65// "testing"66//67// "github.com/maxatome/go-testdeep/td"68// )69//70// func TestFunc(tt *testing.T) {71// got := Func()72//73// t := td.NewT(tt)74// t.Cmp(got, &MyStruct{75// Name: "Bob",76// Details: &MyDetails{77// Nick: t.Anchor(td.HasPrefix("Bobby"), "").(string),78// Age: t.Anchor(td.Between(40, 50)).(int),79// },80// })81// }82//83// In this example:84//85// - [HasPrefix] operates on several input types (string,86// [fmt.Stringer], error, …), so its TypeBehind method returns always87// nil as it can not guess in advance on which type it operates. In88// this case, we must pass "" as model parameter in order to tell it89// to return the string type. Note that the .(string) type assertion90// is then mandatory to conform to the strict type checking.91// - [Between], on its side, knows the type on which it operates, as92// it is the same as the one of its parameters. So its TypeBehind93// method returns the right type, and so no need to pass it as model94// parameter. Note that the .(int) type assertion is still mandatory95// to conform to the strict type checking.96//97// Without operator anchoring feature, the previous example would have98// been:99//100// import (101// "testing"102//103// "github.com/maxatome/go-testdeep/td"104// )105//106// func TestFunc(tt *testing.T) {107// got := Func()108//109// t := td.NewT(tt)110// t.Cmp(got, td.Struct(&MyStruct{Name: "Bob"},111// td.StructFields{112// "Details": td.Struct(&MyDetails{},113// td.StructFields{114// "Nick": td.HasPrefix("Bobby"),115// "Age": td.Between(40, 50),116// }),117// }))118// }119//120// using two times the [Struct] operator to work around the strict type121// checking of golang.122//123// By default, the value returned by Anchor can only be used in the124// next [T.Cmp] or [T.CmpLax] call. To make it persistent across calls,125// see [T.SetAnchorsPersist] and [T.AnchorsPersistTemporarily] methods.126//127// See [T.A] method for a shorter synonym of Anchor.128//129// See also [T.AnchorsPersistTemporarily], [T.DoAnchorsPersist],130// [T.ResetAnchors], [T.SetAnchorsPersist] and [AddAnchorableStructType].131func (t *T) Anchor(operator TestDeep, model ...any) any {132 if operator == nil {133 t.Helper()134 t.Fatal(color.Bad("Cannot anchor a nil TestDeep operator"))135 }136 var typ reflect.Type137 if len(model) > 0 {138 if len(model) != 1 {139 t.Helper()140 t.Fatal(color.TooManyParams("Anchor(OPERATOR[, MODEL])"))141 }142 var ok bool143 typ, ok = model[0].(reflect.Type)144 if !ok {145 typ = reflect.TypeOf(model[0])146 if typ == nil {147 t.Helper()148 t.Fatal(color.Bad("Untyped nil value is not valid as model for an anchor"))149 }150 }151 typeBehind := operator.TypeBehind()152 if typeBehind != nil && typeBehind != typ {153 t.Helper()154 t.Fatal(color.Bad("Operator %s TypeBehind() returned %s which differs from model type %s. Omit model or ensure its type is %[2]s",155 operator.GetLocation().Func, typeBehind, typ))156 }157 } else {158 typ = operator.TypeBehind()159 if typ == nil {160 t.Helper()161 t.Fatal(color.Bad("Cannot anchor operator %s as TypeBehind() returned nil. Use model parameter to specify the type to return",162 operator.GetLocation().Func))163 }164 }165 nvm, err := t.Config.anchors.AddAnchor(typ, reflect.ValueOf(operator))166 if err != nil {167 t.Helper()168 t.Fatal(color.Bad(err.Error()))169 }170 return nvm.Interface()171}172// A is a synonym for [T.Anchor].173//174// import (175// "testing"176//177// "github.com/maxatome/go-testdeep/td"178// )179//180// func TestFunc(tt *testing.T) {181// got := Func()182//183// t := td.NewT(tt)184// t.Cmp(got, &MyStruct{185// Name: "Bob",186// Details: &MyDetails{187// Nick: t.A(td.HasPrefix("Bobby"), "").(string),188// Age: t.A(td.Between(40, 50)).(int),189// },190// })191// }192//193// See also [T.AnchorsPersistTemporarily], [T.DoAnchorsPersist],194// [T.ResetAnchors], [T.SetAnchorsPersist] and [AddAnchorableStructType].195func (t *T) A(operator TestDeep, model ...any) any {196 t.Helper()197 return t.Anchor(operator, model...)198}199func (t *T) resetNonPersistentAnchors() {200 t.Config.anchors.ResetAnchors(false)201}202// ResetAnchors frees all operators anchored with [T.Anchor]203// method. Unless operators anchoring persistence has been enabled204// with [T.SetAnchorsPersist], there is no need to call this205// method. Anchored operators are automatically freed after each [Cmp],206// [CmpDeeply] and [CmpPanic] call (or others methods calling them behind207// the scene).208//209// See also [T.Anchor], [T.AnchorsPersistTemporarily],210// [T.DoAnchorsPersist], [T.SetAnchorsPersist] and [AddAnchorableStructType].211func (t *T) ResetAnchors() {212 t.Config.anchors.ResetAnchors(true)213}214// AnchorsPersistTemporarily is used by helpers to temporarily enable215// anchors persistence. See [tdhttp] package for an example of use. It216// returns a function to be deferred, to restore the normal behavior217// (clear anchored operators if persistence was false, do nothing218// otherwise).219//220// Typically used as:221//222// defer t.AnchorsPersistTemporarily()()223// // or224// t.Cleanup(t.AnchorsPersistTemporarily())225//226// See also [T.Anchor], [T.DoAnchorsPersist], [T.ResetAnchors],227// [T.SetAnchorsPersist] and [AddAnchorableStructType].228//229// [tdhttp]: https://pkg.go.dev/github.com/maxatome/go-testdeep/helpers/tdhttp230func (t *T) AnchorsPersistTemporarily() func() {231 // If already persistent, do nothing on defer232 if t.DoAnchorsPersist() {233 return func() {}234 }235 t.SetAnchorsPersist(true)236 return func() {237 t.SetAnchorsPersist(false)238 t.Config.anchors.ResetAnchors(true)239 }240}241// DoAnchorsPersist returns true if anchors persistence is enabled,242// false otherwise.243//244// See also [T.Anchor], [T.AnchorsPersistTemporarily],245// [T.ResetAnchors], [T.SetAnchorsPersist] and [AddAnchorableStructType].246func (t *T) DoAnchorsPersist() bool {247 return t.Config.anchors.DoAnchorsPersist()248}249// SetAnchorsPersist allows to enable or disable anchors persistence.250//251// See also [T.Anchor], [T.AnchorsPersistTemporarily],252// [T.DoAnchorsPersist], [T.ResetAnchors] and [AddAnchorableStructType].253func (t *T) SetAnchorsPersist(persist bool) {254 t.Config.anchors.SetAnchorsPersist(persist)255}256func (t *T) initAnchors() {257 if t.Config.anchors != nil {258 return259 }260 name := t.Name()261 allAnchorsMu.Lock()262 defer allAnchorsMu.Unlock()263 t.Config.anchors = allAnchors[name]264 if t.Config.anchors == nil {265 t.Config.anchors = anchors.NewInfo()266 allAnchors[name] = t.Config.anchors...

Full Screen

Full Screen

anchor_test.go

Source:anchor_test.go Github

copy

Full Screen

...64 oldAnchorableTypes := anchors.AnchorableTypes65 defer func() { anchors.AnchorableTypes = oldAnchorableTypes }()66 type ok struct{ index int }67 // AddAnchor for ok type68 err := anchors.AddAnchorableStructType(func(nextAnchor int) ok {69 return ok{index: 1000 + nextAnchor}70 })71 if err != nil {72 t.Fatalf("AddAnchorableStructType failed: %s", err)73 }74 checkResolveAnchor(t, ok{}, "ok{}")75 // AddAnchor for ok convertible type76 type okConvert ok77 checkResolveAnchor(t, okConvert{}, "okConvert{}")78 // Replace ok type79 err = anchors.AddAnchorableStructType(func(nextAnchor int) ok {80 return ok{index: 2000 + nextAnchor}81 })82 if err != nil {83 t.Fatalf("AddAnchorableStructType failed: %s", err)84 }85 if len(anchors.AnchorableTypes) != 2 {86 t.Fatalf("Bad number of anchored type: got=%d expected=2",87 len(anchors.AnchorableTypes))88 }89 checkResolveAnchor(t, ok{}, "ok{}")90 // AddAnchor for builtin time.Time type91 checkResolveAnchor(t, time.Time{}, "time.Time{}")92 // AddAnchor for unknown type93 _, err = i.AddAnchor(reflect.TypeOf(func() {}), reflect.ValueOf(123))94 if test.Error(t, err) {95 test.EqualStr(t, err.Error(), "func kind is not supported as an anchor")96 }97 // AddAnchor for unknown struct type98 _, err = i.AddAnchor(reflect.TypeOf(struct{}{}), reflect.ValueOf(123))99 if test.Error(t, err) {100 test.EqualStr(t,101 err.Error(),102 "struct {} struct type is not supported as an anchor. Try AddAnchorableStructType")103 }104 // Struct not comparable105 type notComparable struct{ s []int }106 v := reflect.ValueOf(notComparable{s: []int{42}})107 op, found := i.ResolveAnchor(v)108 test.IsFalse(t, found)109 if !reflect.DeepEqual(v.Interface(), op.Interface()) {110 test.EqualErrorMessage(t, op.Interface(), v.Interface())111 }112 // Struct comparable but not anchored113 v = reflect.ValueOf(struct{}{})114 op, found = i.ResolveAnchor(v)115 test.IsFalse(t, found)116 if !reflect.DeepEqual(v.Interface(), op.Interface()) {...

Full Screen

Full Screen

types_test.go

Source:types_test.go Github

copy

Full Screen

...8 "strings"9 "testing"10 "github.com/maxatome/go-testdeep/internal/anchors"11)12func TestAddAnchorableStructType(t *testing.T) {13 oldAnchorableTypes := anchors.AnchorableTypes14 defer func() { anchors.AnchorableTypes = oldAnchorableTypes }()15 type ok struct{ index int }16 type notComparable struct{ s []int } //nolint: unused17 // Usage error cases18 for i, fn := range []any{19 12,20 func(x ...int) {},21 func(x, y int) {},22 func(x int) (int, int) { return 0, 0 },23 func(x byte) int { return 0 },24 func(x int) int { return 0 },25 } {26 err := anchors.AddAnchorableStructType(fn)27 if err == nil {28 t.Fatalf("#%d function should return an error", i)29 }30 if !strings.HasPrefix(err.Error(), "usage: ") {31 t.Errorf("#%d function returned: `%s` instead of usage", i, err)32 }33 }34 // Not comparable struct35 err := anchors.AddAnchorableStructType(func(nextAnchor int) notComparable {36 return notComparable{}37 })38 if err == nil {39 t.Fatal("function should return an error")40 }41 if err.Error() != "type anchors_test.notComparable is not comparable, it cannot be anchorable" {42 t.Errorf("function returned: `%s` instead of not comparable error", err)43 }44 // Comparable struct => OK45 err = anchors.AddAnchorableStructType(func(nextAnchor int) ok {46 return ok{index: 1000 + nextAnchor}47 })48 if err != nil {49 t.Fatalf("AddAnchorableStructType failed: %s", err)50 }51 if len(anchors.AnchorableTypes) != 2 {52 t.Fatalf("Bad number of anchored type: got=%d expected=2",53 len(anchors.AnchorableTypes))54 }55}...

Full Screen

Full Screen

AddAnchorableStructType

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 file = xlsx.NewFile()4 sheet, err = file.AddSheet("Sheet1")5 if err != nil {6 fmt.Printf(err.Error())7 }8 row = sheet.AddRow()9 cell = row.AddCell()10 cell = row.AddCell()11 cell = row.AddCell()12 cell = row.AddCell()13 cell = row.AddCell()14 cell = row.AddCell()15 err = file.Save("Test.xlsx")16 if err != nil {17 fmt.Printf(err.Error())18 }19}20import (21func main() {22 file = xlsx.NewFile()23 sheet, err = file.AddSheet("Sheet1")24 if err != nil {25 fmt.Printf(err.Error())26 }27 row = sheet.AddRow()28 cell = row.AddCell()29 cell = row.AddCell()30 cell = row.AddCell()31 cell = row.AddCell()32 cell = row.AddCell()33 cell = row.AddCell()34 err = file.Save("Test.xlsx")35 if err != nil {36 fmt.Printf(err.Error())37 }38}39import (40func main() {41 file = xlsx.NewFile()42 sheet, err = file.AddSheet("Sheet1")43 if err != nil {

Full Screen

Full Screen

AddAnchorableStructType

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 f := excelize.NewFile()4 index := f.NewSheet("Sheet2")5 f.SetCellValue("Sheet2", "A2", "Hello world.")6 f.SetCellValue("Sheet2", "B2", 100)7 f.SetActiveSheet(index)8 err := f.SaveAs("Book2.xlsx")9 if err != nil {10 fmt.Println(err)11 }12}13import (14func main() {15 f := excelize.NewFile()16 index := f.NewSheet("Sheet2")17 f.SetCellValue("Sheet2", "A2", "Hello world.")18 f.SetCellValue("Sheet2", "B2", 100)19 f.SetActiveSheet(index)20 err := f.SaveAs("Book2.xlsx")21 if err != nil {22 fmt.Println(err)23 }24}25import (26func main() {27 f := excelize.NewFile()28 index := f.NewSheet("Sheet2")29 f.SetCellValue("Sheet2", "A2", "Hello world.")30 f.SetCellValue("Sheet2", "B2", 100)

Full Screen

Full Screen

AddAnchorableStructType

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 f := excelize.NewFile()4 index := f.NewSheet("Sheet2")5 f.SetCellValue("Sheet2", "A2", "Hello world.")6 f.SetCellValue("Sheet2", "B2", 100)7 f.SetActiveSheet(index)8 if err := f.SaveAs("Book2.xlsx"); err != nil {9 fmt.Println(err)10 }11}12import (13func main() {14 f := excelize.NewFile()15 index := f.NewSheet("Sheet2")16 f.SetCellValue("Sheet2", "A2", "Hello world.")17 f.SetCellValue("Sheet2", "B2", 100)18 f.SetActiveSheet(index)19 if err := f.SaveAs("Book2.xlsx"); err != nil {20 fmt.Println(err)21 }22}23import (24func main() {25 f := excelize.NewFile()26 index := f.NewSheet("Sheet2")27 f.SetCellValue("Sheet2", "A2", "Hello world.")28 f.SetCellValue("Sheet2", "B2", 100)

Full Screen

Full Screen

AddAnchorableStructType

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 f := excelize.NewFile()4 index := f.NewSheet("Sheet2")5 f.SetCellValue("Sheet2", "A2", "Hello world.")6 f.SetCellValue("Sheet2", "B2", 100)7 f.SetActiveSheet(index)8 err := f.SaveAs("Book1.xlsx")9 if err != nil {10 fmt.Println(err)11 }12}13testing.tRunner.func1(0xc0000b0c00)14panic(0x4e8f80, 0x6b4c50)15github.com/360EntSecGroup-Skylar/excelize.(*File).AddAnchorableStructType(0x0, 0x4f8f6a, 0x6, 0x4f8f6a, 0x6, 0x0, 0x0, 0x0, 0x0, 0x0, ...)16main.main()17Click to share on Telegram (Opens in new window)

Full Screen

Full Screen

AddAnchorableStructType

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 core.QCoreApplication_SetAttribute(core.Qt__AA_EnableHighDpiScaling, true)4 widgets.NewQApplication(len(os.Args), os.Args)5 quickcontrols2.QQuickStyle_SetStyle("Material")6 quickcontrols2.QQuickStyle_SetFallbackStyle("Default")7 engine := qml.NewQQmlApplicationEngine(nil)8 view := quick.NewQQuickView(nil)9 widget := widgets.NewQWidget(nil, 0)10 widget.SetMinimumSize2(800, 600)11 widget.SetWindowTitle("Quick Controls 2 Widget Example")12 quickWidget := quickcontrols2.NewQQuickWidget(nil)13 quickWidget.SetResizeMode(quickcontrols2.QQuickWidget__SizeRootObjectToView)14 quickWidget.SetMinimumSize2(800, 600)15 quickWidget2 := quickcontrols2.NewQQuickWidget(nil)16 quickWidget2.SetResizeMode(quickcontrols2.QQuickWidget__SizeRootObjectToView)17 quickWidget2.SetMinimumSize2(800, 600)18 quickWidget3 := quickcontrols2.NewQQuickWidget(nil)19 quickWidget3.SetResizeMode(quickcontrols2.QQuickWidget__SizeRootObjectToView)20 quickWidget3.SetMinimumSize2(800, 600)21 quickWidget4 := quickcontrols2.NewQQuickWidget(nil)22 quickWidget4.SetResizeMode(quickcontrols2.QQuickWidget__SizeRootObjectToView)23 quickWidget4.SetMinimumSize2(800, 600)24 quickWidget5 := quickcontrols2.NewQQuickWidget(nil)25 quickWidget5.SetResizeMode(quickcontrols2.QQuickWidget__SizeRootObjectToView)26 quickWidget5.SetMinimumSize2(800, 600

Full Screen

Full Screen

AddAnchorableStructType

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 xlFile, err := xlsx.OpenFile("Sample.xlsx")4 if err != nil {5 fmt.Println(err)6 }7 anchor.AddAnchorableStructType("Test", "Test", "Test", "Test")8 err = xlFile.Save("Sample.xlsx")9 if err != nil {10 fmt.Println(err)11 }12}13import (14func main() {15 xlFile, err := xlsx.OpenFile("Sample.xlsx")16 if err != nil {17 fmt.Println(err)18 }19 anchor.AddAnchorableStructType("Test", "Test", "Test", "Test")20 err = xlFile.Save("Sample.xlsx")21 if err != nil {22 fmt.Println(err)23 }24}

Full Screen

Full Screen

AddAnchorableStructType

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 f := excelize.NewFile()4 index := f.NewSheet("Sheet2")5 f.SetCellValue("Sheet2", "A2", "Hello world.")6 f.SetActiveSheet(index)7 err := f.SaveAs("Book1.xlsx")8 if err != nil {9 fmt.Println(err)10 }11}12import (13func main() {14 f := excelize.NewFile()15 index := f.NewSheet("Sheet2")16 f.SetCellValue("Sheet2", "A2", "Hello world.")17 f.SetActiveSheet(index)18 err := f.SaveAs("Book1.xlsx")19 if err != nil {20 fmt.Println(err)21 }22}

Full Screen

Full Screen

AddAnchorableStructType

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 anchors := anchors.New()4 anchors.AddAnchorableStructType("myStruct", new(MyStruct))5 myStruct := MyStruct{ID: 1, Name: "MyStruct"}6 anchor := anchors.CreateAnchor(myStruct)7 fmt.Println(anchor)8}9import (10func main() {11 anchors := anchors.New()12 anchors.AddAnchorableStructType("myStruct", new(MyStruct))13 myStruct := MyStruct{ID: 1, Name: "MyStruct"}14 anchor := anchors.CreateAnchor(myStruct)15 fmt.Println(anchor)16}17import (18func main() {19 anchors := anchors.New()20 anchors.AddAnchorableStructType("myStruct", new(MyStruct))21 myStruct := MyStruct{ID: 1, Name: "MyStruct"}22 anchor := anchors.CreateAnchor(myStruct)23 fmt.Println(anchor)24}25import (26func main() {27 anchors := anchors.New()28 anchors.AddAnchorableStructType("myStruct", new(My

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.

Run Go-testdeep automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful