2 // ========================LICENSE_START=================================
5 // Copyright (C) 2022: Nordix Foundation
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
11 // http://www.apache.org/licenses/LICENSE-2.0
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===================================
35 log "github.com/sirupsen/logrus"
36 "github.com/stretchr/testify/require"
39 func createHttpClientMock(t *testing.T, configuration *Config, 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)
51 return &http.Response{
53 Body: ioutil.NopCloser(bytes.NewBuffer(toBody(token))),
54 Header: make(http.Header), // Must be set to non-nil value or it panics
57 t.Error("Wrong call to client: ", req)
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 configuration.RefreshMarginSeconds = 1
72 context := NewContext(configuration)
75 os.Remove(configuration.AuthTokenOutputFileName)
78 accessToken := "Access_token" + fmt.Sprint(time.Now().UnixNano())
79 token := JwtToken{Access_token: accessToken, Expires_in: 7, Token_type: "Token_type"}
81 clientMock := createHttpClientMock(t, configuration, token)
83 go periodicRefreshIwtToken(clientMock, context)
85 waitForFile(configuration.AuthTokenOutputFileName, 30, t)
87 tokenFileContent, err := ioutil.ReadFile(configuration.AuthTokenOutputFileName)
90 assertions.Equal(accessToken, string(tokenFileContent))
92 context.Running = false
95 func waitForFile(fileName string, maxTimeSeconds int, t *testing.T) bool {
96 for i := 1; i < maxTimeSeconds; i++ {
97 if _, err := os.Stat(fileName); err == nil {
100 time.Sleep(time.Second)
102 t.Error("File not created: " + fileName)
107 func TestStart(t *testing.T) {
108 assertions := require.New(t)
109 log.SetLevel(log.TraceLevel)
111 configuration := NewConfig()
112 configuration.AuthTokenOutputFileName = "/tmp/authToken" + fmt.Sprint(time.Now().UnixNano())
113 configuration.CACertsPath = configuration.CertPath
114 context := NewContext(configuration)
116 os.Remove(configuration.AuthTokenOutputFileName)
121 time.Sleep(time.Second * 5)
123 _, err := os.Stat(configuration.AuthTokenOutputFileName)
125 assertions.True(errors.Is(err, os.ErrNotExist))
126 context.Running = false
129 func toBody(token JwtToken) []byte {
130 body, err := json.Marshal(token)
135 type RoundTripFunc func(req *http.Request) *http.Response
137 func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
141 //NewTestClient returns *http.Client with Transport replaced to avoid making real calls
142 func NewTestClient(fn RoundTripFunc) *http.Client {
144 Transport: RoundTripFunc(fn),
148 // waitTimeout waits for the waitgroup for the specified max timeout.
149 // Returns true if waiting timed out.
150 func waitTimeout(wg *sync.WaitGroup, timeout time.Duration) bool {
151 c := make(chan struct{})
158 return false // completed normally
159 case <-time.After(timeout):
160 return true // timed out
164 func getBodyAsString(req *http.Request, t *testing.T) string {
165 buf := new(bytes.Buffer)
166 if _, err := buf.ReadFrom(req.Body); err != nil {