agent_spec.rb 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. require 'spec_helper'
  2. describe Agent do
  3. describe ".run_schedule" do
  4. before do
  5. Agents::WeatherAgent.count.should > 0
  6. Agents::WebsiteAgent.count.should > 0
  7. end
  8. it "runs agents with the given schedule" do
  9. weather_agent_ids = [agents(:bob_weather_agent), agents(:jane_weather_agent)].map(&:id)
  10. stub(Agents::WeatherAgent).async_check(anything) {|agent_id| weather_agent_ids.delete(agent_id) }
  11. stub(Agents::WebsiteAgent).async_check(agents(:bob_website_agent).id)
  12. Agent.run_schedule("midnight")
  13. weather_agent_ids.should be_empty
  14. end
  15. it "groups agents by type" do
  16. mock(Agents::WeatherAgent).bulk_check("midnight").once
  17. mock(Agents::WebsiteAgent).bulk_check("midnight").once
  18. Agent.run_schedule("midnight")
  19. end
  20. it "only runs agents with the given schedule" do
  21. do_not_allow(Agents::WebsiteAgent).async_check
  22. Agent.run_schedule("blah")
  23. end
  24. it "will not run the 'never' schedule" do
  25. agents(:bob_weather_agent).update_attribute 'schedule', 'never'
  26. do_not_allow(Agents::WebsiteAgent).async_check
  27. Agent.run_schedule("never")
  28. end
  29. end
  30. describe "credential" do
  31. it "should return the value of the credential when credential is present" do
  32. agents(:bob_weather_agent).credential("aws_secret").should == user_credentials(:bob_aws_secret).credential_value
  33. end
  34. it "should return nil when credential is not present" do
  35. agents(:bob_weather_agent).credential("non_existing_credential").should == nil
  36. end
  37. it "should memoize the load" do
  38. mock.any_instance_of(UserCredential).credential_value.twice { "foo" }
  39. agents(:bob_weather_agent).credential("aws_secret").should == "foo"
  40. agents(:bob_weather_agent).credential("aws_secret").should == "foo"
  41. agents(:bob_weather_agent).reload
  42. agents(:bob_weather_agent).credential("aws_secret").should == "foo"
  43. agents(:bob_weather_agent).credential("aws_secret").should == "foo"
  44. end
  45. end
  46. describe "changes to type" do
  47. it "validates types" do
  48. source = Agent.new
  49. source.type = "Agents::WeatherAgent"
  50. source.should have(0).errors_on(:type)
  51. source.type = "Agents::WebsiteAgent"
  52. source.should have(0).errors_on(:type)
  53. source.type = "Agents::Fake"
  54. source.should have(1).error_on(:type)
  55. end
  56. it "disallows changes to type once a record has been saved" do
  57. source = agents(:bob_website_agent)
  58. source.type = "Agents::WeatherAgent"
  59. source.should have(1).error_on(:type)
  60. end
  61. it "should know about available types" do
  62. Agent.types.should include(Agents::WeatherAgent, Agents::WebsiteAgent)
  63. end
  64. end
  65. describe "with an example Agent" do
  66. class Agents::SomethingSource < Agent
  67. default_schedule "2pm"
  68. def check
  69. create_event :payload => {}
  70. end
  71. def validate_options
  72. errors.add(:base, "bad is bad") if options[:bad]
  73. end
  74. end
  75. class Agents::CannotBeScheduled < Agent
  76. cannot_be_scheduled!
  77. def receive(events)
  78. events.each do |event|
  79. create_event :payload => { :events_received => 1 }
  80. end
  81. end
  82. end
  83. before do
  84. stub(Agents::SomethingSource).valid_type?("Agents::SomethingSource") { true }
  85. stub(Agents::CannotBeScheduled).valid_type?("Agents::CannotBeScheduled") { true }
  86. end
  87. describe ".default_schedule" do
  88. it "stores the default on the class" do
  89. Agents::SomethingSource.default_schedule.should == "2pm"
  90. Agents::SomethingSource.new.default_schedule.should == "2pm"
  91. end
  92. it "sets the default on new instances, allows setting new schedules, and prevents invalid schedules" do
  93. @checker = Agents::SomethingSource.new(:name => "something")
  94. @checker.user = users(:bob)
  95. @checker.schedule.should == "2pm"
  96. @checker.save!
  97. @checker.reload.schedule.should == "2pm"
  98. @checker.update_attribute :schedule, "5pm"
  99. @checker.reload.schedule.should == "5pm"
  100. @checker.reload.schedule.should == "5pm"
  101. @checker.schedule = "this_is_not_real"
  102. @checker.should have(1).errors_on(:schedule)
  103. end
  104. it "should have an empty schedule if it cannot_be_scheduled" do
  105. @checker = Agents::CannotBeScheduled.new(:name => "something")
  106. @checker.user = users(:bob)
  107. @checker.schedule.should be_nil
  108. @checker.should be_valid
  109. @checker.schedule = "5pm"
  110. @checker.save!
  111. @checker.schedule.should be_nil
  112. @checker.schedule = "5pm"
  113. @checker.should have(0).errors_on(:schedule)
  114. @checker.schedule.should be_nil
  115. end
  116. end
  117. describe "#create_event" do
  118. before do
  119. @checker = Agents::SomethingSource.new(:name => "something")
  120. @checker.user = users(:bob)
  121. @checker.save!
  122. end
  123. it "should use the checker's user" do
  124. @checker.check
  125. Event.last.user.should == @checker.user
  126. end
  127. it "should log an error if the Agent has been marked with 'cannot_create_events!'" do
  128. mock(@checker).can_create_events? { false }
  129. lambda {
  130. @checker.check
  131. }.should_not change { Event.count }
  132. @checker.logs.first.message.should =~ /cannot create events/i
  133. end
  134. end
  135. describe ".async_check" do
  136. before do
  137. @checker = Agents::SomethingSource.new(:name => "something")
  138. @checker.user = users(:bob)
  139. @checker.save!
  140. end
  141. it "records last_check_at and calls check on the given Agent" do
  142. mock(@checker).check.once {
  143. @checker.options[:new] = true
  144. }
  145. mock(Agent).find(@checker.id) { @checker }
  146. @checker.last_check_at.should be_nil
  147. Agents::SomethingSource.async_check(@checker.id)
  148. @checker.reload.last_check_at.should be_within(2).of(Time.now)
  149. @checker.reload.options[:new].should be_true # Show that we save options
  150. end
  151. it "should log exceptions" do
  152. mock(@checker).check.once {
  153. raise "foo"
  154. }
  155. mock(Agent).find(@checker.id) { @checker }
  156. lambda {
  157. Agents::SomethingSource.async_check(@checker.id)
  158. }.should raise_error
  159. log = @checker.logs.first
  160. log.message.should =~ /Exception/
  161. log.level.should == 4
  162. end
  163. end
  164. describe ".receive! and .async_receive" do
  165. before do
  166. stub_request(:any, /wunderground/).to_return(:body => File.read(Rails.root.join("spec/data_fixtures/weather.json")), :status => 200)
  167. stub.any_instance_of(Agents::WeatherAgent).is_tomorrow?(anything) { true }
  168. end
  169. it "should use available events" do
  170. mock.any_instance_of(Agents::TriggerAgent).receive(anything).once
  171. Agent.async_check(agents(:bob_weather_agent).id)
  172. Agent.receive!
  173. end
  174. it "should log exceptions" do
  175. mock.any_instance_of(Agents::TriggerAgent).receive(anything).once {
  176. raise "foo"
  177. }
  178. Agent.async_check(agents(:bob_weather_agent).id)
  179. lambda {
  180. Agent.async_receive(agents(:bob_rain_notifier_agent).id, [agents(:bob_weather_agent).events.last.id])
  181. }.should raise_error
  182. log = agents(:bob_rain_notifier_agent).logs.first
  183. log.message.should =~ /Exception/
  184. log.level.should == 4
  185. end
  186. it "should track when events have been seen and not received them again" do
  187. mock.any_instance_of(Agents::TriggerAgent).receive(anything).once
  188. Agent.async_check(agents(:bob_weather_agent).id)
  189. Agent.receive!
  190. Agent.receive!
  191. end
  192. it "should not run consumers that have nothing to do" do
  193. do_not_allow.any_instance_of(Agents::TriggerAgent).receive(anything)
  194. Agent.receive!
  195. end
  196. it "should group events" do
  197. mock.any_instance_of(Agents::TriggerAgent).receive(anything).twice { |events|
  198. events.map(&:user).map(&:username).uniq.length.should == 1
  199. }
  200. Agent.async_check(agents(:bob_weather_agent).id)
  201. Agent.async_check(agents(:jane_weather_agent).id)
  202. Agent.receive!
  203. end
  204. end
  205. describe "creating a new agent and then calling .receive!" do
  206. it "should not backfill events for a newly created agent" do
  207. Event.delete_all
  208. sender = Agents::SomethingSource.new(:name => "Sending Agent")
  209. sender.user = users(:bob)
  210. sender.save!
  211. sender.create_event :payload => {}
  212. sender.create_event :payload => {}
  213. sender.events.count.should == 2
  214. receiver = Agents::CannotBeScheduled.new(:name => "Receiving Agent")
  215. receiver.user = users(:bob)
  216. receiver.sources << sender
  217. receiver.save!
  218. receiver.events.count.should == 0
  219. Agent.receive!
  220. receiver.events.count.should == 0
  221. sender.create_event :payload => {}
  222. Agent.receive!
  223. receiver.events.count.should == 1
  224. end
  225. end
  226. describe "validations" do
  227. it "calls validate_options" do
  228. agent = Agents::SomethingSource.new(:name => "something")
  229. agent.user = users(:bob)
  230. agent.options[:bad] = true
  231. agent.should have(1).error_on(:base)
  232. agent.options[:bad] = false
  233. agent.should have(0).errors_on(:base)
  234. end
  235. it "makes options symbol-indifferent before validating" do
  236. agent = Agents::SomethingSource.new(:name => "something")
  237. agent.user = users(:bob)
  238. agent.options["bad"] = true
  239. agent.should have(1).error_on(:base)
  240. agent.options["bad"] = false
  241. agent.should have(0).errors_on(:base)
  242. end
  243. it "makes memory symbol-indifferent before validating" do
  244. agent = Agents::SomethingSource.new(:name => "something")
  245. agent.user = users(:bob)
  246. agent.memory["bad"] = 2
  247. agent.save
  248. agent.memory[:bad].should == 2
  249. end
  250. it "should work when assigned a hash or JSON string" do
  251. agent = Agents::SomethingSource.new(:name => "something")
  252. agent.memory = {}
  253. agent.memory.should == {}
  254. agent.memory["foo"].should be_nil
  255. agent.memory = ""
  256. agent.memory["foo"].should be_nil
  257. agent.memory.should == {}
  258. agent.memory = '{"hi": "there"}'
  259. agent.memory.should == { "hi" => "there" }
  260. agent.memory = '{invalid}'
  261. agent.memory.should == { "hi" => "there" }
  262. agent.should have(1).errors_on(:memory)
  263. agent.memory = "{}"
  264. agent.memory["foo"].should be_nil
  265. agent.memory.should == {}
  266. agent.should have(0).errors_on(:memory)
  267. agent.options = "{}"
  268. agent.options["foo"].should be_nil
  269. agent.options.should == {}
  270. agent.should have(0).errors_on(:options)
  271. agent.options = '{"hi": 2}'
  272. agent.options["hi"].should == 2
  273. agent.should have(0).errors_on(:options)
  274. agent.options = '{"hi": wut}'
  275. agent.options["hi"].should == 2
  276. agent.should have(1).errors_on(:options)
  277. agent.errors_on(:options).should include("was assigned invalid JSON")
  278. agent.options = 5
  279. agent.options["hi"].should == 2
  280. agent.should have(1).errors_on(:options)
  281. agent.errors_on(:options).should include("cannot be set to an instance of Fixnum")
  282. end
  283. it "should not allow agents owned by other people" do
  284. agent = Agents::SomethingSource.new(:name => "something")
  285. agent.user = users(:bob)
  286. agent.source_ids = [agents(:bob_weather_agent).id]
  287. agent.should have(0).errors_on(:sources)
  288. agent.source_ids = [agents(:jane_weather_agent).id]
  289. agent.should have(1).errors_on(:sources)
  290. agent.user = users(:jane)
  291. agent.should have(0).errors_on(:sources)
  292. end
  293. it "validates keep_events_for" do
  294. agent = Agents::SomethingSource.new(:name => "something")
  295. agent.user = users(:bob)
  296. agent.should be_valid
  297. agent.keep_events_for = nil
  298. agent.should have(1).errors_on(:keep_events_for)
  299. agent.keep_events_for = 1000
  300. agent.should have(1).errors_on(:keep_events_for)
  301. agent.keep_events_for = ""
  302. agent.should have(1).errors_on(:keep_events_for)
  303. agent.keep_events_for = 5
  304. agent.should be_valid
  305. agent.keep_events_for = 0
  306. agent.should be_valid
  307. agent.keep_events_for = 365
  308. agent.should be_valid
  309. # Rails seems to call to_i on the input. This guards against future changes to that behavior.
  310. agent.keep_events_for = "drop table;"
  311. agent.keep_events_for.should == 0
  312. end
  313. end
  314. describe "cleaning up now-expired events" do
  315. before do
  316. @agent = Agents::SomethingSource.new(:name => "something")
  317. @agent.keep_events_for = 5
  318. @agent.user = users(:bob)
  319. @agent.save!
  320. @event = @agent.create_event :payload => { "hello" => "world" }
  321. @event.expires_at.to_i.should be_within(2).of(5.days.from_now.to_i)
  322. end
  323. describe "when keep_events_for has not changed" do
  324. it "does nothing" do
  325. mock(@agent).update_event_expirations!.times(0)
  326. @agent.options[:foo] = "bar1"
  327. @agent.save!
  328. @agent.options[:foo] = "bar1"
  329. @agent.keep_events_for = 5
  330. @agent.save!
  331. end
  332. end
  333. describe "when keep_events_for is changed" do
  334. it "updates events' expires_at" do
  335. lambda {
  336. @agent.options[:foo] = "bar1"
  337. @agent.keep_events_for = 3
  338. @agent.save!
  339. }.should change { @event.reload.expires_at }
  340. @event.expires_at.to_i.should be_within(2).of(3.days.from_now.to_i)
  341. end
  342. it "updates events relative to their created_at" do
  343. @event.update_attribute :created_at, 2.days.ago
  344. @event.reload.created_at.to_i.should be_within(2).of(2.days.ago.to_i)
  345. lambda {
  346. @agent.options[:foo] = "bar2"
  347. @agent.keep_events_for = 3
  348. @agent.save!
  349. }.should change { @event.reload.expires_at }
  350. @event.expires_at.to_i.should be_within(2).of(1.days.from_now.to_i)
  351. end
  352. it "nulls out expires_at when keep_events_for is set to 0" do
  353. lambda {
  354. @agent.options[:foo] = "bar"
  355. @agent.keep_events_for = 0
  356. @agent.save!
  357. }.should change { @event.reload.expires_at }.to(nil)
  358. end
  359. end
  360. end
  361. end
  362. describe "recent_error_logs?" do
  363. it "returns true if last_error_log_at is near last_event_at" do
  364. agent = Agent.new
  365. agent.last_error_log_at = 10.minutes.ago
  366. agent.last_event_at = 10.minutes.ago
  367. agent.recent_error_logs?.should be_true
  368. agent.last_error_log_at = 11.minutes.ago
  369. agent.last_event_at = 10.minutes.ago
  370. agent.recent_error_logs?.should be_true
  371. agent.last_error_log_at = 5.minutes.ago
  372. agent.last_event_at = 10.minutes.ago
  373. agent.recent_error_logs?.should be_true
  374. agent.last_error_log_at = 15.minutes.ago
  375. agent.last_event_at = 10.minutes.ago
  376. agent.recent_error_logs?.should be_false
  377. agent.last_error_log_at = 2.days.ago
  378. agent.last_event_at = 10.minutes.ago
  379. agent.recent_error_logs?.should be_false
  380. end
  381. end
  382. describe "scopes" do
  383. describe "of_type" do
  384. it "should accept classes" do
  385. agents = Agent.of_type(Agents::WebsiteAgent)
  386. agents.should include(agents(:bob_website_agent))
  387. agents.should include(agents(:jane_website_agent))
  388. agents.should_not include(agents(:bob_weather_agent))
  389. end
  390. it "should accept strings" do
  391. agents = Agent.of_type("Agents::WebsiteAgent")
  392. agents.should include(agents(:bob_website_agent))
  393. agents.should include(agents(:jane_website_agent))
  394. agents.should_not include(agents(:bob_weather_agent))
  395. end
  396. it "should accept instances of an Agent" do
  397. agents = Agent.of_type(agents(:bob_website_agent))
  398. agents.should include(agents(:bob_website_agent))
  399. agents.should include(agents(:jane_website_agent))
  400. agents.should_not include(agents(:bob_weather_agent))
  401. end
  402. end
  403. end
  404. describe "#create_event" do
  405. describe "when the agent has keep_events_for set" do
  406. before do
  407. agents(:jane_weather_agent).keep_events_for.should > 0
  408. end
  409. it "sets expires_at on created events" do
  410. event = agents(:jane_weather_agent).create_event :payload => { 'hi' => 'there' }
  411. event.expires_at.to_i.should be_within(5).of(agents(:jane_weather_agent).keep_events_for.days.from_now.to_i)
  412. end
  413. end
  414. describe "when the agent does not have keep_events_for set" do
  415. before do
  416. agents(:jane_website_agent).keep_events_for.should == 0
  417. end
  418. it "does not set expires_at on created events" do
  419. event = agents(:jane_website_agent).create_event :payload => { 'hi' => 'there' }
  420. event.expires_at.should be_nil
  421. end
  422. end
  423. end
  424. end