eintopf.info@v0.13.16/service/status/transport_test.go (about)

     1  // Copyright (C) 2022 The Eintopf authors
     2  //
     3  // This program is free software: you can redistribute it and/or modify
     4  // it under the terms of the GNU Affero General Public License as
     5  // published by the Free Software Foundation, either version 3 of the
     6  // License, or (at your option) any later version.
     7  //
     8  // This program is distributed in the hope that it will be useful,
     9  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    10  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    11  // GNU Affero General Public License for more details.
    12  //
    13  // You should have received a copy of the GNU Affero General Public License
    14  // along with this program.  If not, see <https://www.gnu.org/licenses/>.
    15  
    16  package status_test
    17  
    18  import (
    19  	"net/http"
    20  	"net/http/httptest"
    21  	"testing"
    22  
    23  	"eintopf.info/internal/mock"
    24  	"eintopf.info/internal/xhttptest"
    25  	"eintopf.info/service/status"
    26  	"github.com/petergtz/pegomock"
    27  )
    28  
    29  func TestRouter(t *testing.T) {
    30  	statusService := mock.NewStatusService()
    31  	pegomock.When(statusService.Status()).ThenReturn(status.Status{
    32  		Uptime:   124,
    33  		Requests: 55,
    34  		RequestDuration: status.RequestDuration{
    35  			Min: 5,
    36  			Max: 15,
    37  			Avg: 7,
    38  		},
    39  	})
    40  
    41  	tests := []xhttptest.HttpTest{
    42  		{
    43  			Name:       "StatusResponse",
    44  			URI:        "/",
    45  			WantBody:   `{"uptime":124,"requests":55,"requestDuration":{"min":5,"max":15,"avg":7}}`,
    46  			WantStatus: 200,
    47  		},
    48  	}
    49  
    50  	xhttptest.TestRouter(t, status.Router(statusService), tests)
    51  }
    52  
    53  func testHandler() http.HandlerFunc {
    54  	fn := func(w http.ResponseWriter, req *http.Request) {
    55  		w.WriteHeader(http.StatusOK)
    56  	}
    57  	return http.HandlerFunc(fn)
    58  }
    59  
    60  func TestMiddleware(t *testing.T) {
    61  	statusService := status.NewService()
    62  
    63  	ts := httptest.NewServer(status.Middleware(statusService)(testHandler()))
    64  	defer ts.Close()
    65  
    66  	_, err := http.Get(ts.URL)
    67  	if err != nil {
    68  		t.Errorf("http.Get(%s): %s", ts.URL, err)
    69  	}
    70  
    71  	if statusService.Status().Requests != 1 {
    72  		t.Errorf("status.Requests != 1: %d", statusService.Status().Requests)
    73  	}
    74  }