@Test
  public void testAddArtifacts() {
    final PublishArtifact publishArtifactConf1 = createNamedPublishArtifact("conf1");
    Configuration configurationStub1 = createConfigurationStub(publishArtifactConf1);
    final PublishArtifact publishArtifactConf2 = createNamedPublishArtifact("conf2");
    Configuration configurationStub2 = createConfigurationStub(publishArtifactConf2);
    final ArtifactsExtraAttributesStrategy artifactsExtraAttributesStrategyMock =
        context.mock(ArtifactsExtraAttributesStrategy.class);
    final Map<String, String> extraAttributesArtifact1 =
        WrapUtil.toMap("name", publishArtifactConf1.getName());
    final Map<String, String> extraAttributesArtifact2 =
        WrapUtil.toMap("name", publishArtifactConf2.getName());
    context.checking(
        new Expectations() {
          {
            one(artifactsExtraAttributesStrategyMock).createExtraAttributes(publishArtifactConf1);
            will(returnValue(extraAttributesArtifact1));
            one(artifactsExtraAttributesStrategyMock).createExtraAttributes(publishArtifactConf2);
            will(returnValue(extraAttributesArtifact2));
          }
        });
    DefaultModuleDescriptor moduleDescriptor =
        HelperUtil.createModuleDescriptor(
            WrapUtil.toSet(configurationStub1.getName(), configurationStub2.getName()));

    DefaultArtifactsToModuleDescriptorConverter artifactsToModuleDescriptorConverter =
        new DefaultArtifactsToModuleDescriptorConverter(artifactsExtraAttributesStrategyMock);

    artifactsToModuleDescriptorConverter.addArtifacts(
        moduleDescriptor, WrapUtil.toSet(configurationStub1, configurationStub2));

    assertArtifactIsAdded(configurationStub1, moduleDescriptor, extraAttributesArtifact1);
    assertArtifactIsAdded(configurationStub2, moduleDescriptor, extraAttributesArtifact2);
    assertThat(moduleDescriptor.getAllArtifacts().length, equalTo(2));
  }
  @Test
  public void deployOrInstall() throws IOException, PlexusContainerException {
    getMavenResolver().mavenSettingsSupplier = context.mock(MavenSettingsSupplier.class);

    PublishArtifact classifierArtifact = artifact(new File("classifier.jar"));
    final DefaultMavenDeployment deployment1 =
        new DefaultMavenDeployment(
            artifact(new File("pom1.pom")),
            artifact(new File("artifact1.jar")),
            Collections.<PublishArtifact>emptySet());
    final DefaultMavenDeployment deployment2 =
        new DefaultMavenDeployment(
            artifact(new File("pom2.pom")),
            artifact(new File("artifact2.jar")),
            WrapUtil.toSet(classifierArtifact));
    final Set<DefaultMavenDeployment> testDefaultMavenDeployments =
        WrapUtil.toSet(deployment1, deployment2);
    final AttachedArtifact attachedArtifact = new AttachedArtifact();
    @SuppressWarnings("unchecked")
    final Action<MavenDeployment> action = context.mock(Action.class);

    context.checking(
        new Expectations() {
          {
            allowing((CustomInstallDeployTaskSupport) getInstallDeployTask())
                .clearAttachedArtifactsList();
            allowing((CustomInstallDeployTaskSupport) getInstallDeployTask()).getSettings();
            will(returnValue(mavenSettingsMock));
            allowing((CustomInstallDeployTaskSupport) getInstallDeployTask()).getProject();
            will(returnValue(AntUtil.createProject()));
            allowing((CustomInstallDeployTaskSupport) getInstallDeployTask()).createAttach();
            will(returnValue(attachedArtifact));
            one(artifactPomContainerMock).addArtifact(TEST_ARTIFACT, TEST_JAR_FILE);
            allowing(artifactPomContainerMock).createDeployableFilesInfos();
            will(returnValue(testDefaultMavenDeployments));
            one(action).execute(deployment1);
            one(action).execute(deployment2);
          }
        });

    getMavenResolver().beforeDeployment(action);
    getMavenResolver().publish(TEST_IVY_ARTIFACT, TEST_IVY_FILE, true);
    getMavenResolver().publish(TEST_ARTIFACT, TEST_JAR_FILE, true);
    checkTransaction(testDefaultMavenDeployments, attachedArtifact, classifierArtifact);
    assertSame(mavenSettingsMock, getMavenResolver().getSettings());
  }
 private IvyResolver createResolver(Set<String> schemes) {
   if (schemes.isEmpty()) {
     throw new InvalidUserDataException(
         "You must specify a base url or at least one artifact pattern for an Ivy repository.");
   }
   if (!WrapUtil.toSet("http", "https", "file").containsAll(schemes)) {
     throw new InvalidUserDataException(
         "You may only specify 'file', 'http' and 'https' urls for an Ivy repository.");
   }
   if (WrapUtil.toSet("http", "https").containsAll(schemes)) {
     return createResolver(transportFactory.createHttpTransport(getName(), getCredentials()));
   }
   if (WrapUtil.toSet("file").containsAll(schemes)) {
     return createResolver(transportFactory.createFileTransport(getName()));
   }
   throw new InvalidUserDataException(
       "You cannot mix file and http(s) urls for a single Ivy repository. Please declare 2 separate repositories.");
 }
示例#4
0
 private void overwriteIncludesIfSinglePropertyIsSet(final Test test) {
   String singleTest = getTaskPrefixedProperty(test, "single");
   if (singleTest == null) {
     return;
   }
   test.doFirst(
       new Action<Task>() {
         public void execute(Task task) {
           test.getLogger().info("Running single tests with pattern: {}", test.getIncludes());
         }
       });
   test.setIncludes(WrapUtil.toSet(String.format("**/%s*.class", singleTest)));
   failIfNoTestIsExecuted(test, singleTest);
 }
 protected DependencyFactory createDependencyFactory() {
   ClassGenerator classGenerator = get(ClassGenerator.class);
   DefaultProjectDependencyFactory projectDependencyFactory =
       new DefaultProjectDependencyFactory(
           startParameter.getProjectDependenciesBuildInstruction(), classGenerator);
   return new DefaultDependencyFactory(
       WrapUtil.<IDependencyImplementationFactory>toSet(
           new ModuleDependencyFactory(classGenerator),
           new SelfResolvingDependencyFactory(classGenerator),
           new ClassPathDependencyFactory(
               classGenerator, get(ClassPathRegistry.class), new IdentityFileResolver()),
           projectDependencyFactory),
       new DefaultClientModuleFactory(classGenerator),
       projectDependencyFactory);
 }
示例#6
0
 @Test
 public void testCheckInputs() throws IOException {
   assertThat(
       wrapper.getInputs().getProperties().keySet(),
       equalTo(
           WrapUtil.toSet(
               "jarPath",
               "archiveClassifier",
               "distributionBase",
               "archiveBase",
               "distributionPath",
               "archiveName",
               "urlRoot",
               "scriptDestinationPath",
               "gradleVersion",
               "archivePath")));
 }
示例#7
0
 private void configureBasedOnSingleProperty(final Test test) {
   String singleTest = getTaskPrefixedProperty(test, "single");
   if (singleTest == null) {
     // configure inputs so that the test task is skipped when there are no source files.
     // unfortunately, this only applies when 'test.single' is *not* applied
     // We should fix this distinction, the behavior with 'test.single' or without it should be the
     // same
     test.getInputs().source(test.getCandidateClassFiles());
     return;
   }
   test.prependParallelSafeAction(
       new Action<Task>() {
         public void execute(Task task) {
           test.getLogger().info("Running single tests with pattern: {}", test.getIncludes());
         }
       });
   test.setIncludes(WrapUtil.toSet(String.format("**/%s*.class", singleTest)));
   test.addTestListener(
       new NoMatchingTestsReporter("Could not find matching test for pattern: " + singleTest));
 }
public class CommandLineConverterTestSupport {
  protected TestFile currentDir;
  protected File expectedBuildFile;
  protected File expectedGradleUserHome = new BuildLayoutParameters().getGradleUserHomeDir();
  protected File expectedCurrentDir;
  protected File expectedProjectDir;
  protected List<String> expectedTaskNames = WrapUtil.toList();
  protected Set<String> expectedExcludedTasks = WrapUtil.toSet();
  protected boolean buildProjectDependencies = true;
  protected Map<String, String> expectedSystemProperties = new HashMap<String, String>();
  protected Map<String, String> expectedProjectProperties = new HashMap<String, String>();
  protected List<File> expectedInitScripts = new ArrayList<File>();
  protected boolean expectedSearchUpwards = true;
  protected boolean expectedDryRun;
  protected ShowStacktrace expectedShowStackTrace = ShowStacktrace.INTERNAL_EXCEPTIONS;
  protected LogLevel expectedLogLevel = LogLevel.LIFECYCLE;
  protected boolean expectedColorOutput = true;
  protected ConsoleOutput expectedConsoleOutput = ConsoleOutput.Auto;
  protected StartParameter actualStartParameter;
  protected boolean expectedProfile;
  protected File expectedProjectCacheDir;
  protected boolean expectedRefreshDependencies;
  protected boolean expectedRerunTasks;
  protected final DefaultCommandLineConverter commandLineConverter =
      new DefaultCommandLineConverter();
  protected boolean expectedContinue;
  protected boolean expectedOffline;
  protected boolean expectedRecompileScripts;
  protected boolean expectedParallelProjectExecution;
  protected int expectedParallelExecutorCount;
  protected int expectedMaxWorkersCount = Runtime.getRuntime().availableProcessors();
  protected boolean expectedConfigureOnDemand;
  protected boolean expectedContinuous;

  protected void checkConversion(String... args) {
    actualStartParameter = new StartParameter();
    actualStartParameter.setCurrentDir(currentDir);
    commandLineConverter.convert(Arrays.asList(args), actualStartParameter);
    // We check the params passed to the build factory
    checkStartParameter(actualStartParameter);
  }

  protected void checkStartParameter(StartParameter startParameter) {
    assertEquals(expectedBuildFile, startParameter.getBuildFile());
    assertEquals(expectedTaskNames, startParameter.getTaskNames());
    assertEquals(buildProjectDependencies, startParameter.isBuildProjectDependencies());
    if (expectedCurrentDir != null) {
      assertEquals(
          expectedCurrentDir.getAbsoluteFile(), startParameter.getCurrentDir().getAbsoluteFile());
    }
    assertEquals(expectedProjectDir, startParameter.getProjectDir());
    assertEquals(expectedSearchUpwards, startParameter.isSearchUpwards());
    assertEquals(expectedProjectProperties, startParameter.getProjectProperties());
    assertEquals(expectedSystemProperties, startParameter.getSystemPropertiesArgs());
    assertEquals(
        expectedGradleUserHome.getAbsoluteFile(),
        startParameter.getGradleUserHomeDir().getAbsoluteFile());
    assertEquals(expectedLogLevel, startParameter.getLogLevel());
    assertEquals(expectedColorOutput, startParameter.isColorOutput());
    assertEquals(expectedConsoleOutput, startParameter.getConsoleOutput());
    assertEquals(expectedDryRun, startParameter.isDryRun());
    assertEquals(expectedShowStackTrace, startParameter.getShowStacktrace());
    assertEquals(expectedExcludedTasks, startParameter.getExcludedTaskNames());
    assertEquals(expectedInitScripts, startParameter.getInitScripts());
    assertEquals(expectedProfile, startParameter.isProfile());
    assertEquals(expectedContinue, startParameter.isContinueOnFailure());
    assertEquals(expectedOffline, startParameter.isOffline());
    assertEquals(expectedRecompileScripts, startParameter.isRecompileScripts());
    assertEquals(expectedRerunTasks, startParameter.isRerunTasks());
    assertEquals(expectedRefreshDependencies, startParameter.isRefreshDependencies());
    assertEquals(expectedProjectCacheDir, startParameter.getProjectCacheDir());
    assertEquals(expectedParallelExecutorCount, startParameter.getParallelThreadCount());
    assertEquals(expectedConfigureOnDemand, startParameter.isConfigureOnDemand());
    assertEquals(expectedMaxWorkersCount, startParameter.getMaxWorkerCount());
    assertEquals(expectedContinuous, startParameter.isContinuous());
  }
}
  public Gradle newInstance(StartParameter startParameter) {
    loggingConfigurer.configure(startParameter.getLogLevel());
    ImportsReader importsReader = new ImportsReader(startParameter.getDefaultImportsFile());
    CachePropertiesHandler cachePropertiesHandler = new DefaultCachePropertiesHandler();

    ISettingsFinder settingsFinder =
        new EmbeddedScriptSettingsFinder(
            new DefaultSettingsFinder(
                WrapUtil.<ISettingsFileSearchStrategy>toList(
                    new MasterDirSettingsFinderStrategy(), new ParentDirSettingsFinderStrategy())));
    ConfigurationContainerFactory configurationContainerFactory =
        new DefaultConfigurationContainerFactory();
    DefaultInternalRepository internalRepository = new DefaultInternalRepository();
    DependencyFactory dependencyFactory =
        new DefaultDependencyFactory(
            WrapUtil.<IDependencyImplementationFactory>toSet(new ModuleDependencyFactory()),
            new DefaultClientModuleFactory(),
            new DefaultProjectDependencyFactory());
    ResolverFactory resolverFactory = new DefaultResolverFactory();
    DefaultProjectEvaluator projectEvaluator =
        new DefaultProjectEvaluator(
            importsReader,
            new DefaultScriptProcessor(
                new DefaultScriptCompilationHandler(
                    cachePropertiesHandler, new BuildScriptTransformer()),
                startParameter.getCacheUsage()),
            new DefaultProjectScriptMetaData());
    Gradle gradle =
        new Gradle(
            startParameter,
            settingsFinder,
            new DefaultGradlePropertiesLoader(),
            new ScriptLocatingSettingsProcessor(
                new PropertiesLoadingSettingsProcessor(
                    new ScriptEvaluatingSettingsProcessor(
                        new DefaultSettingsScriptMetaData(),
                        new DefaultScriptProcessor(
                            new DefaultScriptCompilationHandler(cachePropertiesHandler),
                            startParameter.getCacheUsage()),
                        importsReader,
                        new SettingsFactory(
                            new DefaultProjectDescriptorRegistry(),
                            dependencyFactory,
                            new DefaultRepositoryHandler(resolverFactory, null),
                            configurationContainerFactory,
                            internalRepository,
                            new BuildSourceBuilder(
                                new DefaultGradleFactory(
                                    new LoggingConfigurer() {
                                      public void configure(LogLevel logLevel) {
                                        // do nothing
                                      }
                                    }),
                                new DefaultCacheInvalidationStrategy()))))),
            new BuildLoader(
                new ProjectFactory(
                    new TaskFactory(),
                    configurationContainerFactory,
                    dependencyFactory,
                    new DefaultRepositoryHandlerFactory(resolverFactory),
                    new DefaultPublishArtifactFactory(),
                    internalRepository,
                    projectEvaluator,
                    new PluginRegistry(startParameter.getPluginPropertiesFile()),
                    startParameter.getBuildScriptSource(),
                    new DefaultAntBuilderFactory(new AntLoggingAdapter())),
                internalRepository),
            new BuildConfigurer(new ProjectDependencies2TaskResolver()));
    gradle.addBuildListener(internalRepository);
    gradle.addBuildListener(projectEvaluator);
    return gradle;
  }
示例#10
0
/** @author Hans Dockter */
public class TestTest extends AbstractConventionTaskTest {
  static final String TEST_PATTERN_1 = "pattern1";
  static final String TEST_PATTERN_2 = "pattern2";
  static final String TEST_PATTERN_3 = "pattern3";

  static final File TEST_ROOT_DIR = new File("ROOTDir");
  static final File TEST_TEST_CLASSES_DIR = new File(TEST_ROOT_DIR, "testClassesDir");
  static final File TEST_TEST_RESULTS_DIR = new File(TEST_ROOT_DIR, "resultDir");
  static final File TEST_TEST_REPORT_DIR = new File(TEST_ROOT_DIR, "report/tests");

  static final Set TEST_DEPENDENCY_MANAGER_CLASSPATH = WrapUtil.toSet(new File("jar1"));
  static final List TEST_CONVERTED_UNMANAGED_CLASSPATH = WrapUtil.toList(new File("jar2"));
  static final List TEST_UNMANAGED_CLASSPATH = WrapUtil.toList("jar2");
  static final List TEST_CONVERTED_CLASSPATH =
      GUtil.addLists(
          WrapUtil.toList(TEST_TEST_CLASSES_DIR),
          TEST_CONVERTED_UNMANAGED_CLASSPATH,
          TEST_DEPENDENCY_MANAGER_CLASSPATH);

  static final Set<String> okTestClassNames =
      new HashSet<String>(Arrays.asList("test.HumanTest", "test.CarTest"));

  private JUnit4Mockery context =
      new JUnit4Mockery() {
        {
          setImposteriser(ClassImposteriser.INSTANCE);
        }
      };

  TestFramework testFrameworkMock = context.mock(TestFramework.class);

  private ClasspathConverter classpathConverterMock = context.mock(ClasspathConverter.class);
  private ExistingDirsFilter existentDirsFilterMock = context.mock(ExistingDirsFilter.class);
  private FileCollection configurationMock = context.mock(FileCollection.class);

  private Test test;

  @Before
  public void setUp() {
    super.setUp();
    test = new Test(getProject(), AbstractTaskTest.TEST_TASK_NAME);
    ((AbstractProject) test.getProject()).setProjectDir(TEST_ROOT_DIR);
    context.checking(
        new Expectations() {
          {
            one(testFrameworkMock).initialize(getProject(), test);
          }
        });
    test.useTestFramework(testFrameworkMock);

    if (!TEST_TEST_CLASSES_DIR.exists()) assertTrue(TEST_TEST_CLASSES_DIR.mkdirs());
  }

  public AbstractTask getTask() {
    return test;
  }

  @org.junit.Test
  public void testInit() {
    assertNotNull(test.getTestFramework());
    assertNotNull(test.existingDirsFilter);
    assertNotNull(test.classpathConverter);
    assertNull(test.getTestClassesDir());
    assertNull(test.getConfiguration());
    assertNull(test.getTestResultsDir());
    assertNull(test.getTestReportDir());
    assertNull(test.getIncludes());
    assertNull(test.getExcludes());
    assertNull(test.getUnmanagedClasspath());
    assert test.isStopAtFailuresOrErrors();
  }

  @org.junit.Test
  public void testExecute() {
    setUpMocks(test);
    setExistingDirsFilter();
    context.checking(
        new Expectations() {
          {
            one(testFrameworkMock).prepare(getProject(), test);
            one(testFrameworkMock).getTestClassNames();
            will(returnValue(okTestClassNames));
            one(testFrameworkMock)
                .execute(getProject(), test, okTestClassNames, new ArrayList<String>());
            one(testFrameworkMock).report(getProject(), test);
          }
        });

    test.execute();
  }

  @org.junit.Test
  public void testExecuteWithoutReporting() {
    setUpMocks(test);
    setExistingDirsFilter();
    test.setTestReport(false);
    context.checking(
        new Expectations() {
          {
            one(testFrameworkMock).prepare(getProject(), test);
            one(testFrameworkMock).getTestClassNames();
            will(returnValue(okTestClassNames));
            one(testFrameworkMock)
                .execute(getProject(), test, okTestClassNames, new ArrayList<String>());
          }
        });

    test.execute();
  }

  @org.junit.Test(expected = GradleException.class)
  public void testExecuteWithTestFailuresAndStopAtFailures() {
    setUpMocks(test);
    setExistingDirsFilter();
    context.checking(
        new Expectations() {
          {
            one(testFrameworkMock).prepare(getProject(), test);
            one(testFrameworkMock).getTestClassNames();
            will(returnValue(okTestClassNames));
            one(testFrameworkMock)
                .execute(getProject(), test, okTestClassNames, new ArrayList<String>());
          }
        });
    test.execute();
  }

  @org.junit.Test
  public void testExecuteWithTestFailuresAndContinueWithFailures() {
    setUpMocks(test);
    setExistingDirsFilter();
    test.setStopAtFailuresOrErrors(false);
    context.checking(
        new Expectations() {
          {
            one(testFrameworkMock).prepare(getProject(), test);
            one(testFrameworkMock).getTestClassNames();
            will(returnValue(okTestClassNames));
            one(testFrameworkMock)
                .execute(getProject(), test, okTestClassNames, new ArrayList<String>());
            one(testFrameworkMock).report(getProject(), test);
          }
        });
    test.execute();
  }

  @org.junit.Test
  public void testGetClasspath() {
    setUpMocks(test);
    assertEquals(TEST_CONVERTED_CLASSPATH, test.getClasspath());
  }

  public void testExecuteWithUnspecifiedCompiledTestsDir() {
    setUpMocks(test);
    test.setTestClassesDir(null);
    try {
      test.execute();
      fail();
    } catch (Exception e) {
      assertThat(e.getCause(), Matchers.instanceOf(InvalidUserDataException.class));
    }
  }

  public void testExecuteWithUnspecifiedTestResultsDir() {
    setUpMocks(test);
    test.setTestResultsDir(null);
    try {
      test.execute();
      fail();
    } catch (Exception e) {
      assertThat(e.getCause(), Matchers.instanceOf(InvalidUserDataException.class));
    }
  }

  @org.junit.Test
  public void testExecuteWithNonExistingCompiledTestsDir() {
    setUpMocks(test);
    test.setUnmanagedClasspath(null);
    context.checking(
        new Expectations() {
          {
            allowing(existentDirsFilterMock)
                .checkExistenceAndThrowStopActionIfNot(TEST_TEST_CLASSES_DIR);
            will(throwException(new StopActionException()));
          }
        });
    test.existingDirsFilter = existentDirsFilterMock;

    test.execute();
  }

  private void setUpMocks(final Test test) {
    test.setTestClassesDir(TEST_TEST_CLASSES_DIR);
    test.setTestResultsDir(TEST_TEST_RESULTS_DIR);
    test.setTestReportDir(TEST_TEST_REPORT_DIR);
    test.setUnmanagedClasspath(TEST_UNMANAGED_CLASSPATH);
    test.setConfiguration(configurationMock);
    test.classpathConverter = classpathConverterMock;

    context.checking(
        new Expectations() {
          {
            allowing(configurationMock).iterator();
            will(returnIterator(TEST_DEPENDENCY_MANAGER_CLASSPATH));
            allowing(classpathConverterMock)
                .createFileClasspath(
                    TEST_ROOT_DIR,
                    GUtil.addLists(
                        WrapUtil.toList(TEST_TEST_CLASSES_DIR),
                        TEST_UNMANAGED_CLASSPATH,
                        TEST_DEPENDENCY_MANAGER_CLASSPATH));
            will(returnValue(TEST_CONVERTED_CLASSPATH));
          }
        });
  }

  @org.junit.Test
  public void testIncludes() {
    assertSame(test, test.include(TEST_PATTERN_1, TEST_PATTERN_2));
    assertEquals(WrapUtil.toList(TEST_PATTERN_1, TEST_PATTERN_2), test.getIncludes());
    test.include(TEST_PATTERN_3);
    assertEquals(
        WrapUtil.toList(TEST_PATTERN_1, TEST_PATTERN_2, TEST_PATTERN_3), test.getIncludes());
  }

  @org.junit.Test
  public void testExcludes() {
    assertSame(test, test.exclude(TEST_PATTERN_1, TEST_PATTERN_2));
    assertEquals(WrapUtil.toList(TEST_PATTERN_1, TEST_PATTERN_2), test.getExcludes());
    test.exclude(TEST_PATTERN_3);
    assertEquals(
        WrapUtil.toList(TEST_PATTERN_1, TEST_PATTERN_2, TEST_PATTERN_3), test.getExcludes());
  }

  @org.junit.Test
  public void testUnmanagedClasspath() {
    List<Object> list1 = WrapUtil.toList("a", new Object());
    assertSame(test, test.unmanagedClasspath(list1.toArray(new Object[list1.size()])));
    assertEquals(list1, test.getUnmanagedClasspath());
    List list2 = WrapUtil.toList(WrapUtil.toList("b", "c"));
    test.unmanagedClasspath(list2.toArray(new Object[list2.size()]));
    assertEquals(GUtil.addLists(list1, GUtil.flatten(list2)), test.getUnmanagedClasspath());
  }

  private void setExistingDirsFilter() {
    context.checking(
        new Expectations() {
          {
            allowing(existentDirsFilterMock)
                .checkExistenceAndThrowStopActionIfNot(TEST_TEST_CLASSES_DIR);
          }
        });
    test.existingDirsFilter = existentDirsFilterMock;
  }

  @After
  public void tearDown() throws IOException {
    FileUtils.deleteDirectory(TEST_ROOT_DIR);
  }
}