Best Go-testdeep code snippet using util.JSONPointer
settings_profile.go
Source:settings_profile.go
1package viewmodels2import (3 "github.com/iawaknahc/jsonschema/pkg/jsonpointer"4 "github.com/authgear/authgear-server/pkg/api/model"5 "github.com/authgear/authgear-server/pkg/lib/authn/identity"6 "github.com/authgear/authgear-server/pkg/lib/authn/stdattrs"7 "github.com/authgear/authgear-server/pkg/lib/config"8 "github.com/authgear/authgear-server/pkg/util/accesscontrol"9 "github.com/authgear/authgear-server/pkg/util/clock"10 "github.com/authgear/authgear-server/pkg/util/labelutil"11 "github.com/authgear/authgear-server/pkg/util/territoryutil"12 "github.com/authgear/authgear-server/pkg/util/tzutil"13)14type CustomAttribute struct {15 Value interface{}16 Label string17 EnumValueLabel string18 Pointer string19 Type string20 IsEditable bool21 Minimum *float6422 Maximum *float6423 Enum []CustomAttributeEnum24}25type CustomAttributeEnum struct {26 Value string27 Label string28}29type SettingsProfileViewModel struct {30 FormattedName string31 EndUserAccountID string32 FormattedNames string33 Today string34 Timezones []tzutil.Timezone35 Alpha2 []string36 Languages []string37 Emails []string38 PhoneNumbers []string39 PreferredUsernames []string40 IsReadable func(jsonpointer string) bool41 IsEditable func(jsonpointer string) bool42 GetCustomAttributeByPointer func(jsonpointer string) *CustomAttribute43 IsStandardAttributesAllHidden bool44 Name string45 GivenName string46 FamilyName string47 MiddleName string48 Nickname string49 Picture string50 Profile string51 Website string52 Email string53 PhoneNumber string54 PreferredUsername string55 Gender string56 Birthdate string57 Zoneinfo string58 ZoneinfoTimezone *tzutil.Timezone59 Locale string60 AddressStreetAddress string61 AddressLocality string62 AddressRegion string63 AddressPostalCode string64 AddressCountry string65 CustomAttributes []CustomAttribute66}67type SettingsProfileUserService interface {68 Get(userID string, role accesscontrol.Role) (*model.User, error)69}70type SettingsProfileIdentityService interface {71 ListByUser(userID string) ([]*identity.Info, error)72}73type SettingsProfileViewModeler struct {74 Localization *config.LocalizationConfig75 UserProfileConfig *config.UserProfileConfig76 Users SettingsProfileUserService77 Identities SettingsProfileIdentityService78 Clock clock.Clock79}80func (m *SettingsProfileViewModeler) ViewModel(userID string) (*SettingsProfileViewModel, error) {81 var emails []string82 var phoneNumbers []string83 var preferredUsernames []string84 identities, err := m.Identities.ListByUser(userID)85 if err != nil {86 return nil, err87 }88 for _, iden := range identities {89 standardClaims := iden.IdentityAwareStandardClaims()90 if email, ok := standardClaims[model.ClaimEmail]; ok && email != "" {91 emails = append(emails, email)92 }93 if phoneNumber, ok := standardClaims[model.ClaimPhoneNumber]; ok && phoneNumber != "" {94 phoneNumbers = append(phoneNumbers, phoneNumber)95 }96 if preferredUsername, ok := standardClaims[model.ClaimPreferredUsername]; ok && preferredUsername != "" {97 preferredUsernames = append(preferredUsernames, preferredUsername)98 }99 }100 user, err := m.Users.Get(userID, config.RoleEndUser)101 if err != nil {102 return nil, err103 }104 stdAttrs := user.StandardAttributes105 str := func(key string) string {106 value, _ := stdAttrs[key].(string)107 return value108 }109 addressStr := func(key string) string {110 address, ok := stdAttrs[stdattrs.Address].(map[string]interface{})111 if !ok {112 return ""113 }114 value, _ := address[key].(string)115 return value116 }117 now := m.Clock.NowUTC()118 timezones, err := tzutil.List(now)119 if err != nil {120 return nil, err121 }122 accessControl := m.UserProfileConfig.StandardAttributes.GetAccessControl().MergedWith(123 m.UserProfileConfig.CustomAttributes.GetAccessControl(),124 )125 isReadable := func(jsonpointer string) bool {126 level := accessControl.GetLevel(127 accesscontrol.Subject(jsonpointer),128 config.RoleEndUser,129 config.AccessControlLevelHidden,130 )131 return level >= config.AccessControlLevelReadonly132 }133 isEditable := func(jsonpointer string) bool {134 level := accessControl.GetLevel(135 accesscontrol.Subject(jsonpointer),136 config.RoleEndUser,137 config.AccessControlLevelHidden,138 )139 return level == config.AccessControlLevelReadwrite140 }141 zoneinfo := str(stdattrs.Zoneinfo)142 var zoneinfoTimezone *tzutil.Timezone143 if zoneinfo != "" {144 zoneinfoTimezone, err = tzutil.AsTimezone(zoneinfo, now)145 if err != nil {146 return nil, err147 }148 }149 var customAttrs []CustomAttribute150 for _, c := range m.UserProfileConfig.CustomAttributes.Attributes {151 level := accessControl.GetLevel(152 accesscontrol.Subject(c.Pointer),153 config.RoleEndUser,154 config.AccessControlLevelHidden,155 )156 if level >= config.AccessControlLevelReadonly {157 ptr, err := jsonpointer.Parse(c.Pointer)158 if err != nil {159 return nil, err160 }161 var value interface{}162 if v, err := ptr.Traverse(user.CustomAttributes); err == nil {163 value = v164 }165 var enumValueLabel string166 var enum []CustomAttributeEnum167 if c.Type == config.CustomAttributeTypeEnum {168 if str, ok := value.(string); ok {169 enumValueLabel = labelutil.Label(str)170 }171 for _, variant := range c.Enum {172 enum = append(enum, CustomAttributeEnum{173 Value: variant,174 Label: labelutil.Label(variant),175 })176 }177 }178 customAttrs = append(customAttrs, CustomAttribute{179 Value: value,180 Label: labelutil.Label(ptr[0]),181 EnumValueLabel: enumValueLabel,182 Pointer: c.Pointer,183 Type: string(c.Type),184 IsEditable: level >= config.AccessControlLevelReadwrite,185 Minimum: c.Minimum,186 Maximum: c.Maximum,187 Enum: enum,188 })189 }190 }191 getCustomAttributeByPointer := func(jsonpointer string) *CustomAttribute {192 for _, ca := range customAttrs {193 if ca.Pointer == jsonpointer {194 out := ca195 return &out196 }197 }198 return nil199 }200 viewModel := &SettingsProfileViewModel{201 FormattedName: stdattrs.T(stdAttrs).FormattedName(),202 EndUserAccountID: user.EndUserAccountID(),203 FormattedNames: stdattrs.T(stdAttrs).FormattedNames(),204 Today: now.Format("2006-01-02"),205 Timezones: timezones,206 Alpha2: territoryutil.Alpha2,207 Languages: m.Localization.SupportedLanguages,208 Emails: emails,209 PhoneNumbers: phoneNumbers,210 PreferredUsernames: preferredUsernames,211 IsReadable: isReadable,212 IsEditable: isEditable,213 GetCustomAttributeByPointer: getCustomAttributeByPointer,214 IsStandardAttributesAllHidden: m.UserProfileConfig.StandardAttributes.IsEndUserAllHidden(),215 Name: str(stdattrs.Name),216 GivenName: str(stdattrs.GivenName),217 FamilyName: str(stdattrs.FamilyName),218 MiddleName: str(stdattrs.MiddleName),219 Nickname: str(stdattrs.Nickname),220 Picture: str(stdattrs.Picture),221 Profile: str(stdattrs.Profile),222 Website: str(stdattrs.Website),223 Email: str(stdattrs.Email),224 PhoneNumber: str(stdattrs.PhoneNumber),225 PreferredUsername: str(stdattrs.PreferredUsername),226 Gender: str(stdattrs.Gender),227 Birthdate: str(stdattrs.Birthdate),228 Zoneinfo: zoneinfo,229 ZoneinfoTimezone: zoneinfoTimezone,230 Locale: str(stdattrs.Locale),231 AddressStreetAddress: addressStr(stdattrs.StreetAddress),232 AddressLocality: addressStr(stdattrs.Locality),233 AddressRegion: addressStr(stdattrs.Region),234 AddressPostalCode: addressStr(stdattrs.PostalCode),235 AddressCountry: addressStr(stdattrs.Country),236 CustomAttributes: customAttrs,237 }238 return viewModel, nil239}...
td_json_pointer.go
Source:td_json_pointer.go
...10 "strings"11 "github.com/maxatome/go-testdeep/internal/ctxerr"12 "github.com/maxatome/go-testdeep/internal/util"13)14type tdJSONPointer struct {15 tdSmugglerBase16 pointer string17}18var _ TestDeep = &tdJSONPointer{}19// summary(JSONPointer): compares against JSON representation using a20// JSON pointer21// input(JSONPointer): nil,bool,str,int,float,array,slice,map,struct,ptr22// JSONPointer is a smuggler operator. It takes the JSON23// representation of data, gets the value corresponding to the JSON24// pointer ptr (as [RFC 6901] specifies it) and compares it to25// expectedValue.26//27// [Lax] mode is automatically enabled to simplify numeric tests.28//29// JSONPointer does its best to convert back the JSON pointed data to30// the type of expectedValue or to the type behind the31// expectedValue operator, if it is an operator. Allowing to do32// things like:33//34// type Item struct {35// Val int `json:"val"`36// Next *Item `json:"next"`37// }38// got := Item{Val: 1, Next: &Item{Val: 2, Next: &Item{Val: 3}}}39//40// td.Cmp(t, got, td.JSONPointer("/next/next", Item{Val: 3}))41// td.Cmp(t, got, td.JSONPointer("/next/next", &Item{Val: 3}))42// td.Cmp(t,43// got,44// td.JSONPointer("/next/next",45// td.Struct(Item{}, td.StructFields{"Val": td.Gte(3)})),46// )47//48// got := map[string]int64{"zzz": 42} // 42 is int64 here49// td.Cmp(t, got, td.JSONPointer("/zzz", 42))50// td.Cmp(t, got, td.JSONPointer("/zzz", td.Between(40, 45)))51//52// Of course, it does this conversion only if the expected type can be53// guessed. In the case the conversion cannot occur, data is compared54// as is, in its freshly unmarshaled JSON form (so as bool, float64,55// string, []any, map[string]any or simply nil).56//57// Note that as any [TestDeep] operator can be used as expectedValue,58// [JSON] operator works out of the box:59//60// got := json.RawMessage(`{"foo":{"bar": {"zip": true}}}`)61// td.Cmp(t, got, td.JSONPointer("/foo/bar", td.JSON(`{"zip": true}`)))62//63// It can be used with structs lacking json tags. In this case, fields64// names have to be used in JSON pointer:65//66// type Item struct {67// Val int68// Next *Item69// }70// got := Item{Val: 1, Next: &Item{Val: 2, Next: &Item{Val: 3}}}71//72// td.Cmp(t, got, td.JSONPointer("/Next/Next", Item{Val: 3}))73//74// Contrary to [Smuggle] operator and its fields-path feature, only75// public fields can be followed, as private ones are never (un)marshaled.76//77// There is no JSONHas nor JSONHasnt operators to only check a JSON78// pointer exists or not, but they can easily be emulated:79//80// JSONHas := func(pointer string) td.TestDeep {81// return td.JSONPointer(pointer, td.Ignore())82// }83//84// JSONHasnt := func(pointer string) td.TestDeep {85// return td.Not(td.JSONPointer(pointer, td.Ignore()))86// }87//88// TypeBehind method always returns nil as the expected type cannot be89// guessed from a JSON pointer.90//91// See also [JSON], [SubJSONOf], [SuperJSONOf] and [Smuggle].92//93// [RFC 6901]: https://tools.ietf.org/html/rfc690194func JSONPointer(ptr string, expectedValue any) TestDeep {95 p := tdJSONPointer{96 tdSmugglerBase: newSmugglerBase(expectedValue),97 pointer: ptr,98 }99 if !strings.HasPrefix(ptr, "/") && ptr != "" {100 p.err = ctxerr.OpBad("JSONPointer", "bad JSON pointer %q", ptr)101 return &p102 }103 if !p.isTestDeeper {104 p.expectedValue = reflect.ValueOf(expectedValue)105 }106 return &p107}108func (p *tdJSONPointer) Match(ctx ctxerr.Context, got reflect.Value) *ctxerr.Error {109 if p.err != nil {110 return ctx.CollectError(p.err)111 }112 vgot, eErr := jsonify(ctx, got)113 if eErr != nil {114 return ctx.CollectError(eErr)115 }116 vgot, err := util.JSONPointer(vgot, p.pointer)117 if err != nil {118 if ctx.BooleanError {119 return ctxerr.BooleanError120 }121 pErr := err.(*util.JSONPointerError)122 ctx = jsonPointerContext(ctx, pErr.Pointer)123 return ctx.CollectError(&ctxerr.Error{124 Message: "cannot retrieve value via JSON pointer",125 Summary: ctxerr.NewSummary(pErr.Type),126 })127 }128 // Here, vgot type is either a bool, float64, string,129 // []any, a map[string]any or simply nil130 ctx = jsonPointerContext(ctx, p.pointer)131 ctx.BeLax = true132 return p.jsonValueEqual(ctx, vgot)133}134func (p *tdJSONPointer) String() string {135 if p.err != nil {136 return p.stringError()137 }138 var expected string139 switch {140 case p.isTestDeeper:141 expected = p.expectedValue.Interface().(TestDeep).String()142 case p.expectedValue.IsValid():143 expected = util.ToString(p.expectedValue.Interface())144 default:145 expected = "nil"146 }147 return fmt.Sprintf("JSONPointer(%s, %s)", p.pointer, expected)148}149func (p *tdJSONPointer) HandleInvalid() bool {150 return true151}152func jsonPointerContext(ctx ctxerr.Context, pointer string) ctxerr.Context {153 return ctx.AddCustomLevel(".JSONPointer<" + pointer + ">")154}...
json_pointer.go
Source:json_pointer.go
...9 "strings"10)11var jsonPointerEsc = strings.NewReplacer("~0", "~", "~1", "/")12const (13 ErrJSONPointerInvalid = "invalid JSON pointer"14 ErrJSONPointerKeyNotFound = "key not found"15 ErrJSONPointerArrayNoIndex = "array but not an index in JSON pointer"16 ErrJSONPointerArrayOutOfRange = "out of array range"17 ErrJSONPointerArrayBadType = "not a map nor an array"18)19type JSONPointerError struct {20 Type string21 Pointer string22}23func (e *JSONPointerError) Error() string {24 if e.Pointer == "" {25 return e.Type26 }27 return e.Type + " @" + e.Pointer28}29// JSONPointer returns the value corresponding to JSON pointer30// pointer in v as [RFC 6901] specifies it. To be searched, v has31// to contains map[string]any or []any values. All32// other types fail to be searched.33//34// [RFC 6901]: https://tools.ietf.org/html/rfc690135func JSONPointer(v any, pointer string) (any, error) {36 if !strings.HasPrefix(pointer, "/") {37 if pointer == "" {38 return v, nil39 }40 return nil, &JSONPointerError{Type: ErrJSONPointerInvalid}41 }42 pos := 043 for _, part := range strings.Split(pointer[1:], "/") {44 pos += 1 + len(part)45 part = jsonPointerEsc.Replace(part)46 switch tv := v.(type) {47 case map[string]any:48 var ok bool49 v, ok = tv[part]50 if !ok {51 return nil, &JSONPointerError{52 Type: ErrJSONPointerKeyNotFound,53 Pointer: pointer[:pos],54 }55 }56 case []any:57 i, err := strconv.Atoi(part)58 if err != nil || i < 0 {59 return nil, &JSONPointerError{60 Type: ErrJSONPointerArrayNoIndex,61 Pointer: pointer[:pos],62 }63 }64 if i >= len(tv) {65 return nil, &JSONPointerError{66 Type: ErrJSONPointerArrayOutOfRange,67 Pointer: pointer[:pos],68 }69 }70 v = tv[i]71 default:72 return nil, &JSONPointerError{73 Type: ErrJSONPointerArrayBadType,74 Pointer: pointer[:pos],75 }76 }77 }78 return v, nil79}...
JSONPointer
Using AI Code Generation
1import (2func main() {3 data := []byte(`{"name":{"first":"Janet","last":"Prichard"},"age":47}`)4 value, dataType, offset, err := jsonparser.Get(data, "name", "first")5 if err != nil {6 fmt.Println(err)7 }8 fmt.Println("value:", string(value), "dataType:", dataType, "offset:", offset)9}10import (11func main() {12 data := []byte(`{"name":{"first":"Janet","last":"Prichard"},"age":47}`)13 value, dataType, offset, err := jsonparser.JSONPointer(data, "/name/first")14 if err != nil {15 fmt.Println(err)16 }17 fmt.Println("value:", string(value), "dataType:", dataType, "offset:", offset)18}19import (
JSONPointer
Using AI Code Generation
1import (2func main() {3 data := []byte(`{"name":"Wednesday","age":6,"parents":["Gomez","Morticia"]}`)4 value, dataType, _, err := jsonparser.Get(data, "name")5 if err != nil {6 fmt.Println(err)7 }8 fmt.Printf("Value: %s9 fmt.Printf("Data type: %s10 value, dataType, _, err = jsonparser.Get(data, "age")11 if err != nil {12 fmt.Println(err)13 }14 fmt.Printf("Value: %s15 fmt.Printf("Data type: %s16 value, dataType, _, err = jsonparser.Get(data, "parents")17 if err != nil {18 fmt.Println(err)19 }20 fmt.Printf("Value: %s21 fmt.Printf("Data type: %s22}23{24}
JSONPointer
Using AI Code Generation
1import (2func main() {3 data := []byte(`{"name":"Wednesday","age":6,"parents":["Gomez","Morticia"]}`)4 value, dataType, offset, err := jsonparser.Get(data, "name")5 if err != nil {6 fmt.Println(err)7 }8 fmt.Println(string(value), dataType, offset)9}10import (11func main() {12 data := []byte(`{"name":"Wednesday","age":6,"parents":["Gomez","Morticia"]}`)13 value, dataType, offset, err := jsonparser.JSONPointer(data, "/name")14 if err != nil {15 fmt.Println(err)16 }17 fmt.Println(string(value), dataType, offset)18}
JSONPointer
Using AI Code Generation
1import (2func main() {3 json := `{4 "foo": {5 "bar": {6 }7 }8 }`9 pointer, _ := gojsonpointer.NewJsonPointer("/foo/bar")10 _, _, _, err := pointer.Get([]byte(json))11 if err != nil {12 fmt.Println(err)13 }14}
JSONPointer
Using AI Code Generation
1import (2func main() {3 data := []byte(`{"Name":"John", "Age":30, "Address":{"City":"New York","State":"NY"}}`)4 value, dataType, offset, err := jsonparser.Get(data, "Address", "City")5 if err != nil {6 fmt.Println(err)7 }8 fmt.Println(string(value), dataType, offset)9}
JSONPointer
Using AI Code Generation
1import (2func main() {3 jsondata := `{"name":"John","age":30,"cars":[{"name":"Ford","models":["Fiesta","Focus","Mustang"]},{"name":"BMW","models":["320","X3","X5"]},{"name":"Fiat","models":["500","Panda"]}]}`4 jsonPointer, _ := gojsonpointer.NewJsonPointer("/cars/0/models/0")5 result, _, err := jsonPointer.Get([]byte(jsondata))6 if err != nil {7 fmt.Println("err:", err)8 }9 fmt.Println("result:", result)10}
JSONPointer
Using AI Code Generation
1import (2func main() {3 var s string = `{"foo": [1, 2, 3, 4, 5], "bar": "baz"}`4 var s1 string = `{"foo": [1, 2, 3, 4, 5], "bar": "baz"}`5 var s2 string = `{"foo": [1, 2, 3, 4, 5], "bar": "baz"}`6 var s3 string = `{"foo": [1, 2, 3, 4, 5], "bar": "baz"}`7 var s4 string = `{"foo": [1, 2, 3, 4, 5], "bar": "baz"}`8 var s5 string = `{"foo": [1, 2, 3, 4, 5], "bar": "baz"}`9 var s6 string = `{"foo": [1, 2, 3, 4, 5], "bar": "baz"}`10 var s7 string = `{"foo": [1, 2, 3, 4, 5], "bar": "baz"}`11 var s8 string = `{"foo": [1, 2, 3, 4, 5], "bar": "baz"}`12 var s9 string = `{"foo": [1, 2, 3, 4, 5], "bar": "baz"}`13 var s10 string = `{"foo": [1, 2, 3, 4, 5], "bar": "baz"}`14 var s11 string = `{"foo": [1, 2, 3, 4, 5], "bar": "baz"}`15 var s12 string = `{"foo": [1, 2, 3, 4, 5], "bar": "baz"}`16 var s13 string = `{"foo": [1, 2, 3, 4, 5], "bar": "baz"}`17 var s14 string = `{"foo": [1, 2, 3, 4, 5], "bar": "baz"}`
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!!