1
0

website_agent_spec.rb 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. require 'spec_helper'
  2. describe Agents::WebsiteAgent do
  3. describe "checking without basic auth" do
  4. before do
  5. stub_request(:any, /xkcd/).to_return(body: File.read(Rails.root.join("spec/data_fixtures/xkcd.html")),
  6. status: 200,
  7. headers: {
  8. 'X-Status-Message' => 'OK'
  9. })
  10. @valid_options = {
  11. 'name' => "XKCD",
  12. 'expected_update_period_in_days' => "2",
  13. 'type' => "html",
  14. 'url' => "http://xkcd.com",
  15. 'mode' => 'on_change',
  16. 'extract' => {
  17. 'url' => { 'css' => "#comic img", 'value' => "@src" },
  18. 'title' => { 'css' => "#comic img", 'value' => "@alt" },
  19. 'hovertext' => { 'css' => "#comic img", 'value' => "@title" }
  20. }
  21. }
  22. @checker = Agents::WebsiteAgent.new(:name => "xkcd", :options => @valid_options, :keep_events_for => 2)
  23. @checker.user = users(:bob)
  24. @checker.save!
  25. end
  26. it_behaves_like WebRequestConcern
  27. describe "validations" do
  28. before do
  29. expect(@checker).to be_valid
  30. end
  31. it "should validate the integer fields" do
  32. @checker.options['expected_update_period_in_days'] = "2"
  33. expect(@checker).to be_valid
  34. @checker.options['expected_update_period_in_days'] = "nonsense"
  35. expect(@checker).not_to be_valid
  36. end
  37. it "should validate uniqueness_look_back" do
  38. @checker.options['uniqueness_look_back'] = "nonsense"
  39. expect(@checker).not_to be_valid
  40. @checker.options['uniqueness_look_back'] = "2"
  41. expect(@checker).to be_valid
  42. end
  43. it "should validate mode" do
  44. @checker.options['mode'] = "nonsense"
  45. expect(@checker).not_to be_valid
  46. @checker.options['mode'] = "on_change"
  47. expect(@checker).to be_valid
  48. @checker.options['mode'] = "all"
  49. expect(@checker).to be_valid
  50. @checker.options['mode'] = ""
  51. expect(@checker).to be_valid
  52. end
  53. it "should validate the force_encoding option" do
  54. @checker.options['force_encoding'] = ''
  55. expect(@checker).to be_valid
  56. @checker.options['force_encoding'] = 'UTF-8'
  57. expect(@checker).to be_valid
  58. @checker.options['force_encoding'] = ['UTF-8']
  59. expect(@checker).not_to be_valid
  60. @checker.options['force_encoding'] = 'UTF-42'
  61. expect(@checker).not_to be_valid
  62. end
  63. end
  64. describe "#check" do
  65. it "should check for changes (and update Event.expires_at)" do
  66. expect { @checker.check }.to change { Event.count }.by(1)
  67. event = Event.last
  68. sleep 2
  69. expect { @checker.check }.not_to change { Event.count }
  70. update_event = Event.last
  71. expect(update_event.expires_at).not_to eq(event.expires_at)
  72. end
  73. it "should always save events when in :all mode" do
  74. expect {
  75. @valid_options['mode'] = 'all'
  76. @checker.options = @valid_options
  77. @checker.check
  78. @checker.check
  79. }.to change { Event.count }.by(2)
  80. end
  81. it "should take uniqueness_look_back into account during deduplication" do
  82. @valid_options['mode'] = 'all'
  83. @checker.options = @valid_options
  84. @checker.check
  85. @checker.check
  86. event = Event.last
  87. event.payload = "{}"
  88. event.save
  89. expect {
  90. @valid_options['mode'] = 'on_change'
  91. @valid_options['uniqueness_look_back'] = 2
  92. @checker.options = @valid_options
  93. @checker.check
  94. }.not_to change { Event.count }
  95. expect {
  96. @valid_options['mode'] = 'on_change'
  97. @valid_options['uniqueness_look_back'] = 1
  98. @checker.options = @valid_options
  99. @checker.check
  100. }.to change { Event.count }.by(1)
  101. end
  102. it "should log an error if the number of results for a set of extraction patterns differs" do
  103. @valid_options['extract']['url']['css'] = "div"
  104. @checker.options = @valid_options
  105. @checker.check
  106. expect(@checker.logs.first.message).to match(/Got an uneven number of matches/)
  107. end
  108. it "should accept an array for url" do
  109. @valid_options['url'] = ["http://xkcd.com/1/", "http://xkcd.com/2/"]
  110. @checker.options = @valid_options
  111. expect { @checker.save! }.not_to raise_error;
  112. expect { @checker.check }.not_to raise_error;
  113. end
  114. it "should parse events from all urls in array" do
  115. expect {
  116. @valid_options['url'] = ["http://xkcd.com/", "http://xkcd.com/"]
  117. @valid_options['mode'] = 'all'
  118. @checker.options = @valid_options
  119. @checker.check
  120. }.to change { Event.count }.by(2)
  121. end
  122. it "should follow unique rules when parsing array of urls" do
  123. expect {
  124. @valid_options['url'] = ["http://xkcd.com/", "http://xkcd.com/"]
  125. @checker.options = @valid_options
  126. @checker.check
  127. }.to change { Event.count }.by(1)
  128. end
  129. end
  130. describe 'encoding' do
  131. it 'should be forced with force_encoding option' do
  132. huginn = "\u{601d}\u{8003}"
  133. stub_request(:any, /no-encoding/).to_return(:body => {
  134. :value => huginn,
  135. }.to_json.encode(Encoding::EUC_JP), :headers => {
  136. 'Content-Type' => 'application/json',
  137. }, :status => 200)
  138. site = {
  139. 'name' => "Some JSON Response",
  140. 'expected_update_period_in_days' => "2",
  141. 'type' => "json",
  142. 'url' => "http://no-encoding.example.com",
  143. 'mode' => 'on_change',
  144. 'extract' => {
  145. 'value' => { 'path' => 'value' },
  146. },
  147. 'force_encoding' => 'EUC-JP',
  148. }
  149. checker = Agents::WebsiteAgent.new(:name => "No Encoding Site", :options => site)
  150. checker.user = users(:bob)
  151. checker.save!
  152. checker.check
  153. event = Event.last
  154. expect(event.payload['value']).to eq(huginn)
  155. end
  156. it 'should be overridden with force_encoding option' do
  157. huginn = "\u{601d}\u{8003}"
  158. stub_request(:any, /wrong-encoding/).to_return(:body => {
  159. :value => huginn,
  160. }.to_json.encode(Encoding::EUC_JP), :headers => {
  161. 'Content-Type' => 'application/json; UTF-8',
  162. }, :status => 200)
  163. site = {
  164. 'name' => "Some JSON Response",
  165. 'expected_update_period_in_days' => "2",
  166. 'type' => "json",
  167. 'url' => "http://wrong-encoding.example.com",
  168. 'mode' => 'on_change',
  169. 'extract' => {
  170. 'value' => { 'path' => 'value' },
  171. },
  172. 'force_encoding' => 'EUC-JP',
  173. }
  174. checker = Agents::WebsiteAgent.new(:name => "Wrong Encoding Site", :options => site)
  175. checker.user = users(:bob)
  176. checker.save!
  177. checker.check
  178. event = Event.last
  179. expect(event.payload['value']).to eq(huginn)
  180. end
  181. end
  182. describe '#working?' do
  183. it 'checks if events have been received within the expected receive period' do
  184. stubbed_time = Time.now
  185. stub(Time).now { stubbed_time }
  186. expect(@checker).not_to be_working # No events created
  187. @checker.check
  188. expect(@checker.reload).to be_working # Just created events
  189. @checker.error "oh no!"
  190. expect(@checker.reload).not_to be_working # There is a recent error
  191. stubbed_time = 20.minutes.from_now
  192. @checker.events.delete_all
  193. @checker.check
  194. expect(@checker.reload).to be_working # There is a newer event now
  195. stubbed_time = 2.days.from_now
  196. expect(@checker.reload).not_to be_working # Two days have passed without a new event having been created
  197. end
  198. end
  199. describe "parsing" do
  200. it "parses CSS" do
  201. @checker.check
  202. event = Event.last
  203. expect(event.payload['url']).to eq("http://imgs.xkcd.com/comics/evolving.png")
  204. expect(event.payload['title']).to eq("Evolving")
  205. expect(event.payload['hovertext']).to match(/^Biologists play reverse/)
  206. end
  207. it "parses XPath" do
  208. @valid_options['extract'].each { |key, value|
  209. value.delete('css')
  210. value['xpath'] = "//*[@id='comic']//img"
  211. }
  212. @checker.options = @valid_options
  213. @checker.check
  214. event = Event.last
  215. expect(event.payload['url']).to eq("http://imgs.xkcd.com/comics/evolving.png")
  216. expect(event.payload['title']).to eq("Evolving")
  217. expect(event.payload['hovertext']).to match(/^Biologists play reverse/)
  218. end
  219. it "should turn relative urls to absolute" do
  220. rel_site = {
  221. 'name' => "XKCD",
  222. 'expected_update_period_in_days' => "2",
  223. 'type' => "html",
  224. 'url' => "http://xkcd.com",
  225. 'mode' => "on_change",
  226. 'extract' => {
  227. 'url' => {'css' => "#topLeft a", 'value' => "@href"},
  228. }
  229. }
  230. rel = Agents::WebsiteAgent.new(:name => "xkcd", :options => rel_site)
  231. rel.user = users(:bob)
  232. rel.save!
  233. rel.check
  234. event = Event.last
  235. expect(event.payload['url']).to eq("http://xkcd.com/about")
  236. end
  237. it "should return an integer value if XPath evaluates to one" do
  238. rel_site = {
  239. 'name' => "XKCD",
  240. 'expected_update_period_in_days' => 2,
  241. 'type' => "html",
  242. 'url' => "http://xkcd.com",
  243. 'mode' => "on_change",
  244. 'extract' => {
  245. 'num_links' => {'css' => "#comicLinks", 'value' => "count(./a)"}
  246. }
  247. }
  248. rel = Agents::WebsiteAgent.new(:name => "xkcd", :options => rel_site)
  249. rel.user = users(:bob)
  250. rel.save!
  251. rel.check
  252. event = Event.last
  253. expect(event.payload['num_links']).to eq("9")
  254. end
  255. it "should return all texts concatenated if XPath returns many text nodes" do
  256. rel_site = {
  257. 'name' => "XKCD",
  258. 'expected_update_period_in_days' => 2,
  259. 'type' => "html",
  260. 'url' => "http://xkcd.com",
  261. 'mode' => "on_change",
  262. 'extract' => {
  263. 'slogan' => {'css' => "#slogan", 'value' => ".//text()"}
  264. }
  265. }
  266. rel = Agents::WebsiteAgent.new(:name => "xkcd", :options => rel_site)
  267. rel.user = users(:bob)
  268. rel.save!
  269. rel.check
  270. event = Event.last
  271. expect(event.payload['slogan']).to eq("A webcomic of romance, sarcasm, math, and language.")
  272. end
  273. it "should interpolate _response_" do
  274. @valid_options['extract']['response_info'] =
  275. @valid_options['extract']['url'].merge(
  276. 'value' => '"{{ "The reponse was " | append:_response_.status | append:" " | append:_response_.headers.X-Status-Message | append:"." }}"'
  277. )
  278. @checker.options = @valid_options
  279. @checker.check
  280. event = Event.last
  281. expect(event.payload['response_info']).to eq('The reponse was 200 OK.')
  282. end
  283. describe "JSON" do
  284. it "works with paths" do
  285. json = {
  286. 'response' => {
  287. 'version' => 2,
  288. 'title' => "hello!"
  289. }
  290. }
  291. stub_request(:any, /json-site/).to_return(:body => json.to_json, :status => 200)
  292. site = {
  293. 'name' => "Some JSON Response",
  294. 'expected_update_period_in_days' => "2",
  295. 'type' => "json",
  296. 'url' => "http://json-site.com",
  297. 'mode' => 'on_change',
  298. 'extract' => {
  299. 'version' => {'path' => "response.version"},
  300. 'title' => {'path' => "response.title"}
  301. }
  302. }
  303. checker = Agents::WebsiteAgent.new(:name => "Weather Site", :options => site)
  304. checker.user = users(:bob)
  305. checker.save!
  306. checker.check
  307. event = Event.last
  308. expect(event.payload['version']).to eq(2)
  309. expect(event.payload['title']).to eq("hello!")
  310. end
  311. it "can handle arrays" do
  312. json = {
  313. 'response' => {
  314. 'data' => [
  315. {'title' => "first", 'version' => 2},
  316. {'title' => "second", 'version' => 2.5}
  317. ]
  318. }
  319. }
  320. stub_request(:any, /json-site/).to_return(:body => json.to_json, :status => 200)
  321. site = {
  322. 'name' => "Some JSON Response",
  323. 'expected_update_period_in_days' => "2",
  324. 'type' => "json",
  325. 'url' => "http://json-site.com",
  326. 'mode' => 'on_change',
  327. 'extract' => {
  328. :title => {'path' => "response.data[*].title"},
  329. :version => {'path' => "response.data[*].version"}
  330. }
  331. }
  332. checker = Agents::WebsiteAgent.new(:name => "Weather Site", :options => site)
  333. checker.user = users(:bob)
  334. checker.save!
  335. expect {
  336. checker.check
  337. }.to change { Event.count }.by(2)
  338. event = Event.all[-1]
  339. expect(event.payload['version']).to eq(2.5)
  340. expect(event.payload['title']).to eq("second")
  341. event = Event.all[-2]
  342. expect(event.payload['version']).to eq(2)
  343. expect(event.payload['title']).to eq("first")
  344. end
  345. it "stores the whole object if :extract is not specified" do
  346. json = {
  347. 'response' => {
  348. 'version' => 2,
  349. 'title' => "hello!"
  350. }
  351. }
  352. stub_request(:any, /json-site/).to_return(:body => json.to_json, :status => 200)
  353. site = {
  354. 'name' => "Some JSON Response",
  355. 'expected_update_period_in_days' => "2",
  356. 'type' => "json",
  357. 'url' => "http://json-site.com",
  358. 'mode' => 'on_change'
  359. }
  360. checker = Agents::WebsiteAgent.new(:name => "Weather Site", :options => site)
  361. checker.user = users(:bob)
  362. checker.save!
  363. checker.check
  364. event = Event.last
  365. expect(event.payload['response']['version']).to eq(2)
  366. expect(event.payload['response']['title']).to eq("hello!")
  367. end
  368. end
  369. describe "text parsing" do
  370. before do
  371. stub_request(:any, /text-site/).to_return(body: <<-EOF, status: 200)
  372. water: wet
  373. fire: hot
  374. EOF
  375. site = {
  376. 'name' => 'Some Text Response',
  377. 'expected_update_period_in_days' => '2',
  378. 'type' => 'text',
  379. 'url' => 'http://text-site.com',
  380. 'mode' => 'on_change',
  381. 'extract' => {
  382. 'word' => { 'regexp' => '^(.+?): (.+)$', index: 1 },
  383. 'property' => { 'regexp' => '^(.+?): (.+)$', index: 2 },
  384. }
  385. }
  386. @checker = Agents::WebsiteAgent.new(name: 'Text Site', options: site)
  387. @checker.user = users(:bob)
  388. @checker.save!
  389. end
  390. it "works with regexp" do
  391. @checker.options = @checker.options.merge('extract' => {
  392. 'word' => { 'regexp' => '^(?<word>.+?): (?<property>.+)$', index: 'word' },
  393. 'property' => { 'regexp' => '^(?<word>.+?): (?<property>.+)$', index: 'property' },
  394. })
  395. expect {
  396. @checker.check
  397. }.to change { Event.count }.by(2)
  398. event1, event2 = Event.last(2)
  399. expect(event1.payload['word']).to eq('water')
  400. expect(event1.payload['property']).to eq('wet')
  401. expect(event2.payload['word']).to eq('fire')
  402. expect(event2.payload['property']).to eq('hot')
  403. end
  404. it "works with regexp with named capture" do
  405. expect {
  406. @checker.check
  407. }.to change { Event.count }.by(2)
  408. event1, event2 = Event.last(2)
  409. expect(event1.payload['word']).to eq('water')
  410. expect(event1.payload['property']).to eq('wet')
  411. expect(event2.payload['word']).to eq('fire')
  412. expect(event2.payload['property']).to eq('hot')
  413. end
  414. end
  415. end
  416. describe "#receive" do
  417. before do
  418. @event = Event.new
  419. @event.agent = agents(:bob_rain_notifier_agent)
  420. @event.payload = {
  421. 'url' => 'http://xkcd.com',
  422. 'link' => 'Random',
  423. }
  424. end
  425. it "should scrape from the url element in incoming event payload" do
  426. expect {
  427. @checker.options = @valid_options
  428. @checker.receive([@event])
  429. }.to change { Event.count }.by(1)
  430. end
  431. it "should interpolate values from incoming event payload" do
  432. expect {
  433. @valid_options['extract'] = {
  434. 'from' => {
  435. 'xpath' => '*[1]',
  436. 'value' => '{{url | to_xpath}}'
  437. },
  438. 'to' => {
  439. 'xpath' => '(//a[@href and text()={{link | to_xpath}}])[1]',
  440. 'value' => '@href'
  441. },
  442. }
  443. @checker.options = @valid_options
  444. @checker.receive([@event])
  445. }.to change { Event.count }.by(1)
  446. expect(Event.last.payload).to eq({
  447. 'from' => 'http://xkcd.com',
  448. 'to' => 'http://dynamic.xkcd.com/random/comic/',
  449. })
  450. end
  451. it "should interpolate values from incoming event payload and _response_" do
  452. @event.payload['title'] = 'XKCD'
  453. expect {
  454. @valid_options['extract'] = {
  455. 'response_info' => @valid_options['extract']['url'].merge(
  456. 'value' => '{% capture sentence %}The reponse from {{title}} was {{_response_.status}} {{_response_.headers.X-Status-Message}}.{% endcapture %}{{sentence | to_xpath}}'
  457. )
  458. }
  459. @checker.options = @valid_options
  460. @checker.receive([@event])
  461. }.to change { Event.count }.by(1)
  462. expect(Event.last.payload['response_info']).to eq('The reponse from XKCD was 200 OK.')
  463. end
  464. end
  465. end
  466. describe "checking with http basic auth" do
  467. before do
  468. stub_request(:any, /example/).
  469. with(headers: { 'Authorization' => "Basic #{['user:pass'].pack('m').chomp}" }).
  470. to_return(:body => File.read(Rails.root.join("spec/data_fixtures/xkcd.html")), :status => 200)
  471. @valid_options = {
  472. 'name' => "XKCD",
  473. 'expected_update_period_in_days' => "2",
  474. 'type' => "html",
  475. 'url' => "http://www.example.com",
  476. 'mode' => 'on_change',
  477. 'extract' => {
  478. 'url' => { 'css' => "#comic img", 'value' => "@src" },
  479. 'title' => { 'css' => "#comic img", 'value' => "@alt" },
  480. 'hovertext' => { 'css' => "#comic img", 'value' => "@title" }
  481. },
  482. 'basic_auth' => "user:pass"
  483. }
  484. @checker = Agents::WebsiteAgent.new(:name => "auth", :options => @valid_options)
  485. @checker.user = users(:bob)
  486. @checker.save!
  487. end
  488. describe "#check" do
  489. it "should check for changes" do
  490. expect { @checker.check }.to change { Event.count }.by(1)
  491. expect { @checker.check }.not_to change { Event.count }
  492. end
  493. end
  494. end
  495. describe "checking with headers" do
  496. before do
  497. stub_request(:any, /example/).
  498. with(headers: { 'foo' => 'bar' }).
  499. to_return(:body => File.read(Rails.root.join("spec/data_fixtures/xkcd.html")), :status => 200)
  500. @valid_options = {
  501. 'name' => "XKCD",
  502. 'expected_update_period_in_days' => "2",
  503. 'type' => "html",
  504. 'url' => "http://www.example.com",
  505. 'mode' => 'on_change',
  506. 'headers' => { 'foo' => 'bar' },
  507. 'extract' => {
  508. 'url' => { 'css' => "#comic img", 'value' => "@src" },
  509. }
  510. }
  511. @checker = Agents::WebsiteAgent.new(:name => "ua", :options => @valid_options)
  512. @checker.user = users(:bob)
  513. @checker.save!
  514. end
  515. describe "#check" do
  516. it "should check for changes" do
  517. expect { @checker.check }.to change { Event.count }.by(1)
  518. end
  519. end
  520. end
  521. end