nitroapi 0.0.5 → 0.0.7

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,62 @@
1
+ module NitroApi
2
+ module BatchCalls
3
+
4
+ private
5
+
6
+ # Actually perform the batch call.
7
+ # @return [Hash] The hash containing the results from the nitro server
8
+ def make_run_batch_call
9
+ return false if @batch.nil? or @batch.size == 0
10
+
11
+ # The nitro API returns a differently formatted result if called with
12
+ # only one action. Thus, they need to be handled differently.
13
+ if @batch.size == 1
14
+ handle_batch_single_action
15
+ else
16
+ handle_batch_multiple_actions
17
+ end
18
+ end
19
+
20
+ # This function handles making the call when there is only one call in
21
+ # the batch.
22
+ def handle_batch_single_action
23
+ result = really_make_call(@batch[0][:params], @batch[0][:method])
24
+ @batch = nil
25
+
26
+ # TODO: improve the handling of other methods if only one is called with batch
27
+ if result['method'] == 'user.login' and result['res'] == 'ok'
28
+ @session = result['Login']['sessionKey']
29
+ end
30
+ result
31
+ end
32
+
33
+ # This function handles making the call when there is more than one call in
34
+ # the batch.
35
+ def handle_batch_multiple_actions
36
+ # TODO: improve handling of errors in the batch response
37
+ actions = []
38
+ @batch.each do |action|
39
+ actions << to_query(action[:params])
40
+ end
41
+
42
+ results = really_make_call({'method' => 'batch.run','methodFeed' => JSON.dump(actions)}, :post)
43
+ @batch = nil
44
+ extract_session_key results
45
+ results
46
+ end
47
+
48
+ # Extracts the session key from the results when multiple method calls are
49
+ # made in the batch.
50
+ # @param [Hash] batch_results The hash containing the results from the
51
+ # batch call
52
+ def extract_session_key batch_results
53
+ batch_results['Nitro'].each do |result|
54
+ if result['method'] == 'user.login' and result['res'] == 'ok'
55
+ @session = result['Login']['sessionKey']
56
+ break
57
+ end
58
+ end
59
+ end
60
+
61
+ end
62
+ end
@@ -1,5 +1,10 @@
1
1
  module NitroApi
2
2
  class Challenge
3
3
  attr_accessor :name, :description, :completed, :full_url, :thumb_url
4
+ attr_accessor :rules
5
+
6
+ def initialize()
7
+ @rules = []
8
+ end
4
9
  end
5
10
  end
@@ -0,0 +1,5 @@
1
+ module NitroApi
2
+ class Rule
3
+ attr_accessor :goal, :completed, :type, :action
4
+ end
5
+ end
@@ -0,0 +1,33 @@
1
+ module NitroApi
2
+ module SiteCalls
3
+ def make_points_leaders_call opts
4
+ params = {
5
+ :method => 'site.getPointsLeaders'
6
+ }
7
+
8
+ # Only include the session key when it is present. This is to make batch
9
+ # calls work for this method.
10
+ params[:sessionKey] = @session if @session
11
+
12
+ opts_list = {
13
+ 'criteria' => 'criteria',
14
+ 'point_category' => 'pointCategory',
15
+ 'return_count' => 'returnCount',
16
+ 'start' => 'start',
17
+ 'duration' => 'duration',
18
+ 'user_ids' => 'userIds',
19
+ 'tags' => 'tags',
20
+ 'tags_operator' => 'tagsOperator',
21
+ 'group_name' => 'groupName',
22
+ 'with_rank' => 'withRank',
23
+ 'with_surrounding_users' => 'withSurroundingUsers',
24
+ 'preferences' => 'preferences'
25
+ }
26
+
27
+ opts.each do |key,value|
28
+ params[opts_list[key]] = value if opts_list.has_key?(key)
29
+ end
30
+ make_call(params, :get)
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,155 @@
1
+ module NitroApi
2
+ module UserCalls
3
+
4
+ def make_login_call
5
+ ts = Time.now.utc.to_i.to_s
6
+ params = {
7
+ :sig => sign(ts),
8
+ :ts => ts,
9
+ :apiKey => @api_key,
10
+ :userId => @user,
11
+ :method => 'user.login'
12
+ }
13
+ response = make_call(params)
14
+ if response.is_a?(Hash)
15
+ @session = response["Login"]["sessionKey"]
16
+ end
17
+ response
18
+ end
19
+
20
+ def make_log_action_call actions, opts={}
21
+ value = opts.delete(:value)
22
+ user_id = opts.delete(:other_user)
23
+ session_key = opts.delete(:session_key)
24
+ params = {
25
+ :tags => actions.is_a?(Array) ? actions.join(",") : actions,
26
+ :method => 'user.logAction'
27
+ }
28
+
29
+ # Only include the session key when it is present. This is to make batch
30
+ # calls work for this method.
31
+ if session_key or @session
32
+ params[:sessionKey] = session_key ? session_key : (@session ? @session : nil)
33
+ end
34
+
35
+ params[:value] = value.to_s if value && !value.to_s.empty?
36
+ params[:userId] = user_id if user_id && !user_id.to_s.empty
37
+ make_call(params)
38
+ end
39
+
40
+ def make_challenge_progress_call opts={}
41
+ # TODO: add support for the user.getChallengeProgress call to nitroapi
42
+ if not @batch.nil?
43
+ raise NitroError.new(10000), "user.getChallengeProgress not supported in batch mode by nitroapi"
44
+ end
45
+
46
+ params = {
47
+ :sessionKey => @session,
48
+ :method => 'user.getChallengeProgress'
49
+ }
50
+ challenge = opts[:challenge]
51
+ params['challengeName'] = challenge if challenge and !challenge.to_s.empty?
52
+ params['showOnlyTrophies'] = opts.delete(:trophies_only) || false
53
+ params['folder'] = opts.delete(:folder) if opts.has_key?(:folder)
54
+
55
+ response = make_call(params)
56
+
57
+ if valid_response?(response['challenges'])
58
+ items = ensure_array(response['challenges']['Challenge'])
59
+ items.reduce([]) do |challenges, item|
60
+ challenge = Challenge.new
61
+ challenge.name = item["name"]
62
+ challenge.description = item["description"]
63
+ challenge.full_url = item["fullUrl"]
64
+ challenge.thumb_url = item["thumbUrl"]
65
+ challenge.completed = item["completionCount"].to_i
66
+
67
+ if valid_response?(item["rules"])
68
+ ensure_array(item["rules"]['Rule']).each do |rule_elm|
69
+ rule = Rule.new
70
+ rule.action = rule_elm['actionTag']
71
+ rule.type = rule_elm['type'].to_sym
72
+ rule.completed = rule_elm['type'] == 'true'
73
+ if rule_elm['goal'] && !rule_elm['goal'].empty?
74
+ rule.goal = rule_elm['goal'].to_i
75
+ end
76
+ challenge.rules<< rule
77
+ end
78
+ end
79
+ challenges<< challenge
80
+ end
81
+ end
82
+ end
83
+
84
+ def make_award_challenge_call(challenge)
85
+ params = {
86
+ :sessionKey => @session,
87
+ :userId => @user,
88
+ :method => 'user.awardChallenge',
89
+ :challenge => challenge
90
+ }
91
+ make_call(params)
92
+ end
93
+
94
+ def make_action_history_call actions=[]
95
+ # TODO: add support for the user.getActionHistory call to nitroapi
96
+ if not @batch.nil?
97
+ raise NitroError.new(10000), "user.getActionHistory not supported in batch mode by nitroapi"
98
+ end
99
+
100
+ params = {
101
+ :sessionKey => @session,
102
+ :method => 'user.getActionHistory'
103
+ }
104
+ if actions && !actions.empty?
105
+ params[:tags] = actions.is_a?(Array) ? actions.join(",") : actions
106
+ end
107
+ response = make_call(params)
108
+ if valid_response?(response['ActionHistoryRecord'])
109
+ items = ensure_array(response['ActionHistoryRecord']['ActionHistoryItem'])
110
+ items.reduce([]) do
111
+ |history, item|
112
+ history<< {:tags => item['tags'],
113
+ :ts => Time.at(item['ts'].to_i),
114
+ :value => item['value'].to_i
115
+ }
116
+ end
117
+ else
118
+ []
119
+ end
120
+ end
121
+
122
+ def make_join_group_call group
123
+ params = {
124
+ :sessionKey => @session,
125
+ :method => 'user.joinGroup',
126
+ :groupName => group
127
+ }
128
+ make_call(params)
129
+ end
130
+
131
+ def make_get_points_balance_call opts={}
132
+ params = {
133
+ :method => 'user.getPointsBalance'
134
+ }
135
+
136
+ # Only include the session key when it is present. This is to make batch
137
+ # calls work for this method.
138
+ params[:sessionKey] = @session if @session
139
+
140
+ opts_list = {
141
+ 'criteria' => 'criteria',
142
+ 'point_category' => 'pointCategory',
143
+ 'start' => 'start',
144
+ 'end' => 'end',
145
+ 'user_id' => 'userId',
146
+ 'tags' => 'tags',
147
+ }
148
+
149
+ opts.each do |key,value|
150
+ params[opts_list[key]] = value if opts_list.has_key?(key)
151
+ end
152
+ make_call(params, :get)
153
+ end
154
+ end
155
+ end
@@ -0,0 +1,3 @@
1
+ module NitroApi
2
+ VERSION = "0.0.7"
3
+ end
@@ -1,69 +1,28 @@
1
- # Generated by jeweler
2
- # DO NOT EDIT THIS FILE DIRECTLY
3
- # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
4
1
  # -*- encoding: utf-8 -*-
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'nitro_api/version'
5
5
 
6
- Gem::Specification.new do |s|
7
- s.name = %q{nitroapi}
8
- s.version = "0.0.5"
6
+ Gem::Specification.new do |gem|
7
+ gem.name = "nitroapi"
8
+ gem.version = NitroApi::VERSION
9
+ gem.authors = ["Gilad Buchman", "James H. Linder"]
10
+ gem.email = ["gems@jlinder.com"]
11
+ gem.description = %q{Api client for Bunchball's Nitro. http://www.bunchball.com/nitro/}
12
+ gem.summary = %q{Api client for Bunchball's Nitro}
13
+ gem.homepage = %q{http://github.com/jlinder/nitroapi}
9
14
 
10
- s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
11
- s.authors = ["Gilad Buchman"]
12
- s.date = %q{2011-08-10}
13
- s.description = %q{Api client for Bunchball's Nitro. http://www.bunchball.com/nitro/}
14
- s.extra_rdoc_files = [
15
- "LICENSE.txt",
16
- "README.md"
17
- ]
18
- s.files = [
19
- ".document",
20
- ".rspec",
21
- "Gemfile",
22
- "Gemfile.lock",
23
- "LICENSE.txt",
24
- "README.md",
25
- "Rakefile",
26
- "VERSION",
27
- "examples/award_challenge.rb",
28
- "examples/log_and_check_status.rb",
29
- "keys.json.example",
30
- "lib/nitro_api.rb",
31
- "lib/nitro_api/challenge.rb",
32
- "nitroapi.gemspec",
33
- "spec/nitro_api_spec.rb",
34
- "spec/spec_helper.rb"
35
- ]
36
- s.homepage = %q{http://github.com/Keasinc/nitroapi}
37
- s.licenses = ["MIT"]
38
- s.require_paths = ["lib"]
39
- s.rubygems_version = %q{1.6.2}
40
- s.summary = %q{Api client for Bunchball's Nitro}
15
+ gem.files = `git ls-files`.split($/)
16
+ gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
17
+ gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
18
+ gem.require_paths = ["lib"]
41
19
 
42
- if s.respond_to? :specification_version then
43
- s.specification_version = 3
20
+ # Please keep me alphabetized!
21
+ gem.add_dependency('activesupport')
22
+ gem.add_dependency('json')
44
23
 
45
- if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
46
- s.add_runtime_dependency(%q<activesupport>, [">= 0"])
47
- s.add_runtime_dependency(%q<json>, [">= 0"])
48
- s.add_development_dependency(%q<rspec>, ["~> 2.3.0"])
49
- s.add_development_dependency(%q<bundler>, ["~> 1.0.0"])
50
- s.add_development_dependency(%q<jeweler>, ["~> 1.6.4"])
51
- s.add_development_dependency(%q<rcov>, [">= 0"])
52
- else
53
- s.add_dependency(%q<activesupport>, [">= 0"])
54
- s.add_dependency(%q<json>, [">= 0"])
55
- s.add_dependency(%q<rspec>, ["~> 2.3.0"])
56
- s.add_dependency(%q<bundler>, ["~> 1.0.0"])
57
- s.add_dependency(%q<jeweler>, ["~> 1.6.4"])
58
- s.add_dependency(%q<rcov>, [">= 0"])
59
- end
60
- else
61
- s.add_dependency(%q<activesupport>, [">= 0"])
62
- s.add_dependency(%q<json>, [">= 0"])
63
- s.add_dependency(%q<rspec>, ["~> 2.3.0"])
64
- s.add_dependency(%q<bundler>, ["~> 1.0.0"])
65
- s.add_dependency(%q<jeweler>, ["~> 1.6.4"])
66
- s.add_dependency(%q<rcov>, [">= 0"])
67
- end
24
+ gem.add_development_dependency('bundler', ['~> 1.2.2'])
25
+ gem.add_development_dependency('rspec', ['~> 2.3.0'])
26
+ gem.add_development_dependency('simplecov', ['~> 0.7.1'])
68
27
  end
69
28
 
@@ -6,22 +6,24 @@ describe NitroApi do
6
6
  @api_key = "key"
7
7
  @secret = "secret"
8
8
  @nitro = NitroApi::NitroApi.new @user, @api_key, @secret
9
+ @nitro.protocol = 'http'
9
10
  @success = {"Nitro" => {"res" => "ok"}}.to_json
10
11
  @session = "1"
11
12
  end
12
13
 
13
14
  describe "#sign" do
14
15
  it "takes MD5 like in http://wiki.bunchball.com/w/page/12748060/user_login" do
15
- to_digest = @api_key + @secret + Time.now.utc.to_i.to_s + @user.to_s
16
+ ts = Time.now.utc.to_i.to_s
17
+ to_digest = @api_key + @secret + ts + @user.to_s
16
18
  to_digest += to_digest.length.to_s
17
- @nitro.sign.should == Digest::MD5.hexdigest(to_digest)
19
+ @nitro.sign(ts).should == Digest::MD5.hexdigest(to_digest)
18
20
  end
19
21
  end
20
22
 
21
23
  describe "#login" do
22
24
  it "should set session id for a successful call" do
23
25
  mock_json = {"Nitro" => {"Login" => {"sessionKey" => @session}}}
24
- url = NitroApi::HOST + "?.*method=user.login.*"
26
+ url = @nitro.base_url + "?.*method=user.login.*"
25
27
  stub_http_request(:get, Regexp.new(url)).
26
28
  to_return(:body => mock_json.to_json)
27
29
 
@@ -30,6 +32,34 @@ describe NitroApi do
30
32
  end
31
33
  end
32
34
 
35
+ describe "#base_url" do
36
+ before do
37
+ @user = "user"
38
+ @api_key = "key"
39
+ @secret = "secret"
40
+ @nitro = NitroApi::NitroApi.new @user, @api_key, @secret
41
+ end
42
+
43
+ it "has the correct default URL" do
44
+ @nitro.base_url.should == 'https://sandbox.bunchball.net/nitro/json'
45
+ end
46
+
47
+ it "correctly uses the configured protocol value" do
48
+ @nitro.protocol = 'http'
49
+ @nitro.base_url.should == 'http://sandbox.bunchball.net/nitro/json'
50
+ end
51
+
52
+ it "correctly uses the configured host value" do
53
+ @nitro.host = 'example.com'
54
+ @nitro.base_url.should == 'https://example.com/nitro/json'
55
+ end
56
+
57
+ it "correctly uses the configured accepts value" do
58
+ @nitro.accepts = 'xml'
59
+ @nitro.base_url.should == 'https://sandbox.bunchball.net/nitro/xml'
60
+ end
61
+ end
62
+
33
63
  context "when authenticated" do
34
64
  before do
35
65
  @nitro.session = @session
@@ -42,7 +72,7 @@ describe NitroApi do
42
72
  "sessionKey" => @session,
43
73
  "method" => "user.logAction"
44
74
  }
45
- url = NitroApi::HOST + "?.*method=user.logAction.*"
75
+ url = @nitro.base_url + "?.*method=user.logAction.*"
46
76
  stub_http_request(:get, Regexp.new(url)).
47
77
  with(:query => params).
48
78
  to_return(:body => @success)
@@ -56,38 +86,70 @@ describe NitroApi do
56
86
  "sessionKey" => @session,
57
87
  "method" => "user.logAction"
58
88
  }
59
- url = NitroApi::HOST + "?.*method=user.logAction.*"
89
+ url = @nitro.base_url + "?.*method=user.logAction.*"
60
90
  stub_http_request(:get, Regexp.new(url)).
61
91
  with(:query => params).
62
92
  to_return(:body => @success)
63
93
 
64
94
  @nitro.log_action actions
65
95
  end
96
+
97
+ it "sends one action with specified session key on query string" do
98
+ action_name = "action"
99
+ session = '2'
100
+ params = {"tags" => action_name,
101
+ "sessionKey" => session,
102
+ "method" => "user.logAction"
103
+ }
104
+ opts = {session_key: session}
105
+ url = @nitro.base_url + "?.*method=user.logAction.*"
106
+ stub_http_request(:get, Regexp.new(url)).
107
+ with(:query => params).
108
+ to_return(:body => @success)
109
+
110
+ @nitro.log_action action_name, opts
111
+ end
66
112
  end
67
113
 
68
114
  describe "#challenge_progress" do
69
- it "returns the challenge part of the response" do
115
+ before do
70
116
  params = {
71
117
  "showOnlyTrophies" => "false",
72
118
  "sessionKey" => @session,
73
119
  "method" => "user.getChallengeProgress"
74
120
  }
75
- url = NitroApi::HOST + "?.*method=user.getChallengeProgress.*"
121
+ url = @nitro.base_url + "?.*method=user.getChallengeProgress.*"
122
+ mock_rules = {"goal" => "1", "type" => "none", "completed" => "false",
123
+ "actionTag" => "action"}
124
+
76
125
  mock_data = [{"completionCount"=>"1",
77
126
  "description" => "some description",
78
- "name" => "Watch 10 Videos"}]
127
+ "name" => "Watch 10 Videos",
128
+ "rules" => {"Rule" => mock_rules}}]
79
129
 
80
130
  mock_json = {"Nitro" => {"challenges" => {"Challenge" => mock_data}}}
81
131
  stub_http_request(:get, Regexp.new(url)).
82
132
  with(:query => params).
83
133
  to_return(:body => mock_json.to_json)
84
134
 
85
- progress = @nitro.challenge_progress
86
- progress.should_not be_empty
87
- challenge = progress[0]
88
- challenge.should_not be_nil
89
- challenge.description.should == "some description"
90
- challenge.completed.should == 1
135
+ response = @nitro.challenge_progress
136
+ @challenge = response[0]
137
+ end
138
+
139
+ it "returns the challenge part of the response" do
140
+ @challenge.should_not be_nil
141
+ @challenge.description.should == "some description"
142
+ @challenge.completed.should == 1
143
+ end
144
+
145
+ it "has rules in the challenge" do
146
+ @challenge.rules.should_not be_empty
147
+ @challenge.rules.size.should == 1
148
+ rule = @challenge.rules.first
149
+ rule.type.should == :none
150
+ rule.completed.should be_false
151
+ rule.action.should == "action"
152
+ rule.goal.should == 1
91
153
  end
92
154
  end
93
155
 
@@ -99,7 +161,7 @@ describe NitroApi do
99
161
  "challenge" => "TestChallenge",
100
162
  "method" => "user.awardChallenge"
101
163
  }
102
- url = NitroApi::HOST + "?.*method=user.awardChallenge.*"
164
+ url = @nitro.base_url + "?.*method=user.awardChallenge.*"
103
165
  stub_http_request(:get, Regexp.new(url)).
104
166
  with(:query => params).
105
167
  to_return(:body => @success)
@@ -126,7 +188,7 @@ describe NitroApi do
126
188
  "sessionKey" => @session,
127
189
  "method" => "user.getActionHistory"
128
190
  }
129
- url = NitroApi::HOST + "?.*method=user.getActionHistory.*"
191
+ url = @nitro.base_url + "?.*method=user.getActionHistory.*"
130
192
  stub_http_request(:get, Regexp.new(url)).
131
193
  with(:query => params).
132
194
  to_return(:body => @mock_json)
@@ -144,7 +206,7 @@ describe NitroApi do
144
206
  "method" => "user.getActionHistory",
145
207
  "tags" => "action1"
146
208
  }
147
- url = NitroApi::HOST + "?.*method=user.getActionHistory.*"
209
+ url = @nitro.base_url + "?.*method=user.getActionHistory.*"
148
210
  stub_http_request(:get, Regexp.new(url)).
149
211
  with(:query => params).
150
212
  to_return(:body => @mock_json)
@@ -159,7 +221,7 @@ describe NitroApi do
159
221
  "sessionKey" => @session,
160
222
  "method" => "user.joinGroup"
161
223
  }
162
- url = NitroApi::HOST + "?.*method=user.joinGroup.*"
224
+ url = @nitro.base_url + "?.*method=user.joinGroup.*"
163
225
  stub_http_request(:get, Regexp.new(url)).
164
226
  with(:query => params).
165
227
  to_return(:body => @success)
@@ -167,5 +229,246 @@ describe NitroApi do
167
229
  @nitro.join_group "group"
168
230
  end
169
231
  end
232
+
233
+ describe "#get_points_balance options_hash" do
234
+ it "gets the default points" do
235
+ params = {"sessionKey" => @session,
236
+ "method" => "user.getPointsBalance"
237
+ }
238
+ url = @nitro.base_url + "?.*method=user.getPointsBalance.*"
239
+ stub_http_request(:get, Regexp.new(url)).
240
+ with(:query => params).
241
+ to_return(:body => @success)
242
+
243
+ @nitro.get_points_balance
244
+ end
245
+
246
+ it "passes through all the expected parameters" do
247
+ options = {
248
+ 'point_category' => 'other_points',
249
+ 'criteria' => 'BALANCE',
250
+ 'start' => '1354636962',
251
+ 'end' => '1354637015',
252
+ 'tags' => 'beans,rice',
253
+ 'user_id' => 'another_user',
254
+ }
255
+ url = @nitro.base_url + '?criteria=BALANCE&end=1354637015&method=user.getPointsBalance&pointCategory=other_points&sessionKey=1&start=1354636962&tags=beans,rice&userId=another_user'
256
+ stub_http_request(:get, url).
257
+ to_return(:body => @success)
258
+
259
+ @nitro.get_points_balance options
260
+ end
261
+
262
+ it "passes through only the expected parameters" do
263
+ options = {
264
+ 'point_category' => 'other_points',
265
+ 'criteria' => 'BALANCE',
266
+ 'start' => '1354636962',
267
+ 'end' => '1354637015',
268
+ 'tags' => 'beans,rice',
269
+ 'user_id' => 'another_user',
270
+ 'non_param' => 'some_unknown_param'
271
+ }
272
+ url = @nitro.base_url + '?criteria=BALANCE&end=1354637015&method=user.getPointsBalance&pointCategory=other_points&sessionKey=1&start=1354636962&tags=beans,rice&userId=another_user'
273
+ stub_http_request(:get, url).
274
+ to_return(:body => @success)
275
+
276
+ @nitro.get_points_balance options
277
+ end
278
+ end
279
+
280
+ describe "#get_points_leaders options_hash" do
281
+ it "gets points leaders" do
282
+ options = {
283
+ 'return_count' => 20,
284
+ 'duration' => 'ALLTIME',
285
+ 'point_category' => 'points',
286
+ 'criteria' => 'CREDITS'
287
+ }
288
+
289
+ results = { 'Nitro' => {
290
+ "res"=>"ok",
291
+ "method"=>"site.getPointsLeaders",
292
+ "leaders"=> {
293
+ "Leader"=>[ {
294
+ "UserPreferences"=>true,
295
+ "userId"=>"user_id1",
296
+ "points"=>"860"
297
+ }, {
298
+ "UserPreferences"=>true,
299
+ "userId"=>"user_id2",
300
+ "points"=>"620"
301
+ } ]
302
+ }
303
+ }}
304
+
305
+ # TODO: Figure out why when passing these params into the http request stub
306
+ # the mock doesn't work (it errors out).
307
+ #params = {
308
+ # 'method' => 'site.getPointsLeaders',
309
+ # 'sessionKey' => @session,
310
+ # 'returnCount' => 20,
311
+ # 'duration' => 'ALLTIME',
312
+ # 'pointCategory' => 'points',
313
+ # 'criteria' => 'CREDITS'
314
+ #}
315
+
316
+ url = @nitro.base_url + "?.*method=site.getPointsLeaders.*"
317
+ stub_http_request(:any, Regexp.new(url)).
318
+ #with(:query => params).
319
+ to_return(status: 200, body: results.to_json)
320
+
321
+ s = @nitro.get_points_leaders options
322
+ s['res'].should == results['Nitro']['res']
323
+ s['method'].should == results['Nitro']['method']
324
+ s['leaders']['Leader'][0]['userId'].should == results['Nitro']['leaders']['Leader'][0]['userId']
325
+ s['leaders']['Leader'][0]['points'].should == results['Nitro']['leaders']['Leader'][0]['points']
326
+ s['leaders']['Leader'][1]['userId'].should == results['Nitro']['leaders']['Leader'][1]['userId']
327
+ s['leaders']['Leader'][1]['points'].should == results['Nitro']['leaders']['Leader'][1]['points']
328
+ end
329
+ end
330
+ end
331
+
332
+
333
+ context "batch jobs" do
334
+ describe "#start_batch!" do
335
+ it "starts a batch successfully" do
336
+ @nitro.start_batch!
337
+ end
338
+
339
+ it "errors on second call to start_batch!" do
340
+ @nitro.start_batch!
341
+ expect {@nitro.start_batch!}.to raise_error(NitroApi::NitroError)
342
+ end
343
+ end
344
+
345
+ describe "#cancel_batch" do
346
+ it "cancels a batch successfully" do
347
+ @nitro.start_batch!
348
+ @nitro.cancel_batch
349
+ end
350
+ end
351
+
352
+ describe "#run_batch" do
353
+ describe "#login" do
354
+ it "should set session id for a successful batch call" do
355
+ mock_json = {'Nitro' => {'Login' => {'sessionKey' => @session}, 'method' => 'user.login', 'res' => 'ok'}}
356
+ url = @nitro.base_url #+ "?.*method=batch.run.*"
357
+ stub_http_request(:get, Regexp.new(url)).
358
+ to_return(:body => mock_json.to_json)
359
+
360
+ @nitro.start_batch!
361
+ @nitro.login
362
+ @nitro.run_batch
363
+
364
+ @nitro.session.should == @session
365
+ end
366
+ end
367
+
368
+ it "should call two methods successfully" do
369
+ action_name = "action"
370
+ mock_json = { 'Nitro' =>
371
+ { 'res' => 'ok',
372
+ 'method' => 'batch.run',
373
+ 'Nitro' => [
374
+ {'Login' => {'sessionKey' => @session}, 'method' => 'user.login', 'res' => 'ok'},
375
+ {'res' => 'ok', 'method' => 'user.logAction'}
376
+ ]
377
+ }
378
+ }
379
+ url = @nitro.base_url #+ "?.*method=batch.run.*"
380
+ stub_http_request(:post, Regexp.new(url)).
381
+ to_return(:body => mock_json.to_json)
382
+
383
+ @nitro.start_batch!
384
+ @nitro.login
385
+ @nitro.log_action action_name
386
+ s = @nitro.run_batch
387
+
388
+ @nitro.session.should == @session
389
+ s['res'].should == mock_json['Nitro']['res']
390
+ s['method'].should == mock_json['Nitro']['method']
391
+ s['Nitro'][1]['res'].should == mock_json['Nitro']['Nitro'][1]['res']
392
+ s['Nitro'][1]['method'].should == mock_json['Nitro']['Nitro'][1]['method']
393
+ end
394
+
395
+ it "should call the same method twice successfully" do
396
+ action_name1 = "action1"
397
+ action_name2 = "action2"
398
+ mock_json = { 'Nitro' =>
399
+ { 'res' => 'ok',
400
+ 'method' => 'batch.run',
401
+ 'Nitro' => [
402
+ {'res' => 'ok', 'method' => 'user.logAction'},
403
+ {'res' => 'ok', 'method' => 'user.logAction'}
404
+ ]
405
+ }
406
+ }
407
+ url = @nitro.base_url #+ "?.*method=batch.run.*"
408
+ stub_http_request(:post, Regexp.new(url)).
409
+ to_return(:body => mock_json.to_json)
410
+
411
+ @nitro.session = @session
412
+ @nitro.start_batch!
413
+ @nitro.log_action action_name1
414
+ @nitro.log_action action_name2
415
+ s = @nitro.run_batch
416
+
417
+ s['res'].should == mock_json['Nitro']['res']
418
+ s['method'].should == mock_json['Nitro']['method']
419
+ s['Nitro'][1]['res'].should == mock_json['Nitro']['Nitro'][1]['res']
420
+ s['Nitro'][1]['method'].should == mock_json['Nitro']['Nitro'][1]['method']
421
+ end
422
+
423
+ it "should call the same method twice but using different session keys successfully" do
424
+ action_name1 = "action1"
425
+ action_name2 = "action2"
426
+ session_key1 = '111'
427
+ session_key2 = '222'
428
+
429
+ mock_json = { 'Nitro' =>
430
+ { 'res' => 'ok',
431
+ 'method' => 'batch.run',
432
+ 'Nitro' => [
433
+ {'res' => 'ok', 'method' => 'user.logAction'},
434
+ {'res' => 'ok', 'method' => 'user.logAction'}
435
+ ]
436
+ }
437
+ }
438
+ expected_post_body = "method=batch.run&methodFeed=%5B%22tags%3Daction1%26method%3Duser.logAction%26sessionKey%3D111%22%2C%22tags%3Daction2%26method%3Duser.logAction%26sessionKey%3D222%22%5D"
439
+
440
+ url = @nitro.base_url #+ "?.*method=batch.run.*"
441
+ stub_http_request(:post, Regexp.new(url)).
442
+ with(body: expected_post_body).
443
+ to_return(body: mock_json.to_json)
444
+
445
+ @nitro.session = @session
446
+ @nitro.start_batch!
447
+ @nitro.log_action(action_name1, {session_key: session_key1})
448
+ @nitro.log_action(action_name2, {session_key: session_key2})
449
+ s = @nitro.run_batch
450
+
451
+ s['res'].should == mock_json['Nitro']['res']
452
+ s['method'].should == mock_json['Nitro']['method']
453
+ s['Nitro'][1]['res'].should == mock_json['Nitro']['Nitro'][1]['res']
454
+ s['Nitro'][1]['method'].should == mock_json['Nitro']['Nitro'][1]['method']
455
+ end
456
+
457
+ describe "#challenge_progress" do
458
+ it "should not allow the call in batch mode" do
459
+ @nitro.start_batch
460
+ expect {@nitro.challenge_progress }.to raise_error(NitroApi::NitroError)
461
+ end
462
+ end
463
+
464
+ describe "#action_history" do
465
+ it "should not allow the call in batch mode" do
466
+ @nitro.start_batch
467
+ expect {@nitro.action_history 'action1'}.to raise_error(NitroApi::NitroError)
468
+ end
469
+ end
470
+
471
+ end
170
472
  end
171
473
  end
474
+