@Before
  public void setup() throws Exception {
    configHelper = new GoConfigFileHelper();
    configHelper.usingCruiseConfigDao(goConfigDao);
    configHelper.onSetUp();
    testRepo = new SvnTestRepo("testSvnRepo");
    dbHelper.onSetUp();
    repository = new SvnCommand(null, testRepo.projectRepositoryUrl());
    mingleConfig = configHelper.addPipeline("mingle", STAGE_NAME, repository, "unit", "functional");

    goConfig = configHelper.addPipeline("go", STAGE_NAME, repository, "unit");
    StageConfig ftStageConfig = StageConfigMother.custom("ft", "twist");
    ftStageConfig
        .jobConfigByConfigName(new CaseInsensitiveString("twist"))
        .addVariable("JOB_LVL", "job value");
    ftStageConfig.setVariables(env("STAGE_LVL", "stage value"));
    configHelper.addStageToPipeline("go", ftStageConfig);
    configHelper.addEnvironmentVariableToPipeline("go", env("PIPELINE_LVL", "pipeline value"));
    configHelper.addEnvironments("uat");
    EnvironmentConfig uatEnv =
        configHelper.currentConfig().getEnvironments().named(new CaseInsensitiveString("uat"));
    uatEnv.addPipeline(new CaseInsensitiveString("go"));
    uatEnv.addEnvironmentVariable("ENV_LVL", "env value");

    evolveConfig = configHelper.addPipeline("evolve", STAGE_NAME, repository, "unit");
    goCache.clear();
  }
  @Before
  public void setUp() throws Exception {
    dbHelper.onSetUp();
    configHelper = new GoConfigFileHelper(goConfigDao);
    configHelper.onSetUp();
    configHelper.addPipeline(
        "bar", "stage", MaterialConfigsMother.defaultMaterialConfigs(), "build");

    pipelineConfig =
        configHelper.addPipeline(
            "foo", "stage", MaterialConfigsMother.defaultMaterialConfigs(), "build");
    configHelper.addMingleConfigToPipeline(
        "foo",
        new MingleConfig("https://some-tracking-tool:8443", "project-super-secret", "hello=world"));

    CruiseConfig cruiseConfig = configHelper.load();
    PipelineConfigs group = cruiseConfig.findGroup("defaultGroup");
    group.setAuthorization(
        new Authorization(
            new ViewConfig(new AdminUser(new CaseInsensitiveString("authorized_user")))));
    configHelper.writeConfigFile(cruiseConfig);

    SecurityConfig securityConfig =
        new SecurityConfig(
            new LdapConfig(new GoCipher()), new PasswordFileConfig("/tmp/foo.passwd"), true);
    securityConfig.adminsConfig().add(new AdminUser(new CaseInsensitiveString("admin")));
    configHelper.addSecurity(securityConfig);
  }
  @Before
  public void setup() throws Exception {
    diskSpaceSimulator = new DiskSpaceSimulator();
    new HgTestRepo("testHgRepo");

    svnRepository = new SvnTestRepo("testSvnRepo");

    dbHelper.onSetUp();
    configHelper.onSetUp();
    configHelper.usingCruiseConfigDao(goConfigDao).initializeConfigFile();

    repository = new SvnCommand(null, svnRepository.projectRepositoryUrl());

    goParentPipelineConfig =
        configHelper.addPipeline(
            GO_PIPELINE_UPSTREAM,
            STAGE_NAME,
            new MaterialConfigs(new GitMaterialConfig("foo-bar")),
            "unit");

    goPipelineConfig = configHelper.addPipeline(GO_PIPELINE_NAME, STAGE_NAME, repository, "unit");

    svnMaterialRevs = new MaterialRevisions();
    SvnMaterial svnMaterial = SvnMaterial.createSvnMaterialWithMock(repository);
    svnMaterialRevs.addRevision(
        svnMaterial,
        svnMaterial.latestModification(
            null, new ServerSubprocessExecutionContext(goConfigService, new SystemEnvironment())));

    final MaterialRevisions materialRevisions = new MaterialRevisions();
    SvnMaterial anotherSvnMaterial = SvnMaterial.createSvnMaterialWithMock(repository);
    materialRevisions.addRevision(
        anotherSvnMaterial,
        anotherSvnMaterial.latestModification(null, subprocessExecutionContext));

    transactionTemplate.execute(
        new TransactionCallbackWithoutResult() {
          @Override
          protected void doInTransactionWithoutResult(TransactionStatus status) {
            materialRepository.save(svnMaterialRevs);
          }
        });

    BuildCause buildCause = BuildCause.createWithModifications(svnMaterialRevs, "");

    mingleConfig =
        configHelper.addPipeline(
            MINGLE_PIPELINE_NAME,
            STAGE_NAME,
            repository,
            new Filter(new IgnoredFiles("**/*.doc")),
            "unit",
            "functional");
    latestPipeline = PipelineMother.schedule(this.mingleConfig, buildCause);
    latestPipeline = pipelineDao.saveWithStages(latestPipeline);
    dbHelper.passStage(latestPipeline.getStages().first());
    pipelineScheduleQueue.clear();
  }
 @Test
 public void shouldReturnXmlAndErrorMessageWhenPostOfPipelineAsInvalidPartialXml()
     throws Exception {
   groupName = BasicPipelineConfigs.DEFAULT_GROUP;
   configHelper.addPipeline("pipeline", "stage", "build1", "build2");
   String badXml =
       "<pipeline name=\"cruise\" labeltemplate=\"invalid\">\n"
           + "  <materials>\n"
           + "    <svn url=\"file:///tmp/foo\" checkexternals=\"true\" />\n"
           + "  </materials>\n"
           + "  <stage name=\"dev\">\n"
           + "    <jobs>\n"
           + "      <job name=\"linux\" />\n"
           + "      <job name=\"windows\" />\n"
           + "    </jobs>\n"
           + "  </stage>\n"
           + "</pipeline>";
   String md5 = goConfigDao.md5OfConfigFile();
   ModelAndView mav = controller.postPipelineAsXmlPartial(0, groupName, badXml, md5, response);
   assertThat(response.getStatus(), is(SC_CONFLICT));
   assertThat(response.getContentType(), is(RESPONSE_CHARSET_JSON));
   Map<String, String> json = (Map) mav.getModel().get("json");
   assertThat(json.get("result").toString(), containsString("Label is invalid"));
   assertThat(json.get("originalContent"), is(badXml));
 }
  @Before
  public void setUp() throws Exception {
    configHelper = new GoConfigFileHelper().usingCruiseConfigDao(goConfigDao);
    configHelper.onSetUp();

    dbHelper.onSetUp();
    fixture = new PipelineWithTwoStages(materialRepository, transactionTemplate);
    fixture.usingConfigHelper(configHelper).usingDbHelper(dbHelper).onSetUp();

    repository = new SvnCommand(null, testRepo.projectRepositoryUrl());
    evolveConfig = configHelper.addPipeline("evolve", STAGE_NAME, repository, "unit");
    configHelper.addPipeline("anotherPipeline", STAGE_NAME, repository, "anotherTest");
    configHelper.addPipeline("thirdPipeline", STAGE_NAME, repository, "yetAnotherTest");
    goConfigService.forceNotifyListeners();
    goCache.clear();
    u = new ScheduleTestUtil(transactionTemplate, materialRepository, dbHelper, configHelper);

    agent = new AgentStub();
  }
  @Test
  public void shouldGetBuildAsPartialXml() throws Exception {
    configHelper.addPipeline("pipeline", "stage", "build1", "build2");

    String md5 = goConfigDao.md5OfConfigFile();

    controller.getBuildAsXmlPartial("pipeline", "stage", 1, null, response);
    assertValidContentAndStatus(SC_OK, "text/xml", "<job name=\"build2\" />");
    assertThat(response.getHeader(XmlAction.X_CRUISE_CONFIG_MD5), is(md5));
  }
 @Test
 public void shouldPostStageAsPartialXml() throws Exception {
   configHelper.addPipeline("pipeline", "stage", "build1", "build2");
   String newXml = NEW_STAGE;
   String md5 = goConfigDao.md5OfConfigFile();
   ModelAndView mav = controller.postStageAsXmlPartial("pipeline", 0, newXml, md5, response);
   assertThat(response.getStatus(), is(SC_OK));
   assertThat(response.getContentType(), is(RESPONSE_CHARSET_JSON));
   Map json = (Map) mav.getModel().get("json");
   new JsonTester(json).shouldContain("{ 'result' : 'Stage changed successfully.' }");
 }
  @Test
  public void shouldGetConfigAsXml() throws Exception {
    configHelper.addPipeline("pipeline", "stage", "build1", "build2");

    controller.getCurrentConfigXml(null, response);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    new MagicalGoConfigXmlWriter(new ConfigCache(), registry, metricsProbeService)
        .write(goConfigDao.loadForEditing(), os, true);
    assertValidContentAndStatus(SC_OK, "text/xml", os.toString());
    assertThat(
        response.getHeader(XmlAction.X_CRUISE_CONFIG_MD5), is(goConfigDao.md5OfConfigFile()));
  }
 @Test
 public void shouldReturnXmlAndErrorMessageWhenInvalidPostOfStageAsPartialXml() throws Exception {
   configHelper.addPipeline("pipeline", "stage", "build1", "build2");
   String md5 = goConfigDao.md5OfConfigFile();
   ModelAndView mav = controller.postStageAsXmlPartial("pipeline", 4, NEW_STAGE, md5, response);
   assertThat(response.getStatus(), is(SC_NOT_FOUND));
   assertThat(response.getContentType(), is(RESPONSE_CHARSET_JSON));
   Map<String, Object> json = (Map) mav.getModel().get("json");
   Map<String, Object> jsonMap = new LinkedHashMap<>();
   jsonMap.put("result", "Stage does not exist.");
   jsonMap.put("originalContent", NEW_STAGE);
   assertThat(json, is(jsonMap));
 }
  @Test
  public void shouldReturnConflictIfGetRequestUsesIncorrectConfigMD5() throws Exception {
    String oldMd5 = goConfigDao.md5OfConfigFile();

    configHelper.addPipeline("pipeline", "stage", "build1", "build2");

    String newMd5 = goConfigDao.md5OfConfigFile();

    controller.getBuildAsXmlPartial("pipeline", "stage", 1, oldMd5, response);
    assertValidContentAndStatus(
        SC_CONFLICT, RESPONSE_CHARSET, ConfigFileHasChangedException.CONFIG_CHANGED_PLEASE_REFRESH);
    assertThat(response.getHeader(XmlAction.X_CRUISE_CONFIG_MD5), is(newMd5));
  }
  @Test
  public void shouldLoadShallowCloneFlagForGitMaterialsBaseOnTheirOwnPipelineConfig()
      throws IOException {
    GitTestRepo testRepo = new GitTestRepo();

    PipelineConfig shallowPipeline =
        PipelineConfigMother.pipelineConfig(
            "shallowPipeline",
            new StageConfig(
                new CaseInsensitiveString("stage"), new JobConfigs(new JobConfig("job-one"))));
    shallowPipeline.materialConfigs().clear();
    shallowPipeline.addMaterialConfig(
        new GitMaterialConfig(testRepo.projectRepositoryUrl(), null, true));
    configHelper.addPipeline(shallowPipeline);

    PipelineConfig fullPipeline =
        PipelineConfigMother.pipelineConfig(
            "fullPipeline",
            new StageConfig(
                new CaseInsensitiveString("stage"), new JobConfigs(new JobConfig("job-one"))));
    fullPipeline.materialConfigs().clear();
    fullPipeline.addMaterialConfig(
        new GitMaterialConfig(testRepo.projectRepositoryUrl(), null, false));
    configHelper.addPipeline(fullPipeline);

    Pipeline shallowPipelineInstance = createAndLoadModifyOneFilePipeline(shallowPipeline);
    MaterialRevisions shallowRevisions =
        shallowPipelineInstance.getBuildCause().getMaterialRevisions();
    assertThat(
        ((GitMaterial) shallowRevisions.getRevisions().get(0).getMaterial()).isShallowClone(),
        is(true));

    Pipeline fullPipelineInstance = createAndLoadModifyOneFilePipeline(fullPipeline);
    MaterialRevisions fullRevisions = fullPipelineInstance.getBuildCause().getMaterialRevisions();
    assertThat(
        ((GitMaterial) fullRevisions.getRevisions().get(0).getMaterial()).isShallowClone(),
        is(false));
  }
 @Before
 public void setup() throws Exception {
   dbHelper.onSetUp();
   configHelper.onSetUp();
   configHelper.usingCruiseConfigDao(goConfigDao).initializeConfigFile();
   hgTestRepo = new HgTestRepo("hgTestRepo1");
   hgMaterial = MaterialsMother.hgMaterial(hgTestRepo.projectRepositoryUrl());
   hgMaterial.setFilter(new Filter(new IgnoredFiles("helper/**/*.*")));
   workingFolder = TestFileUtil.createTempFolder("workingFolder");
   outputStreamConsumer = inMemoryConsumer();
   mingleConfig =
       configHelper.addPipeline(
           "cruise", STAGE_NAME, this.hgMaterial.config(), "unit", "functional");
 }
 @Test
 public void shouldReturnXmlAndErrorMessageWhenInvalidPostOfBuildAsPartialXml() throws Exception {
   configHelper.addPipeline("pipeline", "stage", "build1", "build2");
   String newXml = "<job name=\"build3\" />";
   String md5 = goConfigDao.md5OfConfigFile();
   ModelAndView mav =
       controller.postBuildAsXmlPartial("pipeline", "stage", 4, newXml, md5, response);
   assertThat(response.getStatus(), is(SC_NOT_FOUND));
   assertThat(response.getContentType(), is(RESPONSE_CHARSET_JSON));
   Map json = (Map) mav.getModel().get("json");
   new JsonTester(json)
       .shouldContain(
           "{ 'result' : 'Build does not exist.'," + "  'originalContent' : '" + newXml + "' }");
 }
 @Test
 public void shouldGetStageAsPartialXml() throws Exception {
   configHelper.addPipeline("pipeline", "dev", "linux", "windows");
   controller.getStageAsXmlPartial("pipeline", 0, null, response);
   assertValidContentAndStatus(
       SC_OK,
       "text/xml",
       "<stage name=\"dev\">\n"
           + "  <jobs>\n"
           + "    <job name=\"linux\" />\n"
           + "    <job name=\"windows\" />\n"
           + "  </jobs>\n"
           + "</stage>");
 }
  @Test
  public void shouldNotThrowErrorWhenMaterialsChange() throws Exception {
    configHelper.addPipeline("cruise", "dev", repository);
    goConfigService.forceNotifyListeners();
    scheduleHelper.autoSchedulePipelinesWithRealMaterials("mingle", "evolve", "cruise");

    configHelper.replaceMaterialForPipeline(
        "cruise", svnMaterialConfig("http://new-material", null));
    goConfigService.forceNotifyListeners();
    try {
      scheduleService.autoSchedulePipelinesFromRequestBuffer();
    } catch (Exception e) {
      fail("#2520 - should not cause an error if materials have changed");
    }
  }
  @Test
  public void shouldConflictWhenGivenMd5IsDifferent() throws Exception {
    configHelper.addPipeline("pipeline", "stage", "build1", "build2");

    controller.getCurrentConfigXml("crapy_md5", response);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    new MagicalGoConfigXmlWriter(
            new ConfigCache(),
            ConfigElementImplementationRegistryMother.withNoPlugins(),
            metricsProbeService)
        .write(goConfigDao.loadForEditing(), os, true);
    assertValidContentAndStatus(
        SC_CONFLICT, "text/plain; charset=utf-8", CONFIG_CHANGED_PLEASE_REFRESH);
    assertThat(
        response.getHeader(XmlAction.X_CRUISE_CONFIG_MD5), is(goConfigDao.md5OfConfigFile()));
  }
  @Test
  public void shouldSaveBuildStateCorrectly() throws Exception {
    PipelineConfig cruisePlan = configHelper.addPipeline("cruise", "dev", repository);
    goConfigService.forceNotifyListeners();

    autoSchedulePipelines("mingle", "evolve", "cruise");

    Stage cruise =
        stageDao.mostRecentWithBuilds(
            CaseInsensitiveString.str(cruisePlan.name()),
            cruisePlan.findBy(new CaseInsensitiveString("dev")));
    System.out.println("cruise = " + cruise);
    JobInstance instance = cruise.getJobInstances().first();
    System.out.println("instance = " + instance);
    assertThat(instance.getState(), is(JobState.Scheduled));
  }
 @Test
 public void shouldReturnXmlAndErrorMessageWhenPostOfStageAsInvalidPartialXml() throws Exception {
   configHelper.addPipeline("pipeline", "stage", "build1", "build2");
   String badXml = "<;askldjfa;dsklfja;sdjas;lkdf";
   String md5 = goConfigDao.md5OfConfigFile();
   ModelAndView mav = controller.postStageAsXmlPartial("pipeline", 0, badXml, md5, response);
   assertThat(response.getStatus(), is(SC_CONFLICT));
   assertThat(response.getContentType(), is(RESPONSE_CHARSET_JSON));
   Map json = (Map) mav.getModel().get("json");
   new JsonTester(json)
       .shouldContain(
           "{ 'result' : 'Error on line 1 of document  : The markup in the document preceding the root element must be well-formed. Nested exception: The markup in the document preceding the root element must be well-formed.',"
               + "  'originalContent' : '"
               + badXml
               + "' }");
 }
  @Test
  public void shouldRemoveBuildCauseIfAnyExceptionIsThrown() throws Exception {
    configHelper.addPipeline("cruise", "dev", repository);
    goConfigService.forceNotifyListeners();
    goConfigService
        .getCurrentConfig()
        .pipelineConfigByName(new CaseInsensitiveString("cruise"))
        .get(0)
        .jobConfigByConfigName(new CaseInsensitiveString("unit"))
        .setRunOnAllAgents(true);
    scheduleHelper.autoSchedulePipelinesWithRealMaterials("cruise");

    goConfigService.forceNotifyListeners();

    scheduleService.autoSchedulePipelinesFromRequestBuffer();
    assertThat(pipelineScheduleQueue.toBeScheduled().size(), is(0));
  }
 @Test
 public void shouldReturnXmlAndErrorMessageWhenPostOfBuildWithDuplicatedNameAsPartialXml()
     throws Exception {
   configHelper.addPipeline("pipeline", "stage", "build1", "build2");
   String newXml = "<job name=\"build2\" />";
   String md5 = goConfigDao.md5OfConfigFile();
   ModelAndView mav =
       controller.postBuildAsXmlPartial("pipeline", "stage", 0, newXml, md5, response);
   assertThat(response.getStatus(), is(SC_CONFLICT));
   assertThat(response.getContentType(), is(RESPONSE_CHARSET_JSON));
   Map<String, Object> json = (Map) mav.getModel().get("json");
   Map<String, Object> expected = new LinkedHashMap<>();
   expected.put(
       "result",
       "Duplicate unique value [build2] declared for identity constraint \"uniqueJob\" of element \"jobs\".");
   expected.put("originalContent", newXml);
   assertThat(json, is(expected));
 }
  @Test
  public void shouldRemoveBuildCauseIfPipelineNotExist() throws Exception {
    configHelper.addPipeline("cruise", "dev", repository);
    goConfigService.forceNotifyListeners();
    scheduleHelper.autoSchedulePipelinesWithRealMaterials("mingle", "evolve", "cruise");

    Assertions.assertWillHappen(
        2,
        PipelineScheduleQueueMatcher.numberOfScheduledPipelinesIsAtLeast(pipelineScheduleQueue),
        Timeout.FIVE_SECONDS);
    int originalSize = pipelineScheduleQueue.toBeScheduled().size();
    assertThat(originalSize, greaterThan(1));
    configHelper.initializeConfigFile();
    goConfigService.forceNotifyListeners();

    scheduleService.autoSchedulePipelinesFromRequestBuffer();
    assertThat(pipelineScheduleQueue.toBeScheduled().size(), is(0));
  }
 private PipelineConfig setupPipelineWithScmMaterial(
     String pipelineName, String stageName, String jobName) {
   PluggableSCMMaterialConfig pluggableSCMMaterialConfig =
       MaterialConfigsMother.pluggableSCMMaterialConfigWithConfigProperties("url", "password");
   SCMPropertyConfiguration configuration = new SCMPropertyConfiguration();
   configuration.add(
       new SCMProperty("url", null).with(PackageConfiguration.PART_OF_IDENTITY, true));
   configuration.add(
       new SCMProperty("password", null).with(PackageConfiguration.PART_OF_IDENTITY, false));
   SCMMetadataStore.getInstance()
       .addMetadataFor(
           pluggableSCMMaterialConfig.getPluginId(), new SCMConfigurations(configuration), null);
   PipelineConfig pipelineConfig =
       PipelineConfigMother.pipelineConfig(
           pipelineName, stageName, new MaterialConfigs(pluggableSCMMaterialConfig), jobName);
   configHelper.addSCMConfig(pluggableSCMMaterialConfig.getSCMConfig());
   configHelper.addPipeline(pipelineConfig);
   return pipelineConfig;
 }
 @Test
 public void shouldReturnErrorMessageWhenPostOfJobContainsDotForExecWorkingDir() throws Exception {
   configHelper.addPipeline("pipeline", "stage", "build1", "build2");
   String badXml =
       "<job name=\"build3\" >"
           + "<tasks>"
           + "<exec command=\"ant\" workingdir=\".\"/>"
           + "</tasks>"
           + "</job>";
   String md5 = goConfigDao.md5OfConfigFile();
   ModelAndView mav =
       controller.postBuildAsXmlPartial("pipeline", "stage", 0, badXml, md5, response);
   assertThat(response.getStatus(), is(SC_CONFLICT));
   assertThat(response.getContentType(), is(RESPONSE_CHARSET_JSON));
   Map json = (Map) mav.getModel().get("json");
   JsonValue jsonValue = JsonUtils.from(json);
   assertThat(unescapeJavaScript(jsonValue.getString("originalContent")), is(badXml));
   assertThat(
       unescapeJavaScript(jsonValue.getString("result")), containsString("File path is invalid"));
 }
 @Test
 public void shouldReturnErrorMessageIfConfigFileChangesBeforePostBuildAsPartialXml()
     throws Exception {
   String md5 = goConfigDao.md5OfConfigFile();
   configHelper.addPipeline("pipeline", "stage", "build1", "build2");
   String newXml = "<job name=\"build3\" />";
   ModelAndView mav =
       controller.postBuildAsXmlPartial("pipeline", "stage", 0, newXml, md5, response);
   assertThat(response.getStatus(), is(SC_CONFLICT));
   assertThat(response.getContentType(), is(RESPONSE_CHARSET_JSON));
   Map json = (Map) mav.getModel().get("json");
   new JsonTester(json)
       .shouldContain(
           "{ 'result' : '"
               + ConfigFileHasChangedException.CONFIG_CHANGED_PLEASE_REFRESH
               + "',"
               + "  'originalContent' : '"
               + newXml
               + "' }");
 }
  @Test
  public void shouldGetPipelineAsPartialXml() throws Exception {
    // get the pipeline XML
    configHelper.addPipeline("pipeline", "dev", "linux", "windows");
    groupName = BasicPipelineConfigs.DEFAULT_GROUP;
    controller.getPipelineAsXmlPartial(0, groupName, null, response);
    String xml = response.getContentAsString();
    assertThat(xml, containsString("pass"));

    // save the pipeline XML
    MockHttpServletResponse postResponse = new MockHttpServletResponse();
    String modifiedXml = xml.replace("pass", "secret");
    controller.postPipelineAsXmlPartial(
        0, groupName, modifiedXml, goConfigDao.md5OfConfigFile(), postResponse);

    // get the pipeline XML again
    MockHttpServletResponse getResponse = new MockHttpServletResponse();
    controller.getPipelineAsXmlPartial(0, groupName, null, getResponse);
    assertThat(getResponse.getContentAsString(), containsString("secret"));
    assertThat(getResponse.getContentAsString(), is(modifiedXml));
  }
  @Before
  public void setup() throws Exception {
    CONFIG_HELPER = new GoConfigFileHelper();
    dbHelper.onSetUp();
    CONFIG_HELPER.usingCruiseConfigDao(goConfigDao).initializeConfigFile();
    CONFIG_HELPER.onSetUp();

    repository = new SvnCommand(null, testRepo.projectRepositoryUrl());
    goConfigService.forceNotifyListeners();
    agentAssignment.clear();
    goCache.clear();

    CONFIG_HELPER.addPipeline(
        "blahPipeline",
        "blahStage",
        MaterialConfigsMother.hgMaterialConfig(
            "file:///home/cruise/projects/cruisen/manual-testing/ant_hg/dummy"),
        "job1",
        "job2");
    CONFIG_HELPER.makeJobRunOnAllAgents("blahPipeline", "blahStage", "job2");
  }
 @Test
 public void shouldNotAssignWorkWhenPipelineScheduledWithStaleMaterials() {
   AgentIdentifier instance = agent(AgentMother.localAgent());
   Pipeline pipeline =
       instanceFactory.createPipelineInstance(
           evolveConfig,
           modifyNoFiles(evolveConfig),
           new DefaultSchedulingContext(DEFAULT_APPROVED_BY),
           md5,
           new TimeProvider());
   dbHelper.savePipelineWithStagesAndMaterials(pipeline);
   evolveConfig.setMaterialConfigs(new MaterialConfigs(new HgMaterialConfig("foo", null)));
   configHelper.removePipeline(CaseInsensitiveString.str(evolveConfig.name()));
   configHelper.addPipeline(evolveConfig);
   buildAssignmentService.onConfigChange(goConfigService.getCurrentConfig());
   JobInstance job = buildOf(pipeline);
   jobInstanceDao.updateStateAndResult(job);
   assertThat(
       buildAssignmentService.assignWorkToAgent(instance),
       is((Work) BuildAssignmentService.NO_WORK));
 }
  @Test
  public void shouldLoadPipelineAlongwithBuildCauseHavingMaterialPasswordsPopulated() {
    PipelineConfig pipelineConfig =
        PipelineConfigMother.pipelineConfig(
            "last",
            new StageConfig(
                new CaseInsensitiveString("stage"), new JobConfigs(new JobConfig("job-one"))));
    pipelineConfig.materialConfigs().clear();
    SvnMaterial onDirOne =
        MaterialsMother.svnMaterial("google.com", "dirOne", "loser", "boozer", false, "**/*.html");
    P4Material onDirTwo =
        MaterialsMother.p4Material(
            "host:987654321", "zoozer", "secret", "through-the-window", true);
    onDirTwo.setFolder("dirTwo");
    pipelineConfig.addMaterialConfig(onDirOne.config());
    pipelineConfig.addMaterialConfig(onDirTwo.config());

    configHelper.addPipeline(pipelineConfig);

    Pipeline building = PipelineMother.building(pipelineConfig);
    Pipeline pipeline = dbHelper.savePipelineWithMaterials(building);

    final long jobId = pipeline.getStages().get(0).getJobInstances().get(0).getId();
    Pipeline loadedPipeline =
        (Pipeline)
            transactionTemplate.execute(
                new TransactionCallback() {
                  public Object doInTransaction(TransactionStatus status) {
                    return loader.pipelineWithPasswordAwareBuildCauseByBuildId(jobId);
                  }
                });

    MaterialRevisions revisions = loadedPipeline.getBuildCause().getMaterialRevisions();
    assertThat(
        ((SvnMaterial) revisions.findRevisionFor(onDirOne).getMaterial()).getPassword(),
        is("boozer"));
    assertThat(
        ((P4Material) revisions.findRevisionFor(onDirTwo).getMaterial()).getPassword(),
        is("secret"));
  }
 private PipelineConfig setupPipelineWithPackageMaterial(
     String pipelineName, String stageName, String jobName) {
   PackageMaterialConfig packageMaterialConfig = new PackageMaterialConfig("p-id");
   Configuration repoConfig =
       new Configuration(
           ConfigurationPropertyMother.create("repo-key1", false, "repo-k1-value"),
           ConfigurationPropertyMother.create("repo-key2", false, "repo-k2-value"));
   PackageRepository repository =
       PackageRepositoryMother.create("repo-id", "repo-name", "pluginid", "version", repoConfig);
   Configuration packageConfig =
       new Configuration(
           ConfigurationPropertyMother.create("package-key1", false, "package-key1-value"),
           ConfigurationPropertyMother.create("package-key2", false, "package-key2-value"));
   PackageDefinition packageDefinition =
       PackageDefinitionMother.create("p-id", "package-name", packageConfig, repository);
   packageMaterialConfig.setPackageDefinition(packageDefinition);
   repository.getPackages().add(packageDefinition);
   PipelineConfig pipelineConfig =
       PipelineConfigMother.pipelineConfig(
           pipelineName, stageName, new MaterialConfigs(packageMaterialConfig), jobName);
   configHelper.addPackageDefinition(packageMaterialConfig);
   configHelper.addPipeline(pipelineConfig);
   PackageConfigurations packageConfigurations = new PackageConfigurations();
   packageConfigurations.add(
       new PackageConfiguration("package-key1").with(PackageConfiguration.PART_OF_IDENTITY, true));
   packageConfigurations.add(
       new PackageConfiguration("package-key2")
           .with(PackageConfiguration.PART_OF_IDENTITY, false));
   PackageMetadataStore.getInstance()
       .addMetadataFor(packageMaterialConfig.getPluginId(), packageConfigurations);
   PackageConfigurations configuration = new PackageConfigurations();
   configuration.add(
       new PackageConfiguration("repo-key1").with(PackageConfiguration.PART_OF_IDENTITY, true));
   configuration.add(
       new PackageConfiguration("repo-key2").with(PackageConfiguration.PART_OF_IDENTITY, false));
   RepositoryMetadataStore.getInstance()
       .addMetadataFor(packageMaterialConfig.getPluginId(), configuration);
   return pipelineConfig;
 }
  @Test // if other materials have expansion concept at some point, add more tests here
  public void shouldSetPasswordForExpandedSvnMaterial() {
    PipelineConfig pipelineConfig =
        PipelineConfigMother.pipelineConfig(
            "last",
            new StageConfig(
                new CaseInsensitiveString("stage"), new JobConfigs(new JobConfig("job-one"))));
    pipelineConfig.materialConfigs().clear();
    SvnMaterialConfig materialConfig = svnRepo.materialConfig();
    materialConfig.setConfigAttributes(
        Collections.singletonMap(SvnMaterialConfig.CHECK_EXTERNALS, String.valueOf(true)));
    materialConfig.setPassword("boozer");
    pipelineConfig.addMaterialConfig(materialConfig);
    configHelper.addPipeline(pipelineConfig);

    Pipeline loadedPipeline = createAndLoadModifyOneFilePipeline(pipelineConfig);

    MaterialRevisions revisions = loadedPipeline.getBuildCause().getMaterialRevisions();
    assertThat(revisions.getRevisions().size(), is(2));
    assertThat(
        ((SvnMaterial) revisions.getRevisions().get(0).getMaterial()).getPassword(), is("boozer"));
    assertThat(
        ((SvnMaterial) revisions.getRevisions().get(1).getMaterial()).getPassword(), is("boozer"));
  }