Browse code

libnetwork/bitseq: add marshal/unmarshal tests

Catch any backwards-compatibility hazards with serialization of
sequences early.

Signed-off-by: Cory Snider <csnider@mirantis.com>

Cory Snider authored on 2023/01/19 06:23:53
Showing 1 changed files
... ...
@@ -1359,3 +1359,67 @@ func TestGetFirstAvailableFromCurrent(t *testing.T) {
1359 1359
 		}
1360 1360
 	}
1361 1361
 }
1362
+
1363
+func TestMarshalJSON(t *testing.T) {
1364
+	const expectedID = "my-bitseq"
1365
+	expected := []byte("hello libnetwork")
1366
+	hnd, err := NewHandle("", nil, expectedID, uint64(len(expected)*8))
1367
+	if err != nil {
1368
+		t.Fatal(err)
1369
+	}
1370
+
1371
+	for i, c := range expected {
1372
+		for j := 0; j < 8; j++ {
1373
+			if c&(1<<j) == 0 {
1374
+				continue
1375
+			}
1376
+			if err := hnd.Set(uint64(i*8 + j)); err != nil {
1377
+				t.Fatal(err)
1378
+			}
1379
+		}
1380
+	}
1381
+
1382
+	hstr := hnd.String()
1383
+	t.Log(hstr)
1384
+	marshaled, err := hnd.MarshalJSON()
1385
+	if err != nil {
1386
+		t.Fatalf("MarshalJSON() err = %v", err)
1387
+	}
1388
+	t.Logf("%s", marshaled)
1389
+
1390
+	// Serializations of hnd as would be marshaled by versions of the code
1391
+	// found in the wild. We need to support unmarshaling old versions to
1392
+	// maintain backwards compatibility with sequences persisted on disk.
1393
+	const (
1394
+		goldenV0 = `{"id":"my-bitseq","sequence":"AAAAAAAAAIAAAAAAAAAAPRamNjYAAAAAAAAAAfYENpYAAAAAAAAAAUZ2pi4AAAAAAAAAAe72TtYAAAAAAAAAAQ=="}`
1395
+	)
1396
+
1397
+	if string(marshaled) != goldenV0 {
1398
+		t.Errorf("MarshalJSON() output differs from golden. Please add a new golden case to this test.")
1399
+	}
1400
+
1401
+	for _, tt := range []struct {
1402
+		name string
1403
+		data []byte
1404
+	}{
1405
+		{name: "Live", data: marshaled},
1406
+		{name: "Golden-v0", data: []byte(goldenV0)},
1407
+	} {
1408
+		tt := tt
1409
+		t.Run("UnmarshalJSON="+tt.name, func(t *testing.T) {
1410
+			hnd2, err := NewHandle("", nil, "", 0)
1411
+			if err != nil {
1412
+				t.Fatal(err)
1413
+			}
1414
+			if err := hnd2.UnmarshalJSON(tt.data); err != nil {
1415
+				t.Errorf("UnmarshalJSON() err = %v", err)
1416
+			}
1417
+
1418
+			h2str := hnd2.String()
1419
+			t.Log(h2str)
1420
+			if hstr != h2str {
1421
+				t.Errorf("Unmarshaled a different bitseq: want %q, got %q", hstr, h2str)
1422
+			}
1423
+		})
1424
+	}
1425
+}