Merge "Sample consumer to get kafka broker from ICS"
[nonrtric.git] / auth-token-fetch / main_test.go
index 1b0a87e..cceff07 100644 (file)
@@ -28,7 +28,6 @@ import (
        "io/ioutil"
        "net/http"
        "os"
-       "sync"
        "testing"
        "time"
 
@@ -36,7 +35,7 @@ import (
        "github.com/stretchr/testify/require"
 )
 
-func createHttpClientMock(t *testing.T, configuration *Config, wg *sync.WaitGroup, token JwtToken) *http.Client {
+func createHttpClientMock(t *testing.T, configuration *Config, token JwtToken) *http.Client {
        assertions := require.New(t)
        clientMock := NewTestClient(func(req *http.Request) *http.Response {
                if req.URL.String() == configuration.AuthServiceUrl {
@@ -47,7 +46,7 @@ func createHttpClientMock(t *testing.T, configuration *Config, wg *sync.WaitGrou
                        assertions.Contains(body, "grant_type="+configuration.GrantType)
                        contentType := req.Header.Get("content-type")
                        assertions.Equal("application/x-www-form-urlencoded", contentType)
-                       wg.Done()
+
                        return &http.Response{
                                StatusCode: 200,
                                Body:       ioutil.NopCloser(bytes.NewBuffer(toBody(token))),
@@ -68,6 +67,7 @@ func TestFetchAndStoreToken(t *testing.T) {
        configuration.AuthTokenOutputFileName = "/tmp/authToken" + fmt.Sprint(time.Now().UnixNano())
        configuration.ClientId = "testClientId"
        configuration.ClientSecret = "testClientSecret"
+       configuration.RefreshMarginSeconds = 1
        context := NewContext(configuration)
 
        t.Cleanup(func() {
@@ -75,18 +75,13 @@ func TestFetchAndStoreToken(t *testing.T) {
        })
 
        accessToken := "Access_token" + fmt.Sprint(time.Now().UnixNano())
-       token := JwtToken{Access_token: accessToken, Expires_in: 10, Token_type: "Token_type"}
+       token := JwtToken{Access_token: accessToken, Expires_in: 7, Token_type: "Token_type"}
 
-       wg := sync.WaitGroup{}
-       wg.Add(2) // Get token two times
-       clientMock := createHttpClientMock(t, configuration, &wg, token)
+       clientMock := createHttpClientMock(t, configuration, token)
 
        go periodicRefreshIwtToken(clientMock, context)
 
-       if waitTimeout(&wg, 7*time.Second) {
-               t.Error("Not all calls to server were made")
-               t.Fail()
-       }
+       await(func() bool { return fileExists(configuration.AuthTokenOutputFileName) }, t)
 
        tokenFileContent, err := ioutil.ReadFile(configuration.AuthTokenOutputFileName)
        check(err)
@@ -96,13 +91,37 @@ func TestFetchAndStoreToken(t *testing.T) {
        context.Running = false
 }
 
+func fileExists(fileName string) bool {
+       if _, err := os.Stat(fileName); err == nil {
+               return true
+       }
+       log.Debug("Waiting for file: " + fileName)
+       return false
+}
+
+func await(predicate func() bool, t *testing.T) {
+       MAX_TIME_SECONDS := 30
+       for i := 1; i < MAX_TIME_SECONDS; i++ {
+               if predicate() {
+                       return
+               }
+               time.Sleep(time.Second)
+       }
+       t.Error("Predicate not fulfilled")
+       t.Fail()
+}
+
 func TestStart(t *testing.T) {
        assertions := require.New(t)
        log.SetLevel(log.TraceLevel)
 
        configuration := NewConfig()
        configuration.AuthTokenOutputFileName = "/tmp/authToken" + fmt.Sprint(time.Now().UnixNano())
+       configuration.CACertsPath = configuration.CertPath
        context := NewContext(configuration)
+       t.Cleanup(func() {
+               os.Remove(configuration.AuthTokenOutputFileName)
+       })
 
        start(context)
 
@@ -133,22 +152,6 @@ func NewTestClient(fn RoundTripFunc) *http.Client {
        }
 }
 
-// waitTimeout waits for the waitgroup for the specified max timeout.
-// Returns true if waiting timed out.
-func waitTimeout(wg *sync.WaitGroup, timeout time.Duration) bool {
-       c := make(chan struct{})
-       go func() {
-               defer close(c)
-               wg.Wait()
-       }()
-       select {
-       case <-c:
-               return false // completed normally
-       case <-time.After(timeout):
-               return true // timed out
-       }
-}
-
 func getBodyAsString(req *http.Request, t *testing.T) string {
        buf := new(bytes.Buffer)
        if _, err := buf.ReadFrom(req.Body); err != nil {