private Pipeline manualSchedule(String pipelineName)
     throws Exception, StageAlreadyBuildingException {
   scheduleHelper.manuallySchedulePipelineWithRealMaterials(
       pipelineName, new Username(new CaseInsensitiveString("some user name")));
   scheduleService.autoSchedulePipelinesFromRequestBuffer();
   return pipelineService.mostRecentFullPipelineByName(pipelineName);
 }
  @Test
  public void shouldConsumeAllBuildCausesInServerHealth() throws Exception {
    pipelineScheduleQueue.schedule(
        "mingle", BuildCause.createManualForced(modifyOneFile(mingleConfig), Username.ANONYMOUS));
    pipelineScheduleQueue.schedule(
        "evolve", BuildCause.createManualForced(modifyOneFile(evolveConfig), Username.ANONYMOUS));

    scheduleService.autoSchedulePipelinesFromRequestBuffer();
    assertThat(pipelineScheduleQueue.toBeScheduled().size(), is(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 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 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 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));
  }
  @Test
  public void shouldLockPipelineWhenSchedulingStage() throws Exception {
    scheduleAndCompleteInitialPipelines();
    Pipeline pipeline = pipelineDao.mostRecentPipeline("mingle");

    configHelper.lockPipeline("mingle");

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

    scheduleService.scheduleStage(
        pipeline,
        STAGE_NAME,
        "anonymous",
        new ScheduleService.NewStageInstanceCreator(goConfigService),
        new ScheduleService.ExceptioningErrorHandler());

    assertThat(pipelineLockService.isLocked("mingle"), is(true));
  }
  @Test
  public void shouldReScheduleToCorrectAgent() throws Exception {
    JobConfig plan =
        evolveConfig
            .findBy(new CaseInsensitiveString(STAGE_NAME))
            .jobConfigByInstanceName("unit", true);
    plan.addResource("some-resource");

    scheduleHelper.schedule(evolveConfig, modifySomeFiles(evolveConfig), DEFAULT_APPROVED_BY);

    buildAssignmentService.onTimer();

    AgentConfig agentConfig = AgentMother.localAgent();
    agentConfig.addResource(new Resource("some-resource"));
    Work work = buildAssignmentService.assignWorkToAgent(agent(agentConfig));
    assertThat(work, is(not((Work) BuildAssignmentService.NO_WORK)));

    Pipeline pipeline =
        pipelineDao.mostRecentPipeline(CaseInsensitiveString.str(evolveConfig.name()));
    JobInstance job = pipeline.findStage(STAGE_NAME).findJob("unit");

    JobInstance runningJob = jobInstanceDao.buildByIdWithTransitions(job.getId());

    scheduleService.rescheduleJob(runningJob);

    pipeline = pipelineDao.mostRecentPipeline(CaseInsensitiveString.str(evolveConfig.name()));
    JobInstance rescheduledJob = pipeline.findStage(STAGE_NAME).findJob("unit");

    assertThat(rescheduledJob.getId(), not(runningJob.getId()));

    buildAssignmentService.onTimer();
    Work noResourcesWork =
        buildAssignmentService.assignWorkToAgent(
            agent(AgentMother.localAgentWithResources("WITHOUT_RESOURCES")));
    assertThat(noResourcesWork, is((Work) BuildAssignmentService.NO_WORK));

    buildAssignmentService.onTimer();
    Work correctAgentWork = buildAssignmentService.assignWorkToAgent(agent(agentConfig));
    assertThat(correctAgentWork, is(not((Work) BuildAssignmentService.NO_WORK)));
  }
  @Test
  public void shouldPassEnvironmentLevelEnvironmentVariablesToJobsForNewlyScheduledStage()
      throws Exception {
    scheduleAndCompleteInitialPipelines();
    Pipeline pipeline = pipelineDao.mostRecentPipeline("go");

    Stage stage =
        scheduleService.scheduleStage(
            pipeline,
            "ft",
            "anonymous",
            new ScheduleService.NewStageInstanceCreator(goConfigService),
            new ScheduleService.ExceptioningErrorHandler());
    EnvironmentVariablesConfig jobVariables =
        stage.getJobInstances().first().getPlan().getVariables();
    assertThat(
        jobVariables.size(), is(3)); // pipeline, stage, job, env is applied while creating work
    assertThat(
        jobVariables, hasItem(new EnvironmentVariableConfig("PIPELINE_LVL", "pipeline value")));
    assertThat(jobVariables, hasItem(new EnvironmentVariableConfig("STAGE_LVL", "stage value")));
    assertThat(jobVariables, hasItem(new EnvironmentVariableConfig("JOB_LVL", "job value")));
  }
 private void autoSchedulePipelines(String... pipelineNames) throws Exception {
   scheduleHelper.autoSchedulePipelinesWithRealMaterials(pipelineNames);
   scheduleService.autoSchedulePipelinesFromRequestBuffer();
 }