Repository navigation
Expand file tree
/
Copy pathcodec_test.go
More file actions
70 lines (59 loc) · 1.65 KB
/
Copy pathcodec_test.go
File metadata and controls
70 lines (59 loc) · 1.65 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
68
69
70
package api
import (
"bytes"
"io"
"testing"
)
type testCodec struct{}
func (codec testCodec) ContentType() string {
return "application/test"
}
func (codec testCodec) Encode(w io.Writer, value any) error {
_, err := w.Write([]byte("encoded"))
return err
}
func TestDefaultJSONCodecIsRegistered(t *testing.T) {
codec, err := CodecByName("json")
if err != nil {
t.Fatalf("expected json codec, got error: %v", err)
}
if codec.ContentType() != "application/json" {
t.Fatalf("unexpected content type: %s", codec.ContentType())
}
var buf bytes.Buffer
if err := codec.Encode(&buf, map[string]string{"status": "ok"}); err != nil {
t.Fatalf("encode failed: %v", err)
}
if buf.String() != "{\"status\":\"ok\"}\n" {
t.Fatalf("unexpected json output: %q", buf.String())
}
}
func TestRegisteredCodecCanBeResolved(t *testing.T) {
RegisterCodec("test-codec", testCodec{})
codec, err := CodecByName("test-codec")
if err != nil {
t.Fatalf("expected registered codec, got error: %v", err)
}
if codec.ContentType() != "application/test" {
t.Fatalf("unexpected content type: %s", codec.ContentType())
}
}
func TestCodecByNameReturnsErrorForMissingCodec(t *testing.T) {
codec, err := CodecByName("missing-codec")
if err == nil {
t.Fatalf("expected error")
}
if codec != nil {
t.Fatalf("expected nil codec, got %#v", codec)
}
}
func TestRegisterCodecIgnoresInvalidInput(t *testing.T) {
RegisterCodec("", testCodec{})
RegisterCodec("nil-codec", nil)
if _, err := CodecByName(""); err == nil {
t.Fatalf("empty codec name should not be registered")
}
if _, err := CodecByName("nil-codec"); err == nil {
t.Fatalf("nil codec should not be registered")
}
}