package notify
import (
"context"
"net/http"
"net/http/httptest"
"testing"
)
// notify 0.1.9 records each device's outcome in the push message's
// extras.devices; the client hands them on, one per device.
func TestPushOutcomeCarriesEachDevicesOutcome(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/v1/notifications":
w.Write([]byte(`{"items":[{"ID":"n1"}]}`))
case "/v1/notifications/n1/messages":
w.Write([]byte(`[{"Channel":"push","Status":"sent","ErrorText":"delivered 1/2: 1 failure(s) (x)",` +
`"extras":{"devices":[` +
`{"subscriptionId":"s1","host":"fcm.googleapis.com","outcome":"delivered"},` +
`{"subscriptionId":"s2","host":"web.push.apple.com","outcome":"retired","status":403,"reason":"BadJwtToken"}]}}]`))
default:
t.Errorf("unexpected %s", r.URL.Path)
}
}))
defer srv.Close()
res, err := New(srv.URL, "").PushOutcome(context.Background(), "dan", "txn-1")
if err != nil {
t.Fatal(err)
}
if len(res.Devices) != 2 {
t.Fatalf("FAIL: %d devices, want 2: %+v", len(res.Devices), res.Devices)
}
if d := res.Devices[1]; d.Host != "web.push.apple.com" || d.Outcome != "retired" || d.Status != 403 || d.Reason != "BadJwtToken" {
t.Errorf("FAIL: second device %+v", d)
}
if d := res.Devices[0]; d.Outcome != "delivered" || d.Status != 0 {
t.Errorf("FAIL: first device %+v", d)
}
}
// A send that reached no device records its per-device rows on the
// error message too, with each device's endpointSha256.
func TestPushOutcomeReadsDevicesOnAnErrorMessage(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/v1/notifications":
w.Write([]byte(`{"items":[{"ID":"n1"}]}`))
default:
w.Write([]byte(`[{"Channel":"push","Status":"error","ErrorText":"webpush: status 403",` +
`"extras":{"devices":[{"subscriptionId":"s1","endpointSha256":"aa11","host":"web.push.apple.com","outcome":"failed","status":403,"reason":"BadJwtToken"}]}}]`))
}
}))
defer srv.Close()
res, err := New(srv.URL, "").PushOutcome(context.Background(), "dan", "txn-1")
if err != nil {
t.Fatal(err)
}
if res.Status != "error" || len(res.Devices) != 1 || res.Devices[0].EndpointSHA256 != "aa11" {
t.Errorf("FAIL: %+v", res)
}
}