Skip to content

Instantly share code, notes, and snippets.

@mikattack
Created August 16, 2016 19:32
Show Gist options
  • Save mikattack/340a0c00d9fc03f8819ac74fee0c201b to your computer and use it in GitHub Desktop.
Save mikattack/340a0c00d9fc03f8819ac74fee0c201b to your computer and use it in GitHub Desktop.
Example Go unit test for logging middleware
package middleware
import (
"bufio"
"bytes"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
)
func GetTestHandler() http.HandlerFunc {
fn := func(rw http.ResponseWriter, req *http.Request) {
panic("Test entered handler")
}
return http.HandlerFunc(fn)
}
func TestLogger(t *testing.T) {
buf := &bytes.Buffer{}
// Redirect STDOUT to a buffer
stdout := os.Stdout
r, w, err := os.Pipe()
if err != nil {
t.Errorf("Failed to redirect STDOUT")
}
os.Stdout = w
go func() {
scanner := bufio.NewScanner(r)
for scanner.Scan() {
buf.WriteString(scanner.Text())
}
}()
// Create test HTTP server
ts := httptest.NewServer(Logger(GetTestHandler()))
defer ts.Close()
// Trigger a request to get output to log
http.Get(fmt.Sprintf("%s/", ts.URL))
// Reset output
w.Close()
os.Stdout = stdout
// Test output
t.Log(buf)
if buf.Len() == 0 {
t.Error("No information logged to STDOUT")
}
if strings.Count(buf.String(), "\n") > 1 {
t.Error("Expected only a single line of log output")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment