koala 1.0.0.beta → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. data/.autotest +12 -0
  2. data/.gitignore +5 -0
  3. data/.travis.yml +8 -0
  4. data/CHANGELOG +42 -4
  5. data/Gemfile +7 -0
  6. data/LICENSE +1 -1
  7. data/Manifest +5 -2
  8. data/Rakefile +13 -14
  9. data/autotest/discover.rb +1 -0
  10. data/koala.gemspec +35 -20
  11. data/lib/koala/batch_operation.rb +74 -0
  12. data/lib/koala/graph_api.rb +196 -143
  13. data/lib/koala/graph_batch_api.rb +87 -0
  14. data/lib/koala/graph_collection.rb +54 -0
  15. data/lib/koala/http_services/net_http_service.rb +92 -0
  16. data/lib/koala/http_services/typhoeus_service.rb +37 -0
  17. data/lib/koala/http_services.rb +15 -124
  18. data/lib/koala/oauth.rb +181 -0
  19. data/lib/koala/realtime_updates.rb +5 -14
  20. data/lib/koala/rest_api.rb +13 -8
  21. data/lib/koala/test_users.rb +21 -8
  22. data/lib/koala/uploadable_io.rb +175 -0
  23. data/lib/koala.rb +48 -240
  24. data/readme.md +60 -28
  25. data/spec/cases/api_base_spec.rb +101 -0
  26. data/spec/cases/graph_and_rest_api_spec.rb +31 -0
  27. data/spec/cases/graph_api_batch_spec.rb +609 -0
  28. data/spec/cases/graph_api_spec.rb +25 -0
  29. data/spec/cases/http_services/http_service_spec.rb +129 -0
  30. data/spec/cases/http_services/net_http_service_spec.rb +532 -0
  31. data/spec/cases/http_services/typhoeus_service_spec.rb +152 -0
  32. data/spec/cases/koala_spec.rb +55 -0
  33. data/spec/cases/oauth_spec.rb +409 -0
  34. data/spec/cases/realtime_updates_spec.rb +184 -0
  35. data/spec/cases/rest_api_spec.rb +25 -0
  36. data/spec/{koala/test_users/test_users_tests.rb → cases/test_users_spec.rb} +47 -34
  37. data/spec/cases/uploadable_io_spec.rb +193 -0
  38. data/spec/fixtures/cat.m4v +0 -0
  39. data/spec/{facebook_data.yml → fixtures/facebook_data.yml} +12 -14
  40. data/spec/{mock_facebook_responses.yml → fixtures/mock_facebook_responses.yml} +408 -306
  41. data/spec/spec_helper.rb +19 -0
  42. data/spec/support/graph_api_shared_examples.rb +495 -0
  43. data/spec/support/json_testing_fix.rb +18 -0
  44. data/spec/{koala → support}/live_testing_data_helper.rb +39 -42
  45. data/spec/support/mock_http_service.rb +96 -0
  46. data/spec/support/rest_api_shared_examples.rb +285 -0
  47. data/spec/support/setup_mocks_or_live.rb +51 -0
  48. data/spec/support/uploadable_io_shared_examples.rb +76 -0
  49. metadata +110 -64
  50. data/init.rb +0 -2
  51. data/spec/koala/api_base_tests.rb +0 -102
  52. data/spec/koala/graph_and_rest_api/graph_and_rest_api_no_token_tests.rb +0 -14
  53. data/spec/koala/graph_and_rest_api/graph_and_rest_api_with_token_tests.rb +0 -16
  54. data/spec/koala/graph_api/graph_api_no_access_token_tests.rb +0 -63
  55. data/spec/koala/graph_api/graph_api_tests.rb +0 -86
  56. data/spec/koala/graph_api/graph_api_with_access_token_tests.rb +0 -154
  57. data/spec/koala/graph_api/graph_collection_tests.rb +0 -104
  58. data/spec/koala/net_http_service_tests.rb +0 -430
  59. data/spec/koala/oauth/oauth_tests.rb +0 -409
  60. data/spec/koala/realtime_updates/realtime_updates_tests.rb +0 -187
  61. data/spec/koala/rest_api/rest_api_no_access_token_tests.rb +0 -25
  62. data/spec/koala/rest_api/rest_api_tests.rb +0 -118
  63. data/spec/koala/rest_api/rest_api_with_access_token_tests.rb +0 -38
  64. data/spec/koala/typhoeus_service_tests.rb +0 -156
  65. data/spec/koala_spec.rb +0 -18
  66. data/spec/koala_spec_helper.rb +0 -70
  67. data/spec/koala_spec_without_mocks.rb +0 -19
  68. data/spec/mock_http_service.rb +0 -96
  69. /data/spec/{koala/assets → fixtures}/beach.jpg +0 -0
@@ -0,0 +1,96 @@
1
+ require 'erb'
2
+ require 'yaml'
3
+
4
+ module Koala
5
+ module MockHTTPService
6
+ include Koala::HTTPService
7
+
8
+ # fix our specs to use ok_json, so we always get the same results from to_json
9
+ MultiJson.engine = :ok_json
10
+
11
+ # Mocks all HTTP requests for with koala_spec_with_mocks.rb
12
+ # Mocked values to be included in TEST_DATA used in specs
13
+ ACCESS_TOKEN = '*'
14
+ APP_ACCESS_TOKEN = "**"
15
+ OAUTH_CODE = 'OAUTHCODE'
16
+
17
+ # Loads testing data
18
+ TEST_DATA = YAML.load_file(File.join(File.dirname(__FILE__), '..', 'fixtures', 'facebook_data.yml'))
19
+ TEST_DATA.merge!('oauth_token' => Koala::MockHTTPService::ACCESS_TOKEN)
20
+ TEST_DATA['oauth_test_data'].merge!('code' => Koala::MockHTTPService::OAUTH_CODE)
21
+
22
+ # Useful in mock_facebook_responses.yml
23
+ OAUTH_DATA = TEST_DATA['oauth_test_data']
24
+ OAUTH_DATA.merge!({
25
+ 'app_access_token' => APP_ACCESS_TOKEN,
26
+ 'session_key' => "session_key",
27
+ 'multiple_session_keys' => ["session_key", "session_key_2"]
28
+ })
29
+ APP_ID = OAUTH_DATA['app_id']
30
+ SECRET = OAUTH_DATA['secret']
31
+ SUBSCRIPTION_DATA = TEST_DATA["subscription_test_data"]
32
+
33
+ # Loads the mock response data via ERB to substitue values for TEST_DATA (see oauth/access_token)
34
+ mock_response_file_path = File.join(File.dirname(__FILE__), '..', 'fixtures', 'mock_facebook_responses.yml')
35
+ RESPONSES = YAML.load(ERB.new(IO.read(mock_response_file_path)).result(binding))
36
+
37
+ def self.make_request(path, args, verb, options = {})
38
+ path = 'root' if path == '' || path == '/'
39
+ verb ||= 'get'
40
+ server = options[:rest_api] ? 'rest_api' : 'graph_api'
41
+ token = args.delete('access_token')
42
+ with_token = (token == ACCESS_TOKEN || token == APP_ACCESS_TOKEN) ? 'with_token' : 'no_token'
43
+
44
+ # Assume format is always JSON
45
+ args.delete('format')
46
+
47
+ # Create a hash key for the arguments
48
+ args = create_params_key(args)
49
+
50
+ begin
51
+ response = RESPONSES[server][path][args][verb][with_token]
52
+
53
+ # Raises an error of with_token/no_token key is missing
54
+ raise NoMethodError unless response
55
+
56
+ # create response class object
57
+ response_object = if response.is_a? String
58
+ Koala::Response.new(200, response, {})
59
+ else
60
+ Koala::Response.new(response["code"] || 200, response["body"] || "", response["headers"] || {})
61
+ end
62
+
63
+ rescue NoMethodError
64
+ # Raises an error message with the place in the data YML
65
+ # to place a mock as well as a URL to request from
66
+ # Facebook's servers for the actual data
67
+ # (Don't forget to replace ACCESS_TOKEN with a real access token)
68
+ data_trace = [server, path, args, verb, with_token] * ': '
69
+
70
+ args = args == 'no_args' ? '' : "#{args}&"
71
+ args += 'format=json'
72
+ args += "&access_token=#{ACCESS_TOKEN}" if with_token
73
+
74
+ raise "Missing a mock response for #{data_trace}\nAPI PATH: #{[path, args].join('?')}"
75
+ end
76
+
77
+ response_object
78
+ end
79
+
80
+ def self.mock?
81
+ true
82
+ end
83
+
84
+ protected
85
+ def self.create_params_key(params_hash)
86
+ if params_hash.empty?
87
+ 'no_args'
88
+ else
89
+ params_hash.sort{ |a,b| a[0].to_s <=> b[0].to_s}.map do |arr|
90
+ arr[1] = '[FILE]' if arr[1].kind_of?(Koala::UploadableIO)
91
+ arr.join('=')
92
+ end.join('&')
93
+ end
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,285 @@
1
+ shared_examples_for "Koala RestAPI" do
2
+ # REST_CALL
3
+ describe "when making a rest request" do
4
+ it "should use the proper path" do
5
+ method = stub('methodName')
6
+ @api.should_receive(:api).with(
7
+ "method/#{method}",
8
+ anything,
9
+ anything,
10
+ anything
11
+ )
12
+
13
+ @api.rest_call(method)
14
+ end
15
+
16
+ it "should always use the rest api" do
17
+ @api.should_receive(:api).with(
18
+ anything,
19
+ anything,
20
+ anything,
21
+ hash_including(:rest_api => true)
22
+ )
23
+
24
+ @api.rest_call('anything')
25
+ end
26
+
27
+ it "should set the read_only option to true if the method is listed in the read-only list" do
28
+ method = Koala::Facebook::RestAPI::READ_ONLY_METHODS.first
29
+
30
+ @api.should_receive(:api).with(
31
+ anything,
32
+ anything,
33
+ anything,
34
+ hash_including(:read_only => true)
35
+ )
36
+
37
+ @api.rest_call(method)
38
+ end
39
+
40
+ it "should set the read_only option to false if the method is not inthe read-only list" do
41
+ method = "I'm not a read-only method"
42
+
43
+ @api.should_receive(:api).with(
44
+ anything,
45
+ anything,
46
+ anything,
47
+ hash_including(:read_only => false)
48
+ )
49
+
50
+ @api.rest_call(method)
51
+ end
52
+
53
+
54
+ it "should take an optional hash of arguments" do
55
+ args = {:arg1 => 'arg1'}
56
+
57
+ @api.should_receive(:api).with(
58
+ anything,
59
+ hash_including(args),
60
+ anything,
61
+ anything
62
+ )
63
+
64
+ @api.rest_call('anything', args)
65
+ end
66
+
67
+ it "should always ask for JSON" do
68
+ @api.should_receive(:api).with(
69
+ anything,
70
+ hash_including('format' => 'json'),
71
+ anything,
72
+ anything
73
+ )
74
+
75
+ @api.rest_call('anything')
76
+ end
77
+
78
+ it "should pass any options provided to the API" do
79
+ options = {:a => 2}
80
+
81
+ @api.should_receive(:api).with(
82
+ anything,
83
+ hash_including('format' => 'json'),
84
+ anything,
85
+ hash_including(options)
86
+ )
87
+
88
+ @api.rest_call('anything', {}, options)
89
+ end
90
+
91
+ it "uses get by default" do
92
+ @api.should_receive(:api).with(
93
+ anything,
94
+ anything,
95
+ "get",
96
+ anything
97
+ )
98
+
99
+ @api.rest_call('anything')
100
+ end
101
+
102
+ it "allows you to specify other http methods as the last argument" do
103
+ method = 'bar'
104
+ @api.should_receive(:api).with(
105
+ anything,
106
+ anything,
107
+ method,
108
+ anything
109
+ )
110
+
111
+ @api.rest_call('anything', {}, {}, method)
112
+ end
113
+
114
+ it "should throw an APIError if the result hash has an error key" do
115
+ Koala.stub(:make_request).and_return(Koala::Response.new(500, {"error_code" => "An error occurred!"}, {}))
116
+ lambda { @api.rest_call("koppel", {}) }.should raise_exception(Koala::Facebook::APIError)
117
+ end
118
+
119
+ describe "when making a FQL request" do
120
+ it "should call fql.query method" do
121
+ @api.should_receive(:rest_call).with(
122
+ "fql.query", anything, anything
123
+ ).and_return(Koala::Response.new(200, "2", {}))
124
+
125
+ @api.fql_query stub('query string')
126
+ end
127
+
128
+ it "should pass a query argument" do
129
+ query = stub('query string')
130
+
131
+ @api.should_receive(:rest_call).with(
132
+ anything, hash_including(:query => query), anything
133
+ )
134
+
135
+ @api.fql_query(query)
136
+ end
137
+
138
+ it "should pass on any other arguments provided" do
139
+ args = {:a => 2}
140
+ @api.should_receive(:rest_call).with(anything, hash_including(args), anything)
141
+ @api.fql_query("a query", args)
142
+ end
143
+
144
+ it "should pass on any http options provided" do
145
+ opts = {:a => 2}
146
+ @api.should_receive(:rest_call).with(anything, anything, hash_including(opts))
147
+ @api.fql_query("a query", {}, opts)
148
+ end
149
+ end
150
+
151
+ describe "when making a FQL-multiquery request" do
152
+ it "should call fql.multiquery method" do
153
+ @api.should_receive(:rest_call).with(
154
+ "fql.multiquery", anything, anything
155
+ ).and_return({})
156
+
157
+ @api.fql_multiquery 'query string'
158
+ end
159
+
160
+ it "should pass a queries argument" do
161
+ queries = stub('query string')
162
+ queries_json = "some JSON"
163
+ MultiJson.stub(:encode).with(queries).and_return(queries_json)
164
+
165
+ @api.should_receive(:rest_call).with(
166
+ anything,
167
+ hash_including(:queries => queries_json),
168
+ anything
169
+ )
170
+
171
+ @api.fql_multiquery(queries)
172
+ end
173
+
174
+ it "simplifies the response format" do
175
+ raw_results = [
176
+ {"name" => "query1", "fql_result_set" => [1, 2, 3]},
177
+ {"name" => "query2", "fql_result_set" => [:a, :b, :c]}
178
+ ]
179
+ expected_results = {
180
+ "query1" => [1, 2, 3],
181
+ "query2" => [:a, :b, :c]
182
+ }
183
+
184
+ @api.stub(:rest_call).and_return(raw_results)
185
+ results = @api.fql_multiquery({:query => true})
186
+ results.should == expected_results
187
+ end
188
+
189
+ it "should pass on any other arguments provided" do
190
+ args = {:a => 2}
191
+ @api.should_receive(:rest_call).with(anything, hash_including(args), anything)
192
+ @api.fql_multiquery("a query", args)
193
+ end
194
+
195
+ it "should pass on any http options provided" do
196
+ opts = {:a => 2}
197
+ @api.should_receive(:rest_call).with(anything, anything, hash_including(opts))
198
+ @api.fql_multiquery("a query", {}, opts)
199
+ end
200
+ end
201
+ end
202
+ end
203
+
204
+ shared_examples_for "Koala RestAPI with an access token" do
205
+ # FQL
206
+ it "should be able to access public information via FQL" do
207
+ result = @api.fql_query('select first_name from user where uid = 216743')
208
+ result.size.should == 1
209
+ result.first['first_name'].should == 'Chris'
210
+ end
211
+
212
+ it "should be able to access public information via FQL.multiquery" do
213
+ result = @api.fql_multiquery(
214
+ :query1 => 'select first_name from user where uid = 216743',
215
+ :query2 => 'select first_name from user where uid = 2905623'
216
+ )
217
+ result.size.should == 2
218
+ result["query1"].first['first_name'].should == 'Chris'
219
+ result["query2"].first['first_name'].should == 'Alex'
220
+ end
221
+
222
+ it "should be able to access protected information via FQL" do
223
+ # Tests agains the permissions fql table
224
+
225
+ # get the current user's ID
226
+ # we're sneakily using the Graph API, which should be okay since it has its own tests
227
+ g = Koala::Facebook::GraphAPI.new(@token)
228
+ id = g.get_object("me", :fields => "id")["id"]
229
+
230
+ # now send a query about your permissions
231
+ result = @api.fql_query("select read_stream from permissions where uid = #{id}")
232
+
233
+ result.size.should == 1
234
+ # we've verified that you have read_stream permissions, so we can test against that
235
+ result.first["read_stream"].should == 1
236
+ end
237
+
238
+
239
+ it "should be able to access protected information via FQL.multiquery" do
240
+ result = @api.fql_multiquery(
241
+ :query1 => "select post_id from stream where source_id = me()",
242
+ :query2 => "select fromid from comment where post_id in (select post_id from #query1)",
243
+ :query3 => "select uid, name from user where uid in (select fromid from #query2)"
244
+ )
245
+ result.size.should == 3
246
+ result.keys.should include("query1", "query2", "query3")
247
+ end
248
+
249
+ end
250
+
251
+
252
+ shared_examples_for "Koala RestAPI without an access token" do
253
+ # FQL_QUERY
254
+ describe "when making a FQL request" do
255
+ it "should be able to access public information via FQL" do
256
+ @result = @api.fql_query("select first_name from user where uid = 216743")
257
+ @result.size.should == 1
258
+ @result.first["first_name"].should == "Chris"
259
+ end
260
+
261
+ it "should be able to access public information via FQL.multiquery" do
262
+ result = @api.fql_multiquery(
263
+ :query1 => 'select first_name from user where uid = 216743',
264
+ :query2 => 'select first_name from user where uid = 2905623'
265
+ )
266
+ result.size.should == 2
267
+ result["query1"].first['first_name'].should == 'Chris'
268
+ result["query2"].first['first_name'].should == 'Alex'
269
+ end
270
+
271
+ it "should not be able to access protected information via FQL" do
272
+ lambda { @api.fql_query("select read_stream from permissions where uid = 216743") }.should raise_error(Koala::Facebook::APIError)
273
+ end
274
+
275
+ it "should not be able to access protected information via FQL.multiquery" do
276
+ lambda {
277
+ @api.fql_multiquery(
278
+ :query1 => "select post_id from stream where source_id = me()",
279
+ :query2 => "select fromid from comment where post_id in (select post_id from #query1)",
280
+ :query3 => "select uid, name from user where uid in (select fromid from #query2)"
281
+ )
282
+ }.should raise_error(Koala::Facebook::APIError)
283
+ end
284
+ end
285
+ end
@@ -0,0 +1,51 @@
1
+ # small helper method for live testing
2
+ module KoalaTest
3
+ def self.validate_user_info(token)
4
+ print "Validating permissions for live testing..."
5
+ # make sure we have the necessary permissions
6
+ api = Koala::Facebook::GraphAndRestAPI.new(token)
7
+ perms = api.fql_query("select read_stream, publish_stream, user_photos, user_videos, read_insights from permissions where uid = me()")[0]
8
+ perms.each_pair do |perm, value|
9
+ if value == (perm == "read_insights" ? 1 : 0) # live testing depends on insights calls failing
10
+ puts "failed!\n" # put a new line after the print above
11
+ raise ArgumentError, "Your access token must have the read_stream, publish_stream, and user_photos permissions, and lack read_insights. You have: #{perms.inspect}"
12
+ end
13
+ end
14
+ puts "done!"
15
+ end
16
+ end
17
+
18
+
19
+ unless ENV['LIVE']
20
+ # By default the Koala specs are run using stubs for HTTP requests
21
+ #
22
+ # Valid OAuth token and code are not necessary to run these
23
+ # specs. Because of this, specs do not fail due to Facebook
24
+ # imposed rate-limits or server timeouts.
25
+ #
26
+ # However as a result they are more brittle since
27
+ # we are not testing the latest responses from the Facebook servers.
28
+ # Therefore, to be certain all specs pass with the current
29
+ # Facebook services, run koala_spec_without_mocks.rb.
30
+ Koala.http_service = Koala::MockHTTPService
31
+
32
+ $testing_data = Koala::MockHTTPService::TEST_DATA
33
+ else
34
+ # Runs Koala specs through the Facebook servers
35
+ #
36
+ # Note that you need a valid OAuth token and code for these
37
+ # specs to run. See facebook_data.yml for more information.
38
+
39
+ # load testing data (see note in readme.md)
40
+ $testing_data = YAML.load_file(File.join(File.dirname(__FILE__), '../fixtures/facebook_data.yml'))
41
+
42
+ unless $testing_data["oauth_token"]
43
+ puts "Access token tests will fail until you store a valid token in facebook_data.yml"
44
+ end
45
+
46
+ unless $testing_data["oauth_test_data"] && $testing_data["oauth_test_data"]["code"] && $testing_data["oauth_test_data"]["secret"]
47
+ puts "OAuth code tests will fail until you store valid data for the user's OAuth code and the app secret in facebook_data.yml"
48
+ end
49
+
50
+ KoalaTest.validate_user_info $testing_data["oauth_token"]
51
+ end
@@ -0,0 +1,76 @@
1
+ shared_examples_for "MIME::Types can't return results" do
2
+ {
3
+ "jpg" => "image/jpeg",
4
+ "jpeg" => "image/jpeg",
5
+ "png" => "image/png",
6
+ "gif" => "image/gif"
7
+ }.each_pair do |extension, mime_type|
8
+ it "should properly get content types for #{extension} using basic analysis" do
9
+ path = "filename.#{extension}"
10
+ if @koala_io_params[0].is_a?(File)
11
+ @koala_io_params[0].stub!(:path).and_return(path)
12
+ else
13
+ @koala_io_params[0] = path
14
+ end
15
+ Koala::UploadableIO.new(*@koala_io_params).content_type.should == mime_type
16
+ end
17
+
18
+ it "should get content types for #{extension} using basic analysis with file names with more than one dot" do
19
+ path = "file.name.#{extension}"
20
+ if @koala_io_params[0].is_a?(File)
21
+ @koala_io_params[0].stub!(:path).and_return(path)
22
+ else
23
+ @koala_io_params[0] = path
24
+ end
25
+ Koala::UploadableIO.new(*@koala_io_params).content_type.should == mime_type
26
+ end
27
+ end
28
+
29
+ describe "if the MIME type can't be determined" do
30
+ before :each do
31
+ path = "badfile.badextension"
32
+ if @koala_io_params[0].is_a?(File)
33
+ @koala_io_params[0].stub!(:path).and_return(path)
34
+ else
35
+ @koala_io_params[0] = path
36
+ end
37
+ end
38
+
39
+ it "should throw an exception if the MIME type can't be determined and the HTTP service requires content type" do
40
+ Koala.stub!(:multipart_requires_content_type?).and_return(true)
41
+ lambda { Koala::UploadableIO.new(*@koala_io_params) }.should raise_exception(Koala::KoalaError)
42
+ end
43
+
44
+ it "should just have @content_type == nil if the HTTP service doesn't require content type" do
45
+ Koala.stub!(:multipart_requires_content_type?).and_return(false)
46
+ Koala::UploadableIO.new(*@koala_io_params).content_type.should be_nil
47
+ end
48
+ end
49
+ end
50
+
51
+ shared_examples_for "determining a mime type" do
52
+ describe "if MIME::Types is available" do
53
+ it "should return an UploadIO with MIME::Types-determined type if the type exists" do
54
+ type_result = ["type"]
55
+ Koala::MIME::Types.stub(:type_for).and_return(type_result)
56
+ Koala::UploadableIO.new(*@koala_io_params).content_type.should == type_result.first
57
+ end
58
+ end
59
+
60
+ describe "if MIME::Types is unavailable" do
61
+ before :each do
62
+ # fake that MIME::Types doesn't exist
63
+ Koala::MIME::Types.stub(:type_for).and_raise(NameError)
64
+ end
65
+ it_should_behave_like "MIME::Types can't return results"
66
+ end
67
+
68
+ describe "if MIME::Types can't find the result" do
69
+ before :each do
70
+ # fake that MIME::Types doesn't exist
71
+ Koala::MIME::Types.stub(:type_for).and_return([])
72
+ end
73
+
74
+ it_should_behave_like "MIME::Types can't return results"
75
+ end
76
+ end