Skip to content

Commit

Permalink
add src check test
Browse files Browse the repository at this point in the history
  • Loading branch information
cvilsmeier committed Jan 6, 2025
1 parent c5088ac commit cf7b447
Show file tree
Hide file tree
Showing 9 changed files with 150 additions and 62 deletions.
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2023-2024 Christoph Vilsmeier - https://monibot.io
Copyright (c) 2023-2025 Christoph Vilsmeier - https://monibot.io

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ func main() {
// create new api
api := monibot.NewApi(apiKey)
// send a watchdog heartbeat
api.PostWatchdogHeartbeat("5f6d343a471d87687f51771530c3f2f4")
// increment a counter metric
api.PostMetricInc("c3f2fefae7f6d3e387f1d8761ff17730", 42)
api.PostWatchdogHeartbeat("a749ff35891ecb36")
// increment a counter metric by 42
api.PostMetricInc("ffe31498bc7193a4", 42)
}
```

Expand Down
2 changes: 1 addition & 1 deletion api.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ type ApiOptions struct {
// Default is 5s delay.
Delay time.Duration

// Default is time.After (this is only used in tests and hence not exported).
// Default is time.After (this is only used in tests and therefore not exported).
timeAfter sending.TimeAfterFunc
}

Expand Down
6 changes: 3 additions & 3 deletions doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ see https://monibot.io for details.
// create new api
api := monibot.NewApi(apiKey)
// send a watchdog heartbeat
api.PostWatchdogHeartbeat("5f6d343a471d87687f51771530c3f2f4")
// increment a counter metric
api.PostMetricInc("c3f2fefae7f6d3e387f1d8761ff17730", 42)
api.PostWatchdogHeartbeat("a749ff35891ecb36")
// increment a counter metric by 42
api.PostMetricInc("ffe31498bc7193a4", 42)
}
*/
package monibot
6 changes: 3 additions & 3 deletions example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ func main() {
// create new api
api := monibot.NewApi(apiKey)
// send a watchdog heartbeat
api.PostWatchdogHeartbeat("5f6d343a471d87687f51771530c3f2f4")
// increment a counter metric
api.PostMetricInc("c3f2fefae7f6d3e387f1d8761ff17730", 42)
api.PostWatchdogHeartbeat("a749ff35891ecb36")
// increment a counter metric by 42
api.PostMetricInc("ffe31498bc7193a4", 42)
}
2 changes: 1 addition & 1 deletion internal/assert/assert.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,6 @@ func (a *Assert) Nil(have any) {
func (a *Assert) Eq(want, have any) {
a.t.Helper()
if want != have {
a.t.Fatalf("want %T(%v) but have %T(%v)", want, want, have, have)
a.t.Fatalf("\nwant %T(%v)\nhave %T(%v)", want, want, have, have)
}
}
48 changes: 43 additions & 5 deletions internal/sending/sender_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func TestRetrySender(t *testing.T) {
delay := 2 * time.Second
sender := NewSender(transport, logger, trials, delay, timeAfter)
// must retry if network error
transport.responses = []fakeResponse{
transport.responses = []fakeTransportResponse{
{0, nil, fmt.Errorf("connection refused")},
{0, nil, fmt.Errorf("connection refused")},
{200, []byte("{\"ok\":true}"), nil},
Expand All @@ -39,7 +39,7 @@ func TestRetrySender(t *testing.T) {
ass.Eq("{\"ok\":true}", string(data))
transport.calls = nil
// must retry max trials
transport.responses = []fakeResponse{
transport.responses = []fakeTransportResponse{
{0, nil, fmt.Errorf("connection error 1")},
{0, nil, fmt.Errorf("connection error 2")},
{0, nil, fmt.Errorf("connection error 3")},
Expand All @@ -56,7 +56,7 @@ func TestRetrySender(t *testing.T) {
ass.Eq("connection error 3", err.Error())
transport.calls = nil
// must retry if status 502 (bad gateway)
transport.responses = []fakeResponse{
transport.responses = []fakeTransportResponse{
{502, nil, nil},
{502, nil, nil},
{200, []byte("{\"ok\":true}"), nil},
Expand All @@ -74,7 +74,7 @@ func TestRetrySender(t *testing.T) {
ass.Eq("{\"ok\":true}", string(data))
transport.calls = nil
// must not retry if authorization error
transport.responses = []fakeResponse{
transport.responses = []fakeTransportResponse{
{401, []byte("401 - Unauthorized (invalid apiKey)"), nil},
}
_, err = sender.Send(context.Background(), "GET", "/ping", nil)
Expand All @@ -83,7 +83,7 @@ func TestRetrySender(t *testing.T) {
ass.Eq("status 401: 401 - Unauthorized (invalid apiKey)", err.Error())
transport.calls = nil
// must not retry if 404 (not found) but give error
transport.responses = []fakeResponse{
transport.responses = []fakeTransportResponse{
{404, nil, nil},
}
_, err = sender.Send(context.Background(), "GET", "/wrongUrl", nil)
Expand All @@ -92,3 +92,41 @@ func TestRetrySender(t *testing.T) {
ass.Eq("status 404", err.Error())
transport.calls = nil
}

// fakeTransport is a Transport for unit tests
type fakeTransport struct {
calls []string
responses []fakeTransportResponse
}

func (f *fakeTransport) Send(ctx context.Context, method, path string, body []byte) (int, []byte, error) {
call := fmt.Sprintf("%s %s", method, path)
if len(body) > 0 {
call += fmt.Sprintf(" %s", string(body))
}
f.calls = append(f.calls, call)
if len(f.responses) == 0 {
return 0, nil, fmt.Errorf("fakeSender is out of responses for request %s %s", method, path)
}
re := f.responses[0]
f.responses = f.responses[1:]
return re.status, re.data, re.err
}

type fakeTransportResponse struct {
status int
data []byte
err error
}

// fakeLogger is a Logger for unit tests
type fakeLogger struct {
t testing.TB
enabled bool
}

func (f *fakeLogger) Debug(format string, args ...any) {
if f.enabled {
f.t.Logf(format, args...)
}
}
45 changes: 0 additions & 45 deletions internal/sending/testing_test.go

This file was deleted.

95 changes: 95 additions & 0 deletions src_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
package monibot

import (
"io/fs"
"os"
"path/filepath"
"strings"
"testing"

"github.com/cvilsmeier/monibot-go/internal/assert"
)

func TestReadmeVersion(t *testing.T) {
ass := assert.New(t)
// README.md
data, err := os.ReadFile("README.md")
ass.Nil(err)
version, ok := cutout(string(data), "### v", "\n")
ass.True(ok)
ass.Eq(Version, "v"+version)
}

func TestFixmeMarkers(t *testing.T) {
ass := assert.New(t)
filepath.WalkDir(".", func(path string, entry fs.DirEntry, err error) error {
ass.Nil(err)
if entry.IsDir() || strings.HasPrefix(path, ".git/") || strings.HasSuffix(path, "src_test.go") {
return nil
}
code, err := readCode(path)
ass.Nil(err)
if strings.Contains(code, "FIXME") {
t.Fatalf("found FIXME marker in %s", path)
}
if strings.Contains(code, "cvvvv") {
t.Fatalf("found cvvvv marker in %s", path)
}
return nil
})
}

func TestExamples(t *testing.T) {
ass := assert.New(t)
const from = "func main() {"
const to = "\n}"
// example/main.go is the canonical example
code, err := readCode("example/main.go")
ass.Nil(err)
canonical, ok := cutout(code, from, to)
ass.True(ok)
// README.md
code, err = readCode("README.md")
ass.Nil(err)
snip, ok := cutout(code, from, to)
ass.True(ok)
ass.Eq(canonical, snip)
// doc.go
code, err = readCode("doc.go")
ass.Nil(err)
snip, ok = cutout(code, from, to)
ass.True(ok)
ass.Eq(canonical, snip)
}

func readCode(name string) (string, error) {
data, err := os.ReadFile(name)
if err != nil {
return "", err
}
s := string(data)
s = replace(s, "\t", " ")
s = replace(s, "\r", "")
s = replace(s, " ", " ")
s = replace(s, "\n ", "\n")
return s, nil
}

func replace(s, from, to string) string {
for strings.Contains(s, from) {
s = strings.ReplaceAll(s, from, to)
}
return s
}

func cutout(s, from, to string) (string, bool) {
_, after, ok := strings.Cut(s, from)
if !ok {
return s, false
}
before, _, ok := strings.Cut(after, to)
if !ok {
return s, false
}
return before, true
}

0 comments on commit cf7b447

Please sign in to comment.