forked from jfrog/jfrog-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgradle_test.go
More file actions
717 lines (597 loc) · 29.4 KB
/
gradle_test.go
File metadata and controls
717 lines (597 loc) · 29.4 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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
package main
import (
"errors"
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/jfrog/gofrog/io"
"github.com/jfrog/jfrog-cli-artifactory/artifactory/commands/gradle"
"github.com/jfrog/jfrog-cli-core/v2/artifactory/utils"
coretests "github.com/jfrog/jfrog-cli-core/v2/utils/tests"
"github.com/jfrog/jfrog-client-go/http/httpclient"
"github.com/stretchr/testify/require"
urfavecli "github.com/urfave/cli"
"github.com/jfrog/jfrog-cli/utils/cliutils"
"github.com/jfrog/jfrog-client-go/utils/log"
clientTestUtils "github.com/jfrog/jfrog-client-go/utils/tests"
buildinfo "github.com/jfrog/build-info-go/entities"
"github.com/jfrog/jfrog-cli-core/v2/common/build"
commonCliUtils "github.com/jfrog/jfrog-cli-core/v2/common/cliutils"
"github.com/jfrog/jfrog-cli-core/v2/common/commands"
outputFormat "github.com/jfrog/jfrog-cli-core/v2/common/format"
"github.com/jfrog/jfrog-cli-core/v2/common/project"
"github.com/jfrog/jfrog-cli-core/v2/common/spec"
"github.com/jfrog/jfrog-cli-core/v2/utils/coreutils"
"github.com/stretchr/testify/assert"
"github.com/jfrog/jfrog-cli/inttestutils"
"github.com/jfrog/jfrog-cli/utils/tests"
)
const (
gradleModuleId = ":minimal-example:1.0"
)
func cleanGradleTest(t *testing.T) {
clientTestUtils.UnSetEnvAndAssert(t, coreutils.HomeDir)
deleteSpec := spec.NewBuilder().Pattern(tests.GradleRepo).BuildSpec()
_, _, err := tests.DeleteFiles(deleteSpec, serverDetails)
assert.NoError(t, err)
tests.CleanFileSystem()
}
func TestGradleBuildConditionalUpload(t *testing.T) {
initGradleTest(t)
buildGradlePath := createGradleProject(t, "gradleproject")
configFilePath := filepath.Join(filepath.FromSlash(tests.GetTestResourcesPath()), "buildspecs", tests.GradleConfig)
destPath := filepath.Join(filepath.Dir(buildGradlePath), ".jfrog", "projects")
createConfigFile(destPath, configFilePath, t)
searchSpec, err := tests.CreateSpec(tests.SearchAllGradle)
assert.NoError(t, err)
oldHomeDir := changeWD(t, filepath.Dir(buildGradlePath))
defer clientTestUtils.ChangeDirAndAssert(t, oldHomeDir)
execFunc := func() error {
return runGradleConditionalUploadTest(buildGradlePath)
}
testConditionalUpload(t, execFunc, searchSpec, tests.GetGradleDeployedArtifacts()...)
cleanGradleTest(t)
}
func runGradleConditionalUploadTest(buildGradlePath string) (err error) {
configFilePath, exists, err := project.GetProjectConfFilePath(project.Gradle)
if err != nil {
return err
}
if !exists {
return errors.New("no config file was found!")
}
buildConfig := build.NewBuildConfiguration("", "", "", "")
if err = buildConfig.ValidateBuildAndModuleParams(); err != nil {
return
}
printDeploymentView := log.IsStdErrTerminal()
gradleCmd := gradle.NewGradleCommand().
SetTasks([]string{"clean", "artifactoryPublish", "-b" + buildGradlePath}).
SetConfiguration(buildConfig).
SetXrayScan(true).SetScanOutputFormat(outputFormat.Table).
SetDetailedSummary(printDeploymentView).SetConfigPath(configFilePath).SetThreads(commonCliUtils.Threads)
err = commands.Exec(gradleCmd)
result := gradleCmd.Result()
defer cliutils.CleanupResult(result, &err)
err = cliutils.PrintCommandSummary(gradleCmd.Result(), false, printDeploymentView, false, err)
return
}
func TestGradleWithDeploymentView(t *testing.T) {
initGradleTest(t)
buildGradlePath := createGradleProject(t, "gradleproject")
configFilePath := filepath.Join(filepath.FromSlash(tests.GetTestResourcesPath()), "buildspecs", tests.GradleConfig)
destPath := filepath.Join(filepath.Dir(buildGradlePath), ".jfrog", "projects")
createConfigFile(destPath, configFilePath, t)
oldHomeDir := changeWD(t, filepath.Dir(buildGradlePath))
defer clientTestUtils.ChangeDirAndAssert(t, oldHomeDir)
assertPrintedDeploymentViewFunc, cleanupFunc := initDeploymentViewTest(t)
defer cleanupFunc()
assert.NoError(t, runJfrogCliWithoutAssertion("gradle", "clean", "artifactoryPublish", "-b"+buildGradlePath))
assertPrintedDeploymentViewFunc()
cleanGradleTest(t)
}
func TestGradleBuildWithServerID(t *testing.T) {
initGradleTest(t)
buildGradlePath := createGradleProject(t, "gradleproject")
configFilePath := filepath.Join(filepath.FromSlash(tests.GetTestResourcesPath()), "buildspecs", tests.GradleConfig)
destPath := filepath.Join(filepath.Dir(buildGradlePath), ".jfrog", "projects")
createConfigFile(destPath, configFilePath, t)
oldHomeDir := changeWD(t, filepath.Dir(buildGradlePath))
buildNumber := "1"
// Windows compatibility
buildGradlePath = strings.ReplaceAll(buildGradlePath, `\`, "/")
runJfrogCli(t, "gradle", "clean", "artifactoryPublish", "-b"+buildGradlePath, "--build-name="+tests.GradleBuildName, "--build-number="+buildNumber)
clientTestUtils.ChangeDirAndAssert(t, oldHomeDir)
// Validate
searchSpec, err := tests.CreateSpec(tests.SearchAllGradle)
assert.NoError(t, err)
inttestutils.VerifyExistInArtifactory(tests.GetGradleDeployedArtifacts(), searchSpec, serverDetails, t)
verifyExistInArtifactoryByProps(tests.GetGradleDeployedArtifacts(), tests.GradleRepo+"/*", "build.name="+tests.GradleBuildName+";build.number="+buildNumber+";build.timestamp="+getBuildTimestamp(tests.GradleBuildName, buildNumber, t), t)
assert.NoError(t, artifactoryCli.Exec("bp", tests.GradleBuildName, buildNumber))
publishedBuildInfo, found, err := tests.GetBuildInfo(serverDetails, tests.GradleBuildName, buildNumber)
if err != nil {
assert.NoError(t, err)
return
}
if !found {
assert.True(t, found, "build info was expected to be found")
return
}
buildInfo := publishedBuildInfo.BuildInfo
// Expect 1 dependency (junit:4.7) since the project has source code using JUnit
validateBuildInfo(buildInfo, t, 1, 1, gradleModuleId, buildinfo.Gradle)
cleanGradleTest(t)
}
func TestGradleBuildWithServerIDAndDetailedSummary(t *testing.T) {
initGradleTest(t)
buildGradlePath := createGradleProject(t, "gradleproject")
configFilePath := filepath.Join(filepath.FromSlash(tests.GetTestResourcesPath()), "buildspecs", tests.GradleConfig)
destPath := filepath.Join(filepath.Dir(buildGradlePath), ".jfrog", "projects")
createConfigFile(destPath, configFilePath, t)
oldHomeDir := changeWD(t, filepath.Dir(buildGradlePath))
buildNumber := "1"
// Windows compatibility.
buildGradlePath = strings.ReplaceAll(buildGradlePath, `\`, "/")
// Test gradle with detailed summary without buildinfo props.
filteredGradleArgs := []string{"clean", "artifactoryPublish", "-b" + buildGradlePath}
gradleCmd := gradle.NewGradleCommand().SetConfiguration(new(build.BuildConfiguration)).SetTasks(filteredGradleArgs).SetConfigPath(filepath.Join(destPath, "gradle.yaml")).SetDetailedSummary(true)
assert.NoError(t, commands.Exec(gradleCmd))
// Validate sha256
assert.NotNil(t, gradleCmd.Result())
if gradleCmd.Result() != nil {
tests.VerifySha256DetailedSummaryFromResult(t, gradleCmd.Result())
}
// Test gradle with detailed summary + buildinfo.
gradleCmd = gradle.NewGradleCommand().SetConfiguration(build.NewBuildConfiguration(tests.GradleBuildName, buildNumber, "", "")).SetTasks(filteredGradleArgs).SetConfigPath(filepath.Join(destPath, "gradle.yaml")).SetDetailedSummary(true)
assert.NoError(t, commands.Exec(gradleCmd))
// Validate sha256
tests.VerifySha256DetailedSummaryFromResult(t, gradleCmd.Result())
clientTestUtils.ChangeDirAndAssert(t, oldHomeDir)
// Validate build info
searchSpec, err := tests.CreateSpec(tests.SearchAllGradle)
assert.NoError(t, err)
inttestutils.VerifyExistInArtifactory(tests.GetGradleDeployedArtifacts(), searchSpec, serverDetails, t)
verifyExistInArtifactoryByProps(tests.GetGradleDeployedArtifacts(), tests.GradleRepo+"/*", "build.name="+tests.GradleBuildName+";build.number="+buildNumber, t)
assert.NoError(t, artifactoryCli.Exec("bp", tests.GradleBuildName, buildNumber))
publishedBuildInfo, found, err := tests.GetBuildInfo(serverDetails, tests.GradleBuildName, buildNumber)
if err != nil {
assert.NoError(t, err)
return
}
if !found {
assert.True(t, found, "build info was expected to be found")
return
}
buildInfo := publishedBuildInfo.BuildInfo
// Expect 1 dependency (junit:4.7) since the project has source code using JUnit
validateBuildInfo(buildInfo, t, 1, 1, gradleModuleId, buildinfo.Gradle)
cleanGradleTest(t)
}
func TestGradleBuildWithServerIDWithUsesPlugin(t *testing.T) {
initGradleTest(t)
// Create gradle project in a tmp dir
buildGradlePath := createGradleProject(t, "projectwithplugin")
configFilePath := filepath.Join(filepath.FromSlash(tests.GetTestResourcesPath()), "buildspecs", tests.GradleServerIDUsesPluginConfig)
destPath := filepath.Join(filepath.Dir(buildGradlePath), ".jfrog", "projects")
createConfigFile(destPath, configFilePath, t)
err := os.Rename(filepath.Join(destPath, tests.GradleServerIDUsesPluginConfig), filepath.Join(destPath, "gradle.yaml"))
assert.NoError(t, err)
oldHomeDir := changeWD(t, filepath.Dir(buildGradlePath))
buildName := tests.GradleBuildName
buildNumber := "1"
runJfrogCli(t, "gradle", "clean", "artifactoryPublish", "-b"+buildGradlePath, "--build-name="+buildName, "--build-number="+buildNumber)
changeWD(t, oldHomeDir)
// Validate
searchSpec, err := tests.CreateSpec(tests.SearchAllGradle)
assert.NoError(t, err)
inttestutils.VerifyExistInArtifactory(tests.GetGradleDeployedArtifacts(), searchSpec, serverDetails, t)
verifyExistInArtifactoryByProps(tests.GetGradleDeployedArtifacts(), tests.GradleRepo+"/*", "build.name="+buildName+";build.number="+buildNumber, t)
inttestutils.ValidateGeneratedBuildInfoModule(t, buildName, buildNumber, "", []string{gradleModuleId}, buildinfo.Gradle)
assert.NoError(t, artifactoryCli.Exec("bp", tests.GradleBuildName, buildNumber))
publishedBuildInfo, found, err := tests.GetBuildInfo(serverDetails, tests.GradleBuildName, buildNumber)
if err != nil {
assert.NoError(t, err)
return
}
if !found {
assert.True(t, found, "build info was expected to be found")
return
}
buildInfo := publishedBuildInfo.BuildInfo
validateBuildInfo(buildInfo, t, 0, 1, gradleModuleId, buildinfo.Gradle)
cleanGradleTest(t)
}
func TestSetupGradleCommand(t *testing.T) {
restoreFunc := prepareGradleSetupTest(t)
defer restoreFunc()
// Validate that the module does not exist in the cache before running the test.
client, err := httpclient.ClientBuilder().Build()
assert.NoError(t, err)
// This module is part of the dependencies in the build.gradle file of the current test project.
// We want to ensure that it is not exist in the cache before running the build command.
moduleCacheUrl := serverDetails.ArtifactoryUrl + tests.GradleRemoteRepo + "-cache/com/fasterxml/jackson/core/jackson-core/2.13.2/jackson-core-2.13.2.jar"
_, _, err = client.GetRemoteFileDetails(moduleCacheUrl, artHttpDetails)
assert.ErrorContains(t, err, "404")
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
assert.NoError(t, execGo(jfrogCli, "setup", "gradle", "--repo="+tests.GradleRemoteRepo))
// Run `gradle clean` to resolve the artifact from Artifactory and force it to be downloaded.
output, err := exec.Command("gradle",
"clean",
"build",
"--info",
"--refresh-dependencies").CombinedOutput()
assert.NoError(t, err, fmt.Sprintf("%s\n%q", string(output), err))
// Validate that the module exists in the cache after running the build command.
_, res, err := client.GetRemoteFileDetails(moduleCacheUrl, artHttpDetails)
if assert.NoError(t, err, "Failed to find the artifact in the cache: "+moduleCacheUrl) {
assert.Equal(t, http.StatusOK, res.StatusCode)
}
}
// TestGradleBuildWithFlexPack tests Gradle build with JFROG_RUN_NATIVE=true (FlexPack mode)
func TestGradleBuildWithFlexPack(t *testing.T) {
initGradleTest(t)
// Check if Gradle is available in the environment
if _, err := exec.LookPath("gradle"); err != nil {
t.Skip("Gradle not found in PATH, skipping Gradle FlexPack test")
}
buildGradlePath := createGradleProject(t, "gradleproject")
oldHomeDir := changeWD(t, filepath.Dir(buildGradlePath))
defer clientTestUtils.ChangeDirAndAssert(t, oldHomeDir)
// Set environment for native FlexPack implementation
setEnvCallBack := clientTestUtils.SetEnvWithCallbackAndAssert(t, "JFROG_RUN_NATIVE", "true")
defer setEnvCallBack()
// Windows compatibility
buildGradlePath = strings.ReplaceAll(buildGradlePath, `\`, "/")
// Run gradle without config file to trigger FlexPack mode
err := runJfrogCliWithoutAssertion("gradle", "clean", "build", "-b"+buildGradlePath)
assert.NoError(t, err)
cleanGradleTest(t)
}
// TestGradleBuildWithFlexPackBuildInfo tests Gradle build info collection with JFROG_RUN_NATIVE=true
func TestGradleBuildWithFlexPackBuildInfo(t *testing.T) {
initGradleTest(t)
// Check if Gradle is available in the environment
if _, err := exec.LookPath("gradle"); err != nil {
t.Skip("Gradle not found in PATH, skipping Gradle FlexPack build info test")
}
buildGradlePath := createGradleProject(t, "gradleproject")
oldHomeDir := changeWD(t, filepath.Dir(buildGradlePath))
defer clientTestUtils.ChangeDirAndAssert(t, oldHomeDir)
buildName := tests.GradleBuildName + "-flexpack"
buildNumber := "1"
// Set environment for native FlexPack implementation
setEnvCallBack := clientTestUtils.SetEnvWithCallbackAndAssert(t, "JFROG_RUN_NATIVE", "true")
defer setEnvCallBack()
// Windows compatibility
buildGradlePath = strings.ReplaceAll(buildGradlePath, `\`, "/")
// Run gradle with build info (FlexPack mode - no config file)
err := runJfrogCliWithoutAssertion("gradle", "clean", "build", "-b"+buildGradlePath, "--build-name="+buildName, "--build-number="+buildNumber)
assert.NoError(t, err)
// Publish build info
assert.NoError(t, artifactoryCli.Exec("bp", buildName, buildNumber))
// Validate build info was created with FlexPack dependencies
publishedBuildInfo, found, err := tests.GetBuildInfo(serverDetails, buildName, buildNumber)
if err != nil {
assert.NoError(t, err)
return
}
if !found {
assert.True(t, found, "build info was expected to be found")
return
}
// Validate build info structure
buildInfo := publishedBuildInfo.BuildInfo
assert.NotEmpty(t, buildInfo.Modules, "Build info should have modules")
if len(buildInfo.Modules) > 0 {
module := buildInfo.Modules[0]
assert.Equal(t, buildinfo.Gradle, module.Type, "Module type should be Gradle")
assert.NotEmpty(t, module.Id, "Module should have ID")
// FlexPack should collect dependencies with scopes and checksums.
assert.NotEmpty(t, module.Dependencies, "FlexPack build info should include dependencies")
for _, dep := range module.Dependencies {
assert.NotEmpty(t, dep.Id, "Dependency should have ID")
// FlexPack should provide checksums
hasChecksum := dep.Sha1 != "" || dep.Sha256 != "" || dep.Md5 != ""
assert.True(t, hasChecksum, "Dependency %s should have at least one checksum", dep.Id)
// FlexPack should provide scopes (Gradle configurations)
assert.NotEmpty(t, dep.Scopes, "Dependency %s should have scopes/configurations", dep.Id)
}
}
cleanGradleTest(t)
}
// TestGradleBuildWithFlexPackEnvVars tests build info collection using JFROG_CLI_BUILD_NAME and JFROG_CLI_BUILD_NUMBER
func TestGradleBuildWithFlexPackEnvVars(t *testing.T) {
initGradleTest(t)
// Check if Gradle is available in the environment
if _, err := exec.LookPath("gradle"); err != nil {
t.Skip("Gradle not found in PATH, skipping Gradle FlexPack env vars test")
}
buildGradlePath := createGradleProject(t, "gradleproject")
oldHomeDir := changeWD(t, filepath.Dir(buildGradlePath))
defer clientTestUtils.ChangeDirAndAssert(t, oldHomeDir)
buildName := tests.GradleBuildName + "-flexpack-env"
buildNumber := "123"
// Set environment for native FlexPack implementation
setEnvCallBack := clientTestUtils.SetEnvWithCallbackAndAssert(t, "JFROG_RUN_NATIVE", "true")
defer setEnvCallBack()
// Set build name and number via environment variables
setBuildNameCallback := clientTestUtils.SetEnvWithCallbackAndAssert(t, "JFROG_CLI_BUILD_NAME", buildName)
defer setBuildNameCallback()
setBuildNumberCallback := clientTestUtils.SetEnvWithCallbackAndAssert(t, "JFROG_CLI_BUILD_NUMBER", buildNumber)
defer setBuildNumberCallback()
// Windows compatibility
buildGradlePath = strings.ReplaceAll(buildGradlePath, `\`, "/")
// Run gradle without explicit build name/number flags - should use env vars
err := runJfrogCliWithoutAssertion("gradle", "clean", "build", "-b"+buildGradlePath)
assert.NoError(t, err)
// Publish build info
assert.NoError(t, artifactoryCli.Exec("bp", buildName, buildNumber))
// Validate build info was created with the env var values
publishedBuildInfo, found, err := tests.GetBuildInfo(serverDetails, buildName, buildNumber)
if err != nil {
assert.NoError(t, err)
return
}
if !found {
assert.True(t, found, "build info was expected to be found with env var build name/number")
return
}
// Validate build info has the correct build name and number
assert.Equal(t, buildName, publishedBuildInfo.BuildInfo.Name, "Build name should match env var")
assert.Equal(t, buildNumber, publishedBuildInfo.BuildInfo.Number, "Build number should match env var")
cleanGradleTest(t)
}
// TestGradleBuildWithFlexPackInvalidArgs tests 'jf gradle build' with invalid Gradle arguments
func TestGradleBuildWithFlexPackInvalidArgs(t *testing.T) {
initGradleTest(t)
// Check if Gradle is available in the environment
if _, err := exec.LookPath("gradle"); err != nil {
t.Skip("Gradle not found in PATH, skipping Gradle FlexPack invalid args test")
}
// The CLI uses urfave/cli, which may call os.Exit(1) for ExitError (e.g., external tool exit code).
origOsExiter := urfavecli.OsExiter
urfavecli.OsExiter = func(code int) {}
defer func() { urfavecli.OsExiter = origOsExiter }()
buildGradlePath := createGradleProject(t, "gradleproject")
oldHomeDir := changeWD(t, filepath.Dir(buildGradlePath))
defer clientTestUtils.ChangeDirAndAssert(t, oldHomeDir)
// Set environment for native FlexPack implementation
setEnvCallBack := clientTestUtils.SetEnvWithCallbackAndAssert(t, "JFROG_RUN_NATIVE", "true")
defer setEnvCallBack()
// Windows compatibility
buildGradlePath = strings.ReplaceAll(buildGradlePath, `\`, "/")
// Run gradle with invalid task name - should fail
err := runJfrogCliWithoutAssertion("gradle", "nonExistentTask", "-b"+buildGradlePath)
assert.Error(t, err, "Gradle should fail with invalid task name")
// Run gradle with invalid option
err = runJfrogCliWithoutAssertion("gradle", "build", "--invalid-option-xyz", "-b"+buildGradlePath)
assert.Error(t, err, "Gradle should fail with invalid option")
// This test intentionally fails before any deployment/build-info publish.
clientTestUtils.UnSetEnvAndAssert(t, coreutils.HomeDir)
tests.CleanFileSystem()
}
// TestGradleBuildWithFlexPackFallback verifies that gradle falls back to traditional approach
// when JFROG_RUN_NATIVE is not set (covered by existing traditional tests, this is explicit verification)
func TestGradleBuildWithFlexPackFallback(t *testing.T) {
initGradleTest(t)
// Explicitly ensure JFROG_RUN_NATIVE is NOT set
_ = os.Unsetenv("JFROG_RUN_NATIVE")
buildGradlePath := createGradleProject(t, "gradleproject")
configFilePath := filepath.Join(filepath.FromSlash(tests.GetTestResourcesPath()), "buildspecs", tests.GradleConfig)
destPath := filepath.Join(filepath.Dir(buildGradlePath), ".jfrog", "projects")
createConfigFile(destPath, configFilePath, t)
// Create the search spec before changing the working directory.
// tests.GetTestResourcesPath() is relative ("testdata"), so creating the spec after chdir may fail on CI.
searchSpec, err := tests.CreateSpec(tests.SearchAllGradle)
require.NoError(t, err)
oldHomeDir := changeWD(t, filepath.Dir(buildGradlePath))
defer clientTestUtils.ChangeDirAndAssert(t, oldHomeDir)
buildName := tests.GradleBuildName + "-fallback"
buildNumber := "1"
// Windows compatibility
buildGradlePath = strings.ReplaceAll(buildGradlePath, `\`, "/")
// Run gradle with config file (traditional approach)
runJfrogCli(t, "gradle", "clean", "artifactoryPublish", "-b"+buildGradlePath, "--build-name="+buildName, "--build-number="+buildNumber)
// Validate artifacts were deployed (traditional approach deploys to Artifactory)
inttestutils.VerifyExistInArtifactory(tests.GetGradleDeployedArtifacts(), searchSpec, serverDetails, t)
cleanGradleTest(t)
}
// TestGradleHelpCommand verifies 'jf gradle --help' displays correct usage instructions
func TestGradleHelpCommand(t *testing.T) {
initGradleTest(t)
// Run gradle help command
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
err := jfrogCli.Exec("gradle", "--help")
// Help command should succeed
assert.NoError(t, err, "gradle --help should succeed")
cleanGradleTest(t)
}
// TestGradleBuildWithFlexPackKotlinDSL tests build info collection for Kotlin DSL (build.gradle.kts)
// Note: This test requires a Kotlin DSL project to be available
func TestGradleBuildWithFlexPackKotlinDSL(t *testing.T) {
initGradleTest(t)
// Check if Gradle is available in the environment
if _, err := exec.LookPath("gradle"); err != nil {
t.Skip("Gradle not found in PATH, skipping Gradle FlexPack Kotlin DSL test")
}
// Check if Kotlin DSL project exists
kotlinProjectPath := filepath.Join(filepath.FromSlash(tests.GetTestResourcesPath()), "gradle", "kotlinproject")
if _, err := os.Stat(kotlinProjectPath); os.IsNotExist(err) {
t.Skip("Kotlin DSL project not found, skipping Kotlin DSL test")
}
// Create gradle project with Kotlin DSL
buildGradlePath := createGradleProjectKotlin(t, "kotlinproject")
oldHomeDir := changeWD(t, filepath.Dir(buildGradlePath))
defer clientTestUtils.ChangeDirAndAssert(t, oldHomeDir)
buildName := tests.GradleBuildName + "-flexpack-kotlin"
buildNumber := "1"
// Set environment for native FlexPack implementation
setEnvCallBack := clientTestUtils.SetEnvWithCallbackAndAssert(t, "JFROG_RUN_NATIVE", "true")
defer setEnvCallBack()
// Windows compatibility
buildGradlePath = strings.ReplaceAll(buildGradlePath, `\`, "/")
// Run gradle build
err := runJfrogCliWithoutAssertion("gradle", "clean", "build", "-b"+buildGradlePath, "--build-name="+buildName, "--build-number="+buildNumber)
assert.NoError(t, err)
// Publish build info
assert.NoError(t, artifactoryCli.Exec("bp", buildName, buildNumber))
// Validate build info was created
publishedBuildInfo, found, err := tests.GetBuildInfo(serverDetails, buildName, buildNumber)
if err != nil {
assert.NoError(t, err)
return
}
if !found {
assert.True(t, found, "build info was expected to be found")
return
}
// Validate build info structure
buildInfo := publishedBuildInfo.BuildInfo
assert.NotEmpty(t, buildInfo.Modules, "Build info should have modules")
if len(buildInfo.Modules) > 0 {
module := buildInfo.Modules[0]
assert.Equal(t, buildinfo.Gradle, module.Type, "Module type should be Gradle")
}
cleanGradleTest(t)
}
func createGradleProject(t *testing.T, projectName string) string {
// Copy the entire project directory including source files
projectSrc := filepath.Join(filepath.FromSlash(tests.GetTestResourcesPath()), "gradle", projectName)
projectTarget := filepath.Join(tests.Temp, projectName)
// Use absolute paths to avoid issues when tests change working directory and pass relative -b flags.
// (e.g. running from tmp/gradleproject and passing -btmp/gradleproject/build.gradle results in duplicated paths)
var err error
projectTarget, err = filepath.Abs(projectTarget)
assert.NoError(t, err)
err = io.CopyDir(projectSrc, projectTarget, true, nil)
assert.NoError(t, err)
// Replace template variables in build.gradle
srcBuildFile := filepath.Join(projectTarget, "build.gradle")
buildGradlePath, err := tests.ReplaceTemplateVariables(srcBuildFile, projectTarget)
assert.NoError(t, err)
buildGradlePath, err = filepath.Abs(buildGradlePath)
assert.NoError(t, err)
assert.FileExists(t, buildGradlePath)
// Gradle accepts forward slashes on all platforms, and this avoids Windows path edge-cases.
buildGradlePath = filepath.ToSlash(buildGradlePath)
// Replace template variables in settings.gradle
srcSettingsFile := filepath.Join(projectTarget, "settings.gradle")
settingsPath, err := tests.ReplaceTemplateVariables(srcSettingsFile, projectTarget)
assert.NoError(t, err)
settingsPath, err = filepath.Abs(settingsPath)
assert.NoError(t, err)
assert.FileExists(t, settingsPath)
return buildGradlePath
}
// createGradleProjectKotlin creates a Kotlin DSL gradle project for testing
func createGradleProjectKotlin(t *testing.T, projectName string) string {
// Copy the entire project directory including source files
projectSrc := filepath.Join(filepath.FromSlash(tests.GetTestResourcesPath()), "gradle", projectName)
projectTarget := filepath.Join(tests.Temp, projectName)
// Use absolute paths to avoid issues when tests change working directory and pass relative -b flags.
var err error
projectTarget, err = filepath.Abs(projectTarget)
assert.NoError(t, err)
err = io.CopyDir(projectSrc, projectTarget, true, nil)
assert.NoError(t, err)
// Replace template variables in build.gradle.kts
srcBuildFile := filepath.Join(projectTarget, "build.gradle.kts")
buildGradlePath, err := tests.ReplaceTemplateVariables(srcBuildFile, projectTarget)
assert.NoError(t, err)
buildGradlePath, err = filepath.Abs(buildGradlePath)
assert.NoError(t, err)
assert.FileExists(t, buildGradlePath)
// Gradle accepts forward slashes on all platforms, and this avoids Windows path edge-cases.
buildGradlePath = filepath.ToSlash(buildGradlePath)
// Replace template variables in settings.gradle.kts
srcSettingsFile := filepath.Join(projectTarget, "settings.gradle.kts")
settingsPath, err := tests.ReplaceTemplateVariables(srcSettingsFile, projectTarget)
assert.NoError(t, err)
settingsPath, err = filepath.Abs(settingsPath)
assert.NoError(t, err)
assert.FileExists(t, settingsPath)
return buildGradlePath
}
func initGradleTest(t *testing.T) {
if !*tests.TestGradle {
t.Skip("Skipping Gradle test. To run Gradle test add the '-test.gradle=true' option.")
}
// Ensure clean state - unset native flag so traditional tests run correctly
_ = os.Unsetenv("JFROG_RUN_NATIVE")
createJfrogHomeConfig(t, true)
}
func prepareGradleSetupTest(t *testing.T) func() {
initGradleTest(t)
gradleHome := t.TempDir()
t.Setenv(gradle.UserHomeEnv, gradleHome)
wd, err := os.Getwd()
assert.NoError(t, err)
gradleProjectDir := t.TempDir()
err = io.CopyDir(filepath.Join(tests.GetTestResourcesPath(), "gradle", "setupcmd"), gradleProjectDir, true, nil)
require.NoError(t, err)
assert.NoError(t, os.Chdir(gradleProjectDir))
restoreDir := clientTestUtils.ChangeDirWithCallback(t, wd, gradleProjectDir)
return func() {
restoreDir()
}
}
// TestGradleBuildPublishWithCIVcsProps tests that CI VCS properties are set on Gradle artifacts
// when running build-publish in a CI environment (GitHub Actions).
// This test uses FlexPack mode (JFROG_RUN_NATIVE=true) with native Gradle publish task.
func TestGradleBuildPublishWithCIVcsProps(t *testing.T) {
initGradleTest(t)
buildName := "gradle-civcs-test"
buildNumber := "1"
// Setup GitHub Actions environment (uses real env vars on CI, mock values locally)
cleanupEnv, actualOrg, actualRepo := tests.SetupGitHubActionsEnv(t)
defer cleanupEnv()
// Enable FlexPack mode for native publish support
setEnvCallBack := clientTestUtils.SetEnvWithCallbackAndAssert(t, "JFROG_RUN_NATIVE", "true")
defer setEnvCallBack()
// Clean old build
inttestutils.DeleteBuild(serverDetails.ArtifactoryUrl, buildName, artHttpDetails)
defer inttestutils.DeleteBuild(serverDetails.ArtifactoryUrl, buildName, artHttpDetails)
// Create Gradle project with maven-publish configured (dedicated project for CI VCS test)
// Note: No config file needed for FlexPack mode - it uses native publish
buildGradlePath := createGradleProject(t, "civcsproject")
oldHomeDir := changeWD(t, filepath.Dir(buildGradlePath))
defer clientTestUtils.ChangeDirAndAssert(t, oldHomeDir)
// Run Gradle build with native publish task (FlexPack captures artifacts)
// Note: We're already in the project directory, so no -b flag needed
runJfrogCli(t, "gradle", "clean", "publish", "--build-name="+buildName, "--build-number="+buildNumber)
// Publish build info - should set CI VCS props on artifacts
assert.NoError(t, artifactoryCli.Exec("bp", buildName, buildNumber))
// Restore working directory before searching
clientTestUtils.ChangeDirAndAssert(t, oldHomeDir)
// Get the published build info to find artifact paths and repo
publishedBuildInfo, found, err := tests.GetBuildInfo(serverDetails, buildName, buildNumber)
assert.NoError(t, err)
assert.True(t, found, "Build info was not found")
// Create service manager for getting artifact properties
serviceManager, err := utils.CreateServiceManager(serverDetails, 3, 1000, false)
assert.NoError(t, err)
// Verify VCS properties on each artifact from build info
artifactCount := 0
for _, module := range publishedBuildInfo.BuildInfo.Modules {
for _, artifact := range module.Artifacts {
fullPath := artifact.OriginalDeploymentRepo + "/" + artifact.Path
props, err := serviceManager.GetItemProps(fullPath)
assert.NoError(t, err, "Failed to get properties for artifact: %s", fullPath)
assert.NotNil(t, props, "Properties are nil for artifact: %s", fullPath)
// Validate VCS properties
assert.Contains(t, props.Properties, "vcs.provider", "Missing vcs.provider on %s", artifact.Name)
assert.Contains(t, props.Properties["vcs.provider"], "github", "Wrong vcs.provider on %s", artifact.Name)
assert.Contains(t, props.Properties, "vcs.org", "Missing vcs.org on %s", artifact.Name)
assert.Contains(t, props.Properties["vcs.org"], actualOrg, "Wrong vcs.org on %s", artifact.Name)
assert.Contains(t, props.Properties, "vcs.repo", "Missing vcs.repo on %s", artifact.Name)
assert.Contains(t, props.Properties["vcs.repo"], actualRepo, "Wrong vcs.repo on %s", artifact.Name)
artifactCount++
}
}
assert.Greater(t, artifactCount, 0, "No artifacts in build info")
cleanGradleTest(t)
}