require 'spec_helper'

describe JenkinsOnFire::Jenkins::JobConfig do

  describe 'JobConfig#job_config' do
    it 'should return the config for a given job if present' do
      stub_request(:get, /.*\/job\/sample_job\/config.xml/).
        to_return(status: 200, body: '<project></project>')

      api.job_config('sample_job').should eq '<project></project>'
    end


    it "should return false if the given job doesn't exists" do
      stub_request(:get, /.*\/job\/invalid_job\/config.xml/).
        to_return(status: 404, body: 'invalid')

      api.job_config('invalid_job').should be_false
    end
  end


  describe 'JobConfig#job_exists?' do
    it 'should return true if job exists' do
      stub_request(:get, /.*\/job\/sample_job\/api\/json/).
        to_return(status: 200, body: '')
      api.job_exists?('sample_job').should be_true
    end

    it "should return false if the job doesn't exists" do
      stub_request(:get, /.*\/job\/invalid_job\/api\/json/).
        to_return(status: 404, body: '')
      api.job_exists?('invalid_job').should be_false
    end
  end

  describe 'JobConfig#job_create' do
    it 'should create a new job on jenkins' do
      config = "<project></project>"
      stub_request(:post, /.*\/createItem\?mode=hudson.model.FreeStyleProject&name=new_job/).
        with(body: config, headers: {'Content-Type'=>'text/xml; charset=utf-8'}).
        to_return(status:  200)
      api.job_create('new_job', config).should be_true
    end
  end


  describe 'JobConfig#job_clone' do
    it 'should create a new job on jenkins' do
      base_project = fixture 'base_project.xml'
      configured_project = fixture 'configured_project.xml'

      stub_request(:get, /.*\/job\/base_project\/config.xml/).
        to_return(status: 200, body: base_project)

      stub_request(:post, /.*\/createItem\?mode=hudson.model.FreeStyleProject&name=new_job/).
        with(body: configured_project, headers: {'Content-Type'=>'text/xml; charset=utf-8'}).
        to_return(status:  200)

      config = { name: 'new_job', git_repository: 'git@bitbucket.org:firefield/changed.git', git_branch: 'changed' }

      api.job_clone(config).should be_true
    end
  end

  describe 'JobConfig#job_run' do
    it 'should send a build request to jenkins' do
      stub_request(:get, /.*\/job\/sample_job\/build\?delay=0sec/).
        to_return(status: 200, body: '')
      api.job_run('sample_job').should be_true
    end
  end

end
