Skip to content

Commit

Permalink
protocol/examples: tests
Browse files Browse the repository at this point in the history
  • Loading branch information
koron committed Sep 8, 2024
1 parent dba440a commit 867e011
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
14 changes: 14 additions & 0 deletions internal/protocoltest/protocoltest.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
47 changes: 47 additions & 0 deletions protocol/examples/handler_test.go
Original file line number Diff line number Diff line change
@@ -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")
}

0 comments on commit 867e011

Please sign in to comment.