agent_spec.rb 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  1. require 'spec_helper'
  2. describe Agent do
  3. it_behaves_like WorkingHelpers
  4. describe ".bulk_check" do
  5. before do
  6. @weather_agent_count = Agents::WeatherAgent.where(:schedule => "midnight", :disabled => false).count
  7. end
  8. it "should run all Agents with the given schedule" do
  9. mock(Agents::WeatherAgent).async_check(anything).times(@weather_agent_count)
  10. Agents::WeatherAgent.bulk_check("midnight")
  11. end
  12. it "should skip disabled Agents" do
  13. agents(:bob_weather_agent).update_attribute :disabled, true
  14. mock(Agents::WeatherAgent).async_check(anything).times(@weather_agent_count - 1)
  15. Agents::WeatherAgent.bulk_check("midnight")
  16. end
  17. end
  18. describe ".run_schedule" do
  19. before do
  20. Agents::WeatherAgent.count.should > 0
  21. Agents::WebsiteAgent.count.should > 0
  22. end
  23. it "runs agents with the given schedule" do
  24. weather_agent_ids = [agents(:bob_weather_agent), agents(:jane_weather_agent)].map(&:id)
  25. stub(Agents::WeatherAgent).async_check(anything) {|agent_id| weather_agent_ids.delete(agent_id) }
  26. stub(Agents::WebsiteAgent).async_check(agents(:bob_website_agent).id)
  27. Agent.run_schedule("midnight")
  28. weather_agent_ids.should be_empty
  29. end
  30. it "groups agents by type" do
  31. mock(Agents::WeatherAgent).bulk_check("midnight").once
  32. mock(Agents::WebsiteAgent).bulk_check("midnight").once
  33. Agent.run_schedule("midnight")
  34. end
  35. it "only runs agents with the given schedule" do
  36. do_not_allow(Agents::WebsiteAgent).async_check
  37. Agent.run_schedule("blah")
  38. end
  39. it "will not run the 'never' schedule" do
  40. agents(:bob_weather_agent).update_attribute 'schedule', 'never'
  41. do_not_allow(Agents::WebsiteAgent).async_check
  42. Agent.run_schedule("never")
  43. end
  44. end
  45. describe "credential" do
  46. it "should return the value of the credential when credential is present" do
  47. agents(:bob_weather_agent).credential("aws_secret").should == user_credentials(:bob_aws_secret).credential_value
  48. end
  49. it "should return nil when credential is not present" do
  50. agents(:bob_weather_agent).credential("non_existing_credential").should == nil
  51. end
  52. it "should memoize the load" do
  53. mock.any_instance_of(UserCredential).credential_value.twice { "foo" }
  54. agents(:bob_weather_agent).credential("aws_secret").should == "foo"
  55. agents(:bob_weather_agent).credential("aws_secret").should == "foo"
  56. agents(:bob_weather_agent).reload
  57. agents(:bob_weather_agent).credential("aws_secret").should == "foo"
  58. agents(:bob_weather_agent).credential("aws_secret").should == "foo"
  59. end
  60. end
  61. describe "changes to type" do
  62. it "validates types" do
  63. source = Agent.new
  64. source.type = "Agents::WeatherAgent"
  65. source.should have(0).errors_on(:type)
  66. source.type = "Agents::WebsiteAgent"
  67. source.should have(0).errors_on(:type)
  68. source.type = "Agents::Fake"
  69. source.should have(1).error_on(:type)
  70. end
  71. it "disallows changes to type once a record has been saved" do
  72. source = agents(:bob_website_agent)
  73. source.type = "Agents::WeatherAgent"
  74. source.should have(1).error_on(:type)
  75. end
  76. it "should know about available types" do
  77. Agent.types.should include(Agents::WeatherAgent, Agents::WebsiteAgent)
  78. end
  79. end
  80. describe "with an example Agent" do
  81. class Agents::SomethingSource < Agent
  82. default_schedule "2pm"
  83. def check
  84. create_event :payload => {}
  85. end
  86. def validate_options
  87. errors.add(:base, "bad is bad") if options[:bad]
  88. end
  89. end
  90. class Agents::CannotBeScheduled < Agent
  91. cannot_be_scheduled!
  92. def receive(events)
  93. events.each do |event|
  94. create_event :payload => { :events_received => 1 }
  95. end
  96. end
  97. end
  98. before do
  99. stub(Agents::SomethingSource).valid_type?("Agents::SomethingSource") { true }
  100. stub(Agents::CannotBeScheduled).valid_type?("Agents::CannotBeScheduled") { true }
  101. end
  102. describe Agents::SomethingSource do
  103. let(:new_instance) do
  104. agent = Agents::SomethingSource.new(:name => "some agent")
  105. agent.user = users(:bob)
  106. agent
  107. end
  108. it_behaves_like LiquidInterpolatable
  109. it_behaves_like HasGuid
  110. end
  111. describe ".short_type" do
  112. it "returns a short name without 'Agents::'" do
  113. Agents::SomethingSource.new.short_type.should == "SomethingSource"
  114. Agents::CannotBeScheduled.new.short_type.should == "CannotBeScheduled"
  115. end
  116. end
  117. describe ".default_schedule" do
  118. it "stores the default on the class" do
  119. Agents::SomethingSource.default_schedule.should == "2pm"
  120. Agents::SomethingSource.new.default_schedule.should == "2pm"
  121. end
  122. it "sets the default on new instances, allows setting new schedules, and prevents invalid schedules" do
  123. @checker = Agents::SomethingSource.new(:name => "something")
  124. @checker.user = users(:bob)
  125. @checker.schedule.should == "2pm"
  126. @checker.save!
  127. @checker.reload.schedule.should == "2pm"
  128. @checker.update_attribute :schedule, "5pm"
  129. @checker.reload.schedule.should == "5pm"
  130. @checker.reload.schedule.should == "5pm"
  131. @checker.schedule = "this_is_not_real"
  132. @checker.should have(1).errors_on(:schedule)
  133. end
  134. it "should have an empty schedule if it cannot_be_scheduled" do
  135. @checker = Agents::CannotBeScheduled.new(:name => "something")
  136. @checker.user = users(:bob)
  137. @checker.schedule.should be_nil
  138. @checker.should be_valid
  139. @checker.schedule = "5pm"
  140. @checker.save!
  141. @checker.schedule.should be_nil
  142. @checker.schedule = "5pm"
  143. @checker.should have(0).errors_on(:schedule)
  144. @checker.schedule.should be_nil
  145. end
  146. end
  147. describe "#create_event" do
  148. before do
  149. @checker = Agents::SomethingSource.new(:name => "something")
  150. @checker.user = users(:bob)
  151. @checker.save!
  152. end
  153. it "should use the checker's user" do
  154. @checker.check
  155. Event.last.user.should == @checker.user
  156. end
  157. it "should log an error if the Agent has been marked with 'cannot_create_events!'" do
  158. mock(@checker).can_create_events? { false }
  159. lambda {
  160. @checker.check
  161. }.should_not change { Event.count }
  162. @checker.logs.first.message.should =~ /cannot create events/i
  163. end
  164. end
  165. describe ".async_check" do
  166. before do
  167. @checker = Agents::SomethingSource.new(:name => "something")
  168. @checker.user = users(:bob)
  169. @checker.save!
  170. end
  171. it "records last_check_at and calls check on the given Agent" do
  172. mock(@checker).check.once {
  173. @checker.options[:new] = true
  174. }
  175. mock(Agent).find(@checker.id) { @checker }
  176. @checker.last_check_at.should be_nil
  177. Agents::SomethingSource.async_check(@checker.id)
  178. @checker.reload.last_check_at.should be_within(2).of(Time.now)
  179. @checker.reload.options[:new].should be_truthy # Show that we save options
  180. end
  181. it "should log exceptions" do
  182. mock(@checker).check.once {
  183. raise "foo"
  184. }
  185. mock(Agent).find(@checker.id) { @checker }
  186. lambda {
  187. Agents::SomethingSource.async_check(@checker.id)
  188. }.should raise_error
  189. log = @checker.logs.first
  190. log.message.should =~ /Exception/
  191. log.level.should == 4
  192. end
  193. it "should not run disabled Agents" do
  194. mock(Agent).find(agents(:bob_weather_agent).id) { agents(:bob_weather_agent) }
  195. do_not_allow(agents(:bob_weather_agent)).check
  196. agents(:bob_weather_agent).update_attribute :disabled, true
  197. Agent.async_check(agents(:bob_weather_agent).id)
  198. end
  199. end
  200. describe ".receive!" do
  201. before do
  202. stub_request(:any, /wunderground/).to_return(:body => File.read(Rails.root.join("spec/data_fixtures/weather.json")), :status => 200)
  203. stub.any_instance_of(Agents::WeatherAgent).is_tomorrow?(anything) { true }
  204. end
  205. it "should use available events" do
  206. Agent.async_check(agents(:bob_weather_agent).id)
  207. mock(Agent).async_receive(agents(:bob_rain_notifier_agent).id, anything).times(1)
  208. Agent.receive!
  209. end
  210. it "should not propogate to disabled Agents" do
  211. Agent.async_check(agents(:bob_weather_agent).id)
  212. agents(:bob_rain_notifier_agent).update_attribute :disabled, true
  213. mock(Agent).async_receive(agents(:bob_rain_notifier_agent).id, anything).times(0)
  214. Agent.receive!
  215. end
  216. it "should log exceptions" do
  217. mock.any_instance_of(Agents::TriggerAgent).receive(anything).once {
  218. raise "foo"
  219. }
  220. Agent.async_check(agents(:bob_weather_agent).id)
  221. lambda {
  222. Agent.async_receive(agents(:bob_rain_notifier_agent).id, [agents(:bob_weather_agent).events.last.id])
  223. }.should raise_error
  224. log = agents(:bob_rain_notifier_agent).logs.first
  225. log.message.should =~ /Exception/
  226. log.level.should == 4
  227. end
  228. it "should track when events have been seen and not received them again" do
  229. mock.any_instance_of(Agents::TriggerAgent).receive(anything).once
  230. Agent.async_check(agents(:bob_weather_agent).id)
  231. lambda {
  232. Agent.receive!
  233. }.should change { agents(:bob_rain_notifier_agent).reload.last_checked_event_id }
  234. lambda {
  235. Agent.receive!
  236. }.should_not change { agents(:bob_rain_notifier_agent).reload.last_checked_event_id }
  237. end
  238. it "should not run consumers that have nothing to do" do
  239. do_not_allow.any_instance_of(Agents::TriggerAgent).receive(anything)
  240. Agent.receive!
  241. end
  242. it "should group events" do
  243. mock.any_instance_of(Agents::TriggerAgent).receive(anything).twice { |events|
  244. events.map(&:user).map(&:username).uniq.length.should == 1
  245. }
  246. Agent.async_check(agents(:bob_weather_agent).id)
  247. Agent.async_check(agents(:jane_weather_agent).id)
  248. Agent.receive!
  249. end
  250. it "should ignore events that were created before a particular Link" do
  251. agent2 = Agents::SomethingSource.new(:name => "something")
  252. agent2.user = users(:bob)
  253. agent2.save!
  254. agent2.check
  255. mock.any_instance_of(Agents::TriggerAgent).receive(anything).twice
  256. agents(:bob_weather_agent).check # bob_weather_agent makes an event
  257. lambda {
  258. Agent.receive! # event gets propagated
  259. }.should change { agents(:bob_rain_notifier_agent).reload.last_checked_event_id }
  260. # This agent creates a few events before we link to it, but after our last check.
  261. agent2.check
  262. agent2.check
  263. # Now we link to it.
  264. agents(:bob_rain_notifier_agent).sources << agent2
  265. agent2.links_as_source.first.event_id_at_creation.should == agent2.events.reorder("events.id desc").first.id
  266. lambda {
  267. Agent.receive! # but we don't receive those events because they're too old
  268. }.should_not change { agents(:bob_rain_notifier_agent).reload.last_checked_event_id }
  269. # Now a new event is created by agent2
  270. agent2.check
  271. lambda {
  272. Agent.receive! # and we receive it
  273. }.should change { agents(:bob_rain_notifier_agent).reload.last_checked_event_id }
  274. end
  275. end
  276. describe ".async_receive" do
  277. it "should not run disabled Agents" do
  278. mock(Agent).find(agents(:bob_rain_notifier_agent).id) { agents(:bob_rain_notifier_agent) }
  279. do_not_allow(agents(:bob_rain_notifier_agent)).receive
  280. agents(:bob_rain_notifier_agent).update_attribute :disabled, true
  281. Agent.async_receive(agents(:bob_rain_notifier_agent).id, [1, 2, 3])
  282. end
  283. end
  284. describe "creating a new agent and then calling .receive!" do
  285. it "should not backfill events for a newly created agent" do
  286. Event.delete_all
  287. sender = Agents::SomethingSource.new(:name => "Sending Agent")
  288. sender.user = users(:bob)
  289. sender.save!
  290. sender.create_event :payload => {}
  291. sender.create_event :payload => {}
  292. sender.events.count.should == 2
  293. receiver = Agents::CannotBeScheduled.new(:name => "Receiving Agent")
  294. receiver.user = users(:bob)
  295. receiver.sources << sender
  296. receiver.save!
  297. receiver.events.count.should == 0
  298. Agent.receive!
  299. receiver.events.count.should == 0
  300. sender.create_event :payload => {}
  301. Agent.receive!
  302. receiver.events.count.should == 1
  303. end
  304. end
  305. describe "creating agents with propagate_immediately = true" do
  306. it "should schedule subagent events immediately" do
  307. Event.delete_all
  308. sender = Agents::SomethingSource.new(:name => "Sending Agent")
  309. sender.user = users(:bob)
  310. sender.save!
  311. receiver = Agents::CannotBeScheduled.new(
  312. :name => "Receiving Agent",
  313. )
  314. receiver.propagate_immediately = true
  315. receiver.user = users(:bob)
  316. receiver.sources << sender
  317. receiver.save!
  318. sender.create_event :payload => {"message" => "new payload"}
  319. sender.events.count.should == 1
  320. receiver.events.count.should == 1
  321. #should be true without calling Agent.receive!
  322. end
  323. it "should only schedule receiving agents that are set to propagate_immediately" do
  324. Event.delete_all
  325. sender = Agents::SomethingSource.new(:name => "Sending Agent")
  326. sender.user = users(:bob)
  327. sender.save!
  328. im_receiver = Agents::CannotBeScheduled.new(
  329. :name => "Immediate Receiving Agent",
  330. )
  331. im_receiver.propagate_immediately = true
  332. im_receiver.user = users(:bob)
  333. im_receiver.sources << sender
  334. im_receiver.save!
  335. slow_receiver = Agents::CannotBeScheduled.new(
  336. :name => "Slow Receiving Agent",
  337. )
  338. slow_receiver.user = users(:bob)
  339. slow_receiver.sources << sender
  340. slow_receiver.save!
  341. sender.create_event :payload => {"message" => "new payload"}
  342. sender.events.count.should == 1
  343. im_receiver.events.count.should == 1
  344. #we should get the quick one
  345. #but not the slow one
  346. slow_receiver.events.count.should == 0
  347. Agent.receive!
  348. #now we should have one in both
  349. im_receiver.events.count.should == 1
  350. slow_receiver.events.count.should == 1
  351. end
  352. end
  353. describe "validations" do
  354. it "calls validate_options" do
  355. agent = Agents::SomethingSource.new(:name => "something")
  356. agent.user = users(:bob)
  357. agent.options[:bad] = true
  358. agent.should have(1).error_on(:base)
  359. agent.options[:bad] = false
  360. agent.should have(0).errors_on(:base)
  361. end
  362. it "makes options symbol-indifferent before validating" do
  363. agent = Agents::SomethingSource.new(:name => "something")
  364. agent.user = users(:bob)
  365. agent.options["bad"] = true
  366. agent.should have(1).error_on(:base)
  367. agent.options["bad"] = false
  368. agent.should have(0).errors_on(:base)
  369. end
  370. it "makes memory symbol-indifferent before validating" do
  371. agent = Agents::SomethingSource.new(:name => "something")
  372. agent.user = users(:bob)
  373. agent.memory["bad"] = 2
  374. agent.save
  375. agent.memory[:bad].should == 2
  376. end
  377. it "should work when assigned a hash or JSON string" do
  378. agent = Agents::SomethingSource.new(:name => "something")
  379. agent.memory = {}
  380. agent.memory.should == {}
  381. agent.memory["foo"].should be_nil
  382. agent.memory = ""
  383. agent.memory["foo"].should be_nil
  384. agent.memory.should == {}
  385. agent.memory = '{"hi": "there"}'
  386. agent.memory.should == { "hi" => "there" }
  387. agent.memory = '{invalid}'
  388. agent.memory.should == { "hi" => "there" }
  389. agent.should have(1).errors_on(:memory)
  390. agent.memory = "{}"
  391. agent.memory["foo"].should be_nil
  392. agent.memory.should == {}
  393. agent.should have(0).errors_on(:memory)
  394. agent.options = "{}"
  395. agent.options["foo"].should be_nil
  396. agent.options.should == {}
  397. agent.should have(0).errors_on(:options)
  398. agent.options = '{"hi": 2}'
  399. agent.options["hi"].should == 2
  400. agent.should have(0).errors_on(:options)
  401. agent.options = '{"hi": wut}'
  402. agent.options["hi"].should == 2
  403. agent.should have(1).errors_on(:options)
  404. agent.errors_on(:options).should include("was assigned invalid JSON")
  405. agent.options = 5
  406. agent.options["hi"].should == 2
  407. agent.should have(1).errors_on(:options)
  408. agent.errors_on(:options).should include("cannot be set to an instance of Fixnum")
  409. end
  410. it "should not allow source agents owned by other people" do
  411. agent = Agents::SomethingSource.new(:name => "something")
  412. agent.user = users(:bob)
  413. agent.source_ids = [agents(:bob_weather_agent).id]
  414. agent.should have(0).errors_on(:sources)
  415. agent.source_ids = [agents(:jane_weather_agent).id]
  416. agent.should have(1).errors_on(:sources)
  417. agent.user = users(:jane)
  418. agent.should have(0).errors_on(:sources)
  419. end
  420. it "should not allow controller agents owned by other people" do
  421. agent = Agents::SomethingSource.new(:name => "something")
  422. agent.user = users(:bob)
  423. agent.controller_ids = [agents(:bob_weather_agent).id]
  424. agent.should have(0).errors_on(:controllers)
  425. agent.controller_ids = [agents(:jane_weather_agent).id]
  426. agent.should have(1).errors_on(:controllers)
  427. agent.user = users(:jane)
  428. agent.should have(0).errors_on(:controllers)
  429. end
  430. it "should not allow control target agents owned by other people" do
  431. agent = Agents::CannotBeScheduled.new(:name => "something")
  432. agent.user = users(:bob)
  433. agent.control_target_ids = [agents(:bob_weather_agent).id]
  434. agent.should have(0).errors_on(:control_targets)
  435. agent.control_target_ids = [agents(:jane_weather_agent).id]
  436. agent.should have(1).errors_on(:control_targets)
  437. agent.user = users(:jane)
  438. agent.should have(0).errors_on(:control_targets)
  439. end
  440. it "should not allow scenarios owned by other people" do
  441. agent = Agents::SomethingSource.new(:name => "something")
  442. agent.user = users(:bob)
  443. agent.scenario_ids = [scenarios(:bob_weather).id]
  444. agent.should have(0).errors_on(:scenarios)
  445. agent.scenario_ids = [scenarios(:bob_weather).id, scenarios(:jane_weather).id]
  446. agent.should have(1).errors_on(:scenarios)
  447. agent.scenario_ids = [scenarios(:jane_weather).id]
  448. agent.should have(1).errors_on(:scenarios)
  449. agent.user = users(:jane)
  450. agent.should have(0).errors_on(:scenarios)
  451. end
  452. it "validates keep_events_for" do
  453. agent = Agents::SomethingSource.new(:name => "something")
  454. agent.user = users(:bob)
  455. agent.should be_valid
  456. agent.keep_events_for = nil
  457. agent.should have(1).errors_on(:keep_events_for)
  458. agent.keep_events_for = 1000
  459. agent.should have(1).errors_on(:keep_events_for)
  460. agent.keep_events_for = ""
  461. agent.should have(1).errors_on(:keep_events_for)
  462. agent.keep_events_for = 5
  463. agent.should be_valid
  464. agent.keep_events_for = 0
  465. agent.should be_valid
  466. agent.keep_events_for = 365
  467. agent.should be_valid
  468. # Rails seems to call to_i on the input. This guards against future changes to that behavior.
  469. agent.keep_events_for = "drop table;"
  470. agent.keep_events_for.should == 0
  471. end
  472. end
  473. describe "cleaning up now-expired events" do
  474. before do
  475. @agent = Agents::SomethingSource.new(:name => "something")
  476. @agent.keep_events_for = 5
  477. @agent.user = users(:bob)
  478. @agent.save!
  479. @event = @agent.create_event :payload => { "hello" => "world" }
  480. @event.expires_at.to_i.should be_within(2).of(5.days.from_now.to_i)
  481. end
  482. describe "when keep_events_for has not changed" do
  483. it "does nothing" do
  484. mock(@agent).update_event_expirations!.times(0)
  485. @agent.options[:foo] = "bar1"
  486. @agent.save!
  487. @agent.options[:foo] = "bar1"
  488. @agent.keep_events_for = 5
  489. @agent.save!
  490. end
  491. end
  492. describe "when keep_events_for is changed" do
  493. it "updates events' expires_at" do
  494. lambda {
  495. @agent.options[:foo] = "bar1"
  496. @agent.keep_events_for = 3
  497. @agent.save!
  498. }.should change { @event.reload.expires_at }
  499. @event.expires_at.to_i.should be_within(2).of(3.days.from_now.to_i)
  500. end
  501. it "updates events relative to their created_at" do
  502. @event.update_attribute :created_at, 2.days.ago
  503. @event.reload.created_at.to_i.should be_within(2).of(2.days.ago.to_i)
  504. lambda {
  505. @agent.options[:foo] = "bar2"
  506. @agent.keep_events_for = 3
  507. @agent.save!
  508. }.should change { @event.reload.expires_at }
  509. @event.expires_at.to_i.should be_within(60 * 61).of(1.days.from_now.to_i) # The larger time is to deal with daylight savings
  510. end
  511. it "nulls out expires_at when keep_events_for is set to 0" do
  512. lambda {
  513. @agent.options[:foo] = "bar"
  514. @agent.keep_events_for = 0
  515. @agent.save!
  516. }.should change { @event.reload.expires_at }.to(nil)
  517. end
  518. end
  519. end
  520. describe "Agent.build_clone" do
  521. before do
  522. Event.delete_all
  523. @sender = Agents::SomethingSource.new(
  524. name: 'Agent (2)',
  525. options: { foo: 'bar2' },
  526. schedule: '5pm')
  527. @sender.user = users(:bob)
  528. @sender.save!
  529. @sender.create_event :payload => {}
  530. @sender.create_event :payload => {}
  531. @sender.events.count.should == 2
  532. @receiver = Agents::CannotBeScheduled.new(
  533. name: 'Agent',
  534. options: { foo: 'bar3' },
  535. keep_events_for: 3,
  536. propagate_immediately: true)
  537. @receiver.user = users(:bob)
  538. @receiver.sources << @sender
  539. @receiver.memory[:test] = 1
  540. @receiver.save!
  541. end
  542. it "should create a clone of a given agent for editing" do
  543. sender_clone = users(:bob).agents.build_clone(@sender)
  544. sender_clone.attributes.should == Agent.new.attributes.
  545. update(@sender.slice(:user_id, :type,
  546. :options, :schedule, :keep_events_for, :propagate_immediately)).
  547. update('name' => 'Agent (2) (2)', 'options' => { 'foo' => 'bar2' })
  548. sender_clone.source_ids.should == []
  549. receiver_clone = users(:bob).agents.build_clone(@receiver)
  550. receiver_clone.attributes.should == Agent.new.attributes.
  551. update(@receiver.slice(:user_id, :type,
  552. :options, :schedule, :keep_events_for, :propagate_immediately)).
  553. update('name' => 'Agent (3)', 'options' => { 'foo' => 'bar3' })
  554. receiver_clone.source_ids.should == [@sender.id]
  555. end
  556. end
  557. end
  558. describe ".trigger_web_request" do
  559. class Agents::WebRequestReceiver < Agent
  560. cannot_be_scheduled!
  561. end
  562. before do
  563. stub(Agents::WebRequestReceiver).valid_type?("Agents::WebRequestReceiver") { true }
  564. end
  565. context "when .receive_web_request is defined" do
  566. before do
  567. @agent = Agents::WebRequestReceiver.new(:name => "something")
  568. @agent.user = users(:bob)
  569. @agent.save!
  570. def @agent.receive_web_request(params, method, format)
  571. memory['last_request'] = [params, method, format]
  572. ['Ok!', 200]
  573. end
  574. end
  575. it "calls the .receive_web_request hook, updates last_web_request_at, and saves" do
  576. @agent.trigger_web_request({ :some_param => "some_value" }, "post", "text/html")
  577. @agent.reload.memory['last_request'].should == [ { "some_param" => "some_value" }, "post", "text/html" ]
  578. @agent.last_web_request_at.to_i.should be_within(1).of(Time.now.to_i)
  579. end
  580. end
  581. context "when .receive_webhook is defined" do
  582. before do
  583. @agent = Agents::WebRequestReceiver.new(:name => "something")
  584. @agent.user = users(:bob)
  585. @agent.save!
  586. def @agent.receive_webhook(params)
  587. memory['last_webhook_request'] = params
  588. ['Ok!', 200]
  589. end
  590. end
  591. it "outputs a deprecation warning and calls .receive_webhook with the params" do
  592. mock(Rails.logger).warn("DEPRECATED: The .receive_webhook method is deprecated, please switch your Agent to use .receive_web_request.")
  593. @agent.trigger_web_request({ :some_param => "some_value" }, "post", "text/html")
  594. @agent.reload.memory['last_webhook_request'].should == { "some_param" => "some_value" }
  595. @agent.last_web_request_at.to_i.should be_within(1).of(Time.now.to_i)
  596. end
  597. end
  598. end
  599. describe "scopes" do
  600. describe "of_type" do
  601. it "should accept classes" do
  602. agents = Agent.of_type(Agents::WebsiteAgent)
  603. agents.should include(agents(:bob_website_agent))
  604. agents.should include(agents(:jane_website_agent))
  605. agents.should_not include(agents(:bob_weather_agent))
  606. end
  607. it "should accept strings" do
  608. agents = Agent.of_type("Agents::WebsiteAgent")
  609. agents.should include(agents(:bob_website_agent))
  610. agents.should include(agents(:jane_website_agent))
  611. agents.should_not include(agents(:bob_weather_agent))
  612. end
  613. it "should accept instances of an Agent" do
  614. agents = Agent.of_type(agents(:bob_website_agent))
  615. agents.should include(agents(:bob_website_agent))
  616. agents.should include(agents(:jane_website_agent))
  617. agents.should_not include(agents(:bob_weather_agent))
  618. end
  619. end
  620. end
  621. describe "#create_event" do
  622. describe "when the agent has keep_events_for set" do
  623. before do
  624. agents(:jane_weather_agent).keep_events_for.should > 0
  625. end
  626. it "sets expires_at on created events" do
  627. event = agents(:jane_weather_agent).create_event :payload => { 'hi' => 'there' }
  628. event.expires_at.to_i.should be_within(5).of(agents(:jane_weather_agent).keep_events_for.days.from_now.to_i)
  629. end
  630. end
  631. describe "when the agent does not have keep_events_for set" do
  632. before do
  633. agents(:jane_website_agent).keep_events_for.should == 0
  634. end
  635. it "does not set expires_at on created events" do
  636. event = agents(:jane_website_agent).create_event :payload => { 'hi' => 'there' }
  637. event.expires_at.should be_nil
  638. end
  639. end
  640. end
  641. describe '.last_checked_event_id' do
  642. it "should be updated by setting drop_pending_events to true" do
  643. agent = agents(:bob_rain_notifier_agent)
  644. agent.last_checked_event_id = nil
  645. agent.save!
  646. agent.update!(drop_pending_events: true)
  647. agent.reload.last_checked_event_id.should == Event.maximum(:id)
  648. end
  649. it "should not affect a virtual attribute drop_pending_events" do
  650. agent = agents(:bob_rain_notifier_agent)
  651. agent.update!(drop_pending_events: true)
  652. agent.reload.drop_pending_events.should == false
  653. end
  654. end
  655. describe ".drop_pending_events" do
  656. before do
  657. stub_request(:any, /wunderground/).to_return(body: File.read(Rails.root.join("spec/data_fixtures/weather.json")), status: 200)
  658. stub.any_instance_of(Agents::WeatherAgent).is_tomorrow?(anything) { true }
  659. end
  660. it "should drop pending events while the agent was disabled when set to true" do
  661. agent1 = agents(:bob_weather_agent)
  662. agent2 = agents(:bob_rain_notifier_agent)
  663. -> {
  664. -> {
  665. Agent.async_check(agent1.id)
  666. Agent.receive!
  667. }.should change { agent1.events.count }.by(1)
  668. }.should change { agent2.events.count }.by(1)
  669. agent2.disabled = true
  670. agent2.save!
  671. -> {
  672. -> {
  673. Agent.async_check(agent1.id)
  674. Agent.receive!
  675. }.should change { agent1.events.count }.by(1)
  676. }.should_not change { agent2.events.count }
  677. agent2.disabled = false
  678. agent2.drop_pending_events = true
  679. agent2.save!
  680. -> {
  681. Agent.receive!
  682. }.should_not change { agent2.events.count }
  683. end
  684. end
  685. end
  686. describe AgentDrop do
  687. def interpolate(string, agent)
  688. agent.interpolate_string(string, "agent" => agent)
  689. end
  690. before do
  691. @wsa1 = Agents::WebsiteAgent.new(
  692. name: 'XKCD',
  693. options: {
  694. expected_update_period_in_days: 2,
  695. type: 'html',
  696. url: 'http://xkcd.com/',
  697. mode: 'on_change',
  698. extract: {
  699. url: { css: '#comic img', value: '@src' },
  700. title: { css: '#comic img', value: '@alt' },
  701. },
  702. },
  703. schedule: 'every_1h',
  704. keep_events_for: 2)
  705. @wsa1.user = users(:bob)
  706. @wsa1.save!
  707. @wsa2 = Agents::WebsiteAgent.new(
  708. name: 'Dilbert',
  709. options: {
  710. expected_update_period_in_days: 2,
  711. type: 'html',
  712. url: 'http://dilbert.com/',
  713. mode: 'on_change',
  714. extract: {
  715. url: { css: '[id^=strip_enlarged_] img', value: '@src' },
  716. title: { css: '.STR_DateStrip', value: './/text()' },
  717. },
  718. },
  719. schedule: 'every_12h',
  720. keep_events_for: 2)
  721. @wsa2.user = users(:bob)
  722. @wsa2.save!
  723. @efa = Agents::EventFormattingAgent.new(
  724. name: 'Formatter',
  725. options: {
  726. instructions: {
  727. message: '{{agent.name}}: {{title}} {{url}}',
  728. agent: '{{agent.type}}',
  729. },
  730. mode: 'clean',
  731. matchers: [],
  732. skip_created_at: 'false',
  733. },
  734. keep_events_for: 2,
  735. propagate_immediately: true)
  736. @efa.user = users(:bob)
  737. @efa.sources << @wsa1 << @wsa2
  738. @efa.memory[:test] = 1
  739. @efa.save!
  740. end
  741. it 'should be created via Agent#to_liquid' do
  742. @wsa1.to_liquid.class.should be(AgentDrop)
  743. @wsa2.to_liquid.class.should be(AgentDrop)
  744. @efa.to_liquid.class.should be(AgentDrop)
  745. end
  746. it 'should have .type and .name' do
  747. t = '{{agent.type}}: {{agent.name}}'
  748. interpolate(t, @wsa1).should eq('WebsiteAgent: XKCD')
  749. interpolate(t, @wsa2).should eq('WebsiteAgent: Dilbert')
  750. interpolate(t, @efa).should eq('EventFormattingAgent: Formatter')
  751. end
  752. it 'should have .options' do
  753. t = '{{agent.options.url}}'
  754. interpolate(t, @wsa1).should eq('http://xkcd.com/')
  755. interpolate(t, @wsa2).should eq('http://dilbert.com/')
  756. interpolate('{{agent.options.instructions.message}}',
  757. @efa).should eq('{{agent.name}}: {{title}} {{url}}')
  758. end
  759. it 'should have .sources' do
  760. t = '{{agent.sources.size}}: {{agent.sources | map:"name" | join:", "}}'
  761. interpolate(t, @wsa1).should eq('0: ')
  762. interpolate(t, @wsa2).should eq('0: ')
  763. interpolate(t, @efa).should eq('2: XKCD, Dilbert')
  764. end
  765. it 'should have .receivers' do
  766. t = '{{agent.receivers.size}}: {{agent.receivers | map:"name" | join:", "}}'
  767. interpolate(t, @wsa1).should eq('1: Formatter')
  768. interpolate(t, @wsa2).should eq('1: Formatter')
  769. interpolate(t, @efa).should eq('0: ')
  770. end
  771. end