github.com/jfrog/jfrog-cli@v1.54.1/maven_test.go (about)

     1  package main
     2  
     3  import (
     4  	"github.com/jfrog/jfrog-cli-core/artifactory/commands/mvn"
     5  	"github.com/jfrog/jfrog-cli-core/artifactory/utils"
     6  	"github.com/jfrog/jfrog-cli-core/common/commands"
     7  	"github.com/jfrog/jfrog-client-go/artifactory/buildinfo"
     8  	"github.com/jfrog/jfrog-client-go/utils/io/fileutils"
     9  	"net/url"
    10  	"os"
    11  	"path/filepath"
    12  	"testing"
    13  
    14  	"github.com/jfrog/jfrog-cli-core/artifactory/spec"
    15  	"github.com/jfrog/jfrog-cli-core/utils/coreutils"
    16  	"github.com/jfrog/jfrog-cli/utils/tests"
    17  	cliproxy "github.com/jfrog/jfrog-cli/utils/tests/proxy/server"
    18  	"github.com/jfrog/jfrog-cli/utils/tests/proxy/server/certificate"
    19  	"github.com/stretchr/testify/assert"
    20  )
    21  
    22  const mavenFlagName = "maven"
    23  const mavenTestsProxyPort = "1028"
    24  const localRepoSystemProperty = "-Dmaven.repo.local="
    25  
    26  var localRepoDir string
    27  
    28  func cleanMavenTest() {
    29  	os.Unsetenv(coreutils.HomeDir)
    30  	deleteSpec := spec.NewBuilder().Pattern(tests.MvnRepo1).BuildSpec()
    31  	tests.DeleteFiles(deleteSpec, serverDetails)
    32  	deleteSpec = spec.NewBuilder().Pattern(tests.MvnRepo2).BuildSpec()
    33  	tests.DeleteFiles(deleteSpec, serverDetails)
    34  	tests.CleanFileSystem()
    35  }
    36  
    37  func TestMavenBuildWithServerID(t *testing.T) {
    38  	initMavenTest(t, false)
    39  
    40  	pomPath := filepath.Join(createSimpleMavenProject(t), "pom.xml")
    41  	configFilePath := filepath.Join(filepath.FromSlash(tests.GetTestResourcesPath()), "buildspecs", tests.MavenServerIDConfig)
    42  	configFilePath, err := tests.ReplaceTemplateVariables(configFilePath, "")
    43  	assert.NoError(t, err)
    44  	runAndValidateMaven(pomPath, configFilePath, t)
    45  	cleanMavenTest()
    46  }
    47  
    48  func TestNativeMavenBuildWithServerID(t *testing.T) {
    49  	initMavenTest(t, false)
    50  	runNativeMavenCleanInstall(t, createSimpleMavenProject, tests.MavenConfig, []string{})
    51  	// Validate
    52  	searchSpec, err := tests.CreateSpec(tests.SearchAllMaven)
    53  	assert.NoError(t, err)
    54  	verifyExistInArtifactory(tests.GetMavenDeployedArtifacts(), searchSpec, t)
    55  	cleanMavenTest()
    56  }
    57  
    58  func TestNativeMavenBuildWithServerIDAndDetailedSummary(t *testing.T) {
    59  	initMavenTest(t, false)
    60  	pomDir := createSimpleMavenProject(t)
    61  	configFilePath := filepath.Join(filepath.FromSlash(tests.GetTestResourcesPath()), "buildspecs", tests.MavenConfig)
    62  	destPath := filepath.Join(pomDir, ".jfrog", "projects")
    63  	createConfigFile(destPath, configFilePath, t)
    64  	searchSpec, err := tests.CreateSpec(tests.SearchAllMaven)
    65  	assert.NoError(t, err)
    66  
    67  	oldHomeDir := changeWD(t, pomDir)
    68  	defer func() {
    69  		err := os.Chdir(oldHomeDir)
    70  		assert.NoError(t, err)
    71  	}()
    72  	repoLocalSystemProp := localRepoSystemProperty + localRepoDir
    73  	filteredMavenArgs := []string{"clean", "install", repoLocalSystemProp}
    74  
    75  	mvnCmd := mvn.NewMvnCommand().SetConfiguration(new(utils.BuildConfiguration)).SetConfigPath(filepath.Join(destPath, tests.MavenConfig)).SetGoals(filteredMavenArgs).SetDetailedSummary(true)
    76  	assert.NoError(t, commands.Exec(mvnCmd))
    77  
    78  	// Validate
    79  	tests.VerifySha256DetailedSummaryFromResult(t, mvnCmd.Result())
    80  	verifyExistInArtifactory(tests.GetMavenDeployedArtifacts(), searchSpec, t)
    81  	cleanMavenTest()
    82  }
    83  
    84  func TestMavenBuildWithoutDeployer(t *testing.T) {
    85  	initMavenTest(t, false)
    86  	runNativeMavenCleanInstall(t, createSimpleMavenProject, tests.MavenWithoutDeployerConfig, []string{})
    87  	cleanMavenTest()
    88  }
    89  
    90  // This test check legacy behavior whereby the Maven config yml contains the username, url and password.
    91  func TestMavenBuildWithCredentials(t *testing.T) {
    92  	initMavenTest(t, false)
    93  
    94  	if *tests.RtAccessToken != "" {
    95  		origUsername, origPassword := tests.SetBasicAuthFromAccessToken(t)
    96  		defer func() {
    97  			*tests.RtUser = origUsername
    98  			*tests.RtPassword = origPassword
    99  		}()
   100  	}
   101  
   102  	pomPath := filepath.Join(createSimpleMavenProject(t), "pom.xml")
   103  	srcConfigTemplate := filepath.Join(filepath.FromSlash(tests.GetTestResourcesPath()), "buildspecs", tests.MavenUsernamePasswordTemplate)
   104  	configFilePath, err := tests.ReplaceTemplateVariables(srcConfigTemplate, "")
   105  	assert.NoError(t, err)
   106  
   107  	runAndValidateMaven(pomPath, configFilePath, t)
   108  	cleanMavenTest()
   109  }
   110  
   111  func TestInsecureTlsMavenBuild(t *testing.T) {
   112  	initMavenTest(t, true)
   113  	// Establish a reverse proxy without any certificates
   114  	os.Setenv(tests.HttpsProxyEnvVar, mavenTestsProxyPort)
   115  	go cliproxy.StartLocalReverseHttpProxy(serverDetails.ArtifactoryUrl, false)
   116  	// The two certificate files are created by the reverse proxy on startup in the current directory.
   117  	os.Remove(certificate.KEY_FILE)
   118  	os.Remove(certificate.CERT_FILE)
   119  	// Wait for the reverse proxy to start up.
   120  	assert.NoError(t, checkIfServerIsUp(cliproxy.GetProxyHttpsPort(), "https", false))
   121  	// Save the original Artifactory url, and change the url to proxy url
   122  	oldRtUrl := tests.RtUrl
   123  	parsedUrl, err := url.Parse(serverDetails.ArtifactoryUrl)
   124  	proxyUrl := "https://127.0.0.1:" + cliproxy.GetProxyHttpsPort() + parsedUrl.RequestURI()
   125  	tests.RtUrl = &proxyUrl
   126  
   127  	assert.NoError(t, createHomeConfigAndLocalRepo(t, false))
   128  	repoLocalSystemProp := localRepoSystemProperty + localRepoDir
   129  	pomDir := createSimpleMavenProject(t)
   130  	configFilePath := filepath.Join(filepath.FromSlash(tests.GetTestResourcesPath()), "buildspecs", tests.MavenConfig)
   131  	destPath := filepath.Join(pomDir, ".jfrog", "projects")
   132  	createConfigFile(destPath, configFilePath, t)
   133  	searchSpec, err := tests.CreateSpec(tests.SearchAllMaven)
   134  	assert.NoError(t, err)
   135  
   136  	oldHomeDir := changeWD(t, pomDir)
   137  	defer func() {
   138  		err := os.Chdir(oldHomeDir)
   139  		assert.NoError(t, err)
   140  	}()
   141  	rtCli := tests.NewJfrogCli(execMain, "jfrog rt", "")
   142  
   143  	// First, try to run without the insecure-tls flag, failure is expected.
   144  	err = rtCli.Exec("mvn", "clean", "install", repoLocalSystemProp)
   145  	assert.Error(t, err)
   146  	// Run with the insecure-tls flag
   147  	err = rtCli.Exec("mvn", "clean", "install", repoLocalSystemProp, "--insecure-tls")
   148  	assert.NoError(t, err)
   149  
   150  	// Validate Successful deployment
   151  	verifyExistInArtifactory(tests.GetMavenDeployedArtifacts(), searchSpec, t)
   152  
   153  	tests.RtUrl = oldRtUrl
   154  	cleanMavenTest()
   155  }
   156  
   157  func runAndValidateMaven(pomPath, configFilePath string, t *testing.T) {
   158  	repoLocalSystemProp := localRepoSystemProperty + localRepoDir
   159  	runCliWithLegacyBuildtoolsCmd(t, "mvn", "clean install -f "+pomPath+" "+repoLocalSystemProp, configFilePath)
   160  	searchSpec, err := tests.CreateSpec(tests.SearchAllMaven)
   161  	assert.NoError(t, err)
   162  
   163  	verifyExistInArtifactory(tests.GetMavenDeployedArtifacts(), searchSpec, t)
   164  }
   165  
   166  func createSimpleMavenProject(t *testing.T) string {
   167  	srcPomFile := filepath.Join(filepath.FromSlash(tests.GetTestResourcesPath()), "maven", "mavenproject", "pom.xml")
   168  	pomPath, err := tests.ReplaceTemplateVariables(srcPomFile, "")
   169  	assert.NoError(t, err)
   170  	return filepath.Dir(pomPath)
   171  }
   172  
   173  func createMultiMavenProject(t *testing.T) string {
   174  	projectDir := filepath.Join(filepath.FromSlash(tests.GetTestResourcesPath()), "maven", "multiproject")
   175  	destPath, err := os.Getwd()
   176  	if err != nil {
   177  		assert.NoError(t, err)
   178  		return ""
   179  	}
   180  	destPath = filepath.Join(destPath, tests.Temp)
   181  	assert.NoError(t, fileutils.CopyDir(projectDir, destPath, true, nil))
   182  	return destPath
   183  }
   184  
   185  func initMavenTest(t *testing.T, disableConfig bool) {
   186  	if !*tests.TestMaven {
   187  		t.Skip("Skipping Maven test. To run Maven test add the '-test.maven=true' option.")
   188  	}
   189  	if !disableConfig {
   190  		err := createHomeConfigAndLocalRepo(t, true)
   191  		assert.NoError(t, err)
   192  	}
   193  }
   194  
   195  func createHomeConfigAndLocalRepo(t *testing.T, encryptPassword bool) (err error) {
   196  	createJfrogHomeConfig(t, encryptPassword)
   197  	// To make sure we download the dependencies from  Artifactory, we will run with customize .m2 directory.
   198  	// The directory wil be deleted on the test cleanup as part as the out dir.
   199  	localRepoDir, err = os.MkdirTemp(os.Getenv(coreutils.HomeDir), "tmp.m2")
   200  	return err
   201  }
   202  
   203  func TestMavenBuildIncludePatterns(t *testing.T) {
   204  	initMavenTest(t, false)
   205  	buildNumber := "123"
   206  	commandArgs := []string{"--build-name=" + tests.MvnBuildName, "--build-number=" + buildNumber}
   207  	runNativeMavenCleanInstall(t, createMultiMavenProject, tests.MavenIncludeExcludePatternsConfig, commandArgs)
   208  	assert.NoError(t, artifactoryCli.Exec("build-publish", tests.MvnBuildName, buildNumber))
   209  
   210  	// Validate deployed artifacts.
   211  	searchSpec, err := tests.CreateSpec(tests.SearchAllMaven)
   212  	assert.NoError(t, err)
   213  	verifyExistInArtifactory(tests.GetMavenMultiIncludedDeployedArtifacts(), searchSpec, t)
   214  
   215  	// Validate build info.
   216  	publishedBuildInfo, found, err := tests.GetBuildInfo(serverDetails, tests.MvnBuildName, buildNumber)
   217  	if err != nil {
   218  		assert.NoError(t, err)
   219  		return
   220  	}
   221  	if !found {
   222  		assert.True(t, found, "build info was expected to be found")
   223  		return
   224  	}
   225  	buildInfo := publishedBuildInfo.BuildInfo
   226  	if len(buildInfo.Modules) != 4 {
   227  		assert.Len(t, buildInfo.Modules, 4)
   228  		return
   229  	}
   230  	validateSpecificModule(buildInfo, t, 13, 2, 1, "org.jfrog.test:multi1:3.7-SNAPSHOT", buildinfo.Maven)
   231  	validateSpecificModule(buildInfo, t, 1, 0, 2, "org.jfrog.test:multi2:3.7-SNAPSHOT", buildinfo.Maven)
   232  	validateSpecificModule(buildInfo, t, 15, 1, 1, "org.jfrog.test:multi3:3.7-SNAPSHOT", buildinfo.Maven)
   233  	validateSpecificModule(buildInfo, t, 0, 1, 0, "org.jfrog.test:multi:3.7-SNAPSHOT", buildinfo.Maven)
   234  	cleanMavenTest()
   235  }
   236  
   237  func runNativeMavenCleanInstall(t *testing.T, createProjectFunction func(*testing.T) string, configFileName string, additionalArgs []string) {
   238  	projDir := createProjectFunction(t)
   239  	configFilePath := filepath.Join(filepath.FromSlash(tests.GetTestResourcesPath()), "buildspecs", configFileName)
   240  	destPath := filepath.Join(projDir, ".jfrog", "projects")
   241  	createConfigFile(destPath, configFilePath, t)
   242  	assert.NoError(t, os.Rename(filepath.Join(destPath, configFileName), filepath.Join(destPath, "maven.yaml")))
   243  	oldHomeDir := changeWD(t, projDir)
   244  	defer func() {
   245  		err := os.Chdir(oldHomeDir)
   246  		assert.NoError(t, err)
   247  	}()
   248  	repoLocalSystemProp := localRepoSystemProperty + localRepoDir
   249  
   250  	args := []string{"mvn", "clean", "install", repoLocalSystemProp}
   251  	args = append(args, additionalArgs...)
   252  	runCli(t, args...)
   253  }