How to use SubjectID method of internal Package

Best Ginkgo code snippet using internal.SubjectID

definitions.go

Source:definitions.go Github

copy

Full Screen

...27 RelationCollection struct {28 protoRelations []*rts.RelationTuple29 internalRelations []*InternalRelationTuple30 }31 SubjectID struct {32 ID string `json:"id"`33 }34)35type RelationQuery struct {36 // Namespace of the Relation Tuple37 Namespace string `json:"namespace"`38 // Object of the Relation Tuple39 Object string `json:"object"`40 // Relation of the Relation Tuple41 Relation string `json:"relation"`42 // SubjectID of the Relation Tuple43 //44 // Either SubjectSet or SubjectID can be provided.45 SubjectID *string `json:"subject_id,omitempty"`46 // SubjectSet of the Relation Tuple47 //48 // Either SubjectSet or SubjectID can be provided.49 //50 // swagger:allOf51 SubjectSet *SubjectSet `json:"subject_set,omitempty"`52}53// swagger:ignore54type TupleData interface {55 // swagger:ignore56 GetSubject() *rts.Subject57 GetObject() string58 GetNamespace() string59 GetRelation() string60}61// swagger:model subject62type Subject interface {63 // swagger:ignore64 String() string65 // swagger:ignore66 FromString(string) (Subject, error)67 // swagger:ignore68 Equals(interface{}) bool69 // swagger:ignore70 SubjectID() *string71 // swagger:ignore72 SubjectSet() *SubjectSet73 // swagger:ignore74 ToProto() *rts.Subject75}76// swagger:ignore77type InternalRelationTuple struct {78 Namespace string `json:"namespace"`79 Object string `json:"object"`80 Relation string `json:"relation"`81 Subject Subject `json:"subject"`82}83// swagger:parameters getExpand84type SubjectSet struct {85 // Namespace of the Subject Set86 //87 // required: true88 Namespace string `json:"namespace"`89 // Object of the Subject Set90 //91 // required: true92 Object string `json:"object"`93 // Relation of the Subject Set94 //95 // required: true96 Relation string `json:"relation"`97}98var (99 _, _ Subject = &SubjectID{}, &SubjectSet{}100 ErrMalformedInput = herodot.ErrBadRequest.WithError("malformed string input")101 ErrNilSubject = herodot.ErrBadRequest.WithError("subject is not allowed to be nil")102 ErrDuplicateSubject = herodot.ErrBadRequest.WithError("exactly one of subject_set or subject_id has to be provided")103 ErrDroppedSubjectKey = herodot.ErrBadRequest.WithDebug(`provide "subject_id" or "subject_set.*"; support for "subject" was dropped`)104 ErrIncompleteSubject = herodot.ErrBadRequest.WithError(`incomplete subject, provide "subject_id" or a complete "subject_set.*"`)105)106// swagger:enum patchAction107type patchAction string108const (109 ActionInsert patchAction = "insert"110 ActionDelete patchAction = "delete"111)112func SubjectFromString(s string) (Subject, error) {113 if strings.Contains(s, "#") {114 return (&SubjectSet{}).FromString(s)115 }116 return (&SubjectID{}).FromString(s)117}118// swagger:ignore119func SubjectFromProto(gs *rts.Subject) (Subject, error) {120 switch s := gs.GetRef().(type) {121 case nil:122 return nil, errors.WithStack(ErrNilSubject)123 case *rts.Subject_Id:124 return &SubjectID{125 ID: s.Id,126 }, nil127 case *rts.Subject_Set:128 return &SubjectSet{129 Namespace: s.Set.Namespace,130 Object: s.Set.Object,131 Relation: s.Set.Relation,132 }, nil133 }134 return nil, errors.WithStack(ErrNilSubject)135}136func (s *SubjectID) String() string {137 return s.ID138}139func (s *SubjectSet) String() string {140 return fmt.Sprintf("%s:%s#%s", s.Namespace, s.Object, s.Relation)141}142func (s *SubjectID) FromString(str string) (Subject, error) {143 s.ID = str144 return s, nil145}146func (s *SubjectSet) FromString(str string) (Subject, error) {147 parts := strings.Split(str, "#")148 if len(parts) != 2 {149 return nil, errors.WithStack(ErrMalformedInput)150 }151 innerParts := strings.Split(parts[0], ":")152 if len(innerParts) != 2 {153 return nil, errors.WithStack(ErrMalformedInput)154 }155 s.Namespace = innerParts[0]156 s.Object = innerParts[1]157 s.Relation = parts[1]158 return s, nil159}160func (s *SubjectSet) FromURLQuery(values url.Values) *SubjectSet {161 if s == nil {162 s = &SubjectSet{}163 }164 s.Namespace = values.Get("namespace")165 s.Relation = values.Get("relation")166 s.Object = values.Get("object")167 return s168}169func (s *SubjectSet) ToURLQuery() url.Values {170 return url.Values{171 "namespace": []string{s.Namespace},172 "object": []string{s.Object},173 "relation": []string{s.Relation},174 }175}176func (s *SubjectSet) SubjectID() *string {177 return nil178}179func (s *SubjectSet) SubjectSet() *SubjectSet {180 return s181}182func (s *SubjectID) SubjectID() *string {183 return &s.ID184}185func (s *SubjectID) SubjectSet() *SubjectSet {186 return nil187}188// swagger:ignore189func (s *SubjectID) ToProto() *rts.Subject {190 return &rts.Subject{191 Ref: &rts.Subject_Id{192 Id: s.ID,193 },194 }195}196// swagger:ignore197func (s *SubjectSet) ToProto() *rts.Subject {198 return &rts.Subject{199 Ref: &rts.Subject_Set{200 Set: &rts.SubjectSet{201 Namespace: s.Namespace,202 Object: s.Object,203 Relation: s.Relation,204 },205 },206 }207}208func (s *SubjectID) Equals(v interface{}) bool {209 uv, ok := v.(*SubjectID)210 if !ok {211 return false212 }213 return uv.ID == s.ID214}215func (s *SubjectSet) Equals(v interface{}) bool {216 uv, ok := v.(*SubjectSet)217 if !ok {218 return false219 }220 return uv.Relation == s.Relation && uv.Object == s.Object && uv.Namespace == s.Namespace221}222func (s SubjectID) MarshalJSON() ([]byte, error) {223 return json.Marshal(s.ID)224}225func (r *InternalRelationTuple) String() string {226 return fmt.Sprintf("%s:%s#%s@%s", r.Namespace, r.Object, r.Relation, r.Subject)227}228func (r *InternalRelationTuple) FromString(s string) (*InternalRelationTuple, error) {229 parts := strings.SplitN(s, ":", 2)230 if len(parts) != 2 {231 return nil, errors.Wrap(ErrMalformedInput, "expected input to contain ':'")232 }233 r.Namespace = parts[0]234 parts = strings.SplitN(parts[1], "#", 2)235 if len(parts) != 2 {236 return nil, errors.Wrap(ErrMalformedInput, "expected input to contain '#'")237 }238 r.Object = parts[0]239 parts = strings.SplitN(parts[1], "@", 2)240 if len(parts) != 2 {241 return nil, errors.Wrap(ErrMalformedInput, "expected input to contain '@'")242 }243 r.Relation = parts[0]244 // remove optional brackets around the subject set245 sub := strings.Trim(parts[1], "()")246 var err error247 r.Subject, err = SubjectFromString(sub)248 if err != nil {249 return nil, err250 }251 return r, nil252}253func (r *InternalRelationTuple) DeriveSubject() *SubjectSet {254 return &SubjectSet{255 Namespace: r.Namespace,256 Object: r.Object,257 Relation: r.Relation,258 }259}260func (r *InternalRelationTuple) UnmarshalJSON(raw []byte) error {261 var rq RelationQuery262 if err := json.Unmarshal(raw, &rq); err != nil {263 return errors.WithStack(err)264 }265 if rq.SubjectID != nil && rq.SubjectSet != nil {266 return errors.WithStack(ErrDuplicateSubject)267 } else if rq.SubjectID == nil && rq.SubjectSet == nil {268 return errors.WithStack(ErrNilSubject)269 }270 r.Namespace = rq.Namespace271 r.Object = rq.Object272 r.Relation = rq.Relation273 // validation was done before already274 if rq.SubjectID == nil {275 r.Subject = rq.SubjectSet276 } else {277 r.Subject = &SubjectID{ID: *rq.SubjectID}278 }279 return nil280}281func (r *InternalRelationTuple) MarshalJSON() ([]byte, error) {282 return json.Marshal(r.ToQuery())283}284func (r *InternalRelationTuple) FromDataProvider(d TupleData) (*InternalRelationTuple, error) {285 var err error286 r.Subject, err = SubjectFromProto(d.GetSubject())287 if err != nil {288 return nil, err289 }290 r.Object = d.GetObject()291 r.Namespace = d.GetNamespace()292 r.Relation = d.GetRelation()293 return r, nil294}295func (r *InternalRelationTuple) ToProto() *rts.RelationTuple {296 return &rts.RelationTuple{297 Namespace: r.Namespace,298 Object: r.Object,299 Relation: r.Relation,300 Subject: r.Subject.ToProto(),301 }302}303func (r *InternalRelationTuple) ToQuery() *RelationQuery {304 return &RelationQuery{305 Namespace: r.Namespace,306 Object: r.Object,307 Relation: r.Relation,308 SubjectID: r.Subject.SubjectID(),309 SubjectSet: r.Subject.SubjectSet(),310 }311}312func (r *InternalRelationTuple) FromURLQuery(query url.Values) (*InternalRelationTuple, error) {313 q, err := (&RelationQuery{}).FromURLQuery(query)314 if err != nil {315 return nil, err316 }317 if s := q.Subject(); s == nil {318 return nil, errors.WithStack(ErrNilSubject)319 } else {320 r.Subject = s321 }322 r.Namespace = q.Namespace323 r.Object = q.Object324 r.Relation = q.Relation325 return r, nil326}327func (r *InternalRelationTuple) ToURLQuery() (url.Values, error) {328 vals := url.Values{329 "namespace": []string{r.Namespace},330 "object": []string{r.Object},331 "relation": []string{r.Relation},332 }333 switch s := r.Subject.(type) {334 case *SubjectID:335 vals.Set(subjectIDKey, s.ID)336 case *SubjectSet:337 vals.Set(subjectSetNamespaceKey, s.Namespace)338 vals.Set(subjectSetObjectKey, s.Object)339 vals.Set(subjectSetRelationKey, s.Relation)340 case nil:341 return nil, errors.WithStack(ErrNilSubject)342 }343 return vals, nil344}345func (r *InternalRelationTuple) ToLoggerFields() logrus.Fields {346 return logrus.Fields{347 "namespace": r.Namespace,348 "object": r.Object,349 "relation": r.Relation,350 "subject": r.Subject.String(),351 }352}353func (q *RelationQuery) FromProto(query TupleData) (*RelationQuery, error) {354 q.Namespace = query.GetNamespace()355 q.Object = query.GetObject()356 q.Relation = query.GetRelation()357 // reset subject358 q.SubjectID = nil359 q.SubjectSet = nil360 if query.GetSubject() != nil {361 switch s := query.GetSubject().Ref.(type) {362 case *rts.Subject_Id:363 q.SubjectID = &s.Id364 case *rts.Subject_Set:365 q.SubjectSet = &SubjectSet{366 Namespace: s.Set.Namespace,367 Object: s.Set.Object,368 Relation: s.Set.Relation,369 }370 case nil:371 return nil, errors.WithStack(ErrNilSubject)372 }373 }374 return q, nil375}376const (377 subjectIDKey = "subject_id"378 subjectSetNamespaceKey = "subject_set.namespace"379 subjectSetObjectKey = "subject_set.object"380 subjectSetRelationKey = "subject_set.relation"381)382func (q *RelationQuery) FromURLQuery(query url.Values) (*RelationQuery, error) {383 if q == nil {384 q = &RelationQuery{}385 }386 if query.Has("subject") {387 return nil, errors.WithStack(ErrDroppedSubjectKey)388 }389 // reset subject390 q.SubjectID = nil391 q.SubjectSet = nil392 switch {393 case !query.Has(subjectIDKey) && !query.Has(subjectSetNamespaceKey) && !query.Has(subjectSetObjectKey) && !query.Has(subjectSetRelationKey):394 // was not queried for the subject395 case query.Has(subjectIDKey) && query.Has(subjectSetNamespaceKey) && query.Has(subjectSetObjectKey) && query.Has(subjectSetRelationKey):396 return nil, errors.WithStack(ErrDuplicateSubject)397 case query.Has(subjectIDKey):398 q.SubjectID = pointerx.String(query.Get(subjectIDKey))399 case query.Has(subjectSetNamespaceKey) && query.Has(subjectSetObjectKey) && query.Has(subjectSetRelationKey):400 q.SubjectSet = &SubjectSet{401 Namespace: query.Get(subjectSetNamespaceKey),402 Object: query.Get(subjectSetObjectKey),403 Relation: query.Get(subjectSetRelationKey),404 }405 default:406 return nil, errors.WithStack(ErrIncompleteSubject)407 }408 q.Object = query.Get("object")409 q.Relation = query.Get("relation")410 q.Namespace = query.Get("namespace")411 return q, nil412}413func (q *RelationQuery) ToURLQuery() url.Values {414 v := make(url.Values, 4)415 if q.Namespace != "" {416 v.Add("namespace", q.Namespace)417 }418 if q.Relation != "" {419 v.Add("relation", q.Relation)420 }421 if q.Object != "" {422 v.Add("object", q.Object)423 }424 if q.SubjectID != nil {425 v.Add(subjectIDKey, *q.SubjectID)426 } else if q.SubjectSet != nil {427 v.Add(subjectSetNamespaceKey, q.SubjectSet.Namespace)428 v.Add(subjectSetObjectKey, q.SubjectSet.Object)429 v.Add(subjectSetRelationKey, q.SubjectSet.Relation)430 }431 return v432}433func (q *RelationQuery) Subject() Subject {434 if q.SubjectID != nil {435 return &SubjectID{ID: *q.SubjectID}436 } else if q.SubjectSet != nil {437 return q.SubjectSet438 }439 return nil440}441func (q *RelationQuery) String() string {442 if q.SubjectID != nil {443 return fmt.Sprintf("namespace: %s; object: %s; relation: %s; subject: %s", q.Namespace, q.Object, q.Relation, *q.SubjectID)444 }445 return fmt.Sprintf("namespace: %s; object: %s; relation: %s; subject: %v", q.Namespace, q.Object, q.Relation, q.SubjectSet)446}447func (r *InternalRelationTuple) Header() []string {448 return []string{449 "NAMESPACE",450 "OBJECT ID",451 "RELATION NAME",452 "SUBJECT",453 }454}455func (r *InternalRelationTuple) Columns() []string {456 return []string{457 r.Namespace,...

Full Screen

Full Screen

definitions_test.go

Source:definitions_test.go Github

copy

Full Screen

...20 Object: "o",21 Relation: "r",22 },23 &SubjectSet{},24 &SubjectID{25 ID: "id",26 },27 &SubjectID{},28 } {29 t.Run(fmt.Sprintf("case=%d/type=%T", i, sub), func(t *testing.T) {30 enc := sub.String()31 dec, err := SubjectFromString(enc)32 require.NoError(t, err)33 assert.Equal(t, sub, dec)34 })35 }36 })37 t.Run("case=string decoding-encoding", func(t *testing.T) {38 for i, tc := range []struct {39 sub string40 expectedType Subject41 }{42 {43 sub: "",44 expectedType: &SubjectID{},45 },46 {47 sub: "foobar",48 expectedType: &SubjectID{},49 },50 {51 sub: "foo:bar#baz",52 expectedType: &SubjectSet{},53 },54 {55 sub: ":#",56 expectedType: &SubjectSet{},57 },58 } {59 t.Run(fmt.Sprintf("case=%d", i), func(t *testing.T) {60 dec, err := SubjectFromString(tc.sub)61 require.NoError(t, err)62 assert.Equal(t, reflect.TypeOf(tc.expectedType), reflect.TypeOf(dec))63 assert.Equal(t, tc.sub, dec.String())64 })65 }66 })67 t.Run("case=proto decoding", func(t *testing.T) {68 for i, tc := range []struct {69 proto *rts.Subject70 expected Subject71 err error72 }{73 {74 proto: &rts.Subject{75 Ref: &rts.Subject_Id{Id: "foo"},76 },77 expected: &SubjectID{ID: "foo"},78 },79 {80 proto: nil,81 err: ErrNilSubject,82 },83 {84 proto: &rts.Subject{85 Ref: &rts.Subject_Set{86 Set: &rts.SubjectSet{87 Namespace: "n",88 Object: "o",89 Relation: "r",90 },91 },92 },93 expected: &SubjectSet{94 Namespace: "n",95 Object: "o",96 Relation: "r",97 },98 },99 } {100 t.Run(fmt.Sprintf("case=%d", i), func(t *testing.T) {101 actual, err := SubjectFromProto(tc.proto)102 require.True(t, errors.Is(err, tc.err))103 assert.Equal(t, tc.expected, actual)104 })105 }106 })107 t.Run("method=equals", func(t *testing.T) {108 for i, tc := range []struct {109 a, b Subject110 equals bool111 }{112 {113 a: &SubjectID{ID: "foo"},114 b: &SubjectID{ID: "foo"},115 equals: true,116 },117 {118 a: &SubjectID{ID: "foo"},119 b: &SubjectID{ID: "bar"},120 equals: false,121 },122 {123 a: &SubjectSet{},124 b: &SubjectID{},125 equals: false,126 },127 {128 a: &SubjectSet{129 Namespace: "N",130 Object: "O",131 Relation: "R",132 },133 b: &SubjectSet{134 Namespace: "N",135 Object: "O",136 Relation: "R",137 },138 equals: true,139 },140 {141 a: &SubjectSet{142 Object: "O",143 Relation: "R",144 },145 b: &SubjectSet{146 Namespace: "N",147 Object: "O",148 Relation: "R",149 },150 equals: false,151 },152 {153 a: &SubjectSet{154 Namespace: "N",155 Relation: "R",156 },157 b: &SubjectSet{158 Namespace: "N",159 Object: "O",160 Relation: "R",161 },162 equals: false,163 },164 {165 a: &SubjectSet{166 Namespace: "N",167 Object: "O",168 },169 b: &SubjectSet{170 Namespace: "N",171 Object: "O",172 Relation: "R",173 },174 equals: false,175 },176 } {177 t.Run(fmt.Sprintf("case=%d", i), func(t *testing.T) {178 assert.Equal(t, tc.equals, tc.a.Equals(tc.b))179 assert.Equal(t, tc.equals, tc.b.Equals(tc.a))180 })181 }182 })183 t.Run("case=url encoding-decoding", func(t *testing.T) {184 for i, sub := range []*SubjectSet{185 {186 Namespace: "n",187 Object: "o",188 Relation: "r",189 },190 {},191 } {192 t.Run(fmt.Sprintf("case=%d", i), func(t *testing.T) {193 enc := sub.ToURLQuery()194 dec := (&SubjectSet{}).FromURLQuery(enc)195 assert.Equal(t, sub, dec)196 })197 }198 })199 t.Run("case=url decoding-encoding", func(t *testing.T) {200 for i, vals := range []url.Values{201 {202 "namespace": []string{"n"},203 "object": []string{"o"},204 "relation": []string{"r"},205 },206 {207 "namespace": []string{""},208 "object": []string{""},209 "relation": []string{""},210 },211 } {212 t.Run(fmt.Sprintf("case=%d", i), func(t *testing.T) {213 dec := (&SubjectSet{}).FromURLQuery(vals)214 assert.Equal(t, vals, dec.ToURLQuery())215 })216 }217 })218 t.Run("case=json encoding", func(t *testing.T) {219 for i, tc := range []struct {220 sub Subject221 json string222 }{223 {224 sub: &SubjectSet{225 Namespace: "n",226 Object: "o",227 Relation: "r",228 },229 json: `230{231 "namespace": "n",232 "object": "o",233 "relation": "r"234}`,235 },236 {237 sub: &SubjectID{ID: "foo"},238 json: "\"foo\"",239 },240 } {241 t.Run(fmt.Sprintf("case=%d", i), func(t *testing.T) {242 enc, err := json.Marshal(tc.sub)243 require.NoError(t, err)244 assert.JSONEq(t, tc.json, string(enc))245 })246 }247 })248}249func TestInternalRelationTuple(t *testing.T) {250 t.Run("method=string encoding", func(t *testing.T) {251 assert.Equal(t, "n:o#r@s", (&InternalRelationTuple{252 Namespace: "n",253 Object: "o",254 Relation: "r",255 Subject: &SubjectID{ID: "s"},256 }).String())257 })258 t.Run("method=string decoding", func(t *testing.T) {259 for i, tc := range []struct {260 enc string261 err error262 expected *InternalRelationTuple263 }{264 {265 enc: "n:o#r@s",266 expected: &InternalRelationTuple{267 Namespace: "n",268 Object: "o",269 Relation: "r",270 Subject: &SubjectID{ID: "s"},271 },272 },273 {274 enc: "n:o#r@n:o#r",275 expected: &InternalRelationTuple{276 Namespace: "n",277 Object: "o",278 Relation: "r",279 Subject: &SubjectSet{280 Namespace: "n",281 Object: "o",282 Relation: "r",283 },284 },285 },286 {287 enc: "n:o#r@(n:o#r)",288 expected: &InternalRelationTuple{289 Namespace: "n",290 Object: "o",291 Relation: "r",292 Subject: &SubjectSet{293 Namespace: "n",294 Object: "o",295 Relation: "r",296 },297 },298 },299 {300 enc: "#dev:@ory#:working:@projects:keto#awesome",301 expected: &InternalRelationTuple{302 Namespace: "#dev",303 Object: "@ory",304 Relation: ":working:",305 Subject: &SubjectSet{306 Namespace: "projects",307 Object: "keto",308 Relation: "awesome",309 },310 },311 },312 {313 enc: "no-colon#in@this",314 err: ErrMalformedInput,315 },316 {317 enc: "no:hash-in@this",318 err: ErrMalformedInput,319 },320 {321 enc: "no:at#in-this",322 err: ErrMalformedInput,323 },324 } {325 t.Run(fmt.Sprintf("case=%d", i), func(t *testing.T) {326 actual, err := (&InternalRelationTuple{}).FromString(tc.enc)327 assert.True(t, errors.Is(err, tc.err), "%+v", err)328 assert.Equal(t, tc.expected, actual)329 })330 }331 })332 t.Run("case=url encoding-decoding", func(t *testing.T) {333 for i, r := range []*InternalRelationTuple{334 {335 Namespace: "n",336 Object: "o",337 Relation: "r",338 Subject: &SubjectID{ID: "s"},339 },340 {341 Namespace: "n",342 Object: "o",343 Relation: "r",344 Subject: &SubjectSet{345 Namespace: "sn",346 Object: "so",347 Relation: "sr",348 },349 },350 {351 Subject: &SubjectID{},352 },353 } {354 t.Run(fmt.Sprintf("case=%d", i), func(t *testing.T) {355 vals, err := r.ToURLQuery()356 require.NoError(t, err)357 res, err := (&InternalRelationTuple{}).FromURLQuery(vals)358 require.NoError(t, err, "raw: %+v, enc: %+v", r, vals)359 assert.Equal(t, r, res)360 })361 }362 })363 t.Run("case=url decoding-encoding", func(t *testing.T) {364 for i, v := range []url.Values{365 {366 "namespace": []string{"n"},367 "object": []string{"o"},368 "relation": []string{"r"},369 "subject_id": []string{"foo"},370 },371 {372 "namespace": []string{"n"},373 "object": []string{"o"},374 "relation": []string{"r"},375 "subject_set.namespace": []string{"sn"},376 "subject_set.object": []string{"so"},377 "subject_set.relation": []string{"sr"},378 },379 } {380 t.Run(fmt.Sprintf("case=%d", i), func(t *testing.T) {381 rt, err := (&InternalRelationTuple{}).FromURLQuery(v)382 require.NoError(t, err)383 q, err := rt.ToURLQuery()384 require.NoError(t, err)385 assert.Equal(t, v, q)386 })387 }388 })389 t.Run("case=proto decoding", func(t *testing.T) {390 for i, tc := range []struct {391 proto TupleData392 expected *InternalRelationTuple393 err error394 }{395 {396 proto: &rts.RelationTuple{397 Namespace: "n",398 Object: "o",399 Relation: "r",400 Subject: nil,401 },402 err: ErrNilSubject,403 },404 {405 proto: &rts.RelationTuple{406 Namespace: "n",407 Object: "o",408 Relation: "r",409 Subject: &rts.Subject{410 Ref: &rts.Subject_Set{411 Set: &rts.SubjectSet{412 Namespace: "n",413 Object: "o",414 Relation: "r",415 },416 },417 },418 },419 expected: &InternalRelationTuple{420 Namespace: "n",421 Object: "o",422 Relation: "r",423 Subject: &SubjectSet{424 Namespace: "n",425 Object: "o",426 Relation: "r",427 },428 },429 },430 {431 proto: &rts.RelationTuple{432 Namespace: "n",433 Object: "o",434 Relation: "r",435 Subject: &rts.Subject{436 Ref: &rts.Subject_Id{437 Id: "user",438 },439 },440 },441 expected: &InternalRelationTuple{442 Namespace: "n",443 Object: "o",444 Relation: "r",445 Subject: &SubjectID{446 ID: "user",447 },448 },449 },450 } {451 t.Run(fmt.Sprintf("case=%d", i), func(t *testing.T) {452 actual, err := (&InternalRelationTuple{}).FromDataProvider(tc.proto)453 require.True(t, errors.Is(err, tc.err))454 assert.Equal(t, tc.expected, actual)455 })456 }457 })458 t.Run("format=JSON", func(t *testing.T) {459 t.Run("direction=encoding-decoding", func(t *testing.T) {460 for _, tc := range []struct {461 name string462 rt *InternalRelationTuple463 expected string464 }{465 {466 name: "with subject ID",467 rt: &InternalRelationTuple{468 Namespace: "n",469 Object: "o",470 Relation: "r",471 Subject: &SubjectID{ID: "s"},472 },473 expected: `474{475 "namespace": "n",476 "object": "o",477 "relation": "r",478 "subject_id": "s"479}`,480 },481 {482 name: "with subject set",483 rt: &InternalRelationTuple{484 Namespace: "n",485 Object: "o",486 Relation: "r",487 Subject: &SubjectSet{488 Namespace: "sn",489 Object: "so",490 Relation: "sr",491 },492 },493 expected: `494{495 "namespace": "n",496 "object": "o",497 "relation": "r",498 "subject_set": {499 "namespace": "sn",500 "object": "so",501 "relation": "sr"502 }503}`,504 },505 } {506 t.Run("case="+tc.name, func(t *testing.T) {507 raw, err := json.Marshal(tc.rt)508 require.NoError(t, err)509 assert.JSONEq(t, tc.expected, string(raw))510 var dec InternalRelationTuple511 require.NoError(t, json.Unmarshal(raw, &dec))512 assert.Equal(t, tc.rt, &dec)513 })514 }515 })516 })517}518func TestRelationQuery(t *testing.T) {519 t.Run("case=url encoding-decoding-encoding", func(t *testing.T) {520 for i, tc := range []struct {521 v url.Values522 r *RelationQuery523 }{524 {525 v: url.Values{526 "namespace": []string{"n"},527 "object": []string{"o"},528 "relation": []string{"r"},529 "subject_id": []string{"foo"},530 },531 r: &RelationQuery{532 Namespace: "n",533 Object: "o",534 Relation: "r",535 SubjectID: pointerx.String("foo"),536 },537 },538 {539 v: url.Values{540 "namespace": []string{"n"},541 "object": []string{"o"},542 "relation": []string{"r"},543 "subject_set.namespace": []string{"sn"},544 "subject_set.object": []string{"so"},545 "subject_set.relation": []string{"sr"},546 },547 r: &RelationQuery{548 Namespace: "n",549 Object: "o",550 Relation: "r",551 SubjectSet: &SubjectSet{552 Namespace: "sn",553 Object: "so",554 Relation: "sr",555 },556 },557 },558 {559 v: url.Values{560 "namespace": []string{"n"},561 "relation": []string{"r"},562 },563 r: &RelationQuery{564 Namespace: "n",565 Relation: "r",566 },567 },568 } {569 t.Run(fmt.Sprintf("case=%d", i), func(t *testing.T) {570 enc := tc.r.ToURLQuery()571 assert.Equal(t, tc.v, enc)572 dec, err := (&RelationQuery{}).FromURLQuery(tc.v)573 require.NoError(t, err)574 assert.Equal(t, tc.r, dec)575 })576 }577 })578}579func TestRelationCollection(t *testing.T) {580 t.Run("case=prints all", func(t *testing.T) {581 expected := make([]*InternalRelationTuple, 3)582 for i := range expected {583 expected[i] = &InternalRelationTuple{584 Namespace: "n" + strconv.Itoa(i),585 Object: "o" + strconv.Itoa(i),586 Relation: "r" + strconv.Itoa(i),587 Subject: &SubjectID{ID: "s" + strconv.Itoa(i)},588 }589 }590 expected[2].Subject = &SubjectSet{591 Namespace: "sn",592 Object: "so",593 Relation: "sr",594 }595 proto := make([]*rts.RelationTuple, 3)596 for i := range expected {597 proto[i] = &rts.RelationTuple{598 Namespace: "n" + strconv.Itoa(i),599 Object: "o" + strconv.Itoa(i),600 Relation: "r" + strconv.Itoa(i),601 Subject: (&SubjectID{ID: "s" + strconv.Itoa(i)}).ToProto(),602 }603 }604 proto[2].Subject = (&SubjectSet{605 Namespace: "sn",606 Object: "so",607 Relation: "sr",608 }).ToProto()609 NewRelationCollection([]*InternalRelationTuple{})610 NewProtoRelationCollection([]*rts.RelationTuple{})611 for i, c := range []*RelationCollection{612 NewRelationCollection(expected),613 NewProtoRelationCollection(proto),614 } {615 t.Run(fmt.Sprintf("case=%d", i), func(t *testing.T) {616 var vals []string617 for _, row := range c.Table() {618 vals = append(vals, row...)619 }620 ev := reflect.ValueOf(expected)621 for el := 0; el < ev.Len(); el++ {622 et := reflect.TypeOf(expected).Elem().Elem()623 for f := 0; f < et.NumField(); f++ {624 v := ev.Index(el).Elem().Field(f)625 // private field626 if !v.CanSet() {627 continue628 }629 switch v.Kind() {630 case reflect.String:631 assert.Contains(t, vals, v.String())632 default:633 str := v.MethodByName("String").Call(nil)[0].String()634 assert.Contains(t, vals, str)635 }636 }637 }638 })639 }640 })641 t.Run("func=toInternal", func(t *testing.T) {642 for i, tc := range []struct {643 collection *RelationCollection644 expected []*InternalRelationTuple645 err error646 }{647 {648 collection: NewProtoRelationCollection([]*rts.RelationTuple{{649 Namespace: "n",650 Object: "o",651 Relation: "r",652 Subject: (&SubjectID{ID: "s"}).ToProto(),653 }}),654 expected: []*InternalRelationTuple{{655 Namespace: "n",656 Object: "o",657 Relation: "r",658 Subject: &SubjectID{ID: "s"},659 }},660 },661 {662 collection: NewProtoRelationCollection([]*rts.RelationTuple{{ /*subject is nil*/ }}),663 err: ErrNilSubject,664 },665 } {666 t.Run(fmt.Sprintf("case=%d", i), func(t *testing.T) {667 actual, err := tc.collection.ToInternal()668 require.True(t, errors.Is(err, tc.err))669 assert.Equal(t, tc.expected, actual)670 })671 }672 })...

Full Screen

Full Screen

todo.go

Source:todo.go Github

copy

Full Screen

1package handler2import (3 "encoding/json"4 "log"5 "net/http"6 "hacku_vol2/http/response"7 "hacku_vol2/server/model"8)9type todoList struct {10 Name string `json:"name"`11 Limit string `json:"time_limite"`12 Subject string `json:"subject"`13 EndFlag int `json:"end_flag"`14 RegisterDate string `json:"register_date"`15 EndDate string `json:"end_date"`16}17// リクエスト(送られてきた値18type addTodoListRequest struct {19 Token string `json:"token"`20 Name string `json:"name"`21 Limit string `json:"time_limite"`22 Subject string `json:"subject"`23}24// レスポンス(返す値25type addTodoListResponse struct {26 Name string `json:"name"`27 Limit string `json:"time_limite"`28 Subject string `json:"subject"`29}30type todoListResponse struct {31 Todos []todoList `json:"todos"`32}33// todo全件取得 リクエスト34type ToDoGetAllRequest struct {35 Token string `json:"token"`36}37// todo OK38// todo全件取得39func HandleToDoGetAll() http.HandlerFunc {40 return func(writer http.ResponseWriter, request *http.Request) {41 // リクエストBodyから更新後情報を取得42 var requestBody ToDoGetAllRequest43 if err := json.NewDecoder(request.Body).Decode(&requestBody); err != nil {44 log.Println(err)45 response.InternalServerError(writer, "Internal Server Error")46 return47 }48 todoListAlls, err := model.SelectGettingTodo(requestBody.Token)49 if err != nil {50 log.Println(err)51 response.InternalServerError(writer, "Internal Server Error")52 return53 }54 var subject string55 todoLists := make([]todoList, len(todoListAlls))56 for i, to := range todoListAlls {57 subject = ""58 switch to.SubjectId {59 case 1:60 subject = "国語"61 case 2:62 subject = "算数"63 case 3:64 subject = "英語"65 case 4:66 subject = "理科"67 case 5:68 subject = "社会"69 case 6:70 subject = "その他"71 }72 todoLists[i] = todoList{73 Name: to.Name, //タスク名74 Limit: to.Limit, //期限2020,08,3175 Subject: subject, //科目76 EndFlag: to.EndFlag, //終わっているかどうか77 RegisterDate: to.RegisterDate, //登録日時78 EndDate: to.EndDate, //終了日時79 }80 }81 response.Success(writer, &todoListResponse{82 Todos: todoLists,83 })84 }85}86func HandleToDoPost() http.HandlerFunc {87 return func(writer http.ResponseWriter, request *http.Request) {88 // リクエストBodyから更新後情報を取得89 var requestBody addTodoListRequest90 if err := json.NewDecoder(request.Body).Decode(&requestBody); err != nil {91 log.Println(err)92 response.InternalServerError(writer, "Internal Server Error")93 return94 }95 userId := model.SelectUserId(requestBody.Token)96 subject := requestBody.Subject97 name := requestBody.Name98 limit := requestBody.Limit99 subjectId := 0100 switch requestBody.Subject {101 case "国語":102 subjectId = 1103 case "算数":104 subjectId = 2105 case "英語":106 subjectId = 3107 case "理科":108 subjectId = 4109 case "社会":110 subjectId = 5111 case "その他":112 subjectId = 6113 }114 err := model.InsertTodo(&model.Task{115 UserId: userId,116 SubjectId: subjectId,117 Name: requestBody.Name,118 Limit: requestBody.Limit,119 })120 if err != nil {121 log.Println(err)122 response.InternalServerError(writer, "Internal Server Error ww")123 return124 }125 response.Success(writer, &addTodoListResponse{126 Subject: subject,127 Name: name,128 Limit: limit,129 })130 }131}132func HandleToDoEnd() http.HandlerFunc {133 return func(writer http.ResponseWriter, request *http.Request) {134 // リクエストBodyから更新後情報を取得135 var requestBody addTodoListRequest136 if err := json.NewDecoder(request.Body).Decode(&requestBody); err != nil {137 log.Println(err)138 response.InternalServerError(writer, "Internal Server Error")139 return140 }141 userId := model.SelectUserId(requestBody.Token)142 subject := requestBody.Subject143 name := requestBody.Name144 limit := requestBody.Limit145 subjectId := 0146 switch requestBody.Subject {147 case "国語":148 subjectId = 1149 case "算数":150 subjectId = 2151 case "英語":152 subjectId = 3153 case "理科":154 subjectId = 4155 case "社会":156 subjectId = 5157 case "その他":158 subjectId = 6159 }160 err := model.InsertTodoEnd(&model.Task{161 UserId: userId,162 SubjectId: subjectId,163 Name: requestBody.Name,164 Limit: requestBody.Limit,165 })166 if err != nil {167 log.Println(err)168 response.InternalServerError(writer, "Internal Server Error ww")169 return170 }171 response.Success(writer, &addTodoListResponse{172 Name: name,173 Limit: limit,174 Subject: subject,175 })176 }177}...

Full Screen

Full Screen

SubjectID

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Subject ID is: ", internal.SubjectID())4}5import (6func SubjectID() string {7 fmt.Println("Internal class called")8}

Full Screen

Full Screen

SubjectID

Using AI Code Generation

copy

Full Screen

1import "fmt"2import "github.com/learnGo/1"3func main() {4 fmt.Println("Hello, playground")5 s := internal.SubjectID{"Maths"}6 fmt.Println(s)7}8type SubjectID struct {9}10type SubjectID struct {11}12type SubjectID struct {13}14type SubjectID struct {15}16type SubjectID struct {17}18type SubjectID struct {19}20type SubjectID struct {21}22type SubjectID struct {23}24type SubjectID struct {25}26type SubjectID struct {27}28type SubjectID struct {29}30type SubjectID struct {31}32type SubjectID struct {33}34type SubjectID struct {35}36type SubjectID struct {37}38type SubjectID struct {39}

Full Screen

Full Screen

SubjectID

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 s := _1.Subject{Id: 1, Name: "Maths"}4 fmt.Println(s.SubjectId())5}6import (7func main() {8 s := Subject{Id: 1, Name: "Maths"}9 fmt.Println(s.SubjectId())10}11import (12func main() {13 s := _1.Subject{Id: 1, Name: "Maths"}14 fmt.Println(s.Id)15}16import (17func main() {18 s := Subject{Id: 1, Name: "Maths"}19 fmt.Println(s.Id)20}

Full Screen

Full Screen

SubjectID

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World!")4 fmt.Println(package1.SubjectID())5}6import (7func SubjectID() string {8 return fmt.Sprintf("SubjectID: %d", 1)9}10import (11func SubjectID() string {12 return internal.SubjectID()13}14import (15func TestSubjectID(t *testing.T) {16 if SubjectID() != "SubjectID: 1" {17 t.Error("SubjectID() failed")18 }19}20import (21func TestSubjectID(t *testing.T) {22 if SubjectID() != "SubjectID: 1" {23 t.Error("SubjectID() failed")24 }25}26import (27func TestSubjectID(t *testing.T) {28 if SubjectID() != "SubjectID: 1" {29 t.Error("SubjectID() failed")30 }31}32--- PASS: TestSubjectID (0.00s)33--- PASS: TestSubjectID (0.00s)34--- PASS: TestSubjectID (0.00s)

Full Screen

Full Screen

SubjectID

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World!")4 i1 = internal1.Internal1{10}5 fmt.Println(i1.SubjectID())6}7type Internal1 struct {8}9func (i Internal1) SubjectID() int {10}

Full Screen

Full Screen

SubjectID

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 s1 := _2.Student{4 }5 fmt.Println(s1.SubjectID())6}7import "fmt"8type Student struct {9}10func (s Student) SubjectID() string {11 return fmt.Sprintf("%s%d", s.Name, s.Age)12}

Full Screen

Full Screen

SubjectID

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 s := internal.Student{}4 s.SetName("Harsha")5 fmt.Println(s.Name())6 fmt.Println(s.SubjectID())7}

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 Ginkgo automation tests on LambdaTest cloud grid

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

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful