From 867e01162854bf071de1d3c8087bc1eb8f4e026b Mon Sep 17 00:00:00 2001 From: MURAOKA Taro Date: Sun, 8 Sep 2024 22:08:23 +0900 Subject: [PATCH] protocol/examples: tests --- internal/protocoltest/protocoltest.go | 14 ++++++++ protocol/examples/handler_test.go | 47 +++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 protocol/examples/handler_test.go diff --git a/internal/protocoltest/protocoltest.go b/internal/protocoltest/protocoltest.go index 7acef1d..8e47546 100644 --- a/internal/protocoltest/protocoltest.go +++ b/internal/protocoltest/protocoltest.go @@ -24,6 +24,20 @@ func CheckRegistered(t *testing.T, name string, want protocol.Protocol) { } } +func GetRegistered[T any](t *testing.T, name string) T { + t.Helper() + var zero T + got := protocol.Find(name) + if got == nil { + t.Fatalf("%s: the protocol is not registered", name) + } + p, ok := got.(T) + if !ok { + t.Fatalf("%s: registered protocol is not %T", name, zero) + } + return p +} + func Open(t *testing.T, protocolUrl string) *resource.Resource { t.Helper() u, err := url.Parse(protocolUrl) diff --git a/protocol/examples/handler_test.go b/protocol/examples/handler_test.go new file mode 100644 index 0000000..8b9b3bc --- /dev/null +++ b/protocol/examples/handler_test.go @@ -0,0 +1,47 @@ +package examples + +import ( + "io" + "path" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/koron/nvgd/internal/embedresource" + "github.com/koron/nvgd/internal/protocoltest" +) + +func TestRegistered(t *testing.T) { + protocoltest.GetRegistered[*embedresource.EmbedResource](t, "examples") +} + +func loadAsset(t *testing.T, name string) string { + t.Helper() + f, err := assetFS.Open(name) + if err != nil { + t.Fatalf("asset not found: %s", err) + } + defer f.Close() + b, err := io.ReadAll(f) + if err != nil { + t.Fatalf("failed to load the asset %s: %s", name, err) + } + return string(b) +} + +func testAsset(t *testing.T, requrl, assetpath string) { + t.Helper() + want := loadAsset(t, path.Join("assets", assetpath)) + rsrc := protocoltest.Open(t, requrl) + got := protocoltest.ReadAllString(t, rsrc) + if d := cmp.Diff(want, got); d != "" { + t.Errorf("content mismatch: -want +got\n%s", d) + } +} + +func TestContents(t *testing.T) { + testAsset(t, "examples:///line.csv", "line.csv") + testAsset(t, "examples:///pie.csv", "pie.csv") + testAsset(t, "examples:///test.csv", "test.csv") + // Currently index.html is not available. + //testAsset(t, "examples:///", "index.html") +}