github.com/argoproj/argo-cd@v1.8.7/util/swagger/swagger_test.go (about)

     1  package swagger
     2  
     3  import (
     4  	"encoding/json"
     5  	"net"
     6  	"net/http"
     7  	"testing"
     8  
     9  	"github.com/go-openapi/loads"
    10  
    11  	"github.com/argoproj/argo-cd/util/assets"
    12  )
    13  
    14  func TestSwaggerUI(t *testing.T) {
    15  	serve := func(c chan<- string) {
    16  		// listen on first available dynamic (unprivileged) port
    17  		listener, err := net.Listen("tcp", ":0")
    18  		if err != nil {
    19  			panic(err)
    20  		}
    21  
    22  		// send back the address so that it can be used
    23  		c <- listener.Addr().String()
    24  
    25  		mux := http.NewServeMux()
    26  		ServeSwaggerUI(mux, assets.SwaggerJSON, "/swagger-ui", "")
    27  		panic(http.Serve(listener, mux))
    28  	}
    29  
    30  	c := make(chan string, 1)
    31  
    32  	// run a local webserver to test data retrieval
    33  	go serve(c)
    34  
    35  	address := <-c
    36  	t.Logf("Listening at address: %s", address)
    37  
    38  	server := "http://" + address
    39  
    40  	specDoc, err := loads.Spec(server + "/swagger.json")
    41  	if err != nil {
    42  		t.Fatal(err)
    43  	}
    44  
    45  	_, err = json.MarshalIndent(specDoc.Spec(), "", "  ")
    46  	if err != nil {
    47  		t.Fatal(err)
    48  	}
    49  
    50  	resp, err := http.Get(server + "/swagger-ui")
    51  	if err != nil {
    52  		t.Fatal(err)
    53  	}
    54  
    55  	if resp.StatusCode != 200 {
    56  		t.Fatalf("Was expecting status code 200 from swagger-ui, but got %d instead", resp.StatusCode)
    57  	}
    58  }