move common test data to contracts/
This commit is contained in:
@@ -2,10 +2,14 @@ package mainserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
@@ -14,15 +18,51 @@ import (
|
||||
|
||||
const testSecret = "test-secret-key-base"
|
||||
|
||||
// known vector shared with the main-server (Ruby) test suite
|
||||
const testVector = "e0a7f8b5508639b1afe604b41f00070dd282d02b6444db5b4856959f175e8361"
|
||||
// The vectors are shared with the main-server (Ruby) test suite via
|
||||
// contracts/test_signature_vectors.json — the single source of truth for the
|
||||
// wire format. Do not change the formula without updating both sides.
|
||||
func signatureVectorsPath(t *testing.T) string {
|
||||
t.Helper()
|
||||
_, file, _, ok := runtime.Caller(0)
|
||||
if !ok {
|
||||
t.Fatal("cannot locate the test file")
|
||||
}
|
||||
return filepath.Join(filepath.Dir(file), "..", "..", "..", "contracts", "test_signature_vectors.json")
|
||||
}
|
||||
|
||||
func TestSignMatchesSharedVector(t *testing.T) {
|
||||
body := `{"status":"player1_won","duration_seconds":42}`
|
||||
path := "/api/internal/matches/abc/result"
|
||||
got := Sign(1_700_000_000, path, []byte(body), []byte(testSecret))
|
||||
if got != testVector {
|
||||
t.Fatalf("Sign = %q, want %q", got, testVector)
|
||||
type signatureVector struct {
|
||||
Name string `json:"name"`
|
||||
Secret string `json:"secret"`
|
||||
Timestamp int64 `json:"timestamp"`
|
||||
Path string `json:"path"`
|
||||
Body string `json:"body"`
|
||||
SignatureHex string `json:"signature_hex"`
|
||||
}
|
||||
|
||||
func loadSignatureVectors(t *testing.T) []signatureVector {
|
||||
t.Helper()
|
||||
data, err := os.ReadFile(signatureVectorsPath(t))
|
||||
if err != nil {
|
||||
t.Fatalf("read signature vectors: %v", err)
|
||||
}
|
||||
var doc struct {
|
||||
Vectors []signatureVector `json:"vectors"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &doc); err != nil {
|
||||
t.Fatalf("parse signature vectors: %v", err)
|
||||
}
|
||||
if len(doc.Vectors) == 0 {
|
||||
t.Fatal("no signature vectors found")
|
||||
}
|
||||
return doc.Vectors
|
||||
}
|
||||
|
||||
func TestSignMatchesSharedVectors(t *testing.T) {
|
||||
for _, v := range loadSignatureVectors(t) {
|
||||
got := Sign(v.Timestamp, v.Path, []byte(v.Body), []byte(v.Secret))
|
||||
if got != v.SignatureHex {
|
||||
t.Errorf("vector %q: Sign = %q, want %q", v.Name, got, v.SignatureHex)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user