require 'spec_helper'

describe IcecastLimit do

  let(:limit) { IcecastLimit.new }
  let(:output) { StringIO.new }
  let(:builder) { ::Builder::XmlMarkup.new(:target => output, :indent => 1) }


  it "save defaults" do
    limit.save.should be_true
    limit.dumpXml(builder)

    output.rewind

    xml = Nokogiri::XML(output)
    xml.css('limits clients').text.should == "1000"
    xml.css('limits clients').length.should == 1
    xml.css('limits sources').text.should == "50"
    xml.css('limits sources').length.should == 1
    xml.css('limits queue-size').text.should == "102400"
    xml.css('limits queue-size').length.should == 1
    xml.css('limits client-timeout').text.should == "30"
    xml.css('limits client-timeout').length.should == 1
    xml.css('limits header-timeout').text.should == "15"
    xml.css('limits header-timeout').length.should == 1
    xml.css('limits source-timeout').text.should == "10"
    xml.css('limits source-timeout').length.should == 1
    xml.css('limits burst-on-connect').text.should == "1"
    xml.css('limits burst-on-connect').length.should == 1
    xml.css('limits burst-size').text.should == "65536"
    xml.css('limits burst-size').length.should == 1
  end

  it "save specified" do
    limit.clients = 10000
    limit.sources = 2000
    limit.queue_size = 1000
    limit.client_timeout = 10
    limit.header_timeout = 20
    limit.source_timeout = 30
    limit.burst_size = 1000

    limit.save.should be_true
    limit.dumpXml(builder)

    output.rewind

    xml = Nokogiri::XML(output)
    xml.css('limits clients').text.should == limit.clients.to_s
    xml.css('limits sources').text.should == limit.sources.to_s
    xml.css('limits queue-size').text.should == limit.queue_size.to_s
    xml.css('limits client-timeout').text.should == limit.client_timeout.to_s
    xml.css('limits header-timeout').text.should == limit.header_timeout.to_s
    xml.css('limits source-timeout').text.should == limit.source_timeout.to_s
    xml.css('limits burst-on-connect').text.should == "1"
    xml.css('limits burst-size').text.should == limit.burst_size.to_s
  end

  describe "poke configs" do
    let(:server) { a = FactoryGirl.create(:icecast_server_with_overrides); a.config_updated; IcecastServer.find(a.id) }

    it "success via template" do
      server.template.limit.save!
      server.reload
      server.config_changed.should == 1
    end

    it "delete via template" do
      server.template.limit.destroy
      server.reload
      server.config_changed.should == 1
    end

    it "success via server" do
      server.limit.save!
      server.reload
      server.config_changed.should == 1
    end

    it "delete via server" do
      server.limit.destroy
      server.reload
      server.config_changed.should == 1
    end
  end
end
