github.com/abemedia/go-don@v0.2.2-0.20240329015135-be88e32bb73b/api_test.go (about)

     1  package don_test
     2  
     3  import (
     4  	"fmt"
     5  	"net"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/abemedia/go-don"
    10  	_ "github.com/abemedia/go-don/encoding/text"
    11  	"github.com/abemedia/go-don/internal/test"
    12  	"github.com/abemedia/httprouter"
    13  	"github.com/valyala/fasthttp"
    14  )
    15  
    16  func TestAPI(t *testing.T) {
    17  	t.Run("Router", func(t *testing.T) {
    18  		api := don.New(nil)
    19  		test.Router(t, api, api.RequestHandler(), "")
    20  	})
    21  
    22  	t.Run("ListenAndServe", func(t *testing.T) {
    23  		testAPI(t, func(api *don.API, ln net.Listener) error {
    24  			ln.Close()
    25  			return api.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", ln.Addr().(*net.TCPAddr).Port))
    26  		})
    27  	})
    28  
    29  	t.Run("Serve", func(t *testing.T) {
    30  		testAPI(t, func(api *don.API, ln net.Listener) error { return api.Serve(ln) })
    31  	})
    32  }
    33  
    34  func testAPI(t *testing.T, serve func(api *don.API, ln net.Listener) error) {
    35  	t.Helper()
    36  
    37  	api := don.New(nil)
    38  	api.Get("/", func(ctx *fasthttp.RequestCtx, _ httprouter.Params) {
    39  		ctx.WriteString("OK") //nolint:errcheck
    40  	})
    41  
    42  	ln, err := net.Listen("tcp", ":0")
    43  	if err != nil {
    44  		t.Fatal(err)
    45  	}
    46  
    47  	go func() {
    48  		if err := serve(api, ln); err != nil {
    49  			t.Error(err)
    50  		}
    51  	}()
    52  
    53  	time.Sleep(time.Millisecond) // Wait for server to be listening.
    54  
    55  	if t.Failed() {
    56  		t.FailNow() // Fail fast if calling serve failed.
    57  	}
    58  
    59  	code, body, err := fasthttp.Get(nil, fmt.Sprintf("http://localhost:%d/", ln.Addr().(*net.TCPAddr).Port))
    60  	if err != nil {
    61  		t.Fatal(err)
    62  	}
    63  
    64  	if code != fasthttp.StatusOK {
    65  		t.Fatal("should return success status")
    66  	}
    67  
    68  	if string(body) != "OK" {
    69  		t.Fatalf(`should return body "OK": %q`, body)
    70  	}
    71  }