Best Go-testdeep code snippet using td.newFieldMatcher
td_struct.go
Source:td_struct.go
...60 subs = subs[1:]61 }62 return subs63}64// newFieldMatcher checks name matches "[NUM] OP PATTERN" where NUM65// is an optional number used to sort patterns, OP is "=~", "!~", "="66// or "!" and PATTERN is a regexp (when OP is either "=~" or "!~") or67// a shell pattern (when OP is either "=" or "!").68//69// NUM, OP and PATTERN can be separated by spaces (or not).70func newFieldMatcher(name string, expected any) (fieldMatcher, error) {71 subs := parseMatcher(name)72 if subs == nil {73 return fieldMatcher{}, errNotAMatcher74 }75 fm := fieldMatcher{76 name: name,77 expected: expected,78 ok: subs[1][0] == '=',79 }80 if subs[0] != "" {81 fm.order, _ = strconv.Atoi(subs[0]) //nolint: errcheck82 }83 // Shell pattern84 if subs[1] == "=" || subs[1] == "!" {85 pattern := subs[2]86 fm.match = func(s string) (bool, error) {87 return path.Match(pattern, s)88 }89 return fm, nil90 }91 // Regexp92 r, err := regexp.Compile(subs[2])93 if err != nil {94 return fieldMatcher{}, fmt.Errorf("bad regexp field %#q: %s", name, err)95 }96 fm.match = func(s string) (bool, error) {97 return r.MatchString(s), nil98 }99 return fm, nil100}101type fieldMatcherSlice []fieldMatcher102func (m fieldMatcherSlice) Len() int { return len(m) }103func (m fieldMatcherSlice) Less(i, j int) bool {104 if m[i].order != m[j].order {105 return m[i].order < m[j].order106 }107 return m[i].name < m[j].name108}109func (m fieldMatcherSlice) Swap(i, j int) { m[i], m[j] = m[j], m[i] }110// StructFields allows to pass struct fields to check in functions111// [Struct] and [SStruct]. It is a map whose each key is the expected112// field name (or a regexp or a shell pattern matching a field name,113// see [Struct] & [SStruct] docs for details) and the corresponding114// value the expected field value (which can be a [TestDeep] operator115// as well as a zero value.)116type StructFields map[string]any117// canonStructField canonicalizes name, a key in a StructFields map,118// so it can be compared with other keys during a mergeStructFields().119// - "name" â "name"120// - "> name " â ">name"121// - " 22 =~ [A-Z].*At$ " â "22=~[A-Z].*At$"122func canonStructField(name string) string {123 r, _ := utf8.DecodeRuneInString(name)124 if r == utf8.RuneError || unicode.IsLetter(r) {125 return name // shortcut126 }127 // Overwrite a field128 if strings.HasPrefix(name, ">") {129 new := strings.TrimSpace(name[1:])130 if 1+len(new) == len(name) {131 return name // already canonicalized132 }133 return ">" + new134 }135 // Matcher136 if subs := parseMatcher(name); subs != nil {137 if len(subs[0])+len(subs[1])+len(subs[2]) == len(name) {138 return name // already canonicalized139 }140 return subs[0] + subs[1] + subs[2]141 }142 // Will probably raise an error later as it cannot be a field, not143 // an overwritter and not a matcher144 return name145}146// mergeStructFields merges all sfs items into one StructFields and147// returns it.148func mergeStructFields(sfs ...StructFields) StructFields {149 switch len(sfs) {150 case 0:151 return nil152 case 1:153 return sfs[0]154 default:155 // Do a smart merge so "> pipo" replaces ">pipo " for example.156 canon2field := map[string]string{}157 ret := make(StructFields, len(sfs[0]))158 for _, sf := range sfs {159 for field, value := range sf {160 canon := canonStructField(field)161 if prevField, ok := canon2field[canon]; ok {162 delete(ret, prevField)163 delete(canon2field, canon)164 } else {165 delete(ret, canon)166 }167 if canon != field {168 canon2field[canon] = field169 }170 ret[field] = value171 }172 }173 return ret174 }175}176func newStruct(model any, strict bool) (*tdStruct, reflect.Value) {177 vmodel := reflect.ValueOf(model)178 st := tdStruct{179 tdExpectedType: tdExpectedType{180 base: newBase(5),181 },182 }183 switch vmodel.Kind() {184 case reflect.Ptr:185 if vmodel.Type().Elem().Kind() != reflect.Struct {186 break187 }188 st.isPtr = true189 if vmodel.IsNil() {190 st.expectedType = vmodel.Type().Elem()191 return &st, reflect.Value{}192 }193 vmodel = vmodel.Elem()194 fallthrough195 case reflect.Struct:196 st.expectedType = vmodel.Type()197 return &st, vmodel198 }199 st.err = ctxerr.OpBadUsage(st.location.Func,200 "(STRUCT|&STRUCT, EXPECTED_FIELDS)",201 model, 1, true)202 return &st, reflect.Value{}203}204func anyStruct(model any, expectedFields StructFields, strict bool) *tdStruct {205 st, vmodel := newStruct(model, strict)206 if st.err != nil {207 return st208 }209 st.expectedFields = make([]fieldInfo, 0, len(expectedFields))210 checkedFields := make(map[string]bool, len(expectedFields))211 var matchers fieldMatcherSlice //nolint: prealloc212 // Check that all given fields are available in model213 stType := st.expectedType214 for fieldName, expectedValue := range expectedFields {215 field, found := stType.FieldByName(fieldName)216 if found {217 st.addExpectedValue(field, expectedValue, "")218 if st.err != nil {219 return st220 }221 checkedFields[fieldName] = false222 continue223 }224 // overwrite model field: ">fieldName", "> fieldName"225 if strings.HasPrefix(fieldName, ">") {226 name := strings.TrimSpace(fieldName[1:])227 field, found = stType.FieldByName(name)228 if !found {229 st.err = ctxerr.OpBad(st.location.Func,230 "struct %s has no field %q (from %q)", stType, name, fieldName)231 return st232 }233 st.addExpectedValue(234 field, expectedValue,235 fmt.Sprintf(" (from %q)", fieldName),236 )237 if st.err != nil {238 return st239 }240 checkedFields[name] = true241 continue242 }243 // matcher: "=~At$", "!~At$", "=*At", "!*At"244 matcher, err := newFieldMatcher(fieldName, expectedValue)245 if err != nil {246 if err == errNotAMatcher {247 st.err = ctxerr.OpBad(st.location.Func,248 "struct %s has no field %q", stType, fieldName)249 } else {250 st.err = ctxerr.OpBad(st.location.Func, err.Error())251 }252 return st253 }254 matchers = append(matchers, matcher)255 }256 // Get all field names257 allFields := map[string]struct{}{}258 stType.FieldByNameFunc(func(fieldName string) bool {...
td_struct_private_test.go
Source:td_struct_private_test.go
...61 test.EqualInt(t, len(sfs), 1)62 test.EqualInt(t, sfs["1\t=~\tpipo"].(int), 3)63}64func TestFieldMatcher(t *testing.T) {65 _, err := newFieldMatcher("pipo", 123)66 if test.Error(t, err) {67 if err != errNotAMatcher {68 t.Errorf("got %q, but %q was expected", err, errNotAMatcher)69 }70 }71 for _, tst := range []struct {72 name string73 order int74 match bool75 }{76 // Regexp77 {name: "=~.*", match: true},78 {name: "=~bc", match: true},79 {name: "=~3$", match: true},80 {name: "!~^b", match: false},81 {name: "134=~bc", match: true, order: 134},82 {name: "134 =~ bc", match: true, order: 134},83 {name: " 134 =~ bc", match: true, order: 134},84 // Shell pattern85 {name: "=*", match: true},86 {name: "=*bc*", match: true},87 {name: "=*3", match: true},88 {name: "!b*", match: false},89 {name: "134=*", match: true, order: 134},90 {name: "134 = *", match: true, order: 134},91 {name: " 134 = *", match: true, order: 134},92 } {93 fm, err := newFieldMatcher(tst.name, 123)94 test.NoError(t, err, tst.name)95 test.EqualStr(t, fm.name, tst.name, tst.name)96 test.EqualInt(t, fm.expected.(int), 123, tst.name)97 test.EqualInt(t, fm.order, tst.order, tst.name)98 test.EqualBool(t, fm.ok, strings.ContainsRune(tst.name, '='), tst.name)99 if test.IsTrue(t, fm.match != nil, tst.name) {100 ok, err := fm.match("abc123")101 test.NoError(t, err, tst.name)102 test.EqualBool(t, ok, tst.match)103 }104 }105 _, err = newFieldMatcher("=~bad(*", 123)106 if test.Error(t, err) {107 test.IsTrue(t, strings.HasPrefix(err.Error(), "bad regexp field `=~bad(*`: "))108 }109}...
newFieldMatcher
Using AI Code Generation
1import (2type Td struct {3 FieldMatcher func(v interface{}) bool4}5func (td *Td) newFieldMatcher() {6 td.FieldMatcher = func(v interface{}) bool {7 return reflect.ValueOf(v).String() == "test"8 }9}10func main() {11 td := &Td{}12 td.newFieldMatcher()13 fmt.Println(td.FieldMatcher("test"))14 fmt.Println(td.FieldMatcher("not test"))15}16import (17type Td struct {18 FieldMatcher func(v interface{}) bool19}20type FieldMatcher interface {21 Matches(v interface{}) bool22}23func (td *Td) newFieldMatcher() {24 td.FieldMatcher = func(v interface{}) bool {25 return reflect.ValueOf(v).String() == "test"26 }27}28func (td *Td) newFieldMatcherInterface() FieldMatcher {29 return &Td{30 FieldMatcher: func(v interface{}) bool {31 return reflect.ValueOf(v).String() == "test"32 },33 }34}35func main() {36 td := &Td{}37 td.newFieldMatcher()38 fmt.Println(td.FieldMatcher("test"))39 fmt.Println(td.FieldMatcher("not test"))40 td2 := td.newFieldMatcherInterface()41 fmt.Println(td2.Matches("test"))42 fmt.Println(td2.Matches("not test"))43}44import (45type Td struct {46 FieldMatcher func(v interface{}) bool47}48type FieldMatcher interface {49 Matches(v interface{}) bool50}
newFieldMatcher
Using AI Code Generation
1import (2type td struct {3 values []interface{}4}5func (t td) String() string {6 return fmt.Sprintf("%s %s", t.name, t.kind)7}8func newFieldMatcher(name string, kind reflect.Kind, values ...interface{}) td {9 return td{name, kind, values}10}11func main() {12 fm := newFieldMatcher("Name", reflect.String, "test")13 fmt.Println(fm)14}15import (16type td struct {17 values []interface{}18}19func (t td) String() string {20 return fmt.Sprintf("%s %s", t.name, t.kind)21}22func newFieldMatcher(name string, kind reflect.Kind, values ...interface{}) td {23 return td{name, kind, values}24}25func main() {26 fm := newFieldMatcher("Name", reflect.String, "test")27 fmt.Println(fm)28}29import (30type td struct {31 values []interface{}32}33func (t td) String() string {34 return fmt.Sprintf("%s %s", t.name, t.kind)35}36func newFieldMatcher(name string, kind reflect.Kind, values ...interface{}) td {37 return td{name, kind, values}38}39func main() {40 fm := newFieldMatcher("Name", reflect.String, "test")41 fmt.Println(fm)42}43import (44type td struct {45 values []interface{}46}47func (t td) String() string {48 return fmt.Sprintf("%s %s", t.name, t.kind)49}50func newFieldMatcher(name string, kind reflect.Kind, values ...interface{}) td {51 return td{name, kind, values}52}53func main() {
newFieldMatcher
Using AI Code Generation
1import (2func main() {3 t = reflect.TypeOf(1)4 f = t.Field(0)5 fmt.Println(td.newFieldMatcher(f))6}7import (8func main() {9 t = reflect.TypeOf(1)10 f = t.Field(0)11 fmt.Println(td.newFieldMatcher(f))12}13import (14func main() {
newFieldMatcher
Using AI Code Generation
1td := new(td)2td.newFieldMatcher("name", "string", "abc")3td.newFieldMatcher("age", "int", "20")4td.newFieldMatcher("salary", "float", "2500.50")5td := new(td)6td.newFieldMatcher("name", "string", "abc")7td.newFieldMatcher("age", "int", "20")8td.newFieldMatcher("salary", "float", "2500.50")9td := new(td)10td.newFieldMatcher("name", "string", "abc")11td.newFieldMatcher("age", "int", "20")12td.newFieldMatcher("salary", "float", "2500.50")13td := new(td)14td.newFieldMatcher("name", "string", "abc")15td.newFieldMatcher("age", "int", "20")16td.newFieldMatcher("salary", "float", "2500.50")17td := new(td)18td.newFieldMatcher("name", "string", "abc")19td.newFieldMatcher("age", "int", "20")20td.newFieldMatcher("salary", "float", "2500.50")21td := new(td)22td.newFieldMatcher("name", "string", "abc")23td.newFieldMatcher("age", "int", "20")24td.newFieldMatcher("salary", "float", "2500.50")25td := new(td)26td.newFieldMatcher("name", "string", "abc")27td.newFieldMatcher("age", "int", "20")28td.newFieldMatcher("salary", "float", "2500.50")29td := new(td)30td.newFieldMatcher("name", "string", "abc")31td.newFieldMatcher("age", "int", "20")32td.newFieldMatcher("
newFieldMatcher
Using AI Code Generation
1newFieldMatcher("hello")2newFieldMatcher("hello")3newFieldMatcher("hello")4newFieldMatcher("hello")5newFieldMatcher("hello")6newFieldMatcher("hello")7newFieldMatcher("hello")8newFieldMatcher("hello")9newFieldMatcher("hello")10newFieldMatcher("hello")
newFieldMatcher
Using AI Code Generation
1import (2type td struct {3}4type person struct {5}6func (t *td) newFieldMatcher(v reflect.Value) (bool, error) {7 if v.Kind() != reflect.Struct {8 }9 p := v.Interface().(person)10 if p.name != "Bob" {11 return false, fmt.Errorf("name is not Bob")12 }13 if p.age != 20 {14 return false, fmt.Errorf("age is not 20")15 }16}17func main() {18 t := &td{}19 p := person{name: "Bob", age: 20}20 v := reflect.ValueOf(p)21 ok, err := t.newFieldMatcher(v)22 if err != nil {23 fmt.Println(err)24 }25 fmt.Println(ok)26}27import (28type td struct {29}30type person struct {31}32func (t *td) newFieldMatcher(v reflect.Value) (bool, error) {33 if v.Kind() != reflect.Struct {34 }35 p := v.Interface().(person)36 if p.name != "Bob" {37 return false, fmt.Errorf("name is not Bob")38 }39 if p.age != 20 {40 return false, fmt.Errorf("age is not 20")41 }42}43func main() {44 t := &td{}45 p := person{name: "Bob", age: 20}46 v := reflect.ValueOf(p)47 ok, err := t.newFieldMatcher(v)48 if err != nil {49 fmt.Println(err)50 }51 fmt.Println(ok)52}53import (
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!