Repository navigation
Expand file tree
/
Copy pathcodec_test.go
More file actions
67 lines (60 loc) · 1.51 KB
/
Copy pathcodec_test.go
File metadata and controls
67 lines (60 loc) · 1.51 KB
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
66
67
package rchan
import (
"context"
"errors"
"fmt"
"testing"
)
func TestJSONCodecRoundtrip(t *testing.T) {
type point struct{ X, Y int }
data, err := JSON.Marshal(point{1, 2})
if err != nil {
t.Fatal(err)
}
var p point
if err := JSON.Unmarshal(data, &p); err != nil {
t.Fatal(err)
}
if p != (point{1, 2}) {
t.Fatalf("roundtrip got %+v", p)
}
if JSON.Name() != "json" {
t.Fatalf("Name() = %q, want json", JSON.Name())
}
}
type prefixCodec struct{}
func (prefixCodec) Marshal(v any) ([]byte, error) {
b, err := JSON.Marshal(v)
if err != nil {
return nil, err
}
return append([]byte("x:"), b...), nil
}
func (prefixCodec) Unmarshal(d []byte, v any) error {
if len(d) < 2 || d[0] != 'x' || d[1] != ':' {
return fmt.Errorf("prefixCodec: bad frame")
}
return JSON.Unmarshal(d[2:], v)
}
func (prefixCodec) Name() string { return "prefix" }
func TestCustomCodecRoundtripAndMismatch(t *testing.T) {
ctx := context.Background()
rdb := testClient(t)
name := testName(t, rdb)
ch, err := New[string](ctx, rdb, name, WithCapacity(4), WithCodec(prefixCodec{}))
if err != nil {
t.Fatal(err)
}
defer ch.Stop()
if err := ch.Send(ctx, "custom"); err != nil {
t.Fatal(err)
}
v, ok, err := ch.Recv(ctx)
if err != nil || !ok || v != "custom" {
t.Fatalf("v=%q ok=%v err=%v", v, ok, err)
}
// Opening the same channel with a different codec must be rejected.
if _, err := New[string](ctx, rdb, name, WithCapacity(4)); !errors.Is(err, ErrMismatch) {
t.Fatalf("want ErrMismatch for codec change, got %v", err)
}
}