package transcode import ( "errors" "testing" ) // TestRegistryRegisterAndLookup 断言注册 / 查找 / 发现三件事。 func TestRegistryRegisterAndLookup(t *testing.T) { reg := NewRegistry() codec := newStubCodec() if err := reg.Register(codec); err != nil { t.Fatalf("register: %v", err) } got, ok := reg.Lookup(FormatAMR, FormatWAV) if !ok || got != Codec(codec) { t.Fatalf("lookup = (%v, %v), want the registered codec", got, ok) } if _, ok := reg.Lookup(FormatWAV, FormatAMR); ok { t.Fatalf("reverse route must not exist") } if n := reg.Len(); n != 1 { t.Fatalf("Len = %d, want 1", n) } if formats := reg.Formats(); len(formats) != 2 || formats[0] != FormatAMR || formats[1] != FormatWAV { t.Fatalf("Formats = %v, want [amr wav](去重且有序)", formats) } } // TestRegistryRejectsBadCodecs 断言不合法注册项被拒(nil / 空格式 / 自我转换), // 且 repeated 注册返回 ErrDuplicate。 func TestRegistryRejectsBadCodecs(t *testing.T) { reg := NewRegistry() cases := []struct { name string codec Codec }{ {"nil", nil}, {"empty from", &stubCodec{from: "", to: FormatWAV}}, {"empty to", &stubCodec{from: FormatAMR, to: ""}}, {"identity", &stubCodec{from: FormatWAV, to: FormatWAV}}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { if err := reg.Register(tc.codec); !errors.Is(err, ErrInvalidCodec) { t.Fatalf("err = %v, want ErrInvalidCodec", err) } }) } if err := reg.Register(newStubCodec()); err != nil { t.Fatalf("register: %v", err) } if err := reg.Register(newStubCodec()); !errors.Is(err, ErrDuplicate) { t.Fatalf("duplicate err = %v, want ErrDuplicate", err) } if n := reg.Len(); n != 1 { t.Fatalf("Len = %d after a rejected duplicate, want 1", n) } } // TestRegistryFormatsDedupe 断言多路共享格式时 Formats 去重。 func TestRegistryFormatsDedupe(t *testing.T) { reg := NewRegistry() if err := reg.Register(&stubCodec{from: FormatAMR, to: FormatWAV}); err != nil { t.Fatalf("register: %v", err) } if err := reg.Register(&stubCodec{from: FormatWAV, to: FormatAMRWB}); err != nil { t.Fatalf("register: %v", err) } want := []Format{FormatAMR, FormatAMRWB, FormatWAV} got := reg.Formats() if len(got) != len(want) { t.Fatalf("Formats = %v, want %v", got, want) } for i := range want { if got[i] != want[i] { t.Fatalf("Formats = %v, want %v(有序)", got, want) } } }