package oltp
import (
"path/filepath"
"testing"
)
func pushDB(t *testing.T) *DB {
t.Helper()
db, err := Open(filepath.Join(t.TempDir(), "oltp.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { db.Close() })
return db
}
// A device is remembered by the HASH of its endpoint, never the
// endpoint itself: a push endpoint is a bearer capability to notify
// somebody's phone, and quarry has no reason to hold one — notify does.
func TestPushDeviceRoundTrip(t *testing.T) {
db := pushDB(t)
const ep = "https://push.example/abcdef"
if err := db.AddPushDevice("dan", ep, "Firefox on Linux"); err != nil {
t.Fatal(err)
}
devs, err := db.PushDevices("dan")
if err != nil {
t.Fatal(err)
}
if len(devs) != 1 {
t.Fatalf("devices = %+v", devs)
}
if devs[0].UA != "Firefox on Linux" || devs[0].At == "" {
t.Fatalf("device = %+v", devs[0])
}
if devs[0].EndpointHash == ep || len(devs[0].EndpointHash) != 64 {
t.Fatalf("endpoint must be stored as a sha-256 hex hash, got %q", devs[0].EndpointHash)
}
if devs[0].EndpointHash != PushEndpointHash(ep) {
t.Fatalf("hash is not derivable from the endpoint")
}
}
// Re-registering the same browser refreshes the row rather than adding
// a second one: one endpoint is one device however often the page
// re-subscribes.
func TestPushDeviceIsIdempotentPerEndpoint(t *testing.T) {
db := pushDB(t)
for i := 0; i < 3; i++ {
if err := db.AddPushDevice("dan", "https://push.example/a", "UA"); err != nil {
t.Fatal(err)
}
}
devs, _ := db.PushDevices("dan")
if len(devs) != 1 {
t.Fatalf("devices = %+v", devs)
}
}
func TestPushDeviceDelete(t *testing.T) {
db := pushDB(t)
db.AddPushDevice("dan", "https://push.example/a", "one")
db.AddPushDevice("dan", "https://push.example/b", "two")
db.AddPushDevice("alice", "https://push.example/c", "hers")
if err := db.DeletePushDevice("dan", "https://push.example/a"); err != nil {
t.Fatal(err)
}
devs, _ := db.PushDevices("dan")
if len(devs) != 1 || devs[0].UA != "two" {
t.Fatalf("devices = %+v", devs)
}
// Another account's device is untouched by a namesake delete.
if devs, _ := db.PushDevices("alice"); len(devs) != 1 {
t.Fatalf("alice's devices = %+v", devs)
}
}