Repository: datreeio/datree
Pull request #31 (2021-05-11 15:16:21)

fix: fixed test command and refactored


Patch:
diff --git a/bl/evaluator.go b/bl/evaluator.go
index e45c6d1..caa8aa2 100644
--- a/bl/evaluator.go
+++ b/bl/evaluator.go
@@ -19,6 +19,7 @@ type Printer interface {
 type CLIClient interface {
 	RequestEvaluation(cliClient.EvaluationRequest) (cliClient.EvaluationResponse, error)
 }
+
 type PropertiesExtractor interface {
 	ReadFilesFromPaths(paths []string, conc int) ([]*propertiesExtractor.FileProperties, []propertiesExtractor.FileError, []error)
 }
diff --git a/bl/versionMessage.go b/bl/versionMessage.go
index 8859881..45a1676 100644
--- a/bl/versionMessage.go
+++ b/bl/versionMessage.go
@@ -1,34 +1,31 @@
 package bl
 
 import (
-	"time"
-
 	"github.com/datreeio/datree/pkg/cliClient"
-	"github.com/datreeio/datree/pkg/deploymentConfig"
 	"github.com/datreeio/datree/pkg/printer"
 )
 
-func PopulateVersionMessageChan(cliVersion string) chan *cliClient.VersionMessage {
-	messageChannel := make(chan *cliClient.VersionMessage, 1)
+type VersionMessageClient interface {
+	GetVersionMessage(cliVersion string) (*cliClient.VersionMessage, error)
+}
+
+func PopulateVersionMessageChan(c VersionMessageClient, cliVersion string) <-chan *cliClient.VersionMessage {
+	messageChannel := make(chan *cliClient.VersionMessage)
 	go func() {
-		c := cliClient.NewCliClient(deploymentConfig.URL)
 		msg, _ := c.GetVersionMessage(cliVersion)
 		if msg != nil {
 			messageChannel <- msg
 		}
 		close(messageChannel)
 	}()
+
 	return messageChannel
 }
 
-func HandleVersionMessage(messageChannel chan *cliClient.VersionMessage) {
-	select {
-	case msg := <-messageChannel:
-		if msg != nil {
-			p := printer.CreateNewPrinter()
-			p.PrintVersionMessage(msg.MessageText+"\n", msg.MessageColor)
-		}
-	case <-time.After(600 * time.Millisecond):
-		break
+func HandleVersionMessage(messageChannel <-chan *cliClient.VersionMessage) {
+	msg, ok := <-messageChannel
+	if ok {
+		p := printer.CreateNewPrinter()
+		p.PrintVersionMessage(msg.MessageText+"\n", msg.MessageColor)
 	}
 }
diff --git a/cmd/root.go b/cmd/root.go
index 056023b..180b99a 100644
--- a/cmd/root.go
+++ b/cmd/root.go
@@ -24,12 +24,16 @@ func init() {
 	app := startup()
 
 	rootCmd.AddCommand(test.NewTestCommand(&test.TestCommandContext{
-		CliVersion:  CliVersion,
-		Evaluator:   app.Context.Evaluator,
-		LocalConfig: app.Context.LocalConfig,
+		CliVersion:           CliVersion,
+		Evaluator:            app.Context.Evaluator,
+		LocalConfig:          app.Context.LocalConfig,
+		VersionMessageClient: app.Context.VersionMessageClient,
 	}))
 
-	rootCmd.AddCommand(version.NewVersionCommand(CliVersion))
+	rootCmd.AddCommand(version.NewVersionCommand(&version.VersionCommandContext{
+		CliVersion:           CliVersion,
+		VersionMessageClient: app.Context.VersionMessageClient,
+	}))
 }
 
 func Execute() error {
@@ -38,26 +42,32 @@ func Execute() error {
 
 type app struct {
 	Context struct {
-		LocalConfig *localConfig.LocalConfiguration
-		Evaluator   *bl.Evaluator
+		LocalConfig          *localConfig.LocalConfiguration
+		Evaluator            *bl.Evaluator
+		CliClient            *cliClient.CliClient
+		VersionMessageClient cliClient.VersionMessageClient
 	}
 }
 
 func startup() *app {
 	app := &app{
 		Context: struct {
-			LocalConfig *localConfig.LocalConfiguration
-			Evaluator   *bl.Evaluator
+			LocalConfig          *localConfig.LocalConfiguration
+			Evaluator            *bl.Evaluator
+			CliClient            *cliClient.CliClient
+			VersionMessageClient cliClient.VersionMessageClient
 		}{},
 	}
 
 	client := cliClient.NewCliClient(deploymentConfig.URL)
+	versionMessageClient := cliClient.NewVersionMessageClient(deploymentConfig.URL)
 	extractor := propertiesExtractor.NewPropertiesExtractor(nil)
 	printer := printer.CreateNewPrinter()
 	evaluator := bl.CreateNewEvaluator(extractor, client, printer)
 
 	app.Context.LocalConfig = &localConfig.LocalConfiguration{}
 	app.Context.Evaluator = evaluator
+	app.Context.VersionMessageClient = versionMessageClient
 
 	return app
 }
diff --git a/cmd/version/main.go b/cmd/version/main.go
index c9dc1f3..9dfed9a 100644
--- a/cmd/version/main.go
+++ b/cmd/version/main.go
@@ -7,15 +7,24 @@ import (
 	"github.com/spf13/cobra"
 )
 
-func NewVersionCommand(cliVersion string) *cobra.Command {
+type VersionCommandContext struct {
+	CliVersion           string
+	VersionMessageClient bl.VersionMessageClient
+}
+
+func version(ctx *VersionCommandContext) {
+	messageChannel := bl.PopulateVersionMessageChan(ctx.VersionMessageClient, ctx.CliVersion)
+	fmt.Println(ctx.CliVersion)
+	bl.HandleVersionMessage(messageChannel)
+}
+
+func NewVersionCommand(ctx *VersionCommandContext) *cobra.Command {
 	var versionCmd = &cobra.Command{
 		Use:   "version",
 		Short: "Print the version number",
 		Long:  "Print the version number",
 		Run: func(cmd *cobra.Command, args []string) {
-			messageChannel := bl.PopulateVersionMessageChan(cliVersion)
-			fmt.Println(cliVersion)
-			bl.HandleVersionMessage(messageChannel)
+			version(ctx)
 		},
 	}
 	return versionCmd
diff --git a/pkg/cliClient/cliClient.go b/pkg/cliClient/cliClient.go
index 9b23826..7937b94 100644
--- a/pkg/cliClient/cliClient.go
+++ b/pkg/cliClient/cliClient.go
@@ -3,6 +3,7 @@ package cliClient
 import (
 	"encoding/json"
 	"net/http"
+	"time"
 
 	"github.com/datreeio/datree/pkg/httpClient"
 	extractor "github.com/datreeio/datree/pkg/propertiesExtractor"
@@ -24,6 +25,19 @@ func NewCliClient(url string) *CliClient {
 	}
 }
 
+type VersionMessageClient struct {
+	baseUrl    string
+	httpClient HTTPClient
+}
+
+func NewVersionMessageClient(url string) VersionMessageClient {
+	httpClient := httpClient.NewClientTimeout(url, nil, 900*time.Millisecond)
+	return VersionMessageClient{
+		baseUrl:    url,
+		httpClient: httpClient,
+	}
+}
+
 type Metadata struct {
 	CliVersion      string `json:"cliVersion"`
 	Os              string `json:"os"`
@@ -63,12 +77,6 @@ type EvaluationResponse struct {
 	Status       string             `json:"status"`
 }
 
-type VersionMessage struct {
-	CliVersion   string `json:"cliVersion"`
-	MessageText  string `json:"messageText"`
-	MessageColor string `json:"messageColor"`
-}
-
 func (c *CliClient) RequestEvaluation(request EvaluationRequest) (EvaluationResponse, error) {
 	res, err := c.httpClient.Request(http.MethodPost, "/cli/evaluate", request, nil)
 	if err != nil {
@@ -84,7 +92,13 @@ func (c *CliClient) RequestEvaluation(request EvaluationRequest) (EvaluationResp
 	return *evaluationResponse, nil
 }
 
-func (c *CliClient) GetVersionMessage(cliVersion string) (*VersionMessage, error) {
+type VersionMessage struct {
+	CliVersion   string `json:"cliVersion"`
+	MessageText  string `json:"messageText"`
+	MessageColor string `json:"messageColor"`
+}
+
+func (c VersionMessageClient) GetVersionMessage(cliVersion string) (*VersionMessage, error) {
 	res, err := c.httpClient.Request(http.MethodGet, "/cli/messages/versions/"+cliVersion, nil, nil)
 	if err != nil {
 		return nil, err
@@ -92,8 +106,10 @@ func (c *CliClient) GetVersionMessage(cliVersion string) (*VersionMessage, error
 
 	var response = &VersionMessage{}
 	err = json.Unmarshal(res.Body, &response)
+
 	if err != nil {
 		return nil, err
 	}
+
 	return response, nil
 }
diff --git a/pkg/httpClient/client.go b/pkg/httpClient/client.go
index 6a0468b..d2a97ab 100644
--- a/pkg/httpClient/client.go
+++ b/pkg/httpClient/client.go
@@ -9,6 +9,7 @@ import (
 	"net/http"
 	"net/url"
 	"strings"
+	"time"
 )
 
 const (
@@ -36,6 +37,17 @@ func NewClient(baseURL string, defaultHeaders map[string]string) *Client {
 	return &Client{httpClient: &http.Client{}, baseURL: url, defaultHeaders: defaultHeaders}
 }
 
+// NewClientTimeout creates new Client with predefined timeout
+func NewClientTimeout(baseURL string, defaultHeaders map[string]string, timeout time.Duration) *Client {
+	url, _ := url.Parse(baseURL)
+	if defaultHeaders == nil {
+		defaultHeaders = make(map[string]string)
+	}
+	return &Client{httpClient: &http.Client{
+		Timeout: timeout,
+	}, baseURL: url, defaultHeaders: defaultHeaders}
+}
+
 // Request creates httpRequest and returns response
 func (c *Client) Request(method string, resourceURI string, body interface{}, headers map[string]string) (Response, error) {
 	url, _ := c.baseURL.Parse(resourceURI)


Test patch:
diff --git a/cmd/test/main.go b/cmd/test/main.go
index 7f9ea63..607a564 100644
--- a/cmd/test/main.go
+++ b/cmd/test/main.go
@@ -22,9 +22,10 @@ type Evaluator interface {
 }
 
 type TestCommandContext struct {
-	CliVersion  string
-	LocalConfig LocalConfigManager
-	Evaluator   Evaluator
+	CliVersion           string
+	LocalConfig          LocalConfigManager
+	Evaluator            Evaluator
+	VersionMessageClient bl.VersionMessageClient
 }
 
 type TestCommandFlags struct {
@@ -61,6 +62,8 @@ func test(ctx *TestCommandContext, paths []string, flags TestCommandFlags) error
 	s.Color("cyan")
 	s.Start()
 
+	messageChannel := bl.PopulateVersionMessageChan(ctx.VersionMessageClient, ctx.CliVersion)
+
 	config, err := ctx.LocalConfig.GetConfiguration()
 	if err != nil {
 		fmt.Println(err.Error())
@@ -83,7 +86,6 @@ func test(ctx *TestCommandContext, paths []string, flags TestCommandFlags) error
 		return err
 	}
 
-	messageChannel := bl.PopulateVersionMessageChan(ctx.CliVersion)
 	err = ctx.Evaluator.PrintResults(evaluationResponse, config.CliId, flags.Output)
 	bl.HandleVersionMessage(messageChannel)
 
diff --git a/cmd/test/main_test.go b/cmd/test/main_test.go
index 5a3a500..a3d9648 100644
--- a/cmd/test/main_test.go
+++ b/cmd/test/main_test.go
@@ -4,6 +4,7 @@ import (
 	"testing"
 
 	"github.com/datreeio/datree/bl"
+	"github.com/datreeio/datree/pkg/cliClient"
 	"github.com/datreeio/datree/pkg/localConfig"
 	"github.com/datreeio/datree/pkg/propertiesExtractor"
 	"github.com/stretchr/testify/mock"
@@ -35,6 +36,15 @@ func (m *mockEvaluator) Evaluate(paths []string, cliId string, evaluationConc in
 	args := m.Called(paths, cliId, evaluationConc)
 	return args.Get(0).(*bl.EvaluationResults), args.Get(1).([]propertiesExtractor.FileError), args.Error(2)
 }
+
+type mockVersionMessageClient struct {
+	mock.Mock
+}
+
+func (m *mockVersionMessageClient) GetVersionMessage(cliVersion string) (*cliClient.VersionMessage, error) {
+	args := m.Called(cliVersion)
+	return args.Get(0).(*cliClient.VersionMessage), nil
+}
 func TestTestCommand(t *testing.T) {
 	evaluator := &mockEvaluator{}
 	mockedEvaluateResponse := &bl.EvaluationResults{
@@ -51,9 +61,18 @@ func TestTestCommand(t *testing.T) {
 	localConfigManager := &mockLocalConfigManager{}
 	localConfigManager.On("GetConfiguration").Return(localConfig.LocalConfiguration{CliId: "134kh"}, nil)
 
+	versionMessageClient := &mockVersionMessageClient{}
+	versionMessageClient.On("GetVersionMessage", mock.Anything).Return(
+		&cliClient.VersionMessage{
+			CliVersion:   "1.2.3",
+			MessageText:  "version message mock",
+			MessageColor: "green"},
+	)
+
 	ctx := &TestCommandContext{
-		Evaluator:   evaluator,
-		LocalConfig: localConfigManager,
+		Evaluator:            evaluator,
+		LocalConfig:          localConfigManager,
+		VersionMessageClient: versionMessageClient,
 	}
 
 	test_testCommand_no_flags(t, localConfigManager, evaluator, mockedEvaluateResponse, ctx)
diff --git a/cmd/version/main_test.go b/cmd/version/main_test.go
index 61b4cb0..17deb2d 100644
--- a/cmd/version/main_test.go
+++ b/cmd/version/main_test.go
@@ -4,10 +4,33 @@ import (
 	"bytes"
 	"io/ioutil"
 	"testing"
+
+	"github.com/datreeio/datree/pkg/cliClient"
+	"github.com/stretchr/testify/mock"
 )
 
+type mockVersionMessageClient struct {
+	mock.Mock
+}
+
+func (m *mockVersionMessageClient) GetVersionMessage(cliVersion string) (*cliClient.VersionMessage, error) {
+	args := m.Called(cliVersion)
+	return args.Get(0).(*cliClient.VersionMessage), nil
+}
+
 func Test_ExecuteCommand(t *testing.T) {
-	cmd := NewVersionCommand("1.2.3")
+	versionMessageClient := &mockVersionMessageClient{}
+	versionMessageClient.On("GetVersionMessage", mock.Anything).Return(
+		&cliClient.VersionMessage{
+			CliVersion:   "1.2.3",
+			MessageText:  "version message mock",
+			MessageColor: "green"},
+	)
+
+	cmd := NewVersionCommand(&VersionCommandContext{
+		CliVersion:           "1.2.3",
+		VersionMessageClient: versionMessageClient,
+	})
 	b := bytes.NewBufferString("1.2.3")
 	cmd.SetOut(b)
 	cmd.Execute()
diff --git a/pkg/cliClient/cliClient_test.go b/pkg/cliClient/cliClient_test.go
index 85a4fbb..451e100 100644
--- a/pkg/cliClient/cliClient_test.go
+++ b/pkg/cliClient/cliClient_test.go
@@ -106,7 +106,7 @@ func TestGetVersionMessage(t *testing.T) {
 			mockedHTTPResponse := httpClient.Response{StatusCode: tt.mock.response.status, Body: body}
 			httpClientMock.On("Request", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(mockedHTTPResponse, nil)
 
-			client := &CliClient{
+			client := &VersionMessageClient{
 				baseUrl:    "http://cli-service.test.io",
 				httpClient: &httpClientMock,
 			}