Skip to content

Commit

Permalink
Add a basic test for dynamic linking
Browse files Browse the repository at this point in the history
  • Loading branch information
cespare committed Aug 24, 2021
1 parent 3c9a0f3 commit 3b9a658
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 0 deletions.
1 change: 1 addition & 0 deletions dynamic/.gitignore
@@ -0,0 +1 @@
/plugin.so
46 changes: 46 additions & 0 deletions dynamic/dynamic_test.go
@@ -0,0 +1,46 @@
// +build linux darwin

package main

import (
"bytes"
"log"
"os/exec"
"plugin"
"testing"
)

// This is a cursory test that checks whether things work under dynamic linking.

func TestMain(m *testing.M) {
cmd := exec.Command(
"go", "build",
"-buildmode", "plugin",
"-o", "plugin.so",
"plugin.go",
)
var out bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &out
if err := cmd.Run(); err != nil {
log.Fatalf("Error building plugin: %s\nOutput:\n%s", err, out.String())
}
m.Run()
}

func TestDynamic(t *testing.T) {
plug, err := plugin.Open("plugin.so")
if err != nil {
t.Fatal(err)
}
for _, test := range []string{
"TestSum",
"TestDigest",
} {
f, err := plug.Lookup(test)
if err != nil {
t.Fatalf("cannot find func %s: %s", test, err)
}
f.(func(*testing.T))(t)
}
}
46 changes: 46 additions & 0 deletions dynamic/plugin.go
@@ -0,0 +1,46 @@
// +build ignore

package main

import (
"fmt"
"log"
"testing"

"github.com/cespare/xxhash/v2"
)

const (
in = "Call me Ishmael. Some years ago--never mind how long precisely-"
want = 0x02a2e85470d6fd96
)

func TestSum(t *testing.T) {
got := xxhash.Sum64String(in)
if got != want {
t.Fatalf("Sum64String: got 0x%x; want 0x%x", got, want)
}
}

func TestDigest(t *testing.T) {
for chunkSize := 1; chunkSize <= len(in); chunkSize++ {
name := fmt.Sprintf("[chunkSize=%d]", chunkSize)
t.Run(name, func(t *testing.T) {
d := xxhash.New()
for i := 0; i < len(in); i += chunkSize {
chunk := in[i:]
if len(chunk) > chunkSize {
chunk = chunk[:chunkSize]
}
n, err := d.WriteString(chunk)
if err != nil || n != len(chunk) {
t.Fatalf("Digest.WriteString: got (%d, %v); want (%d, nil)",
n, err, len(chunk))
}
}
if got := d.Sum64(); got != want {
log.Fatalf("Digest.Sum64: got 0x%x; want 0x%x", got, want)
}
})
}
}

0 comments on commit 3b9a658

Please sign in to comment.