PageRenderTime 44ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/activeresource/test/cases/base_test.rb

https://github.com/ghar/rails
Ruby | 1136 lines | 839 code | 208 blank | 89 comment | 4 complexity | b506e03dc532622d1227a54f240f81c9 MD5 | raw file
  1. require 'abstract_unit'
  2. require "fixtures/person"
  3. require "fixtures/customer"
  4. require "fixtures/street_address"
  5. require "fixtures/sound"
  6. require "fixtures/beast"
  7. require "fixtures/proxy"
  8. require "fixtures/address"
  9. require "fixtures/subscription_plan"
  10. require 'active_support/json'
  11. require 'active_support/ordered_hash'
  12. require 'active_support/core_ext/hash/conversions'
  13. require 'mocha'
  14. class BaseTest < Test::Unit::TestCase
  15. def setup
  16. setup_response # find me in abstract_unit
  17. @original_person_site = Person.site
  18. end
  19. def teardown
  20. Person.site = @original_person_site
  21. end
  22. ########################################################################
  23. # Tests relating to setting up the API-connection configuration
  24. ########################################################################
  25. def test_site_accessor_accepts_uri_or_string_argument
  26. site = URI.parse('http://localhost')
  27. assert_nothing_raised { Person.site = 'http://localhost' }
  28. assert_equal site, Person.site
  29. assert_nothing_raised { Person.site = site }
  30. assert_equal site, Person.site
  31. end
  32. def test_should_use_site_prefix_and_credentials
  33. assert_equal 'http://foo:bar@beast.caboo.se', Forum.site.to_s
  34. assert_equal 'http://foo:bar@beast.caboo.se/forums/:forum_id', Topic.site.to_s
  35. end
  36. def test_site_variable_can_be_reset
  37. actor = Class.new(ActiveResource::Base)
  38. assert_nil actor.site
  39. actor.site = 'http://localhost:31337'
  40. actor.site = nil
  41. assert_nil actor.site
  42. end
  43. def test_proxy_accessor_accepts_uri_or_string_argument
  44. proxy = URI.parse('http://localhost')
  45. assert_nothing_raised { Person.proxy = 'http://localhost' }
  46. assert_equal proxy, Person.proxy
  47. assert_nothing_raised { Person.proxy = proxy }
  48. assert_equal proxy, Person.proxy
  49. end
  50. def test_should_use_proxy_prefix_and_credentials
  51. assert_equal 'http://user:password@proxy.local:3000', ProxyResource.proxy.to_s
  52. end
  53. def test_proxy_variable_can_be_reset
  54. actor = Class.new(ActiveResource::Base)
  55. assert_nil actor.site
  56. actor.proxy = 'http://localhost:31337'
  57. actor.proxy = nil
  58. assert_nil actor.site
  59. end
  60. def test_should_accept_setting_user
  61. Forum.user = 'david'
  62. assert_equal('david', Forum.user)
  63. assert_equal('david', Forum.connection.user)
  64. end
  65. def test_should_accept_setting_password
  66. Forum.password = 'test123'
  67. assert_equal('test123', Forum.password)
  68. assert_equal('test123', Forum.connection.password)
  69. end
  70. def test_should_accept_setting_auth_type
  71. Forum.auth_type = :digest
  72. assert_equal(:digest, Forum.auth_type)
  73. assert_equal(:digest, Forum.connection.auth_type)
  74. end
  75. def test_should_accept_setting_timeout
  76. Forum.timeout = 5
  77. assert_equal(5, Forum.timeout)
  78. assert_equal(5, Forum.connection.timeout)
  79. end
  80. def test_should_accept_setting_ssl_options
  81. expected = {:verify => 1}
  82. Forum.ssl_options= expected
  83. assert_equal(expected, Forum.ssl_options)
  84. assert_equal(expected, Forum.connection.ssl_options)
  85. end
  86. def test_user_variable_can_be_reset
  87. actor = Class.new(ActiveResource::Base)
  88. actor.site = 'http://cinema'
  89. assert_nil actor.user
  90. actor.user = 'username'
  91. actor.user = nil
  92. assert_nil actor.user
  93. assert_nil actor.connection.user
  94. end
  95. def test_password_variable_can_be_reset
  96. actor = Class.new(ActiveResource::Base)
  97. actor.site = 'http://cinema'
  98. assert_nil actor.password
  99. actor.password = 'username'
  100. actor.password = nil
  101. assert_nil actor.password
  102. assert_nil actor.connection.password
  103. end
  104. def test_timeout_variable_can_be_reset
  105. actor = Class.new(ActiveResource::Base)
  106. actor.site = 'http://cinema'
  107. assert_nil actor.timeout
  108. actor.timeout = 5
  109. actor.timeout = nil
  110. assert_nil actor.timeout
  111. assert_nil actor.connection.timeout
  112. end
  113. def test_ssl_options_hash_can_be_reset
  114. actor = Class.new(ActiveResource::Base)
  115. actor.site = 'https://cinema'
  116. assert_nil actor.ssl_options
  117. actor.ssl_options = {:foo => 5}
  118. actor.ssl_options = nil
  119. assert_nil actor.ssl_options
  120. assert_nil actor.connection.ssl_options
  121. end
  122. def test_credentials_from_site_are_decoded
  123. actor = Class.new(ActiveResource::Base)
  124. actor.site = 'http://my%40email.com:%31%32%33@cinema'
  125. assert_equal("my@email.com", actor.user)
  126. assert_equal("123", actor.password)
  127. end
  128. def test_site_reader_uses_superclass_site_until_written
  129. # Superclass is Object so returns nil.
  130. assert_nil ActiveResource::Base.site
  131. assert_nil Class.new(ActiveResource::Base).site
  132. # Subclass uses superclass site.
  133. actor = Class.new(Person)
  134. assert_equal Person.site, actor.site
  135. # Subclass returns frozen superclass copy.
  136. assert !Person.site.frozen?
  137. assert actor.site.frozen?
  138. # Changing subclass site doesn't change superclass site.
  139. actor.site = 'http://localhost:31337'
  140. assert_not_equal Person.site, actor.site
  141. # Changed subclass site is not frozen.
  142. assert !actor.site.frozen?
  143. # Changing superclass site doesn't overwrite subclass site.
  144. Person.site = 'http://somewhere.else'
  145. assert_not_equal Person.site, actor.site
  146. # Changing superclass site after subclassing changes subclass site.
  147. jester = Class.new(actor)
  148. actor.site = 'http://nomad'
  149. assert_equal actor.site, jester.site
  150. assert jester.site.frozen?
  151. # Subclasses are always equal to superclass site when not overridden
  152. fruit = Class.new(ActiveResource::Base)
  153. apple = Class.new(fruit)
  154. fruit.site = 'http://market'
  155. assert_equal fruit.site, apple.site, 'subclass did not adopt changes from parent class'
  156. fruit.site = 'http://supermarket'
  157. assert_equal fruit.site, apple.site, 'subclass did not adopt changes from parent class'
  158. end
  159. def test_proxy_reader_uses_superclass_site_until_written
  160. # Superclass is Object so returns nil.
  161. assert_nil ActiveResource::Base.proxy
  162. assert_nil Class.new(ActiveResource::Base).proxy
  163. # Subclass uses superclass proxy.
  164. actor = Class.new(Person)
  165. assert_equal Person.proxy, actor.proxy
  166. # Subclass returns frozen superclass copy.
  167. assert !Person.proxy.frozen?
  168. assert actor.proxy.frozen?
  169. # Changing subclass proxy doesn't change superclass site.
  170. actor.proxy = 'http://localhost:31337'
  171. assert_not_equal Person.proxy, actor.proxy
  172. # Changed subclass proxy is not frozen.
  173. assert !actor.proxy.frozen?
  174. # Changing superclass proxy doesn't overwrite subclass site.
  175. Person.proxy = 'http://somewhere.else'
  176. assert_not_equal Person.proxy, actor.proxy
  177. # Changing superclass proxy after subclassing changes subclass site.
  178. jester = Class.new(actor)
  179. actor.proxy = 'http://nomad'
  180. assert_equal actor.proxy, jester.proxy
  181. assert jester.proxy.frozen?
  182. # Subclasses are always equal to superclass proxy when not overridden
  183. fruit = Class.new(ActiveResource::Base)
  184. apple = Class.new(fruit)
  185. fruit.proxy = 'http://market'
  186. assert_equal fruit.proxy, apple.proxy, 'subclass did not adopt changes from parent class'
  187. fruit.proxy = 'http://supermarket'
  188. assert_equal fruit.proxy, apple.proxy, 'subclass did not adopt changes from parent class'
  189. end
  190. def test_user_reader_uses_superclass_user_until_written
  191. # Superclass is Object so returns nil.
  192. assert_nil ActiveResource::Base.user
  193. assert_nil Class.new(ActiveResource::Base).user
  194. Person.user = 'anonymous'
  195. # Subclass uses superclass user.
  196. actor = Class.new(Person)
  197. assert_equal Person.user, actor.user
  198. # Subclass returns frozen superclass copy.
  199. assert !Person.user.frozen?
  200. assert actor.user.frozen?
  201. # Changing subclass user doesn't change superclass user.
  202. actor.user = 'david'
  203. assert_not_equal Person.user, actor.user
  204. # Changing superclass user doesn't overwrite subclass user.
  205. Person.user = 'john'
  206. assert_not_equal Person.user, actor.user
  207. # Changing superclass user after subclassing changes subclass user.
  208. jester = Class.new(actor)
  209. actor.user = 'john.doe'
  210. assert_equal actor.user, jester.user
  211. # Subclasses are always equal to superclass user when not overridden
  212. fruit = Class.new(ActiveResource::Base)
  213. apple = Class.new(fruit)
  214. fruit.user = 'manager'
  215. assert_equal fruit.user, apple.user, 'subclass did not adopt changes from parent class'
  216. fruit.user = 'client'
  217. assert_equal fruit.user, apple.user, 'subclass did not adopt changes from parent class'
  218. end
  219. def test_password_reader_uses_superclass_password_until_written
  220. # Superclass is Object so returns nil.
  221. assert_nil ActiveResource::Base.password
  222. assert_nil Class.new(ActiveResource::Base).password
  223. Person.password = 'my-password'
  224. # Subclass uses superclass password.
  225. actor = Class.new(Person)
  226. assert_equal Person.password, actor.password
  227. # Subclass returns frozen superclass copy.
  228. assert !Person.password.frozen?
  229. assert actor.password.frozen?
  230. # Changing subclass password doesn't change superclass password.
  231. actor.password = 'secret'
  232. assert_not_equal Person.password, actor.password
  233. # Changing superclass password doesn't overwrite subclass password.
  234. Person.password = 'super-secret'
  235. assert_not_equal Person.password, actor.password
  236. # Changing superclass password after subclassing changes subclass password.
  237. jester = Class.new(actor)
  238. actor.password = 'even-more-secret'
  239. assert_equal actor.password, jester.password
  240. # Subclasses are always equal to superclass password when not overridden
  241. fruit = Class.new(ActiveResource::Base)
  242. apple = Class.new(fruit)
  243. fruit.password = 'mega-secret'
  244. assert_equal fruit.password, apple.password, 'subclass did not adopt changes from parent class'
  245. fruit.password = 'ok-password'
  246. assert_equal fruit.password, apple.password, 'subclass did not adopt changes from parent class'
  247. end
  248. def test_timeout_reader_uses_superclass_timeout_until_written
  249. # Superclass is Object so returns nil.
  250. assert_nil ActiveResource::Base.timeout
  251. assert_nil Class.new(ActiveResource::Base).timeout
  252. Person.timeout = 5
  253. # Subclass uses superclass timeout.
  254. actor = Class.new(Person)
  255. assert_equal Person.timeout, actor.timeout
  256. # Changing subclass timeout doesn't change superclass timeout.
  257. actor.timeout = 10
  258. assert_not_equal Person.timeout, actor.timeout
  259. # Changing superclass timeout doesn't overwrite subclass timeout.
  260. Person.timeout = 15
  261. assert_not_equal Person.timeout, actor.timeout
  262. # Changing superclass timeout after subclassing changes subclass timeout.
  263. jester = Class.new(actor)
  264. actor.timeout = 20
  265. assert_equal actor.timeout, jester.timeout
  266. # Subclasses are always equal to superclass timeout when not overridden.
  267. fruit = Class.new(ActiveResource::Base)
  268. apple = Class.new(fruit)
  269. fruit.timeout = 25
  270. assert_equal fruit.timeout, apple.timeout, 'subclass did not adopt changes from parent class'
  271. fruit.timeout = 30
  272. assert_equal fruit.timeout, apple.timeout, 'subclass did not adopt changes from parent class'
  273. end
  274. def test_ssl_options_reader_uses_superclass_ssl_options_until_written
  275. # Superclass is Object so returns nil.
  276. assert_nil ActiveResource::Base.ssl_options
  277. assert_nil Class.new(ActiveResource::Base).ssl_options
  278. Person.ssl_options = {:foo => 'bar'}
  279. # Subclass uses superclass ssl_options.
  280. actor = Class.new(Person)
  281. assert_equal Person.ssl_options, actor.ssl_options
  282. # Changing subclass ssl_options doesn't change superclass ssl_options.
  283. actor.ssl_options = {:baz => ''}
  284. assert_not_equal Person.ssl_options, actor.ssl_options
  285. # Changing superclass ssl_options doesn't overwrite subclass ssl_options.
  286. Person.ssl_options = {:color => 'blue'}
  287. assert_not_equal Person.ssl_options, actor.ssl_options
  288. # Changing superclass ssl_options after subclassing changes subclass ssl_options.
  289. jester = Class.new(actor)
  290. actor.ssl_options = {:color => 'red'}
  291. assert_equal actor.ssl_options, jester.ssl_options
  292. # Subclasses are always equal to superclass ssl_options when not overridden.
  293. fruit = Class.new(ActiveResource::Base)
  294. apple = Class.new(fruit)
  295. fruit.ssl_options = {:alpha => 'betas'}
  296. assert_equal fruit.ssl_options, apple.ssl_options, 'subclass did not adopt changes from parent class'
  297. fruit.ssl_options = {:omega => 'moos'}
  298. assert_equal fruit.ssl_options, apple.ssl_options, 'subclass did not adopt changes from parent class'
  299. end
  300. def test_updating_baseclass_site_object_wipes_descendent_cached_connection_objects
  301. # Subclasses are always equal to superclass site when not overridden
  302. fruit = Class.new(ActiveResource::Base)
  303. apple = Class.new(fruit)
  304. fruit.site = 'http://market'
  305. assert_equal fruit.connection.site, apple.connection.site
  306. first_connection = apple.connection.object_id
  307. fruit.site = 'http://supermarket'
  308. assert_equal fruit.connection.site, apple.connection.site
  309. second_connection = apple.connection.object_id
  310. assert_not_equal(first_connection, second_connection, 'Connection should be re-created')
  311. end
  312. def test_updating_baseclass_user_wipes_descendent_cached_connection_objects
  313. # Subclasses are always equal to superclass user when not overridden
  314. fruit = Class.new(ActiveResource::Base)
  315. apple = Class.new(fruit)
  316. fruit.site = 'http://market'
  317. fruit.user = 'david'
  318. assert_equal fruit.connection.user, apple.connection.user
  319. first_connection = apple.connection.object_id
  320. fruit.user = 'john'
  321. assert_equal fruit.connection.user, apple.connection.user
  322. second_connection = apple.connection.object_id
  323. assert_not_equal(first_connection, second_connection, 'Connection should be re-created')
  324. end
  325. def test_updating_baseclass_password_wipes_descendent_cached_connection_objects
  326. # Subclasses are always equal to superclass password when not overridden
  327. fruit = Class.new(ActiveResource::Base)
  328. apple = Class.new(fruit)
  329. fruit.site = 'http://market'
  330. fruit.password = 'secret'
  331. assert_equal fruit.connection.password, apple.connection.password
  332. first_connection = apple.connection.object_id
  333. fruit.password = 'supersecret'
  334. assert_equal fruit.connection.password, apple.connection.password
  335. second_connection = apple.connection.object_id
  336. assert_not_equal(first_connection, second_connection, 'Connection should be re-created')
  337. end
  338. def test_updating_baseclass_timeout_wipes_descendent_cached_connection_objects
  339. # Subclasses are always equal to superclass timeout when not overridden
  340. fruit = Class.new(ActiveResource::Base)
  341. apple = Class.new(fruit)
  342. fruit.site = 'http://market'
  343. fruit.timeout = 5
  344. assert_equal fruit.connection.timeout, apple.connection.timeout
  345. first_connection = apple.connection.object_id
  346. fruit.timeout = 10
  347. assert_equal fruit.connection.timeout, apple.connection.timeout
  348. second_connection = apple.connection.object_id
  349. assert_not_equal(first_connection, second_connection, 'Connection should be re-created')
  350. end
  351. ########################################################################
  352. # Tests for setting up remote URLs for a given model (including adding
  353. # parameters appropriately)
  354. ########################################################################
  355. def test_collection_name
  356. assert_equal "people", Person.collection_name
  357. end
  358. def test_collection_path
  359. assert_equal '/people.json', Person.collection_path
  360. end
  361. def test_collection_path_with_parameters
  362. assert_equal '/people.json?gender=male', Person.collection_path(:gender => 'male')
  363. assert_equal '/people.json?gender=false', Person.collection_path(:gender => false)
  364. assert_equal '/people.json?gender=', Person.collection_path(:gender => nil)
  365. assert_equal '/people.json?gender=male', Person.collection_path('gender' => 'male')
  366. # Use includes? because ordering of param hash is not guaranteed
  367. assert Person.collection_path(:gender => 'male', :student => true).include?('/people.json?')
  368. assert Person.collection_path(:gender => 'male', :student => true).include?('gender=male')
  369. assert Person.collection_path(:gender => 'male', :student => true).include?('student=true')
  370. assert_equal '/people.json?name%5B%5D=bob&name%5B%5D=your+uncle%2Bme&name%5B%5D=&name%5B%5D=false', Person.collection_path(:name => ['bob', 'your uncle+me', nil, false])
  371. assert_equal '/people.json?struct%5Ba%5D%5B%5D=2&struct%5Ba%5D%5B%5D=1&struct%5Bb%5D=fred', Person.collection_path(:struct => ActiveSupport::OrderedHash[:a, [2,1], 'b', 'fred'])
  372. end
  373. def test_custom_element_path
  374. assert_equal '/people/1/addresses/1.json', StreetAddress.element_path(1, :person_id => 1)
  375. assert_equal '/people/1/addresses/1.json', StreetAddress.element_path(1, 'person_id' => 1)
  376. assert_equal '/people/Greg/addresses/1.json', StreetAddress.element_path(1, 'person_id' => 'Greg')
  377. assert_equal '/people/ann%20mary/addresses/ann%20mary.json', StreetAddress.element_path(:'ann mary', 'person_id' => 'ann mary')
  378. end
  379. def test_custom_element_path_without_required_prefix_param
  380. assert_raise ActiveResource::MissingPrefixParam do
  381. StreetAddress.element_path(1)
  382. end
  383. end
  384. def test_module_element_path
  385. assert_equal '/sounds/1.json', Asset::Sound.element_path(1)
  386. end
  387. def test_custom_element_path_with_redefined_to_param
  388. Person.module_eval do
  389. alias_method :original_to_param_element_path, :to_param
  390. def to_param
  391. name
  392. end
  393. end
  394. # Class method.
  395. assert_equal '/people/Greg.json', Person.element_path('Greg')
  396. # Protected Instance method.
  397. assert_equal '/people/Greg.json', Person.find('Greg').send(:element_path)
  398. ensure
  399. # revert back to original
  400. Person.module_eval do
  401. # save the 'new' to_param so we don't get a warning about discarding the method
  402. alias_method :element_path_to_param, :to_param
  403. alias_method :to_param, :original_to_param_element_path
  404. end
  405. end
  406. def test_custom_element_path_with_parameters
  407. assert_equal '/people/1/addresses/1.json?type=work', StreetAddress.element_path(1, :person_id => 1, :type => 'work')
  408. assert_equal '/people/1/addresses/1.json?type=work', StreetAddress.element_path(1, 'person_id' => 1, :type => 'work')
  409. assert_equal '/people/1/addresses/1.json?type=work', StreetAddress.element_path(1, :type => 'work', :person_id => 1)
  410. assert_equal '/people/1/addresses/1.json?type%5B%5D=work&type%5B%5D=play+time', StreetAddress.element_path(1, :person_id => 1, :type => ['work', 'play time'])
  411. end
  412. def test_custom_element_path_with_prefix_and_parameters
  413. assert_equal '/people/1/addresses/1.json?type=work', StreetAddress.element_path(1, {:person_id => 1}, {:type => 'work'})
  414. end
  415. def test_custom_collection_path_without_required_prefix_param
  416. assert_raise ActiveResource::MissingPrefixParam do
  417. StreetAddress.collection_path
  418. end
  419. end
  420. def test_custom_collection_path
  421. assert_equal '/people/1/addresses.json', StreetAddress.collection_path(:person_id => 1)
  422. assert_equal '/people/1/addresses.json', StreetAddress.collection_path('person_id' => 1)
  423. end
  424. def test_custom_collection_path_with_parameters
  425. assert_equal '/people/1/addresses.json?type=work', StreetAddress.collection_path(:person_id => 1, :type => 'work')
  426. assert_equal '/people/1/addresses.json?type=work', StreetAddress.collection_path('person_id' => 1, :type => 'work')
  427. end
  428. def test_custom_collection_path_with_prefix_and_parameters
  429. assert_equal '/people/1/addresses.json?type=work', StreetAddress.collection_path({:person_id => 1}, {:type => 'work'})
  430. end
  431. def test_custom_element_name
  432. assert_equal 'address', StreetAddress.element_name
  433. end
  434. def test_custom_collection_name
  435. assert_equal 'addresses', StreetAddress.collection_name
  436. end
  437. def test_prefix
  438. assert_equal "/", Person.prefix
  439. assert_equal Set.new, Person.__send__(:prefix_parameters)
  440. end
  441. def test_set_prefix
  442. SetterTrap.rollback_sets(Person) do |person_class|
  443. person_class.prefix = "the_prefix"
  444. assert_equal "the_prefix", person_class.prefix
  445. end
  446. end
  447. def test_set_prefix_with_inline_keys
  448. SetterTrap.rollback_sets(Person) do |person_class|
  449. person_class.prefix = "the_prefix:the_param"
  450. assert_equal "the_prefixthe_param_value", person_class.prefix(:the_param => "the_param_value")
  451. end
  452. end
  453. def test_set_prefix_twice_should_clear_params
  454. SetterTrap.rollback_sets(Person) do |person_class|
  455. person_class.prefix = "the_prefix/:the_param1"
  456. assert_equal Set.new([:the_param1]), person_class.prefix_parameters
  457. person_class.prefix = "the_prefix/:the_param2"
  458. assert_equal Set.new([:the_param2]), person_class.prefix_parameters
  459. person_class.prefix = "the_prefix/:the_param1/other_prefix/:the_param2"
  460. assert_equal Set.new([:the_param2, :the_param1]), person_class.prefix_parameters
  461. end
  462. end
  463. def test_set_prefix_with_default_value
  464. SetterTrap.rollback_sets(Person) do |person_class|
  465. person_class.set_prefix
  466. assert_equal "/", person_class.prefix
  467. end
  468. end
  469. def test_custom_prefix
  470. assert_equal '/people//', StreetAddress.prefix
  471. assert_equal '/people/1/', StreetAddress.prefix(:person_id => 1)
  472. assert_equal [:person_id].to_set, StreetAddress.__send__(:prefix_parameters)
  473. end
  474. ########################################################################
  475. # Tests basic CRUD functions (find/save/create etc)
  476. ########################################################################
  477. def test_respond_to
  478. matz = Person.find(1)
  479. assert_respond_to matz, :name
  480. assert_respond_to matz, :name=
  481. assert_respond_to matz, :name?
  482. assert !matz.respond_to?(:super_scalable_stuff)
  483. end
  484. def test_custom_header
  485. Person.headers['key'] = 'value'
  486. assert_raise(ActiveResource::ResourceNotFound) { Person.find(4) }
  487. ensure
  488. Person.headers.delete('key')
  489. end
  490. def test_save
  491. rick = Person.new
  492. assert rick.save
  493. assert_equal '5', rick.id
  494. end
  495. def test_save!
  496. rick = Person.new
  497. assert rick.save!
  498. assert_equal '5', rick.id
  499. end
  500. def test_id_from_response
  501. p = Person.new
  502. resp = {'Location' => '/foo/bar/1'}
  503. assert_equal '1', p.__send__(:id_from_response, resp)
  504. resp['Location'] << '.json'
  505. assert_equal '1', p.__send__(:id_from_response, resp)
  506. end
  507. def test_id_from_response_without_location
  508. p = Person.new
  509. resp = {}
  510. assert_nil p.__send__(:id_from_response, resp)
  511. end
  512. def test_not_persisted_with_no_body_and_positive_content_length
  513. resp = ActiveResource::Response.new(nil)
  514. resp['Content-Length'] = "100"
  515. Person.connection.expects(:post).returns(resp)
  516. assert !Person.create.persisted?
  517. end
  518. def test_not_persisted_with_body_and_zero_content_length
  519. resp = ActiveResource::Response.new(@rick)
  520. resp['Content-Length'] = "0"
  521. Person.connection.expects(:post).returns(resp)
  522. assert !Person.create.persisted?
  523. end
  524. # These response codes aren't allowed to have bodies per HTTP spec
  525. def test_not_persisted_with_empty_response_codes
  526. [100,101,204,304].each do |status_code|
  527. resp = ActiveResource::Response.new(@rick, status_code)
  528. Person.connection.expects(:post).returns(resp)
  529. assert !Person.create.persisted?
  530. end
  531. end
  532. # Content-Length is not required by HTTP 1.1, so we should read
  533. # the body anyway in its absence.
  534. def test_persisted_with_no_content_length
  535. resp = ActiveResource::Response.new(@rick)
  536. resp['Content-Length'] = nil
  537. Person.connection.expects(:post).returns(resp)
  538. assert Person.create.persisted?
  539. end
  540. def test_create_with_custom_prefix
  541. matzs_house = StreetAddress.new(:person_id => 1)
  542. matzs_house.save
  543. assert_equal '5', matzs_house.id
  544. end
  545. # Test that loading a resource preserves its prefix_options.
  546. def test_load_preserves_prefix_options
  547. address = StreetAddress.find(1, :params => { :person_id => 1 })
  548. ryan = Person.new(:id => 1, :name => 'Ryan', :address => address)
  549. assert_equal address.prefix_options, ryan.address.prefix_options
  550. end
  551. def test_reload_works_with_prefix_options
  552. address = StreetAddress.find(1, :params => { :person_id => 1 })
  553. assert_equal address, address.reload
  554. end
  555. def test_reload_with_redefined_to_param
  556. Person.module_eval do
  557. alias_method :original_to_param_reload, :to_param
  558. def to_param
  559. name
  560. end
  561. end
  562. person = Person.find('Greg')
  563. assert_equal person, person.reload
  564. ensure
  565. # revert back to original
  566. Person.module_eval do
  567. # save the 'new' to_param so we don't get a warning about discarding the method
  568. alias_method :reload_to_param, :to_param
  569. alias_method :to_param, :original_to_param_reload
  570. end
  571. end
  572. def test_reload_works_without_prefix_options
  573. person = Person.find(:first)
  574. assert_equal person, person.reload
  575. end
  576. def test_create
  577. rick = Person.create(:name => 'Rick')
  578. assert rick.valid?
  579. assert !rick.new?
  580. assert_equal '5', rick.id
  581. # test additional attribute returned on create
  582. assert_equal 25, rick.age
  583. # Test that save exceptions get bubbled up too
  584. ActiveResource::HttpMock.respond_to do |mock|
  585. mock.post "/people.json", {}, nil, 409
  586. end
  587. assert_raise(ActiveResource::ResourceConflict) { Person.create(:name => 'Rick') }
  588. end
  589. def test_create_without_location
  590. ActiveResource::HttpMock.respond_to do |mock|
  591. mock.post "/people.json", {}, nil, 201
  592. end
  593. person = Person.create(:name => 'Rick')
  594. assert_nil person.id
  595. end
  596. def test_clone
  597. matz = Person.find(1)
  598. matz_c = matz.clone
  599. assert matz_c.new?
  600. matz.attributes.each do |k, v|
  601. assert_equal v, matz_c.send(k) if k != Person.primary_key
  602. end
  603. end
  604. def test_nested_clone
  605. addy = StreetAddress.find(1, :params => {:person_id => 1})
  606. addy_c = addy.clone
  607. assert addy_c.new?
  608. addy.attributes.each do |k, v|
  609. assert_equal v, addy_c.send(k) if k != StreetAddress.primary_key
  610. end
  611. assert_equal addy.prefix_options, addy_c.prefix_options
  612. end
  613. def test_complex_clone
  614. matz = Person.find(1)
  615. matz.address = StreetAddress.find(1, :params => {:person_id => matz.id})
  616. matz.non_ar_hash = {:not => "an ARes instance"}
  617. matz.non_ar_arr = ["not", "ARes"]
  618. matz_c = matz.clone
  619. assert matz_c.new?
  620. assert_raise(NoMethodError) {matz_c.address}
  621. assert_equal matz.non_ar_hash, matz_c.non_ar_hash
  622. assert_equal matz.non_ar_arr, matz_c.non_ar_arr
  623. # Test that actual copy, not just reference copy
  624. matz.non_ar_hash[:not] = "changed"
  625. assert_not_equal matz.non_ar_hash, matz_c.non_ar_hash
  626. end
  627. def test_update
  628. matz = Person.find(:first)
  629. matz.name = "David"
  630. assert_kind_of Person, matz
  631. assert_equal "David", matz.name
  632. assert_equal true, matz.save
  633. end
  634. def test_update_with_custom_prefix_with_specific_id
  635. addy = StreetAddress.find(1, :params => { :person_id => 1 })
  636. addy.street = "54321 Street"
  637. assert_kind_of StreetAddress, addy
  638. assert_equal "54321 Street", addy.street
  639. addy.save
  640. end
  641. def test_update_with_custom_prefix_without_specific_id
  642. addy = StreetAddress.find(:first, :params => { :person_id => 1 })
  643. addy.street = "54321 Lane"
  644. assert_kind_of StreetAddress, addy
  645. assert_equal "54321 Lane", addy.street
  646. addy.save
  647. end
  648. def test_update_conflict
  649. ActiveResource::HttpMock.respond_to do |mock|
  650. mock.get "/people/2.json", {}, @david
  651. mock.put "/people/2.json", @default_request_headers, nil, 409
  652. end
  653. assert_raise(ActiveResource::ResourceConflict) { Person.find(2).save }
  654. end
  655. ######
  656. # update_attribute(s)(!)
  657. def test_update_attribute_as_symbol
  658. matz = Person.first
  659. matz.expects(:save).returns(true)
  660. assert_equal "Matz", matz.name
  661. assert matz.update_attribute(:name, "David")
  662. assert_equal "David", matz.name
  663. end
  664. def test_update_attribute_as_string
  665. matz = Person.first
  666. matz.expects(:save).returns(true)
  667. assert_equal "Matz", matz.name
  668. assert matz.update_attribute('name', "David")
  669. assert_equal "David", matz.name
  670. end
  671. def test_update_attributes_as_symbols
  672. addy = StreetAddress.first(:params => {:person_id => 1})
  673. addy.expects(:save).returns(true)
  674. assert_equal "12345 Street", addy.street
  675. assert_equal "Australia", addy.country
  676. assert addy.update_attributes(:street => '54321 Street', :country => 'USA')
  677. assert_equal "54321 Street", addy.street
  678. assert_equal "USA", addy.country
  679. end
  680. def test_update_attributes_as_strings
  681. addy = StreetAddress.first(:params => {:person_id => 1})
  682. addy.expects(:save).returns(true)
  683. assert_equal "12345 Street", addy.street
  684. assert_equal "Australia", addy.country
  685. assert addy.update_attributes('street' => '54321 Street', 'country' => 'USA')
  686. assert_equal "54321 Street", addy.street
  687. assert_equal "USA", addy.country
  688. end
  689. #####
  690. # Mayhem and destruction
  691. def test_destroy
  692. assert Person.find(1).destroy
  693. ActiveResource::HttpMock.respond_to do |mock|
  694. mock.get "/people/1.json", {}, nil, 404
  695. end
  696. assert_raise(ActiveResource::ResourceNotFound) { Person.find(1).destroy }
  697. end
  698. def test_destroy_with_custom_prefix
  699. assert StreetAddress.find(1, :params => { :person_id => 1 }).destroy
  700. ActiveResource::HttpMock.respond_to do |mock|
  701. mock.get "/people/1/addresses/1.json", {}, nil, 404
  702. end
  703. assert_raise(ActiveResource::ResourceNotFound) { StreetAddress.find(1, :params => { :person_id => 1 }) }
  704. end
  705. def test_destroy_with_410_gone
  706. assert Person.find(1).destroy
  707. ActiveResource::HttpMock.respond_to do |mock|
  708. mock.get "/people/1.json", {}, nil, 410
  709. end
  710. assert_raise(ActiveResource::ResourceGone) { Person.find(1).destroy }
  711. end
  712. def test_delete
  713. assert Person.delete(1)
  714. ActiveResource::HttpMock.respond_to do |mock|
  715. mock.get "/people/1.json", {}, nil, 404
  716. end
  717. assert_raise(ActiveResource::ResourceNotFound) { Person.find(1) }
  718. end
  719. def test_delete_with_custom_prefix
  720. assert StreetAddress.delete(1, :person_id => 1)
  721. ActiveResource::HttpMock.respond_to do |mock|
  722. mock.get "/people/1/addresses/1.json", {}, nil, 404
  723. end
  724. assert_raise(ActiveResource::ResourceNotFound) { StreetAddress.find(1, :params => { :person_id => 1 }) }
  725. end
  726. def test_delete_with_410_gone
  727. assert Person.delete(1)
  728. ActiveResource::HttpMock.respond_to do |mock|
  729. mock.get "/people/1.json", {}, nil, 410
  730. end
  731. assert_raise(ActiveResource::ResourceGone) { Person.find(1) }
  732. end
  733. ########################################################################
  734. # Tests the more miscellaneous helper methods
  735. ########################################################################
  736. def test_exists
  737. # Class method.
  738. assert !Person.exists?(nil)
  739. assert Person.exists?(1)
  740. assert !Person.exists?(99)
  741. # Instance method.
  742. assert !Person.new.exists?
  743. assert Person.find(1).exists?
  744. assert !Person.new(:id => 99).exists?
  745. # Nested class method.
  746. assert StreetAddress.exists?(1, :params => { :person_id => 1 })
  747. assert !StreetAddress.exists?(1, :params => { :person_id => 2 })
  748. assert !StreetAddress.exists?(2, :params => { :person_id => 1 })
  749. # Nested instance method.
  750. assert StreetAddress.find(1, :params => { :person_id => 1 }).exists?
  751. assert !StreetAddress.new({:id => 1, :person_id => 2}).exists?
  752. assert !StreetAddress.new({:id => 2, :person_id => 1}).exists?
  753. end
  754. def test_exists_with_redefined_to_param
  755. Person.module_eval do
  756. alias_method :original_to_param_exists, :to_param
  757. def to_param
  758. name
  759. end
  760. end
  761. # Class method.
  762. assert Person.exists?('Greg')
  763. # Instance method.
  764. assert Person.find('Greg').exists?
  765. # Nested class method.
  766. assert StreetAddress.exists?(1, :params => { :person_id => Person.find('Greg').to_param })
  767. # Nested instance method.
  768. assert StreetAddress.find(1, :params => { :person_id => Person.find('Greg').to_param }).exists?
  769. ensure
  770. # revert back to original
  771. Person.module_eval do
  772. # save the 'new' to_param so we don't get a warning about discarding the method
  773. alias_method :exists_to_param, :to_param
  774. alias_method :to_param, :original_to_param_exists
  775. end
  776. end
  777. def test_exists_without_http_mock
  778. http = Net::HTTP.new(Person.site.host, Person.site.port)
  779. ActiveResource::Connection.any_instance.expects(:http).returns(http)
  780. http.expects(:request).returns(ActiveResource::Response.new(""))
  781. assert Person.exists?('not-mocked')
  782. end
  783. def test_exists_with_410_gone
  784. ActiveResource::HttpMock.respond_to do |mock|
  785. mock.head "/people/1.json", {}, nil, 410
  786. end
  787. assert !Person.exists?(1)
  788. end
  789. def test_to_xml
  790. Person.format = :xml
  791. matz = Person.find(1)
  792. encode = matz.encode
  793. xml = matz.to_xml
  794. assert_equal encode, xml
  795. assert xml.include?('<?xml version="1.0" encoding="UTF-8"?>')
  796. assert xml.include?('<name>Matz</name>')
  797. assert xml.include?('<id type="integer">1</id>')
  798. ensure
  799. Person.format = :json
  800. end
  801. def test_to_xml_with_element_name
  802. Person.format = :xml
  803. old_elem_name = Person.element_name
  804. matz = Person.find(1)
  805. Person.element_name = 'ruby_creator'
  806. encode = matz.encode
  807. xml = matz.to_xml
  808. assert_equal encode, xml
  809. assert xml.include?('<?xml version="1.0" encoding="UTF-8"?>')
  810. assert xml.include?('<ruby-creator>')
  811. assert xml.include?('<name>Matz</name>')
  812. assert xml.include?('<id type="integer">1</id>')
  813. assert xml.include?('</ruby-creator>')
  814. ensure
  815. Person.format = :json
  816. Person.element_name = old_elem_name
  817. end
  818. def test_to_xml_with_private_method_name_as_attribute
  819. Person.format = :xml
  820. assert_nothing_raised(ArgumentError) {
  821. Customer.new(:test => true).to_xml
  822. }
  823. ensure
  824. Person.format = :json
  825. end
  826. def test_to_json
  827. Person.include_root_in_json = true
  828. joe = Person.find(6)
  829. encode = joe.encode
  830. json = joe.to_json
  831. assert_equal encode, json
  832. assert_match %r{^\{"person":\{}, json
  833. assert_match %r{"id":6}, json
  834. assert_match %r{"name":"Joe"}, json
  835. assert_match %r{\}\}$}, json
  836. end
  837. def test_to_json_with_element_name
  838. old_elem_name = Person.element_name
  839. Person.include_root_in_json = true
  840. joe = Person.find(6)
  841. Person.element_name = 'ruby_creator'
  842. encode = joe.encode
  843. json = joe.to_json
  844. assert_equal encode, json
  845. assert_match %r{^\{"ruby_creator":\{}, json
  846. assert_match %r{"id":6}, json
  847. assert_match %r{"name":"Joe"}, json
  848. assert_match %r{\}\}$}, json
  849. ensure
  850. Person.element_name = old_elem_name
  851. end
  852. def test_to_param_quacks_like_active_record
  853. new_person = Person.new
  854. assert_nil new_person.to_param
  855. matz = Person.find(1)
  856. assert_equal '1', matz.to_param
  857. end
  858. def test_to_key_quacks_like_active_record
  859. new_person = Person.new
  860. assert_nil new_person.to_key
  861. matz = Person.find(1)
  862. assert_equal [1], matz.to_key
  863. end
  864. def test_parse_deep_nested_resources
  865. luis = Customer.find(1)
  866. assert_kind_of Customer, luis
  867. luis.friends.each do |friend|
  868. assert_kind_of Customer::Friend, friend
  869. friend.brothers.each do |brother|
  870. assert_kind_of Customer::Friend::Brother, brother
  871. brother.children.each do |child|
  872. assert_kind_of Customer::Friend::Brother::Child, child
  873. end
  874. end
  875. end
  876. end
  877. def test_load_yaml_array
  878. assert_nothing_raised do
  879. Person.format = :xml
  880. marty = Person.find(5)
  881. assert_equal 3, marty.colors.size
  882. marty.colors.each do |color|
  883. assert_kind_of String, color
  884. end
  885. end
  886. ensure
  887. Person.format = :json
  888. end
  889. def test_with_custom_formatter
  890. addresses = [{ :id => "1", :street => "1 Infinite Loop", :city => "Cupertino", :state => "CA" }].to_xml(:root => :addresses)
  891. ActiveResource::HttpMock.respond_to do |mock|
  892. mock.get "/addresses.xml", {}, addresses, 200
  893. end
  894. # late bind the site
  895. AddressResource.site = "http://localhost"
  896. addresses = AddressResource.find(:all)
  897. assert_equal "Cupertino, CA", addresses.first.city_state
  898. end
  899. def test_create_with_custom_primary_key
  900. silver_plan = { :plan => { :code => "silver", :price => 5.00 } }.to_json
  901. ActiveResource::HttpMock.respond_to do |mock|
  902. mock.post "/plans.json", {}, silver_plan, 201, 'Location' => '/plans/silver.json'
  903. end
  904. plan = SubscriptionPlan.new(:code => "silver", :price => 5.00)
  905. assert plan.new?
  906. plan.save!
  907. assert !plan.new?
  908. end
  909. def test_update_with_custom_primary_key
  910. silver_plan = { :plan => { :code => "silver", :price => 5.00 } }.to_json
  911. silver_plan_updated = { :plan => { :code => "silver", :price => 10.00 } }.to_json
  912. ActiveResource::HttpMock.respond_to do |mock|
  913. mock.get "/plans/silver.json", {}, silver_plan
  914. mock.put "/plans/silver.json", {}, silver_plan_updated, 201, 'Location' => '/plans/silver.json'
  915. end
  916. plan = SubscriptionPlan.find("silver")
  917. assert !plan.new?
  918. assert_equal 5.00, plan.price
  919. # update price
  920. plan.price = 10.00
  921. plan.save!
  922. assert_equal 10.00, plan.price
  923. end
  924. def test_namespacing
  925. sound = Asset::Sound.find(1)
  926. assert_equal "Asset::Sound::Author", sound.author.class.to_s
  927. end
  928. end