Skip to content

Instantly share code, notes, and snippets.

@barkbay
Created June 13, 2022 12:46
Show Gist options
  • Select an option

  • Save barkbay/f88ee6d6eb60cbd72403d5af8be9c623 to your computer and use it in GitHub Desktop.

Select an option

Save barkbay/f88ee6d6eb60cbd72403d5af8be9c623 to your computer and use it in GitHub Desktop.
HTTP Integration Test
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License 2.0;
// you may not use this file except in compliance with the Elastic License 2.0.
package association
import (
"context"
"fmt"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"testing"
"time"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/suite"
)
type e2eTestSuite struct {
suite.Suite
port int
}
func (s *e2eTestSuite) Test_EndToEnd_Request() {
for i := 1; i <= 1000000; i++ {
connectionInfo := UnmanagedAssociationConnectionInfo{
URL: fmt.Sprintf("http://localhost:%d", s.port),
}
_, err := connectionInfo.Request("/foo", "{}")
s.Assertions.Error(err)
}
}
func TestE2ETestSuite(t *testing.T) {
suite.Run(t, &e2eTestSuite{})
}
func (s *e2eTestSuite) SetupSuite() {
// Find an available TCP port
listener, err := net.Listen("tcp", ":0")
s.Assertions.NoError(err)
s.port = listener.Addr().(*net.TCPAddr).Port
serverReady := make(chan bool)
server := Server{
listener: listener,
ServerReady: serverReady,
}
go server.Start()
<-serverReady
}
func (s *e2eTestSuite) TearDownSuite() {
p, _ := os.FindProcess(syscall.Getpid())
p.Signal(syscall.SIGINT)
}
func (s *e2eTestSuite) SetupTest() {}
func (s *e2eTestSuite) TearDownTest() {}
// Fake http server
type Server struct {
listener net.Listener
ServerReady chan bool
}
type ErrorHandler struct{}
func (eh *ErrorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Simulated error", http.StatusInternalServerError)
}
// Start starts http server with a handler that always returns an error.
func (s *Server) Start() {
srv := &http.Server{Handler: &ErrorHandler{}}
go func() {
if err := srv.Serve(s.listener); err != nil {
logrus.Errorf(err.Error())
logrus.Infof("shutting down the server")
}
}()
if s.ServerReady != nil {
s.ServerReady <- true
}
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if srv != nil {
err := srv.Shutdown(ctx)
if err != nil {
logrus.Errorf(err.Error())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment