Aucune description http://j1x-huginn.herokuapp.com

agent_spec.rb 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  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 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 scenarios owned by other people" do
  421. agent = Agents::SomethingSource.new(:name => "something")
  422. agent.user = users(:bob)
  423. agent.scenario_ids = [scenarios(:bob_weather).id]
  424. agent.should have(0).errors_on(:scenarios)
  425. agent.scenario_ids = [scenarios(:bob_weather).id, scenarios(:jane_weather).id]
  426. agent.should have(1).errors_on(:scenarios)
  427. agent.scenario_ids = [scenarios(:jane_weather).id]
  428. agent.should have(1).errors_on(:scenarios)
  429. agent.user = users(:jane)
  430. agent.should have(0).errors_on(:scenarios)
  431. end
  432. it "validates keep_events_for" do
  433. agent = Agents::SomethingSource.new(:name => "something")
  434. agent.user = users(:bob)
  435. agent.should be_valid
  436. agent.keep_events_for = nil
  437. agent.should have(1).errors_on(:keep_events_for)
  438. agent.keep_events_for = 1000
  439. agent.should have(1).errors_on(:keep_events_for)
  440. agent.keep_events_for = ""
  441. agent.should have(1).errors_on(:keep_events_for)
  442. agent.keep_events_for = 5
  443. agent.should be_valid
  444. agent.keep_events_for = 0
  445. agent.should be_valid
  446. agent.keep_events_for = 365
  447. agent.should be_valid
  448. # Rails seems to call to_i on the input. This guards against future changes to that behavior.
  449. agent.keep_events_for = "drop table;"
  450. agent.keep_events_for.should == 0
  451. end
  452. end
  453. describe "cleaning up now-expired events" do
  454. before do
  455. @agent = Agents::SomethingSource.new(:name => "something")
  456. @agent.keep_events_for = 5
  457. @agent.user = users(:bob)
  458. @agent.save!
  459. @event = @agent.create_event :payload => { "hello" => "world" }
  460. @event.expires_at.to_i.should be_within(2).of(5.days.from_now.to_i)
  461. end
  462. describe "when keep_events_for has not changed" do
  463. it "does nothing" do
  464. mock(@agent).update_event_expirations!.times(0)
  465. @agent.options[:foo] = "bar1"
  466. @agent.save!
  467. @agent.options[:foo] = "bar1"
  468. @agent.keep_events_for = 5
  469. @agent.save!
  470. end
  471. end
  472. describe "when keep_events_for is changed" do
  473. it "updates events' expires_at" do
  474. lambda {
  475. @agent.options[:foo] = "bar1"
  476. @agent.keep_events_for = 3
  477. @agent.save!
  478. }.should change { @event.reload.expires_at }
  479. @event.expires_at.to_i.should be_within(2).of(3.days.from_now.to_i)
  480. end
  481. it "updates events relative to their created_at" do
  482. @event.update_attribute :created_at, 2.days.ago
  483. @event.reload.created_at.to_i.should be_within(2).of(2.days.ago.to_i)
  484. lambda {
  485. @agent.options[:foo] = "bar2"
  486. @agent.keep_events_for = 3
  487. @agent.save!
  488. }.should change { @event.reload.expires_at }
  489. @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
  490. end
  491. it "nulls out expires_at when keep_events_for is set to 0" do
  492. lambda {
  493. @agent.options[:foo] = "bar"
  494. @agent.keep_events_for = 0
  495. @agent.save!
  496. }.should change { @event.reload.expires_at }.to(nil)
  497. end
  498. end
  499. end
  500. describe "Agent.build_clone" do
  501. before do
  502. Event.delete_all
  503. @sender = Agents::SomethingSource.new(
  504. name: 'Agent (2)',
  505. options: { foo: 'bar2' },
  506. schedule: '5pm')
  507. @sender.user = users(:bob)
  508. @sender.save!
  509. @sender.create_event :payload => {}
  510. @sender.create_event :payload => {}
  511. @sender.events.count.should == 2
  512. @receiver = Agents::CannotBeScheduled.new(
  513. name: 'Agent',
  514. options: { foo: 'bar3' },
  515. keep_events_for: 3,
  516. propagate_immediately: true)
  517. @receiver.user = users(:bob)
  518. @receiver.sources << @sender
  519. @receiver.memory[:test] = 1
  520. @receiver.save!
  521. end
  522. it "should create a clone of a given agent for editing" do
  523. sender_clone = users(:bob).agents.build_clone(@sender)
  524. sender_clone.attributes.should == Agent.new.attributes.
  525. update(@sender.slice(:user_id, :type,
  526. :options, :schedule, :keep_events_for, :propagate_immediately)).
  527. update('name' => 'Agent (2) (2)', 'options' => { 'foo' => 'bar2' })
  528. sender_clone.source_ids.should == []
  529. receiver_clone = users(:bob).agents.build_clone(@receiver)
  530. receiver_clone.attributes.should == Agent.new.attributes.
  531. update(@receiver.slice(:user_id, :type,
  532. :options, :schedule, :keep_events_for, :propagate_immediately)).
  533. update('name' => 'Agent (3)', 'options' => { 'foo' => 'bar3' })
  534. receiver_clone.source_ids.should == [@sender.id]
  535. end
  536. end
  537. end
  538. describe ".trigger_web_request" do
  539. class Agents::WebRequestReceiver < Agent
  540. cannot_be_scheduled!
  541. end
  542. before do
  543. stub(Agents::WebRequestReceiver).valid_type?("Agents::WebRequestReceiver") { true }
  544. end
  545. context "when .receive_web_request is defined" do
  546. before do
  547. @agent = Agents::WebRequestReceiver.new(:name => "something")
  548. @agent.user = users(:bob)
  549. @agent.save!
  550. def @agent.receive_web_request(params, method, format)
  551. memory['last_request'] = [params, method, format]
  552. ['Ok!', 200]
  553. end
  554. end
  555. it "calls the .receive_web_request hook, updates last_web_request_at, and saves" do
  556. @agent.trigger_web_request({ :some_param => "some_value" }, "post", "text/html")
  557. @agent.reload.memory['last_request'].should == [ { "some_param" => "some_value" }, "post", "text/html" ]
  558. @agent.last_web_request_at.to_i.should be_within(1).of(Time.now.to_i)
  559. end
  560. end
  561. context "when .receive_webhook is defined" do
  562. before do
  563. @agent = Agents::WebRequestReceiver.new(:name => "something")
  564. @agent.user = users(:bob)
  565. @agent.save!
  566. def @agent.receive_webhook(params)
  567. memory['last_webhook_request'] = params
  568. ['Ok!', 200]
  569. end
  570. end
  571. it "outputs a deprecation warning and calls .receive_webhook with the params" do
  572. mock(Rails.logger).warn("DEPRECATED: The .receive_webhook method is deprecated, please switch your Agent to use .receive_web_request.")
  573. @agent.trigger_web_request({ :some_param => "some_value" }, "post", "text/html")
  574. @agent.reload.memory['last_webhook_request'].should == { "some_param" => "some_value" }
  575. @agent.last_web_request_at.to_i.should be_within(1).of(Time.now.to_i)
  576. end
  577. end
  578. end
  579. describe "scopes" do
  580. describe "of_type" do
  581. it "should accept classes" do
  582. agents = Agent.of_type(Agents::WebsiteAgent)
  583. agents.should include(agents(:bob_website_agent))
  584. agents.should include(agents(:jane_website_agent))
  585. agents.should_not include(agents(:bob_weather_agent))
  586. end
  587. it "should accept strings" do
  588. agents = Agent.of_type("Agents::WebsiteAgent")
  589. agents.should include(agents(:bob_website_agent))
  590. agents.should include(agents(:jane_website_agent))
  591. agents.should_not include(agents(:bob_weather_agent))
  592. end
  593. it "should accept instances of an Agent" do
  594. agents = Agent.of_type(agents(:bob_website_agent))
  595. agents.should include(agents(:bob_website_agent))
  596. agents.should include(agents(:jane_website_agent))
  597. agents.should_not include(agents(:bob_weather_agent))
  598. end
  599. end
  600. end
  601. describe "#create_event" do
  602. describe "when the agent has keep_events_for set" do
  603. before do
  604. agents(:jane_weather_agent).keep_events_for.should > 0
  605. end
  606. it "sets expires_at on created events" do
  607. event = agents(:jane_weather_agent).create_event :payload => { 'hi' => 'there' }
  608. event.expires_at.to_i.should be_within(5).of(agents(:jane_weather_agent).keep_events_for.days.from_now.to_i)
  609. end
  610. end
  611. describe "when the agent does not have keep_events_for set" do
  612. before do
  613. agents(:jane_website_agent).keep_events_for.should == 0
  614. end
  615. it "does not set expires_at on created events" do
  616. event = agents(:jane_website_agent).create_event :payload => { 'hi' => 'there' }
  617. event.expires_at.should be_nil
  618. end
  619. end
  620. end
  621. end
  622. describe AgentDrop do
  623. def interpolate(string, agent)
  624. agent.interpolate_string(string, "agent" => agent)
  625. end
  626. before do
  627. @wsa1 = Agents::WebsiteAgent.new(
  628. name: 'XKCD',
  629. options: {
  630. expected_update_period_in_days: 2,
  631. type: 'html',
  632. url: 'http://xkcd.com/',
  633. mode: 'on_change',
  634. extract: {
  635. url: { css: '#comic img', value: '@src' },
  636. title: { css: '#comic img', value: '@alt' },
  637. },
  638. },
  639. schedule: 'every_1h',
  640. keep_events_for: 2)
  641. @wsa1.user = users(:bob)
  642. @wsa1.save!
  643. @wsa2 = Agents::WebsiteAgent.new(
  644. name: 'Dilbert',
  645. options: {
  646. expected_update_period_in_days: 2,
  647. type: 'html',
  648. url: 'http://dilbert.com/',
  649. mode: 'on_change',
  650. extract: {
  651. url: { css: '[id^=strip_enlarged_] img', value: '@src' },
  652. title: { css: '.STR_DateStrip', value: './/text()' },
  653. },
  654. },
  655. schedule: 'every_12h',
  656. keep_events_for: 2)
  657. @wsa2.user = users(:bob)
  658. @wsa2.save!
  659. @efa = Agents::EventFormattingAgent.new(
  660. name: 'Formatter',
  661. options: {
  662. instructions: {
  663. message: '{{agent.name}}: {{title}} {{url}}',
  664. agent: '{{agent.type}}',
  665. },
  666. mode: 'clean',
  667. matchers: [],
  668. skip_created_at: 'false',
  669. },
  670. keep_events_for: 2,
  671. propagate_immediately: true)
  672. @efa.user = users(:bob)
  673. @efa.sources << @wsa1 << @wsa2
  674. @efa.memory[:test] = 1
  675. @efa.save!
  676. end
  677. it 'should be created via Agent#to_liquid' do
  678. @wsa1.to_liquid.class.should be(AgentDrop)
  679. @wsa2.to_liquid.class.should be(AgentDrop)
  680. @efa.to_liquid.class.should be(AgentDrop)
  681. end
  682. it 'should have .type and .name' do
  683. t = '{{agent.type}}: {{agent.name}}'
  684. interpolate(t, @wsa1).should eq('WebsiteAgent: XKCD')
  685. interpolate(t, @wsa2).should eq('WebsiteAgent: Dilbert')
  686. interpolate(t, @efa).should eq('EventFormattingAgent: Formatter')
  687. end
  688. it 'should have .options' do
  689. t = '{{agent.options.url}}'
  690. interpolate(t, @wsa1).should eq('http://xkcd.com/')
  691. interpolate(t, @wsa2).should eq('http://dilbert.com/')
  692. interpolate('{{agent.options.instructions.message}}',
  693. @efa).should eq('{{agent.name}}: {{title}} {{url}}')
  694. end
  695. it 'should have .sources' do
  696. t = '{{agent.sources.size}}: {{agent.sources | map:"name" | join:", "}}'
  697. interpolate(t, @wsa1).should eq('0: ')
  698. interpolate(t, @wsa2).should eq('0: ')
  699. interpolate(t, @efa).should eq('2: XKCD, Dilbert')
  700. end
  701. it 'should have .receivers' do
  702. t = '{{agent.receivers.size}}: {{agent.receivers | map:"name" | join:", "}}'
  703. interpolate(t, @wsa1).should eq('1: Formatter')
  704. interpolate(t, @wsa2).should eq('1: Formatter')
  705. interpolate(t, @efa).should eq('0: ')
  706. end
  707. end