github.com/pf-qiu/concourse/v6@v6.7.3-0.20201207032516-1f455d73275f/fly/integration/events_helper_test.go (about)

     1  package integration_test
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"net/http"
     7  
     8  	"github.com/pf-qiu/concourse/v6/atc"
     9  	"github.com/pf-qiu/concourse/v6/atc/event"
    10  	. "github.com/onsi/gomega"
    11  	"github.com/onsi/gomega/gbytes"
    12  	"github.com/onsi/gomega/gexec"
    13  	"github.com/onsi/gomega/ghttp"
    14  	"github.com/vito/go-sse/sse"
    15  )
    16  
    17  func BuildEventsHandler(buildID int, streaming chan<- struct{}, events <-chan atc.Event) http.HandlerFunc {
    18  	return ghttp.CombineHandlers(
    19  		ghttp.VerifyRequest("GET", fmt.Sprintf("/api/v1/builds/%d/events", buildID)),
    20  		func(w http.ResponseWriter, r *http.Request) {
    21  			flusher := w.(http.Flusher)
    22  
    23  			w.Header().Add("Content-Type", "text/event-stream; charset=utf-8")
    24  			w.Header().Add("Cache-Control", "no-cache, no-store, must-revalidate")
    25  			w.Header().Add("Connection", "keep-alive")
    26  
    27  			w.WriteHeader(http.StatusOK)
    28  
    29  			flusher.Flush()
    30  
    31  			close(streaming)
    32  
    33  			id := 0
    34  
    35  			for e := range events {
    36  				payload, err := json.Marshal(event.Message{Event: e})
    37  				Expect(err).NotTo(HaveOccurred())
    38  
    39  				event := sse.Event{
    40  					ID:   fmt.Sprintf("%d", id),
    41  					Name: "event",
    42  					Data: payload,
    43  				}
    44  
    45  				err = event.Write(w)
    46  				Expect(err).NotTo(HaveOccurred())
    47  
    48  				flusher.Flush()
    49  
    50  				id++
    51  			}
    52  
    53  			err := sse.Event{
    54  				Name: "end",
    55  			}.Write(w)
    56  			Expect(err).NotTo(HaveOccurred())
    57  		},
    58  	)
    59  }
    60  
    61  func AssertEvents(sess *gexec.Session, streaming <-chan struct{}, events chan<- atc.Event) {
    62  	Eventually(streaming).Should(BeClosed())
    63  
    64  	events <- event.Log{Payload: "sup"}
    65  
    66  	Eventually(sess.Out).Should(gbytes.Say("sup"))
    67  
    68  	close(events)
    69  
    70  	<-sess.Exited
    71  	Expect(sess.ExitCode()).To(Equal(0))
    72  }
    73  
    74  func AssertErrorEvents(sess *gexec.Session, streaming <-chan struct{}, events chan<- atc.Event) {
    75  	Eventually(streaming).Should(BeClosed())
    76  
    77  	events <- event.Error{Message: "oh no"}
    78  	events <- event.Status{Status: atc.StatusErrored}
    79  
    80  	Eventually(sess.Out).Should(gbytes.Say("oh no"))
    81  
    82  	close(events)
    83  
    84  	<-sess.Exited
    85  	Expect(sess.ExitCode()).To(Equal(2))
    86  }