...

Source file src/github.com/go-openapi/runtime/middleware/swaggerui_test.go

Documentation: github.com/go-openapi/runtime/middleware

     1  package middleware
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"net/http"
     7  	"net/http/httptest"
     8  	"strings"
     9  	"testing"
    10  
    11  	"github.com/stretchr/testify/assert"
    12  	"github.com/stretchr/testify/require"
    13  )
    14  
    15  func TestSwaggerUIMiddleware(t *testing.T) {
    16  	var o SwaggerUIOpts
    17  	o.EnsureDefaults()
    18  	swui := SwaggerUI(o, nil)
    19  
    20  	t.Run("with defaults ", func(t *testing.T) {
    21  		req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/docs", nil)
    22  		require.NoError(t, err)
    23  		recorder := httptest.NewRecorder()
    24  
    25  		swui.ServeHTTP(recorder, req)
    26  		assert.Equal(t, http.StatusOK, recorder.Code)
    27  
    28  		assert.Equal(t, "text/html; charset=utf-8", recorder.Header().Get(contentTypeHeader))
    29  		assert.Contains(t, recorder.Body.String(), fmt.Sprintf("<title>%s</title>", o.Title))
    30  		assert.Contains(t, recorder.Body.String(), fmt.Sprintf(`url: '%s',`, strings.ReplaceAll(o.SpecURL, `/`, `\/`)))
    31  		assert.Contains(t, recorder.Body.String(), swaggerLatest)
    32  		assert.Contains(t, recorder.Body.String(), swaggerPresetLatest)
    33  		assert.Contains(t, recorder.Body.String(), swaggerStylesLatest)
    34  		assert.Contains(t, recorder.Body.String(), swaggerFavicon16Latest)
    35  		assert.Contains(t, recorder.Body.String(), swaggerFavicon32Latest)
    36  	})
    37  
    38  	t.Run("with path with a trailing / (issue #238)", func(t *testing.T) {
    39  		req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/docs/", nil)
    40  		require.NoError(t, err)
    41  		recorder := httptest.NewRecorder()
    42  
    43  		swui.ServeHTTP(recorder, req)
    44  		assert.Equal(t, http.StatusOK, recorder.Code)
    45  	})
    46  
    47  	t.Run("should yield not found", func(t *testing.T) {
    48  		req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/nowhere", nil)
    49  		require.NoError(t, err)
    50  		recorder := httptest.NewRecorder()
    51  
    52  		swui.ServeHTTP(recorder, req)
    53  		assert.Equal(t, http.StatusNotFound, recorder.Code)
    54  	})
    55  
    56  	t.Run("edge cases", func(t *testing.T) {
    57  		t.Run("with custom template that fails to execute", func(t *testing.T) {
    58  			assert.Panics(t, func() {
    59  				SwaggerUI(SwaggerUIOpts{
    60  					Template: `<!DOCTYPE html>
    61  <html>
    62  	spec-url='{{ .Unknown }}'
    63  </html>
    64  `,
    65  				}, nil)
    66  			})
    67  		})
    68  	})
    69  }
    70  

View as plain text