Skip to content
Myr

test_helpers.go

This file

Path

test_helpers.go

57 lines · 1.9 KiB · Go

Last changed by

refactor(test): use the built-in max/min to simplify the code (#4576)tsingluabefore adoption6d88072

History of this file

Take it

1// Copyright 2017 Manu Martinez-Almeida. All rights reserved.2// Use of this source code is governed by a MIT style3// license that can be found in the LICENSE file.45package gin67import (8	"fmt"9	"net/http"10	"time"11)1213// CreateTestContext returns a fresh Engine and a Context associated with it.14// This is useful for tests that need to set up a new Gin engine instance15// along with a context, for example, to test middleware that doesn't depend on16// specific routes. The ResponseWriter `w` is used to initialize the context's writer.17func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine) {18	r = New()19	c = r.allocateContext(0)20	c.reset()21	c.writermem.reset(w)22	return23}2425// CreateTestContextOnly returns a fresh Context associated with the provided Engine `r`.26// This is useful for tests that operate on an existing, possibly pre-configured,27// Gin engine instance and need a new context for it.28// The ResponseWriter `w` is used to initialize the context's writer.29// The context is allocated with the `maxParams` setting from the provided engine.30func CreateTestContextOnly(w http.ResponseWriter, r *Engine) (c *Context) {31	c = r.allocateContext(r.maxParams)32	c.reset()33	c.writermem.reset(w)34	return35}3637// waitForServerReady waits for a server to be ready by making HTTP requests38// with exponential backoff. This is more reliable than time.Sleep() for testing.39func waitForServerReady(url string, maxAttempts int) error {40	client := &http.Client{41		Timeout: 100 * time.Millisecond,42	}4344	for i := 0; i < maxAttempts; i++ {45		resp, err := client.Get(url)46		if err == nil {47			resp.Body.Close()48			return nil49		}5051		// Exponential backoff: 10ms, 20ms, 40ms, 80ms, 160ms...52		backoff := min(time.Duration(10*(1<<uint(i)))*time.Millisecond, 500*time.Millisecond)53		time.Sleep(backoff)54	}5556	return fmt.Errorf("server at %s did not become ready after %d attempts", url, maxAttempts)57}