Merge "Fetch of authorization token"
[nonrtric.git] / auth-token-fetch / main_test.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2022: Nordix Foundation
6 //   %%
7 //   Licensed under the Apache License, Version 2.0 (the "License");
8 //   you may not use this file except in compliance with the License.
9 //   You may obtain a copy of the License at
10 //
11 //        http://www.apache.org/licenses/LICENSE-2.0
12 //
13 //   Unless required by applicable law or agreed to in writing, software
14 //   distributed under the License is distributed on an "AS IS" BASIS,
15 //   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 //   See the License for the specific language governing permissions and
17 //   limitations under the License.
18 //   ========================LICENSE_END===================================
19 //
20
21 package main
22
23 import (
24         "bytes"
25         "encoding/json"
26         "errors"
27         "fmt"
28         "io/ioutil"
29         "net/http"
30         "os"
31         "sync"
32         "testing"
33         "time"
34
35         log "github.com/sirupsen/logrus"
36         "github.com/stretchr/testify/require"
37 )
38
39 func createHttpClientMock(t *testing.T, configuration *Config, wg *sync.WaitGroup, token JwtToken) *http.Client {
40         assertions := require.New(t)
41         clientMock := NewTestClient(func(req *http.Request) *http.Response {
42                 if req.URL.String() == configuration.AuthServiceUrl {
43                         assertions.Equal(req.Method, "POST")
44                         body := getBodyAsString(req, t)
45                         assertions.Contains(body, "client_id="+configuration.ClientId)
46                         assertions.Contains(body, "secret="+configuration.ClientSecret)
47                         assertions.Contains(body, "grant_type="+configuration.GrantType)
48                         contentType := req.Header.Get("content-type")
49                         assertions.Equal("application/x-www-form-urlencoded", contentType)
50                         wg.Done()
51                         return &http.Response{
52                                 StatusCode: 200,
53                                 Body:       ioutil.NopCloser(bytes.NewBuffer(toBody(token))),
54                                 Header:     make(http.Header), // Must be set to non-nil value or it panics
55                         }
56                 }
57                 t.Error("Wrong call to client: ", req)
58                 t.Fail()
59                 return nil
60         })
61         return clientMock
62 }
63
64 func TestFetchAndStoreToken(t *testing.T) {
65         log.SetLevel(log.TraceLevel)
66         assertions := require.New(t)
67         configuration := NewConfig()
68         configuration.AuthTokenOutputFileName = "/tmp/authToken" + fmt.Sprint(time.Now().UnixNano())
69         configuration.ClientId = "testClientId"
70         configuration.ClientSecret = "testClientSecret"
71         context := NewContext(configuration)
72
73         t.Cleanup(func() {
74                 os.Remove(configuration.AuthTokenOutputFileName)
75         })
76
77         accessToken := "Access_token" + fmt.Sprint(time.Now().UnixNano())
78         token := JwtToken{Access_token: accessToken, Expires_in: 10, Token_type: "Token_type"}
79
80         wg := sync.WaitGroup{}
81         wg.Add(2) // Get token two times
82         clientMock := createHttpClientMock(t, configuration, &wg, token)
83
84         go periodicRefreshIwtToken(clientMock, context)
85
86         if waitTimeout(&wg, 7*time.Second) {
87                 t.Error("Not all calls to server were made")
88                 t.Fail()
89         }
90
91         tokenFileContent, err := ioutil.ReadFile(configuration.AuthTokenOutputFileName)
92         check(err)
93
94         assertions.Equal(accessToken, string(tokenFileContent))
95
96         context.Running = false
97 }
98
99 func TestStart(t *testing.T) {
100         assertions := require.New(t)
101         log.SetLevel(log.TraceLevel)
102
103         configuration := NewConfig()
104         configuration.AuthTokenOutputFileName = "/tmp/authToken" + fmt.Sprint(time.Now().UnixNano())
105         context := NewContext(configuration)
106
107         start(context)
108
109         time.Sleep(time.Second * 5)
110
111         _, err := os.Stat(configuration.AuthTokenOutputFileName)
112
113         assertions.True(errors.Is(err, os.ErrNotExist))
114         context.Running = false
115 }
116
117 func toBody(token JwtToken) []byte {
118         body, err := json.Marshal(token)
119         check(err)
120         return body
121 }
122
123 type RoundTripFunc func(req *http.Request) *http.Response
124
125 func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
126         return f(req), nil
127 }
128
129 //NewTestClient returns *http.Client with Transport replaced to avoid making real calls
130 func NewTestClient(fn RoundTripFunc) *http.Client {
131         return &http.Client{
132                 Transport: RoundTripFunc(fn),
133         }
134 }
135
136 // waitTimeout waits for the waitgroup for the specified max timeout.
137 // Returns true if waiting timed out.
138 func waitTimeout(wg *sync.WaitGroup, timeout time.Duration) bool {
139         c := make(chan struct{})
140         go func() {
141                 defer close(c)
142                 wg.Wait()
143         }()
144         select {
145         case <-c:
146                 return false // completed normally
147         case <-time.After(timeout):
148                 return true // timed out
149         }
150 }
151
152 func getBodyAsString(req *http.Request, t *testing.T) string {
153         buf := new(bytes.Buffer)
154         if _, err := buf.ReadFrom(req.Body); err != nil {
155                 t.Fail()
156         }
157         return buf.String()
158 }