...

Source file src/github.com/prometheus/common/server/static_file_server_test.go

Documentation: github.com/prometheus/common/server

     1  // Copyright 2019 The Prometheus Authors
     2  // Licensed under the Apache License, Version 2.0 (the "License");
     3  // you may not use this file except in compliance with the License.
     4  // You may obtain a copy of the License at
     5  //
     6  // http://www.apache.org/licenses/LICENSE-2.0
     7  //
     8  // Unless required by applicable law or agreed to in writing, software
     9  // distributed under the License is distributed on an "AS IS" BASIS,
    10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package server
    15  
    16  import (
    17  	"net/http"
    18  	"net/http/httptest"
    19  	"testing"
    20  )
    21  
    22  type dummyFileSystem struct{}
    23  
    24  func (fs dummyFileSystem) Open(path string) (http.File, error) {
    25  	return http.Dir(".").Open(".")
    26  }
    27  
    28  func TestServeHttp(t *testing.T) {
    29  	cases := []struct {
    30  		name        string
    31  		path        string
    32  		contentType string
    33  	}{
    34  		{
    35  			name:        "normal file",
    36  			path:        "index.html",
    37  			contentType: "",
    38  		},
    39  		{
    40  			name:        "javascript",
    41  			path:        "test.js",
    42  			contentType: "application/javascript",
    43  		},
    44  		{
    45  			name:        "css",
    46  			path:        "test.css",
    47  			contentType: "text/css",
    48  		},
    49  		{
    50  			name:        "png",
    51  			path:        "test.png",
    52  			contentType: "image/png",
    53  		},
    54  		{
    55  			name:        "jpg",
    56  			path:        "test.jpg",
    57  			contentType: "image/jpeg",
    58  		},
    59  		{
    60  			name:        "gif",
    61  			path:        "test.gif",
    62  			contentType: "image/gif",
    63  		},
    64  	}
    65  
    66  	for _, c := range cases {
    67  		t.Run(c.name, func(t *testing.T) {
    68  			rr := httptest.NewRecorder()
    69  			req, err := http.NewRequest("GET", "http://localhost/"+c.path, nil)
    70  			if err != nil {
    71  				t.Fatal(err)
    72  			}
    73  
    74  			s := StaticFileServer(dummyFileSystem{})
    75  			s.ServeHTTP(rr, req)
    76  
    77  			if rr.Header().Get("Content-Type") != c.contentType {
    78  				t.Fatalf("Unexpected Content-Type: %s", rr.Header().Get("Content-Type"))
    79  			}
    80  		})
    81  	}
    82  }
    83  

View as plain text