Skip to content

Commit

Permalink
Merge pull request cloudflare#341 from cloudflare/tests
Browse files Browse the repository at this point in the history
Refactor tests
  • Loading branch information
prymitive authored Aug 4, 2022
2 parents 9586e8b + b08d143 commit aedc0e8
Show file tree
Hide file tree
Showing 20 changed files with 174 additions and 1,231 deletions.
124 changes: 117 additions & 7 deletions cmd/pint/main_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
package main

import (
"context"
"fmt"
"net"
"net/http"
"os"
"strconv"
"strings"
"testing"
"time"

"github.com/rogpeppe/go-internal/testscript"
"github.com/rs/zerolog"
Expand Down Expand Up @@ -44,15 +50,119 @@ func TestScripts(t *testing.T) {
testscript.Run(t, testscript.Params{
Dir: "tests",
UpdateScripts: os.Getenv("UPDATE_SNAPSHOTS") == "1",
Cmds: map[string]func(ts *testscript.TestScript, neg bool, args []string){
"http": httpServer,
},
Setup: func(env *testscript.Env) error {
// inject an env variable with the current working directory
// so we can use it to copy files into testscript workdir
cwd, err := os.Getwd()
if err != nil {
return err
}
env.Vars = append(env.Vars, fmt.Sprintf("TESTCWD=%s", cwd))
env.Values["mocks"] = &httpMocks{responses: map[string][]httpMock{}}
return nil
},
})
}

func httpServer(ts *testscript.TestScript, neg bool, args []string) {
mocks := ts.Value("mocks").(*httpMocks)

if len(args) == 0 {
ts.Fatalf("! http command requires arguments")
}
cmd := args[0]

switch cmd {
// http response name /200 200 OK
case "response":
if len(args) < 5 {
ts.Fatalf("! http response command requires '$NAME $PATH $CODE $BODY' args, got [%s]", strings.Join(args, " "))
}
name := args[1]
path := args[2]
code, err := strconv.Atoi(args[3])
ts.Check(err)
body := strings.Join(args[4:], " ")
mocks.add(name, httpMock{pattern: path, handler: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(code)
_, err := w.Write([]byte(body))
ts.Check(err)
}})
// http response name /200 200 OK
case "slow-response":
if len(args) < 6 {
ts.Fatalf("! http response command requires '$NAME $PATH $DELAY $CODE $BODY' args, got [%s]", strings.Join(args, " "))
}
name := args[1]
path := args[2]
delay, err := time.ParseDuration(args[3])
ts.Check(err)
code, err := strconv.Atoi(args[4])
ts.Check(err)
body := strings.Join(args[5:], " ")
mocks.add(name, httpMock{pattern: path, handler: func(w http.ResponseWriter, r *http.Request) {
time.Sleep(delay)
w.WriteHeader(code)
_, err := w.Write([]byte(body))
ts.Check(err)
}})
// http redirect name /foo/src /dst
case "redirect":
if len(args) != 4 {
ts.Fatalf("! http redirect command requires '$NAME $SRCPATH $DSTPATH' args, got [%s]", strings.Join(args, " "))
}
name := args[1]
srcpath := args[2]
dstpath := args[3]
mocks.add(name, httpMock{pattern: srcpath, handler: func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Location", dstpath)
w.WriteHeader(http.StatusFound)
}})
// http start name 127.0.0.1:7088
case "start":
if len(args) != 3 {
ts.Fatalf("! http start command requires '$NAME $LISTEN' args, got [%s]", strings.Join(args, " "))
}
name := args[1]
listen := args[2]

mux := http.NewServeMux()
for n, mockList := range mocks.responses {
if n == name {
for _, mock := range mockList {
mock := mock
mux.HandleFunc(mock.pattern, mock.handler)
}
break
}
}

listener, err := net.Listen("tcp", listen)
ts.Check(err)
server := &http.Server{Addr: listen, Handler: mux}
go func() {
_ = server.Serve(listener)
}()

ts.Defer(func() {
ts.Logf("http server %s shutting down", name)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = server.Shutdown(ctx)
})
default:
ts.Fatalf("! unknown http command: %v", args)
}
}

type httpMock struct {
pattern string
handler func(http.ResponseWriter, *http.Request)
}

type httpMocks struct {
responses map[string][]httpMock
}

func (m *httpMocks) add(name string, mock httpMock) {
if _, ok := m.responses[name]; !ok {
m.responses[name] = []httpMock{}
}
m.responses[name] = append(m.responses[name], mock)
}
60 changes: 2 additions & 58 deletions cmd/pint/tests/0031_ci_bitbucket.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
exec bash -x ./webserver.sh &
exec bash -c 'I=0 ; while [ ! -f server.pid ] && [ $I -lt 30 ]; do sleep 1; I=$((I+1)); done'
http response bitbucket / 200 OK
http start bitbucket 127.0.0.1:6031

mkdir testrepo
cd testrepo
Expand All @@ -25,7 +25,6 @@ stderr 'level=debug msg="Sending a request to BitBucket" method=PUT'
stderr 'level=debug msg="BitBucket request completed" status=200'
stderr 'level=debug msg="Sending a request to BitBucket" method=DELETE'
stderr 'level=debug msg="BitBucket request completed" status=200'
exec sh -c 'cat ../server.pid | xargs kill'

-- src/v1.yml --
- alert: rule1
Expand Down Expand Up @@ -56,58 +55,3 @@ repository {
repository = "rules"
}
}

-- webserver.go --
package main

import (
"context"
"io"
"log"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
)

func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "OK")
})

listener, err := net.Listen("tcp", "127.0.0.1:6031")
if err != nil {
log.Fatal(err)
}

server := &http.Server{
Addr: "127.0.0.1:6031",
}

go func() {
_ = server.Serve(listener)
}()

pid := os.Getpid()
err = os.WriteFile("server.pid", []byte(strconv.Itoa(pid)), 0644)
if err != nil {
log.Fatal(err)
}

stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
go func() {
time.Sleep(time.Minute*2)
stop <- syscall.SIGTERM
}()
<-stop
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
server.Shutdown(ctx)
}

-- webserver.sh --
env GOCACHE=$TMPDIR go run webserver.go
61 changes: 2 additions & 59 deletions cmd/pint/tests/0032_ci_github.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
exec bash -x ./webserver.sh &
exec bash -c 'I=0 ; while [ ! -f server.pid ] && [ $I -lt 30 ]; do sleep 1; I=$((I+1)); done'
http response github / 200 {}
http start github 127.0.0.1:6032

mkdir testrepo
cd testrepo
Expand All @@ -24,8 +24,6 @@ pint.ok -l debug --offline --no-color ci
! stdout .
stderr 'level=info msg="Report submitted" status="200 OK"'

exec sh -c 'cat ../server.pid | xargs kill'

-- src/v1.yml --
- alert: rule1
expr: sum(foo) by(job)
Expand Down Expand Up @@ -56,58 +54,3 @@ repository {
repo = "pint"
}
}

-- webserver.go --
package main

import (
"context"
"io"
"log"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
)

func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "{}")
})

listener, err := net.Listen("tcp", "127.0.0.1:6032")
if err != nil {
log.Fatal(err)
}

server := &http.Server{
Addr: "127.0.0.1:6032",
}

go func() {
_ = server.Serve(listener)
}()

pid := os.Getpid()
err = os.WriteFile("server.pid", []byte(strconv.Itoa(pid)), 0644)
if err != nil {
log.Fatal(err)
}

stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
go func() {
time.Sleep(time.Minute*2)
stop <- syscall.SIGTERM
}()
<-stop
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
server.Shutdown(ctx)
}

-- webserver.sh --
env GOCACHE=$TMPDIR go run webserver.go
61 changes: 2 additions & 59 deletions cmd/pint/tests/0033_ci_github_multi.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
exec bash -x ./webserver.sh &
exec bash -c 'I=0 ; while [ ! -f server.pid ] && [ $I -lt 30 ]; do sleep 1; I=$((I+1)); done'
http response github / 200 {}
http start github 127.0.0.1:6033

mkdir testrepo
cd testrepo
Expand All @@ -24,8 +24,6 @@ pint.error -l debug --no-color ci
! stdout .
stderr 'level=info msg="Report submitted" status="200 OK"'

exec sh -c 'cat ../server.pid | xargs kill'

-- src/v1.yml --
- alert: rule1
expr: sum(foo) by(instance)
Expand Down Expand Up @@ -62,58 +60,3 @@ repository {
repo = "pint"
}
}

-- webserver.go --
package main

import (
"context"
"io"
"log"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
)

func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "{}")
})

listener, err := net.Listen("tcp", "127.0.0.1:6033")
if err != nil {
log.Fatal(err)
}

server := &http.Server{
Addr: "127.0.0.1:6033",
}

go func() {
_ = server.Serve(listener)
}()

pid := os.Getpid()
err = os.WriteFile("server.pid", []byte(strconv.Itoa(pid)), 0644)
if err != nil {
log.Fatal(err)
}

stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
go func() {
time.Sleep(time.Minute*2)
stop <- syscall.SIGTERM
}()
<-stop
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
server.Shutdown(ctx)
}

-- webserver.sh --
env GOCACHE=$TMPDIR go run webserver.go
Loading

0 comments on commit aedc0e8

Please sign in to comment.