gtsocial-umbx

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

negotiate_test.go (1918B)


      1 package util
      2 
      3 import (
      4 	"net/http"
      5 	"net/http/httptest"
      6 	"strings"
      7 	"testing"
      8 
      9 	"github.com/gin-gonic/gin"
     10 )
     11 
     12 type testMIMES []MIME
     13 
     14 func (tm testMIMES) String(t *testing.T) string {
     15 	t.Helper()
     16 
     17 	res := tm.StringS(t)
     18 	return strings.Join(res, ",")
     19 }
     20 
     21 func (tm testMIMES) StringS(t *testing.T) []string {
     22 	t.Helper()
     23 
     24 	res := make([]string, 0, len(tm))
     25 	for _, m := range tm {
     26 		res = append(res, string(m))
     27 	}
     28 	return res
     29 }
     30 
     31 func TestNegotiateFormat(t *testing.T) {
     32 	tests := []struct {
     33 		incoming []string
     34 		offered  testMIMES
     35 		format   string
     36 	}{
     37 		{incoming: testMIMES{AppJSON}.StringS(t), offered: testMIMES{AppJRDJSON, AppJSON}, format: "application/json"},
     38 		{incoming: testMIMES{AppJRDJSON}.StringS(t), offered: testMIMES{AppJRDJSON, AppJSON}, format: "application/jrd+json"},
     39 		{incoming: testMIMES{AppJRDJSON, AppJSON}.StringS(t), offered: testMIMES{AppJRDJSON}, format: "application/jrd+json"},
     40 		{incoming: testMIMES{AppJRDJSON, AppJSON}.StringS(t), offered: testMIMES{AppJSON}, format: "application/json"},
     41 		{incoming: testMIMES{"text/html,application/xhtml+xml,application/xml;q=0.9;q=0.8"}.StringS(t), offered: testMIMES{AppJSON, AppXML}, format: "application/xml"},
     42 		{incoming: testMIMES{"text/html,application/xhtml+xml,application/xml;q=0.9;q=0.8"}.StringS(t), offered: testMIMES{TextHTML, AppXML}, format: "text/html"},
     43 	}
     44 
     45 	for _, tt := range tests {
     46 		name := "incoming:" + strings.Join(tt.incoming, ",") + " offered:" + tt.offered.String(t)
     47 		t.Run(name, func(t *testing.T) {
     48 			tt := tt
     49 			t.Parallel()
     50 
     51 			c, _ := gin.CreateTestContext(httptest.NewRecorder())
     52 			c.Request = &http.Request{
     53 				Header: make(http.Header),
     54 			}
     55 			for _, header := range tt.incoming {
     56 				c.Request.Header.Add("accept", header)
     57 			}
     58 
     59 			format := NegotiateFormat(c, tt.offered.StringS(t)...)
     60 			if tt.format != format {
     61 				t.Fatalf("expected format: '%s', got format: '%s'", tt.format, format)
     62 			}
     63 		})
     64 	}
     65 }