Skip to content

Commit

Permalink
🐛 fix flaky tests
Browse files Browse the repository at this point in the history
  • Loading branch information
thibaultleouay committed Nov 7, 2024
1 parent 5331c89 commit 5a36814
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 79 deletions.
59 changes: 5 additions & 54 deletions internal/monitors/monitor_trigger.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ import (
"io"
"net/http"

"github.com/fatih/color"
"github.com/rodaine/table"
"github.com/urfave/cli/v3"
)

Expand All @@ -24,7 +22,7 @@ func MonitorTrigger(httpClient *http.Client, apiKey string, monitorId string) er
}
fmt.Println("Waiting for the result...")

url := fmt.Sprintf("https://api.openstatus.dev/v1/monitor/%s/run", monitorId)
url := fmt.Sprintf("https://api.openstatus.dev/v1/monitor/%s/trigger", monitorId)

req, err := http.NewRequest("POST", url, nil)
if err != nil {
Expand All @@ -43,55 +41,14 @@ func MonitorTrigger(httpClient *http.Client, apiKey string, monitorId string) er
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)

var result []RunResult
err = json.Unmarshal(body, &result)
var r MonitorTriggerResponse
err = json.Unmarshal(body, &r)
if err != nil {
return err
}

headerFmt := color.New(color.FgGreen, color.Underline).SprintfFunc()
columnFmt := color.New(color.FgYellow).SprintfFunc()

tbl := table.New("Region", "Latency (ms)", "Status")
tbl.WithHeaderFormatter(headerFmt).WithFirstColumnFormatter(columnFmt)

var inError bool
for _, r := range result {
if r.JobType == "tcp" {
var result TCPRunResult
if err := json.Unmarshal(r.Message, &result); err != nil {
return fmt.Errorf("unable to unmarshal : %w", err)
}
if result.ErrorMessge != "" {
inError = true
tbl.AddRow(r.Region, r.Latency, color.RedString("❌"))
continue
}

}
if r.JobType == "http" {
var result HTTPRunResult
if err := json.Unmarshal(r.Message, &result); err != nil {
return fmt.Errorf("unable to unmarshal : %w", err)
}
if result.Error != "" {
inError = true
tbl.AddRow(r.Region, r.Latency, color.RedString("❌"))
continue
}
}
tbl.AddRow(r.Region, r.Latency, color.GreenString("✔"))

return err
}
tbl.Print()

if inError {
fmt.Println(color.RedString("Some regions failed"))
fmt.Printf("Result ID: %d\n", r.ResultId)

return fmt.Errorf("Some regions failed")
} else {
fmt.Println(color.GreenString("All regions passed"))
}
return nil
}

Expand All @@ -100,12 +57,6 @@ func GetMonitorsTriggerCmd() *cli.Command {
Name: "trigger",
Usage: "Trigger a monitor test",
Flags: []cli.Flag{

&cli.BoolFlag{
Name: "no-result",
Usage: "Do not return the result of the test, return the result ID",
Destination: &noResult,
},
&cli.StringFlag{
Name: "access-token",
Usage: "OpenStatus API Access Token",
Expand Down
6 changes: 3 additions & 3 deletions internal/monitors/monitor_trigger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ func Test_getMonitorTrigger(t *testing.T) {
t.Cleanup(func() {
log.SetOutput(os.Stdout)
})
err := monitors.MonitorTrigger(interceptor.GetHTTPClient(), "", "")
if err == nil {
t.Errorf("Expected log output, got nothing")
err := monitors.MonitorTrigger(interceptor.GetHTTPClient(), "", "1")
if err != nil {
t.Errorf("Expected no output, got error")
}
})
t.Run("No 200 throw error", func(t *testing.T) {
Expand Down
4 changes: 2 additions & 2 deletions internal/monitors/monitors.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ type HTTPRunResult struct {
}

type TCPRunResult struct {
ErrorMessge string `json:"errorMessage"`
Timing struct {
ErrorMessage string `json:"errorMessage"`
Timing struct {
TCPStart int64 `json:"tcpStart"`
TCPDone int64 `json:"tcpDone"`
} `json:"timing"`
Expand Down
53 changes: 33 additions & 20 deletions internal/run/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func MonitorTrigger(httpClient *http.Client, apiKey string, monitorId string) er
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)

var result []monitors.RunResult
var result []json.RawMessage
err = json.Unmarshal(body, &result)
if err != nil {
return err
Expand All @@ -54,31 +54,44 @@ func MonitorTrigger(httpClient *http.Client, apiKey string, monitorId string) er

var inError bool
for _, r := range result {
if r.JobType == "tcp" {
var result monitors.TCPRunResult
if err := json.Unmarshal(r.Message, &result); err != nil {
return fmt.Errorf("unable to unmarshal : %w", err)
}
if result.ErrorMessge != "" {
inError = true
tbl.AddRow(r.Region, r.Latency, color.RedString("❌"))
continue
}
result := monitors.RunResult{}

if err := json.Unmarshal(r, &result); err != nil {

return fmt.Errorf("unable to unmarshal : %w", err)
}
if r.JobType == "http" {
var result monitors.HTTPRunResult
if err := json.Unmarshal(r.Message, &result); err != nil {
return fmt.Errorf("unable to unmarshal : %w", err)
switch result.JobType {
case "tcp":
{
var tcp monitors.TCPRunResult
if err := json.Unmarshal(r, &result); err != nil {
return fmt.Errorf("unable to unmarshal : %w", err)
}
if tcp.ErrorMessage != "" {
inError = true
tbl.AddRow(result.Region, result.Latency, color.RedString("❌"))
continue
}

}
if result.Error != "" {
inError = true
tbl.AddRow(r.Region, r.Latency, color.RedString("❌"))
continue
case "http":
{
var http monitors.HTTPRunResult
if err := json.Unmarshal(r, &http); err != nil {
fmt.Println("Error", err)
return fmt.Errorf("unable to unmarshal : %w", err)
}
if http.Error != "" {
inError = true
tbl.AddRow(result.Region, result.Latency, color.RedString("❌"))
continue
}
}
default:
return fmt.Errorf("Unknown job type")
}

tbl.AddRow(r.Region, r.Latency, color.GreenString("✔"))
tbl.AddRow(result.Region, result.Latency, color.GreenString("✔"))

}
tbl.Print()
Expand Down
37 changes: 37 additions & 0 deletions internal/run/run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ func Test_run(t *testing.T) {
t.Run("Successfully run http reponse", func(t *testing.T) {
body := `[
{
"jobType": "http",
"status": 200,
"latency": 318,
"region": "iad",
Expand Down Expand Up @@ -88,6 +89,42 @@ func Test_run(t *testing.T) {
},
}

var bf bytes.Buffer
log.SetOutput(&bf)
t.Cleanup(func() {
log.SetOutput(os.Stdout)
})
err := run.MonitorTrigger(interceptor.GetHTTPClient(), "", "1")
if err != nil {
t.Error(err)
t.Errorf("Monitor Trigger should return error")
}
})
t.Run("Successfully run tcp reponse", func(t *testing.T) {
body := `[
{
"jobType": "tcp",
"latency": 3,
"region": "ams",
"timestamp": 1730990324626,
"timing": {
"tcpStart": 1730990324626,
"tcpDone": 1730990324629
},
"errorMessage": ""
}]`

r := io.NopCloser(bytes.NewReader([]byte(body)))

interceptor := &interceptorHTTPClient{
f: func(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
Body: r,
}, nil
},
}

var bf bytes.Buffer
log.SetOutput(&bf)
t.Cleanup(func() {
Expand Down

0 comments on commit 5a36814

Please sign in to comment.