require File.expand_path(File.dirname(__FILE__) + '/spec_helper') require 'yaml' # WebMock.disable_net_connect! describe Junkie::Pyload::Api do include EMHelper # remove the Config module behaviour before(:each) do Junkie::Config.stub!(:get_config).and_return( Junkie::Pyload::Api::DEFAULT_CONFIG.merge( {api_user: 'user', api_password: 'pass'})) end context "standard configuration" do before(:each) do @api = Junkie::Pyload::Api.new() end it "should have the right standard url" do expect(@api.build_url).to eq "http://localhost:8000/api" end end context "#login" do context "valid credentials" do before(:each) do @api = Junkie::Pyload::Api.new() @stub = stub_request(:post, "http://localhost:8000/api/login"). with(:body => "username=user&password=pass"). to_return(:status => 200, :body => "", :headers => {SET_COOKIE: "api.id=123456; valid until it is removed"}) end it "should use the right url for API login" do em { @api.login @stub.should have_been_requested } end it "should extract the Cookie from the login response" do em { @api.login expect(@api.cookie).to eq "api.id=123456" } end end context "invalid credentials" do before(:each) do @api = Junkie::Pyload::Api.new() @api.config[:api_password] = "invalid" @stub = stub_request(:post, "http://localhost:8000/api/login"). with(:body => "username=user&password=invalid"). to_return(:status => 403, :body => "", :headers => {}) end it "should raise an error if login does not work" do em { expect { @api.login }.to raise_error(Junkie::InvalidCredentialsError) } end end end context "#call" do before(:each) do @api = Junkie::Pyload::Api.new() @api.stub(:cookie).and_return("api.id=123456") end it "should call the right url for the method name" do em { stub = stub_request(:get, "http://localhost:8000/api/getQueue") @api.call(:getQueue) stub.should have_been_requested } end it "should pass parameters as JSON to the Request" do em { stub_request(:get, "http://localhost:8000/api/addPackage?links=%255B%2522http%253A%252F%252Ftest.test.de%2522%255D&name=%2522testpkg%2522"). to_return(:status => 200, :body => "76", :headers => {"Content-Type" => "application/json"}) res = @api.call(:addPackage, { name: "testpkg", links: [ "http://test.test.de" ]}) res.should eq 76 } end it "should build ruby datatypes from the JSON" do em { stub_request(:get, "http://localhost:8000/api/statusServer"). to_return(:status => 200, :body => '{ "pause": false, "total": 141 }', :headers => {"Content-Type" => "application/json"}) res = @api.call(:statusServer) hash = { "pause" => false, "total" => 141 } res.should eq hash } end end end