Skip to content

Commit fb9755b

Browse files
committed
Add Tests
1 parent 69a6fbc commit fb9755b

File tree

5 files changed

+189
-112
lines changed

5 files changed

+189
-112
lines changed

cmd/main.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ func main() {
2727
var err error
2828
bindProxy()
2929
bindKeysToEnvAndDefault()
30-
configuration.LoadConfiguration()
30+
err = configuration.LoadConfiguration()
31+
exitIfError(err)
3132
scans := viper.GetString(params.ScansPathKey)
3233
groups := viper.GetString(params.GroupsPathKey)
3334
logs := viper.GetString(params.LogsPathKey)

internal/commands/util/configuration_test.go

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package util
22

33
import (
4+
"github.com/checkmarx/ast-cli/internal/params"
5+
"github.com/spf13/viper"
46
"os"
57
"strings"
68
"testing"
@@ -47,9 +49,11 @@ func TestGetConfigFilePath_CheckmarxConfigFileExists_Success(t *testing.T) {
4749
}
4850

4951
func TestWriteSingleConfigKeyToExistingFile_ChangeAscaPortToZero_Success(t *testing.T) {
50-
configuration.LoadConfiguration()
52+
err := configuration.LoadConfiguration()
53+
assert.NilError(t, err)
54+
5155
configFilePath, _ := configuration.GetConfigFilePath()
52-
err := configuration.SafeWriteSingleConfigKey(configFilePath, cxAscaPort, 0)
56+
err = configuration.SafeWriteSingleConfigKey(configFilePath, cxAscaPort, 0)
5357
assert.NilError(t, err)
5458

5559
config, err := configuration.LoadConfig(configFilePath)
@@ -78,7 +82,9 @@ func TestWriteSingleConfigKeyNonExistingFile_CreatingTheFileAndWritesTheKey_Succ
7882
}
7983

8084
func TestChangedOnlyAscaPortInConfigFile_ConfigFileExistsWithDefaultValues_OnlyAscaPortChangedSuccess(t *testing.T) {
81-
configuration.LoadConfiguration()
85+
err := configuration.LoadConfiguration()
86+
assert.NilError(t, err)
87+
8288
configFilePath, _ := configuration.GetConfigFilePath()
8389

8490
oldConfig, err := configuration.LoadConfig(configFilePath)
@@ -100,9 +106,11 @@ func TestChangedOnlyAscaPortInConfigFile_ConfigFileExistsWithDefaultValues_OnlyA
100106
}
101107

102108
func TestWriteSingleConfigKeyStringToExistingFile_UpdateScsScanOverviewPath_Success(t *testing.T) {
103-
configuration.LoadConfiguration()
109+
err := configuration.LoadConfiguration()
110+
assert.NilError(t, err)
111+
104112
configFilePath, _ := configuration.GetConfigFilePath()
105-
err := configuration.SafeWriteSingleConfigKeyString(configFilePath, cxScsScanOverviewPath, defaultScsScanOverviewPath)
113+
err = configuration.SafeWriteSingleConfigKeyString(configFilePath, cxScsScanOverviewPath, defaultScsScanOverviewPath)
106114
assert.NilError(t, err)
107115

108116
config, err := configuration.LoadConfig(configFilePath)
@@ -131,7 +139,9 @@ func TestWriteSingleConfigKeyStringNonExistingFile_CreatingTheFileAndWritesTheKe
131139
}
132140

133141
func TestChangedOnlyScsScanOverviewPathInConfigFile_ConfigFileExistsWithDefaultValues_OnlyScsScanOverviewPathChangedSuccess(t *testing.T) {
134-
configuration.LoadConfiguration()
142+
err := configuration.LoadConfiguration()
143+
assert.NilError(t, err)
144+
135145
configFilePath, _ := configuration.GetConfigFilePath()
136146

137147
oldConfig, err := configuration.LoadConfig(configFilePath)
@@ -151,3 +161,12 @@ func TestChangedOnlyScsScanOverviewPathInConfigFile_ConfigFileExistsWithDefaultV
151161
}
152162
}
153163
}
164+
165+
func TestGetConfigFilePath_CustomFile(t *testing.T) {
166+
expectedPath := "/custom/path/checkmarxcli.yaml"
167+
viper.Set(params.ConfigFilePathKey, expectedPath)
168+
169+
actualPath, err := configuration.GetConfigFilePath()
170+
assert.NilError(t, err)
171+
assert.Equal(t, actualPath, expectedPath, "Expected path to match the set value in viper")
172+
}

internal/wrappers/configuration/configuration.go

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,10 @@ func setConfigPropertyQuiet(propName, propValue string) {
108108
// SafeWriteConfig() will not update files but it will create them, combined
109109
// this code will successfully update files.
110110
if viperErr := viper.SafeWriteConfig(); viperErr != nil {
111-
_ = viper.WriteConfig()
111+
err := viper.WriteConfig()
112+
if err != nil {
113+
fmt.Println("Error writing config file", err)
114+
}
112115
}
113116
}
114117

@@ -117,19 +120,17 @@ func SetConfigProperty(propName, propValue string) {
117120
setConfigPropertyQuiet(propName, propValue)
118121
}
119122

120-
func LoadConfiguration() {
123+
func LoadConfiguration() error {
121124
configFilePath := viper.GetString(params.ConfigFilePathKey)
122125

123126
if configFilePath != "" {
124127
err := validateConfigFile(configFilePath)
125128
if err != nil {
126-
fmt.Println(err)
127-
os.Exit(1)
129+
return err
128130
}
129131
viper.SetConfigFile(configFilePath)
130132
if err = viper.ReadInConfig(); err != nil {
131-
fmt.Println("An error occurred while accessing the file or environment variable. Please verify the CLI configuration file")
132-
os.Exit(1)
133+
return errors.New("An error occurred while accessing the file or environment variable. Please verify the CLI configuration file")
133134
}
134135
} else {
135136
usr, err := user.Current()
@@ -144,6 +145,7 @@ func LoadConfiguration() {
144145
viper.SetConfigType("yaml")
145146
_ = viper.ReadInConfig()
146147
}
148+
return nil
147149
}
148150

149151
func validateConfigFile(configFilePath string) error {
Lines changed: 75 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -1,95 +1,75 @@
1-
////go:build integration
2-
//
3-
//package integration
4-
//
5-
//import (
6-
// "gotest.tools/assert"
7-
// "os"
8-
// "strings"
9-
// "testing"
10-
//)
11-
//
12-
//var filePath = "data/config.yaml"
13-
//
14-
//func TestIntegration_LoadConfiguration_EnvVarConfigFilePath(t *testing.T) {
15-
// os.Setenv("CX_CONFIG_FILE_PATH", filePath)
16-
// defer os.Unsetenv("CX_CONFIG_FILE_PATH")
17-
//
18-
// cmd, buffer := createRedirectedTestCommand(t)
19-
//
20-
// err := execute(cmd, "configure", "show")
21-
// assert.NilError(t, err)
22-
//
23-
// output := buffer.String()
24-
// if !strings.Contains(output, "cx_base_uri: https://example.com") {
25-
// t.Errorf("expected output to contain 'cx_base_uri: https://example.com', but it did not")
26-
// }
27-
//}
28-
//
29-
//func TestIntegration_LoadConfiguration_FileNotFound(t *testing.T) {
30-
// // Set an invalid file path
31-
// os.Setenv("CX_CONFIG_FILE_PATH", "data/nonexistent_config.yaml")
32-
// defer os.Unsetenv("CX_CONFIG_FILE_PATH")
33-
//
34-
// cmd, buffer := createRedirectedTestCommand(t)
35-
//
36-
// // Execute the command
37-
// err := execute(cmd, "configure", "show")
38-
//
39-
// // Verify that an error occurred
40-
// assert.ErrorContains(t, err, "The specified file does not exist")
41-
//
42-
// // Verify the output contains the expected error message
43-
// output := buffer.String()
44-
// if !strings.Contains(output, "The specified file does not exist") {
45-
// t.Errorf("expected output to contain 'The specified file does not exist', but it did not")
46-
// }
47-
//}
48-
//
49-
//func TestIntegration_LoadConfiguration_FileWithoutPermission_UsingConfigFile(t *testing.T) {
50-
//
51-
// // Set the file to have no permissions
52-
// if err := os.Chmod(filePath, 0000); err != nil {
53-
// t.Fatalf("failed to set file permissions: %v", err)
54-
// }
55-
// defer os.Chmod(filePath, 0644) // Restore permissions for cleanup
56-
//
57-
// // Set the environment variable to point to the restricted file
58-
// os.Setenv("CX_CONFIG_FILE_PATH", filePath)
59-
// defer os.Unsetenv("CX_CONFIG_FILE_PATH")
60-
//
61-
// cmd, buffer := createRedirectedTestCommand(t)
62-
//
63-
// // Execute the command
64-
// err := execute(cmd, "configure", "show")
65-
//
66-
// // Verify that an error occurred
67-
// assert.ErrorContains(t, err, "Access to the specified file is restricted")
68-
//
69-
// // Verify the output contains the expected error message
70-
// output := buffer.String()
71-
// if !strings.Contains(output, "Access to the specified file is restricted") {
72-
// t.Errorf("expected output to contain 'Access to the specified file is restricted', but it did not")
73-
// }
74-
//}
75-
//
76-
//
77-
//func TestIntegration_SetConfigProperty_EnvVarConfigFilePath(t *testing.T) {
78-
// // Set environment variable
79-
// os.Setenv("CX_CONFIG_FILE_PATH", filePath)
80-
// defer os.Unsetenv("CX_CONFIG_FILE_PATH")
81-
//
82-
// // Create command
83-
// cmd, buffer := createRedirectedTestCommand(t)
84-
//
85-
// // Execute command
86-
// err := execute(cmd, "configure", "set", "--prop-name", "new_key", "--prop-value", "new_value")
87-
// assert.NilError(t, err)
88-
//
89-
// // Verify output
90-
// output := buffer.String()
91-
// asserts.Contains(t, output, "Setting property [new_key] to value [new_value]")
92-
//
93-
// // Verify configuration
94-
// asserts.Equal(t, viper.GetString("new_key"), "new_value")
95-
//}
1+
//go:build integration
2+
3+
package integration
4+
5+
import (
6+
"github.com/checkmarx/ast-cli/internal/wrappers/configuration"
7+
"github.com/spf13/viper"
8+
"gotest.tools/assert"
9+
"os"
10+
"strings"
11+
"testing"
12+
)
13+
14+
const filePath = "data/config.yaml"
15+
16+
func TestLoadConfiguration_EnvVarConfigFilePath(t *testing.T) {
17+
os.Setenv("CX_CONFIG_FILE_PATH", filePath)
18+
defer os.Unsetenv("CX_CONFIG_FILE_PATH")
19+
20+
_ = viper.BindEnv("CX_CONFIG_FILE_PATH")
21+
err := configuration.LoadConfiguration()
22+
assert.NilError(t, err)
23+
}
24+
25+
func TestLoadConfiguration_FileNotFound(t *testing.T) {
26+
os.Setenv("CX_CONFIG_FILE_PATH", "data/nonexistent_config.yaml")
27+
defer os.Unsetenv("CX_CONFIG_FILE_PATH")
28+
29+
_ = viper.BindEnv("CX_CONFIG_FILE_PATH")
30+
var err error
31+
err = configuration.LoadConfiguration()
32+
assert.ErrorContains(t, err, "The specified file does not exist")
33+
}
34+
func TestLoadConfiguration_ValidDirectory(t *testing.T) {
35+
validDirPath := "data"
36+
os.Setenv("CX_CONFIG_FILE_PATH", validDirPath)
37+
defer os.Unsetenv("CX_CONFIG_FILE_PATH")
38+
39+
_ = viper.BindEnv("CX_CONFIG_FILE_PATH")
40+
err := configuration.LoadConfiguration()
41+
assert.ErrorContains(t, err, "The specified path points to a directory")
42+
}
43+
func TestLoadConfiguration_FileWithoutPermission_UsingConfigFile(t *testing.T) {
44+
if err := os.Chmod(filePath, 0000); err != nil {
45+
t.Fatalf("failed to set file permissions: %v", err)
46+
}
47+
defer os.Chmod(filePath, 0644)
48+
49+
os.Setenv("CX_CONFIG_FILE_PATH", filePath)
50+
defer os.Unsetenv("CX_CONFIG_FILE_PATH")
51+
52+
_ = viper.BindEnv("CX_CONFIG_FILE_PATH")
53+
err := configuration.LoadConfiguration()
54+
55+
assert.ErrorContains(t, err, "Access to the specified file is restricted")
56+
}
57+
58+
func TestSetConfigProperty_EnvVarConfigFilePath(t *testing.T) {
59+
os.Setenv("CX_CONFIG_FILE_PATH", filePath)
60+
defer os.Unsetenv("CX_CONFIG_FILE_PATH")
61+
62+
_ = viper.BindEnv("CX_CONFIG_FILE_PATH")
63+
err := configuration.LoadConfiguration()
64+
assert.NilError(t, err)
65+
66+
err, _ = executeCommand(t, "configure", "set", "--prop-name", "cx_client_id", "--prop-value", "dummy-client_id")
67+
assert.NilError(t, err)
68+
69+
content, err := os.ReadFile(filePath)
70+
assert.NilError(t, err)
71+
assert.Assert(t, strings.Contains(string(content), "dummy-client_id"))
72+
73+
err, _ = executeCommand(t, "configure", "set", "--prop-name", "cx_client_id", "--prop-value", "example_client_id")
74+
assert.NilError(t, err)
75+
}

test/integration/data/config.yaml

Lines changed: 79 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,82 @@
1-
cx_base_uri: https://example.com
2-
cx_base_auth_uri: https://auth.example.com
3-
cx_tenant: example_tenant
1+
apikey-override: false
2+
cx_access_management_path: api/access-management
3+
cx_agent_name: ASTCLI
4+
cx_aiproxy_azureai_route: api/ai-proxy/redirect/externalAzure
5+
cx_aiproxy_checkmarxai_route: api/ai-proxy/redirect/azure
46
cx_api_key: example_api_key
7+
cx_apikey: ""
8+
cx_applications_path: api/applications
9+
cx_asca_port: ""
10+
cx_ast_keycloak_web_app_health_check_path: auth
11+
cx_ast_role: SCA_AGENT
12+
cx_ast_web_app_health_check_path: '#/projects'
13+
cx_base_auth_uri: https://auth.example.com
14+
cx_base_uri: https://example.com
15+
cx_bfl_path: api/bfl
16+
cx_branch: ""
17+
cx_byor_path: api/byor
518
cx_client_id: example_client_id
619
cx_client_secret: example_client_secret
7-
cx_proxy: http://proxy.example.com
20+
cx_codebashing_path: api/codebashing/lessons
21+
cx_config_file_path: data/config.yaml
22+
cx_create_oath2_client_path: auth/realms/organization/pip/clients
23+
cx_custom_states_path: api/custom-states
24+
cx_descriptions_path: api/queries/descriptions
25+
cx_export_path: api/sca/export
26+
cx_feature_flags_path: api/flags
27+
cx_groups_path: auth/realms/organization/pip/groups
28+
cx_healthcheck_db_path: logging
29+
cx_healthcheck_in_memory_db_path: in-memory-db
30+
cx_healthcheck_message_queue_path: message-queue
31+
cx_healthcheck_object_store_path: object-store
32+
cx_healthcheck_path: api/healthcheck
33+
cx_healthcheck_sast_engines_path: sast-engines
34+
cx_healthcheck_scan_flow_path: scan-flow
35+
cx_ignore_proxy: ""
36+
cx_kics_results_path: api/kics-results
37+
cx_kics_results_predicates_path: api/kics-results-predicates
38+
cx_logs_engine_log_path: /%s/%s
39+
cx_logs_path: api/logs
40+
cx_origin: CLI
41+
cx_policy_evaluation_path: api/policy_management_service_uri/evaluation
42+
cx_pr_decoration_azure_path: api/flow-publisher/pr/azure
43+
cx_pr_decoration_bitbucket_cloud_path: api/flow-publisher/pr/bitbucket
44+
cx_pr_decoration_bitbucket_server_path: api/flow-publisher/pr/bitbucket-server
45+
cx_pr_decoration_github_path: api/flow-publisher/pr/github
46+
cx_pr_decoration_gitlab_path: api/flow-publisher/pr/gitlab
47+
cx_projects_path: api/projects
48+
cx_proxy: http://proxy.example.com
49+
cx_proxy_auth_type: basic
50+
cx_proxy_ntlm_domain: ""
51+
cx_queries_clone_path: clone
52+
cx_queries_path: api/queries
53+
cx_results_path: api/results
54+
cx_results_pdf_report_path: api/reports
55+
cx_risk_management_path: api/risk-management/projects/%s/results
56+
cx_risks_overview_path: api/apisec/static/api/scan/%s/risks-overview
57+
cx_sast_results_path: api/sast-results
58+
cx_sast_results_predicates_path: api/sast-results-predicates
59+
cx_sast_rm_path: api/sast-rm
60+
cx_sast_scan_inc_metrics_path: '%s/metrics'
61+
cx_sast_scan_inc_path: api/sast-metadata
62+
cx_scan_summary_path: api/scan-summary
63+
cx_scans_path: api/scans
64+
cx_scs_results_predicates_read_path: api/micro-engines/read/predicates
65+
cx_scs_results_predicates_write_path: api/micro-engines/write/predicates
66+
cx_scs_scan_overview_path: api/micro-engines/read/scans/%s/scan-overview
67+
cx_tenant: example_tenant
68+
cx_tenant_configuration_path: api/configuration/tenant
69+
cx_timeout: "30"
70+
cx_token_expiry_seconds: 2
71+
cx_uploads_path: api/uploads
72+
debug: false
73+
http_proxy: ""
74+
insecure: false
75+
kics-container-name: cli-kics-realtime-b0ddfae9-fb90-4571-8b81-85cbf08fd4b3
76+
retry: "3"
77+
retry-delay: "5"
78+
sca_resolver: ./ScaResolver
79+
scs_repo_token: ""
80+
token: ""
81+
url: https://api.github.com
82+
url-gitlab: https://gitlab.com

0 commit comments

Comments
 (0)