-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathanalyze_test.go
More file actions
407 lines (377 loc) · 10.7 KB
/
analyze_test.go
File metadata and controls
407 lines (377 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
package cmd
import (
"codacy/cli-v2/config"
"codacy/cli-v2/constants"
"codacy/cli-v2/domain"
"os"
"path/filepath"
"testing"
"codacy/cli-v2/plugins"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestGetFileExtension(t *testing.T) {
tests := []struct {
name string
filePath string
want string
}{
{
name: "Python file",
filePath: "test.py",
want: ".py",
},
{
name: "C++ file",
filePath: "test.cpp",
want: ".cpp",
},
{
name: "File with path",
filePath: "/path/to/file.js",
want: ".js",
},
{
name: "File without extension",
filePath: "noextension",
want: "",
},
{
name: "File with uppercase extension",
filePath: "test.PY",
want: ".py",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := GetFileExtension(tt.filePath); got != tt.want {
t.Errorf("GetFileExtension() = %v, want %v", got, tt.want)
}
})
}
}
func TestIsToolSupportedForFile(t *testing.T) {
langConfig := &LanguagesConfig{
Tools: []struct {
Name string `yaml:"name" json:"name"`
Languages []string `yaml:"languages" json:"languages"`
Extensions []string `yaml:"extensions" json:"extensions"`
}{
{
Name: "pylint",
Languages: []string{"Python"},
Extensions: []string{".py"},
},
{
Name: "cppcheck",
Languages: []string{"C", "CPP"},
Extensions: []string{".c", ".cpp", ".h", ".hpp"},
},
{
Name: "trivy",
Languages: []string{"Multiple"},
Extensions: []string{},
},
},
}
tests := []struct {
name string
toolName string
filePath string
config *LanguagesConfig
want bool
}{
{
name: "Pylint with Python file",
toolName: "pylint",
filePath: "test.py",
config: langConfig,
want: true,
},
{
name: "Pylint with C++ file",
toolName: "pylint",
filePath: "test.cpp",
config: langConfig,
want: false,
},
{
name: "Cppcheck with C++ file",
toolName: "cppcheck",
filePath: "test.cpp",
config: langConfig,
want: true,
},
{
name: "Tool with no extensions specified",
toolName: "trivy",
filePath: "any.file",
config: langConfig,
want: true,
},
{
name: "Unknown tool",
toolName: "unknown",
filePath: "test.py",
config: langConfig,
want: true,
},
{
name: "Nil config",
toolName: "pylint",
filePath: "test.cpp",
config: nil,
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := IsToolSupportedForFile(tt.toolName, tt.filePath, tt.config); got != tt.want {
t.Errorf("IsToolSupportedForFile() = %v, want %v", got, tt.want)
}
})
}
}
func TestEslintInstallationValidationLogic(t *testing.T) {
// Test the logic that determines when ESLint installation should be triggered
// This tests the core logic from runEslintAnalysis without complex config setup
tests := []struct {
name string
eslint *plugins.ToolInfo
nodeRuntime *plugins.RuntimeInfo
isToolInstalled bool
expectInstallTriggered bool
description string
}{
{
name: "tool_nil_should_trigger_install",
eslint: nil,
nodeRuntime: nil,
isToolInstalled: false,
expectInstallTriggered: true,
description: "When ESLint tool is nil, installation should be triggered",
},
{
name: "tool_exists_runtime_nil_should_trigger_install",
eslint: &plugins.ToolInfo{
Name: "eslint",
Version: "8.38.0",
Runtime: "node",
},
nodeRuntime: nil,
isToolInstalled: true,
expectInstallTriggered: true,
description: "When ESLint tool exists but runtime is nil, installation should be triggered",
},
{
name: "tool_not_installed_runtime_exists_should_trigger_install",
eslint: &plugins.ToolInfo{
Name: "eslint",
Version: "8.38.0",
Runtime: "node",
},
nodeRuntime: &plugins.RuntimeInfo{
Name: "node",
Version: "22.2.0",
},
isToolInstalled: false,
expectInstallTriggered: true,
description: "When ESLint tool is not installed, installation should be triggered",
},
{
name: "both_tool_and_runtime_available_should_not_trigger_install",
eslint: &plugins.ToolInfo{
Name: "eslint",
Version: "8.38.0",
Runtime: "node",
},
nodeRuntime: &plugins.RuntimeInfo{
Name: "node",
Version: "22.2.0",
},
isToolInstalled: true,
expectInstallTriggered: false,
description: "When both ESLint tool and runtime are available and installed, installation should not be triggered",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// This mimics the logic from runEslintAnalysis
// Check if the runtime is installed
var isRuntimeInstalled bool
if tt.eslint != nil {
isRuntimeInstalled = tt.nodeRuntime != nil
// In the real code, this would also call Config.IsRuntimeInstalled,
// but for this test we simplify it to just checking if runtime exists
}
// Apply the installation trigger logic
shouldInstall := tt.eslint == nil || !tt.isToolInstalled || !isRuntimeInstalled
if tt.expectInstallTriggered {
assert.True(t, shouldInstall, tt.description)
} else {
assert.False(t, shouldInstall, tt.description)
}
})
}
}
func TestValidatePaths(t *testing.T) {
tests := []struct {
name string
paths []string
expectError bool
}{
{
name: "valid path",
paths: []string{"."},
expectError: false,
},
{
name: "non-existent file",
paths: []string{"non-existent-file.txt"},
expectError: true,
},
{
name: "multiple paths with one invalid",
paths: []string{".", "non-existent-file.txt"},
expectError: true,
},
{
name: "empty paths",
paths: []string{},
expectError: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := validatePaths(tt.paths)
if tt.expectError {
assert.Error(t, err)
assert.Contains(t, err.Error(), "❌ Error: cannot find file or directory")
} else {
assert.NoError(t, err)
}
})
}
}
func TestCheckIfConfigExistsAndIsNeeded(t *testing.T) {
// Save original initFlags and config
originalFlags := initFlags
originalConfig := config.Config
originalWorkingDir, _ := os.Getwd()
defer func() {
initFlags = originalFlags
config.Config = originalConfig
os.Chdir(originalWorkingDir)
}()
tests := []struct {
name string
toolName string
cliLocalMode bool
apiToken string
configFileExists bool
expectError bool
description string
}{
{
name: "tool_without_config_file",
toolName: "unsupported-tool",
cliLocalMode: false,
apiToken: "test-token",
configFileExists: false,
expectError: false,
description: "Tool that doesn't use config files should return without error",
},
{
name: "config_file_exists",
toolName: "eslint",
cliLocalMode: false,
apiToken: "test-token",
configFileExists: true,
expectError: false,
description: "When config file exists, should find it successfully",
},
{
name: "remote_mode_without_token_no_config",
toolName: "eslint",
cliLocalMode: false,
apiToken: "",
configFileExists: false,
expectError: false,
description: "Remote mode without token should show appropriate message",
},
{
name: "local_mode_no_config",
toolName: "eslint",
cliLocalMode: true,
apiToken: "",
configFileExists: false,
expectError: false,
description: "Local mode should show message about adding config file",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Setup temporary directory and change to it to avoid creating files in project dir
tmpDir, err := os.MkdirTemp("", "codacy-test-*")
require.NoError(t, err)
defer os.RemoveAll(tmpDir)
// Change to temp directory to prevent config file creation in project
err = os.Chdir(tmpDir)
require.NoError(t, err)
// Mock config to use our temporary directory BEFORE creating files
config.Config = *config.NewConfigType(tmpDir, tmpDir, tmpDir)
// Create config file if needed - using the same path logic as the function under test
if tt.configFileExists && constants.ToolConfigFileNames[tt.toolName] != "" {
// Use config.Config.ToolsConfigDirectory() to get the exact same path the function will use
toolsConfigDir := config.Config.ToolsConfigDirectory()
err := os.MkdirAll(toolsConfigDir, 0755)
require.NoError(t, err)
configPath := filepath.Join(toolsConfigDir, constants.ToolConfigFileNames[tt.toolName])
err = os.WriteFile(configPath, []byte("test config"), 0644)
require.NoError(t, err)
// Ensure the file was created and can be found
_, err = os.Stat(configPath)
require.NoError(t, err, "Config file should exist at %s", configPath)
}
// Setup initFlags
initFlags = domain.InitFlags{
ApiToken: tt.apiToken,
}
// Execute the function
err = checkIfConfigExistsAndIsNeeded(tt.toolName, tt.cliLocalMode)
// Clean up any files that might have been created by the function under test
if !tt.configFileExists && constants.ToolConfigFileNames[tt.toolName] != "" {
toolsConfigDir := config.Config.ToolsConfigDirectory()
configPath := filepath.Join(toolsConfigDir, constants.ToolConfigFileNames[tt.toolName])
if _, statErr := os.Stat(configPath); statErr == nil {
os.Remove(configPath)
}
}
// Verify results
if tt.expectError {
assert.Error(t, err, tt.description)
} else {
assert.NoError(t, err, tt.description)
}
})
}
}
func TestToolConfigFileNameMap(t *testing.T) {
expectedTools := map[string]string{
"eslint": constants.ESLintConfigFileName,
"trivy": constants.TrivyConfigFileName,
"pmd": constants.PMDConfigFileName,
"pylint": constants.PylintConfigFileName,
"dartanalyzer": constants.DartAnalyzerConfigFileName,
"semgrep": constants.SemgrepConfigFileName,
"revive": constants.ReviveConfigFileName,
"lizard": constants.LizardConfigFileName,
}
for toolName, expectedFileName := range expectedTools {
t.Run(toolName, func(t *testing.T) {
actualFileName, exists := constants.ToolConfigFileNames[toolName]
assert.True(t, exists, "Tool %s should exist in constants.ToolConfigFileNames map", toolName)
assert.Equal(t, expectedFileName, actualFileName, "Config filename for %s should match expected", toolName)
})
}
}