Debian Codegraph @

tests/unmarshal_test.go

raw symbols SCIP
1 package tests
2
3 import (
4 "bytes"
5 "fmt"
6 "io"
7 "os"
8 "path/filepath"
9 "reflect"
10 "testing"
11 "time"
12 "unsafe"
13
14 pub "github.com/go-ap/activitypub"
15
16 j "github.com/go-ap/jsonld"
17 )
18
19 const dir = "./mocks"
20
21 var stopOnFailure = false
22
23 type testPair struct {
24 expected bool
25 blank interface{}
26 result interface{}
27 }
28
29 type testMaps map[string]testPair
30
31 type visit struct {
32 a1 unsafe.Pointer
33 a2 unsafe.Pointer
34 typ reflect.Type
35 }
36
37 type canErrorFunc func(format string, args ...interface{})
38
39 // See reflect.DeepEqual
40 func assertDeepEquals(t canErrorFunc, x, y interface{}) bool {
41 if x == nil || y == nil {
42 return x == y
43 }
44 v1 := reflect.ValueOf(x)
45 v2 := reflect.ValueOf(y)
46 if v1.Type() != v2.Type() {
47 t("%T != %T", x, y)
48 return false
49 }
50 return deepValueEqual(t, v1, v2, make(map[visit]bool), 0)
51 }
52
53 // See reflect.deepValueEqual
54 func deepValueEqual(t canErrorFunc, v1, v2 reflect.Value, visited map[visit]bool, depth int) bool {
55 if !v1.IsValid() || !v2.IsValid() {
56 return v1.IsValid() == v2.IsValid()
57 }
58 if v1.Type() != v2.Type() {
59 t("types differ %s != %s", v1.Type().Name(), v2.Type().Name())
60 return false
61 }
62
63 hard := func(v1, v2 reflect.Value) bool {
64 switch v1.Kind() {
65 case reflect.Ptr:
66 return false
67 case reflect.Map, reflect.Slice, reflect.Interface:
68 // Nil pointers cannot be cyclic. Avoid putting them in the visited map.
69 return !v1.IsNil() && !v2.IsNil()
70 }
71 return false
72 }
73
74 if hard(v1, v2) {
75 var addr1, addr2 unsafe.Pointer
76 if v1.CanAddr() {
77 addr1 = unsafe.Pointer(v1.UnsafeAddr())
78 } else {
79 addr1 = unsafe.Pointer(v1.Pointer())
80 }
81 if v2.CanAddr() {
82 addr2 = unsafe.Pointer(v2.UnsafeAddr())
83 } else {
84 addr2 = unsafe.Pointer(v2.Pointer())
85 }
86 if uintptr(addr1) > uintptr(addr2) {
87 // Canonicalize order to reduce number of entries in visited.
88 // Assumes non-moving garbage collector.
89 addr1, addr2 = addr2, addr1
90 }
91 // Short circuit if references are already seen.
92 typ := v1.Type()
93 v := visit{addr1, addr2, typ}
94 if visited[v] {
95 return true
96 }
97
98 // Remember for later.
99 visited[v] = true
100 }
101
102 switch v1.Kind() {
103 case reflect.Array:
104 for i := 0; i < v1.Len(); i++ {
105 if !deepValueEqual(t, v1.Index(i), v2.Index(i), visited, depth+1) {
106 t("Arrays not equal at index %d %s %s", i, v1.Index(i), v2.Index(i))
107 return false
108 }
109 }
110 return true
111 case reflect.Slice:
112 if v1.IsNil() != v2.IsNil() {
113 t("One of the slices is not nil %s[%d] vs %s[%d]", v1.Type().Name(), v1.Len(), v2.Type().Name(), v2.Len())
114 return false
115 }
116 if v1.Len() != v2.Len() {
117 t("Slices lengths are different %s[%d] vs %s[%d]", v1.Type().Name(), v1.Len(), v2.Type().Name(), v2.Len())
118 return false
119 }
120 if v1.Pointer() == v2.Pointer() {
121 return true
122 }
123 for i := 0; i < v1.Len(); i++ {
124 if !deepValueEqual(t, v1.Index(i), v2.Index(i), visited, depth+1) {
125 t("Slices elements at pos %d are not equal %#v vs %#v", i, v1.Index(i), v2.Index(i))
126 return false
127 }
128 }
129 return true
130 case reflect.Interface:
131 if v1.IsNil() || v2.IsNil() {
132 if v1.IsNil() == v2.IsNil() {
133 return true
134 }
135 var isNil1, isNil2 string
136 if v1.IsNil() {
137 isNil1 = "is"
138 } else {
139 isNil1 = "is not"
140 }
141 if v2.IsNil() {
142 isNil2 = "is"
143 } else {
144 isNil2 = "is not"
145 }
146 t("Interface '%s' %s nil and '%s' %s nil", v1.Type().Name(), isNil1, v2.Type().Name(), isNil2)
147 return false
148 }
149 return deepValueEqual(t, v1.Elem(), v2.Elem(), visited, depth+1)
150 case reflect.Ptr:
151 if v1.Pointer() == v2.Pointer() {
152 return true
153 }
154 return deepValueEqual(t, v1.Elem(), v2.Elem(), visited, depth+1)
155 case reflect.Struct:
156 for i, n := 0, v1.NumField(); i < n; i++ {
157 var (
158 f1 = v1.Field(i)
159 f2 = v2.Field(i)
160 n1 = v1.Type().Field(i).Name
161 n2 = v2.Type().Field(i).Name
162 t1 = f1.Type().Name()
163 t2 = f2.Type().Name()
164 )
165 if !deepValueEqual(t, v1.Field(i), v2.Field(i), visited, depth+1) {
166 t("Struct fields at pos %d %s[%s] and %s[%s] are not deeply equal", i, n1, t1, n2, t2)
167 if f1.CanInterface() && f2.CanInterface() {
168 t(" Values: %#v - %#v", v1.Field(i).Interface(), v2.Field(i).Interface())
169 }
170 return false
171 }
172 }
173 return true
174 case reflect.Map:
175 if v1.IsNil() != v2.IsNil() {
176 t("Maps are not nil", v1.Type().Name(), v2.Type().Name())
177 return false
178 }
179 if v1.Len() != v2.Len() {
180 t("Maps don't have the same length %d vs %d", v1.Len(), v2.Len())
181 return false
182 }
183 if v1.Pointer() == v2.Pointer() {
184 return true
185 }
186 for _, k := range v1.MapKeys() {
187 val1 := v1.MapIndex(k)
188 val2 := v2.MapIndex(k)
189 if !val1.IsValid() || !val2.IsValid() || !deepValueEqual(t, v1.MapIndex(k), v2.MapIndex(k), visited, depth+1) {
190 t("Maps values at index %s are not equal", k.String())
191 return false
192 }
193 }
194 return true
195 case reflect.Func:
196 if v1.IsNil() && v2.IsNil() {
197 return true
198 }
199 // Can't do better than this:
200 return false
201 case reflect.String:
202 return v1.String() == v2.String()
203 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
204 return v1.Int() == v2.Int()
205 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
206 return v1.Uint() == v2.Uint()
207 case reflect.Float32, reflect.Float64:
208 return v1.Float() == v2.Float()
209 case reflect.Bool:
210 return v1.Bool() == v2.Bool()
211 case reflect.Complex64, reflect.Complex128:
212 return v1.Complex() == v2.Complex()
213 }
214 return false
215 }
216
217 var zLoc, _ = time.LoadLocation("UTC")
218
219 var allTests = testMaps{
220 //"empty": testPair{
221 // expected: true,
222 // blank: &pub.Object{},
223 // result: &pub.Object{},
224 //},
225 //"link_simple": testPair{
226 // expected: true,
227 // blank: &pub.Link{},
228 // result: &pub.Link{
229 // Type: pub.LinkType,
230 // Href: pub.IRI("http://example.org/abc"),
231 // HrefLang: pub.LangRef("en"),
232 // MediaType: pub.MimeType("text/html"),
233 // Name: pub.NaturalLanguageValues{{
234 // pub.NilLangRef, pub.Content("An example link"),
235 // }},
236 // },
237 //},
238 //"object_with_url": testPair{
239 // expected: true,
240 // blank: &pub.Object{},
241 // result: &pub.Object{
242 // URL: pub.IRI("http://littr.git/api/accounts/system"),
243 // },
244 //},
245 //"object_with_url_collection": testPair{
246 // expected: true,
247 // blank: &pub.Object{},
248 // result: &pub.Object{
249 // URL: pub.ItemCollection{
250 // pub.IRI("http://littr.git/api/accounts/system"),
251 // pub.IRI("http://littr.git/~system"),
252 // },
253 // },
254 //},
255 //"object_simple": testPair{
256 // expected: true,
257 // blank: &pub.Object{},
258 // result: &pub.Object{
259 // Type: pub.ObjectType,
260 // ID: pub.ID("http://www.test.example/object/1"),
261 // Name: pub.NaturalLanguageValues{{
262 // pub.NilLangRef, pub.Content("A Simple, non-specific object"),
263 // }},
264 // },
265 //},
266 //"object_no_type": testPair{
267 // expected: true,
268 // blank: &pub.Object{},
269 // result: &pub.Object{
270 // ID: pub.ID("http://www.test.example/object/1"),
271 // Name: pub.NaturalLanguageValues{{
272 // pub.NilLangRef, pub.Content("A Simple, non-specific object without a type"),
273 // }},
274 // },
275 //},
276 //"object_with_tags": testPair{
277 // expected: true,
278 // blank: &pub.Object{},
279 // result: &pub.Object{
280 // Type: pub.ObjectType,
281 // ID: pub.ID("http://www.test.example/object/1"),
282 // Name: pub.NaturalLanguageValues{{
283 // pub.NilLangRef, pub.Content("A Simple, non-specific object"),
284 // }},
285 // Tag: pub.ItemCollection{
286 // &pub.Mention{
287 // Name: pub.NaturalLanguageValues{{
288 // pub.NilLangRef, pub.Content("#my_tag"),
289 // }},
290 // Type: pub.MentionType,
291 // ID: pub.ID("http://example.com/tag/my_tag"),
292 // },
293 // &pub.Mention{
294 // Name: pub.NaturalLanguageValues{{
295 // pub.NilLangRef, pub.Content("@ana"),
296 // }},
297 // Type: pub.MentionType,
298 // ID: pub.ID("http://example.com/users/ana"),
299 // },
300 // },
301 // },
302 //},
303 //"object_with_replies": testPair{
304 // expected: true,
305 // blank: &pub.Object{},
306 // result: &pub.Object{
307 // Type: pub.ObjectType,
308 // ID: pub.ID("http://www.test.example/object/1"),
309 // Replies: &pub.Collection{
310 // ID: pub.ID("http://www.test.example/object/1/replies"),
311 // Type: pub.CollectionType,
312 // TotalItems: 1,
313 // Items: pub.ItemCollection{
314 // &pub.Object{
315 // ID: pub.ID("http://www.test.example/object/1/replies/2"),
316 // Type: pub.ArticleType,
317 // Name: pub.NaturalLanguageValues{{
318 // pub.NilLangRef, pub.Content("Example title"),
319 // }},
320 // },
321 // },
322 // },
323 // },
324 //},
325 //"activity_simple": testPair{
326 // expected: true,
327 // blank: &pub.Activity{
328 // Actor: &pub.Person{},
329 // },
330 // result: &pub.Activity{
331 // Type: pub.ActivityType,
332 // Summary: pub.NaturalLanguageValues{{pub.NilLangRef, pub.Content("Sally did something to a note")}},
333 // Actor: &pub.Person{
334 // Type: pub.PersonType,
335 // Name: pub.NaturalLanguageValues{{pub.NilLangRef, pub.Content("Sally")}},
336 // },
337 // Object: &pub.Object{
338 // Type: pub.NoteType,
339 // Name: pub.NaturalLanguageValues{{pub.NilLangRef, pub.Content("A Note")}},
340 // },
341 // },
342 //},
343 //"person_with_outbox": testPair{
344 // expected: true,
345 // blank: &pub.Person{},
346 // result: &pub.Person{
347 // ID: pub.ID("http://example.com/accounts/ana"),
348 // Type: pub.PersonType,
349 // Name: pub.NaturalLanguageValues{{pub.NilLangRef, pub.Content("ana")}},
350 // PreferredUsername: pub.NaturalLanguageValues{{pub.NilLangRef, pub.Content("Ana")}},
351 // URL: pub.IRI("http://example.com/accounts/ana"),
352 // Outbox: &pub.OrderedCollection{
353 // ID: "http://example.com/accounts/ana/outbox",
354 // Type: pub.OrderedCollectionType,
355 // URL: pub.IRI("http://example.com/outbox"),
356 // },
357 // },
358 //},
359 //"ordered_collection": testPair{
360 // expected: true,
361 // blank: &pub.OrderedCollection{},
362 // result: &pub.OrderedCollection{
363 // ID: pub.ID("http://example.com/outbox"),
364 // Type: pub.OrderedCollectionType,
365 // URL: pub.IRI("http://example.com/outbox"),
366 // TotalItems: 1,
367 // OrderedItems: pub.ItemCollection{
368 // &pub.Object{
369 // ID: pub.ID("http://example.com/outbox/53c6fb47"),
370 // Type: pub.ArticleType,
371 // Name: pub.NaturalLanguageValues{{pub.NilLangRef, pub.Content("Example title")}},
372 // Content: pub.NaturalLanguageValues{{pub.NilLangRef, pub.Content("Example content!")}},
373 // URL: pub.IRI("http://example.com/53c6fb47"),
374 // MediaType: pub.MimeType("text/markdown"),
375 // Published: time.Date(2018, time.July, 5, 16, 46, 44, 0, zLoc),
376 // Generator: pub.IRI("http://example.com"),
377 // AttributedTo: pub.IRI("http://example.com/accounts/alice"),
378 // },
379 // },
380 // },
381 //},
382 "ordered_collection_page": testPair{
383 expected: true,
384 blank: &pub.OrderedCollectionPage{},
385 result: &pub.OrderedCollectionPage{
386 PartOf: pub.IRI("http://example.com/outbox"),
387 Next: pub.IRI("http://example.com/outbox?page=3"),
388 Prev: pub.IRI("http://example.com/outbox?page=1"),
389 ID: pub.ID("http://example.com/outbox?page=2"),
390 Type: pub.OrderedCollectionPageType,
391 URL: pub.IRI("http://example.com/outbox?page=2"),
392 Current: pub.IRI("http://example.com/outbox?page=2"),
393 TotalItems: 1,
394 StartIndex: 100,
395 OrderedItems: pub.ItemCollection{
396 &pub.Object{
397 ID: pub.ID("http://example.com/outbox/53c6fb47"),
398 Type: pub.ArticleType,
399 Name: pub.DefaultNaturalLanguage("Example title"),
400 Content: pub.DefaultNaturalLanguage("Example content!"),
401 URL: pub.IRI("http://example.com/53c6fb47"),
402 MediaType: pub.MimeType("text/markdown"),
403 Published: time.Date(2018, time.July, 5, 16, 46, 44, 0, zLoc),
404 Generator: pub.IRI("http://example.com"),
405 AttributedTo: pub.IRI("http://example.com/accounts/alice"),
406 },
407 },
408 },
409 },
410 //"natural_language_values": {
411 // expected: true,
412 // blank: &pub.NaturalLanguageValues{},
413 // result: &pub.NaturalLanguageValues{
414 // {
415 // pub.NilLangRef, pub.Content([]byte{'\n','\t', '\t', '\n'}),
416 // },
417 // {pub.LangRef("en"), pub.Content("Ana got apples ⓐ")},
418 // {pub.LangRef("fr"), pub.Content("Aná a des pommes ⒜")},
419 // {pub.LangRef("ro"), pub.Content("Ana are mere")},
420 // },
421 //},
422 //"activity_create_simple": {
423 // expected: true,
424 // blank: &pub.Create{},
425 // result: &pub.Create{
426 // Type: pub.CreateType,
427 // Actor: pub.IRI("https://littr.git/api/accounts/anonymous"),
428 // Object: &pub.Object{
429 // Type: pub.NoteType,
430 // AttributedTo: pub.IRI("https://littr.git/api/accounts/anonymous"),
431 // InReplyTo: pub.IRI("https://littr.git/api/accounts/system/outbox/7ca154ff"),
432 // Content: pub.NaturalLanguageValues{{pub.NilLangRef, pub.Content("<p>Hello world</p>")}},
433 // To: pub.ItemCollection{pub.IRI("https://www.w3.org/ns/activitystreams#Public")},
434 // },
435 // },
436 //},
437 //"activity_create_multiple_objects": {
438 // expected: true,
439 // blank: &pub.Create{},
440 // result: &pub.Create{
441 // Type: pub.CreateType,
442 // Actor: pub.IRI("https://littr.git/api/accounts/anonymous"),
443 // Object: pub.ItemCollection{
444 // &pub.Object{
445 // Type: pub.NoteType,
446 // AttributedTo: pub.IRI("https://littr.git/api/accounts/anonymous"),
447 // InReplyTo: pub.IRI("https://littr.git/api/accounts/system/outbox/7ca154ff"),
448 // Content: pub.NaturalLanguageValues{{pub.NilLangRef, pub.Content("<p>Hello world</p>")}},
449 // To: pub.ItemCollection{pub.IRI("https://www.w3.org/ns/activitystreams#Public")},
450 // },
451 // &pub.Article{
452 // Type: pub.ArticleType,
453 // ID: pub.ID("http://www.test.example/article/1"),
454 // Name: pub.NaturalLanguageValues{
455 // {
456 // pub.NilLangRef,
457 // pub.Content("This someday will grow up to be an article"),
458 // },
459 // },
460 // InReplyTo: pub.ItemCollection{
461 // pub.IRI("http://www.test.example/object/1"),
462 // pub.IRI("http://www.test.example/object/778"),
463 // },
464 // },
465 // },
466 // },
467 //},
468 //"object_with_audience": testPair{
469 // expected: true,
470 // blank: &pub.Object{},
471 // result: &pub.Object{
472 // Type: pub.ObjectType,
473 // ID: pub.ID("http://www.test.example/object/1"),
474 // To: pub.ItemCollection{
475 // pub.IRI("https://www.w3.org/ns/activitystreams#Public"),
476 // },
477 // Bto: pub.ItemCollection{
478 // pub.IRI("http://example.com/sharedInbox"),
479 // },
480 // CC: pub.ItemCollection{
481 // pub.IRI("https://example.com/actors/ana"),
482 // pub.IRI("https://example.com/actors/bob"),
483 // },
484 // BCC: pub.ItemCollection{
485 // pub.IRI("https://darkside.cookie/actors/darthvader"),
486 // },
487 // },
488 //},
489 //"article_with_multiple_inreplyto": {
490 // expected: true,
491 // blank: &pub.Article{},
492 // result: &pub.Article{
493 // Type: pub.ArticleType,
494 // ID: pub.ID("http://www.test.example/article/1"),
495 // Name: pub.NaturalLanguageValues{
496 // {
497 // pub.NilLangRef,
498 // pub.Content("This someday will grow up to be an article"),
499 // },
500 // },
501 // InReplyTo: pub.ItemCollection{
502 // pub.IRI("http://www.test.example/object/1"),
503 // pub.IRI("http://www.test.example/object/778"),
504 // },
505 // },
506 //},
507 }
508
509 func getFileContents(path string) ([]byte, error) {
510 f, err := os.Open(path)
511 if err != nil {
512 return nil, err
513 }
514
515 st, err := f.Stat()
516 if err != nil {
517 return nil, err
518 }
519
520 data := make([]byte, st.Size())
521 _, _ = io.ReadFull(f, data)
522 data = bytes.Trim(data, "\x00")
523
524 return data, nil
525 }
526
527 func TestUnmarshal(t *testing.T) {
528 var err error
529
530 f := t.Errorf
531 if len(allTests) == 0 {
532 t.Skip("No tests found")
533 }
534
535 for k, pair := range allTests {
536 path := filepath.Join(dir, fmt.Sprintf("%s.json", k))
537 t.Run(path, func(t *testing.T) {
538 var data []byte
539 data, err = getFileContents(path)
540 if err != nil {
541 f("Error: %s for %s", err, path)
542 return
543 }
544 object := pair.blank
545
546 err = j.Unmarshal(data, object)
547 if err != nil {
548 f("Error: %s for %s", err, data)
549 return
550 }
551 expLbl := ""
552 if !pair.expected {
553 expLbl = "not be "
554 }
555 status := assertDeepEquals(f, object, pair.result)
556 if pair.expected != status {
557 if stopOnFailure {
558 f = t.Fatalf
559 }
560
561 f("Mock: %s: %s\n%#v\n should %sequal to expected\n%#v", k, path, object, expLbl, pair.result)
562 return
563 }
564 if !status {
565 oj, err := j.Marshal(object)
566 if err != nil {
567 f(err.Error())
568 }
569 tj, err := j.Marshal(pair.result)
570 if err != nil {
571 f(err.Error())
572 }
573 f("Mock: %s: %s\n%s\n should %sequal to expected\n%s", k, path, oj, expLbl, tj)
574 }
575 //if err == nil {
576 // fmt.Printf(" --- %s: %s\n %s\n", "PASS", k, path)
577 //}
578 })
579 }
580 }