Skip to content

Commit

Permalink
Tests for SSE API
Browse files Browse the repository at this point in the history
  • Loading branch information
mortenlj committed Aug 21, 2024
1 parent b1fb1da commit 0d83db3
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions pkg/election/official/official_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package official

import (
"context"
"fmt"
. "github.com/benjamintf1/unmarshalledmatchers"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
Expand Down Expand Up @@ -72,4 +73,55 @@ var _ = Describe("Official", func() {
Expect(io.ReadAll(res.Body)).To(ContainUnorderedJSON(`{"name":"new result"}`))
})
})

Context("sse api", func() {
var w *httptest.ResponseRecorder

BeforeEach(func() {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, 100*time.Millisecond)
DeferCleanup(cancel)

w = httptest.NewRecorder()
o.lastResult = result{
Name: "last result",
LastUpdate: "then",
}
})

It("should return initial election result", func() {
go o.sseHandler(ctx)(w, nil)
time.Sleep(10 * time.Millisecond)

line, err := w.Body.ReadString('\n')
Expect(err).ToNot(HaveOccurred())
Expect(line).To(HavePrefix("data: "))
data := line[6:]
Expect(data).To(MatchJSON(`{"name":"last result","last_update":"then"}`))
})

It("should continue to update election results", func() {
go o.sseHandler(ctx)(w, nil)
time.Sleep(10 * time.Millisecond)

line, err := w.Body.ReadString('\n')
Expect(err).ToNot(HaveOccurred())
Expect(line).To(HavePrefix("data: "))
data := line[6:]
Expect(data).To(MatchJSON(`{"name":"last result","last_update":"then"}`))
Expect(w.Body.ReadString('\n')).To(Equal("\n"))

for _, result := range []string{"first result", "second result", "third result"} {
electionResults <- result
time.Sleep(10 * time.Millisecond)

line, err := w.Body.ReadString('\n')
Expect(err).ToNot(HaveOccurred())
Expect(line).To(HavePrefix("data: "))
data := line[6:]
Expect(data).To(ContainUnorderedJSON(fmt.Sprintf(`{"name":"%s"}`, result)))
Expect(w.Body.ReadString('\n')).To(Equal("\n"))
}
})
})
})

0 comments on commit 0d83db3

Please sign in to comment.