Sync from Azure to LF
[ric-plt/resource-status-manager.git] / RSM / httpserver / http_server_test.go
1 //
2 // Copyright 2019 AT&T Intellectual Property
3 // Copyright 2019 Nokia
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //      http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17
18 package httpserver
19
20 import (
21         "github.com/gorilla/mux"
22         "github.com/stretchr/testify/assert"
23         "net/http"
24         "net/http/httptest"
25         "rsm/mocks"
26         "testing"
27         "time"
28 )
29
30 func setupRouterAndMocks() (*mux.Router, *mocks.RootControllerMock) {
31         rootControllerMock := &mocks.RootControllerMock{}
32         rootControllerMock.On("HandleHealthCheckRequest").Return(nil)
33
34         router := mux.NewRouter()
35         initializeRoutes(router, rootControllerMock)
36         return router, rootControllerMock
37 }
38
39 func TestRouteGetHealth(t *testing.T) {
40         router, rootControllerMock := setupRouterAndMocks()
41
42         req, err := http.NewRequest("GET", "/v1/health", nil)
43         if err != nil {
44                 t.Fatal(err)
45         }
46         rr := httptest.NewRecorder()
47         router.ServeHTTP(rr, req)
48
49         rootControllerMock.AssertNumberOfCalls(t, "HandleHealthCheckRequest", 1)
50 }
51
52 func TestRouteNotFound(t *testing.T) {
53         router, _ := setupRouterAndMocks()
54
55         req, err := http.NewRequest("GET", "/v1/no/such/route", nil)
56         if err != nil {
57                 t.Fatal(err)
58         }
59         rr := httptest.NewRecorder()
60         router.ServeHTTP(rr, req)
61
62         assert.Equal(t, http.StatusNotFound, rr.Code, "handler returned wrong status code")
63 }
64
65 func TestRunError(t *testing.T) {
66         rootControllerMock := &mocks.RootControllerMock{}
67
68         err := Run(111222333, rootControllerMock)
69
70         assert.NotNil(t, err)
71 }
72
73 func TestRun(t *testing.T) {
74         rootControllerMock := &mocks.RootControllerMock{}
75         rootControllerMock.On("HandleHealthCheckRequest").Return(nil)
76
77         go Run(11223, rootControllerMock)
78
79         time.Sleep(time.Millisecond * 100)
80         resp, err := http.Get("http://localhost:11223/v1/health")
81         if err != nil {
82                 t.Fatalf("failed to perform GET to http://localhost:11223/v1/health")
83         }
84         assert.Equal(t, 200, resp.StatusCode)
85 }