@Test
  public void postGroupAsXmlPartial_shouldEnforcePipelineGroupAdminPermissionsForPipelineTemplates()
      throws Exception {
    String md5 = setUpPipelineGroupsWithAdminPermissions();

    ConfigElementImplementationRegistry registry =
        ConfigElementImplementationRegistryMother.withNoPlugins();
    XmlUtils.validate(
        new FileInputStream(configHelper.getConfigFile()),
        GoConfigSchema.getCurrentSchema(),
        new XsdErrorTranslator(),
        new SAXBuilder(),
        registry.xsds());
    controller.postGroupAsXmlPartial(
        TemplatesConfig.PIPELINE_TEMPLATES_FAKE_GROUP_NAME, NEW_TEMPLATES, md5, response);

    assertThat(response.getStatus(), is(SC_UNAUTHORIZED));
    XmlUtils.validate(
        new FileInputStream(configHelper.getConfigFile()),
        GoConfigSchema.getCurrentSchema(),
        new XsdErrorTranslator(),
        new SAXBuilder(),
        registry.xsds());

    setCurrentUser("admin");
    controller.postGroupAsXmlPartial(
        TemplatesConfig.PIPELINE_TEMPLATES_FAKE_GROUP_NAME, NEW_TEMPLATES, md5, response);
    assertThat(response.getStatus(), is(SC_OK));
  }
 @Before
 public void setup() throws Exception {
   configHelper = new GoConfigFileHelper();
   configHelper.usingCruiseConfigDao(goConfigDao).initializeConfigFile();
   configHelper.onSetUp();
   goConfigService.forceNotifyListeners();
 }
  @Test
  public void canPauseShouldBeFalseForUnauthorizedAccess() throws Exception {
    configHelper.addSecurityWithAdminConfig();
    configHelper.setOperatePermissionForGroup("defaultGroup", "jez");

    JsonMap jsonMap = requestPipelineHistoryPage();
    assertThat(getItemInJson(jsonMap, "canPause"), is("false"));
  }
Esempio n. 4
0
 public static String loadAndMigrate(String originalContent) {
   GoConfigFileHelper helper = new GoConfigFileHelper(originalContent);
   try {
     return FileUtils.readFileToString(helper.getConfigFile());
   } catch (IOException e) {
     throw bomb(e);
   }
 }
  @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();
  }
  @Before
  public void setUp() throws Exception {
    preCondition = new PipelineWithTwoStages(materialRepository, transactionTemplate);
    configHelper.usingCruiseConfigDao(goConfigFileDao);
    configHelper.onSetUp();

    dbHelper.onSetUp();
    preCondition.usingConfigHelper(configHelper).usingDbHelper(dbHelper).onSetUp();
  }
  @Test
  public void canPauseShouldBeTrueForAuthorizedAccess() throws Exception {
    configHelper.addSecurityWithAdminConfig();
    configHelper.setOperatePermissionForGroup(
        "defaultGroup", CaseInsensitiveString.str(Username.ANONYMOUS.getUsername()));

    JsonMap jsonMap = requestPipelineHistoryPage();
    assertThat(getItemInJson(jsonMap, "canPause"), is("true"));
  }
 @Before
 public void setup() throws Exception {
   dataSource.reloadEveryTime();
   configHelper.usingCruiseConfigDao(goConfigDao);
   configHelper.onSetUp();
   response = new MockHttpServletResponse();
   configHelper.addSecurityWithPasswordFile();
   configHelper.addAdmins("admin");
   setCurrentUser("admin");
 }
  @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 {
    fixture = new PipelineWithMultipleStages(3, materialRepository, transactionTemplate);
    configHelper.usingCruiseConfigDao(goConfigFileDao);
    configHelper.onSetUp();

    dbHelper.onSetUp();
    fixture.usingConfigHelper(configHelper).usingDbHelper(dbHelper).onSetUp();
    goConfigService.forceNotifyListeners();
    request = new MockHttpServletRequest();
    response = new MockHttpServletResponse();
  }
Esempio n. 11
0
  @Test
  public void shouldScheduleJobForAllAgentsWhenToBeRunOnAllAgents() throws Exception {
    configHelper.addAgent("localhost", "uuid1");
    configHelper.addAgent("localhost", "uuid2");
    configHelper.addAgent("localhost", "uuid3");
    configHelper.addAgentToEnvironment("dev", "uuid1");
    configHelper.setRunOnAllAgents(
        CaseInsensitiveString.str(evolveConfig.name()), STAGE_NAME, "unit", true);

    Material stubMaterial = new TestingMaterial();
    evolveConfig.setMaterialConfigs(new MaterialConfigs(stubMaterial.config()));
    MaterialRevisions revisions = new MaterialRevisions();
    revisions.addRevision(
        stubMaterial,
        ((TestingMaterial) stubMaterial)
            .modificationsSince(null, null, subprocessExecutionContext));
    BuildCause buildCause = BuildCause.createWithModifications(revisions, "");
    dbHelper.saveMaterials(buildCause.getMaterialRevisions());

    Pipeline pipeline =
        instanceFactory.createPipelineInstance(
            evolveConfig,
            buildCause,
            new DefaultSchedulingContext(
                DEFAULT_APPROVED_BY,
                environmentConfigService.agentsForPipeline(evolveConfig.name())),
            md5,
            new TimeProvider());
    pipelineService.save(pipeline);

    Stage instance =
        scheduleService.scheduleStage(
            pipeline,
            STAGE_NAME,
            "anyone",
            new ScheduleService.NewStageInstanceCreator(goConfigService),
            new ScheduleService.ExceptioningErrorHandler());
    JobInstances scheduledJobs = instance.getJobInstances();
    assertThat(
        scheduledJobs.toArray(),
        hasItemInArray(
            hasProperty(
                "name", is(RunOnAllAgents.CounterBasedJobNameGenerator.appendMarker("unit", 1)))));
    assertThat(scheduledJobs.toArray(), hasItemInArray(hasProperty("agentUuid", is("uuid2"))));
    assertThat(
        scheduledJobs.toArray(),
        hasItemInArray(
            hasProperty(
                "name", is(RunOnAllAgents.CounterBasedJobNameGenerator.appendMarker("unit", 2)))));
    assertThat(scheduledJobs.toArray(), hasItemInArray(hasProperty("agentUuid", is("uuid3"))));
    assertThat(scheduledJobs.size(), is(2));
  }
  @Test
  public void shouldPostGroupWithTemplateAsPartialXml() throws Exception {
    configHelper.addTemplate("template-1", "dev");
    configHelper.addPipelineWithGroup("group", "pipeline", "dev", "linux", "windows");
    configHelper.addPipelineWithTemplate("group", "pipeline-with-template", "template-1");

    String newXml = NEW_GROUP;
    String md5 = goConfigDao.md5OfConfigFile();
    ModelAndView mav = controller.postGroupAsXmlPartial("group", newXml, md5, response);
    assertResponseMessage(mav, "Group changed successfully.");
    assertThat(response.getStatus(), is(SC_OK));
    assertThat(response.getContentType(), is(RESPONSE_CHARSET_JSON));
  }
  private String setUpPipelineGroupsWithAdminPermissions() throws IOException {
    setCurrentUser("ram");
    assertThat(CaseInsensitiveString.str(UserHelper.getUserName().getUsername()), is("ram"));

    configHelper.addPipelineWithGroup("studios", "go", "stage", "build1", "build2");
    configHelper.setAdminPermissionForGroup("studios", "barrow");

    configHelper.addPipelineWithGroup("consulting", "bcg", "stage", "build1", "build2");
    configHelper.setAdminPermissionForGroup("consulting", "ram");
    configHelper.addTemplate("newTemplate", "stage");

    return goConfigDao.md5OfConfigFile();
  }
  @Test
  public void should_NOT_markAsChangedWhenMaterialIsReIntroducedWithSameRevisionsToPipeline()
      throws Exception {
    SvnMaterial svn1 = SvnMaterial.createSvnMaterialWithMock(repository);
    svn1.setFolder("another_repo");
    mingleConfig = configHelper.replaceMaterialForPipeline(MINGLE_PIPELINE_NAME, svn1.config());
    runAndPassWith(svn1, "foo.c", svnRepository);

    SvnTestRepo svn2Repository = new SvnTestRepo("testSvnRepo2");
    Subversion repository2 = new SvnCommand(null, svn2Repository.projectRepositoryUrl());
    SvnMaterial svn2 = SvnMaterial.createSvnMaterialWithMock(repository2);
    svn2.setFolder("boulder");

    checkinFile(svn2, "bar.c", svn2Repository);

    mingleConfig = configHelper.addMaterialToPipeline(MINGLE_PIPELINE_NAME, svn2.config());

    scheduleHelper.autoSchedulePipelinesWithRealMaterials(MINGLE_PIPELINE_NAME);

    assertThat(pipelineScheduleQueue.toBeScheduled().keySet(), hasItem(MINGLE_PIPELINE_NAME));
    BuildCause mingleBuildCause = pipelineScheduleQueue.toBeScheduled().get(MINGLE_PIPELINE_NAME);
    verifyChanged(svn2, mingleBuildCause, true);
    verifyChanged(
        svn1,
        mingleBuildCause,
        false); // this should not have changed, as foo.c was already built in the previous instance

    runAndPass(mingleBuildCause.getMaterialRevisions());

    mingleConfig = configHelper.replaceMaterialForPipeline(MINGLE_PIPELINE_NAME, svn1.config());
    scheduleHelper.autoSchedulePipelinesWithRealMaterials(MINGLE_PIPELINE_NAME);

    assertThat(pipelineScheduleQueue.toBeScheduled().keySet(), hasItem(MINGLE_PIPELINE_NAME));
    mingleBuildCause = pipelineScheduleQueue.toBeScheduled().get(MINGLE_PIPELINE_NAME);
    verifyChanged(
        svn1,
        mingleBuildCause,
        false); // this should not have changed, as foo.c was already built in the previous instance
    runAndPassWith(svn1, "baz.c", svnRepository);

    mingleConfig = configHelper.addMaterialToPipeline(MINGLE_PIPELINE_NAME, svn2.config());

    checkinFile(svn1, "quux.c", svnRepository);

    scheduleHelper.autoSchedulePipelinesWithRealMaterials(MINGLE_PIPELINE_NAME);

    assertThat(pipelineScheduleQueue.toBeScheduled().keySet(), hasItem(MINGLE_PIPELINE_NAME));
    mingleBuildCause = pipelineScheduleQueue.toBeScheduled().get(MINGLE_PIPELINE_NAME);
    verifyChanged(svn2, mingleBuildCause, false);
    verifyChanged(svn1, mingleBuildCause, true);
  }
  @Test
  public void shouldGetGroupWithTemplatesAsXml() throws Exception {
    configHelper.addTemplate("template-1", "dev");
    configHelper.addPipelineWithGroup("group", "pipeline", "dev", "linux");
    PipelineConfig pipelineWithTemplate =
        configHelper.addPipelineWithTemplate("group", "pipeline-with-template", "template-1");
    assertThat(
        pipelineWithTemplate.size(),
        is(0)); // should not expect mutation of pipeline config passed in
    assertThat(
        configHelper
            .currentConfig()
            .pipelineConfigByName(new CaseInsensitiveString("pipeline-with-template"))
            .size(),
        is(1));

    CruiseConfig config = goConfigService.currentCruiseConfig();
    PipelineConfig pipelineConfig =
        config.pipelineConfigByName(new CaseInsensitiveString("pipeline-with-template"));
    assertThat("Should not modify the original template", pipelineConfig.size(), is(1));

    controller.getGroupAsXmlPartial("group", null, response);
    String content =
        "<pipelines group=\"group\">\n"
            + "  <pipeline name=\"pipeline\">\n"
            + "    <materials>\n"
            + "      <svn url=\"svn:///user:pass@tmp/foo\" />\n"
            + "    </materials>\n"
            + "    <stage name=\"dev\">\n"
            + "      <jobs>\n"
            + "        <job name=\"linux\" />\n"
            + "      </jobs>\n"
            + "    </stage>\n"
            + "  </pipeline>\n"
            + "  <pipeline name=\"pipeline-with-template\" template=\"template-1\">\n"
            + "    <materials>\n"
            + "      <svn url=\"svn:///user:pass@tmp/foo\" />\n"
            + "    </materials>\n"
            + "  </pipeline>\n"
            + "</pipelines>";
    assertValidContentAndStatus(SC_OK, "text/xml", content);

    MockHttpServletResponse postResponse = new MockHttpServletResponse();
    controller.postGroupAsXmlPartial("group", content, null, postResponse);

    config = goConfigService.currentCruiseConfig();
    pipelineConfig =
        config.pipelineConfigByName(new CaseInsensitiveString("pipeline-with-template"));
    assertThat("Should not modify the original template", pipelineConfig.size(), is(1));
  }
 @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 shouldModifyExistingPipelineTemplateWhenPostedAsPartial() throws Exception {
   configHelper.addPipelineWithGroup(
       "some-group", "some-pipeline", "some-dev", "some-linux", "some-windows");
   configHelper.addAgent("some-home", "UUID");
   String newXml = NEW_TEMPLATES;
   String md5 = goConfigDao.md5OfConfigFile();
   ModelAndView mav =
       controller.postGroupAsXmlPartial("Pipeline Templates", newXml, md5, response);
   assertResponseMessage(mav, "Template changed successfully.");
   assertThat(response.getStatus(), is(SC_OK));
   assertThat(response.getContentType(), is(RESPONSE_CHARSET_JSON));
   assertThat(configHelper.currentConfig().getTemplates().size(), is(1));
 }
  @Test
  public void shouldCancelBuildBelongingToNonExistentPipelineWhenCreatingWork() throws Exception {
    fixture.createPipelineWithFirstStageScheduled();
    Pipeline pipeline = pipelineDao.mostRecentPipeline(fixture.pipelineName);

    ScheduledPipelineLoader scheduledPipelineLoader = mock(ScheduledPipelineLoader.class);
    when(scheduledPipelineLoader.pipelineWithPasswordAwareBuildCauseByBuildId(
            pipeline.getFirstStage().getJobInstances().first().getId()))
        .thenThrow(new PipelineNotFoundException("thrown by mockPipelineService"));

    GoConfigService mockGoConfigService = mock(GoConfigService.class);
    CruiseConfig config = configHelper.currentConfig();
    configHelper.removePipeline(fixture.pipelineName, config);
    when(mockGoConfigService.getCurrentConfig()).thenReturn(config);

    buildAssignmentService =
        new BuildAssignmentService(
            mockGoConfigService,
            jobInstanceService,
            scheduleService,
            agentService,
            environmentConfigService,
            timeProvider,
            transactionTemplate,
            scheduledPipelineLoader,
            pipelineService,
            builderFactory,
            agentRemoteHandler);
    buildAssignmentService.onTimer();

    AgentConfig agentConfig = AgentMother.localAgent();
    agentConfig.addResource(new Resource("some-other-resource"));

    try {
      buildAssignmentService.assignWorkToAgent(agent(agentConfig));
      fail("should have thrown PipelineNotFoundException");
    } catch (PipelineNotFoundException e) {
      // ok
    }

    pipeline = pipelineDao.mostRecentPipeline(fixture.pipelineName);

    JobInstance job = pipeline.getFirstStage().getJobInstances().first();
    assertThat(job.getState(), is(JobState.Completed));
    assertThat(job.getResult(), is(JobResult.Cancelled));
    Stage stage = stageDao.findStageWithIdentifier(job.getIdentifier().getStageIdentifier());
    assertThat(stage.getState(), is(StageState.Cancelled));
    assertThat(stage.getResult(), is(StageResult.Cancelled));
  }
Esempio n. 19
0
  @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");
    }
  }
 @Before
 public void setup() throws Exception {
   configHelper = new GoConfigFileHelper();
   dbHelper.onSetUp();
   configHelper.usingCruiseConfigDao(goConfigDao).initializeConfigFile();
   configHelper.onSetUp();
   goConfigService.forceNotifyListeners();
   File dumpDir = tempFolder.newFolder("perf-pipelineapi-test");
   FileUtil.deleteDirectoryNoisily(dumpDir);
   dumpDir.mkdirs();
   result = new HttpLocalizedOperationResult();
   user = new Username(new CaseInsensitiveString("admin"));
   consoleAppenderForPerformanceTest = "ConsoleAppenderForPerformanceTest";
   rollingFileAppenderForPerformanceTest = "RollingFileAppenderForPerformanceTest";
 }
 @After
 public void teardown() throws Exception {
   dbHelper.onTearDown();
   fixture.onTearDown();
   configHelper.onTearDown();
   resetSecurityContext();
 }
 @After
 public void teardown() throws Exception {
   if (originalSecurityContext != null) {
     SecurityContextHolder.setContext(originalSecurityContext);
   }
   configHelper.onTearDown();
 }
 @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));
 }
 @Test
 public void shouldNotSchedulePipelineWithManualFirstStageForAutomaticBuild() throws Exception {
   configHelper.configureStageAsManualApproval(MINGLE_PIPELINE_NAME, STAGE_NAME);
   svnRepository.checkInOneFile("a.java");
   scheduleHelper.autoSchedulePipelinesWithRealMaterials(MINGLE_PIPELINE_NAME);
   assertThat(pipelineScheduleQueue.toBeScheduled().keySet(), not(hasItem(MINGLE_PIPELINE_NAME)));
 }
 @After
 public void tearDown() throws Exception {
   configHelper.onTearDown();
   dbHelper.onTearDown();
   TestRepo.internalTearDown();
   cleanupTempFolders();
 }
Esempio n. 26
0
  @Test
  public void shouldLockPipelineWhenSchedulingIt() throws Exception {
    scheduleAndCompleteInitialPipelines();

    configHelper.lockPipeline("mingle");

    Material stubMaterial = new TestingMaterial();
    mingleConfig.setMaterialConfigs(new MaterialConfigs(stubMaterial.config()));

    assertThat(pipelineLockService.isLocked("mingle"), is(false));

    MaterialRevisions revisions = new MaterialRevisions();
    revisions.addRevision(
        stubMaterial,
        ((TestingMaterial) stubMaterial)
            .modificationsSince(null, null, subprocessExecutionContext));
    BuildCause buildCause = BuildCause.createWithModifications(revisions, "");
    dbHelper.saveMaterials(buildCause.getMaterialRevisions());
    Pipeline pipeline =
        instanceFactory.createPipelineInstance(
            mingleConfig,
            buildCause,
            new DefaultSchedulingContext(DEFAULT_APPROVED_BY),
            md5,
            new TimeProvider());
    pipelineService.save(pipeline);

    assertThat(pipelineLockService.isLocked("mingle"), is(true));
  }
  @Test
  public void shouldCancelBuildsForDeletedJobsWhenPipelineConfigChanges() throws Exception {
    fixture = new PipelineWithTwoStages(materialRepository, transactionTemplate).usingTwoJobs();
    fixture.usingConfigHelper(configHelper).usingDbHelper(dbHelper).onSetUp();
    fixture.createPipelineWithFirstStageScheduled();

    buildAssignmentService.onTimer();
    configHelper.removeJob(fixture.pipelineName, fixture.devStage, fixture.JOB_FOR_DEV_STAGE);

    buildAssignmentService.onPipelineConfigChange(
        goConfigService
            .getCurrentConfig()
            .getPipelineConfigByName(new CaseInsensitiveString(fixture.pipelineName)),
        "g1");

    Pipeline pipeline = pipelineDao.mostRecentPipeline(fixture.pipelineName);
    JobInstance deletedJob =
        pipeline.getFirstStage().getJobInstances().getByName(fixture.JOB_FOR_DEV_STAGE);
    assertThat(deletedJob.getState(), is(JobState.Completed));
    assertThat(deletedJob.getResult(), is(JobResult.Cancelled));
    JobInstance retainedJob =
        pipeline.getFirstStage().getJobInstances().getByName(fixture.DEV_STAGE_SECOND_JOB);
    assertThat(retainedJob.getState(), is(JobState.Scheduled));
    assertThat(retainedJob.getResult(), is(JobResult.Unknown));
  }
  @Test
  public void
      shouldCancelAScheduledJobInCaseThePipelineIsRemovedFromTheConfig_SpecificallyAPipelineRenameToADifferentCaseAndStageNameToADifferentName()
          throws Exception {
    Material hgMaterial = new HgMaterial("url", "folder");
    String[] hgRevs = new String[] {"h1"};
    u.checkinInOrder(hgMaterial, hgRevs);

    ScheduleTestUtil.AddedPipeline p1 =
        u.saveConfigWith("PIPELINE_WHICH_WILL_EVENTUALLY_CHANGE_CASE", u.m(hgMaterial));

    u.scheduleWith(p1, hgRevs);
    ScheduleTestUtil.AddedPipeline renamedPipeline =
        u.renamePipelineAndFirstStage(
            p1,
            "pipeline_which_will_eventually_change_case",
            "NEW_RANDOM_STAGE_NAME" + UUID.randomUUID());

    Pipeline p1_2 = u.scheduleWith(renamedPipeline, hgRevs);
    CruiseConfig cruiseConfig = configHelper.load();
    buildAssignmentService.onTimer(); // To Reload Job Plans
    buildAssignmentService.onConfigChange(cruiseConfig);

    Stages allStages = stageDao.findAllStagesFor(p1_2.getName(), p1_2.getCounter());
    assertThat(
        allStages.byName(CaseInsensitiveString.str(p1.config.first().name())).getState(),
        is(StageState.Cancelled));
  }
 @After
 public void teardown() throws Exception {
   dbHelper.onTearDown();
   preCondition.onTearDown();
   pipelineScheduleQueue.clear();
   configHelper.onTearDown();
 }
  @Test
  public void shouldOnlyAssignWorkToIdleAgentsRegisteredInAgentRemoteHandler() {
    AgentConfig agentConfig = AgentMother.remoteAgent();
    configHelper.addAgent(agentConfig);
    fixture.createPipelineWithFirstStageScheduled();
    AgentRuntimeInfo info =
        AgentRuntimeInfo.fromServer(agentConfig, true, "location", 1000000l, "OS");
    info.setCookie("cookie");

    AgentStatus[] statuses =
        new AgentStatus[] {
          AgentStatus.Building, AgentStatus.Pending,
          AgentStatus.Disabled, AgentStatus.Disabled,
          AgentStatus.LostContact, AgentStatus.Missing
        };
    for (AgentStatus status : statuses) {
      info.setStatus(status);
      agent = new AgentStub();

      agentRemoteHandler.process(agent, new Message(Action.ping, info));
      buildAssignmentService.onTimer();

      assertThat(
          "Should not assign work when agent status is " + status, agent.messages.size(), is(0));
    }
  }