aboutsummaryrefslogtreecommitdiffhomepage
path: root/internal/pipewire/pod_test.go
blob: a39f961415d053e6b2ab6ed1079c9058a2ade9bc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package pipewire_test

import (
	"encoding"
	"encoding/json"
	"reflect"
	"testing"
)

type encodingTestCases[V any, S interface {
	encoding.BinaryMarshaler
	encoding.BinaryUnmarshaler
	*V
}] []struct {
	// Uninterpreted name of subtest.
	name string
	// Encoded data.
	wantData []byte
	// Value corresponding to wantData.
	value V
	// Expected decoding error. Skips encoding check if non-nil.
	wantErr error
}

// run runs all test cases as subtests of [testing.T].
func (testCases encodingTestCases[V, S]) run(t *testing.T) {
	t.Helper()

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			t.Parallel()

			t.Run("decode", func(t *testing.T) {
				t.Parallel()

				var value V
				if err := S(&value).UnmarshalBinary(tc.wantData); err != nil {
					t.Fatalf("UnmarshalBinary: error = %v", err)
				}
				if !reflect.DeepEqual(&value, &tc.value) {
					t.Fatalf("UnmarshalBinary:\n%s\nwant\n%s", mustMarshalJSON(value), mustMarshalJSON(tc.value))
				}
			})

			t.Run("encode", func(t *testing.T) {
				t.Parallel()

				if gotData, err := S(&tc.value).MarshalBinary(); err != nil {
					t.Fatalf("MarshalBinary: error = %v", err)
				} else if string(gotData) != string(tc.wantData) {
					t.Fatalf("MarshalBinary: %#v, want %#v", gotData, tc.wantData)
				}
			})
		})
	}
}

// mustMarshalJSON calls [json.Marshal] and returns the result.
func mustMarshalJSON(v any) string {
	if data, err := json.Marshal(v); err != nil {
		panic(err)
	} else {
		return string(data)
	}
}