require 'spec_helper'

describe IcecastUserAuthentication do

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

  it "save error" do
    auth.save.should be_false
    auth.errors[:mount_add].should == ["can't be blank"]
    auth.errors[:mount_remove].should == ["can't be blank"]
    auth.errors[:listener_add].should == ["can't be blank"]
    auth.errors[:listener_remove].should == ["can't be blank"]
    #auth.errors[:unused_username].should == ["is too short (minimum is 5 characters)"]
    #auth.errors[:unused_pass].should == ["is too short (minimum is 5 characters)"]
  end

  it "save" do
    auth.mount_add = Faker::Lorem.characters(10)
    auth.mount_remove = Faker::Lorem.characters(10)
    auth.listener_add = Faker::Lorem.characters(10)
    auth.listener_remove = Faker::Lorem.characters(10)
    auth.unused_username = Faker::Lorem.characters(10)
    auth.unused_pass = Faker::Lorem.characters(10)

    auth.save!
    
    auth.dumpXml(builder)

    output.rewind

    xml = Nokogiri::XML(output)
    xml.css('authentication')[0]["type"].should == auth.authentication_type
    xml.css('authentication option[name="mount_add"]')[0]["value"].should == auth.mount_add
    xml.css('authentication option[name="mount_remove"]')[0]["value"].should == auth.mount_remove
    xml.css('authentication option[name="listener_add"]')[0]["value"].should == auth.listener_add
    xml.css('authentication option[name="listener_remove"]')[0]["value"].should == auth.listener_remove
    xml.css('authentication option[name="username"]')[0]["value"].should == auth.unused_username
    xml.css('authentication option[name="password"]')[0]["value"].should == auth.unused_pass
    xml.css('authentication option[name="auth_header"]')[0]["value"].should == auth.auth_header
    xml.css('authentication option[name="timelimit_header"]')[0]["value"].should == auth.timelimit_header
  end

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

    before(:each) do
      server.mounts << FactoryGirl.create(:icecast_mount_with_auth)
      server.save!
      server.config_updated
      server.reload
    end

    it "success via server" do
      server.mounts.first.authentication.save!
      server.reload
      server.config_changed.should == 1
    end
  end
end
