Class: SauceOverage::Account

Inherits:
Object
  • Object
show all
Defined in:
lib/sauce_overage/account.rb

Constant Summary collapse

MUTEX =
Mutex.new

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Account

Returns a new instance of Account.



5
6
7
8
9
10
11
12
13
# File 'lib/sauce_overage/account.rb', line 5

def initialize(opts = {})
  @user = opts.fetch(:user, sauce_user)
  fail 'Must provide user' unless user
  @user = user.strip

  @key = opts.fetch(:key, sauce_key)
  fail 'Must provide key' unless key
  @key = key.strip
end

Instance Attribute Details

#keyObject (readonly)

Returns the value of attribute key.



3
4
5
# File 'lib/sauce_overage/account.rb', line 3

def key
  @key
end

#userObject (readonly)

Returns the value of attribute user.



3
4
5
# File 'lib/sauce_overage/account.rb', line 3

def user
  @user
end

Instance Method Details

#check(minutes_limit = nil) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/sauce_overage/account.rb', line 53

def check minutes_limit = nil
  unless minutes_limit
    env           = ENV['SAUCE_OVERAGE_LIMIT']
    minutes_limit = env.to_i if env && !env.strip.empty?
  end

  fail 'minutes limit must be set' unless minutes_limit
  fail 'minutes limit must be an int' unless minutes_limit.is_a?(Integer)

  remaining_minutes = minutes

  if remaining_minutes < minutes_limit
    fail "#{minutes_limit} minute limit breached (#{remaining_minutes} remaining)"
  end

  nil
end

#get_userObject



45
46
47
# File 'lib/sauce_overage/account.rb', line 45

def get_user
  wait(2 * 60) { hurley_client.get("users/#{user}").body }
end

#hurley_clientObject



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/sauce_overage/account.rb', line 17

def hurley_client
  MUTEX.synchronize do
    return @hurley_client if @hurley_client
    client                              = @hurley_client = Hurley::Client.new 'https://saucelabs.com/rest/v1/'
    client.header[:content_type]        = 'application/json'
    client.request_options.timeout      = 2 * 60
    client.request_options.open_timeout = 2 * 60
    client.url.user                     = user
    client.url.password                 = key

    # Ensure body JSON string is parsed into a hash
    # Detect errors and fail so wait_true will retry the request
    client.after_call do |response|
      response.body = MultiJson.load(response.body) rescue {}

      client_server_error = %i(client_error server_error).include? response.status_type
      body_error          = response.body['error']

      if client_server_error || body_error
        response_error = body_error || ''
        fail(::Errno::ECONNREFUSED, response_error)
      end
    end

    @hurley_client
  end
end

#minutesObject



49
50
51
# File 'lib/sauce_overage/account.rb', line 49

def minutes
  get_user['minutes'].to_i
end