repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/twitter_favorites_spec.rb
spec/models/agents/twitter_favorites_spec.rb
require 'rails_helper' describe Agents::TwitterFavorites do before do stub_request(:any, /tectonic.*[?&]tweet_mode=extended/) .to_return(body: File.read(Rails.root.join("spec/data_fixtures/user_fav_tweets.json")), headers: { 'Content-Type': 'application/json;charset=utf-8' }, status: 200) end before do @opts = { username: "tectonic", number: "10", history: "100", expected_update_period_in_days: "2", starting_at: "Sat Feb 20 01:32:08 +0000 2016" } @agent = Agents::TwitterFavorites.new(name: "tectonic", options: @opts) @agent.service = services(:generic) @agent.events.new(payload: JSON.parse(File.read(Rails.root.join("spec/data_fixtures/one_fav_tweet.json")))) @agent.user = users(:bob) @agent.save! @event = Event.new @event.agent = agents(:tectonic_twitter_user_agent) @event.payload = JSON.parse(File.read(Rails.root.join("spec/data_fixtures/one_fav_tweet.json"))) @event.save! end describe "making sure agent last event payload is equivalent to event payload" do it "expect change method to change event" do expect(@agent.events.last.payload).to eq(@event.payload) end end describe "making sure check method works" do it "expect change method to change event" do expect { @agent.check }.to change { Event.count }.by(3) Event.last(3).each_cons(2) do |t1, t2| expect(t1.payload[:id]).to be < t2.payload[:id] end end end describe "#check with starting_at=future date" do it "should check for changes starting_at a future date, thus not find any" do opts = @opts.merge({ starting_at: "Thurs Feb 23 16:12:04 +0000 2017" }) @agent1 = Agents::TwitterFavorites.new(name: "tectonic", options: opts) @agent1.service = services(:generic) @agent1.user = users(:bob) @agent1.save! expect { @agent1.check }.to change { Event.count }.by(0) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/sentiment_agent_spec.rb
spec/models/agents/sentiment_agent_spec.rb
require 'rails_helper' describe Agents::SentimentAgent do before do @valid_params = { :name => "somename", :options => { :content => "$.message", :expected_receive_period_in_days => 1 } } @checker = Agents::SentimentAgent.new(@valid_params) @checker.user = users(:jane) @checker.save! @event = Event.new @event.agent = agents(:jane_weather_agent) @event.payload = { :message => "value1" } @event.save! end describe "#working?" do it "checks if events have been received within expected receive period" do expect(@checker).not_to be_working Agents::SentimentAgent.async_receive @checker.id, [@event.id] expect(@checker.reload).to be_working two_days_from_now = 2.days.from_now allow(Time).to receive(:now) { two_days_from_now } expect(@checker.reload).not_to be_working end end describe "validation" do before do expect(@checker).to be_valid end it "should validate presence of content key" do @checker.options[:content] = nil expect(@checker).not_to be_valid end it "should validate presence of expected_receive_period_in_days key" do @checker.options[:expected_receive_period_in_days] = nil expect(@checker).not_to be_valid end end describe "#receive" do it "checks if content key is working fine" do @checker.receive([@event]) expect(Event.last.payload[:content]).to eq("value1") expect(Event.last.payload[:original_event]).to eq({ 'message' => "value1" }) end it "should handle multiple events" do event1 = Event.new event1.agent = agents(:bob_weather_agent) event1.payload = { :message => "The quick brown fox jumps over the lazy dog" } event2 = Event.new event2.agent = agents(:jane_weather_agent) event2.payload = { :message => "The quick brown fox jumps over the lazy dog" } expect { @checker.receive([@event,event1,event2]) }.to change { Event.count }.by(3) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/weather_agent_spec.rb
spec/models/agents/weather_agent_spec.rb
require 'rails_helper' describe Agents::WeatherAgent do let(:agent) do Agents::WeatherAgent.create( name: 'weather', options: { :location => "37.77550,-122.41292", :api_key => 'test', :which_day => 1, } ).tap do |agent| agent.user = users(:bob) agent.save! end end let :pirate_weather_agent do Agents::WeatherAgent.create( name: "weather from Pirate Weather", options: { :location => "37.779329,-122.41915", :service => "pirateweather", :which_day => 1, :api_key => "test" } ).tap do |agent| agent.user = users(:bob) agent.save! end end it "creates a valid agent" do expect(agent).to be_valid end it "is valid with put-your-key-here or your-key" do agent.options['api_key'] = 'put-your-key-here' expect(agent).to be_valid expect(agent.working?).to be_falsey agent.options['api_key'] = 'your-key' expect(agent).to be_valid expect(agent.working?).to be_falsey end context "pirate weather" do it "validates the location properly" do expect(pirate_weather_agent.options["location"]).to eq "37.779329,-122.41915" expect(pirate_weather_agent).to be_valid pirate_weather_agent.options["location"] = "37.779329, -122.41915" # with a space expect(pirate_weather_agent).to be_valid pirate_weather_agent.options["location"] = "94103" # a zip code expect(pirate_weather_agent).to_not be_valid pirate_weather_agent.options["location"] = "37.779329,-122.41915" expect(pirate_weather_agent.options["location"]).to eq "37.779329,-122.41915" expect(pirate_weather_agent).to be_valid end it "fails cases that pass the first test but are invalid" do pirate_weather_agent.options["location"] = "137.779329, -122.41915" # too high latitude expect(pirate_weather_agent).to_not be_valid pirate_weather_agent.options["location"] = "37.779329, -522.41915" # too low longitude expect(pirate_weather_agent).to_not be_valid end end describe "#service" do it "doesn't have a Service object attached" do expect(agent.service).to be_nil end end describe "Agents::WeatherAgent::VALID_COORDS_REGEX" do it "matches 37.779329,-122.41915" do expect( "37.779329,-122.41915" =~ Agents::WeatherAgent::VALID_COORDS_REGEX ).to be_truthy end it "matches a dozen random valid values" do valid_longitude_range = -180.0..180.0 valid_latitude_range = -90.0..90.0 12.times do expect( "#{rand valid_latitude_range},#{rand valid_longitude_range}" =~ Agents::WeatherAgent::VALID_COORDS_REGEX ).not_to be_nil end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/local_file_agent_spec.rb
spec/models/agents/local_file_agent_spec.rb
require 'rails_helper' describe Agents::LocalFileAgent do before(:each) do @valid_params = { 'mode' => 'read', 'watch' => 'false', 'append' => 'false', 'path' => File.join(Rails.root, 'tmp', 'spec') } FileUtils.mkdir_p File.join(Rails.root, 'tmp', 'spec') @checker = Agents::LocalFileAgent.new(:name => "somename", :options => @valid_params) @checker.user = users(:jane) @checker.save! end after(:all) do FileUtils.rm_r File.join(Rails.root, 'tmp', 'spec') end describe "#validate_options" do it "is valid with the given options" do expect(@checker).to be_valid end it "requires mode to be either 'read' or 'write'" do @checker.options['mode'] = 'write' expect(@checker).to be_valid @checker.options['mode'] = 'write' expect(@checker).to be_valid @checker.options['mode'] = 'test' expect(@checker).not_to be_valid end it "requires the path to be set" do @checker.options['path'] = '' expect(@checker).not_to be_valid end it "requires watch to be present" do @checker.options['watch'] = '' expect(@checker).not_to be_valid end it "requires watch to be either 'true' or 'false'" do @checker.options['watch'] = 'true' expect(@checker).to be_valid @checker.options['watch'] = 'false' expect(@checker).to be_valid @checker.options['watch'] = 'test' expect(@checker).not_to be_valid end it "requires append to be either 'true' or 'false'" do @checker.options['append'] = 'true' expect(@checker).to be_valid @checker.options['append'] = 'false' expect(@checker).to be_valid @checker.options['append'] = 'test' expect(@checker).not_to be_valid end end context "#working" do it "is working with no recent errors in read mode" do @checker.last_check_at = Time.now expect(@checker).to be_working end it "is working with no recent errors in write mode" do @checker.options['mode'] = 'write' @checker.last_receive_at = Time.now expect(@checker).to be_working end end context "#check_path_existance" do it "is truethy when the path exists" do expect(@checker.check_path_existance).to be_truthy end it "is falsy when the path does not exist" do @checker.options['path'] = '/doesnotexist' expect(@checker.check_path_existance).to be_falsy end it "create a log entry" do @checker.options['path'] = '/doesnotexist' expect { @checker.check_path_existance(true) }.to change(AgentLog, :count).by(1) end it "works with non-expanded paths" do @checker.options['path'] = '~' expect(@checker.check_path_existance).to be_truthy end end def with_files(*files) files.each { |f| FileUtils.touch(f) } yield files.each { |f| FileUtils.rm(f) } end context "#check" do it "does not create events when the directory is empty" do expect { @checker.check }.to change(Event, :count).by(0) end it "creates an event for every file in the directory" do with_files(File.join(Rails.root, 'tmp', 'spec', 'one'), File.join(Rails.root, 'tmp', 'spec', 'two')) do expect { @checker.check }.to change(Event, :count).by(2) expect(Event.last.payload.has_key?('file_pointer')).to be_truthy end end it "creates an event if the configured file exists" do @checker.options['path'] = File.join(Rails.root, 'tmp', 'spec', 'one') with_files(File.join(Rails.root, 'tmp', 'spec', 'one'), File.join(Rails.root, 'tmp', 'spec', 'two')) do expect { @checker.check }.to change(Event, :count).by(1) payload = Event.last.payload expect(payload.has_key?('file_pointer')).to be_truthy expect(payload['file_pointer']['file']).to eq(@checker.options['path']) end end it "does not run when ENABLE_INSECURE_AGENTS is not set to true" do ENV['ENABLE_INSECURE_AGENTS'] = 'false' expect { @checker.check }.to change(AgentLog, :count).by(1) ENV['ENABLE_INSECURE_AGENTS'] = 'true' end end context "#event_description" do it "should include event_type when watch is set to true" do @checker.options['watch'] = 'true' expect(@checker.event_description).to include('event_type') end it "should not include event_type when watch is set to false" do @checker.options['watch'] = 'false' expect(@checker.event_description).not_to include('event_type') end end it "get_io opens the file" do expect(File).to receive(:open).with('test', 'r') @checker.get_io('test') end context "#start_worker?" do it "reeturns true when watch is true" do @checker.options['watch'] = 'true' expect(@checker.start_worker?).to be_truthy end it "returns false when watch is false" do @checker.options['watch'] = 'false' expect(@checker.start_worker?).to be_falsy end end context "#receive" do before(:each) do @checker.options['mode'] = 'write' @checker.options['data'] = '{{ data }}' @file_mock = double() end it "writes the data at data into a file" do expect(@file_mock).to receive(:write).with('hello world') event = Event.new(payload: {'data' => 'hello world'}) expect(File).to receive(:open).with(File.join(Rails.root, 'tmp', 'spec'), 'w').and_yield(@file_mock) @checker.receive([event]) end it "appends the data at data onto a file" do expect(@file_mock).to receive(:write).with('hello world') @checker.options['append'] = 'true' event = Event.new(payload: {'data' => 'hello world'}) expect(File).to receive(:open).with(File.join(Rails.root, 'tmp', 'spec'), 'a').and_yield(@file_mock) @checker.receive([event]) end it "does not receive when ENABLE_INSECURE_AGENTS is not set to true" do ENV['ENABLE_INSECURE_AGENTS'] = 'false' expect { @checker.receive([]) }.to change(AgentLog, :count).by(1) ENV['ENABLE_INSECURE_AGENTS'] = 'true' end it "emits an event containing the file pointer" do expect(@file_mock).to receive(:write).with('hello world') event = Event.new(payload: {'data' => 'hello world'}) expect(File).to receive(:open).with(File.join(Rails.root, 'tmp', 'spec'), 'w').and_yield(@file_mock) expect { @checker.receive([event]) }.to change(Event, :count).by(1) expect(Event.last.payload.has_key?('file_pointer')).to be_truthy end end describe describe Agents::LocalFileAgent::Worker do require 'listen' before(:each) do @checker.options['watch'] = true @checker.save @worker = Agents::LocalFileAgent::Worker.new(agent: @checker) @listen_mock = double() end context "#setup" do it "initializes the listen gem" do expect(Listen).to receive(:to).with(@checker.options['path'], ignore!: []) @worker.setup end end context "#run" do before(:each) do allow(Listen).to receive(:to) { @listen_mock } @worker.setup end it "starts to listen to changes in the directory when the path is present" do expect(@worker).to receive(:sleep) expect(@listen_mock).to receive(:start) @worker.run end it "does nothing when the path does not exist" do expect(@worker.agent).to receive(:check_path_existance).with(true) { false } expect(@listen_mock).not_to receive(:start) expect(@worker).to receive(:sleep) { raise "Sleeping" } expect { @worker.run }.to raise_exception(RuntimeError, 'Sleeping') end end context "#stop" do it "stops the listen gem" do allow(Listen).to receive(:to) { @listen_mock } @worker.setup expect(@listen_mock).to receive(:stop) @worker.stop end end context "#callback" do let(:file) { File.join(Rails.root, 'tmp', 'one') } let(:file2) { File.join(Rails.root, 'tmp', 'one2') } it "creates an event for modifies files" do expect { @worker.send(:callback, [file], [], [])}.to change(Event, :count).by(1) payload = Event.last.payload expect(payload['event_type']).to eq('modified') end it "creates an event for modifies files" do expect { @worker.send(:callback, [], [file], [])}.to change(Event, :count).by(1) payload = Event.last.payload expect(payload['event_type']).to eq('added') end it "creates an event for modifies files" do expect { @worker.send(:callback, [], [], [file])}.to change(Event, :count).by(1) payload = Event.last.payload expect(payload['event_type']).to eq('removed') end it "creates an event each changed file" do expect { @worker.send(:callback, [], [file], [file2])}.to change(Event, :count).by(2) end end context "#listen_options" do it "returns the path when a directory is given" do expect(@worker.send(:listen_options)).to eq([File.join(Rails.root, 'tmp', 'spec'), ignore!: []]) end it "restricts to only the specified filename" do @worker.agent.options['path'] = File.join(Rails.root, 'tmp', 'one') expect(@worker.send(:listen_options)).to eq([File.join(Rails.root, 'tmp'), { only: /\Aone\z/, ignore!: [] } ]) end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/delay_agent_spec.rb
spec/models/agents/delay_agent_spec.rb
require 'rails_helper' describe Agents::DelayAgent do let(:agent) { Agents::DelayAgent.create!( name: 'My DelayAgent', user: users(:bob), options: default_options.merge('max_events' => 2), sources: [agents(:bob_website_agent)] ) } let(:default_options) { Agents::DelayAgent.new.default_options } def create_event(value) Event.create!(payload: { value: }, agent: agents(:bob_website_agent)) end let(:first_event) { create_event("one") } let(:second_event) { create_event("two") } let(:third_event) { create_event("three") } describe "#working?" do it "checks if events have been received within expected receive period" do expect(agent).not_to be_working Agents::DelayAgent.async_receive agent.id, [events(:bob_website_agent_event).id] expect(agent.reload).to be_working the_future = (agent.options[:expected_receive_period_in_days].to_i + 1).days.from_now allow(Time).to receive(:now) { the_future } expect(agent.reload).not_to be_working end end describe "validation" do before do expect(agent).to be_valid end it "should validate max_events" do agent.options.delete('max_events') expect(agent).not_to be_valid agent.options['max_events'] = "" expect(agent).not_to be_valid agent.options['max_events'] = "0" expect(agent).not_to be_valid agent.options['max_events'] = "10" expect(agent).to be_valid end it "should validate emit_interval" do agent.options.delete('emit_interval') expect(agent).to be_valid agent.options['emit_interval'] = "0" expect(agent).to be_valid agent.options['emit_interval'] = "0.5" expect(agent).to be_valid agent.options['emit_interval'] = 0.5 expect(agent).to be_valid agent.options['emit_interval'] = '' expect(agent).not_to be_valid agent.options['emit_interval'] = nil expect(agent).to be_valid end it "should validate presence of expected_receive_period_in_days" do agent.options['expected_receive_period_in_days'] = "" expect(agent).not_to be_valid agent.options['expected_receive_period_in_days'] = 0 expect(agent).not_to be_valid agent.options['expected_receive_period_in_days'] = -1 expect(agent).not_to be_valid end it "should validate keep" do agent.options.delete('keep') expect(agent).not_to be_valid agent.options['keep'] = "" expect(agent).not_to be_valid agent.options['keep'] = 'wrong' expect(agent).not_to be_valid agent.options['keep'] = 'newest' expect(agent).to be_valid agent.options['keep'] = 'oldest' expect(agent).to be_valid end end describe "#receive" do it "records Events" do expect(agent.memory).to be_empty agent.receive([first_event]) expect(agent.memory).not_to be_empty agent.receive([second_event]) expect(agent.memory['event_ids']).to eq [first_event.id, second_event.id] end it "keeps the newest when 'keep' is set to 'newest'" do expect(agent.options['keep']).to eq 'newest' agent.receive([first_event, second_event, third_event]) expect(agent.memory['event_ids']).to eq [second_event.id, third_event.id] end it "keeps the oldest when 'keep' is set to 'oldest'" do agent.options['keep'] = 'oldest' agent.receive([first_event, second_event, third_event]) expect(agent.memory['event_ids']).to eq [first_event.id, second_event.id] end end describe "#check" do it "re-emits Events and clears the memory" do agent.receive([first_event, second_event, third_event]) expect(agent.memory['event_ids']).to eq [second_event.id, third_event.id] expect(agent).to receive(:sleep).with(0).once expect { agent.check }.to change { agent.events.count }.by(2) expect(agent.events.take(2).map(&:payload)).to eq [ third_event, second_event, ].map(&:payload) expect(agent.memory['event_ids']).to eq [] end context "with events_order and emit_interval" do before do agent.update!(options: agent.options.merge( 'events_order' => ['{{ value }}'], 'emit_interval' => 1, )) end it "re-emits Events in that order and clears the memory with that interval" do agent.receive([first_event, second_event, third_event]) expect(agent.memory['event_ids']).to eq [second_event.id, third_event.id] expect(agent).to receive(:sleep).with(1).once expect { agent.check }.to change { agent.events.count }.by(2) expect(agent.events.take(2).map(&:payload)).to eq [ second_event, third_event, ].map(&:payload) expect(agent.memory['event_ids']).to eq [] end end context "with max_emitted_events" do before do agent.update!(options: agent.options.merge('max_emitted_events' => 1)) end it "re-emits max_emitted_events per run" do agent.receive([first_event, second_event, third_event]) expect(agent.memory['event_ids']).to eq [second_event.id, third_event.id] expect { agent.check }.to change { agent.events.count }.by(1) expect(agent.events.take.payload).to eq second_event.payload expect(agent.memory['event_ids']).to eq [third_event.id] expect { agent.check }.to change { agent.events.count }.by(1) expect(agent.events.take.payload).to eq third_event.payload expect(agent.memory['event_ids']).to eq [] expect { agent.check }.not_to(change { agent.events.count }) end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/data_output_agent_spec.rb
spec/models/agents/data_output_agent_spec.rb
# encoding: utf-8 require 'rails_helper' describe Agents::DataOutputAgent do let(:agent) do _agent = Agents::DataOutputAgent.new(:name => 'My Data Output Agent') _agent.options = _agent.default_options.merge('secrets' => ['secret1', 'secret2'], 'events_to_show' => 3) _agent.options['template']['item']['pubDate'] = "{{date}}" _agent.options['template']['item']['category'] = "{{ category | as_object }}" _agent.user = users(:bob) _agent.sources << agents(:bob_website_agent) _agent.save! _agent end describe "#working?" do it "checks if events have been received within expected receive period" do expect(agent).not_to be_working Agents::DataOutputAgent.async_receive agent.id, [events(:bob_website_agent_event).id] expect(agent.reload).to be_working two_days_from_now = 2.days.from_now allow(Time).to receive(:now) { two_days_from_now } expect(agent.reload).not_to be_working end end describe "validation" do before do expect(agent).to be_valid end it "should validate presence and length of secrets" do agent.options[:secrets] = "" expect(agent).not_to be_valid agent.options[:secrets] = "foo" expect(agent).not_to be_valid agent.options[:secrets] = "foo/bar" expect(agent).not_to be_valid agent.options[:secrets] = "foo.xml" expect(agent).not_to be_valid agent.options[:secrets] = false expect(agent).not_to be_valid agent.options[:secrets] = [] expect(agent).not_to be_valid agent.options[:secrets] = ["foo.xml"] expect(agent).not_to be_valid agent.options[:secrets] = ["hello", true] expect(agent).not_to be_valid agent.options[:secrets] = ["hello"] expect(agent).to be_valid agent.options[:secrets] = ["hello", "world"] expect(agent).to be_valid end it "should validate presence of expected_receive_period_in_days" do agent.options[:expected_receive_period_in_days] = "" expect(agent).not_to be_valid agent.options[:expected_receive_period_in_days] = 0 expect(agent).not_to be_valid agent.options[:expected_receive_period_in_days] = -1 expect(agent).not_to be_valid end it "should validate presence of template and template.item" do agent.options[:template] = "" expect(agent).not_to be_valid agent.options[:template] = {} expect(agent).not_to be_valid agent.options[:template] = { 'item' => 'foo' } expect(agent).not_to be_valid agent.options[:template] = { 'item' => { 'title' => 'hi' } } expect(agent).to be_valid end end describe "#receive" do it "should push to hubs when push_hubs is given" do agent.options[:push_hubs] = %w[http://push.example.com] agent.options[:template] = { 'link' => 'http://huginn.example.org' } alist = nil stub_request(:post, 'http://push.example.com/') .with(headers: { 'Content-Type' => %r{\Aapplication/x-www-form-urlencoded\s*(?:;|\z)} }) .to_return { |request| alist = URI.decode_www_form(request.body).sort { status: 200, body: 'ok' } } agent.receive(events(:bob_website_agent_event)) expect(alist).to eq [ ["hub.mode", "publish"], ["hub.url", agent.feed_url(secret: agent.options[:secrets].first, format: :xml)] ] end end describe "#receive_web_request" do before do current_time = Time.now allow(Time).to receive(:now) { current_time } agents(:bob_website_agent).events.destroy_all end it "requires a valid secret" do content, status, content_type = agent.receive_web_request({ 'secret' => 'fake' }, 'get', 'text/xml') expect(status).to eq(401) expect(content).to eq("Not Authorized") content, status, content_type = agent.receive_web_request({ 'secret' => 'fake' }, 'get', 'application/json') expect(status).to eq(401) expect(content).to eq({ :error => "Not Authorized" }) content, status, content_type = agent.receive_web_request({ 'secret' => 'secret1' }, 'get', 'application/json') expect(status).to eq(200) end describe "outputting events as RSS and JSON" do let!(:event1) do agents(:bob_website_agent).create_event :payload => { "site_title" => "XKCD", "url" => "http://imgs.xkcd.com/comics/evolving.png", "title" => "Evolving", "hovertext" => "Biologists play reverse Pokemon, trying to avoid putting any one team member on the front lines long enough for the experience to cause evolution.", "category" => [] } end let!(:event2) do agents(:bob_website_agent).create_event :payload => { "site_title" => "XKCD", "url" => "http://imgs.xkcd.com/comics/evolving2.png", "title" => "Evolving again", "date" => '', "hovertext" => "Something else", "category" => ["Category 1", "Category 2"] } end let!(:event3) do agents(:bob_website_agent).create_event :payload => { "site_title" => "XKCD", "url" => "http://imgs.xkcd.com/comics/evolving0.png", "title" => "Evolving yet again with a past date", "date" => '2014/05/05', "hovertext" => "A small text", "category" => ["Some category"] } end it "can output RSS" do allow(agent).to receive(:feed_link) { "https://yoursite.com" } content, status, content_type = agent.receive_web_request({ 'secret' => 'secret1' }, 'get', 'text/xml') expect(status).to eq(200) expect(content_type).to eq('application/rss+xml') expect(content.gsub(/\s+/, '')).to eq Utils.unindent(<<-XML).gsub(/\s+/, '') <?xml version="1.0" encoding="UTF-8" ?> <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/"> <channel> <atom:link href="https://yoursite.com/users/#{agent.user.id}/web_requests/#{agent.id}/secret1.xml" rel="self" type="application/rss+xml"/> <atom:icon>https://yoursite.com/favicon.ico</atom:icon> <title>XKCD comics as a feed</title> <description>This is a feed of recent XKCD comics, generated by Huginn</description> <link>https://yoursite.com</link> <lastBuildDate>#{Time.now.rfc2822}</lastBuildDate> <pubDate>#{Time.now.rfc2822}</pubDate> <ttl>60</ttl> <item> <title>Evolving yet again with a past date</title> <description>Secret hovertext: A small text</description> <link>http://imgs.xkcd.com/comics/evolving0.png</link> <pubDate>#{Time.zone.parse(event3.payload['date']).rfc2822}</pubDate> <category>Some category</category> <guid isPermaLink="false">#{event3.id}</guid> </item> <item> <title>Evolving again</title> <description>Secret hovertext: Something else</description> <link>http://imgs.xkcd.com/comics/evolving2.png</link> <pubDate>#{event2.created_at.rfc2822}</pubDate> <category>Category 1</category> <category>Category 2</category> <guid isPermaLink="false">#{event2.id}</guid> </item> <item> <title>Evolving</title> <description>Secret hovertext: Biologists play reverse Pokemon, trying to avoid putting any one team member on the front lines long enough for the experience to cause evolution.</description> <link>http://imgs.xkcd.com/comics/evolving.png</link> <pubDate>#{event1.created_at.rfc2822}</pubDate> <guid isPermaLink="false">#{event1.id}</guid> </item> </channel> </rss> XML end describe "with custom rss_content_type given" do before do agent.options['rss_content_type'] = 'text/xml' agent.save! end it "can output RSS with the Content-Type" do content, status, content_type = agent.receive_web_request({ 'secret' => 'secret1' }, 'get', 'text/xml') expect(status).to eq(200) expect(content_type).to eq('text/xml') end end it "can output RSS with hub links when push_hubs is specified" do allow(agent).to receive(:feed_link) { "https://yoursite.com" } agent.options[:push_hubs] = %w[https://pubsubhubbub.superfeedr.com/ https://pubsubhubbub.appspot.com/] content, status, content_type = agent.receive_web_request({ 'secret' => 'secret1' }, 'get', 'text/xml') expect(status).to eq(200) expect(content_type).to eq('application/rss+xml') xml = Nokogiri::XML(content) expect(xml.xpath('/rss/channel/atom:link[@rel="hub"]/@href').map(&:text).sort).to eq agent.options[:push_hubs].sort end it "can output JSON" do agent.options['template']['item']['foo'] = "hi" content, status, content_type = agent.receive_web_request({ 'secret' => 'secret2' }, 'get', 'application/json') expect(status).to eq(200) expect(content).to eq({ 'title' => 'XKCD comics as a feed', 'description' => 'This is a feed of recent XKCD comics, generated by Huginn', 'pubDate' => Time.now, 'items' => [ { 'title' => 'Evolving yet again with a past date', 'description' => 'Secret hovertext: A small text', 'link' => 'http://imgs.xkcd.com/comics/evolving0.png', 'guid' => {"contents" => event3.id, "isPermaLink" => "false"}, 'pubDate' => Time.zone.parse(event3.payload['date']).rfc2822, 'category' => ['Some category'], 'foo' => 'hi' }, { 'title' => 'Evolving again', 'description' => 'Secret hovertext: Something else', 'link' => 'http://imgs.xkcd.com/comics/evolving2.png', 'guid' => {"contents" => event2.id, "isPermaLink" => "false"}, 'pubDate' => event2.created_at.rfc2822, 'category' => ['Category 1', 'Category 2'], 'foo' => 'hi' }, { 'title' => 'Evolving', 'description' => 'Secret hovertext: Biologists play reverse Pokemon, trying to avoid putting any one team member on the front lines long enough for the experience to cause evolution.', 'link' => 'http://imgs.xkcd.com/comics/evolving.png', 'guid' => {"contents" => event1.id, "isPermaLink" => "false"}, 'pubDate' => event1.created_at.rfc2822, 'category' => [], 'foo' => 'hi' } ] }) end describe "with custom response_headers given" do before do agent.options['response_headers'] = {"Access-Control-Allow-Origin" => "*", "X-My-Custom-Header" => "hello"} agent.save! end it "can respond with custom headers" do content, status, content_type, response_headers = agent.receive_web_request({ 'secret' => 'secret1' }, 'get', 'text/xml') expect(status).to eq(200) expect(response_headers).to eq({"Access-Control-Allow-Origin" => "*", "X-My-Custom-Header" => "hello"}) end end context 'with more events' do let!(:event4) do agents(:bob_website_agent).create_event payload: { 'site_title' => 'XKCD', 'url' => 'http://imgs.xkcd.com/comics/comic1.png', 'title' => 'Comic 1', 'date' => '', 'hovertext' => 'Hovertext for Comic 1' } end let!(:event5) do agents(:bob_website_agent).create_event payload: { 'site_title' => 'XKCD', 'url' => 'http://imgs.xkcd.com/comics/comic2.png', 'title' => 'Comic 2', 'date' => '', 'hovertext' => 'Hovertext for Comic 2' } end let!(:event6) do agents(:bob_website_agent).create_event payload: { 'site_title' => 'XKCD', 'url' => 'http://imgs.xkcd.com/comics/comic3.png', 'title' => 'Comic 3', 'date' => '', 'hovertext' => 'Hovertext for Comic 3' } end describe 'limiting' do it 'can select the last `events_to_show` events' do agent.options['events_to_show'] = 2 content, _status, _content_type = agent.receive_web_request({ 'secret' => 'secret2' }, 'get', 'application/json') expect(content['items'].map {|i| i["title"] }).to eq(["Comic 3", "Comic 2"]) end end end describe 'ordering' do before do agent.options['events_order'] = ['{{hovertext}}'] agent.options['events_list_order'] = ['{{title}}'] end it 'can reorder the last `events_to_show` events based on a Liquid expression' do agent.options['events_to_show'] = 2 asc_content, _status, _content_type = agent.receive_web_request({ 'secret' => 'secret2' }, 'get', 'application/json') expect(asc_content['items'].map {|i| i["title"] }).to eq(["Evolving", "Evolving again"]) agent.options['events_to_show'] = 40 asc_content, _status, _content_type = agent.receive_web_request({ 'secret' => 'secret2' }, 'get', 'application/json') expect(asc_content['items'].map {|i| i["title"] }).to eq(["Evolving", "Evolving again", "Evolving yet again with a past date"]) agent.options['events_list_order'] = [['{{title}}', 'string', true]] desc_content, _status, _content_type = agent.receive_web_request({ 'secret' => 'secret2' }, 'get', 'application/json') expect(desc_content['items']).to eq(asc_content['items'].reverse) end end describe "interpolating \"events\"" do before do agent.options['template']['title'] = "XKCD comics as a feed{% if events.first.site_title %} ({{events.first.site_title}}){% endif %}" agent.save! end it "can output RSS" do allow(agent).to receive(:feed_link) { "https://yoursite.com" } content, status, content_type = agent.receive_web_request({ 'secret' => 'secret1' }, 'get', 'text/xml') expect(status).to eq(200) expect(content_type).to eq('application/rss+xml') expect(Nokogiri(content).at('/rss/channel/title/text()').text).to eq('XKCD comics as a feed (XKCD)') end it "can output JSON" do content, status, content_type = agent.receive_web_request({ 'secret' => 'secret2' }, 'get', 'application/json') expect(status).to eq(200) expect(content['title']).to eq('XKCD comics as a feed (XKCD)') end context "with event with \"events\"" do before do agent.sources.first.create_event payload: { 'site_title' => 'XKCD', 'url' => 'http://imgs.xkcd.com/comics/comicX.png', 'title' => 'Comic X', 'date' => '', 'hovertext' => 'Hovertext for Comic X', 'events' => 'Events!' } agent.options['template']['item']['events_data'] = "{{ events }}" agent.save! end it "can access the value without being overridden" do content, status, content_type = agent.receive_web_request({ 'secret' => 'secret2' }, 'get', 'application/json') expect(status).to eq(200) expect(content['items'].first['events_data']).to eq('Events!') end end end describe "with a specified icon" do before do agent.options['template']['icon'] = 'https://somesite.com/icon.png' agent.save! end it "can output RSS" do allow(agent).to receive(:feed_link) { "https://yoursite.com" } content, status, content_type = agent.receive_web_request({ 'secret' => 'secret1' }, 'get', 'text/xml') expect(status).to eq(200) expect(content_type).to eq('application/rss+xml') expect(Nokogiri(content).at('/rss/channel/atom:icon/text()').text).to eq('https://somesite.com/icon.png') end end describe "with media namespace not set" do before do agent.options['ns_media'] = nil agent.save! end it "can output RSS" do allow(agent).to receive(:feed_link) { "https://yoursite.com" } content, status, content_type = agent.receive_web_request({ 'secret' => 'secret1' }, 'get', 'text/xml') expect(status).to eq(200) expect(content_type).to eq('application/rss+xml') doc = Nokogiri(content) namespaces = doc.collect_namespaces expect(namespaces).not_to include("xmlns:media") end end describe "with media namespace set true" do before do agent.options['ns_media'] = 'true' agent.save! end it "can output RSS" do allow(agent).to receive(:feed_link) { "https://yoursite.com" } content, status, content_type = agent.receive_web_request({ 'secret' => 'secret1' }, 'get', 'text/xml') expect(status).to eq(200) expect(content_type).to eq('application/rss+xml') doc = Nokogiri(content) namespaces = doc.collect_namespaces expect(namespaces).to include( "xmlns:media" => 'http://search.yahoo.com/mrss/' ) end end describe "with media namespace set false" do before do agent.options['ns_media'] = 'false' agent.save! end it "can output RSS" do allow(agent).to receive(:feed_link) { "https://yoursite.com" } content, status, content_type = agent.receive_web_request({ 'secret' => 'secret1' }, 'get', 'text/xml') expect(status).to eq(200) expect(content_type).to eq('application/rss+xml') doc = Nokogiri(content) namespaces = doc.collect_namespaces expect(namespaces).not_to include("xmlns:media") end end describe "with itunes namespace not set" do before do agent.options['ns_itunes'] = nil agent.save! end it "can output RSS" do allow(agent).to receive(:feed_link) { "https://yoursite.com" } content, status, content_type = agent.receive_web_request({ 'secret' => 'secret1' }, 'get', 'text/xml') expect(status).to eq(200) expect(content_type).to eq('application/rss+xml') doc = Nokogiri(content) namespaces = doc.collect_namespaces expect(namespaces).not_to include("xmlns:itunes") expect(doc.at("/rss/channel/*[local-name()='itunes:image']")).to be_nil end end describe "with itunes namespace set true" do before do agent.options['ns_itunes'] = 'true' agent.save! end it "can output RSS" do allow(agent).to receive(:feed_link) { "https://yoursite.com" } content, status, content_type = agent.receive_web_request({ 'secret' => 'secret1' }, 'get', 'text/xml') expect(status).to eq(200) expect(content_type).to eq('application/rss+xml') doc = Nokogiri(content) namespaces = doc.collect_namespaces expect(namespaces).to include( "xmlns:itunes" => 'http://www.itunes.com/dtds/podcast-1.0.dtd' ) expect(doc.at('/rss/channel/itunes:image').attr('href')).to eq('https://yoursite.com/favicon.ico') end end describe "with itunes namespace set false" do before do agent.options['ns_itunes'] = 'false' agent.save! end it "can output RSS" do allow(agent).to receive(:feed_link) { "https://yoursite.com" } content, status, content_type = agent.receive_web_request({ 'secret' => 'secret1' }, 'get', 'text/xml') expect(status).to eq(200) expect(content_type).to eq('application/rss+xml') doc = Nokogiri(content) namespaces = doc.collect_namespaces expect(namespaces).not_to include("xmlns:itunes") end end end describe "outputting nesting" do before do agent.options['template']['item']['enclosure'] = { "_attributes" => { "type" => "audio/mpeg", "url" => "{{media_url}}" } } agent.options['template']['item']['foo'] = { "_attributes" => { "attr" => "attr-value-{{foo}}" }, "_contents" => "Foo: {{foo}}" } agent.options['template']['item']['nested'] = { "_attributes" => { "key" => "value" }, "_contents" => { "title" => "some title" } } agent.options['template']['item']['simpleNested'] = { "title" => "some title", "complex" => { "_attributes" => { "key" => "value" }, "_contents" => { "first" => { "_attributes" => { "a" => "b" }, "_contents" => { "second" => "value" } } } } } agent.save! end let!(:event) do agents(:bob_website_agent).create_event :payload => { "url" => "http://imgs.xkcd.com/comics/evolving.png", "title" => "Evolving", "hovertext" => "Biologists play reverse Pokemon, trying to avoid putting any one team member on the front lines long enough for the experience to cause evolution.", "media_url" => "http://google.com/audio.mpeg", "category" => ["Category 1", "Category 2"], "foo" => 1 } end it "can output JSON" do content, status, content_type = agent.receive_web_request({ 'secret' => 'secret2' }, 'get', 'application/json') expect(status).to eq(200) expect(content['items'].first).to eq( { 'title' => 'Evolving', 'description' => 'Secret hovertext: Biologists play reverse Pokemon, trying to avoid putting any one team member on the front lines long enough for the experience to cause evolution.', 'link' => 'http://imgs.xkcd.com/comics/evolving.png', 'guid' => {"contents" => event.id, "isPermaLink" => "false"}, 'pubDate' => event.created_at.rfc2822, 'category' => ['Category 1', 'Category 2'], 'enclosure' => { "type" => "audio/mpeg", "url" => "http://google.com/audio.mpeg" }, 'foo' => { 'attr' => 'attr-value-1', 'contents' => 'Foo: 1' }, 'nested' => { "key" => "value", "title" => "some title" }, 'simpleNested' => { "title" => "some title", "complex" => { "key"=>"value", "first" => { "a" => "b", "second"=>"value" } } } } ) end it "can output RSS" do allow(agent).to receive(:feed_link) { "https://yoursite.com" } content, status, content_type = agent.receive_web_request({ 'secret' => 'secret1' }, 'get', 'text/xml') expect(status).to eq(200) expect(content_type).to eq('application/rss+xml') expect(content.gsub(/\s+/, '')).to eq Utils.unindent(<<-XML).gsub(/\s+/, '') <?xml version="1.0" encoding="UTF-8" ?> <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" > <channel> <atom:link href="https://yoursite.com/users/#{agent.user.id}/web_requests/#{agent.id}/secret1.xml" rel="self" type="application/rss+xml"/> <atom:icon>https://yoursite.com/favicon.ico</atom:icon> <title>XKCD comics as a feed</title> <description>This is a feed of recent XKCD comics, generated by Huginn</description> <link>https://yoursite.com</link> <lastBuildDate>#{Time.now.rfc2822}</lastBuildDate> <pubDate>#{Time.now.rfc2822}</pubDate> <ttl>60</ttl> <item> <title>Evolving</title> <description>Secret hovertext: Biologists play reverse Pokemon, trying to avoid putting any one team member on the front lines long enough for the experience to cause evolution.</description> <link>http://imgs.xkcd.com/comics/evolving.png</link> <pubDate>#{event.created_at.rfc2822}</pubDate> <category>Category 1</category> <category>Category 2</category> <enclosure type="audio/mpeg" url="http://google.com/audio.mpeg" /> <foo attr="attr-value-1">Foo: 1</foo> <nested key="value"><title>some title</title></nested> <simpleNested> <title>some title</title> <complex key="value"> <first a="b"> <second>value</second> </first> </complex> </simpleNested> <guid isPermaLink="false">#{event.id}</guid> </item> </channel> </rss> XML end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/human_task_agent_spec.rb
spec/models/agents/human_task_agent_spec.rb
require 'rails_helper' describe Agents::HumanTaskAgent do before do @checker = Agents::HumanTaskAgent.new(name: 'my human task agent') @checker.options = @checker.default_options @checker.user = users(:bob) @checker.save! @event = Event.new @event.agent = agents(:bob_rain_notifier_agent) @event.payload = { 'foo' => { 'bar' => { 'baz' => 'a2b' } }, 'name' => 'Joe' } @event.id = 345 expect(@checker).to be_valid end describe 'validations' do it "validates that trigger_on is 'schedule' or 'event'" do @checker.options['trigger_on'] = 'foo' expect(@checker).not_to be_valid end it "requires expected_receive_period_in_days when trigger_on is set to 'event'" do @checker.options['trigger_on'] = 'event' @checker.options['expected_receive_period_in_days'] = nil expect(@checker).not_to be_valid @checker.options['expected_receive_period_in_days'] = 2 expect(@checker).to be_valid end it "requires a positive submission_period when trigger_on is set to 'schedule'" do @checker.options['trigger_on'] = 'schedule' @checker.options['submission_period'] = nil expect(@checker).not_to be_valid @checker.options['submission_period'] = 2 expect(@checker).to be_valid end it 'requires a hit.title' do @checker.options['hit']['title'] = '' expect(@checker).not_to be_valid end it 'requires a hit.description' do @checker.options['hit']['description'] = '' expect(@checker).not_to be_valid end it 'requires hit.assignments' do @checker.options['hit']['assignments'] = '' expect(@checker).not_to be_valid @checker.options['hit']['assignments'] = 0 expect(@checker).not_to be_valid @checker.options['hit']['assignments'] = 'moose' expect(@checker).not_to be_valid @checker.options['hit']['assignments'] = '2' expect(@checker).to be_valid end it 'requires hit.questions' do old_questions = @checker.options['hit']['questions'] @checker.options['hit']['questions'] = nil expect(@checker).not_to be_valid @checker.options['hit']['questions'] = [] expect(@checker).not_to be_valid @checker.options['hit']['questions'] = [old_questions[0]] expect(@checker).to be_valid end it 'requires that all questions have key, name, required, type, and question' do old_questions = @checker.options['hit']['questions'] @checker.options['hit']['questions'].first['key'] = '' expect(@checker).not_to be_valid @checker.options['hit']['questions'] = old_questions @checker.options['hit']['questions'].first['name'] = '' expect(@checker).not_to be_valid @checker.options['hit']['questions'] = old_questions @checker.options['hit']['questions'].first['required'] = nil expect(@checker).not_to be_valid @checker.options['hit']['questions'] = old_questions @checker.options['hit']['questions'].first['type'] = '' expect(@checker).not_to be_valid @checker.options['hit']['questions'] = old_questions @checker.options['hit']['questions'].first['question'] = '' expect(@checker).not_to be_valid end it "requires that all questions of type 'selection' have a selections array with keys and text" do @checker.options['hit']['questions'][0]['selections'] = [] expect(@checker).not_to be_valid @checker.options['hit']['questions'][0]['selections'] = [{}] expect(@checker).not_to be_valid @checker.options['hit']['questions'][0]['selections'] = [{ 'key' => '', 'text' => '' }] expect(@checker).not_to be_valid @checker.options['hit']['questions'][0]['selections'] = [{ 'key' => '', 'text' => 'hi' }] expect(@checker).not_to be_valid @checker.options['hit']['questions'][0]['selections'] = [{ 'key' => 'hi', 'text' => '' }] expect(@checker).not_to be_valid @checker.options['hit']['questions'][0]['selections'] = [{ 'key' => 'hi', 'text' => 'hi' }] expect(@checker).to be_valid @checker.options['hit']['questions'][0]['selections'] = [{ 'key' => 'hi', 'text' => 'hi' }, {}] expect(@checker).not_to be_valid end it "requires that 'poll_options' be present and populated when 'combination_mode' is set to 'poll'" do @checker.options['combination_mode'] = 'poll' expect(@checker).not_to be_valid @checker.options['poll_options'] = {} expect(@checker).not_to be_valid @checker.options['poll_options'] = { 'title' => 'Take a poll about jokes', 'instructions' => 'Rank these by how funny they are', 'assignments' => 3, 'row_template' => '{{joke}}' } expect(@checker).to be_valid @checker.options['poll_options'] = { 'instructions' => 'Rank these by how funny they are', 'assignments' => 3, 'row_template' => '{{joke}}' } expect(@checker).not_to be_valid @checker.options['poll_options'] = { 'title' => 'Take a poll about jokes', 'assignments' => 3, 'row_template' => '{{joke}}' } expect(@checker).not_to be_valid @checker.options['poll_options'] = { 'title' => 'Take a poll about jokes', 'instructions' => 'Rank these by how funny they are', 'row_template' => '{{joke}}' } expect(@checker).not_to be_valid @checker.options['poll_options'] = { 'title' => 'Take a poll about jokes', 'instructions' => 'Rank these by how funny they are', 'assignments' => 3 } expect(@checker).not_to be_valid end it "requires that all questions be of type 'selection' when 'combination_mode' is 'take_majority'" do @checker.options['combination_mode'] = 'take_majority' expect(@checker).not_to be_valid @checker.options['hit']['questions'][1]['type'] = 'selection' @checker.options['hit']['questions'][1]['selections'] = @checker.options['hit']['questions'][0]['selections'] expect(@checker).to be_valid end it "accepts 'take_majority': 'true' for legacy support" do @checker.options['take_majority'] = 'true' expect(@checker).not_to be_valid @checker.options['hit']['questions'][1]['type'] = 'selection' @checker.options['hit']['questions'][1]['selections'] = @checker.options['hit']['questions'][0]['selections'] expect(@checker).to be_valid end end describe "when 'trigger_on' is set to 'schedule'" do before do @checker.options['trigger_on'] = 'schedule' @checker.options['submission_period'] = '2' @checker.options.delete('expected_receive_period_in_days') end it 'should check for reviewable HITs frequently' do expect(@checker).to receive(:review_hits).twice expect(@checker).to receive(:create_basic_hit).once @checker.check @checker.check end it "should create HITs every 'submission_period' hours" do now = Time.now allow(Time).to receive(:now) { now } expect(@checker).to receive(:review_hits).exactly(3).times expect(@checker).to receive(:create_basic_hit).twice @checker.check now += 1 * 60 * 60 @checker.check now += 1 * 60 * 60 @checker.check end it 'should ignore events' do expect(@checker).not_to receive(:create_basic_hit).with(anything) @checker.receive([events(:bob_website_agent_event)]) end end describe "when 'trigger_on' is set to 'event'" do it 'should not create HITs during check but should check for reviewable HITs' do @checker.options['submission_period'] = '2' now = Time.now allow(Time).to receive(:now) { now } expect(@checker).to receive(:review_hits).exactly(3).times expect(@checker).not_to receive(:create_basic_hit) @checker.check now += 1 * 60 * 60 @checker.check now += 1 * 60 * 60 @checker.check end it 'should create HITs based on events' do expect(@checker).to receive(:create_basic_hit).with(events(:bob_website_agent_event)).once @checker.receive([events(:bob_website_agent_event)]) end end describe 'creating hits' do it 'can create HITs based on events, interpolating their values' do @checker.options['hit']['title'] = 'Hi {{name}}' @checker.options['hit']['description'] = 'Make something for {{name}}' @checker.options['hit']['questions'][0]['name'] = '{{name}} Question 1' question_form = nil hit_interface = double('hit_interface', id: 123, url: 'https://') allow(hit_interface).to receive(:question_form).with(instance_of(Agents::HumanTaskAgent::AgentQuestionForm)) { |agent_question_form_instance| question_form = agent_question_form_instance } allow(hit_interface).to receive(:max_assignments=).with(@checker.options['hit']['assignments']) allow(hit_interface).to receive(:description=).with('Make something for Joe') allow(hit_interface).to receive(:lifetime=) allow(hit_interface).to receive(:reward=).with(@checker.options['hit']['reward']) expect(RTurk::Hit).to receive(:create).with(title: 'Hi Joe').and_yield(hit_interface).and_return(hit_interface) @checker.send :create_basic_hit, @event xml = question_form.to_xml expect(xml).to include('<Title>Hi Joe</Title>') expect(xml).to include('<Text>Make something for Joe</Text>') expect(xml).to include('<DisplayName>Joe Question 1</DisplayName>') expect(@checker.memory['hits'][123]['event_id']).to eq(@event.id) end it 'works without an event too' do @checker.options['hit']['title'] = 'Hi {{name}}' hit_interface = double('hit_interface', id: 123, url: 'https://') allow(hit_interface).to receive(:question_form).with(instance_of(Agents::HumanTaskAgent::AgentQuestionForm)) allow(hit_interface).to receive(:max_assignments=).with(@checker.options['hit']['assignments']) allow(hit_interface).to receive(:description=) allow(hit_interface).to receive(:lifetime=) allow(hit_interface).to receive(:reward=).with(@checker.options['hit']['reward']) expect(RTurk::Hit).to receive(:create).with(title: 'Hi').and_yield(hit_interface).and_return(hit_interface) @checker.send :create_basic_hit end end describe 'reviewing HITs' do class FakeHit def initialize(options = {}) @options = options end def assignments @options[:assignments] || [] end def max_assignments @options[:max_assignments] || 1 end def dispose! @disposed = true end def disposed? @disposed end end class FakeAssignment attr_accessor :approved def initialize(options = {}) @options = options end def answers @options[:answers] || {} end def status @options[:status] || '' end def approve! @approved = true end end it 'should work on multiple HITs' do event2 = Event.new event2.agent = agents(:bob_rain_notifier_agent) event2.payload = { 'foo2' => { 'bar2' => { 'baz2' => 'a2b2' } }, 'name2' => 'Joe2' } event2.id = 3452 # It knows about two HITs from two different events. @checker.memory['hits'] = {} @checker.memory['hits']['JH3132836336DHG'] = { 'event_id' => @event.id } @checker.memory['hits']['JH39AA63836DHG'] = { 'event_id' => event2.id } hit_ids = %w[JH3132836336DHG JH39AA63836DHG JH39AA63836DH12345] expect(RTurk::GetReviewableHITs).to receive(:create) { double(hit_ids:) } # It sees 3 HITs. # It looksup the two HITs that it owns. Neither are ready yet. expect(RTurk::Hit).to receive(:new).with('JH3132836336DHG') { FakeHit.new } expect(RTurk::Hit).to receive(:new).with('JH39AA63836DHG') { FakeHit.new } @checker.send :review_hits end it "shouldn't do anything if an assignment isn't ready" do @checker.memory['hits'] = { 'JH3132836336DHG' => { 'event_id' => @event.id } } expect(RTurk::GetReviewableHITs).to receive(:create) { double(hit_ids: %w[JH3132836336DHG JH39AA63836DHG JH39AA63836DH12345]) } assignments = [ FakeAssignment.new(status: 'Accepted', answers: {}), FakeAssignment.new(status: 'Submitted', answers: { 'sentiment' => 'happy', 'feedback' => 'Take 2' }) ] hit = FakeHit.new(max_assignments: 2, assignments:) expect(RTurk::Hit).to receive(:new).with('JH3132836336DHG') { hit } # One of the assignments isn't set to "Submitted", so this should get skipped for now. expect_any_instance_of(FakeAssignment).not_to receive(:answers) @checker.send :review_hits expect(assignments.all? { |a| a.approved == true }).to be_falsey expect(@checker.memory['hits']).to eq({ 'JH3132836336DHG' => { 'event_id' => @event.id } }) end it "shouldn't do anything if an assignment is missing" do @checker.memory['hits'] = { 'JH3132836336DHG' => { 'event_id' => @event.id } } expect(RTurk::GetReviewableHITs).to receive(:create) { double(hit_ids: %w[JH3132836336DHG JH39AA63836DHG JH39AA63836DH12345]) } assignments = [ FakeAssignment.new(status: 'Submitted', answers: { 'sentiment' => 'happy', 'feedback' => 'Take 2' }) ] hit = FakeHit.new(max_assignments: 2, assignments:) expect(RTurk::Hit).to receive(:new).with('JH3132836336DHG') { hit } # One of the assignments hasn't shown up yet, so this should get skipped for now. expect_any_instance_of(FakeAssignment).not_to receive(:answers) @checker.send :review_hits expect(assignments.all? { |a| a.approved == true }).to be_falsey expect(@checker.memory['hits']).to eq({ 'JH3132836336DHG' => { 'event_id' => @event.id } }) end context 'emitting events' do before do @checker.memory['hits'] = { 'JH3132836336DHG' => { 'event_id' => @event.id } } expect(RTurk::GetReviewableHITs).to receive(:create) { double(hit_ids: %w[JH3132836336DHG JH39AA63836DHG JH39AA63836DH12345]) } @assignments = [ FakeAssignment.new(status: 'Submitted', answers: { 'sentiment' => 'neutral', 'feedback' => '' }), FakeAssignment.new(status: 'Submitted', answers: { 'sentiment' => 'happy', 'feedback' => 'Take 2' }) ] @hit = FakeHit.new(max_assignments: 2, assignments: @assignments) expect(@hit).not_to be_disposed expect(RTurk::Hit).to receive(:new).with('JH3132836336DHG') { @hit } end it 'should create events when all assignments are ready' do expect do @checker.send :review_hits end.to change { Event.count }.by(1) expect(@assignments.all? { |a| a.approved == true }).to be_truthy expect(@hit).to be_disposed expect(@checker.events.last.payload['answers']).to eq([ { 'sentiment' => 'neutral', 'feedback' => '' }, { 'sentiment' => 'happy', 'feedback' => 'Take 2' } ]) expect(@checker.memory['hits']).to eq({}) end it 'should emit separate answers when options[:separate_answers] is true' do @checker.options[:separate_answers] = true expect do @checker.send :review_hits end.to change { Event.count }.by(2) expect(@assignments.all? { |a| a.approved == true }).to be_truthy expect(@hit).to be_disposed event1, event2 = @checker.events.last(2) expect(event1.payload).not_to have_key('answers') expect(event2.payload).not_to have_key('answers') expect(event1.payload['answer']).to eq({ 'sentiment' => 'happy', 'feedback' => 'Take 2' }) expect(event2.payload['answer']).to eq({ 'sentiment' => 'neutral', 'feedback' => '' }) expect(@checker.memory['hits']).to eq({}) end end describe 'taking majority votes' do before do @checker.options['combination_mode'] = 'take_majority' @checker.memory['hits'] = { 'JH3132836336DHG' => { 'event_id' => @event.id } } expect(RTurk::GetReviewableHITs).to receive(:create) { double(hit_ids: %w[JH3132836336DHG JH39AA63836DHG JH39AA63836DH12345]) } end it 'should take the majority votes of all questions' do @checker.options['hit']['questions'][1] = { 'type' => 'selection', 'key' => 'age_range', 'name' => 'Age Range', 'required' => 'true', 'question' => 'Please select your age range:', 'selections' => [ { 'key' => '<50', 'text' => '50 years old or younger' }, { 'key' => '>50', 'text' => 'Over 50 years old' } ] } assignments = [ FakeAssignment.new(status: 'Submitted', answers: { 'sentiment' => 'sad', 'age_range' => '<50' }), FakeAssignment.new(status: 'Submitted', answers: { 'sentiment' => 'neutral', 'age_range' => '>50' }), FakeAssignment.new(status: 'Submitted', answers: { 'sentiment' => 'happy', 'age_range' => '>50' }), FakeAssignment.new(status: 'Submitted', answers: { 'sentiment' => 'happy', 'age_range' => '>50' }) ] hit = FakeHit.new(max_assignments: 4, assignments:) expect(RTurk::Hit).to receive(:new).with('JH3132836336DHG') { hit } expect do @checker.send :review_hits end.to change { Event.count }.by(1) expect(assignments.all? { |a| a.approved == true }).to be_truthy expect(@checker.events.last.payload['answers']).to eq([ { 'sentiment' => 'sad', 'age_range' => '<50' }, { 'sentiment' => 'neutral', 'age_range' => '>50' }, { 'sentiment' => 'happy', 'age_range' => '>50' }, { 'sentiment' => 'happy', 'age_range' => '>50' } ]) expect(@checker.events.last.payload['counts']).to eq({ 'sentiment' => { 'happy' => 2, 'sad' => 1, 'neutral' => 1 }, 'age_range' => { '>50' => 3, '<50' => 1 } }) expect(@checker.events.last.payload['majority_answer']).to eq({ 'sentiment' => 'happy', 'age_range' => '>50' }) expect(@checker.events.last.payload).not_to have_key('average_answer') expect(@checker.memory['hits']).to eq({}) end it 'should also provide an average answer when all questions are numeric' do # it should accept 'take_majority': 'true' as well for legacy support. Demonstrating that here. @checker.options.delete :combination_mode @checker.options['take_majority'] = 'true' @checker.options['hit']['questions'] = [ { 'type' => 'selection', 'key' => 'rating', 'name' => 'Rating', 'required' => 'true', 'question' => 'Please select a rating:', 'selections' => [ { 'key' => '1', 'text' => 'One' }, { 'key' => '2', 'text' => 'Two' }, { 'key' => '3', 'text' => 'Three' }, { 'key' => '4', 'text' => 'Four' }, { 'key' => '5.1', 'text' => 'Five Point One' } ] } ] assignments = [ FakeAssignment.new(status: 'Submitted', answers: { 'rating' => '1' }), FakeAssignment.new(status: 'Submitted', answers: { 'rating' => '3' }), FakeAssignment.new(status: 'Submitted', answers: { 'rating' => '5.1' }), FakeAssignment.new(status: 'Submitted', answers: { 'rating' => '2' }), FakeAssignment.new(status: 'Submitted', answers: { 'rating' => '2' }) ] hit = FakeHit.new(max_assignments: 5, assignments:) expect(RTurk::Hit).to receive(:new).with('JH3132836336DHG') { hit } expect do @checker.send :review_hits end.to change { Event.count }.by(1) expect(assignments.all? { |a| a.approved == true }).to be_truthy expect(@checker.events.last.payload['answers']).to eq([ { 'rating' => '1' }, { 'rating' => '3' }, { 'rating' => '5.1' }, { 'rating' => '2' }, { 'rating' => '2' } ]) expect(@checker.events.last.payload['counts']).to eq({ 'rating' => { '1' => 1, '2' => 2, '3' => 1, '4' => 0, '5.1' => 1 } }) expect(@checker.events.last.payload['majority_answer']).to eq({ 'rating' => '2' }) expect(@checker.events.last.payload['average_answer']).to eq({ 'rating' => (1 + 2 + 2 + 3 + 5.1) / 5.0 }) expect(@checker.memory['hits']).to eq({}) end end describe 'creating and reviewing polls' do before do @checker.options['combination_mode'] = 'poll' @checker.options['poll_options'] = { 'title' => 'Hi!', 'instructions' => 'hello!', 'assignments' => 2, 'row_template' => 'This is {{sentiment}}' } @event.save! expect(RTurk::GetReviewableHITs).to receive(:create) { double(hit_ids: %w[JH3132836336DHG JH39AA63836DHG JH39AA63836DH12345]) } end it 'creates a poll using the row_template, message, and correct number of assignments' do @checker.memory['hits'] = { 'JH3132836336DHG' => { 'event_id' => @event.id } } # Mock out the HIT's submitted assignments. assignments = [ FakeAssignment.new(status: 'Submitted', answers: { 'sentiment' => 'sad', 'feedback' => 'This is my feedback 1' }), FakeAssignment.new(status: 'Submitted', answers: { 'sentiment' => 'neutral', 'feedback' => 'This is my feedback 2' }), FakeAssignment.new(status: 'Submitted', answers: { 'sentiment' => 'happy', 'feedback' => 'This is my feedback 3' }), FakeAssignment.new(status: 'Submitted', answers: { 'sentiment' => 'happy', 'feedback' => 'This is my feedback 4' }) ] hit = FakeHit.new(max_assignments: 4, assignments:) expect(RTurk::Hit).to receive(:new).with('JH3132836336DHG') { hit } expect(@checker.memory['hits']['JH3132836336DHG']).to be_present # Setup mocks for HIT creation question_form = nil hit_interface = double('hit_interface', id: 'JH39AA63836DH12345', url: 'https://') allow(hit_interface).to receive(:question_form).with(instance_of(Agents::HumanTaskAgent::AgentQuestionForm)) { |agent_question_form_instance| question_form = agent_question_form_instance } allow(hit_interface).to receive(:max_assignments=).with(@checker.options['poll_options']['assignments']) allow(hit_interface).to receive(:description=).with(@checker.options['poll_options']['instructions']) allow(hit_interface).to receive(:lifetime=) allow(hit_interface).to receive(:reward=).with(@checker.options['hit']['reward']) expect(RTurk::Hit).to receive(:create).with(title: 'Hi!').and_yield(hit_interface).and_return(hit_interface) # And finally, the test. # it does not emit an event until all poll results are in expect do @checker.send :review_hits end.to change { Event.count }.by(0) # it approves the existing assignments expect(assignments.all? { |a| a.approved == true }).to be_truthy expect(hit).to be_disposed # it creates a new HIT for the poll xml = question_form.to_xml expect(xml).to include('<Text>This is happy</Text>') expect(xml).to include('<Text>This is neutral</Text>') expect(xml).to include('<Text>This is sad</Text>') @checker.save @checker.reload expect(@checker.memory['hits']['JH3132836336DHG']).not_to be_present expect(@checker.memory['hits']['JH39AA63836DH12345']).to be_present expect(@checker.memory['hits']['JH39AA63836DH12345']['event_id']).to eq(@event.id) expect(@checker.memory['hits']['JH39AA63836DH12345']['type']).to eq('poll') expect(@checker.memory['hits']['JH39AA63836DH12345']['original_hit']).to eq('JH3132836336DHG') expect(@checker.memory['hits']['JH39AA63836DH12345']['answers'].length).to eq(4) end it 'emits an event when all poll results are in, containing the data from the best answer, plus all others' do original_answers = [ { 'sentiment' => 'sad', 'feedback' => 'This is my feedback 1' }, { 'sentiment' => 'neutral', 'feedback' => 'This is my feedback 2' }, { 'sentiment' => 'happy', 'feedback' => 'This is my feedback 3' }, { 'sentiment' => 'happy', 'feedback' => 'This is my feedback 4' } ] @checker.memory['hits'] = { 'JH39AA63836DH12345' => { 'type' => 'poll', 'original_hit' => 'JH3132836336DHG', 'answers' => original_answers, 'event_id' => 345 } } # Mock out the HIT's submitted assignments. assignments = [ FakeAssignment.new(status: 'Submitted', answers: { '1' => '2', '2' => '5', '3' => '3', '4' => '2' }), FakeAssignment.new(status: 'Submitted', answers: { '1' => '3', '2' => '4', '3' => '1', '4' => '4' }) ] hit = FakeHit.new(max_assignments: 2, assignments:) expect(RTurk::Hit).to receive(:new).with('JH39AA63836DH12345') { hit } expect(@checker.memory['hits']['JH39AA63836DH12345']).to be_present expect do @checker.send :review_hits end.to change { Event.count }.by(1) # It emits an event expect(@checker.events.last.payload['answers']).to eq(original_answers) expect(@checker.events.last.payload['poll']).to eq([{ '1' => '2', '2' => '5', '3' => '3', '4' => '2' }, { '1' => '3', '2' => '4', '3' => '1', '4' => '4' }]) expect(@checker.events.last.payload['best_answer']).to eq({ 'sentiment' => 'neutral', 'feedback' => 'This is my feedback 2' }) # it approves the existing assignments expect(assignments.all? { |a| a.approved == true }).to be_truthy expect(hit).to be_disposed expect(@checker.memory['hits']).to be_empty end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/liquid_output_agent_spec.rb
spec/models/agents/liquid_output_agent_spec.rb
# encoding: utf-8 require 'rails_helper' describe Agents::LiquidOutputAgent do let(:agent) do _agent = Agents::LiquidOutputAgent.new(name: 'My Data Output Agent') _agent.options = _agent.default_options.merge( 'secret' => 'a secret1', 'events_to_show' => 3, ) _agent.user = users(:bob) _agent.sources << agents(:bob_website_agent) _agent.save! _agent end let(:event_struct) { Struct.new(:payload) } describe "#working?" do it "checks if events have been received within expected receive period" do expect(agent).not_to be_working Agents::LiquidOutputAgent.async_receive agent.id, [events(:bob_website_agent_event).id] expect(agent.reload).to be_working two_days_from_now = 2.days.from_now allow(Time).to receive(:now) { two_days_from_now } expect(agent.reload).not_to be_working end end describe "validation" do before do expect(agent).to be_valid end it "should validate presence and length of secret" do agent.options[:secret] = "" expect(agent).not_to be_valid agent.options[:secret] = "foo" expect(agent).to be_valid agent.options[:secret] = "foo/bar" expect(agent).not_to be_valid agent.options[:secret] = "foo.xml" expect(agent).not_to be_valid agent.options[:secret] = false expect(agent).not_to be_valid agent.options[:secret] = [] expect(agent).not_to be_valid agent.options[:secret] = ["foo.xml"] expect(agent).not_to be_valid agent.options[:secret] = ["hello", true] expect(agent).not_to be_valid agent.options[:secret] = ["hello"] expect(agent).not_to be_valid agent.options[:secret] = ["hello", "world"] expect(agent).not_to be_valid end it "should validate presence of expected_receive_period_in_days" do agent.options[:expected_receive_period_in_days] = "" expect(agent).not_to be_valid agent.options[:expected_receive_period_in_days] = 0 expect(agent).not_to be_valid agent.options[:expected_receive_period_in_days] = -1 expect(agent).not_to be_valid end it "should validate the event_limit" do agent.options[:event_limit] = "" expect(agent).to be_valid agent.options[:event_limit] = "1" expect(agent).to be_valid agent.options[:event_limit] = "1001" expect(agent).not_to be_valid agent.options[:event_limit] = "10000" expect(agent).not_to be_valid end it "should validate the event_limit with relative time" do agent.options[:event_limit] = "15 minutes" expect(agent).to be_valid agent.options[:event_limit] = "1 century" expect(agent).not_to be_valid end it "should not allow non-integer event limits" do agent.options[:event_limit] = "abc1234" expect(agent).not_to be_valid end end describe "#receive?" do let(:key) { SecureRandom.uuid } let(:value) { SecureRandom.uuid } let(:incoming_events) do last_payload = { key => value } [event_struct.new( { key => SecureRandom.uuid } ), event_struct.new( { key => SecureRandom.uuid } ), event_struct.new(last_payload)] end describe "and the mode is last event in" do before { agent.options['mode'] = 'Last event in' } it "stores the last event in memory" do agent.receive incoming_events expect(agent.memory['last_event'][key]).to equal(value) end describe "but the casing is wrong" do before { agent.options['mode'] = 'LAST EVENT IN' } it "stores the last event in memory" do agent.receive incoming_events expect(agent.memory['last_event'][key]).to equal(value) end end end describe "but the mode is merge" do let(:second_key) { SecureRandom.uuid } let(:second_value) { SecureRandom.uuid } before { agent.options['mode'] = 'Merge events' } let(:incoming_events) do last_payload = { key => value } [event_struct.new( { key => SecureRandom.uuid, second_key => second_value } ), event_struct.new(last_payload)] end it "should merge all of the events passed to it" do agent.receive incoming_events expect(agent.memory['last_event'][key]).to equal(value) expect(agent.memory['last_event'][second_key]).to equal(second_value) end describe "but the casing on the mode is wrong" do before { agent.options['mode'] = 'MERGE EVENTS' } it "should merge all of the events passed to it" do agent.receive incoming_events expect(agent.memory['last_event'][key]).to equal(value) expect(agent.memory['last_event'][second_key]).to equal(second_value) end end end describe "but the mode is anything else" do before { agent.options['mode'] = SecureRandom.uuid } let(:incoming_events) do last_payload = { key => value } [event_struct.new(last_payload)] end it "should update nothing" do expect { agent.receive incoming_events }.not_to change { agent.reload.memory&.fetch("last_event", nil) } end end end describe "#count_limit" do it "should have a default of 1000" do agent.options['event_limit'] = nil expect(agent.send(:count_limit)).to eq(1000) agent.options['event_limit'] = '' expect(agent.send(:count_limit)).to eq(1000) agent.options['event_limit'] = ' ' expect(agent.send(:count_limit)).to eq(1000) end it "should convert string count limits to integers" do agent.options['event_limit'] = '1' expect(agent.send(:count_limit)).to eq(1) agent.options['event_limit'] = '2' expect(agent.send(:count_limit)).to eq(2) agent.options['event_limit'] = 3 expect(agent.send(:count_limit)).to eq(3) end it "should default to 1000 with invalid values" do agent.options['event_limit'] = SecureRandom.uuid expect(agent.send(:count_limit)).to eq(1000) agent.options['event_limit'] = 'John Galt' expect(agent.send(:count_limit)).to eq(1000) end it "should not allow event limits above 1000" do agent.options['event_limit'] = '1001' expect(agent.send(:count_limit)).to eq(1000) agent.options['event_limit'] = '5000' expect(agent.send(:count_limit)).to eq(1000) end end describe "#receive_web_request" do let(:secret) { SecureRandom.uuid } let(:headers) { {} } let(:params) { { 'secret' => secret } } let(:format) { :html } let(:request) { instance_double( ActionDispatch::Request, headers:, params:, format:, ) } let(:mime_type) { SecureRandom.uuid } let(:content) { "The key is {{#{key}}}." } let(:key) { SecureRandom.uuid } let(:value) { SecureRandom.uuid } before do agent.options['secret'] = secret agent.options['mime_type'] = mime_type agent.options['content'] = content agent.memory['last_event'] = { key => value } agent.save! agents(:bob_website_agent).events.destroy_all end it "should output LF-terminated lines if line_break_is_lf is true" do agent.options["content"] = "hello\r\nworld\r\n" result = agent.receive_web_request request expect(result[0]).to eq "hello\r\nworld\r\n" agent.options["line_break_is_lf"] = "true" result = agent.receive_web_request request expect(result[0]).to eq "hello\nworld\n" agent.options["line_break_is_lf"] = "false" result = agent.receive_web_request request expect(result[0]).to eq "hello\r\nworld\r\n" end it 'should respond with custom response header if configured with `response_headers` option' do agent.options['response_headers'] = { "X-My-Custom-Header" => 'hello' } result = agent.receive_web_request request expect(result).to match([ "The key is #{value}.", 200, mime_type, a_hash_including( "Cache-Control" => a_kind_of(String), "ETag" => a_kind_of(String), "Last-Modified" => a_kind_of(String), "X-My-Custom-Header" => "hello" ) ]) end it 'should allow the usage custom liquid tags' do agent.options['content'] = "{% credential aws_secret %}" result = agent.receive_web_request request expect(result).to match([ "1111111111-bob", 200, mime_type, a_hash_including( "Cache-Control" => a_kind_of(String), "ETag" => a_kind_of(String), "Last-Modified" => a_kind_of(String), ) ]) end describe "when requested with or without the If-None-Match header" do let(:now) { Time.now } it "should conditionally return 304 responses whenever ETag matches" do travel_to now allow(agent).to receive(:liquified_content).and_call_original result = agent.receive_web_request request expect(result).to eq([ "The key is #{value}.", 200, mime_type, { 'Cache-Control' => "max-age=#{agent.options['expected_receive_period_in_days'].to_i * 86400}", 'ETag' => agent.etag, 'Last-Modified' => agent.memory['last_modified_at'].to_time.httpdate, } ]) expect(agent).to have_received(:liquified_content).once travel_to now + 1 request.headers['If-None-Match'] = agent.etag result = agent.receive_web_request request expect(result).to eq([nil, 304, {}]) expect(agent).to have_received(:liquified_content).once # Receiving an event will update the ETag and Last-Modified-At event = agents(:bob_website_agent).events.create!(payload: { key => 'latest' }) AgentReceiveJob.perform_now agent.id, [event.id] agent.reload travel_to now + 2 result = agent.receive_web_request request expect(result).to eq(["The key is latest.", 200, mime_type, { 'Cache-Control' => "max-age=#{agent.options['expected_receive_period_in_days'].to_i * 86400}", 'ETag' => agent.etag, 'Last-Modified' => agent.last_receive_at.httpdate, }]) expect(agent).to have_received(:liquified_content).twice travel_to now + 3 request.headers['If-None-Match'] = agent.etag result = agent.receive_web_request request expect(result).to eq([nil, 304, {}]) expect(agent).to have_received(:liquified_content).twice # Changing options will update the ETag and Last-Modified-At agent.update!(options: agent.options.merge('content' => "The key is now {{#{key}}}.")) agent.reload result = agent.receive_web_request request expect(result).to eq(["The key is now latest.", 200, mime_type, { 'Cache-Control' => "max-age=#{agent.options['expected_receive_period_in_days'].to_i * 86400}", 'ETag' => agent.etag, 'Last-Modified' => (now + 3).httpdate, }]) expect(agent).to have_received(:liquified_content).exactly(3).times end end describe "and the mode is last event in" do before { agent.options['mode'] = 'Last event in' } it "should render the results as a liquid template from the last event in" do result = agent.receive_web_request request expect(result[0]).to eq("The key is #{value}.") expect(result[1]).to eq(200) expect(result[2]).to eq(mime_type) end describe "but the casing is wrong" do before { agent.options['mode'] = 'last event in' } it "should render the results as a liquid template from the last event in" do result = agent.receive_web_request request expect(result).to match(["The key is #{value}.", 200, mime_type, a_kind_of(Hash)]) end end end describe "and the mode is merge events" do before { agent.options['mode'] = 'Merge events' } it "should render the results as a liquid template from the last event in" do result = agent.receive_web_request request expect(result).to match(["The key is #{value}.", 200, mime_type, a_kind_of(Hash)]) end end describe "and the mode is last X events" do before do agent.options['mode'] = 'Last X events' agents(:bob_website_agent).create_event payload: { "name" => "Dagny Taggart", "book" => "Atlas Shrugged" } agents(:bob_website_agent).create_event payload: { "name" => "John Galt", "book" => "Atlas Shrugged" } agents(:bob_website_agent).create_event payload: { "name" => "Howard Roark", "book" => "The Fountainhead" } agent.options['content'] = <<EOF <table> {% for event in events %} <tr> <td>{{ event.name }}</td> <td>{{ event.book }}</td> </tr> {% endfor %} </table> EOF end it "should render the results as a liquid template from the last event in, limiting to 2" do agent.options['event_limit'] = 2 result = agent.receive_web_request request expect(result[0]).to eq <<EOF <table> <tr> <td>Howard Roark</td> <td>The Fountainhead</td> </tr> <tr> <td>John Galt</td> <td>Atlas Shrugged</td> </tr> </table> EOF end it "should render the results as a liquid template from the last event in, limiting to 1" do agent.options['event_limit'] = 1 result = agent.receive_web_request request expect(result[0]).to eq <<EOF <table> <tr> <td>Howard Roark</td> <td>The Fountainhead</td> </tr> </table> EOF end it "should render the results as a liquid template from the last event in, allowing no limit" do agent.options['event_limit'] = '' result = agent.receive_web_request request expect(result[0]).to eq <<EOF <table> <tr> <td>Howard Roark</td> <td>The Fountainhead</td> </tr> <tr> <td>John Galt</td> <td>Atlas Shrugged</td> </tr> <tr> <td>Dagny Taggart</td> <td>Atlas Shrugged</td> </tr> </table> EOF end it "should allow the limiting by time, as well" do one_event = agent.received_events.select { |x| x.payload['name'] == 'John Galt' }.first one_event.created_at = 2.days.ago one_event.save! agent.options['event_limit'] = '1 day' result = agent.receive_web_request request expect(result[0]).to eq <<EOF <table> <tr> <td>Howard Roark</td> <td>The Fountainhead</td> </tr> <tr> <td>Dagny Taggart</td> <td>Atlas Shrugged</td> </tr> </table> EOF end it "should not be case sensitive when limiting on time" do one_event = agent.received_events.select { |x| x.payload['name'] == 'John Galt' }.first one_event.created_at = 2.days.ago one_event.save! agent.options['event_limit'] = '1 DaY' result = agent.receive_web_request request expect(result[0]).to eq <<EOF <table> <tr> <td>Howard Roark</td> <td>The Fountainhead</td> </tr> <tr> <td>Dagny Taggart</td> <td>Atlas Shrugged</td> </tr> </table> EOF end it "it should continue to work when the event limit is wrong" do agent.options['event_limit'] = 'five days' result = agent.receive_web_request request expect(result[0]).to include("Howard Roark") expect(result[0]).to include("Dagny Taggart") expect(result[0]).to include("John Galt") agent.options['event_limit'] = '5 quibblequarks' result = agent.receive_web_request request expect(result[0]).to include("Howard Roark") expect(result[0]).to include("Dagny Taggart") expect(result[0]).to include("John Galt") end describe "but the mode was set to last X events with the wrong casing" do before { agent.options['mode'] = 'LAST X EVENTS' } it "should still work as last x events" do result = agent.receive_web_request request expect(result[0]).to include("Howard Roark") expect(result[0]).to include("Dagny Taggart") expect(result[0]).to include("John Galt") end end end describe "but the secret provided does not match" do before { params['secret'] = SecureRandom.uuid } it "should return a 401 response" do result = agent.receive_web_request request expect(result[0]).to eq("Not Authorized") expect(result[1]).to eq(401) end context 'if the format is json' do let(:format) { :json } it "should return a 401 json response " do result = agent.receive_web_request request expect(result[0][:error]).to eq("Not Authorized") expect(result[1]).to eq(401) end end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/twilio_agent_spec.rb
spec/models/agents/twilio_agent_spec.rb
require 'rails_helper' describe Agents::TwilioAgent do before do @checker = Agents::TwilioAgent.new(:name => 'somename', :options => { :account_sid => 'x', :auth_token => 'x', :sender_cell => 'x', :receiver_cell => '{{to}}', :server_url => 'http://somename.com:3000', :receive_text => 'true', :receive_call => 'true', :expected_receive_period_in_days => '1' }) @checker.user = users(:bob) @checker.save! @event = Event.new @event.agent = agents(:bob_weather_agent) @event.payload = {message: 'Looks like its going to rain', to: 54321} @event.save! @messages = [] @calls = [] allow(Twilio::REST::Client).to receive(:new) do instance_double(Twilio::REST::Client).tap { |c| allow(c).to receive(:calls) do double.tap { |l| allow(l).to receive(:create) do |message| @calls << message end } end allow(c).to receive(:messages) do double.tap { |l| allow(l).to receive(:create) do |message| @messages << message end } end } end end describe '#receive' do it 'should make sure multiple events are being received' do event1 = Event.new event1.agent = agents(:bob_rain_notifier_agent) event1.payload = {message: 'Some message', to: 12345} event1.save! event2 = Event.new event2.agent = agents(:bob_weather_agent) event2.payload = {message: 'Some other message', to: 987654} event2.save! @checker.receive([@event,event1,event2]) expect(@messages).to eq [ {from: "x", to: "54321", body: "Looks like its going to rain"}, {from: "x", to: "12345", body: "Some message"}, {from: "x", to: "987654", body: "Some other message"} ] end it 'should check if receive_text is working fine' do @checker.options[:receive_text] = 'false' @checker.receive([@event]) expect(@messages).to be_empty end it 'should check if receive_call is working fine' do @checker.options[:receive_call] = 'true' @checker.receive([@event]) expect(@checker.memory[:pending_calls]).not_to eq({}) end end describe '#working?' do it 'checks if events have been received within the expected receive period' do expect(@checker).not_to be_working # No events received Agents::TwilioAgent.async_receive @checker.id, [@event.id] expect(@checker.reload).to be_working # Just received events two_days_from_now = 2.days.from_now allow(Time).to receive(:now) { two_days_from_now } expect(@checker.reload).not_to be_working # More time has passed than the expected receive period without any new events end end describe "validation" do before do expect(@checker).to be_valid end it "should validate presence of of account_sid" do @checker.options[:account_sid] = "" expect(@checker).not_to be_valid end it "should validate presence of auth_token" do @checker.options[:auth_token] = "" expect(@checker).not_to be_valid end it "should validate presence of receiver_cell" do @checker.options[:receiver_cell] = "" expect(@checker).not_to be_valid end it "should validate presence of sender_cell" do @checker.options[:sender_cell] = "" expect(@checker).not_to be_valid end it "should make sure filling sure filling server_url is not necessary" do @checker.options[:server_url] = "" expect(@checker).to be_valid end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/jabber_agent_spec.rb
spec/models/agents/jabber_agent_spec.rb
require 'rails_helper' describe Agents::JabberAgent do let(:sent) { [] } let(:config) { { jabber_server: '127.0.0.1', jabber_port: '5222', jabber_sender: 'foo@localhost', jabber_receiver: 'bar@localhost', jabber_password: 'password', message: 'Warning! {{title}} - {{url}}', expected_receive_period_in_days: '2' } } let(:agent) do Agents::JabberAgent.new(name: 'Jabber Agent', options: config).tap do |a| a.user = users(:bob) a.save! end end let(:event) do Event.new.tap do |e| e.agent = agents(:bob_weather_agent) e.payload = { :title => 'Weather Alert!', :url => 'http://www.weather.com/' } e.save! end end before do allow_any_instance_of(Agents::JabberAgent).to receive(:deliver) { |agent, message| sent << message } end describe "#working?" do it "checks if events have been received within the expected receive period" do expect(agent).not_to be_working # No events received Agents::JabberAgent.async_receive agent.id, [event.id] expect(agent.reload).to be_working # Just received events two_days_from_now = 2.days.from_now allow(Time).to receive(:now) { two_days_from_now } expect(agent.reload).not_to be_working # More time has passed than the expected receive period without any new events end end context "#start_worker?" do it "starts when connect_to_receiver is truthy" do agent.options[:connect_to_receiver] = 'true' expect(agent.start_worker?).to be_truthy end it "does not starts when connect_to_receiver is not truthy" do expect(agent.start_worker?).to be_falsy end end describe "validation" do before do expect(agent).to be_valid end it "should validate presence of of jabber_server" do agent.options[:jabber_server] = "" expect(agent).not_to be_valid end it "should validate presence of jabber_sender" do agent.options[:jabber_sender] = "" expect(agent).not_to be_valid end it "should validate presence of jabber_receiver" do agent.options[:jabber_receiver] = "" expect(agent).not_to be_valid end end describe "receive" do it "should send an IM for each event" do event2 = Event.create!( agent: agents(:bob_weather_agent), payload: { title: 'Another Weather Alert!', url: 'http://www.weather.com/we-are-screwed' }, ) agent.receive([event, event2]) expect(sent).to eq([ 'Warning! Weather Alert! - http://www.weather.com/', 'Warning! Another Weather Alert! - http://www.weather.com/we-are-screwed' ]) end end describe Agents::JabberAgent::Worker do before(:each) do @worker = Agents::JabberAgent::Worker.new(agent: agent) @worker.setup allow_any_instance_of(Jabber::Client).to receive(:connect) allow_any_instance_of(Jabber::Client).to receive(:auth) end it "runs" do agent.options[:jabber_receiver] = 'someJID' expect_any_instance_of(Jabber::MUC::SimpleMUCClient).to receive(:join).with('someJID') @worker.run end it "stops" do @worker.instance_variable_set(:@client, @worker.client) expect_any_instance_of(Jabber::Client).to receive(:close) expect_any_instance_of(Jabber::Client).to receive(:stop) expect(@worker).to receive(:thread) { double(terminate: nil) } @worker.stop end context "#message_handler" do it "it ignores messages for the first seconds" do @worker.instance_variable_set(:@started_at, Time.now) expect { @worker.message_handler(:on_message, [123456, 'nick', 'hello']) } .to change { agent.events.count }.by(0) end it "creates events" do @worker.instance_variable_set(:@started_at, Time.now - 10.seconds) expect { @worker.message_handler(:on_message, [123456, 'nick', 'hello']) } .to change { agent.events.count }.by(1) event = agent.events.last expect(event.payload).to eq({'event' => 'on_message', 'time' => 123456, 'nick' => 'nick', 'message' => 'hello'}) end end context "#normalize_args" do it "handles :on_join and :on_leave" do time, nick, message = @worker.send(:normalize_args, :on_join, [123456, 'nick']) expect(time).to eq(123456) expect(nick).to eq('nick') expect(message).to be_nil end it "handles :on_message and :on_leave" do time, nick, message = @worker.send(:normalize_args, :on_message, [123456, 'nick', 'hello']) expect(time).to eq(123456) expect(nick).to eq('nick') expect(message).to eq('hello') end it "handles :on_room_message" do time, nick, message = @worker.send(:normalize_args, :on_room_message, [123456, 'hello']) expect(time).to eq(123456) expect(nick).to be_nil expect(message).to eq('hello') end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/dropbox_watch_agent_spec.rb
spec/models/agents/dropbox_watch_agent_spec.rb
require 'rails_helper' describe Agents::DropboxWatchAgent do before(:each) do @agent = Agents::DropboxWatchAgent.new( name: 'save to dropbox', options: { access_token: '70k3n', dir_to_watch: '/my/dropbox/dir', expected_update_period_in_days: 2 } ) @agent.user = users(:bob) @agent.service = services(:generic) @agent.save! end it 'cannot receive events' do expect(@agent.cannot_receive_events?).to eq true end it 'has agent description' do expect(@agent.description).to_not be_nil end it 'has event description' do expect(@agent.event_description).to_not be_nil end describe '#valid?' do before(:each) { expect(@agent.valid?).to eq true } it 'requires a "dir_to_watch"' do @agent.options[:dir_to_watch] = nil expect(@agent.valid?).to eq false end describe 'expected_update_period_in_days' do it 'needs to be present' do @agent.options[:expected_update_period_in_days] = nil expect(@agent.valid?).to eq false end it 'needs to be a positive integer' do @agent.options[:expected_update_period_in_days] = -1 expect(@agent.valid?).to eq false end end end describe '#check' do let(:first_result) do Dropbox::API::Object.convert( [ { 'path_display' => '1.json', 'rev' => '1', 'server_modified' => '01-01-01' }, { 'path_display' => 'sub_dir_1', '.tag' => 'folder' } ], nil ) end before(:each) do allow(Dropbox::API::Client).to receive(:new) do instance_double(Dropbox::API::Client).tap { |api| allow(api).to receive(:ls).with('/my/dropbox/dir') { first_result } } end end it 'saves the directory listing in its memory' do @agent.check expect(@agent.memory).to eq({"contents"=>[{"path"=>"1.json", "rev"=>"1", "modified"=>"01-01-01"}]}) end context 'first time' do before(:each) { @agent.memory = {} } it 'does not send any events' do expect { @agent.check }.to_not change(Event, :count) end end context 'subsequent calls' do let(:second_result) do Dropbox::API::Object.convert( [ { 'path_display' => '2.json', 'rev' => '1', 'server_modified' => '02-02-02' }, { 'path_display' => 'sub_dir_2', '.tag' => 'folder' } ], nil ) end before(:each) do @agent.memory = { 'contents' => 'not_empty' } allow(Dropbox::API::Client).to receive(:new) do instance_double(Dropbox::API::Client).tap { |api| allow(api).to receive(:ls).with('/my/dropbox/dir') { second_result } } end end it 'sends an event upon a different directory listing' do payload = { 'diff' => 'object as hash' } allow(Agents::DropboxWatchAgent::DropboxDirDiff).to receive(:new).with(@agent.memory['contents'], [{"path"=>"2.json", "rev"=>"1", "modified"=>"02-02-02"}]) do instance_double(Agents::DropboxWatchAgent::DropboxDirDiff).tap { |diff| allow(diff).to receive(:empty?) { false } allow(diff).to receive(:to_hash) { payload } } end expect { @agent.check }.to change(Event, :count).by(1) expect(Event.last.payload).to eq(payload) end it 'does not sent any events when there is no difference on the directory listing' do allow(Agents::DropboxWatchAgent::DropboxDirDiff).to receive(:new).with(@agent.memory['contents'], [{"path"=>"2.json", "rev"=>"1", "modified"=>"02-02-02"}]) do instance_double(Agents::DropboxWatchAgent::DropboxDirDiff).tap { |diff| allow(diff).to receive(:empty?) { true } } end expect { @agent.check }.to_not change(Event, :count) end end end describe Agents::DropboxWatchAgent::DropboxDirDiff do let(:previous) { [ { 'path' => '1.json', 'rev' => '1' }, { 'path' => '2.json', 'rev' => '1' }, { 'path' => '3.json', 'rev' => '1' } ] } let(:current) { [ { 'path' => '1.json', 'rev' => '2' }, { 'path' => '3.json', 'rev' => '1' }, { 'path' => '4.json', 'rev' => '1' } ] } describe '#empty?' do it 'is true when no differences are detected' do diff = Agents::DropboxWatchAgent::DropboxDirDiff.new(previous, previous) expect(diff.empty?).to eq true end it 'is false when differences were detected' do diff = Agents::DropboxWatchAgent::DropboxDirDiff.new(previous, current) expect(diff.empty?).to eq false end end describe '#to_hash' do subject(:diff_hash) { Agents::DropboxWatchAgent::DropboxDirDiff.new(previous, current).to_hash } it 'detects additions' do expect(diff_hash[:added]).to eq [{ 'path' => '4.json', 'rev' => '1' }] end it 'detects removals' do expect(diff_hash[:removed]).to eq [ { 'path' => '2.json', 'rev' => '1' } ] end it 'detects updates' do expect(diff_hash[:updated]).to eq [ { 'path' => '1.json', 'rev' => '2' } ] end context 'when the previous value is not defined' do it 'considers all additions' do diff_hash = Agents::DropboxWatchAgent::DropboxDirDiff.new(nil, current).to_hash expect(diff_hash[:added]).to eq current expect(diff_hash[:removed]).to eq [] expect(diff_hash[:updated]).to eq [] end end context 'when the current value is not defined' do it 'considers all removals' do diff_hash = Agents::DropboxWatchAgent::DropboxDirDiff.new(previous, nil).to_hash expect(diff_hash[:added]).to eq [] expect(diff_hash[:removed]).to eq previous expect(diff_hash[:updated]).to eq [] end end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/public_transport_agent_spec.rb
spec/models/agents/public_transport_agent_spec.rb
require 'rails_helper' describe Agents::PublicTransportAgent do before do valid_params = { "name" => "sf muni agent", "options" => { "alert_window_in_minutes" => "20", "stops" => ['N|5221', 'N|5215'], "agency" => "sf-muni" } } @agent = Agents::PublicTransportAgent.new(valid_params) @agent.user = users(:bob) @agent.save! end describe "#check" do before do stub_request(:get, "http://webservices.nextbus.com/service/publicXMLFeed?a=sf-muni&command=predictionsForMultiStops&stops=N%7C5215"). with(:headers => {'User-Agent'=>'Typhoeus - https://github.com/typhoeus/typhoeus'}). to_return(:status => 200, :body => File.read(Rails.root.join("spec/data_fixtures/public_transport_agent.xml")), :headers => {}) end it "should create 4 events" do expect { @agent.check }.to change {@agent.events.count}.by(4) end it "should add 4 items to memory" do travel_to Time.parse("2014-01-14 20:21:30 +0500") do expect(@agent.memory).to eq({}) @agent.check @agent.save expect(@agent.reload.memory).to eq({"existing_routes" => [ {"stopTag"=>"5221", "tripTag"=>"5840324", "epochTime"=>"1389706393991", "currentTime"=>Time.now.to_s}, {"stopTag"=>"5221", "tripTag"=>"5840083", "epochTime"=>"1389706512784", "currentTime"=>Time.now.to_s}, {"stopTag"=>"5215", "tripTag"=>"5840324", "epochTime"=>"1389706282012", "currentTime"=>Time.now.to_s}, {"stopTag"=>"5215", "tripTag"=>"5840083", "epochTime"=>"1389706400805", "currentTime"=>Time.now.to_s} ] }) end end it "should not create events twice" do expect { @agent.check }.to change {@agent.events.count}.by(4) expect { @agent.check }.not_to change {@agent.events.count} end it "should reset memory after 2 hours" do travel_to Time.parse("2014-01-14 20:21:30 +0500") do expect { @agent.check }.to change {@agent.events.count}.by(4) end travel_to "2014-01-14 23:21:30 +0500".to_time do @agent.cleanup_old_memory expect { @agent.check }.to change {@agent.events.count}.by(4) end end end describe "validation" do it "should validate presence of stops" do @agent.options['stops'] = nil expect(@agent).not_to be_valid end it "should validate presence of agency" do @agent.options['agency'] = "" expect(@agent).not_to be_valid end it "should validate presence of alert_window_in_minutes" do @agent.options['alert_window_in_minutes'] = "" expect(@agent).not_to be_valid end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/rss_agent_spec.rb
spec/models/agents/rss_agent_spec.rb
require 'rails_helper' describe Agents::RssAgent do before do @valid_options = { 'expected_update_period_in_days' => "2", 'url' => "https://github.com/cantino/huginn/commits/master.atom", } stub_request(:any, /github.com/).to_return(:body => File.read(Rails.root.join("spec/data_fixtures/github_rss.atom")), :status => 200) stub_request(:any, /bad.github.com/).to_return(body: File.read(Rails.root.join("spec/data_fixtures/github_rss.atom")).gsub(/<link [^>]+\/>/, '<link/>'), status: 200) stub_request(:any, /SlickdealsnetFP/).to_return(:body => File.read(Rails.root.join("spec/data_fixtures/slickdeals.atom")), :status => 200) stub_request(:any, /onethingwell.org/).to_return(body: File.read(Rails.root.join("spec/data_fixtures/onethingwell.rss")), status: 200) stub_request(:any, /bad.onethingwell.org/).to_return(body: File.read(Rails.root.join("spec/data_fixtures/onethingwell.rss")).gsub(/(?<=<link>)[^<]*/, ''), status: 200) stub_request(:any, /iso-8859-1/).to_return(body: File.binread(Rails.root.join("spec/data_fixtures/iso-8859-1.rss")), headers: { 'Content-Type' => 'application/rss+xml; charset=ISO-8859-1' }, status: 200) stub_request(:any, /podcast/).to_return(body: File.read(Rails.root.join("spec/data_fixtures/podcast.rss")), status: 200) stub_request(:any, /youtube/).to_return(body: File.read(Rails.root.join("spec/data_fixtures/youtube.xml")), status: 200) end let(:agent) do _agent = Agents::RssAgent.new(:name => "rss feed", :options => @valid_options) _agent.user = users(:bob) _agent.save! _agent end it_behaves_like WebRequestConcern describe "validations" do it "should validate the presence of url" do agent.options['url'] = "http://google.com" expect(agent).to be_valid agent.options['url'] = ["http://google.com", "http://yahoo.com"] expect(agent).to be_valid agent.options['url'] = "" expect(agent).not_to be_valid agent.options['url'] = nil expect(agent).not_to be_valid end it "should validate the presence and numericality of expected_update_period_in_days" do agent.options['expected_update_period_in_days'] = "5" expect(agent).to be_valid agent.options['expected_update_period_in_days'] = "wut?" expect(agent).not_to be_valid agent.options['expected_update_period_in_days'] = 0 expect(agent).not_to be_valid agent.options['expected_update_period_in_days'] = nil expect(agent).not_to be_valid agent.options['expected_update_period_in_days'] = "" expect(agent).not_to be_valid end end describe "emitting RSS events" do it "should emit items as events for an Atom feed" do agent.options['include_feed_info'] = true agent.options['include_sort_info'] = true expect { agent.check }.to change { agent.events.count }.by(20) first, *, last = agent.events.last(20) [first, last].each do |event| expect(event.payload['feed']).to include({ "type" => "atom", "title" => "Recent Commits to huginn:master", "url" => "https://github.com/cantino/huginn/commits/master", "links" => [ { "type" => "text/html", "rel" => "alternate", "href" => "https://github.com/cantino/huginn/commits/master", }, { "type" => "application/atom+xml", "rel" => "self", "href" => "https://github.com/cantino/huginn/commits/master.atom", }, ], }) end expect(first.payload['url']).to eq("https://github.com/cantino/huginn/commit/d0a844662846cf3c83b94c637c1803f03db5a5b0") expect(first.payload['urls']).to eq(["https://github.com/cantino/huginn/commit/d0a844662846cf3c83b94c637c1803f03db5a5b0"]) expect(first.payload['links']).to eq([ { "href" => "https://github.com/cantino/huginn/commit/d0a844662846cf3c83b94c637c1803f03db5a5b0", "rel" => "alternate", "type" => "text/html", } ]) expect(first.payload['authors']).to eq(["cantino (https://github.com/cantino)"]) expect(first.payload['date_published']).to be_nil expect(first.payload['last_updated']).to eq("2014-07-16T22:26:22-07:00") expect(first.payload['sort_info']).to eq({ 'position' => 20, 'count' => 20 }) expect(last.payload['url']).to eq("https://github.com/cantino/huginn/commit/d465158f77dcd9078697e6167b50abbfdfa8b1af") expect(last.payload['urls']).to eq(["https://github.com/cantino/huginn/commit/d465158f77dcd9078697e6167b50abbfdfa8b1af"]) expect(last.payload['links']).to eq([ { "href" => "https://github.com/cantino/huginn/commit/d465158f77dcd9078697e6167b50abbfdfa8b1af", "rel" => "alternate", "type" => "text/html", } ]) expect(last.payload['authors']).to eq(["CloCkWeRX (https://github.com/CloCkWeRX)"]) expect(last.payload['date_published']).to be_nil expect(last.payload['last_updated']).to eq("2014-07-01T16:37:47+09:30") expect(last.payload['sort_info']).to eq({ 'position' => 1, 'count' => 20 }) end it "should emit items as events in the order specified in the events_order option" do expect { agent.options['events_order'] = ['{{title | replace_regex: "^[[:space:]]+", "" }}'] agent.options['include_sort_info'] = true agent.check }.to change { agent.events.count }.by(20) first, *, last = agent.events.last(20) expect(first.payload['title'].strip).to eq('upgrade rails and gems') expect(first.payload['url']).to eq("https://github.com/cantino/huginn/commit/87a7abda23a82305d7050ac0bb400ce36c863d01") expect(first.payload['urls']).to eq(["https://github.com/cantino/huginn/commit/87a7abda23a82305d7050ac0bb400ce36c863d01"]) expect(first.payload['sort_info']).to eq({ 'position' => 20, 'count' => 20 }) expect(last.payload['title'].strip).to eq('Dashed line in a diagram indicates propagate_immediately being false.') expect(last.payload['url']).to eq("https://github.com/cantino/huginn/commit/0e80f5341587aace2c023b06eb9265b776ac4535") expect(last.payload['urls']).to eq(["https://github.com/cantino/huginn/commit/0e80f5341587aace2c023b06eb9265b776ac4535"]) expect(last.payload['sort_info']).to eq({ 'position' => 1, 'count' => 20 }) end it "should emit items as events for a FeedBurner RSS 2.0 feed" do agent.options['url'] = "http://feeds.feedburner.com/SlickdealsnetFP?format=atom" # This is actually RSS 2.0 w/ Atom extension agent.options['include_feed_info'] = true agent.save! expect { agent.check }.to change { agent.events.count }.by(79) first, *, last = agent.events.last(79) expect(first.payload['feed']).to include({ "type" => "rss", "title" => "SlickDeals.net", "description" => "Slick online shopping deals.", "url" => "http://slickdeals.net/", }) # Feedjira extracts feedburner:origLink expect(first.payload['url']).to eq("http://slickdeals.net/permadeal/130160/green-man-gaming---pc-games-tomb-raider-game-of-the-year-6-hitman-absolution-elite-edition") expect(last.payload['feed']).to include({ "type" => "rss", "title" => "SlickDeals.net", "description" => "Slick online shopping deals.", "url" => "http://slickdeals.net/", }) expect(last.payload['url']).to eq("http://slickdeals.net/permadeal/129980/amazon---rearth-ringke-fusion-bumper-hybrid-case-for-iphone-6") end it "should track ids and not re-emit the same item when seen again" do agent.check expect(agent.memory['seen_ids']).to eq(agent.events.map {|e| e.payload['id'] }) newest_id = agent.memory['seen_ids'][0] expect(agent.events.first.payload['id']).to eq(newest_id) agent.memory['seen_ids'] = agent.memory['seen_ids'][1..-1] # forget the newest id expect { agent.check }.to change { agent.events.count }.by(1) expect(agent.events.first.payload['id']).to eq(newest_id) expect(agent.memory['seen_ids'][0]).to eq(newest_id) end it "should truncate the seen_ids in memory at 500 items per default" do agent.memory['seen_ids'] = ['x'] * 490 agent.check expect(agent.memory['seen_ids'].length).to eq(500) end it "should truncate the seen_ids in memory at amount of items configured in options" do agent.options['remembered_id_count'] = "600" agent.memory['seen_ids'] = ['x'] * 590 agent.check expect(agent.memory['seen_ids'].length).to eq(600) end it "should truncate the seen_ids after configuring a lower limit of items when check is executed" do agent.memory['seen_ids'] = ['x'] * 600 agent.options['remembered_id_count'] = "400" expect(agent.memory['seen_ids'].length).to eq(600) agent.check expect(agent.memory['seen_ids'].length).to eq(400) end it "should truncate the seen_ids at default after removing custom limit" do agent.options['remembered_id_count'] = "600" agent.memory['seen_ids'] = ['x'] * 590 agent.check expect(agent.memory['seen_ids'].length).to eq(600) agent.options.delete('remembered_id_count') agent.memory['seen_ids'] = ['x'] * 590 agent.check expect(agent.memory['seen_ids'].length).to eq(500) end it "should support an array of URLs" do agent.options['url'] = ["https://github.com/cantino/huginn/commits/master.atom", "http://feeds.feedburner.com/SlickdealsnetFP?format=atom"] agent.save! expect { agent.check }.to change { agent.events.count }.by(20 + 79) end it "should fetch one event per run" do agent.options['url'] = ["https://github.com/cantino/huginn/commits/master.atom"] agent.options['max_events_per_run'] = 1 agent.check expect(agent.events.count).to eq(1) end it "should fetch all events per run" do agent.options['url'] = ["https://github.com/cantino/huginn/commits/master.atom"] # <= 0 should ignore option and get all agent.options['max_events_per_run'] = 0 agent.check expect(agent.events.count).to eq(20) agent.options['max_events_per_run'] = -1 expect { agent.check }.to_not change { agent.events.count } end end context "when no ids are available" do before do @valid_options['url'] = 'http://feeds.feedburner.com/SlickdealsnetFP?format=atom' end it "calculates content MD5 sums" do expect { agent.check }.to change { agent.events.count }.by(79) expect(agent.memory['seen_ids']).to eq(agent.events.map {|e| Digest::MD5.hexdigest(e.payload['content']) }) end end context "parsing feeds" do before do @valid_options['url'] = 'http://onethingwell.org/rss' end it "captures timestamps normalized in the ISO 8601 format" do agent.check first, *, third = agent.events.take(3) expect(first.payload['date_published']).to eq('2015-08-20T17:00:10+01:00') expect(third.payload['date_published']).to eq('2015-08-20T13:00:07+01:00') end it "captures multiple categories" do agent.check first, *, third = agent.events.take(3) expect(first.payload['categories']).to eq(["csv", "crossplatform", "utilities"]) expect(third.payload['categories']).to eq(["web"]) end it "sanitizes HTML content" do agent.options['clean'] = true agent.check event = agent.events.last expect(event.payload['content']).to eq('<a href="http://showgoers.tv/">Showgoers</a>: <blockquote> <p>Showgoers is a Chrome browser extension to synchronize your Netflix player with someone else so that you can co-watch the same movie on different computers with no hassle. Syncing up your player is as easy as sharing a URL.</p> </blockquote>') expect(event.payload['description']).to eq('<a href="http://showgoers.tv/">Showgoers</a>: <blockquote> <p>Showgoers is a Chrome browser extension to synchronize your Netflix player with someone else so that you can co-watch the same movie on different computers with no hassle. Syncing up your player is as easy as sharing a URL.</p> </blockquote>') end it "captures an enclosure" do agent.check event = agent.events.fourth expect(event.payload['enclosure']).to eq({ "url" => "http://c.1tw.org/images/2015/itsy.png", "type" => "image/png", "length" => "48249" }) expect(event.payload['image']).to eq("http://c.1tw.org/images/2015/itsy.png") end it "ignores an empty author" do agent.check event = agent.events.first expect(event.payload['authors']).to eq([]) end context 'with an empty link in RSS' do before do @valid_options['url'] = 'http://bad.onethingwell.org/rss' end it "does not leak :no_buffer" do agent.check event = agent.events.first expect(event.payload['links']).to eq([]) end end context 'with an empty link in RSS' do before do @valid_options['url'] = "https://bad.github.com/cantino/huginn/commits/master.atom" end it "does not leak :no_buffer" do agent.check event = agent.events.first expect(event.payload['links']).to eq([]) end end context 'with the encoding declared in both headers and the content' do before do @valid_options['url'] = 'http://example.org/iso-8859-1.rss' end it "decodes the content properly" do agent.check event = agent.events.first expect(event.payload['title']).to eq('Mëkanïk Zaïn') end it "decodes the content properly with force_encoding specified" do @valid_options['force_encoding'] = 'iso-8859-1' agent.check event = agent.events.first expect(event.payload['title']).to eq('Mëkanïk Zaïn') end end context 'with podcast elements' do before do @valid_options['url'] = 'http://example.com/podcast.rss' @valid_options['include_feed_info'] = true end let :feed_info do { "id" => nil, "type" => "rss", "url" => "http://www.example.com/podcasts/everything/index.html", "links" => [ { "href" => "http://www.example.com/podcasts/everything/index.html" } ], "title" => "All About Everything", "description" => "All About Everything is a show about everything. Each week we dive into any subject known to man and talk about it as much as we can. Look for our podcast in the Podcasts app or in the iTunes Store", "copyright" => "℗ & © 2014 John Doe & Family", "generator" => nil, "icon" => nil, "authors" => [ "John Doe" ], "date_published" => nil, "last_updated" => nil, "itunes_categories" => [ "Technology", "Gadgets", "TV & Film", "Arts", "Food" ], "itunes_complete" => "yes", "itunes_explicit" => "no", "itunes_image" => "http://example.com/podcasts/everything/AllAboutEverything.jpg", "itunes_owners" => ["John Doe <john.doe@example.com>"], "itunes_subtitle" => "A show about everything", "itunes_summary" => "All About Everything is a show about everything. Each week we dive into any subject known to man and talk about it as much as we can. Look for our podcast in the Podcasts app or in the iTunes Store", "language" => "en-us" } end it "is parsed correctly" do expect { agent.check }.to change { agent.events.count }.by(4) expect(agent.events.map(&:payload)).to match([ { "feed" => feed_info, "id" => "http://example.com/podcasts/archive/aae20140601.mp3", "url" => "http://example.com/podcasts/archive/aae20140601.mp3", "urls" => ["http://example.com/podcasts/archive/aae20140601.mp3"], "links" => [], "title" => "Red,Whine, & Blue", "description" => nil, "content" => nil, "image" => nil, "enclosure" => { "url" => "http://example.com/podcasts/everything/AllAboutEverythingEpisode4.mp3", "type" => "audio/mpeg", "length" => "498537" }, "authors" => ["<Various>"], "categories" => [], "date_published" => "2016-03-11T01:15:00+00:00", "last_updated" => "2016-03-11T01:15:00+00:00", "itunes_duration" => "03:59", "itunes_explicit" => "no", "itunes_image" => "http://example.com/podcasts/everything/AllAboutEverything/Episode4.jpg", "itunes_subtitle" => "Red + Blue != Purple", "itunes_summary" => "This week we talk about surviving in a Red state if you are a Blue person. Or vice versa." }, { "feed" => feed_info, "id" => "http://example.com/podcasts/archive/aae20140697.m4v", "url" => "http://example.com/podcasts/archive/aae20140697.m4v", "urls" => ["http://example.com/podcasts/archive/aae20140697.m4v"], "links" => [], "title" => "The Best Chili", "description" => nil, "content" => nil, "image" => nil, "enclosure" => { "url" => "http://example.com/podcasts/everything/AllAboutEverythingEpisode2.m4v", "type" => "video/x-m4v", "length" => "5650889" }, "authors" => ["Jane Doe"], "categories" => [], "date_published" => "2016-03-10T02:00:00-07:00", "last_updated" => "2016-03-10T02:00:00-07:00", "itunes_closed_captioned" => "Yes", "itunes_duration" => "04:34", "itunes_explicit" => "no", "itunes_image" => "http://example.com/podcasts/everything/AllAboutEverything/Episode3.jpg", "itunes_subtitle" => "Jane and Eric", "itunes_summary" => "This week we talk about the best Chili in the world. Which chili is better?" }, { "feed" => feed_info, "id" => "http://example.com/podcasts/archive/aae20140608.mp4", "url" => "http://example.com/podcasts/archive/aae20140608.mp4", "urls" => ["http://example.com/podcasts/archive/aae20140608.mp4"], "links" => [], "title" => "Socket Wrench Shootout", "description" => nil, "content" => nil, "image" => nil, "enclosure" => { "url" => "http://example.com/podcasts/everything/AllAboutEverythingEpisode2.mp4", "type" => "video/mp4", "length" => "5650889" }, "authors" => ["Jane Doe"], "categories" => [], "date_published" => "2016-03-09T13:00:00-05:00", "last_updated" => "2016-03-09T13:00:00-05:00", "itunes_duration" => "04:34", "itunes_explicit" => "no", "itunes_image" => "http://example.com/podcasts/everything/AllAboutEverything/Episode2.jpg", "itunes_subtitle" => "Comparing socket wrenches is fun!", "itunes_summary" => "This week we talk about metric vs. Old English socket wrenches. Which one is better? Do you really need both? Get all of your answers here." }, { "feed" => feed_info, "id" => "http://example.com/podcasts/archive/aae20140615.m4a", "url" => "http://example.com/podcasts/archive/aae20140615.m4a", "urls" => ["http://example.com/podcasts/archive/aae20140615.m4a"], "links" => [], "title" => "Shake Shake Shake Your Spices", "description" => nil, "content" => nil, "image" => nil, "enclosure" => { "url" => "http://example.com/podcasts/everything/AllAboutEverythingEpisode3.m4a", "type" => "audio/x-m4a", "length" => "8727310" }, "authors" => ["John Doe"], "categories" => [], "date_published" => "2016-03-08T12:00:00+00:00", "last_updated" => "2016-03-08T12:00:00+00:00", "itunes_duration" => "07:04", "itunes_explicit" => "no", "itunes_image" => "http://example.com/podcasts/everything/AllAboutEverything/Episode1.jpg", "itunes_subtitle" => "A short primer on table spices", "itunes_summary" => "This week we talk about <a href=\"https://itunes/apple.com/us/book/antique-trader-salt-pepper/id429691295?mt=11\">salt and pepper shakers</a>, comparing and contrasting pour rates, construction materials, and overall aesthetics. Come and join the party!" } ]) end end context 'of YouTube' do before do @valid_options['url'] = 'http://example.com/youtube.xml' @valid_options['include_feed_info'] = true end it "is parsed correctly" do expect { agent.check }.to change { agent.events.count }.by(15) expect(agent.events.first.payload).to match({ "feed" => { "id" => "yt:channel:UCoTLdfNePDQzvdEgIToLIUg", "type" => "atom", "url" => "https://www.youtube.com/channel/UCoTLdfNePDQzvdEgIToLIUg", "links" => [ { "href" => "http://www.youtube.com/feeds/videos.xml?channel_id=UCoTLdfNePDQzvdEgIToLIUg", "rel" => "self" }, { "href" => "https://www.youtube.com/channel/UCoTLdfNePDQzvdEgIToLIUg", "rel" => "alternate" } ], "title" => "SecDSM", "description" => nil, "copyright" => nil, "generator" => nil, "icon" => nil, "authors" => ["SecDSM (https://www.youtube.com/channel/UCoTLdfNePDQzvdEgIToLIUg)"], "date_published" => "2016-07-28T18:46:21+00:00", "last_updated" => "2016-07-28T18:46:21+00:00" }, "id" => "yt:video:OCs1E0vP7Oc", "authors" => ["SecDSM (https://www.youtube.com/channel/UCoTLdfNePDQzvdEgIToLIUg)"], "categories" => [], "content" => nil, "date_published" => "2017-06-15T02:36:17+00:00", "description" => nil, "enclosure" => nil, "image" => nil, "last_updated" => "2017-06-15T02:36:17+00:00", "links" => [ { "href"=>"https://www.youtube.com/watch?v=OCs1E0vP7Oc", "rel"=>"alternate" } ], "title" => "SecDSM 2017 March - Talk 01", "url" => "https://www.youtube.com/watch?v=OCs1E0vP7Oc", "urls" => ["https://www.youtube.com/watch?v=OCs1E0vP7Oc"] }) end end end describe 'logging errors with the feed url' do it 'includes the feed URL when an exception is raised' do expect(Feedjira).to receive(:parse).with(anything) { raise StandardError.new("Some error!") } expect { agent.check }.not_to raise_error expect(agent.logs.last.message).to match(%r[Failed to fetch https://github.com]) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/aftership_agent_spec.rb
spec/models/agents/aftership_agent_spec.rb
require 'rails_helper' describe Agents::AftershipAgent do before do stub_request(:get, /trackings/).to_return( :body => File.read(Rails.root.join("spec/data_fixtures/aftership.json")), :status => 200, :headers => {"Content-Type" => "text/json"} ) @opts = { "api_key" => '800deeaf-e285-9d62-bc90-j999c1973cc9', "path" => 'trackings' } @checker = Agents::AftershipAgent.new(:name => "tectonic", :options => @opts) @checker.user = users(:bob) @checker.save! end describe '#helpers' do it "should return the correct request header" do expect(@checker.send(:request_options)).to eq({:headers => {"aftership-api-key" => '800deeaf-e285-9d62-bc90-j999c1973cc9', "Content-Type"=>"application/json"}}) end it "should generate the correct events url" do expect(@checker.send(:event_url)).to eq("https://api.aftership.com/v4/trackings") end it "should generate the correct specific tracking url" do @checker.options['path'] = "trackings/usps/9361289878905919630610" expect(@checker.send(:event_url)).to eq("https://api.aftership.com/v4/trackings/usps/9361289878905919630610") end it "should generate the correct last checkpoint url" do @checker.options['path'] = "last_checkpoint/usps/9361289878905919630610" expect(@checker.send(:event_url)).to eq("https://api.aftership.com/v4/last_checkpoint/usps/9361289878905919630610") end end describe "#that checker should be valid" do it "should check that the aftership object is valid" do expect(@checker).to be_valid end it "should require credentials" do @checker.options['api_key'] = nil expect(@checker).not_to be_valid end end describe "path request must exist" do it "should check that validation added if path does not exist" do opts = @opts.tap { |o| o.delete('path') } @checker = Agents::AftershipAgent.new(:name => "tectonic", :options => opts) @checker.user = users(:bob) expect(@checker.save).to eq false expect(@checker.errors.full_messages.first).to eq("You need to specify a path request") end end describe '#check' do it "should check that initial run creates an event" do @checker.memory[:last_updated_at] = '2016-03-15T14:01:05+00:00' expect { @checker.check }.to change { Event.count }.by(1) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/pushbullet_agent_spec.rb
spec/models/agents/pushbullet_agent_spec.rb
require 'rails_helper' describe Agents::PushbulletAgent do before(:each) do @valid_params = { 'api_key' => 'token', 'device_id' => '124', 'body' => '{{body}}', 'url' => 'url', 'name' => 'name', 'address' => 'address', 'title' => 'hello from huginn', 'type' => 'note' } @checker = Agents::PushbulletAgent.new(:name => "somename", :options => @valid_params) @checker.user = users(:jane) @checker.save! @event = Event.new @event.agent = agents(:bob_weather_agent) @event.payload = { :body => 'One two test' } @event.save! end describe "validating" do before do expect(@checker).to be_valid end it "should require the api_key" do @checker.options['api_key'] = nil expect(@checker).not_to be_valid end it "should try do create a device_id" do @checker.options['device_id'] = nil expect(@checker).not_to be_valid end it "should require fields based on the type" do @checker.options['type'] = 'address' @checker.options['address'] = nil expect(@checker).not_to be_valid end end describe "helpers" do before(:each) do @base_options = { body: { device_iden: @checker.options[:device_id] }, basic_auth: { username: @checker.options[:api_key], :password=>'' } } end context "#query_options" do it "should work for a note" do options = @base_options.deep_merge({ body: {title: 'hello from huginn', body: 'One two test', type: 'note'} }) expect(@checker.send(:query_options, @event)).to eq(options) end it "should work for a link" do @checker.options['type'] = 'link' options = @base_options.deep_merge({ body: {title: 'hello from huginn', body: 'One two test', type: 'link', url: 'url'} }) expect(@checker.send(:query_options, @event)).to eq(options) end it "should work for an address" do @checker.options['type'] = 'address' options = @base_options.deep_merge({ body: {name: 'name', address: 'address', type: 'address'} }) expect(@checker.send(:query_options, @event)).to eq(options) end end end describe '#validate_api_key' do it "should return true when working" do expect(@checker).to receive(:devices) expect(@checker.validate_api_key).to be_truthy end it "should return true when working" do expect(@checker).to receive(:devices) { raise Agents::PushbulletAgent::Unauthorized } expect(@checker.validate_api_key).to be_falsy end end describe '#complete_device_id' do it "should return an array" do expect(@checker).to receive(:devices) { [{'iden' => '12345', 'nickname' => 'huginn'}] } expect(@checker.complete_device_id).to eq([{:text=>"All Devices", :id=>"__ALL__"}, {:text=>"huginn", :id=>"12345"}]) end end describe "#receive" do it "send a note" do stub_request(:post, "https://api.pushbullet.com/v2/pushes"). with(basic_auth: [@checker.options[:api_key], ''], body: "device_iden=124&type=note&title=hello%20from%20huginn&body=One%20two%20test"). to_return(status: 200, body: "{}", headers: {}) expect(@checker).not_to receive(:error) @checker.receive([@event]) end it "should log resquests which return an error" do stub_request(:post, "https://api.pushbullet.com/v2/pushes"). with(basic_auth: [@checker.options[:api_key], ''], body: "device_iden=124&type=note&title=hello%20from%20huginn&body=One%20two%20test"). to_return(status: 200, body: '{"error": {"message": "error"}}', headers: {}) expect(@checker).to receive(:error).with("error") @checker.receive([@event]) end end describe "#working?" do it "should not be working until the first event was received" do expect(@checker).not_to be_working @checker.last_receive_at = Time.now expect(@checker).to be_working end end describe '#devices' do it "should return an array of devices" do stub_request(:get, "https://api.pushbullet.com/v2/devices"). with(basic_auth: [@checker.options[:api_key], '']). to_return(status: 200, body: '{"devices": [{"pushable": false}, {"nickname": "test", "iden": "iden", "pushable": true}]}', headers: {}) expect(@checker.send(:devices)).to eq([{"nickname"=>"test", "iden"=>"iden", "pushable"=>true}]) end it "should return an empty array on error" do allow(@checker).to receive(:request) { raise Agents::PushbulletAgent::Unauthorized } expect(@checker.send(:devices)).to eq([]) end end describe '#create_device' do it "should create a new device and assign it to the options" do stub_request(:post, "https://api.pushbullet.com/v2/devices"). with(basic_auth: [@checker.options[:api_key], ''], body: "nickname=Huginn&type=stream"). to_return(status: 200, body: '{"iden": "udm0Tdjz5A7bL4NM"}', headers: {}) @checker.options['device_id'] = nil @checker.send(:create_device) expect(@checker.options[:device_id]).to eq('udm0Tdjz5A7bL4NM') end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/twitter_stream_agent_spec.rb
spec/models/agents/twitter_stream_agent_spec.rb
require 'rails_helper' describe Agents::TwitterStreamAgent do before do @opts = { consumer_key: "---", consumer_secret: "---", oauth_token: "---", oauth_token_secret: "---", filters: %w[keyword1 keyword2], expected_update_period_in_days: "2", generate: "events", include_retweets: "false" } @agent = Agents::TwitterStreamAgent.new(name: "HuginnBot", options: @opts) @agent.service = services(:generic) @agent.user = users(:bob) @agent.save! end describe '#process_tweet' do context "when generate is set to 'counts'" do before do @agent.options[:generate] = 'counts' end it 'records counts' do @agent.process_tweet('keyword1', { text: "something", user: { name: "Mr. Someone" } }) @agent.process_tweet('keyword2', { text: "something", user: { name: "Mr. Someone" } }) @agent.process_tweet('keyword1', { text: "something", user: { name: "Mr. Someone" } }) @agent.reload expect(@agent.memory[:filter_counts][:keyword1]).to eq(2) expect(@agent.memory[:filter_counts][:keyword2]).to eq(1) end it 'records counts for keyword sets as well' do @agent.options[:filters][0] = %w[keyword1-1 keyword1-2 keyword1-3] @agent.save! @agent.process_tweet('keyword2', { text: "something", user: { name: "Mr. Someone" } }) @agent.process_tweet('keyword2', { text: "something", user: { name: "Mr. Someone" } }) @agent.process_tweet('keyword1-1', { text: "something", user: { name: "Mr. Someone" } }) @agent.process_tweet('keyword1-2', { text: "something", user: { name: "Mr. Someone" } }) @agent.process_tweet('keyword1-3', { text: "something", user: { name: "Mr. Someone" } }) @agent.process_tweet('keyword1-1', { text: "something", user: { name: "Mr. Someone" } }) @agent.reload expect(@agent.memory[:filter_counts][:'keyword1-1']).to eq(4) # it stores on the first keyword expect(@agent.memory[:filter_counts][:keyword2]).to eq(2) end it 'removes unused keys' do @agent.memory[:filter_counts] = { keyword1: 2, keyword2: 3, keyword3: 4 } @agent.save! @agent.process_tweet('keyword1', { text: "something", user: { name: "Mr. Someone" } }) expect(@agent.reload.memory[:filter_counts]).to eq({ 'keyword1' => 3, 'keyword2' => 3 }) end end context "when generate is set to 'events'" do it 'emits events immediately' do expect { @agent.process_tweet('keyword1', { text: "something", user: { name: "Mr. Someone" } }) }.to change { @agent.events.count }.by(1) expect(@agent.events.last.payload).to eq({ 'filter' => 'keyword1', 'text' => "something", 'user' => { 'name' => "Mr. Someone" } }) end it 'handles keyword sets too' do @agent.options[:filters][0] = %w[keyword1-1 keyword1-2 keyword1-3] @agent.save! expect { @agent.process_tweet('keyword1-2', { text: "something", user: { name: "Mr. Someone" } }) }.to change { @agent.events.count }.by(1) expect(@agent.events.last.payload).to eq({ 'filter' => 'keyword1-1', 'text' => "something", 'user' => { 'name' => "Mr. Someone" } }) end end end describe '#check' do context "when generate is set to 'counts'" do before do @agent.options[:generate] = 'counts' @agent.save! end it 'emits events' do @agent.process_tweet('keyword1', { text: "something", user: { name: "Mr. Someone" } }) @agent.process_tweet('keyword2', { text: "something", user: { name: "Mr. Someone" } }) @agent.process_tweet('keyword1', { text: "something", user: { name: "Mr. Someone" } }) expect { @agent.reload.check }.to change { @agent.events.count }.by(2) expect(@agent.events[-1].payload[:filter]).to eq('keyword1') expect(@agent.events[-1].payload[:count]).to eq(2) expect(@agent.events[-2].payload[:filter]).to eq('keyword2') expect(@agent.events[-2].payload[:count]).to eq(1) expect(@agent.memory[:filter_counts]).to eq({}) end end context "when generate is not set to 'counts'" do it 'does nothing' do @agent.memory[:filter_counts] = { keyword1: 2 } @agent.save! expect { @agent.reload.check }.not_to change { Event.count } expect(@agent.memory[:filter_counts]).to eq({}) end end end context "#setup_worker" do it "ensures the dependencies are available" do expect(Agents::TwitterStreamAgent).to receive(:warn).with(Agents::TwitterStreamAgent.twitter_dependencies_missing) expect(Agents::TwitterStreamAgent).to receive(:dependencies_missing?) { true } expect(Agents::TwitterStreamAgent.setup_worker).to eq(false) end it "returns now workers if no agent is active" do @agent.destroy expect(Agents::TwitterStreamAgent.active).to be_empty expect(Agents::TwitterStreamAgent.setup_worker).to eq([]) end it "returns a worker for an active agent" do expect(Agents::TwitterStreamAgent.active).to eq([@agent]) workers = Agents::TwitterStreamAgent.setup_worker expect(workers).to be_a(Array) expect(workers.length).to eq(1) expect(workers.first).to be_a(Agents::TwitterStreamAgent::Worker) filter_to_agent_map = workers.first.config[:filter_to_agent_map] expect(filter_to_agent_map.keys).to eq(['keyword1', 'keyword2']) expect(filter_to_agent_map.values).to eq([[@agent], [@agent]]) end it "correctly maps keywords to agents" do agent2 = @agent.dup agent2.options[:filters] = ['agent2'] agent2.save! expect(Agents::TwitterStreamAgent.active.order(:id).pluck(:id)).to eq([@agent.id, agent2.id]) workers = Agents::TwitterStreamAgent.setup_worker filter_to_agent_map = workers.first.config[:filter_to_agent_map] expect(filter_to_agent_map.keys).to eq(['keyword1', 'keyword2', 'agent2']) expect(filter_to_agent_map['keyword1']).to eq([@agent]) expect(filter_to_agent_map['agent2']).to eq([agent2]) end end describe Agents::TwitterStreamAgent::Worker do before(:each) do @mock_agent = double @config = { agent: @agent, config: { filter_to_agent_map: { 'agent' => [@mock_agent] } } } @worker = Agents::TwitterStreamAgent::Worker.new(@config) @worker.instance_variable_set(:@recent_tweets, []) # mock(@worker).schedule_in(Agents::TwitterStreamAgent::Worker::RELOAD_TIMEOUT) @worker.setup!(nil, Mutex.new) end context "#run" do before(:each) do allow(EventMachine).to receive(:run).and_yield allow(EventMachine).to receive(:add_periodic_timer).with(3600) end it "starts the stream" do expect(@worker).to receive(:stream!).with(['agent'], @agent) expect(Thread).to receive(:stop) @worker.run end it "yields received tweets" do expect(@worker).to receive(:stream!).with(['agent'], @agent).and_yield('status' => 'hello') expect(@worker).to receive(:handle_status).with({ 'status' => 'hello' }) expect(Thread).to receive(:stop) @worker.run end end context "#stop" do it "stops the thread" do expect(@worker).to receive(:terminate_thread!) @worker.stop end end context "stream!" do def stream_stub stream = double( each_item: nil, on_error: nil, on_no_data: nil, on_max_reconnects: nil, ) allow(Twitter::JSONStream).to receive(:connect) { stream } stream end def stream_stub_yielding(**pairs) stream = stream_stub pairs.each do |method, args| expect(stream).to receive(method).and_yield(*args) end stream end it "initializes Twitter::JSONStream" do expect(Twitter::JSONStream).to receive(:connect).with({ path: "/1.1/statuses/filter.json?track=agent", ssl: true, oauth: { consumer_key: "twitteroauthkey", consumer_secret: "twitteroauthsecret", access_key: "1234token", access_secret: "56789secret" } }) { stream_stub } @worker.send(:stream!, ['agent'], @agent) end context "callback handling" do it "logs error messages" do stream_stub_yielding(on_error: ['woups']) expect(@worker).to receive(:warn).with(anything) { |text| expect(text).to match(/woups/) } expect(@worker).to receive(:warn).with(anything) { |text| expect(text).to match(/Sleeping/) } expect(@worker).to receive(:sleep).with(15) expect(@worker).to receive(:restart!) @worker.send(:stream!, ['agent'], @agent) end it "stop when no data was received" do stream_stub_yielding(on_no_data: ['woups']) expect(@worker).to receive(:restart!) expect(@worker).to receive(:warn).with(anything) @worker.send(:stream!, ['agent'], @agent) end it "sleeps for 60 seconds on_max_reconnects" do stream_stub_yielding(on_max_reconnects: [1, 1]) expect(@worker).to receive(:warn).with(anything) expect(@worker).to receive(:sleep).with(60) expect(@worker).to receive(:restart!) @worker.send(:stream!, ['agent'], @agent) end it "yields every status received" do stream_stub_yielding(each_item: [{ 'text' => 'hello' }]) @worker.send(:stream!, ['agent'], @agent) do |status| expect(status).to eq({ 'text' => 'hello' }) end end end end context "#handle_status" do it "skips retweets" do @worker.send(:handle_status, { 'text' => 'retweet', 'retweeted_status' => { one: true }, 'id_str' => '123' }) expect(@worker.instance_variable_get(:'@recent_tweets')).not_to include('123') end it "includes retweets if configured" do @agent.options[:include_retweets] = 'true' @agent.save! @worker.send(:handle_status, { 'text' => 'retweet', 'retweeted_status' => { one: true }, 'id_str' => '1234' }) expect(@worker.instance_variable_get(:'@recent_tweets')).to include('1234') end it "deduplicates tweets" do @worker.send(:handle_status, { 'text' => 'dup', 'id_str' => '1' }) expect(@worker).to receive(:puts).with(anything) { |text| expect(text).to match(/Skipping/) } @worker.send(:handle_status, { 'text' => 'dup', 'id_str' => '1' }) expect(@worker.instance_variable_get(:'@recent_tweets').select { |str| str == '1' }.length).to eq 1 end it "calls the agent to process the tweet" do expect(@mock_agent).to receive(:name) { 'mock' } expect(@mock_agent).to receive(:process_tweet).with('agent', { text: 'agent', id_str: '123', expanded_text: 'agent' }) expect(@worker).to receive(:puts).with(a_string_matching(/received/)) @worker.send(:handle_status, { 'text' => 'agent', 'id_str' => '123' }) expect(@worker.instance_variable_get(:'@recent_tweets')).to include('123') end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/witai_agent_spec.rb
spec/models/agents/witai_agent_spec.rb
require 'rails_helper' describe Agents::WitaiAgent do before do stub_request(:get, /wit/).to_return(:body => File.read(Rails.root.join('spec/data_fixtures/witai.json')), :status => 200, :headers => {'Content-Type' => 'text/json'}) @valid_params = { :server_access_token => 'x', :expected_receive_period_in_days => '2', :query => '{{message.content}}' } @checker = Agents::WitaiAgent.new :name => 'wit.ai agent', :options => @valid_params @checker.user = users :jane @checker.save! @event = Event.new @event.agent = agents :jane_weather_agent @event.payload = {:message => { :content => 'set the temperature to 22 degrees at 7 PM' }} @event.save! end describe '#validation' do before do expect(@checker).to be_valid end it 'validates presence of server access token' do @checker.options[:server_access_token] = nil expect(@checker).not_to be_valid end it 'validates presence of query' do @checker.options[:query] = nil expect(@checker).not_to be_valid end it 'validates presence of expected receive period in days key' do @checker.options[:expected_receive_period_in_days] = nil expect(@checker).not_to be_valid end end describe '#working' do it 'checks if agent is working when event is received withing expected number of days' do expect(@checker).not_to be_working Agents::WitaiAgent.async_receive @checker.id, [@event.id] expect(@checker.reload).to be_working two_days_from_now = 2.days.from_now allow(Time).to receive(:now) { two_days_from_now } expect(@checker.reload).not_to be_working end end describe '#receive' do it 'checks that a new event is created after receiving one' do expect { @checker.receive([@event]) }.to change { Event.count }.by(1) end it 'checks the integrity of new event' do @checker.receive([@event]) expect(Event.last.payload[:outcomes][0][:_text]).to eq(@event.payload[:message][:content]) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/manual_event_agent_spec.rb
spec/models/agents/manual_event_agent_spec.rb
require 'rails_helper' describe Agents::ManualEventAgent do before do @checker = Agents::ManualEventAgent.new(name: "My Manual Event Agent") @checker.user = users(:jane) @checker.save! end describe "#handle_details_post" do it "emits an event with the given payload" do expect { json = { 'foo' => "bar" }.to_json expect(@checker.handle_details_post({ 'payload' => json })).to eq({ success: true }) }.to change { @checker.events.count }.by(1) expect(@checker.events.last.payload).to eq({ 'foo' => 'bar' }) end it "emits multiple events when given a magic 'payloads' key" do expect { json = { 'payloads' => [{ 'key' => 'value1' }, { 'key' => 'value2' }] }.to_json expect(@checker.handle_details_post({ 'payload' => json })).to eq({ success: true }) }.to change { @checker.events.count }.by(2) events = @checker.events.order('id desc') expect(events[0].payload).to eq({ 'key' => 'value2' }) expect(events[1].payload).to eq({ 'key' => 'value1' }) end it "errors when given both payloads and other top-level keys" do expect { json = { 'key' => 'value2', 'payloads' => [{ 'key' => 'value1' }] }.to_json expect(@checker.handle_details_post({ 'payload' => json })).to eq({ success: false, error: "If you provide the 'payloads' key, please do not provide any other keys at the top level." }) }.to_not change { @checker.events.count } end it "supports Liquid formatting" do expect { json = { 'key' => "{{ 'now' | date: '%Y' }}", 'nested' => { 'lowercase' => "{{ 'uppercase' | upcase }}" } }.to_json expect(@checker.handle_details_post({ 'payload' => json })).to eq({ success: true }) }.to change { @checker.events.count }.by(1) expect(@checker.events.last.payload).to eq({ 'key' => Time.now.year.to_s, 'nested' => { 'lowercase' => 'UPPERCASE' } }) end it "errors when not given a JSON payload" do expect { expect(@checker.handle_details_post({ 'foo' =>'bar' })).to eq({ success: false, error: "You must provide a JSON payload" }) }.not_to change { @checker.events.count } end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/webhook_agent_spec.rb
spec/models/agents/webhook_agent_spec.rb
require 'rails_helper' describe Agents::WebhookAgent do let(:agent) do _agent = Agents::WebhookAgent.new(:name => 'webhook', :options => { 'secret' => 'foobar', 'payload_path' => 'some_key' }) _agent.user = users(:bob) _agent.save! _agent end let(:payload) { {'people' => [{ 'name' => 'bob' }, { 'name' => 'jon' }] } } describe 'receive_web_request' do it 'should create event if secret matches' do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) out = nil agent.options['event_headers'] = 'Accept,X-Hello-World' agent.options['event_headers_key'] = 'X-HTTP-HEADERS' expect { out = agent.receive_web_request(webpayload) }.to change { Event.count }.by(1) expect(out).to eq(['Event Created', 201]) expect(Event.last.payload).to eq( {"people"=>[{"name"=>"bob"}, {"name"=>"jon"}], "X-HTTP-HEADERS"=>{"Accept"=>"application/xml", "X-Hello-World"=>"Hello Huginn"}}) end it 'should be able to create multiple events when given an array' do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) out = nil agent.options['payload_path'] = 'some_key.people' agent.options['event_headers'] = 'Accept,X-Hello-World' agent.options['event_headers_key'] = 'X-HTTP-HEADERS' expect { out = agent.receive_web_request(webpayload) }.to change { Event.count }.by(2) expect(out).to eq(['Event Created', 201]) expect(Event.last.payload).to eq({"name"=>"jon", "X-HTTP-HEADERS"=>{"Accept"=>"application/xml", "X-Hello-World"=>"Hello Huginn"}}) end it 'should not create event if secrets do not match' do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'bazbat' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) out = nil agent.options['event_headers'] = 'Accept,X-Hello-World' agent.options['event_headers_key'] = 'X-HTTP-HEADERS' expect { out = agent.receive_web_request(webpayload) }.to change { Event.count }.by(0) expect(out).to eq(['Not Authorized', 401]) end it 'should respond with customized response message if configured with `response` option' do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) agent.options['response'] = 'That Worked' out = agent.receive_web_request(webpayload) expect(out).to eq(['That Worked', 201]) # Empty string is a valid response agent.options['response'] = '' out = agent.receive_web_request(webpayload) expect(out).to eq(['', 201]) end it 'should respond with interpolated response message if configured with `response` option' do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) agent.options['response'] = '{{some_key.people[1].name}}' out = agent.receive_web_request(webpayload) expect(out).to eq(['jon', 201]) end it 'should respond with custom response header if configured with `response_headers` option' do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) agent.options['response_headers'] = {"X-My-Custom-Header" => 'hello'} out = agent.receive_web_request(webpayload) expect(out).to eq(['Event Created', 201, "text/plain", {"X-My-Custom-Header" => 'hello'}]) end it 'should respond with `Event Created` if the response option is nil or missing' do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) agent.options['response'] = nil out = agent.receive_web_request(webpayload) expect(out).to eq(['Event Created', 201]) agent.options.delete('response') out = agent.receive_web_request(webpayload) expect(out).to eq(['Event Created', 201]) end it 'should respond with customized response code if configured with `code` option' do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) agent.options['code'] = '200' out = agent.receive_web_request(webpayload) expect(out).to eq(['Event Created', 200]) end it 'should respond with `201` if the code option is empty, nil or missing' do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) agent.options['code'] = '' out = agent.receive_web_request(webpayload) expect(out).to eq(['Event Created', 201]) agent.options['code'] = nil out = agent.receive_web_request(webpayload) expect(out).to eq(['Event Created', 201]) agent.options.delete('code') out = agent.receive_web_request(webpayload) expect(out).to eq(['Event Created', 201]) end describe "receiving events" do context "default settings" do it "should not accept GET" do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "GET", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) out = nil expect { out = agent.receive_web_request(webpayload) }.to change { Event.count }.by(0) expect(out).to eq(['Please use POST requests only', 401]) end it "should accept POST" do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) out = nil expect { out = agent.receive_web_request(webpayload) }.to change { Event.count }.by(1) expect(out).to eq(['Event Created', 201]) end end context "accepting get and post" do before { agent.options['verbs'] = 'get,post' } it "should accept GET" do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "GET", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) out = nil expect { out = agent.receive_web_request(webpayload) }.to change { Event.count }.by(1) expect(out).to eq(['Event Created', 201]) end it "should accept POST" do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) out = nil expect { out = agent.receive_web_request(webpayload) }.to change { Event.count }.by(1) expect(out).to eq(['Event Created', 201]) end it "should not accept PUT" do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "PUT", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) out = nil expect { out = agent.receive_web_request(webpayload) }.to change { Event.count }.by(0) expect(out).to eq(['Please use GET/POST requests only', 401]) end end context "accepting only get" do before { agent.options['verbs'] = 'get' } it "should accept GET" do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "GET", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) out = nil expect { out = agent.receive_web_request(webpayload) }.to change { Event.count }.by(1) expect(out).to eq(['Event Created', 201]) end it "should not accept POST" do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) out = nil expect { out = agent.receive_web_request(webpayload) }.to change { Event.count }.by(0) expect(out).to eq(['Please use GET requests only', 401]) end end context "accepting only post" do before { agent.options['verbs'] = 'post' } it "should not accept GET" do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "GET", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) out = nil expect { out = agent.receive_web_request(webpayload) }.to change { Event.count }.by(0) expect(out).to eq(['Please use POST requests only', 401]) end it "should accept POST" do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) out = nil expect { out = agent.receive_web_request(webpayload) }.to change { Event.count }.by(1) expect(out).to eq(['Event Created', 201]) end end context "accepting only put" do before { agent.options['verbs'] = 'put' } it "should accept PUT" do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "PUT", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) out = nil expect { out = agent.receive_web_request(webpayload) }.to change { Event.count }.by(1) expect(out).to eq(['Event Created', 201]) end it "should not accept GET" do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "GET", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) out = nil expect { out = agent.receive_web_request(webpayload) }.to change { Event.count }.by(0) expect(out).to eq(['Please use PUT requests only', 401]) end it "should not accept POST" do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) out = nil expect { out = agent.receive_web_request(webpayload) }.to change { Event.count }.by(0) expect(out).to eq(['Please use PUT requests only', 401]) end end context "flaky content with commas" do before { agent.options['verbs'] = ',, PUT,POST, gEt , ,' } it "should accept PUT" do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "PUT", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) out = nil expect { out = agent.receive_web_request(webpayload) }.to change { Event.count }.by(1) expect(out).to eq(['Event Created', 201]) end it "should accept GET" do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "GET", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) out = nil expect { out = agent.receive_web_request(webpayload) }.to change { Event.count }.by(1) expect(out).to eq(['Event Created', 201]) end it "should accept POST" do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) out = nil expect { out = agent.receive_web_request(webpayload) }.to change { Event.count }.by(1) expect(out).to eq(['Event Created', 201]) end it "should not accept DELETE" do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "DELETE", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) out = nil expect { out = agent.receive_web_request(webpayload) }.to change { Event.count }.by(0) expect(out).to eq(['Please use PUT/POST/GET requests only', 401]) end end context "with reCAPTCHA" do it "should not check a reCAPTCHA response unless recaptcha_secret is set" do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) checked = false out = nil stub_request(:any, /verify/).to_return { |request| checked = true { status: 200, body: '{"success":false}' } } expect { out= agent.receive_web_request(webpayload) }.not_to change { checked } expect(out).to eq(["Event Created", 201]) end it "should reject a request if recaptcha_secret is set but g-recaptcha-response is not given" do agent.options['recaptcha_secret'] = 'supersupersecret' webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) checked = false out = nil stub_request(:any, /verify/).to_return { |request| checked = true { status: 200, body: '{"success":false}' } } expect { out = agent.receive_web_request(webpayload) }.not_to change { checked } expect(out).to eq(["Not Authorized", 401]) end it "should reject a request if recaptcha_secret is set and g-recaptcha-response given is not verified" do agent.options['recaptcha_secret'] = 'supersupersecret' webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload, 'g-recaptcha-response' => 'somevalue' }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) checked = false out = nil stub_request(:any, /verify/).to_return { |request| checked = true { status: 200, body: '{"success":false}' } } expect { out = agent.receive_web_request(webpayload) }.to change { checked } expect(out).to eq(["Not Authorized", 401]) end it "should accept a request if recaptcha_secret is set and g-recaptcha-response given is verified" do agent.options['payload_path'] = '.' agent.options['recaptcha_secret'] = 'supersupersecret' webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => payload.merge({ 'g-recaptcha-response' => 'somevalue' }), 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) checked = false out = nil stub_request(:any, /verify/).to_return { |request| checked = true { status: 200, body: '{"success":true}' } } expect { out = agent.receive_web_request(webpayload) }.to change { checked } expect(out).to eq(["Event Created", 201]) expect(Event.last.payload).to eq(payload) end it "should accept a request if recaptcha_secret is set and g-recaptcha-response given is verified and reCAPTCHA v3 score is above score_treshold" do agent.options['payload_path'] = '.' agent.options['recaptcha_secret'] = 'supersupersecret' agent.options['score_threshold'] = 0.5 webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => payload.merge({ 'g-recaptcha-response' => 'somevalue' }), 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) checked = false out = nil stub_request(:any, /verify/).to_return { |request| checked = true { status: 200, body: '{"success":true, "score":0.9}' } } expect { out = agent.receive_web_request(webpayload) }.to change { checked } expect(out).to eq(["Event Created", 201]) expect(Event.last.payload).to eq(payload) end it "should reject a request if recaptcha_secret is set and g-recaptcha-response given is verified and reCAPTCHA v3 score is below score_treshold" do agent.options['payload_path'] = '.' agent.options['recaptcha_secret'] = 'supersupersecret' agent.options['score_threshold'] = 0.5 webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => payload.merge({ 'g-recaptcha-response' => 'somevalue' }), 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) checked = false out = nil stub_request(:any, /verify/).to_return { |request| checked = true { status: 200, body: '{"success":true, "score":0.1}' } } expect { out = agent.receive_web_request(webpayload) }.to change { checked } expect(out).to eq(["Not Authorized", 401]) end end end context "with headers" do it "should not pass any headers if event_headers_key is not set" do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) agent.options['event_headers'] = 'Accept,X-Hello-World' agent.options['event_headers_key'] = '' out = nil expect { out = agent.receive_web_request(webpayload) }.to change { Event.count }.by(1) expect(out).to eq(['Event Created', 201]) expect(Event.last.payload).to eq(payload) end it "should pass selected headers specified in event_headers_key" do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) agent.options['event_headers'] = 'X-Hello-World' agent.options['event_headers_key'] = 'X-HTTP-HEADERS' out = nil expect { out= agent.receive_web_request(webpayload) }.to change { Event.count }.by(1) expect(out).to eq(['Event Created', 201]) expect(Event.last.payload).to eq({"people"=>[{"name"=>"bob"}, {"name"=>"jon"}], "X-HTTP-HEADERS"=>{"X-Hello-World"=>"Hello Huginn"}}) end it "should pass empty event_headers_key if none of the headers exist" do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) agent.options['event_headers'] = 'x-hello-world1' agent.options['event_headers_key'] = 'X-HTTP-HEADERS' out = nil expect { out= agent.receive_web_request(webpayload) }.to change { Event.count }.by(1) expect(out).to eq(['Event Created', 201]) expect(Event.last.payload).to eq({"people"=>[{"name"=>"bob"}, {"name"=>"jon"}], "X-HTTP-HEADERS"=>{}}) end it "should pass empty event_headers_key if event_headers is empty" do webpayload = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { 'some_key' => payload }, 'action_dispatch.request.path_parameters' => { secret: 'foobar' }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_HELLO_WORLD' => "Hello Huginn" }) agent.options['event_headers'] = '' agent.options['event_headers_key'] = 'X-HTTP-HEADERS' out = nil expect { out= agent.receive_web_request(webpayload) }.to change { Event.count }.by(1) expect(out).to eq(['Event Created', 201]) expect(Event.last.payload).to eq({"people"=>[{"name"=>"bob"}, {"name"=>"jon"}], "X-HTTP-HEADERS"=>{}}) end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/website_agent_spec.rb
spec/models/agents/website_agent_spec.rb
require 'rails_helper' describe Agents::WebsiteAgent do describe "checking without basic auth" do before do stub_request(:any, /xkcd/).to_return(body: File.read(Rails.root.join("spec/data_fixtures/xkcd.html")), status: 200, headers: { 'X-Status-Message' => 'OK' }) stub_request(:any, /xkcd\.com\/index$/).to_return(status: 301, headers: { 'Location' => 'http://xkcd.com/' }) @valid_options = { 'name' => "XKCD", 'expected_update_period_in_days' => "2", 'type' => "html", 'url' => "http://xkcd.com", 'mode' => 'on_change', 'extract' => { 'url' => { 'css' => "#comic img", 'value' => "@src" }, 'title' => { 'css' => "#comic img", 'value' => "@alt" }, 'hovertext' => { 'css' => "#comic img", 'value' => "@title" } } } @checker = Agents::WebsiteAgent.new(name: "xkcd", options: @valid_options, keep_events_for: 2.days) @checker.user = users(:bob) @checker.save! end it_behaves_like WebRequestConcern describe "validations" do before do expect(@checker).to be_valid end it "should validate the integer fields" do @checker.options['expected_update_period_in_days'] = "2" expect(@checker).to be_valid @checker.options['expected_update_period_in_days'] = "nonsense" expect(@checker).not_to be_valid end it 'should validate the http_success_codes fields' do @checker.options['http_success_codes'] = [404] expect(@checker).to be_valid @checker.options['http_success_codes'] = [404, 404] expect(@checker).not_to be_valid @checker.options['http_success_codes'] = [404, "422"] expect(@checker).to be_valid @checker.options['http_success_codes'] = [404.0] expect(@checker).not_to be_valid @checker.options['http_success_codes'] = ["not_a_code"] expect(@checker).not_to be_valid @checker.options['http_success_codes'] = [] expect(@checker).to be_valid @checker.options['http_success_codes'] = '' expect(@checker).to be_valid @checker.options['http_success_codes'] = false expect(@checker).to be_valid end it "should validate uniqueness_look_back" do @checker.options['uniqueness_look_back'] = "nonsense" expect(@checker).not_to be_valid @checker.options['uniqueness_look_back'] = "2" expect(@checker).to be_valid end it "should validate mode" do @checker.options['mode'] = "nonsense" expect(@checker).not_to be_valid @checker.options['mode'] = "on_change" expect(@checker).to be_valid @checker.options['mode'] = "all" expect(@checker).to be_valid @checker.options['mode'] = "" expect(@checker).to be_valid end it "should validate the force_encoding option" do @checker.options['force_encoding'] = '' expect(@checker).to be_valid @checker.options['force_encoding'] = 'UTF-8' expect(@checker).to be_valid @checker.options['force_encoding'] = ['UTF-8'] expect(@checker).not_to be_valid @checker.options['force_encoding'] = 'UTF-42' expect(@checker).not_to be_valid end context "in 'json' type" do it "should ensure that all extractions have a 'path'" do @checker.options['type'] = 'json' @checker.options['extract'] = { 'url' => { 'foo' => 'bar' }, } expect(@checker).to_not be_valid expect(@checker.errors_on(:base)).to include(/When type is json, all extractions must have a path attribute/) @checker.options['type'] = 'json' @checker.options['extract'] = { 'url' => { 'path' => 'bar' }, } expect(@checker).to be_valid end end context "in 'html' type" do it "should ensure that all extractions have either 'xpath' or 'css'" do @checker.options['type'] = 'html' @checker.options['extract'] = { 'url' => { 'array' => true }, } expect(@checker).to_not be_valid expect(@checker.errors_on(:base)).to include(/When type is html or xml, all extractions must have a css or xpath attribute/) & include(/Unknown key "array"/) @checker.options['extract'] = { 'url' => { 'xpath' => '//bar', 'single_array' => true }, } expect(@checker).to be_valid @checker.options['extract'] = { 'url' => { 'css' => 'bar' }, } expect(@checker).to be_valid end end end describe "#check" do it "should check for changes (and update Event.expires_at)" do travel(-2.seconds) do expect { @checker.check }.to change { Event.count }.by(1) end event = Event.last expect { @checker.check }.not_to(change { Event.count }) update_event = Event.last expect(update_event.expires_at).not_to eq(event.expires_at) end it "should always save events when in :all mode" do expect { @valid_options['mode'] = 'all' @checker.options = @valid_options @checker.check @checker.check }.to change { Event.count }.by(2) end it "should take uniqueness_look_back into account during deduplication" do @valid_options['mode'] = 'all' @checker.options = @valid_options @checker.check @checker.check event = Event.last event.payload = "{}" event.save expect { @valid_options['mode'] = 'on_change' @valid_options['uniqueness_look_back'] = 2 @checker.options = @valid_options @checker.check }.not_to(change { Event.count }) expect { @valid_options['mode'] = 'on_change' @valid_options['uniqueness_look_back'] = 1 @checker.options = @valid_options @checker.check }.to change { Event.count }.by(1) end it "should log an error if the number of results for a set of extraction patterns differs" do @valid_options['extract']['url']['css'] = "div" @checker.options = @valid_options @checker.check expect(@checker.logs.first.message).to match(/Got an uneven number of matches/) end it "should accept an array for url" do @valid_options['url'] = ["http://xkcd.com/1/", "http://xkcd.com/2/"] @checker.options = @valid_options expect { @checker.save! }.not_to raise_error expect { @checker.check }.not_to raise_error end it "should parse events from all urls in array" do expect { @valid_options['url'] = ["http://xkcd.com/", "http://xkcd.com/"] @valid_options['mode'] = 'all' @checker.options = @valid_options @checker.check }.to change { Event.count }.by(2) end it "should follow unique rules when parsing array of urls" do expect { @valid_options['url'] = ["http://xkcd.com/", "http://xkcd.com/"] @checker.options = @valid_options @checker.check }.to change { Event.count }.by(1) end end describe 'http_success_codes' do it 'should allow scraping from a 404 result' do json = { 'response' => { 'version' => 2, 'title' => "hello!" } } zipped = ActiveSupport::Gzip.compress(json.to_json) stub_request(:any, /gzip/).to_return(body: zipped, headers: { 'Content-Encoding' => 'gzip' }, status: 404) site = { 'name' => "Some JSON Response", 'expected_update_period_in_days' => "2", 'type' => "json", 'url' => "http://gzip.com", 'mode' => 'on_change', 'http_success_codes' => [404], 'extract' => { 'version' => { 'path' => 'response.version' }, }, # no unzip option } checker = Agents::WebsiteAgent.new(name: "Weather Site", options: site) checker.user = users(:bob) checker.save! checker.check event = Event.last expect(event.payload['version']).to eq(2) end end describe 'unzipping' do it 'should unzip automatically if the response has Content-Encoding: gzip' do json = { 'response' => { 'version' => 2, 'title' => "hello!" } } zipped = ActiveSupport::Gzip.compress(json.to_json) stub_request(:any, /gzip/).to_return(body: zipped, headers: { 'Content-Encoding' => 'gzip' }, status: 200) site = { 'name' => "Some JSON Response", 'expected_update_period_in_days' => "2", 'type' => "json", 'url' => "http://gzip.com", 'mode' => 'on_change', 'extract' => { 'version' => { 'path' => 'response.version' }, }, # no unzip option } checker = Agents::WebsiteAgent.new(name: "Weather Site", options: site) checker.user = users(:bob) checker.save! checker.check event = Event.last expect(event.payload['version']).to eq(2) end it 'should unzip with unzip option' do json = { 'response' => { 'version' => 2, 'title' => "hello!" } } zipped = ActiveSupport::Gzip.compress(json.to_json) stub_request(:any, /gzip/).to_return(body: zipped, status: 200) site = { 'name' => "Some JSON Response", 'expected_update_period_in_days' => "2", 'type' => "json", 'url' => "http://gzip.com", 'mode' => 'on_change', 'extract' => { 'version' => { 'path' => 'response.version' }, }, 'unzip' => 'gzip', } checker = Agents::WebsiteAgent.new(name: "Weather Site", options: site) checker.user = users(:bob) checker.save! checker.check event = Event.last expect(event.payload['version']).to eq(2) end it 'should either avoid or support a raw deflate stream (#1018)' do stub_request(:any, /deflate/).with(headers: { 'Accept-Encoding' => /\A(?!.*deflate)/ }) .to_return(body: 'hello', status: 200) stub_request(:any, /deflate/).with(headers: { 'Accept-Encoding' => /deflate/ }) .to_return(body: "\xcb\x48\xcd\xc9\xc9\x07\x00\x06\x2c".b, headers: { 'Content-Encoding' => 'deflate' }, status: 200) site = { 'name' => 'Some Response', 'expected_update_period_in_days' => '2', 'type' => 'text', 'url' => 'http://deflate', 'mode' => 'on_change', 'extract' => { 'content' => { 'regexp' => '.+', 'index' => 0 } } } checker = Agents::WebsiteAgent.new(name: "Deflate Test", options: site) checker.user = users(:bob) checker.save! expect { checker.check }.to change { Event.count }.by(1) event = Event.last expect(event.payload['content']).to eq('hello') end end describe 'encoding' do let :huginn do "\u{601d}\u{8003}" end let :odin do "\u{d3}\u{f0}inn" end let :url do 'http://encoding-test.example.com/' end let :content_type do raise 'define me' end let :body do raise 'define me' end before do stub_request(:any, url).to_return( headers: { 'Content-Type' => content_type, }, body: body.b, status: 200 ) end let :options do { 'name' => 'Some agent', 'expected_update_period_in_days' => '2', 'url' => url, 'mode' => 'on_change', } end let :checker do Agents::WebsiteAgent.create!(name: 'Encoding Checker', options:) { |agent| agent.user = users(:bob) } end context 'with no encoding information' do context 'for a JSON file' do let :content_type do 'application/json' end let :body do { value: huginn, }.to_json end let :options do super().merge( 'type' => 'json', 'extract' => { 'value' => { 'path' => 'value' } } ) end it 'should be assumed to be UTF-8' do expect { checker.check }.to change { Event.count }.by(1) event = Event.last expect(event.payload['value']).to eq(huginn) end end context 'for an HTML file' do let :content_type do 'text/html' end let :options do super().merge( 'type' => 'html', 'extract' => { 'value' => { 'css' => 'title', 'value' => 'string(.)' } } ) end context 'with a charset in the header' do let :content_type do super() + '; charset=iso-8859-1' end let :body do <<~HTML.encode(Encoding::ISO_8859_1) <!DOCTYPE html> <title>#{odin}</title> <p>Hello, world. HTML end it 'should be detected from it' do expect { checker.check }.to change { Event.count }.by(1) event = Event.last expect(event.payload['value']).to eq(odin) end end context 'with no charset in the header' do let :body do <<~HTML.encode(Encoding::ISO_8859_1) <!DOCTYPE html> <meta charset="iso-8859-1"> <title>#{odin}</title> <p>Hello, world. HTML end it 'should be detected from a meta tag' do expect { checker.check }.to change { Event.count }.by(1) event = Event.last expect(event.payload['value']).to eq(odin) end end context 'with charset desclarations both in the header and in the content' do let :content_type do super() + '; charset=iso-8859-1' end let :body do <<~HTML.encode(Encoding::ISO_8859_1) <!DOCTYPE html> <meta charset="UTF-8"> <title>#{odin}</title> <p>Hello, world. HTML end it 'should be detected as that of the header' do expect { checker.check }.to change { Event.count }.by(1) event = Event.last expect(event.payload['value']).to eq(odin) end end end context 'for an XML file' do let :content_type do 'application/xml' end let :options do super().merge( 'type' => 'xml', 'extract' => { 'value' => { 'xpath' => '/root/message', 'value' => 'string(.)' } } ) end context 'with a charset in the header' do let :content_type do super() + '; charset=euc-jp' end let :body do <<~XML.encode(Encoding::EUC_JP) <?xml version="1.0"?> <root> <message>#{huginn}</message> </root> XML end it 'should be detected from it' do expect { checker.check }.to change { Event.count }.by(1) event = Event.last expect(event.payload['value']).to eq(huginn) end end context 'with no charset in the header' do context 'but in XML declaration' do let :body do <<~XML.encode(Encoding::EUC_JP) <?xml version="1.0" encoding="euc-jp"?> <root> <message>#{huginn}</message> </root> XML end it 'should be detected' do expect { checker.check }.to change { Event.count }.by(1) event = Event.last expect(event.payload['value']).to eq(huginn) end end context 'but having a BOM' do let :body do <<~XML.encode(Encoding::UTF_16LE) \u{feff}<?xml version="1.0"?> <root> <message>#{huginn}</message> </root> XML end it 'should be detected' do expect { checker.check }.to change { Event.count }.by(1) event = Event.last expect(event.payload['value']).to eq(huginn) end end end end end context 'when force_encoding option is specified' do let :options do super().merge( 'force_encoding' => 'EUC-JP' ) end context 'for a JSON file' do let :content_type do 'application/json' end let :body do { value: huginn, }.to_json.encode(Encoding::EUC_JP) end let :options do super().merge( 'type' => 'json', 'extract' => { 'value' => { 'path' => 'value' } } ) end it 'should be forced' do expect { checker.check }.to change { Event.count }.by(1) event = Event.last expect(event.payload['value']).to eq(huginn) end end context 'for an HTML file' do let :content_type do 'text/html' end context 'with charset specified in the header and the content' do let :content_type do super() + '; charset=UTF-8' end let :body do <<~HTML.encode(Encoding::EUC_JP) <!DOCTYPE html> <meta charset="UTF-8"/> <title>#{huginn}</title> <p>Hello, world. HTML end let :options do super().merge( 'type' => 'html', 'extract' => { 'value' => { 'css' => 'title', 'value' => 'string(.)' } } ) end it 'should still be forced' do expect { checker.check }.to change { Event.count }.by(1) event = Event.last expect(event.payload['value']).to eq(huginn) end end end end end describe '#working?' do it 'checks if events have been received within the expected receive period' do stubbed_time = Time.now allow(Time).to receive(:now) { stubbed_time } expect(@checker).not_to be_working # No events created @checker.check expect(@checker.reload).to be_working # Just created events @checker.error "oh no!" expect(@checker.reload).not_to be_working # There is a recent error stubbed_time = 20.minutes.from_now @checker.events.delete_all @checker.check expect(@checker.reload).to be_working # There is a newer event now stubbed_time = 2.days.from_now expect(@checker.reload).not_to be_working # Two days have passed without a new event having been created end end describe "parsing" do it "parses CSS" do @checker.check event = Event.last expect(event.payload['url']).to eq("http://imgs.xkcd.com/comics/evolving.png") expect(event.payload['title']).to eq("Evolving") expect(event.payload['hovertext']).to match(/^Biologists play reverse/) end it "parses XPath" do @valid_options['extract'].each { |key, value| value.delete('css') value['xpath'] = "//*[@id='comic']//img" } @checker.options = @valid_options @checker.check event = Event.last expect(event.payload).to match( 'url' => 'http://imgs.xkcd.com/comics/evolving.png', 'title' => 'Evolving', 'hovertext' => /^Biologists play reverse/ ) end it "should exclude hidden keys" do @valid_options['extract']['hovertext']['hidden'] = true @checker.options = @valid_options @checker.check event = Event.last expect(event.payload).to match( 'url' => 'http://imgs.xkcd.com/comics/evolving.png', 'title' => 'Evolving' ) end it "should return an integer value if XPath evaluates to one" do rel_site = { 'name' => "XKCD", 'expected_update_period_in_days' => 2, 'type' => "html", 'url' => "http://xkcd.com", 'mode' => "on_change", 'extract' => { 'num_links' => { 'css' => "#comicLinks", 'value' => "count(./a)" } } } rel = Agents::WebsiteAgent.new(name: "xkcd", options: rel_site) rel.user = users(:bob) rel.save! rel.check event = Event.last expect(event.payload['num_links']).to eq("9") end it "should return everything concatenated if XPath returns many nodes" do rel_site = { 'name' => "XKCD", 'expected_update_period_in_days' => 2, 'type' => "html", 'url' => "http://xkcd.com", 'mode' => "on_change", 'extract' => { 'slogan' => { 'css' => "#slogan", 'value' => ".//text()" } } } rel = Agents::WebsiteAgent.new(name: "xkcd", options: rel_site) rel.user = users(:bob) rel.save! rel.check event = Event.last expect(event.payload['slogan']).to eq("A webcomic of romance, sarcasm, math, &amp; language.") end it "should return an array if XPath returns many nodes and the raw option is specified" do rel_site = { 'name' => "XKCD", 'expected_update_period_in_days' => 2, 'type' => "html", 'url' => "http://xkcd.com", 'mode' => "on_change", 'extract' => { 'slogan' => { 'css' => "#slogan", 'value' => ".//text()", 'raw' => true }, 'slogan_length' => { 'css' => "#slogan", 'value' => "string-length(.)", 'raw' => true }, } } rel = Agents::WebsiteAgent.new(name: "xkcd", options: rel_site) rel.user = users(:bob) rel.save! rel.check event = Event.last expect(event.payload['slogan']).to eq(["A webcomic of romance,", " sarcasm, math, &amp; language."]) expect(event.payload['slogan_length']).to eq(49) end it "should return a string value returned by XPath" do rel_site = { 'name' => "XKCD", 'expected_update_period_in_days' => 2, 'type' => "html", 'url' => "http://xkcd.com", 'mode' => "on_change", 'extract' => { 'slogan' => { 'css' => "#slogan", 'value' => "string(.)" }, 'slogan_length' => { 'css' => "#slogan", 'value' => "string-length(.)" }, } } rel = Agents::WebsiteAgent.new(name: "xkcd", options: rel_site) rel.user = users(:bob) rel.save! rel.check event = Event.last expect(event.payload['slogan']).to eq("A webcomic of romance, sarcasm, math, & language.") expect(event.payload['slogan_length']).to eq("49") end it "should interpolate _response_" do @valid_options['url'] = 'http://xkcd.com/index' @valid_options['extract']['response_info'] = @valid_options['extract']['url'].merge( 'value' => '{{ "The reponse from " | append:_response_.url | append:" was " | append:_response_.status | append:" " | append:_response_.headers.X-Status-Message | append:"." | to_xpath }}' ) @valid_options['extract']['original_url'] = @valid_options['extract']['url'].merge( 'value' => '{{ _url_ | to_xpath }}' ) @checker.options = @valid_options @checker.check event = Event.last expect(event.payload['response_info']).to eq('The reponse from http://xkcd.com/ was 200 OK.') expect(event.payload['original_url']).to eq('http://xkcd.com/index') end it "should format and merge values in template after extraction" do @valid_options['extract']['hovertext']['hidden'] = true @valid_options['template'] = { 'title' => '{{title | upcase}}', 'summary' => '{{title}}: {{hovertext | truncate: 20}}', } @checker.options = @valid_options @checker.check expect(@checker.event_keys).to contain_exactly('url', 'title', 'summary') expect(@checker.event_description.scan(/"(\w+)": "\.\.\."/).flatten).to contain_exactly('url', 'title', 'summary') event = Event.last expect(event.payload).to eq({ 'title' => 'EVOLVING', 'url' => 'http://imgs.xkcd.com/comics/evolving.png', 'summary' => 'Evolving: Biologists play r...', }) end describe "XML" do before do stub_request(:any, /github_rss/).to_return( body: File.read(Rails.root.join("spec/data_fixtures/github_rss.atom")), status: 200 ) @checker = Agents::WebsiteAgent.new(name: 'github', options: { 'name' => 'GitHub', 'expected_update_period_in_days' => '2', 'type' => 'xml', 'url' => 'http://example.com/github_rss.atom', 'mode' => 'on_change', 'extract' => { 'title' => { 'xpath' => '/feed/entry', 'value' => 'normalize-space(./title)' }, 'url' => { 'xpath' => '/feed/entry', 'value' => './link[1]/@href' }, 'thumbnail' => { 'xpath' => '/feed/entry', 'value' => './thumbnail/@url' }, 'page_title' => { 'xpath' => '/feed/title', 'value' => 'string(.)', 'repeat' => true } } }, keep_events_for: 2.days) @checker.user = users(:bob) @checker.save! end it "works with XPath" do expect { @checker.check }.to change { Event.count }.by(20) events = Event.last(20) expect(events.size).to eq(20) expect(events.map { |event| event.payload['page_title'] }.uniq).to eq(['Recent Commits to huginn:master']) event = events.last expect(event.payload['title']).to eq('Shift to dev group') expect(event.payload['url']).to eq('https://github.com/cantino/huginn/commit/d465158f77dcd9078697e6167b50abbfdfa8b1af') expect(event.payload['thumbnail']).to eq('https://avatars3.githubusercontent.com/u/365751?s=30') end it "works with XPath with namespaces unstripped" do @checker.options['use_namespaces'] = 'true' @checker.save! expect { @checker.check }.to change { Event.count }.by(0) @checker.options['extract'] = { 'title' => { 'xpath' => '/xmlns:feed/xmlns:entry', 'value' => 'normalize-space(./xmlns:title)' }, 'url' => { 'xpath' => '/xmlns:feed/xmlns:entry', 'value' => './xmlns:link[1]/@href' }, 'thumbnail' => { 'xpath' => '/xmlns:feed/xmlns:entry', 'value' => './media:thumbnail/@url' }, } @checker.save! expect { @checker.check }.to change { Event.count }.by(20) event = Event.last expect(event.payload['title']).to eq('Shift to dev group') expect(event.payload['url']).to eq('https://github.com/cantino/huginn/commit/d465158f77dcd9078697e6167b50abbfdfa8b1af') expect(event.payload['thumbnail']).to eq('https://avatars3.githubusercontent.com/u/365751?s=30') end it "works with CSS selectors" do @checker.options['extract'] = { 'title' => { 'css' => 'feed > entry', 'value' => 'normalize-space(./title)' }, 'url' => { 'css' => 'feed > entry', 'value' => './link[1]/@href' }, 'thumbnail' => { 'css' => 'feed > entry', 'value' => './thumbnail/@url' }, } @checker.save! expect { @checker.check }.to change { Event.count }.by(20) event = Event.last expect(event.payload['title']).to be_empty expect(event.payload['thumbnail']).to be_empty @checker.options['extract'] = { 'title' => { 'css' => 'feed > entry', 'value' => 'normalize-space(./xmlns:title)' }, 'url' => { 'css' => 'feed > entry', 'value' => './xmlns:link[1]/@href' }, 'thumbnail' => { 'css' => 'feed > entry', 'value' => './media:thumbnail/@url' }, } @checker.save! expect { @checker.check }.to change { Event.count }.by(20) event = Event.last expect(event.payload['title']).to eq('Shift to dev group') expect(event.payload['url']).to eq('https://github.com/cantino/huginn/commit/d465158f77dcd9078697e6167b50abbfdfa8b1af') expect(event.payload['thumbnail']).to eq('https://avatars3.githubusercontent.com/u/365751?s=30') end it "works with CSS selectors with namespaces stripped" do @checker.options['extract'] = { 'title' => { 'css' => 'feed > entry', 'value' => 'normalize-space(./title)' }, 'url' => { 'css' => 'feed > entry', 'value' => './link[1]/@href' }, 'thumbnail' => { 'css' => 'feed > entry', 'value' => './thumbnail/@url' }, } @checker.options['use_namespaces'] = 'false' @checker.save! expect { @checker.check }.to change { Event.count }.by(20) event = Event.last expect(event.payload['title']).to eq('Shift to dev group') expect(event.payload['url']).to eq('https://github.com/cantino/huginn/commit/d465158f77dcd9078697e6167b50abbfdfa8b1af') expect(event.payload['thumbnail']).to eq('https://avatars3.githubusercontent.com/u/365751?s=30') end end describe "XML with cdata" do before do stub_request(:any, /cdata_rss/).to_return( body: File.read(Rails.root.join("spec/data_fixtures/cdata_rss.atom")), status: 200 ) @checker = Agents::WebsiteAgent.new(name: 'cdata', options: { 'name' => 'CDATA', 'expected_update_period_in_days' => '2', 'type' => 'xml', 'url' => 'http://example.com/cdata_rss.atom', 'mode' => 'on_change', 'extract' => { 'author' => { 'xpath' => '/feed/entry/author/name', 'value' => 'string(.)' }, 'title' => { 'xpath' => '/feed/entry/title', 'value' => 'string(.)' }, 'content' => { 'xpath' => '/feed/entry/content', 'value' => 'string(.)' }, } }, keep_events_for: 2.days) @checker.user = users(:bob) @checker.save! end it "works with XPath" do expect { @checker.check }.to change { Event.count }.by(10) event = Event.last expect(event.payload['author']).to eq('bill98') expect(event.payload['title']).to eq('Help: Rainmeter Skins • Test if Today is Between 2 Dates') expect(event.payload['content']).to start_with('Can I ') end end describe "JSON" do
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
true
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/event_formatting_agent_spec.rb
spec/models/agents/event_formatting_agent_spec.rb
require 'rails_helper' describe Agents::EventFormattingAgent do before do @valid_params = { :name => "somename", :options => { :instructions => { :message => "Received {{content.text}} from {{content.name}} .", :subject => "Weather looks like {{conditions}} according to the forecast at {{pretty_date.time}}", :timezone => "{{timezone}}", :agent => "{{agent.type}}", :created_at => "{{created_at}}", :created_at_iso => "{{created_at | date:'%FT%T%:z'}}", }, :mode => "clean", :matchers => [ { :path => "{{date.pretty}}", :regexp => "\\A(?<time>\\d\\d:\\d\\d [AP]M [A-Z]+)", :to => "pretty_date", }, { :path => "{{pretty_date.time}}", :regexp => "(?<timezone>[A-Z]+)\\z", }, ], } } @checker = Agents::EventFormattingAgent.new(@valid_params) @checker.user = users(:jane) @checker.save! @event = Event.new @event.agent = agents(:jane_weather_agent) @event.created_at = Time.now @event.payload = { :content => { :text => "Some Lorem Ipsum", :name => "somevalue", }, :date => { :epoch => "1357959600", :pretty => "10:00 PM EST on January 11, 2013" }, :conditions => "someothervalue" } @event2 = Event.new @event2.agent = agents(:jane_weather_agent) @event2.created_at = Time.now @event2.payload = { :content => { :text => "Some Lorem Ipsum 2", :name => "somevalue2", }, :date => { :epoch => "1366372800", :pretty => "08:00 AM EDT on April 19, 2013" }, :conditions => "someothervalue2" } end describe "#receive" do it "should accept clean mode" do @checker.receive([@event]) expect(Event.last.payload[:content]).to eq(nil) end it "should accept merge mode" do @checker.options[:mode] = "merge" @checker.receive([@event]) expect(Event.last.payload[:content]).not_to eq(nil) end it "should handle Liquid templating in mode" do @checker.options[:mode] = "{{'merge'}}" @checker.receive([@event]) expect(Event.last.payload[:content]).not_to eq(nil) end it "should handle Liquid templating in instructions" do @checker.receive([@event]) expect(Event.last.payload[:message]).to eq("Received Some Lorem Ipsum from somevalue .") expect(Event.last.payload[:agent]).to eq("WeatherAgent") expect(Event.last.payload[:created_at]).to eq(@event.created_at.to_s) expect(Event.last.payload[:created_at_iso]).to eq(@event.created_at.iso8601) end it "should handle matchers and Liquid templating in instructions" do expect { @checker.receive([@event, @event2]) }.to change { Event.count }.by(2) formatted_event1, formatted_event2 = Event.last(2) expect(formatted_event1.payload[:subject]).to eq("Weather looks like someothervalue according to the forecast at 10:00 PM EST") expect(formatted_event1.payload[:timezone]).to eq("EST") expect(formatted_event2.payload[:subject]).to eq("Weather looks like someothervalue2 according to the forecast at 08:00 AM EDT") expect(formatted_event2.payload[:timezone]).to eq("EDT") end it "should not fail if no matchers are defined" do @checker.options.delete(:matchers) expect { @checker.receive([@event, @event2]) }.to change { Event.count }.by(2) formatted_event1, formatted_event2 = Event.last(2) expect(formatted_event1.payload[:subject]).to eq("Weather looks like someothervalue according to the forecast at ") expect(formatted_event1.payload[:timezone]).to eq("") expect(formatted_event2.payload[:subject]).to eq("Weather looks like someothervalue2 according to the forecast at ") expect(formatted_event2.payload[:timezone]).to eq("") end it "should allow escaping" do @event.payload[:content][:name] = "escape this!?" @event.save! @checker.options[:instructions][:message] = "Escaped: {{content.name | uri_escape}}\nNot escaped: {{content.name}}" @checker.save! @checker.receive([@event]) expect(Event.last.payload[:message]).to eq("Escaped: escape+this%21%3F\nNot escaped: escape this!?") end it "should handle multiple events" do event1 = Event.new event1.agent = agents(:bob_weather_agent) event1.payload = { :content => { :text => "Some Lorem Ipsum", :name => "somevalue" }, :conditions => "someothervalue" } event2 = Event.new event2.agent = agents(:bob_weather_agent) event2.payload = { :content => { :text => "Some Lorem Ipsum", :name => "somevalue" }, :conditions => "someothervalue" } expect { @checker.receive([event2, event1]) }.to change { Event.count }.by(2) end end describe "validation" do before do expect(@checker).to be_valid end it "should validate presence of instructions" do @checker.options[:instructions] = "" expect(@checker).not_to be_valid end it "should validate type of matchers" do @checker.options[:matchers] = "" expect(@checker).not_to be_valid @checker.options[:matchers] = {} expect(@checker).not_to be_valid end it "should validate the contents of matchers" do @checker.options[:matchers] = [ {} ] expect(@checker).not_to be_valid @checker.options[:matchers] = [ { :regexp => "(not closed", :path => "text" } ] expect(@checker).not_to be_valid @checker.options[:matchers] = [ { :regexp => "(closed)", :path => "text", :to => "foo" } ] expect(@checker).to be_valid end it "should validate presence of mode" do @checker.options[:mode] = "" expect(@checker).not_to be_valid end it "requires mode to be 'clean' or 'merge'" do @checker.options['mode'] = 'what?' expect(@checker).not_to be_valid @checker.options['mode'] = 'clean' expect(@checker).to be_valid @checker.options['mode'] = 'merge' expect(@checker).to be_valid @checker.options['mode'] = :clean expect(@checker).to be_valid @checker.options['mode'] = :merge expect(@checker).to be_valid @checker.options['mode'] = '{{somekey}}' expect(@checker).to be_valid end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/tumblr_likes_agent_spec.rb
spec/models/agents/tumblr_likes_agent_spec.rb
require 'rails_helper' describe Agents::TumblrLikesAgent do before do allow_any_instance_of(Agents::TumblrLikesAgent).to receive(:tumblr) { double.tap { |obj| allow(obj).to receive(:blog_likes).with('wendys.tumblr.com', after: 0) { JSON.parse File.read(Rails.root.join('spec/data_fixtures/tumblr_likes.json')) } allow(obj).to receive(:blog_likes).with('notfound.tumblr.com', after: 0) { { 'status' => 404, 'msg' => 'Not Found' } } } } end describe 'a blog which returns likes' do before do @agent = Agents::TumblrLikesAgent.new(name: "Wendy's Tumblr Likes", options: { blog_name: 'wendys.tumblr.com', expected_update_period_in_days: 10 }) @agent.service = services(:generic) @agent.user = users(:bob) @agent.save! end it 'creates events based on likes' do expect { @agent.check }.to change { Event.count }.by(20) end end describe 'a blog which returns an error' do before do @broken_agent = Agents::TumblrLikesAgent.new(name: "Fake Blog Likes", options: { blog_name: 'notfound.tumblr.com', expected_update_period_in_days: 10 }) @broken_agent.user = users(:bob) @broken_agent.service = services(:generic) @broken_agent.save! end it 'creates an error message when status and msg are returned instead of liked_posts' do expect { @broken_agent.check }.to change { @broken_agent.logs.count }.by(1) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/twitter_publish_agent_spec.rb
spec/models/agents/twitter_publish_agent_spec.rb
require 'rails_helper' describe Agents::TwitterPublishAgent do before do @opts = { :username => "HuginnBot", :expected_update_period_in_days => "2", :consumer_key => "---", :consumer_secret => "---", :oauth_token => "---", :oauth_token_secret => "---", :message => "{{text}}" } @checker = Agents::TwitterPublishAgent.new(:name => "HuginnBot", :options => @opts) @checker.service = services(:generic) @checker.user = users(:bob) @checker.save! @event = Event.new @event.agent = agents(:bob_weather_agent) @event.payload = { :text => 'Gonna rain..' } @event.save! @sent_messages = [] allow_any_instance_of(Agents::TwitterPublishAgent).to receive(:publish_tweet) { |message| @sent_messages << message OpenStruct.new(:id => 454209588376502272) } end describe '#receive' do it 'should publish any payload it receives' do event1 = Event.new event1.agent = agents(:bob_rain_notifier_agent) event1.payload = { :text => 'Gonna rain..' } event1.save! event2 = Event.new event2.agent = agents(:bob_weather_agent) event2.payload = { :text => 'More payload' } event2.save! Agents::TwitterPublishAgent.async_receive(@checker.id, [event1.id, event2.id]) expect(@sent_messages.count).to eq(2) expect(@checker.events.count).to eq(2) end end describe '#working?' do it 'checks if events have been received within the expected receive period' do expect(@checker).not_to be_working # No events received Agents::TwitterPublishAgent.async_receive(@checker.id, [@event.id]) expect(@checker.reload).to be_working # Just received events two_days_from_now = 2.days.from_now allow(Time).to receive(:now) { two_days_from_now } expect(@checker.reload).not_to be_working # More time has passed than the expected receive period without any new events end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/twitter_user_agent_spec.rb
spec/models/agents/twitter_user_agent_spec.rb
require 'rails_helper' describe Agents::TwitterUserAgent do before do # intercept the twitter API request for @tectonic's user profile stub_request(:any, "https://api.twitter.com/1.1/statuses/user_timeline.json?contributor_details=true&count=200&exclude_replies=false&include_entities=true&include_rts=true&screen_name=tectonic&tweet_mode=extended") .to_return(body: File.read(Rails.root.join("spec/data_fixtures/user_tweets.json")), headers: { 'Content-Type': 'application/json;charset=utf-8' }, status: 200) @opts = { username: "tectonic", include_retweets: "true", exclude_replies: "false", expected_update_period_in_days: "2", starting_at: "Jan 01 00:00:01 +0000 2000", consumer_key: "---", consumer_secret: "---", oauth_token: "---", oauth_token_secret: "---" } @checker = Agents::TwitterUserAgent.new(name: "tectonic", options: @opts) @checker.service = services(:generic) @checker.user = users(:bob) @checker.save! end describe "#check" do it "should check for changes" do expect { @checker.check }.to change { Event.count }.by(5) Event.last(5).each_cons(2) do |t1, t2| expect(t1.payload[:id]).to be < t2.payload[:id] end end end describe "#check with starting_at=future date" do it "should check for changes starting_at a future date, thus not find any" do opts = @opts.merge({ starting_at: "Jan 01 00:00:01 +0000 2999", }) checker = Agents::TwitterUserAgent.new(name: "tectonic", options: opts) checker.service = services(:generic) checker.user = users(:bob) checker.save! expect { checker.check }.to change { Event.count }.by(0) end end describe "#check that if choose time line is false then username is required" do before do stub_request(:any, "https://api.twitter.com/1.1/statuses/home_timeline.json?contributor_details=true&count=200&exclude_replies=false&include_entities=true&include_rts=true&tweet_mode=extended").to_return( body: File.read(Rails.root.join("spec/data_fixtures/user_tweets.json")), status: 200 ) end it 'requires username unless choose_home_time_line is true' do expect(@checker).to be_valid @checker.options['username'] = nil expect(@checker).to_not be_valid @checker.options['choose_home_time_line'] = 'true' expect(@checker).to be_valid end context "when choose_home_time_line is true" do before do @checker.options['choose_home_time_line'] = true @checker.options.delete('username') @checker.save! end end it "error messaged added if choose_home_time_line is false and username does not exist" do opts = @opts.tap { |o| o.delete(:username) }.merge!({ choose_home_time_line: "false" }) checker = Agents::TwitterUserAgent.new(name: "tectonic", options: opts) checker.service = services(:generic) checker.user = users(:bob) expect(checker.save).to eq false expect(checker.errors.full_messages.first).to eq("username is required") end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/twilio_receive_text_agent_spec.rb
spec/models/agents/twilio_receive_text_agent_spec.rb
require 'rails_helper' # Twilio Params # https://www.twilio.com/docs/api/twiml/sms/twilio_request # url: https://b924379f.ngrok.io/users/1/web_requests/7/sms-endpoint # params: {"ToCountry"=>"US", "ToState"=>"NY", "SmsMessageSid"=>"SMxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "NumMedia"=>"0", "ToCity"=>"NEW YORK", "FromZip"=>"48342", "SmsSid"=>"SMxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "FromState"=>"MI", "SmsStatus"=>"received", "FromCity"=>"PONTIAC", "Body"=>"Lol", "FromCountry"=>"US", "To"=>"+1347555555", "ToZip"=>"10016", "NumSegments"=>"1", "MessageSid"=>"SMxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "AccountSid"=>"ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "From"=>"+12485551111", "ApiVersion"=>"2010-04-01"} # signature: K29NMD9+v5/QLzbdGZW/DRGyxNU= describe Agents::TwilioReceiveTextAgent do before do allow_any_instance_of(Twilio::Security::RequestValidator).to receive(:validate) { true } end let(:payload) { { "ToCountry"=>"US", "ToState"=>"NY", "SmsMessageSid"=>"SMxxxxxxxxxxxxxxxx", "NumMedia"=>"0", "ToCity"=>"NEW YORK", "FromZip"=>"48342", "SmsSid"=>"SMxxxxxxxxxxxxxxxx", "FromState"=>"MI", "SmsStatus"=>"received", "FromCity"=>"PONTIAC", "Body"=>"Hy ", "FromCountry"=>"US", "To"=>"+1347555555", "ToZip"=>"10016", "NumSegments"=>"1", "MessageSid"=>"SMxxxxxxxxxxxxxxxx", "AccountSid"=>"ACxxxxxxxxxxxxxxxx", "From"=>"+12485551111", "ApiVersion"=>"2010-04-01"} } describe 'receive_twilio_text_message' do before do @agent = Agents::TwilioReceiveTextAgent.new( :name => 'twilioreceive', :options => { :account_sid => 'x', :auth_token => 'x', :server_url => 'http://example.com', :expected_receive_period_in_days => 1 } ) @agent.user = users(:bob) @agent.save! end it 'should create event upon receiving request' do request = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => payload.merge({"secret" => "sms-endpoint"}), 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_TWILIO_SIGNATURE' => "HpS7PBa1Agvt4OtO+wZp75IuQa0=" }) out = nil expect { out = @agent.receive_web_request(request) }.to change { Event.count }.by(1) expect(out).to eq(["<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Response/>\n", 200, "text/xml"]) expect(Event.last.payload).to eq(payload) end end describe 'receive_twilio_text_message and send a response' do before do @agent = Agents::TwilioReceiveTextAgent.new( :name => 'twilioreceive', :options => { :account_sid => 'x', :auth_token => 'x', :server_url => 'http://example.com', :reply_text => "thanks!", :expected_receive_period_in_days => 1 } ) @agent.user = users(:bob) @agent.save! end it 'should create event and send back TwiML Message if reply_text is set' do out = nil request = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => payload.merge({"secret" => "sms-endpoint"}), 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'application/xml', 'HTTP_X_TWILIO_SIGNATURE' => "HpS7PBa1Agvt4OtO+wZp75IuQa0=" }) expect { out = @agent.receive_web_request(request) }.to change { Event.count }.by(1) expect(out).to eq(["<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Response>\n<Message>thanks!</Message>\n</Response>\n", 200, "text/xml"]) expect(Event.last.payload).to eq(payload) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/jq_agent_spec.rb
spec/models/agents/jq_agent_spec.rb
require 'rails_helper' describe Agents::JqAgent do def create_event(payload) agents(:jane_weather_agent).events.create!(payload: payload) end let!(:agent) { Agents::JqAgent.create!( name: 'somename', options: { filter: '.+{"total": .numbers | add} | del(.numbers)' }, user: users(:jane) ) } describe '.should_run?' do it 'should be true' do expect(Agents::JqAgent).to be_should_run end context 'when not enabled' do before do allow(ENV).to receive(:[]) { nil } allow(ENV).to receive(:[]).with('USE_JQ') { nil } end it 'should be false' do expect(Agents::JqAgent).not_to be_should_run end end context 'when jq command is not available' do before do allow(Agents::JqAgent).to receive(:jq_version) { nil } end it 'should be false' do expect(Agents::JqAgent).not_to be_should_run end end end describe 'validation' do before do expect(agent).to be_valid end it 'should validate filter' do agent.options.delete(:filter) expect(agent).not_to be_valid agent.options[:filter] = [1] expect(agent).not_to be_valid # An empty expression is OK agent.options[:filter] = '' expect(agent).to be_valid end it 'should validate variables' do agent.options[:variables] = [] expect(agent).not_to be_valid agent.options[:variables] = '' expect(agent).not_to be_valid agent.options[:variables] = { 'x' => [1, 2, 3] } expect(agent).to be_valid end end describe '#receive' do let!(:event) { create_event({ name: 'foo', numbers: [1, 2, 3, 4] }) } it 'should filter an event and create a single event if the result is an object' do expect { agent.receive([event]) }.to change(Event, :count).by(1) created_event = agent.events.last expect(created_event.payload).to eq({ 'name' => 'foo', 'total' => 10 }) end it 'should filter an event and create no event if the result is an empty array' do agent.update!(options: { filter: '[]' }) expect { agent.receive([event]) }.not_to change(Event, :count) end it 'should filter an event and create no event if the result is a scalar value' do agent.update!(options: { filter: '.numbers | add' }) expect { agent.receive([event]) }.not_to change(Event, :count) end it 'should filter an event and create no event if the result is an array of scalar values' do agent.update!(options: { filter: '.numbers' }) expect { agent.receive([event]) }.not_to change(Event, :count) end it 'should filter an event and create multiple events if the result is an array of objects' do agent.update!(options: { filter: '. as $original | .numbers[] | $original + { "number": . } | del(.numbers)' }) expect { agent.receive([event]) }.to change(Event, :count).by(4) created_events = agent.events.limit(4) expect(created_events.map(&:payload)).to eq([ { 'name' => 'foo', 'number' => 4 }, { 'name' => 'foo', 'number' => 3 }, { 'name' => 'foo', 'number' => 2 }, { 'name' => 'foo', 'number' => 1 } ]) end it 'should reference passed in variables and filter an event' do agent.update!( options: { filter: '.+{ "extra": $somevar }', variables: { somevar: { foo: ['bar', 'baz'] } } } ) expect { agent.receive([event]) }.to change(Event, :count).by(1) created_event = agent.events.last expect(created_event.payload).to eq({ 'name' => 'foo', 'numbers' => [1, 2, 3, 4], 'extra' => { 'foo' => ['bar', 'baz'] } }) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/jira_agent_spec.rb
spec/models/agents/jira_agent_spec.rb
require 'rails_helper' describe Agents::JiraAgent do before(:each) do stub_request(:get, /atlassian.com/).to_return(:body => File.read(Rails.root.join("spec/data_fixtures/jira.json")), :status => 200, :headers => {"Content-Type" => "text/json"}) @valid_params = { :username => "user", :password => "pass", :jira_url => 'https://jira.atlassian.com', :jql => 'resolution = unresolved', :expected_update_period_in_days => '7', :timeout => '1' } @checker = Agents::JiraAgent.new(:name => "jira-agent", :options => @valid_params) @checker.user = users(:jane) @checker.save! end describe "validating" do before do expect(@checker).to be_valid end it "should work without username" do @checker.options['username'] = nil expect(@checker).to be_valid end it "should require the jira password if username is specified" do @checker.options['username'] = 'user' @checker.options['password'] = nil expect(@checker).not_to be_valid end it "should require the jira url" do @checker.options['jira_url'] = nil expect(@checker).not_to be_valid end it "should work without jql" do @checker.options['jql'] = nil expect(@checker).to be_valid end it "should require the expected_update_period_in_days" do @checker.options['expected_update_period_in_days'] = nil expect(@checker).not_to be_valid end it "should require timeout" do @checker.options['timeout'] = nil expect(@checker).not_to be_valid end end describe "helpers" do it "should generate a correct request options hash" do expect(@checker.send(:request_options)).to eq({basic_auth: {username: "user", password: "pass"}, headers: {"User-Agent" => "Huginn - https://github.com/huginn/huginn"}}) end it "should generate a correct request url" do expect(@checker.send(:request_url, 'foo=bar', 10)).to eq("https://jira.atlassian.com/rest/api/2/search?jql=foo%3Dbar&fields=*all&startAt=10") end it "should not set the 'since' time on the first run" do expected_url = "https://jira.atlassian.com/rest/api/2/search?jql=resolution+%3D+unresolved&fields=*all&startAt=0" expected_headers = {headers: {"User-Agent"=>"Huginn - https://github.com/huginn/huginn"}, basic_auth: {username: "user", password: "pass"}} reply = JSON.parse(File.read(Rails.root.join("spec/data_fixtures/jira.json"))) expect(@checker).to receive(:get).with(expected_url, expected_headers).and_return(reply) @checker.check end it "should provide set the 'since' time after the first run" do expected_url_1 = "https://jira.atlassian.com/rest/api/2/search?jql=resolution+%3D+unresolved&fields=*all&startAt=0" expected_url_2 = "https://jira.atlassian.com/rest/api/2/search?jql=resolution+%3D+unresolved&fields=*all&startAt=0" expected_headers = {headers: {"User-Agent"=>"Huginn - https://github.com/huginn/huginn"}, basic_auth: {username: "user", password: "pass"}} reply = JSON.parse(File.read(Rails.root.join("spec/data_fixtures/jira.json"))) expect(@checker).to receive(:get).with(expected_url_1, expected_headers).and_return(reply) @checker.check expect(@checker).to receive(:get).with(/\d+-\d+-\d+\+\d+%3A\d+/, expected_headers).and_return(reply) @checker.check end end describe "#check" do it "should be able to retrieve issues" do reply = JSON.parse(File.read(Rails.root.join("spec/data_fixtures/jira.json"))) expect(@checker).to receive(:get).and_return(reply) expect { @checker.check }.to change { Event.count }.by(50) end end describe "#working?" do it "it is working when at least one event was emited" do expect(@checker).not_to be_working @checker.check expect(@checker.reload).to be_working end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/json_parse_agent_spec.rb
spec/models/agents/json_parse_agent_spec.rb
require 'rails_helper' describe Agents::JsonParseAgent do before(:each) do @checker = Agents::JsonParseAgent.new(:name => "somename", :options => Agents::JsonParseAgent.new.default_options) @checker.user = users(:jane) @checker.save! end it "event description does not throw an exception" do expect(@checker.event_description).to include('parsed') end describe "validating" do before do expect(@checker).to be_valid end it "requires data to be present" do @checker.options['data'] = '' expect(@checker).not_to be_valid end it "requires data_key to be set" do @checker.options['data_key'] = '' expect(@checker).not_to be_valid end end context '#working' do it 'is not working without having received an event' do expect(@checker).not_to be_working end it 'is working after receiving an event without error' do @checker.last_receive_at = Time.now expect(@checker).to be_working end end describe "#receive" do it "parses valid JSON" do event = Event.new(payload: { data: '{"test": "data"}' } ) expect { @checker.receive([event]) }.to change(Event, :count).by(1) end it "writes to the error log when the JSON could not be parsed" do event = Event.new(payload: { data: '{"test": "data}' } ) expect { @checker.receive([event]) }.to change(AgentLog, :count).by(1) end it "support merge mode" do @checker.options[:mode] = "merge" event = Event.new(payload: { data: '{"test": "data"}', extra: 'a' } ) expect { @checker.receive([event]) }.to change { Event.count }.by(1) last_payload = Event.last.payload expect(last_payload['extra']).to eq('a') end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/gap_detector_agent_spec.rb
spec/models/agents/gap_detector_agent_spec.rb
require 'rails_helper' describe Agents::GapDetectorAgent do let(:valid_params) { { 'name' => "my gap detector agent", 'options' => { 'window_duration_in_days' => "2", 'message' => "A gap was found!" } } } let(:agent) { _agent = Agents::GapDetectorAgent.new(valid_params) _agent.user = users(:bob) _agent.save! _agent } describe 'validation' do before do expect(agent).to be_valid end it 'should validate presence of message' do agent.options['message'] = nil expect(agent).not_to be_valid end it 'should validate presence of window_duration_in_days' do agent.options['window_duration_in_days'] = "" expect(agent).not_to be_valid agent.options['window_duration_in_days'] = "wrong" expect(agent).not_to be_valid agent.options['window_duration_in_days'] = "1" expect(agent).to be_valid agent.options['window_duration_in_days'] = "0.5" expect(agent).to be_valid end end describe '#receive' do it 'records the event if it has a created_at newer than the last seen' do agent.receive([events(:bob_website_agent_event)]) expect(agent.memory['newest_event_created_at']).to eq events(:bob_website_agent_event).created_at.to_i events(:bob_website_agent_event).created_at = 2.days.ago expect { agent.receive([events(:bob_website_agent_event)]) }.to_not change { agent.memory['newest_event_created_at'] } events(:bob_website_agent_event).created_at = 2.days.from_now expect { agent.receive([events(:bob_website_agent_event)]) }.to change { agent.memory['newest_event_created_at'] }.to(events(:bob_website_agent_event).created_at.to_i) end it 'ignores the event if value_path is present and the value at the path is blank' do agent.options['value_path'] = 'title' agent.receive([events(:bob_website_agent_event)]) expect(agent.memory['newest_event_created_at']).to eq events(:bob_website_agent_event).created_at.to_i events(:bob_website_agent_event).created_at = 2.days.from_now events(:bob_website_agent_event).payload['title'] = '' expect { agent.receive([events(:bob_website_agent_event)]) }.to_not change { agent.memory['newest_event_created_at'] } events(:bob_website_agent_event).payload['title'] = 'present!' expect { agent.receive([events(:bob_website_agent_event)]) }.to change { agent.memory['newest_event_created_at'] }.to(events(:bob_website_agent_event).created_at.to_i) end it 'clears any previous alert' do agent.memory['alerted_at'] = 2.days.ago.to_i agent.receive([events(:bob_website_agent_event)]) expect(agent.memory).to_not have_key('alerted_at') end end describe '#check' do it 'alerts once if no data has been received during window_duration_in_days' do agent.memory['newest_event_created_at'] = 1.days.ago.to_i expect { agent.check }.to_not change { agent.events.count } agent.memory['newest_event_created_at'] = 3.days.ago.to_i expect { agent.check }.to change { agent.events.count }.by(1) expect(agent.events.last.payload).to eq ({ 'message' => 'A gap was found!', 'gap_started_at' => agent.memory['newest_event_created_at'] }) expect { agent.check }.not_to change { agent.events.count } end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/dropbox_file_url_agent_spec.rb
spec/models/agents/dropbox_file_url_agent_spec.rb
require 'rails_helper' describe Agents::DropboxFileUrlAgent do before(:each) do @agent = Agents::DropboxFileUrlAgent.new( name: 'dropbox file to url', options: {} ) @agent.user = users(:bob) @agent.service = services(:generic) @agent.save! end it 'cannot be scheduled' do expect(@agent.cannot_be_scheduled?).to eq true end it 'has agent description' do expect(@agent.description).to_not be_nil end it 'has event description' do expect(@agent.event_description).to_not be_nil end it 'renders the event description when link_type=permanent' do @agent.options['link_type'] = 'permanent' expect(@agent.event_description).to_not be_nil end describe "#receive" do def event(payload) event = Event.new(payload: payload) event.agent = agents(:bob_manual_event_agent) event end context 'with temporary urls' do let(:first_dropbox_url_payload) { Dropbox::API::Object.new({ 'link' => 'http://dropbox.com/first/path/url' }, nil) } let(:second_dropbox_url_payload) { Dropbox::API::Object.new({ 'link' => 'http://dropbox.com/second/path/url' }, nil) } let(:third_dropbox_url_payload) { Dropbox::API::Object.new({ 'link' => 'http://dropbox.com/third/path/url' }, nil) } before(:each) do allow(Dropbox::API::Client).to receive(:new) do instance_double(Dropbox::API::Client).tap { |api| allow(api).to receive(:find).with('/first/path') { Dropbox::API::File.new({}, nil).tap { |file| allow(file).to receive(:direct_url) { first_dropbox_url_payload } } } allow(api).to receive(:find).with('/second/path') { Dropbox::API::File.new({}, nil).tap { |file| allow(file).to receive(:direct_url) { second_dropbox_url_payload } } } allow(api).to receive(:find).with('/third/path') { Dropbox::API::File.new({}, nil).tap { |file| allow(file).to receive(:direct_url) { third_dropbox_url_payload } } } } end end context 'with a single path' do before(:each) { @event = event(paths: '/first/path') } it 'creates one event with the temporary dropbox link' do expect { @agent.receive([@event]) }.to change(Event, :count).by(1) expect(Event.last.payload).to eq({ 'url' => 'http://dropbox.com/first/path/url' }) end end context 'with multiple comma-separated paths' do before(:each) { @event = event(paths: '/first/path, /second/path, /third/path') } it 'creates one event with the temporary dropbox link for each path' do expect { @agent.receive([@event]) }.to change(Event, :count).by(3) last_events = Event.last(3) expect(last_events[0].payload['url']).to eq('http://dropbox.com/first/path/url') expect(last_events[1].payload['url']).to eq('http://dropbox.com/second/path/url') expect(last_events[2].payload['url']).to eq('http://dropbox.com/third/path/url') end end end context 'with permanent urls' do def response_for(url) Dropbox::API::Object.new({'url' => "https://www.dropbox.com/s/#{url}?dl=0"}, nil) end let(:first_dropbox_url_payload) { response_for('/first/path') } let(:second_dropbox_url_payload) { response_for('/second/path') } let(:third_dropbox_url_payload) { response_for('/third/path') } before(:each) do allow(Dropbox::API::Client).to receive(:new) do instance_double(Dropbox::API::Client).tap { |api| allow(api).to receive(:find).with('/first/path') { Dropbox::API::File.new({}, nil).tap { |file| allow(file).to receive(:share_url) { first_dropbox_url_payload } } } allow(api).to receive(:find).with('/second/path') { Dropbox::API::File.new({}, nil).tap { |file| allow(file).to receive(:share_url) { second_dropbox_url_payload } } } allow(api).to receive(:find).with('/third/path') { Dropbox::API::File.new({}, nil).tap { |file| allow(file).to receive(:share_url) { third_dropbox_url_payload } } } } end @agent.options['link_type'] = 'permanent' end it 'creates one event with a single path' do expect { @agent.receive([event(paths: '/first/path')]) }.to change(Event, :count).by(1) expect(Event.last.payload).to eq(first_dropbox_url_payload.response) end it 'creates one event with the permanent dropbox link for each path' do event = event(paths: '/first/path, /second/path, /third/path') expect { @agent.receive([event]) }.to change(Event, :count).by(3) last_events = Event.last(3) expect(last_events[0].payload).to eq(first_dropbox_url_payload.response) expect(last_events[1].payload).to eq(second_dropbox_url_payload.response) expect(last_events[2].payload).to eq(third_dropbox_url_payload.response) end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/twitter_action_agent_spec.rb
spec/models/agents/twitter_action_agent_spec.rb
require 'rails_helper' describe Agents::TwitterActionAgent do describe '#receive' do before do @event1 = Event.new @event1.agent = agents(:bob_twitter_user_agent) @event1.payload = { id: 123, text: 'So awesome.. gotta retweet' } @event1.save! @tweet1 = Twitter::Tweet.new( id: @event1.payload[:id], text: @event1.payload[:text] ) @event2 = Event.new @event2.agent = agents(:bob_twitter_user_agent) @event2.payload = { id: 456, text: 'Something Justin Bieber said' } @event2.save! @tweet2 = Twitter::Tweet.new( id: @event2.payload[:id], text: @event2.payload[:text] ) end context 'when set up to retweet' do before do @agent = build_agent( 'favorite' => 'false', 'retweet' => 'true', 'emit_error_events' => 'true' ) @agent.save! end context 'when the twitter client succeeds retweeting' do it 'should retweet the tweets from the payload' do expect(@agent.twitter).to receive(:retweet).with([@tweet1, @tweet2]) @agent.receive([@event1, @event2]) end end context 'when the twitter client fails retweeting' do it 'creates an event with tweet info and the error message' do allow(@agent.twitter).to receive(:retweet).with(anything) { raise Twitter::Error.new('uh oh') } @agent.receive([@event1, @event2]) failure_event = @agent.events.last expect(failure_event.payload[:error]).to eq('uh oh') expect(failure_event.payload[:tweets]).to eq( { @event1.payload[:id].to_s => @event1.payload[:text], @event2.payload[:id].to_s => @event2.payload[:text] } ) expect(failure_event.payload[:agent_ids]).to match_array( [@event1.agent_id, @event2.agent_id] ) expect(failure_event.payload[:event_ids]).to match_array( [@event2.id, @event1.id] ) end end end context 'when set up to favorite' do before do @agent = build_agent( 'favorite' => 'true', 'retweet' => 'false', 'emit_error_events' => 'true' ) @agent.save! end context 'when the twitter client succeeds favoriting' do it 'should favorite the tweets from the payload' do expect(@agent.twitter).to receive(:favorite).with([@tweet1, @tweet2]) @agent.receive([@event1, @event2]) end end context 'when the twitter client fails retweeting' do it 'creates an event with tweet info and the error message' do allow(@agent.twitter).to receive(:favorite).with(anything) { raise Twitter::Error.new('uh oh') } @agent.receive([@event1, @event2]) failure_event = @agent.events.last expect(failure_event.payload[:error]).to eq('uh oh') expect(failure_event.payload[:tweets]).to eq( { @event1.payload[:id].to_s => @event1.payload[:text], @event2.payload[:id].to_s => @event2.payload[:text] } ) expect(failure_event.payload[:agent_ids]).to match_array( [@event1.agent_id, @event2.agent_id] ) expect(failure_event.payload[:event_ids]).to match_array( [@event2.id, @event1.id] ) end end end context 'with emit_error_events set to false' do let(:agent) { build_agent.tap(&:save!) } it 're-raises the exception on failure' do allow(agent.twitter).to receive(:retweet).with(anything) { raise Twitter::Error.new('uh oh') } expect { agent.receive([@event1]) }.to raise_error(StandardError, /uh oh/) end it 'does not re-raise the exception on "already retweeted" error' do allow(agent.twitter).to receive(:retweet).with(anything) { raise Twitter::Error::AlreadyRetweeted.new('You have already retweeted this tweet.') } expect { agent.receive([@event1]) }.not_to raise_error end it 'does not re-raise the exception on "already favorited" error' do allow(agent.twitter).to receive(:retweet).with(anything) { raise Twitter::Error::AlreadyFavorited.new('You have already favorited this status.') } expect { agent.receive([@event1]) }.not_to raise_error end end end describe "#validate_options" do it 'the default options are valid' do agent = build_agent(described_class.new.default_options) expect(agent).to be_valid end context 'emit_error_events' do it 'can be set to true' do agent = build_agent(described_class.new.default_options.merge('emit_error_events' => 'true')) expect(agent).to be_valid end it 'must be a boolean' do agent = build_agent(described_class.new.default_options.merge('emit_error_events' => 'notbolean')) expect(agent).not_to be_valid end end it 'expected_receive_period_in_days must be set' do agent = build_agent(described_class.new.default_options.merge('expected_receive_period_in_days' => '')) expect(agent).not_to be_valid end context 'when set up to neither favorite or retweet' do it 'is invalid' do agent = build_agent( 'favorite' => 'false', 'retweet' => 'false', ) expect(agent).not_to be_valid end end end describe '#working?' do before do allow_any_instance_of(Twitter::REST::Client).to receive(:retweet) end it 'checks if events have been received within the expected time period' do agent = build_agent agent.save! expect(agent).not_to be_working # No events received described_class.async_receive(agent.id, [events(:bob_website_agent_event)]) expect(agent.reload).to be_working # Just received events two_days_from_now = 2.days.from_now allow(Time).to receive(:now) { two_days_from_now } expect(agent.reload).not_to be_working # Too much time has passed end end def build_agent(options = {}) described_class.new do |agent| agent.name = 'twitter stuff' agent.options = agent.default_options.merge(options) agent.service = services(:generic) agent.user = users(:bob) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/tumblr_publish_agent_spec.rb
spec/models/agents/tumblr_publish_agent_spec.rb
require 'rails_helper' describe Agents::TumblrPublishAgent do describe "Should create post" do before do @opts = { :blog_name => "huginnbot.tumblr.com", :post_type => "text", :expected_update_period_in_days => "2", :options => { :title => "{{title}}", :body => "{{body}}", }, } @checker = Agents::TumblrPublishAgent.new(:name => "HuginnBot", :options => @opts) @checker.service = services(:generic) @checker.user = users(:bob) @checker.save! @event = Event.new @event.agent = agents(:bob_weather_agent) @event.payload = { :title => "Gonna rain...", :body => 'San Francisco is gonna get wet' } @event.save! @post_body = { "id" => 5, "title" => "Gonna rain...", "link" => "http://huginnbot.tumblr.com/gonna-rain..." } allow_any_instance_of(Agents::TumblrPublishAgent).to receive(:tumblr) { double.tap { |obj| allow(obj).to receive(:text).with(anything, anything) { { "id" => "5" } } allow(obj).to receive(:posts).with("huginnbot.tumblr.com", { id: "5" }) { {"posts" => [@post_body]} } } } end describe '#receive' do it 'should publish any payload it receives' do Agents::TumblrPublishAgent.async_receive(@checker.id, [@event.id]) expect(@checker.events.count).to eq(1) expect(@checker.events.first.payload['post_id']).to eq('5') expect(@checker.events.first.payload['published_post']).to eq('[huginnbot.tumblr.com] text') expect(@checker.events.first.payload["post"]).to eq @post_body end end end describe "Should handle tumblr error" do before do @opts = { :blog_name => "huginnbot.tumblr.com", :post_type => "text", :expected_update_period_in_days => "2", :options => { :title => "{{title}}", :body => "{{body}}", }, } @checker = Agents::TumblrPublishAgent.new(:name => "HuginnBot", :options => @opts) @checker.service = services(:generic) @checker.user = users(:bob) @checker.save! @event = Event.new @event.agent = agents(:bob_weather_agent) @event.payload = { :title => "Gonna rain...", :body => 'San Francisco is gonna get wet' } @event.save! allow_any_instance_of(Agents::TumblrPublishAgent).to receive(:tumblr) { double.tap { |obj| allow(obj).to receive(:text).with(anything, anything) { {"status" => 401,"msg" => "Not Authorized"} } } } end describe '#receive' do it 'should publish any payload it receives and handle error' do Agents::TumblrPublishAgent.async_receive(@checker.id, [@event.id]) expect(@checker.events.count).to eq(0) end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/post_agent_spec.rb
spec/models/agents/post_agent_spec.rb
require 'rails_helper' require 'ostruct' describe Agents::PostAgent do let(:mocked_response) do { status: 200, body: "<html>a webpage!</html>", headers: { 'Content-type' => 'text/html', 'X-Foo-Bar' => 'baz', } } end before do @valid_options = { 'post_url' => "http://www.example.com", 'expected_receive_period_in_days' => 1, 'payload' => { 'default' => 'value' } } @valid_params = { name: "somename", options: @valid_options } @checker = Agents::PostAgent.new(@valid_params) @checker.user = users(:jane) @checker.save! @event = Event.new @event.agent = agents(:jane_weather_agent) @event.payload = { 'somekey' => 'somevalue', 'someotherkey' => { 'somekey' => 'value' } } @requests = 0 @sent_requests = Hash.new { |hash, method| hash[method] = [] } stub_request(:any, /:/).to_return { |request| method = request.method @requests += 1 @sent_requests[method] << req = OpenStruct.new(uri: request.uri, headers: request.headers) case method when :get, :delete req.data = request.uri.query else content_type = request.headers['Content-Type'][/\A[^;\s]+/] case content_type when 'application/x-www-form-urlencoded' req.data = request.body when 'application/json' req.data = ActiveSupport::JSON.decode(request.body) when 'text/xml' req.data = Hash.from_xml(request.body) when Agents::PostAgent::MIME_RE req.data = request.body else raise "unexpected Content-Type: #{content_type}" end end mocked_response } end it_behaves_like WebRequestConcern it_behaves_like 'FileHandlingConsumer' it 'renders the description markdown without errors' do expect { @checker.description }.not_to raise_error end describe "making requests" do it "can make requests of each type" do %w[get put post patch delete].each.with_index(1) do |verb, index| @checker.options['method'] = verb expect(@checker).to be_valid @checker.check expect(@requests).to eq(index) expect(@sent_requests[verb.to_sym].length).to eq(1) end end end describe "#receive" do it "can handle multiple events and merge the payloads with options['payload']" do event1 = Event.new event1.agent = agents(:bob_weather_agent) event1.payload = { 'xyz' => 'value1', 'message' => 'value2', 'default' => 'value2' } expect { expect { @checker.receive([@event, event1]) }.to change { @sent_requests[:post].length }.by(2) }.not_to(change { @sent_requests[:get].length }) expect(@sent_requests[:post][0].data).to eq(@event.payload.merge('default' => 'value').to_query) expect(@sent_requests[:post][1].data).to eq(event1.payload.to_query) end it "can make GET requests" do @checker.options['method'] = 'get' expect { expect { @checker.receive([@event]) }.to change { @sent_requests[:get].length }.by(1) }.not_to(change { @sent_requests[:post].length }) expect(@sent_requests[:get][0].data).to eq(@event.payload.merge('default' => 'value').to_query) end it "can make a GET request merging params in post_url, payload and event" do @checker.options['method'] = 'get' @checker.options['post_url'] = "http://example.com/a/path?existing_param=existing_value" @event.payload = { "some_param" => "some_value", "another_param" => "another_value" } @checker.receive([@event]) uri = @sent_requests[:get].first.uri # parameters are alphabetically sorted by Faraday expect(uri.request_uri).to eq("/a/path?another_param=another_value&default=value&existing_param=existing_value&some_param=some_value") end it "can skip merging the incoming event when no_merge is set, but it still interpolates" do @checker.options['no_merge'] = 'true' @checker.options['payload'] = { 'key' => 'it said: {{ someotherkey.somekey }}' } @checker.receive([@event]) expect(@sent_requests[:post].first.data).to eq({ 'key' => 'it said: value' }.to_query) end it "interpolates when receiving a payload" do @checker.options['post_url'] = "https://{{ domain }}/{{ variable }}?existing_param=existing_value" @event.payload = { 'domain' => 'google.com', 'variable' => 'a_variable' } @checker.receive([@event]) uri = @sent_requests[:post].first.uri expect(uri.scheme).to eq('https') expect(uri.host).to eq('google.com') expect(uri.path).to eq('/a_variable') expect(uri.query).to eq("existing_param=existing_value") end it "interpolates outgoing headers with the event payload" do @checker.options['headers'] = { "Foo" => "{{ variable }}" } @event.payload = { 'variable' => 'a_variable' } @checker.receive([@event]) headers = @sent_requests[:post].first.headers expect(headers["Foo"]).to eq("a_variable") end it 'makes a multipart request when receiving a file_pointer' do WebMock.reset! stub_request(:post, "http://www.example.com/") .with(headers: { 'Accept-Encoding' => 'gzip,deflate', 'Content-Type' => /\Amultipart\/form-data; boundary=/, 'User-Agent' => 'Huginn - https://github.com/huginn/huginn' }) { |request| qboundary = Regexp.quote(request.headers['Content-Type'][/ boundary=(.+)/, 1]) /\A--#{qboundary}\r\nContent-Disposition: form-data; name="default"\r\n\r\nvalue\r\n--#{qboundary}\r\nContent-Disposition: form-data; name="file"; filename="local.path"\r\nContent-Length: 8\r\nContent-Type: \r\nContent-Transfer-Encoding: binary\r\n\r\ntestdata\r\n--#{qboundary}--\r\n\z/ === request.body }.to_return(status: 200, body: "", headers: {}) event = Event.new(payload: { file_pointer: { agent_id: 111, file: 'test' } }) io_mock = double expect(@checker).to receive(:get_io).with(event) { StringIO.new("testdata") } @checker.options['no_merge'] = true @checker.receive([event]) end end describe "#check" do it "sends options['payload'] as a POST request" do expect { @checker.check }.to change { @sent_requests[:post].length }.by(1) expect(@sent_requests[:post][0].data).to eq(@checker.options['payload'].to_query) end it "sends options['payload'] as JSON as a POST request" do @checker.options['content_type'] = 'json' expect { @checker.check }.to change { @sent_requests[:post].length }.by(1) expect(@sent_requests[:post][0].data).to eq(@checker.options['payload']) end it "sends options['payload'] as XML as a POST request" do @checker.options['content_type'] = 'xml' expect { @checker.check }.to change { @sent_requests[:post].length }.by(1) expect(@sent_requests[:post][0].data.keys).to eq(['post']) expect(@sent_requests[:post][0].data['post']).to eq(@checker.options['payload']) end it "sends options['payload'] as XML with custom root element name, as a POST request" do @checker.options['content_type'] = 'xml' @checker.options['xml_root'] = 'foobar' expect { @checker.check }.to change { @sent_requests[:post].length }.by(1) expect(@sent_requests[:post][0].data.keys).to eq(['foobar']) expect(@sent_requests[:post][0].data['foobar']).to eq(@checker.options['payload']) end it "sends options['payload'] as a GET request" do @checker.options['method'] = 'get' expect { expect { @checker.check }.to change { @sent_requests[:get].length }.by(1) }.not_to(change { @sent_requests[:post].length }) expect(@sent_requests[:get][0].data).to eq(@checker.options['payload'].to_query) end it "sends options['payload'] as a string POST request when content-type continas a MIME type" do @checker.options['payload'] = '<test>hello</test>' @checker.options['content_type'] = 'application/xml' expect { @checker.check }.to change { @sent_requests[:post].length }.by(1) expect(@sent_requests[:post][0].data).to eq('<test>hello</test>') end it "interpolates outgoing headers" do @checker.options['headers'] = { "Foo" => "{% credential aws_key %}" } @checker.check headers = @sent_requests[:post].first.headers expect(headers["Foo"]).to eq("2222222222-jane") end describe "emitting events" do context "when emit_events is not set to true" do it "does not emit events" do expect { @checker.check }.not_to(change { @checker.events.count }) end end context "when emit_events is set to true" do before do @checker.options['emit_events'] = 'true' @checker.save! end it "emits the response status" do expect { @checker.check }.to change { @checker.events.count }.by(1) expect(@checker.events.last.payload['status']).to eq 200 end it "emits the body" do @checker.check expect(@checker.events.last.payload['body']).to eq '<html>a webpage!</html>' end context "and the response is in JSON" do let(:json_data) { { "foo" => 123, "bar" => 456 } } let(:mocked_response) do { status: 200, body: json_data.to_json, headers: { 'Content-type' => 'application/json', 'X-Foo-Bar' => 'baz', } } end it "emits the unparsed JSON body" do @checker.check expect(@checker.events.last.payload['body']).to eq json_data.to_json end it "emits the parsed JSON body when parse_body is true" do @checker.options['parse_body'] = 'true' @checker.save! @checker.check expect(@checker.events.last.payload['body']).to eq json_data end end it "emits the response headers capitalized by default" do @checker.check expect(@checker.events.last.payload['headers']).to eq({ 'Content-Type' => 'text/html', 'X-Foo-Bar' => 'baz' }) end it "emits the response headers capitalized" do @checker.options['event_headers_style'] = 'capitalized' @checker.check expect(@checker.events.last.payload['headers']).to eq({ 'Content-Type' => 'text/html', 'X-Foo-Bar' => 'baz' }) end it "emits the response headers downcased" do @checker.options['event_headers_style'] = 'downcased' @checker.check expect(@checker.events.last.payload['headers']).to eq({ 'content-type' => 'text/html', 'x-foo-bar' => 'baz' }) end it "emits the response headers snakecased" do @checker.options['event_headers_style'] = 'snakecased' @checker.check expect(@checker.events.last.payload['headers']).to eq({ 'content_type' => 'text/html', 'x_foo_bar' => 'baz' }) end it "emits the response headers only including those specified by event_headers" do @checker.options['event_headers_style'] = 'snakecased' @checker.options['event_headers'] = 'content-type' @checker.check expect(@checker.events.last.payload['headers']).to eq({ 'content_type' => 'text/html' }) end context "when output_mode is set to 'merge'" do before do @checker.options['output_mode'] = 'merge' @checker.save! end it "emits the received event" do @checker.receive([@event]) @checker.check expect(@checker.events.last.payload['somekey']).to eq('somevalue') expect(@checker.events.last.payload['someotherkey']).to eq({ 'somekey' => 'value' }) end end end end end describe "#working?" do it "checks if there was an error" do @checker.error("error") expect(@checker.logs.count).to eq(1) expect(@checker.reload).not_to be_working end it "checks if 'expected_receive_period_in_days' was not set" do expect(@checker.logs.count).to eq(0) @checker.options.delete('expected_receive_period_in_days') expect(@checker).to be_working end it "checks if no event has been received" do expect(@checker.logs.count).to eq(0) expect(@checker.last_receive_at).to be_nil expect(@checker.reload).not_to be_working end it "checks if events have been received within expected receive period" do expect(@checker).not_to be_working Agents::PostAgent.async_receive @checker.id, [@event.id] expect(@checker.reload).to be_working two_days_from_now = 2.days.from_now allow(Time).to receive(:now) { two_days_from_now } expect(@checker.reload).not_to be_working end end describe "validation" do before do expect(@checker).to be_valid end it "should validate presence of post_url" do @checker.options['post_url'] = "" expect(@checker).not_to be_valid end it "should validate absence of expected_receive_period_in_days is allowed" do @checker.options['expected_receive_period_in_days'] = "" expect(@checker).to be_valid end it "should validate method as post, get, put, patch, or delete, defaulting to post" do @checker.options['method'] = "" expect(@checker.method).to eq("post") expect(@checker).to be_valid @checker.options['method'] = "POST" expect(@checker.method).to eq("post") expect(@checker).to be_valid @checker.options['method'] = "get" expect(@checker.method).to eq("get") expect(@checker).to be_valid @checker.options['method'] = "patch" expect(@checker.method).to eq("patch") expect(@checker).to be_valid @checker.options['method'] = "wut" expect(@checker.method).to eq("wut") expect(@checker).not_to be_valid end it "should validate that no_merge is 'true' or 'false', if present" do @checker.options['no_merge'] = "" expect(@checker).to be_valid @checker.options['no_merge'] = "true" expect(@checker).to be_valid @checker.options['no_merge'] = "false" expect(@checker).to be_valid @checker.options['no_merge'] = false expect(@checker).to be_valid @checker.options['no_merge'] = true expect(@checker).to be_valid @checker.options['no_merge'] = 'blarg' expect(@checker).not_to be_valid end it "should validate payload as a hash, if present" do @checker.options['payload'] = "" expect(@checker).to be_valid @checker.options['payload'] = ["foo", "bar"] expect(@checker).to be_valid @checker.options['payload'] = "hello" expect(@checker).not_to be_valid @checker.options['payload'] = { 'this' => 'that' } expect(@checker).to be_valid end it "should not validate payload as a hash or an array if content_type includes a MIME type and method is not get or delete" do @checker.options['no_merge'] = 'true' @checker.options['content_type'] = 'text/xml' @checker.options['payload'] = "test" expect(@checker).to be_valid @checker.options['method'] = 'get' expect(@checker).not_to be_valid @checker.options['method'] = 'delete' expect(@checker).not_to be_valid end it "requires `no_merge` to be set to true when content_type contains a MIME type" do @checker.options['content_type'] = 'text/xml' @checker.options['payload'] = "test" expect(@checker).not_to be_valid end it "requires headers to be a hash, if present" do @checker.options['headers'] = [1, 2, 3] expect(@checker).not_to be_valid @checker.options['headers'] = "hello world" expect(@checker).not_to be_valid @checker.options['headers'] = "" expect(@checker).to be_valid @checker.options['headers'] = {} expect(@checker).to be_valid @checker.options['headers'] = { "Authorization" => "foo bar" } expect(@checker).to be_valid end it "requires emit_events to be true or false" do @checker.options['emit_events'] = 'what?' expect(@checker).not_to be_valid @checker.options.delete('emit_events') expect(@checker).to be_valid @checker.options['emit_events'] = 'true' expect(@checker).to be_valid @checker.options['emit_events'] = 'false' expect(@checker).to be_valid @checker.options['emit_events'] = true expect(@checker).to be_valid end it "requires output_mode to be 'clean' or 'merge', if present" do @checker.options['output_mode'] = 'what?' expect(@checker).not_to be_valid @checker.options.delete('output_mode') expect(@checker).to be_valid @checker.options['output_mode'] = 'clean' expect(@checker).to be_valid @checker.options['output_mode'] = 'merge' expect(@checker).to be_valid @checker.options['output_mode'] = :clean expect(@checker).to be_valid @checker.options['output_mode'] = :merge expect(@checker).to be_valid @checker.options['output_mode'] = '{{somekey}}' expect(@checker).to be_valid @checker.options['output_mode'] = "{% if key == 'foo' %}merge{% else %}clean{% endif %}" expect(@checker).to be_valid end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/email_agent_spec.rb
spec/models/agents/email_agent_spec.rb
require 'rails_helper' describe Agents::EmailAgent do it_behaves_like EmailConcern def get_message_part(mail, content_type) mail.body.parts.find { |p| p.content_type.match content_type }.body.raw_source end before do @checker = Agents::EmailAgent.new(:name => "something", :options => { :expected_receive_period_in_days => "2", :subject => "something interesting" }) @checker.user = users(:bob) @checker.save! expect(ActionMailer::Base.deliveries).to eq([]) end after do ActionMailer::Base.deliveries = [] end describe "#receive" do it "immediately sends any payloads it receives" do event1 = Event.new event1.agent = agents(:bob_rain_notifier_agent) event1.payload = { :message => "hi!", :data => "Something you should know about" } event1.save! event2 = Event.new event2.agent = agents(:bob_weather_agent) event2.payload = { :data => "Something else you should know about" } event2.save! Agents::EmailAgent.async_receive(@checker.id, [event1.id]) Agents::EmailAgent.async_receive(@checker.id, [event2.id]) expect(ActionMailer::Base.deliveries.count).to eq(2) expect(ActionMailer::Base.deliveries.last.to).to eq(["bob@example.com"]) expect(ActionMailer::Base.deliveries.last.subject).to eq("something interesting") expect(get_message_part(ActionMailer::Base.deliveries.last, /plain/).strip).to eq("Event\n data: Something else you should know about") expect(get_message_part(ActionMailer::Base.deliveries.first, /plain/).strip).to eq("hi!\n data: Something you should know about") end it "logs and re-raises any mailer errors" do event1 = Event.new event1.agent = agents(:bob_rain_notifier_agent) event1.payload = { :message => "hi!", :data => "Something you should know about" } event1.save! expect(SystemMailer).to receive(:send_message).with(anything) { raise Net::SMTPAuthenticationError.new("Wrong password") } expect { Agents::EmailAgent.async_receive(@checker.id, [event1.id]) }.to raise_error(/Wrong password/) expect(@checker.logs.last.message).to match(/Error sending mail .* Wrong password/) end it "can receive complex events and send them on" do stub_request(:any, /pirateweather/).to_return(:body => File.read(Rails.root.join("spec/data_fixtures/weather.json")), :status => 200) @checker.sources << agents(:bob_weather_agent) Agent.async_check(agents(:bob_weather_agent).id) Agent.receive! plain_email_text = get_message_part(ActionMailer::Base.deliveries.last, /plain/).strip html_email_text = get_message_part(ActionMailer::Base.deliveries.last, /html/).strip expect(plain_email_text).to match(/avehumidity/) expect(html_email_text).to match(/avehumidity/) end it "can take body option for selecting the resulting email's body" do @checker.update :options => @checker.options.merge({ 'subject' => '{{foo.subject}}', 'body' => '{{some_html}}' }) event = Event.new event.agent = agents(:bob_rain_notifier_agent) event.payload = { :foo => { :subject => "Something you should know about" }, :some_html => "<script>console.log('hello, world.')</script><strong>rain!</strong>" } event.save! Agents::EmailAgent.async_receive(@checker.id, [event.id]) expect(ActionMailer::Base.deliveries.count).to eq(1) expect(ActionMailer::Base.deliveries.last.to).to eq(["bob@example.com"]) expect(ActionMailer::Base.deliveries.last.subject).to eq("Something you should know about") expect(get_message_part(ActionMailer::Base.deliveries.last, /plain/).strip).to match(/\A\s*#{Regexp.escape("<script>console.log('hello, world.')</script><strong>rain!</strong>")}\s*\z/) expect(get_message_part(ActionMailer::Base.deliveries.last, /html/).strip).to match(/<body>\s*#{Regexp.escape("console.log('hello, world.')<strong>rain!</strong>")}\s*<\/body>/) end it "can take content type option to set content type of email sent" do @checker.update :options => @checker.options.merge({ 'content_type' => 'text/plain' }) event2 = Event.new event2.agent = agents(:bob_rain_notifier_agent) event2.payload = { :foo => { :subject => "Something you should know about" }, :some_html => "<strong>rain!</strong>" } event2.save! Agents::EmailAgent.async_receive(@checker.id, [event2.id]) expect(ActionMailer::Base.deliveries.last.content_type).to eq("text/plain; charset=UTF-8") end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/phantom_js_cloud_agent_spec.rb
spec/models/agents/phantom_js_cloud_agent_spec.rb
require 'rails_helper' describe Agents::PhantomJsCloudAgent do before do @valid_options = { 'name' => "XKCD", 'render_type' => "html", 'url' => "http://xkcd.com", 'mode' => 'clean', 'api_key' => '1234567890' } @checker = Agents::PhantomJsCloudAgent.new(:name => "xkcd", :options => @valid_options, :keep_events_for => 2.days) @checker.user = users(:jane) @checker.save! end describe "validations" do before do expect(@checker).to be_valid end it "should validate the presence of url" do @checker.options['url'] = "http://google.com" expect(@checker).to be_valid @checker.options['url'] = "" expect(@checker).not_to be_valid @checker.options['url'] = nil expect(@checker).not_to be_valid end end describe "emitting event" do it "should emit url as event" do expect { @checker.check }.to change { @checker.events.count }.by(1) item,* = @checker.events.last(1) expect(item.payload['url']).to eq("https://phantomjscloud.com/api/browser/v2/1234567890/?request=%7B%22url%22%3A%22http%3A%2F%2Fxkcd.com%22%2C%22renderType%22%3A%22html%22%2C%22requestSettings%22%3A%7B%22userAgent%22%3A%22Huginn%20-%20https%3A%2F%2Fgithub.com%2Fhuginn%2Fhuginn%22%7D%7D") end it "should set render type as plain text" do @checker.options['render_type'] = 'plainText' expect { @checker.check }.to change { @checker.events.count }.by(1) item,* = @checker.events.last(1) expect(item.payload['url']).to eq("https://phantomjscloud.com/api/browser/v2/1234567890/?request=%7B%22url%22%3A%22http%3A%2F%2Fxkcd.com%22%2C%22renderType%22%3A%22plainText%22%2C%22requestSettings%22%3A%7B%22userAgent%22%3A%22Huginn%20-%20https%3A%2F%2Fgithub.com%2Fhuginn%2Fhuginn%22%7D%7D") end it "should set render type as jpg" do @checker.options['render_type'] = 'jpg' expect { @checker.check }.to change { @checker.events.count }.by(1) item,* = @checker.events.last(1) expect(item.payload['url']).to eq("https://phantomjscloud.com/api/browser/v2/1234567890/?request=%7B%22url%22%3A%22http%3A%2F%2Fxkcd.com%22%2C%22renderType%22%3A%22jpg%22%2C%22requestSettings%22%3A%7B%22userAgent%22%3A%22Huginn%20-%20https%3A%2F%2Fgithub.com%2Fhuginn%2Fhuginn%22%7D%7D") end it "should set output as json" do @checker.options['output_as_json'] = true expect { @checker.check }.to change { @checker.events.count }.by(1) item,* = @checker.events.last(1) expect(item.payload['url']).to eq("https://phantomjscloud.com/api/browser/v2/1234567890/?request=%7B%22url%22%3A%22http%3A%2F%2Fxkcd.com%22%2C%22renderType%22%3A%22html%22%2C%22outputAsJson%22%3Atrue%2C%22requestSettings%22%3A%7B%22userAgent%22%3A%22Huginn%20-%20https%3A%2F%2Fgithub.com%2Fhuginn%2Fhuginn%22%7D%7D") end it "should not set ignore images" do @checker.options['ignore_images'] = false expect { @checker.check }.to change { @checker.events.count }.by(1) item,* = @checker.events.last(1) expect(item.payload['url']).to eq("https://phantomjscloud.com/api/browser/v2/1234567890/?request=%7B%22url%22%3A%22http%3A%2F%2Fxkcd.com%22%2C%22renderType%22%3A%22html%22%2C%22requestSettings%22%3A%7B%22userAgent%22%3A%22Huginn%20-%20https%3A%2F%2Fgithub.com%2Fhuginn%2Fhuginn%22%7D%7D") end it "should set ignore images" do @checker.options['ignore_images'] = true expect { @checker.check }.to change { @checker.events.count }.by(1) item,* = @checker.events.last(1) expect(item.payload['url']).to eq("https://phantomjscloud.com/api/browser/v2/1234567890/?request=%7B%22url%22%3A%22http%3A%2F%2Fxkcd.com%22%2C%22renderType%22%3A%22html%22%2C%22requestSettings%22%3A%7B%22ignoreImages%22%3Atrue%2C%22userAgent%22%3A%22Huginn%20-%20https%3A%2F%2Fgithub.com%2Fhuginn%2Fhuginn%22%7D%7D") end it "should set wait interval to zero" do @checker.options['wait_interval'] = '0' expect { @checker.check }.to change { @checker.events.count }.by(1) item,* = @checker.events.last(1) expect(item.payload['url']).to eq("https://phantomjscloud.com/api/browser/v2/1234567890/?request=%7B%22url%22%3A%22http%3A%2F%2Fxkcd.com%22%2C%22renderType%22%3A%22html%22%2C%22requestSettings%22%3A%7B%22userAgent%22%3A%22Huginn%20-%20https%3A%2F%2Fgithub.com%2Fhuginn%2Fhuginn%22%2C%22wait_interval%22%3A%220%22%7D%7D") end it "should set user agent to BlackBerry" do @checker.options['user_agent'] = 'Mozilla/5.0 (BlackBerry; U; BlackBerry 9900; en) AppleWebKit/534.11+ (KHTML, like Gecko) Version/7.1.0.346 Mobile Safari/534.11+' expect { @checker.check }.to change { @checker.events.count }.by(1) item,* = @checker.events.last(1) expect(item.payload['url']).to eq("https://phantomjscloud.com/api/browser/v2/1234567890/?request=%7B%22url%22%3A%22http%3A%2F%2Fxkcd.com%22%2C%22renderType%22%3A%22html%22%2C%22requestSettings%22%3A%7B%22userAgent%22%3A%22Mozilla%2F5.0%20%28BlackBerry%3B%20U%3B%20BlackBerry%209900%3B%20en%29%20AppleWebKit%2F534.11%2B%20%28KHTML%2C%20like%20Gecko%29%20Version%2F7.1.0.346%20Mobile%20Safari%2F534.11%2B%22%7D%7D") end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/hipchat_agent_spec.rb
spec/models/agents/hipchat_agent_spec.rb
require 'rails_helper' describe Agents::HipchatAgent do before(:each) do @valid_params = { 'auth_token' => 'token', 'room_name' => 'test', 'username' => "{{username}}", 'message' => "{{message}}", 'notify' => 'false', 'color' => 'yellow', } @checker = Agents::HipchatAgent.new(name: "somename", options: @valid_params) @checker.user = users(:jane) @checker.save! @event = Event.new @event.agent = agents(:bob_weather_agent) @event.payload = { room_name: 'test room', message: 'Looks like its going to rain', username: "Huggin user " } @event.save! end describe "validating" do before do expect(@checker).to be_valid end it "should require the basecamp username" do @checker.options['auth_token'] = nil expect(@checker).not_to be_valid end it "should require the basecamp password" do @checker.options['room_name'] = nil expect(@checker).not_to be_valid end it "should require the basecamp user_id" do @checker.options['room_name'] = nil @checker.options['room_name_path'] = 'jsonpath' expect(@checker).to be_valid end it "should also allow a credential" do @checker.options['auth_token'] = nil expect(@checker).not_to be_valid @checker.user.user_credentials.create credential_name: 'hipchat_auth_token', credential_value: 'something' expect(@checker.reload).to be_valid end end describe "#validate_auth_token" do it "should return true when valid" do allow_any_instance_of(HipChat::Client).to receive(:rooms) { true } expect(@checker.validate_auth_token).to be true end it "should return false when invalid" do allow_any_instance_of(HipChat::Client).to receive(:rooms).and_raise(HipChat::UnknownResponseCode, '403') expect(@checker.validate_auth_token).to be false end end describe "#complete_room_name" do it "should return a array of hashes" do allow_any_instance_of(HipChat::Client).to receive(:rooms) { [OpenStruct.new(name: 'test'), OpenStruct.new(name: 'test1')] } expect(@checker.complete_room_name).to eq [{ text: 'test', id: 'test' }, { text: 'test1', id: 'test1' }] end end describe "#receive" do it "send a message to the hipchat" do expect_any_instance_of(HipChat::Room).to receive(:send).with(@event.payload[:username][0..14], @event.payload[:message], { notify: false, color: 'yellow', message_format: 'html' }) @checker.receive([@event]) end end describe "#working?" do it "should not be working until the first event was received" do expect(@checker).not_to be_working @checker.last_receive_at = Time.now expect(@checker).to be_working end it "should not be working when the last error occured after the last received event" do @checker.last_receive_at = Time.now - 1.minute @checker.last_error_log_at = Time.now expect(@checker).not_to be_working end it "should be working when the last received event occured after the last error" do @checker.last_receive_at = Time.now @checker.last_error_log_at = Time.now - 1.minute expect(@checker).to be_working end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/adioso_agent_spec.rb
spec/models/agents/adioso_agent_spec.rb
require 'rails_helper' describe Agents::AdiosoAgent do before do stub_request(:get, /parse/).to_return(:body => File.read(Rails.root.join("spec/data_fixtures/adioso_parse.json")), :status => 200, :headers => {"Content-Type" => "text/json"}) stub_request(:get, /fares/).to_return(:body => File.read(Rails.root.join("spec/data_fixtures/adioso_fare.json")), :status => 200, :headers => {"Content-Type" => "text/json"}) @valid_params = { :start_date => "June 25 2013", :end_date => "July 15 2013", :from => "Portland", :to => "Chicago", :username => "xx", :password => "xx", :expected_update_period_in_days => "2" } @checker = Agents::AdiosoAgent.new(:name => "somename", :options => @valid_params) @checker.user = users(:jane) @checker.save! end describe "#check" do it "should check that initial run creates an event" do expect { @checker.check }.to change { Event.count }.by(1) end end describe "#working?" do it "checks if its generating events as scheduled" do expect(@checker).not_to be_working @checker.check expect(@checker.reload).to be_working three_days_from_now = 3.days.from_now allow(Time).to receive(:now) { three_days_from_now } expect(@checker).not_to be_working end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/slack_agent_spec.rb
spec/models/agents/slack_agent_spec.rb
require 'rails_helper' describe Agents::SlackAgent do before(:each) do @fallback = "Its going to rain" @attachments = [{'fallback' => "{{fallback}}"}] @valid_params = { 'webhook_url' => 'https://hooks.slack.com/services/random1/random2/token', 'channel' => '#random', 'username' => "{{username}}", 'message' => "{{message}}", 'attachments' => @attachments } @checker = Agents::SlackAgent.new(:name => "slacker", :options => @valid_params) @checker.user = users(:jane) @checker.save! @event = Event.new @event.agent = agents(:bob_weather_agent) @event.payload = { :channel => '#random', :message => 'Looks like its going to rain', username: "Huggin user", fallback: @fallback} @event.save! end describe "validating" do before do expect(@checker).to be_valid end it "should require a webhook_url" do @checker.options['webhook_url'] = nil expect(@checker).not_to be_valid end it "should require a channel" do @checker.options['channel'] = nil expect(@checker).not_to be_valid end it "should allow an icon" do @checker.options['icon_emoji'] = nil expect(@checker).to be_valid @checker.options['icon_emoji'] = ":something:" expect(@checker).to be_valid @checker.options['icon_url'] = "http://something.com/image.png" expect(@checker).to be_valid @checker.options['icon_emoji'] = "something" expect(@checker).to be_valid end it "should allow attachments" do @checker.options['attachments'] = nil expect(@checker).to be_valid @checker.options['attachments'] = [] expect(@checker).to be_valid @checker.options['attachments'] = @attachments expect(@checker).to be_valid end end describe "#receive" do it "receive an event without errors" do expect_any_instance_of(Slack::Notifier).to receive(:ping).with(@event.payload[:message], attachments: [{'fallback' => @fallback}], channel: @event.payload[:channel], username: @event.payload[:username] ) expect { @checker.receive([@event]) }.not_to raise_error end end describe "#working?" do it "should call received_event_without_error?" do expect(@checker).to receive(:received_event_without_error?) @checker.working? end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/mqtt_agent_spec.rb
spec/models/agents/mqtt_agent_spec.rb
require 'rails_helper' require 'mqtt' require './spec/support/fake_mqtt_server' describe Agents::MqttAgent do before :each do @error_log = StringIO.new @server = MQTT::FakeServer.new('127.0.0.1') @server.logger = Logger.new(@error_log) @server.logger.level = Logger::DEBUG @server.start @valid_params = { 'uri' => "mqtt://#{@server.address}:#{@server.port}", 'topic' => '/#', 'max_read_time' => '0.1', 'expected_update_period_in_days' => "2" } @checker = Agents::MqttAgent.new( :name => "somename", :options => @valid_params, :schedule => "midnight", ) @checker.user = users(:jane) @checker.save! end after :each do @server.stop end describe "#check" do it "should create events in the initial run" do expect { @checker.check }.to change { Event.count }.by(2) end it "should ignore retained messages that are previously received" do expect { @checker.check }.to change { Event.count }.by(2) expect { @checker.check }.to change { Event.count }.by(1) expect { @checker.check }.to change { Event.count }.by(1) expect { @checker.check }.to change { Event.count }.by(2) end end describe "#working?" do it "checks if its generating events as scheduled" do expect(@checker).not_to be_working @checker.check expect(@checker.reload).to be_working three_days_from_now = 3.days.from_now allow(Time).to receive(:now) { three_days_from_now } expect(@checker).not_to be_working end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/trigger_agent_spec.rb
spec/models/agents/trigger_agent_spec.rb
require 'rails_helper' describe Agents::TriggerAgent do before do @valid_params = { 'name' => "my trigger agent", 'options' => { 'expected_receive_period_in_days' => 2, 'rules' => [{ 'type' => "regex", 'value' => "a\\db", 'path' => "foo.bar.baz", }], 'message' => "I saw '{{foo.bar.baz}}' from {{name}}" } } @checker = Agents::TriggerAgent.new(@valid_params) @checker.user = users(:bob) @checker.save! @event = Event.new @event.agent = agents(:bob_rain_notifier_agent) @event.payload = { 'foo' => { "bar" => { 'baz' => "a2b" } }, 'name' => "Joe" } end describe "validation" do before do expect(@checker).to be_valid end it "should validate presence of message" do @checker.options['message'] = nil expect(@checker).not_to be_valid @checker.options['message'] = '' expect(@checker).not_to be_valid end it "should be valid without a message when 'keep_event' is set" do @checker.options['keep_event'] = 'true' @checker.options['message'] = '' expect(@checker).to be_valid end it "if present, 'keep_event' must equal true or false" do @checker.options['keep_event'] = 'true' expect(@checker).to be_valid @checker.options['keep_event'] = 'false' expect(@checker).to be_valid @checker.options['keep_event'] = '' expect(@checker).to be_valid @checker.options['keep_event'] = 'tralse' expect(@checker).not_to be_valid end it "validates that 'must_match' is a positive integer, not greater than the number of rules, if provided" do @checker.options['must_match'] = '1' expect(@checker).to be_valid @checker.options['must_match'] = '0' expect(@checker).not_to be_valid @checker.options['must_match'] = 'wrong' expect(@checker).not_to be_valid @checker.options['must_match'] = '' expect(@checker).to be_valid @checker.options.delete('must_match') expect(@checker).to be_valid @checker.options['must_match'] = '2' expect(@checker).not_to be_valid expect(@checker.errors[:base].first).to match(/equal to or less than the number of rules/) end it "should validate the three fields in each rule" do @checker.options['rules'] << { 'path' => "foo", 'type' => "fake", 'value' => "6" } expect(@checker).not_to be_valid @checker.options['rules'].last['type'] = "field!=value" expect(@checker).to be_valid @checker.options['rules'].last.delete('value') expect(@checker).not_to be_valid @checker.options['rules'].last['value'] = '' expect(@checker).to be_valid @checker.options['rules'].last['value'] = nil expect(@checker).to be_valid @checker.options['rules'].last.delete('value') expect(@checker).not_to be_valid @checker.options['rules'].last['value'] = ['a'] expect(@checker).to be_valid @checker.options['rules'].last['path'] = '' expect(@checker).not_to be_valid end it "should validate non-hash rules" do @checker.options['rules'] << "{% if status == 'ok' %}true{% endif %}" expect(@checker).to be_valid @checker.options['rules'] << [] expect(@checker).not_to be_valid end end describe "#working?" do it "checks to see if the Agent has received any events in the last 'expected_receive_period_in_days' days" do @event.save! expect(@checker).not_to be_working # no events have ever been received Agents::TriggerAgent.async_receive(@checker.id, [@event.id]) expect(@checker.reload).to be_working # Events received three_days_from_now = 3.days.from_now allow(Time).to receive(:now) { three_days_from_now } expect(@checker.reload).not_to be_working # too much time has passed end end describe "#receive" do it "handles regex" do @event.payload['foo']['bar']['baz'] = "a222b" expect { @checker.receive([@event]) }.not_to(change { Event.count }) @event.payload['foo']['bar']['baz'] = "a2b" expect { @checker.receive([@event]) }.to change { Event.count }.by(1) end it "handles array of regex" do @event.payload['foo']['bar']['baz'] = "a222b" @checker.options['rules'][0] = { 'type' => "regex", 'value' => ["a\\db", "a\\Wb"], 'path' => "foo.bar.baz", } expect { @checker.receive([@event]) }.not_to(change { Event.count }) @event.payload['foo']['bar']['baz'] = "a2b" expect { @checker.receive([@event]) }.to change { Event.count }.by(1) @event.payload['foo']['bar']['baz'] = "a b" expect { @checker.receive([@event]) }.to change { Event.count }.by(1) end it "handles negated regex" do @event.payload['foo']['bar']['baz'] = "a2b" @checker.options['rules'][0] = { 'type' => "!regex", 'value' => "a\\db", 'path' => "foo.bar.baz", } expect { @checker.receive([@event]) }.not_to(change { Event.count }) @event.payload['foo']['bar']['baz'] = "a22b" expect { @checker.receive([@event]) }.to change { Event.count }.by(1) end it "handles array of negated regex" do @event.payload['foo']['bar']['baz'] = "a2b" @checker.options['rules'][0] = { 'type' => "!regex", 'value' => ["a\\db", "a2b"], 'path' => "foo.bar.baz", } expect { @checker.receive([@event]) }.not_to(change { Event.count }) @event.payload['foo']['bar']['baz'] = "a3b" expect { @checker.receive([@event]) }.to change { Event.count }.by(1) end it "puts can extract values into the message based on paths" do @checker.receive([@event]) expect(Event.last.payload['message']).to eq("I saw 'a2b' from Joe") end it "handles numerical comparisons" do @event.payload['foo']['bar']['baz'] = "5" @checker.options['rules'].first['value'] = 6 @checker.options['rules'].first['type'] = "field<value" expect { @checker.receive([@event]) }.to change { Event.count }.by(1) @checker.options['rules'].first['value'] = 3 expect { @checker.receive([@event]) }.not_to(change { Event.count }) end it "handles array of numerical comparisons" do @event.payload['foo']['bar']['baz'] = "5" @checker.options['rules'].first['value'] = [6, 3] @checker.options['rules'].first['type'] = "field<value" expect { @checker.receive([@event]) }.to change { Event.count }.by(1) @checker.options['rules'].first['value'] = [4, 3] expect { @checker.receive([@event]) }.not_to(change { Event.count }) end it "handles exact comparisons" do @event.payload['foo']['bar']['baz'] = "hello world" @checker.options['rules'].first['type'] = "field==value" @checker.options['rules'].first['value'] = "hello there" expect { @checker.receive([@event]) }.not_to(change { Event.count }) @checker.options['rules'].first['value'] = "hello world" expect { @checker.receive([@event]) }.to change { Event.count }.by(1) end it "handles array of exact comparisons" do @event.payload['foo']['bar']['baz'] = "hello world" @checker.options['rules'].first['type'] = "field==value" @checker.options['rules'].first['value'] = ["hello there", "hello universe"] expect { @checker.receive([@event]) }.not_to(change { Event.count }) @checker.options['rules'].first['value'] = ["hello world", "hello universe"] expect { @checker.receive([@event]) }.to change { Event.count }.by(1) end it "handles negated comparisons" do @event.payload['foo']['bar']['baz'] = "hello world" @checker.options['rules'].first['type'] = "field!=value" @checker.options['rules'].first['value'] = "hello world" expect { @checker.receive([@event]) }.not_to(change { Event.count }) @checker.options['rules'].first['value'] = "hello there" expect { @checker.receive([@event]) }.to change { Event.count }.by(1) end it "handles array of negated comparisons" do @event.payload['foo']['bar']['baz'] = "hello world" @checker.options['rules'].first['type'] = "field!=value" @checker.options['rules'].first['value'] = ["hello world", "hello world"] expect { @checker.receive([@event]) }.not_to(change { Event.count }) @checker.options['rules'].first['value'] = ["hello there", "hello world"] expect { @checker.receive([@event]) }.to change { Event.count }.by(1) end it "handles array of `not in` comparisons" do @event.payload['foo']['bar']['baz'] = "hello world" @checker.options['rules'].first['type'] = "not in" @checker.options['rules'].first['value'] = ["hello world", "hello world"] expect { @checker.receive([@event]) }.not_to(change { Event.count }) @checker.options['rules'].first['value'] = ["hello there", "hello world"] expect { @checker.receive([@event]) }.not_to(change { Event.count }) @checker.options['rules'].first['value'] = ["hello there", "hello here"] expect { @checker.receive([@event]) }.to change { Event.count }.by(1) end it "does fine without dots in the path" do @event.payload = { 'hello' => "world" } @checker.options['rules'].first['type'] = "field==value" @checker.options['rules'].first['path'] = "hello" @checker.options['rules'].first['value'] = "world" expect { @checker.receive([@event]) }.to change { Event.count }.by(1) @checker.options['rules'].first['path'] = "foo" expect { @checker.receive([@event]) }.not_to(change { Event.count }) @checker.options['rules'].first['value'] = "hi" expect { @checker.receive([@event]) }.not_to(change { Event.count }) end it "handles multiple events" do event2 = Event.new event2.agent = agents(:bob_weather_agent) event2.payload = { 'foo' => { 'bar' => { 'baz' => "a2b" } } } event3 = Event.new event3.agent = agents(:bob_weather_agent) event3.payload = { 'foo' => { 'bar' => { 'baz' => "a222b" } } } expect { @checker.receive([@event, event2, event3]) }.to change { Event.count }.by(2) end it "handles Liquid rules" do event1 = Event.create!( agent: agents(:bob_rain_notifier_agent), payload: { 'hello' => 'world1', 'created_at' => '2019-03-27T08:54:12+09:00' } ) event2 = Event.create!( agent: agents(:bob_rain_notifier_agent), payload: { 'hello' => 'world2', 'created_at' => '2019-03-27T09:17:01+09:00' } ) @checker.options['message'] = '{{hello}}' @checker.options['rules'] = [ "{% assign value = created_at | date: '%s' | plus: 0 %}{% assign threshold = 'now' | date: '%s' | minus: 86400 %}{% if value > threshold %}true{% endif %}" ] expect { travel_to(Time.parse('2019-03-28T00:00:00+00:00')) { @checker.receive([event1, event2]) } }.to change { Event.count }.by(1) expect(Event.last.payload['message']).to eq("world2") end describe "with multiple rules" do before do @checker.options['rules'] << { 'type' => "field>=value", 'value' => "4", 'path' => "foo.bing" } end it "handles ANDing rules together" do @event.payload['foo']["bing"] = "5" expect { @checker.receive([@event]) }.to change { Event.count }.by(1) @event.payload['foo']["bing"] = "2" expect { @checker.receive([@event]) }.not_to(change { Event.count }) end it "can accept a partial rule set match when 'must_match' is present and less than the total number of rules" do @checker.options['must_match'] = "1" @event.payload['foo']["bing"] = "5" # 5 > 4 expect { @checker.receive([@event]) }.to change { Event.count }.by(1) @event.payload['foo']["bing"] = "2" # 2 !> 4 expect { @checker.receive([@event]) }.to(change { Event.count }) # but the first one matches @checker.options['must_match'] = "2" @event.payload['foo']["bing"] = "5" # 5 > 4 expect { @checker.receive([@event]) }.to change { Event.count }.by(1) @event.payload['foo']["bing"] = "2" # 2 !> 4 expect { @checker.receive([@event]) }.not_to(change { Event.count }) # only 1 matches, we needed 2 end end describe "when 'keep_event' is true" do before do @checker.options['keep_event'] = 'true' @event.payload['foo']['bar']['baz'] = "5" @checker.options['rules'].first['type'] = "field<value" end it "can re-emit the origin event" do @checker.options['rules'].first['value'] = 3 @checker.options['message'] = '' @event.payload['message'] = 'hi there' expect { @checker.receive([@event]) }.not_to(change { Event.count }) @checker.options['rules'].first['value'] = 6 expect { @checker.receive([@event]) }.to change { Event.count }.by(1) expect(@checker.most_recent_event.payload).to eq(@event.payload) end it "merges 'message' into the original event when present" do @checker.options['rules'].first['value'] = 6 @checker.receive([@event]) expect(@checker.most_recent_event.payload).to eq(@event.payload.merge(message: "I saw '5' from Joe")) end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/shell_command_agent_spec.rb
spec/models/agents/shell_command_agent_spec.rb
require 'rails_helper' describe Agents::ShellCommandAgent do before do @valid_path = Dir.pwd @valid_params = { path: @valid_path, command: 'pwd', expected_update_period_in_days: '1', } @valid_params2 = { path: @valid_path, command: [RbConfig.ruby, '-e', 'puts "hello, #{STDIN.eof? ? "world" : STDIN.read.strip}."; STDERR.puts "warning!"'], stdin: "{{name}}", expected_update_period_in_days: '1', } @checker = Agents::ShellCommandAgent.new(name: 'somename', options: @valid_params) @checker.user = users(:jane) @checker.save! @checker2 = Agents::ShellCommandAgent.new(name: 'somename2', options: @valid_params2) @checker2.user = users(:jane) @checker2.save! @event = Event.new @event.agent = agents(:jane_weather_agent) @event.payload = { 'name' => 'Huginn', 'cmd' => 'ls', } @event.save! allow(Agents::ShellCommandAgent).to receive(:should_run?) { true } end describe "validation" do before do expect(@checker).to be_valid expect(@checker2).to be_valid end it "should validate presence of necessary fields" do @checker.options[:command] = nil expect(@checker).not_to be_valid end it "should validate path" do @checker.options[:path] = 'notarealpath/itreallyisnt' expect(@checker).not_to be_valid end it "should validate path" do @checker.options[:path] = '/' expect(@checker).to be_valid end end describe "#working?" do it "generating events as scheduled" do allow(@checker).to receive(:run_command).with(@valid_path, 'pwd', nil) { ["fake pwd output", "", 0] } expect(@checker).not_to be_working @checker.check expect(@checker.reload).to be_working three_days_from_now = 3.days.from_now allow(Time).to receive(:now) { three_days_from_now } expect(@checker).not_to be_working end end describe "#check" do before do orig_run_command = @checker.method(:run_command) allow(@checker).to receive(:run_command).with(@valid_path, 'pwd', nil) { ["fake pwd output", "", 0] } allow(@checker).to receive(:run_command).with(@valid_path, 'empty_output', nil) { ["", "", 0] } allow(@checker).to receive(:run_command).with(@valid_path, 'failure', nil) { ["failed", "error message", 1] } allow(@checker).to receive(:run_command).with(@valid_path, 'echo $BUNDLE_GEMFILE', nil, unbundle: true) { orig_run_command.call(@valid_path, 'echo $BUNDLE_GEMFILE', nil, unbundle: true) } allow(@checker).to receive(:run_command).with(@valid_path, 'echo $BUNDLE_GEMFILE', nil) { [ENV['BUNDLE_GEMFILE'].to_s, "", 0] } allow(@checker).to receive(:run_command).with(@valid_path, 'echo $BUNDLE_GEMFILE', nil, unbundle: false) { [ENV['BUNDLE_GEMFILE'].to_s, "", 0] } end it "should create an event when checking" do expect { @checker.check }.to change { Event.count }.by(1) expect(Event.last.payload[:path]).to eq(@valid_path) expect(Event.last.payload[:command]).to eq('pwd') expect(Event.last.payload[:output]).to eq("fake pwd output") end it "should create an event when checking (unstubbed)" do expect { @checker2.check }.to change { Event.count }.by(1) expect(Event.last.payload[:path]).to eq(@valid_path) expect(Event.last.payload[:command]).to eq [ RbConfig.ruby, '-e', 'puts "hello, #{STDIN.eof? ? "world" : STDIN.read.strip}."; STDERR.puts "warning!"' ] expect(Event.last.payload[:output]).to eq('hello, world.') expect(Event.last.payload[:errors]).to eq('warning!') end describe "with suppress_on_empty_output" do it "should suppress events on empty output" do @checker.options[:suppress_on_empty_output] = true @checker.options[:command] = 'empty_output' expect { @checker.check }.not_to change { Event.count } end it "should not suppress events on non-empty output" do @checker.options[:suppress_on_empty_output] = true @checker.options[:command] = 'failure' expect { @checker.check }.to change { Event.count }.by(1) end end describe "with suppress_on_failure" do it "should suppress events on failure" do @checker.options[:suppress_on_failure] = true @checker.options[:command] = 'failure' expect { @checker.check }.not_to change { Event.count } end it "should not suppress events on success" do @checker.options[:suppress_on_failure] = true @checker.options[:command] = 'empty_output' expect { @checker.check }.to change { Event.count }.by(1) end end it "does not run when should_run? is false" do allow(Agents::ShellCommandAgent).to receive(:should_run?) { false } expect { @checker.check }.not_to change { Event.count } end describe "with unbundle" do before do @checker.options[:command] = 'echo $BUNDLE_GEMFILE' end context "unspecified" do it "should be run inside of our bundler context" do expect { @checker.check }.to change { Event.count }.by(1) expect(Event.last.payload[:output].strip).to eq(ENV['BUNDLE_GEMFILE']) end end context "explicitly set to false" do before do @checker.options[:unbundle] = false end it "should be run inside of our bundler context" do expect { @checker.check }.to change { Event.count }.by(1) expect(Event.last.payload[:output].strip).to eq(ENV['BUNDLE_GEMFILE']) end end context "set to true" do before do @checker.options[:unbundle] = true end it "should be run outside of our bundler context" do expect { @checker.check }.to change { Event.count }.by(1) expect(Event.last.payload[:output].strip).to eq('') # not_to eq(ENV['BUNDLE_GEMFILE'] end end end end describe "#receive" do before do allow(@checker).to receive(:run_command).with(@valid_path, @event.payload[:cmd], nil) { ["fake ls output", "", 0] } end it "creates events" do @checker.options[:command] = "{{cmd}}" @checker.receive([@event]) expect(Event.last.payload[:path]).to eq(@valid_path) expect(Event.last.payload[:command]).to eq(@event.payload[:cmd]) expect(Event.last.payload[:output]).to eq("fake ls output") end it "creates events (unstubbed)" do @checker2.receive([@event]) expect(Event.last.payload[:path]).to eq(@valid_path) expect(Event.last.payload[:output]).to eq('hello, Huginn.') expect(Event.last.payload[:errors]).to eq('warning!') end it "does not run when should_run? is false" do allow(Agents::ShellCommandAgent).to receive(:should_run?) { false } expect { @checker.receive([@event]) }.not_to change { Event.count } end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/digest_agent_spec.rb
spec/models/agents/digest_agent_spec.rb
require "rails_helper" describe Agents::DigestAgent do before do @checker = Agents::DigestAgent.new(:name => "something", :options => { :expected_receive_period_in_days => "2", :retained_events => "0", :message => "{{ events | map:'data' | join:';' }}" }) @checker.user = users(:bob) @checker.save! end describe "#working?" do it "checks to see if the Agent has received any events in the last 'expected_receive_period_in_days' days" do event = Event.new event.agent = agents(:bob_rain_notifier_agent) event.payload = { :data => "event" } event.save! expect(@checker).not_to be_working # no events have ever been received @checker.options[:expected_receive_period_in_days] = 2 @checker.save! Agents::DigestAgent.async_receive @checker.id, [event.id] expect(@checker.reload).to be_working # Events received three_days_from_now = 3.days.from_now allow(Time).to receive(:now) { three_days_from_now } expect(@checker).not_to be_working # too much time has passed end end describe "validation" do before do expect(@checker).to be_valid end it "should validate retained_events" do @checker.options[:retained_events] = "" expect(@checker).to be_valid @checker.options[:retained_events] = "0" expect(@checker).to be_valid @checker.options[:retained_events] = "10" expect(@checker).to be_valid @checker.options[:retained_events] = "10000" expect(@checker).not_to be_valid @checker.options[:retained_events] = "-1" expect(@checker).not_to be_valid end end describe "#receive" do describe "and retained_events is 0" do before { @checker.options['retained_events'] = 0 } it "retained_events any payloads it receives" do event1 = Event.new event1.agent = agents(:bob_rain_notifier_agent) event1.payload = { :data => "event1" } event1.save! event2 = Event.new event2.agent = agents(:bob_weather_agent) event2.payload = { :data => "event2" } event2.save! @checker.receive([event1]) @checker.receive([event2]) expect(@checker.memory["queue"]).to eq([event1.id, event2.id]) end end describe "but retained_events is 1" do before { @checker.options['retained_events'] = 1 } it "retained_eventss only 1 event at a time" do event1 = Event.new event1.agent = agents(:bob_rain_notifier_agent) event1.payload = { :data => "event1" } event1.save! event2 = Event.new event2.agent = agents(:bob_weather_agent) event2.payload = { :data => "event2" } event2.save! @checker.receive([event1]) @checker.receive([event2]) expect(@checker.memory['queue']).to eq([event2.id]) end end end describe "#check" do describe "and retained_events is 0" do before { @checker.options['retained_events'] = 0 } it "should emit a event" do expect { Agents::DigestAgent.async_check(@checker.id) }.not_to change { Event.count } event1 = Event.new event1.agent = agents(:bob_rain_notifier_agent) event1.payload = { :data => "event" } event1.save! event2 = Event.new event2.agent = agents(:bob_weather_agent) event2.payload = { :data => "event" } event2.save! @checker.receive([event1]) @checker.receive([event2]) @checker.sources << agents(:bob_rain_notifier_agent) << agents(:bob_weather_agent) @checker.save! expect { @checker.check }.to change { Event.count }.by(1) expect(@checker.most_recent_event.payload["events"]).to eq([event1.payload, event2.payload]) expect(@checker.most_recent_event.payload["message"]).to eq("event;event") expect(@checker.memory['queue']).to be_empty end end describe "but retained_events is 1" do before { @checker.options['retained_events'] = 1 } it "should emit a event" do expect { Agents::DigestAgent.async_check(@checker.id) }.not_to change { Event.count } event1 = Event.new event1.agent = agents(:bob_rain_notifier_agent) event1.payload = { :data => "event" } event1.save! event2 = Event.new event2.agent = agents(:bob_weather_agent) event2.payload = { :data => "event" } event2.save! @checker.receive([event1]) @checker.receive([event2]) @checker.sources << agents(:bob_rain_notifier_agent) << agents(:bob_weather_agent) @checker.save! expect { @checker.check }.to change { Event.count }.by(1) expect(@checker.most_recent_event.payload["events"]).to eq([event2.payload]) expect(@checker.most_recent_event.payload["message"]).to eq("event") expect(@checker.memory['queue'].length).to eq(1) end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/telegram_agent_spec.rb
spec/models/agents/telegram_agent_spec.rb
require 'rails_helper' describe Agents::TelegramAgent do before do default_options = { auth_token: 'xxxxxxxxx:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', chat_id: 'xxxxxxxx', caption: '{{ caption }}', disable_web_page_preview: '{{ disable_web_page_preview }}', disable_notification: '{{ silent }}', long_message: '{{ long }}', parse_mode: 'html' } @checker = Agents::TelegramAgent.new name: 'Telegram Tester', options: default_options @checker.user = users(:bob) @checker.save! end def event_with_payload(payload) event = Event.new event.agent = agents(:bob_weather_agent) event.payload = payload event.save! event end def stub_methods allow_any_instance_of(Agents::TelegramAgent).to receive(:send_message) do |agent, method, params| @sent_messages << { method => params } end end describe 'validation' do before do expect(@checker).to be_valid end it 'should validate presence of auth_token' do @checker.options[:auth_token] = '' expect(@checker).not_to be_valid end it 'should validate presence of chat_id' do @checker.options[:chat_id] = '' expect(@checker).not_to be_valid end it 'should validate value of caption' do @checker.options[:caption] = 'a' * 1025 expect(@checker).not_to be_valid end it 'should validate value of disable_web_page_preview' do @checker.options[:disable_web_page_preview] = 'invalid' expect(@checker).not_to be_valid end it 'should validate value of disable_notification' do @checker.options[:disable_notification] = 'invalid' expect(@checker).not_to be_valid end it 'should validate value of long_message' do @checker.options[:long_message] = 'invalid' expect(@checker).not_to be_valid end it 'should validate value of parse_mode' do @checker.options[:parse_mode] = 'invalid' expect(@checker).not_to be_valid end end describe '#receive' do before do stub_methods @sent_messages = [] end it 'processes multiple events properly' do event_0 = event_with_payload silent: 'true', text: 'Looks like it is going to rain' event_1 = event_with_payload disable_web_page_preview: 'true', long: 'split', text: "#{'a' * 4095} #{'b' * 6}" event_2 = event_with_payload disable_web_page_preview: 'true', long: 'split', text: "#{'a' * 4096}#{'b' * 6}" event_3 = event_with_payload long: 'split', text: "#{'a' * 2142} #{'b' * 2142}" @checker.receive [event_0, event_1, event_2, event_3] expect(@sent_messages).to eq([ { text: { chat_id: 'xxxxxxxx', disable_notification: 'true', parse_mode: 'html', text: 'Looks like it is going to rain' } }, { text: { chat_id: 'xxxxxxxx', disable_web_page_preview: 'true', parse_mode: 'html', text: 'a' * 4095 } }, { text: { chat_id: 'xxxxxxxx', disable_web_page_preview: 'true', parse_mode: 'html', text: 'b' * 6 } }, { text: { chat_id: 'xxxxxxxx', disable_web_page_preview: 'true', parse_mode: 'html', text: 'a' * 4096 } }, { text: { chat_id: 'xxxxxxxx', disable_web_page_preview: 'true', parse_mode: 'html', text: 'b' * 6 } }, { text: { chat_id: 'xxxxxxxx', parse_mode: 'html', text: 'a' * 2142 } }, { text: { chat_id: 'xxxxxxxx', parse_mode: 'html', text: 'b' * 2142 } } ]) end it 'accepts audio key and uses :send_audio to send the file with truncated caption' do event = event_with_payload audio: 'https://example.com/sound.mp3', caption: 'a' * 1025 @checker.receive [event] expect(@sent_messages).to eq([{ audio: { audio: 'https://example.com/sound.mp3', caption: 'a'* 1024, chat_id: 'xxxxxxxx' } }]) end it 'accepts document key and uses :send_document to send the file and the full caption' do event = event_with_payload caption: "#{'a' * 1023} #{'b' * 6}", document: 'https://example.com/document.pdf', long: 'split' @checker.receive [event] expect(@sent_messages).to eq([ { document: { caption: 'a' * 1023, chat_id: 'xxxxxxxx', document: 'https://example.com/document.pdf' } }, { text: { chat_id: 'xxxxxxxx', parse_mode: 'html', text: 'b' * 6 } } ]) end it 'accepts photo key and uses :send_photo to send the file' do event = event_with_payload photo: 'https://example.com/image.png' @checker.receive [event] expect(@sent_messages).to eq([{ photo: { chat_id: 'xxxxxxxx', photo: 'https://example.com/image.png' } }]) end it 'accepts photo key with no caption when long:split is set' do event = event_with_payload photo: 'https://example.com/image.png', long: 'split', caption: nil @checker.receive [event] end it 'accepts video key and uses :send_video to send the file' do event = event_with_payload video: 'https://example.com/video.avi' @checker.receive [event] expect(@sent_messages).to eq([{ video: { chat_id: 'xxxxxxxx', video: 'https://example.com/video.avi' } }]) end it 'accepts group key and uses :send_media_group to send the file' do event = event_with_payload group: [{ type: 'photo', media: 'https://example.com/photo1.jpg' }, { type: 'photo', media: 'https://example.com/photo2.jpg' }] @checker.receive [event] expect(@sent_messages).to eq([{ group: { chat_id: 'xxxxxxxx', media: [{ 'type' => 'photo', 'media' => 'https://example.com/photo1.jpg' }, { 'type' => 'photo', 'media' => 'https://example.com/photo2.jpg' }] } }]) end it 'creates a log entry when no key of the received event was useable' do event = event_with_payload test: '1234' expect { @checker.receive [event] }.to change(AgentLog, :count).by(1) end end it 'creates an error log if the request fails' do event = event_with_payload text: 'hello' stub_request(:post, "https://api.telegram.org/botxxxxxxxxx:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/sendMessage"). with(headers: {'Content-type'=>'application/json'}). to_return(status: 200, body: '{"ok": false}', headers: {'Content-Type' => 'application/json'}) expect { @checker.receive [event] }.to change(AgentLog, :count).by(1) end describe '#working?' do it 'is not working without having received an event' do expect(@checker).not_to be_working end it 'is working after receiving an event without error' do @checker.last_receive_at = Time.now expect(@checker).to be_working end end describe '#complete_chat_id' do it 'returns a list of all recents chats, groups and channels' do stub_request(:post, "https://api.telegram.org/botxxxxxxxxx:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/getUpdates"). to_return(status: 200, body: '{"ok":true,"result":[{"update_id":252965475,"message":{"message_id":15,"from":{"id":97201077,"is_bot":false,"first_name":"Dominik","last_name":"Sander","language_code":"en-US"},"chat":{"id":97201077,"first_name":"Dominik","last_name":"Sander","type":"private"},"date":1506774710,"text":"test"}},{"update_id":252965476,"channel_post":{"message_id":4,"chat":{"id":-1001144599139,"title":"Much channel","type":"channel"},"date":1506782283,"text":"channel"}},{"update_id":252965477,"message":{"message_id":18,"from":{"id":97201077,"is_bot":false,"first_name":"Dominik","last_name":"Sander","language_code":"en-US"},"chat":{"id":-217850512,"title":"Just a test","type":"group","all_members_are_administrators":true},"date":1506782504,"left_chat_participant":{"id":136508315,"is_bot":true,"first_name":"Huginn","username":"HuginnNotificationBot"},"left_chat_member":{"id":136508315,"is_bot":true,"first_name":"Huginn","username":"HuginnNotificationBot"}}}]}', headers: {'Content-Type' => 'application/json'}) expect(@checker.complete_chat_id).to eq([{:id=>97201077, :text=>"Dominik Sander"}, {:id=>-1001144599139, :text=>"Much channel"}, {:id=>-217850512, :text=>"Just a test"}]) end end describe '#validate_auth_token' do it 'returns true if the token is valid' do stub_request(:post, "https://api.telegram.org/botxxxxxxxxx:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/getMe"). to_return(status: 200, body: '{"ok": true}', headers: {'Content-Type' => 'application/json'}) expect(@checker.validate_auth_token).to be_truthy end it 'returns false if the token is invalid' do stub_request(:post, "https://api.telegram.org/botxxxxxxxxx:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/getMe"). to_return(status: 200, body: "{}") expect(@checker.validate_auth_token).to be_falsy end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/weibo_publish_agent_spec.rb
spec/models/agents/weibo_publish_agent_spec.rb
# encoding: utf-8 require 'rails_helper' describe Agents::WeiboPublishAgent do before do @opts = { :uid => "1234567", :expected_update_period_in_days => "2", :app_key => "---", :app_secret => "---", :access_token => "---", :message_path => "text", :pic_path => "pic" } @checker = Agents::WeiboPublishAgent.new(:name => "Weibo Publisher", :options => @opts) @checker.user = users(:bob) @checker.save! @event = Event.new @event.agent = agents(:bob_weather_agent) @event.payload = { :text => 'Gonna rain..' } @event.save! @sent_messages = [] @sent_pictures = [] allow_any_instance_of(Agents::WeiboPublishAgent).to receive(:publish_tweet) { |agent, message| @sent_messages << message} allow_any_instance_of(Agents::WeiboPublishAgent).to receive(:publish_tweet_with_pic) { |agent, message, picture| @sent_pictures << picture} allow_any_instance_of(Agents::WeiboPublishAgent).to receive(:sleep) end describe '#receive' do it 'should publish any payload it receives' do event1 = Event.new event1.agent = agents(:bob_rain_notifier_agent) event1.payload = { :text => 'Gonna rain..' } event1.save! event2 = Event.new event2.agent = agents(:bob_weather_agent) event2.payload = { :text => 'More payload' } event2.save! Agents::WeiboPublishAgent.async_receive(@checker.id, [event1.id, event2.id]) expect(@sent_messages.count).to eq(2) expect(@checker.events.count).to eq(2) end end describe '#receive a tweet' do it 'should publish a tweet after expanding any t.co urls' do event = Event.new event.agent = agents(:bob_twitter_user_agent) event.payload = JSON.parse(File.read(Rails.root.join("spec/data_fixtures/one_tweet.json"))) event.save! Agents::WeiboPublishAgent.async_receive(@checker.id, [event.id]) expect(@sent_messages.count).to eq(1) expect(@sent_pictures.count).to eq(0) expect(@checker.events.count).to eq(1) expect(@sent_messages.first.include?("t.co")).not_to be_truthy end end describe '#receive payload with picture url' do before do stub_request(:head, 'http://valid.image').to_return(status: 200, headers: {"Content-Type" => "image/jpeg"}) stub_request(:head, 'http://invalid.image').to_return(status: 200, headers: {"Content-Type" => "text/html"}) end it 'should publish a tweet without a picture if image url is not valid' do event = Event.new event.agent = agents(:bob_weather_agent) event.payload = {:text => 'whatever', :pic => 'http://invalid.image'} event.save! Agents::WeiboPublishAgent.async_receive(@checker.id, [event.id]) expect(@sent_messages.count).to eq(1) expect(@sent_pictures.count).to eq(0) expect(@checker.events.count).to eq(1) end it 'should publish a tweet along with a picture if image url is valid' do event = Event.new event.agent = agents(:bob_weather_agent) event.payload = {:text => 'whatever', :pic => 'http://valid.image'} event.save! Agents::WeiboPublishAgent.async_receive(@checker.id, [event.id]) expect(@sent_messages.count).to eq(0) expect(@sent_pictures.count).to eq(1) expect(@checker.events.count).to eq(1) end end describe '#working?' do it 'checks if events have been received within the expected receive period' do expect(@checker).not_to be_working # No events received Agents::WeiboPublishAgent.async_receive(@checker.id, [@event.id]) expect(@checker.reload).to be_working # Just received events two_days_from_now = 2.days.from_now allow(Time).to receive(:now) { two_days_from_now } expect(@checker.reload).not_to be_working # More time has passed than the expected receive period without any new events end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/attribute_difference_agent_spec.rb
spec/models/agents/attribute_difference_agent_spec.rb
require 'rails_helper' describe Agents::AttributeDifferenceAgent do def create_event(value=nil) event = Event.new event.agent = agents(:jane_weather_agent) event.payload = { rate: value } event.save! event end before do @valid_params = { path: 'rate', output: 'rate_diff', method: 'integer_difference', expected_update_period_in_days: '1' } @checker = Agents::AttributeDifferenceAgent.new(name: 'somename', options: @valid_params) @checker.user = users(:jane) @checker.save! end describe 'validation' do before do expect(@checker).to be_valid end it 'should validate presence of output' do @checker.options[:output] = nil expect(@checker).not_to be_valid end it 'should validate presence of path' do @checker.options[:path] = nil expect(@checker).not_to be_valid end it 'should validate presence of method' do @checker.options[:method] = nil expect(@checker).not_to be_valid end it 'should validate presence of expected_update_period_in_days' do @checker.options[:expected_update_period_in_days] = nil expect(@checker).not_to be_valid end end describe '#working?' do before :each do # Need to create an event otherwise event_created_within? returns nil event = create_event @checker.receive([event]) end it 'is when event created within :expected_update_period_in_days' do @checker.options[:expected_update_period_in_days] = 2 expect(@checker).to be_working end it 'isnt when event created outside :expected_update_period_in_days' do @checker.options[:expected_update_period_in_days] = 2 # Add more than 1 hour to 2 days to avoid DST boundary issues travel 50.hours do expect(@checker).not_to be_working end end end describe '#receive' do before :each do @event = create_event('5.5') end it 'creates events when memory is empty' do expect { @checker.receive([@event]) }.to change(Event, :count).by(1) expect(Event.last.payload[:rate_diff]).to eq(0) end it 'creates event with extra attribute for integer_difference' do @checker.receive([@event]) event = create_event('6.5') expect { @checker.receive([event]) }.to change(Event, :count).by(1) expect(Event.last.payload[:rate_diff]).to eq(1) end it 'creates event with extra attribute for decimal_difference' do @checker.options[:method] = 'decimal_difference' @checker.receive([@event]) event = create_event('6.4') expect { @checker.receive([event]) }.to change(Event, :count).by(1) expect(Event.last.payload[:rate_diff]).to eq(0.9) end it 'creates event with extra attribute for percentage_change' do @checker.options[:method] = 'percentage_change' @checker.receive([@event]) event = create_event('9') expect { @checker.receive([event]) }.to change(Event, :count).by(1) expect(Event.last.payload[:rate_diff]).to eq(63.636) end it 'creates event with extra attribute for percentage_change with the correct rounding' do @checker.options[:method] = 'percentage_change' @checker.options[:decimal_precision] = 5 @checker.receive([@event]) event = create_event('9') expect { @checker.receive([event]) }.to change(Event, :count).by(1) expect(Event.last.payload[:rate_diff]).to eq(63.63636) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/de_duplication_agent_spec.rb
spec/models/agents/de_duplication_agent_spec.rb
require 'rails_helper' describe Agents::DeDuplicationAgent do def create_event(output=nil) event = Event.new event.agent = agents(:jane_weather_agent) event.payload = { :output => output } event.save! event end before do @valid_params = { :property => "{{output}}", :lookback => 3, :expected_update_period_in_days => "1", } @checker = Agents::DeDuplicationAgent.new(:name => "somename", :options => @valid_params) @checker.user = users(:jane) @checker.save! end describe "validation" do before do expect(@checker).to be_valid end it "should validate presence of lookback" do @checker.options[:lookback] = nil expect(@checker).not_to be_valid end it "should validate presence of property" do @checker.options[:expected_update_period_in_days] = nil expect(@checker).not_to be_valid end end describe '#initialize_memory' do it 'sets properties to an empty array' do expect(@checker.memory['properties']).to eq([]) end it 'does not override an existing value' do @checker.memory['properties'] = [1,2,3] @checker.save @checker.reload expect(@checker.memory['properties']).to eq([1,2,3]) end end describe "#working?" do before :each do # Need to create an event otherwise event_created_within? returns nil event = create_event @checker.receive([event]) end it "is when event created within :expected_update_period_in_days" do @checker.options[:expected_update_period_in_days] = 2 expect(@checker).to be_working end it "isnt when event created outside :expected_update_period_in_days" do @checker.options[:expected_update_period_in_days] = 2 # Add more than 1 hour to 2 days to avoid DST boundary issues travel 50.hours do expect(@checker).not_to be_working end end end describe "#receive" do before :each do @event = create_event("2014-07-01") end it "creates events when memory is empty" do @event.payload[:output] = "2014-07-01" expect { @checker.receive([@event]) }.to change(Event, :count).by(1) expect(Event.last.payload[:command]).to eq(@event.payload[:command]) expect(Event.last.payload[:output]).to eq(@event.payload[:output]) end it "creates events when new event is unique" do @event.payload[:output] = "2014-07-01" @checker.receive([@event]) event = create_event("2014-08-01") expect { @checker.receive([event]) }.to change(Event, :count).by(1) end it "does not create event when event is a duplicate" do @event.payload[:output] = "2014-07-01" @checker.receive([@event]) expect { @checker.receive([@event]) }.to change(Event, :count).by(0) end it "should respect the lookback value" do 3.times do |i| @event.payload[:output] = "2014-07-0#{i}" @checker.receive([@event]) end @event.payload[:output] = "2014-07-05" expect { @checker.receive([@event]) }.to change(Event, :count).by(1) expect(@checker.memory['properties'].length).to eq(3) expect(@checker.memory['properties']).to eq(["2014-07-01", "2014-07-02", "2014-07-05"]) end it "should hash the value if its longer then 10 chars" do @event.payload[:output] = "01234567890" expect { @checker.receive([@event]) }.to change(Event, :count).by(1) expect(@checker.memory['properties'].last).to eq('2256157795') end it "should use the whole event if :property is blank" do @checker.options['property'] = '' expect { @checker.receive([@event]) }.to change(Event, :count).by(1) expect(@checker.memory['properties'].last).to eq('3023526198') end it "should still work after the memory was cleared" do @checker.memory = {} @checker.save @checker.reload expect { @checker.receive([@event]) }.not_to raise_error end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/http_status_agent_spec.rb
spec/models/agents/http_status_agent_spec.rb
require 'rails_helper' describe 'HttpStatusAgent' do before do stub_request(:get, 'http://google.com/') end let(:default_url) { 'http://google.com/' } let(:agent_options) do { url: "{{ url | default: '#{default_url}' }}", headers_to_save: '{{ headers_to_save }}', } end let(:agent) do Agents::HttpStatusAgent.create!( name: SecureRandom.uuid, service: services(:generic), user: users(:jane), options: agent_options ) end def created_events agent.events.reorder(id: :asc) end describe "working" do it "should be working when the last status is 200" do agent.memory['last_status'] = '200' expect(agent.working?).to eq(true) end it "should be working when the last status is 304" do agent.memory['last_status'] = '304' expect(agent.working?).to eq(true) end it "should not be working if the status is 0" do agent.memory['last_status'] = '0' expect(agent.working?).to eq(false) end it "should not be working if the status is missing" do agent.memory['last_status'] = nil expect(agent.working?).to eq(false) end it "should not be working if the status is -1" do agent.memory['last_status'] = '-1' expect(agent.working?).to eq(false) end end describe "check" do let(:url) { "http://#{SecureRandom.uuid}/" } let(:default_url) { url } let(:agent_options) do super().merge(headers_to_save: '') end it "should check the url" do stub = stub_request(:get, url) agent.check expect(stub).to have_been_requested end end describe "receive" do describe "with an event with a successful ping" do let(:successful_url) { "http://#{SecureRandom.uuid}/" } let(:default_url) { successful_url } let(:status_code) { 200 } let(:header) { 'X-Some-Header' } let(:header_value) { SecureRandom.uuid } before do stub_request(:get, successful_url).to_return(status: status_code) end let(:event_with_a_successful_ping) do Event.new(payload: { url: successful_url, headers_to_save: "" }) end let(:events) do [event_with_a_successful_ping] end it "should create one event" do agent.receive events expect(created_events.count).to eq(1) end it "should note that the successful response succeeded" do agent.receive events expect(created_events.last[:payload]['response_received']).to eq(true) end it "should return the status code" do agent.receive events expect(created_events.last[:payload]['status']).to eq('200') end it "should remember the status" do agent.receive events expect(agent.memory['last_status']).to eq('200') end it "should record the time spent waiting for the reply" do agent.receive events expect(created_events.last[:payload]['elapsed_time']).not_to be_nil end it "should not return a header" do agent.receive events expect(created_events.last[:payload]['headers']).to be_nil end describe "but the last status code was 200" do before do agent.memory['last_status'] = '200' agent.save! end describe "and no duplication settings have been set" do it "should create one event" do agent.receive events expect(created_events.count).to eq(1) end end describe "and change settings have been set to true" do before do agent.options[:changes_only] = 'true' agent.save! end it "should NOT create any events" do agent.receive events expect(created_events.count).to eq(0) end describe "but actually, the ping failed" do let(:failing_url) { "http://#{SecureRandom.uuid}/" } let(:event_with_a_failing_ping) do Event.new(payload: { url: failing_url, headers_to_save: "" }) end let(:events) do [event_with_a_successful_ping, event_with_a_failing_ping] end before do stub_request(:get, failing_url).to_return(status: 500) end it "should create an event" do agent.receive events expect(created_events.count).to eq(1) end end end describe "and change settings have been set to false" do before do agent.options[:changes_only] = 'false' agent.save! end it "should create one event" do agent.receive events expect(created_events.count).to eq(1) end end end describe "but the status code is not 200" do let(:status_code) { 500 } it "should return the status code" do agent.receive events expect(created_events.last[:payload]['status']).to eq('500') end it "should remember the status" do agent.receive events expect(agent.memory['last_status']).to eq('500') end end it "should return the original url" do agent.receive events expect(created_events.last[:payload]['url']).to eq(successful_url) end it "should return the final url" do agent.receive events expect(created_events.last[:payload]['final_url']).to eq(successful_url) end it "should return whether the url redirected" do agent.receive events expect(created_events.last[:payload]['redirected']).to eq(false) end describe "but the ping returns a status code of 0" do before do stub_request(:get, successful_url).to_return(status: 0) end let(:event_with_a_successful_ping) do Event.new(payload: { url: successful_url, headers_to_save: "" }) end it "should create one event" do agent.receive events expect(created_events.count).to eq(1) end it "should note that no response was received" do agent.receive events expect(created_events.last[:payload]['response_received']).to eq(false) end it "should return the original url" do agent.receive events expect(created_events.last[:payload]['url']).to eq(successful_url) end it "should remember no status" do agent.memory['last_status'] = '200' agent.receive events expect(agent.memory['last_status']).to be_nil end end describe "but the ping returns a status code of -1" do before do stub_request(:get, successful_url).to_return(status: -1) end let(:event_with_a_successful_ping) do Event.new(payload: { url: successful_url, headers_to_save: "" }) end it "should create one event" do agent.receive events expect(created_events.count).to eq(1) end it "should note that no response was received" do agent.receive events expect(created_events.last[:payload]['response_received']).to eq(false) end it "should return the original url" do agent.receive events expect(created_events.last[:payload]['url']).to eq(successful_url) end end describe "and with one event with a failing ping" do let(:failing_url) { "http://#{SecureRandom.uuid}/" } let(:event_with_a_failing_ping) do Event.new(payload: { url: failing_url, headers_to_save: "" }) end let(:events) do [event_with_a_successful_ping, event_with_a_failing_ping] end before do stub_request(:get, failing_url).to_raise(RuntimeError) #to_return(status: 500) end it "should create two events" do agent.receive events expect(created_events.count).to eq(2) end it "should note that the failed response failed" do agent.receive events expect(created_events[1][:payload]['response_received']).to eq(false) end it "should note that the successful response succeeded" do agent.receive events expect(created_events[0][:payload]['response_received']).to eq(true) end it "should return the original url on both events" do agent.receive events expect(created_events[0][:payload]['url']).to eq(successful_url) expect(created_events[1][:payload]['url']).to eq(failing_url) end it "should record the time spent waiting for the reply" do agent.receive events expect(created_events[0][:payload]['elapsed_time']).not_to be_nil expect(created_events[1][:payload]['elapsed_time']).not_to be_nil end end describe "with a response with a header" do before do stub_request(:get, successful_url).to_return( status: status_code, headers: { header => header_value } ) end let(:event_with_a_successful_ping) do Event.new(payload: { url: successful_url, headers_to_save: header }) end it "should save the header value according to headers_to_save" do agent.receive events event = created_events.last expect(event[:payload]['headers']).not_to be_nil expect(event[:payload]['headers'][header]).to eq(header_value) end context "regarding case-insensitivity" do let(:event_with_a_successful_ping) do super().tap { |event| event.payload[:headers_to_save].swapcase! } end it "should save the header value according to headers_to_save" do agent.receive events event = created_events.last expect(event[:payload]['headers']).not_to be_nil expect(event[:payload]['headers'][header.swapcase]).to eq(header_value) end end end describe "with existing and non-existing headers specified" do let(:nonexistant_header) { SecureRandom.uuid } before do stub_request(:get, successful_url).to_return( status: status_code, headers: { header => header_value } ) end let(:event_with_a_successful_ping) do Event.new(payload: { url: successful_url, headers_to_save: header + "," + nonexistant_header }) end it "should return the existing header's value" do agent.receive events expect(created_events.last[:payload]['headers'][header]).to eq(header_value) end it "should return nil for the nonexistant header" do agent.receive events expect(created_events.last[:payload]['headers'][nonexistant_header]).to be_nil end end end describe "validations" do before do expect(agent).to be_valid end it "should validate url" do agent.options['url'] = "" expect(agent).not_to be_valid agent.options['url'] = "http://www.google.com" expect(agent).to be_valid end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/user_location_agent_spec.rb
spec/models/agents/user_location_agent_spec.rb
require 'rails_helper' describe Agents::UserLocationAgent do before do @agent = Agent.build_for_type('Agents::UserLocationAgent', users(:bob), :name => 'something', :options => { :secret => 'my_secret', :max_accuracy => '50', :min_distance => '50', :api_key => 'api_key' }) @agent.save! end it 'receives an event' do event = Event.new event.agent = agents(:bob_weather_agent) event.created_at = Time.now event.payload = { 'longitude' => 123, 'latitude' => 45, 'something' => 'else' } expect { @agent.receive([event]) }.to change { @agent.events.count }.by(1) expect(@agent.events.last.payload).to eq({ 'longitude' => 123, 'latitude' => 45, 'something' => 'else' }) expect(@agent.events.last.lat).to eq(45) expect(@agent.events.last.lng).to eq(123) end it 'does not accept a web request that is not POST' do %w[get put delete patch].each { |method| content, status, content_type = @agent.receive_web_request({ 'secret' => 'my_secret' }, method, 'application/json') expect(status).to eq(404) } end it 'requires a valid secret for a web request' do content, status, content_type = @agent.receive_web_request({ 'secret' => 'fake' }, 'post', 'application/json') expect(status).to eq(401) content, status, content_type = @agent.receive_web_request({ 'secret' => 'my_secret' }, 'post', 'application/json') expect(status).to eq(200) end it 'creates an event on a web request' do expect { @agent.receive_web_request({ 'secret' => 'my_secret', 'longitude' => 123, 'latitude' => 45, 'something' => 'else' }, 'post', 'application/json') }.to change { @agent.events.count }.by(1) expect(@agent.events.last.payload).to eq({ 'longitude' => 123, 'latitude' => 45, 'something' => 'else' }) expect(@agent.events.last.lat).to eq(45) expect(@agent.events.last.lng).to eq(123) end it 'does not create event when too inaccurate' do event = Event.new event.agent = agents(:bob_weather_agent) event.created_at = Time.now event.payload = { 'longitude' => 123, 'latitude' => 45, 'accuracy' => '100', 'something' => 'else' } expect { @agent.receive([event]) }.to change { @agent.events.count }.by(0) end it 'does create event when accurate enough' do event = Event.new event.agent = agents(:bob_weather_agent) event.created_at = Time.now event.payload = { 'longitude' => 123, 'latitude' => 45, 'accuracy' => '20', 'something' => 'else' } expect { @agent.receive([event]) }.to change { @agent.events.count }.by(1) expect(@agent.events.last.payload).to eq({ 'longitude' => 123, 'latitude' => 45, 'accuracy' => '20', 'something' => 'else' }) expect(@agent.events.last.lat).to eq(45) expect(@agent.events.last.lng).to eq(123) end it 'allows a custom accuracy field' do event = Event.new event.agent = agents(:bob_weather_agent) event.created_at = Time.now @agent.options['accuracy_field'] = 'estimated_to' event.payload = { 'longitude' => 123, 'latitude' => 45, 'estimated_to' => '20', 'something' => 'else' } expect { @agent.receive([event]) }.to change { @agent.events.count }.by(1) expect(@agent.events.last.payload).to eq({ 'longitude' => 123, 'latitude' => 45, 'estimated_to' => '20', 'something' => 'else' }) expect(@agent.events.last.lat).to eq(45) expect(@agent.events.last.lng).to eq(123) end it 'does create an event when far enough' do @agent.memory["last_location"] = { 'longitude' => 12, 'latitude' => 34, 'something' => 'else' } event = Event.new event.agent = agents(:bob_weather_agent) event.created_at = Time.now event.payload = { 'longitude' => 123, 'latitude' => 45, 'something' => 'else' } expect { @agent.receive([event]) }.to change { @agent.events.count }.by(1) expect(@agent.events.last.payload).to eq({ 'longitude' => 123, 'latitude' => 45, 'something' => 'else' }) expect(@agent.events.last.lat).to eq(45) expect(@agent.events.last.lng).to eq(123) end it 'does not create an event when too close' do @agent.memory["last_location"] = { 'longitude' => 123, 'latitude' => 45, 'something' => 'else' } event = Event.new event.agent = agents(:bob_weather_agent) event.created_at = Time.now event.payload = { 'longitude' => 123, 'latitude' => 45, 'something' => 'else' } expect { @agent.receive([event]) }.to change { @agent.events.count }.by(0) end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/imap_folder_agent_spec.rb
spec/models/agents/imap_folder_agent_spec.rb
require 'rails_helper' require 'time' describe Agents::ImapFolderAgent do module MessageMixin def folder 'INBOX' end def uidvalidity 100 end def has_attachment? false end def body_parts(mime_types = %(text/plain text/enriched text/html)) mime_types.map do |type| all_parts.find do |part| part.mime_type == type end end.compact.map! do |part| part.extend(Agents::ImapFolderAgent::Message::Scrubbed) end end def uid; end def raw_mail; end def delete; end def mark_as_read; end include Agents::ImapFolderAgent::Message::Scrubbed end describe 'checking IMAP' do let(:valid_options) do { 'expected_update_period_in_days' => 1, 'host' => 'mail.example.net', 'ssl' => true, 'username' => 'foo', 'password' => 'bar', 'folders' => ['INBOX'], 'conditions' => {} } end let(:mails) do [ Mail.read(Rails.root.join('spec/data_fixtures/imap1.eml')).tap do |mail| mail.extend(MessageMixin) allow(mail).to receive(:uid).and_return(1) allow(mail).to receive(:raw_mail).and_return(mail.encoded) end, Mail.read(Rails.root.join('spec/data_fixtures/imap2.eml')).tap do |mail| mail.extend(MessageMixin) allow(mail).to receive(:uid).and_return(2) allow(mail).to receive(:has_attachment?).and_return(true) allow(mail).to receive(:raw_mail).and_return(mail.encoded) end ] end let(:expected_payloads) do [ { 'message_id' => 'foo.123@mail.example.jp', 'folder' => 'INBOX', 'from' => 'nanashi.gombeh@example.jp', 'to' => ['jane.doe@example.com', 'john.doe@example.com'], 'cc' => [], 'date' => '2014-05-09T16:00:00+09:00', 'subject' => 'some subject', 'body' => "Some plain text\nSome second line\n", 'has_attachment' => false, 'matches' => {}, 'mime_type' => 'text/plain' }, { 'message_id' => 'bar.456@mail.example.com', 'folder' => 'INBOX', 'from' => 'john.doe@example.com', 'to' => ['jane.doe@example.com', 'nanashi.gombeh@example.jp'], 'cc' => [], 'subject' => 'Re: some subject', 'body' => "Some reply\n", 'date' => '2014-05-09T17:00:00+09:00', 'has_attachment' => true, 'matches' => {}, 'mime_type' => 'text/plain' } ] end before do @checker = Agents::ImapFolderAgent.new(name: 'Example', options: valid_options, keep_events_for: 2.days) @checker.user = users(:bob) @checker.save! allow(@checker).to receive(:each_unread_mail) { |&yielder| seen = @checker.lastseen notified = @checker.notified mails.each do |mail| yielder[mail, notified] seen[mail.uidvalidity] = mail.uid end @checker.lastseen = seen @checker.notified = notified nil } end describe 'validations' do before do expect(@checker).to be_valid end it 'should validate the integer fields' do @checker.options['expected_update_period_in_days'] = 'nonsense' expect(@checker).not_to be_valid @checker.options['expected_update_period_in_days'] = '2' expect(@checker).to be_valid @checker.options['port'] = -1 expect(@checker).not_to be_valid @checker.options['port'] = 'imap' expect(@checker).not_to be_valid @checker.options['port'] = '143' expect(@checker).to be_valid @checker.options['port'] = 993 expect(@checker).to be_valid end it 'should validate the boolean fields' do %w[ssl mark_as_read].each do |key| @checker.options[key] = 1 expect(@checker).not_to be_valid @checker.options[key] = false expect(@checker).to be_valid @checker.options[key] = 'true' expect(@checker).to be_valid @checker.options[key] = '' expect(@checker).to be_valid end end it 'should validate regexp conditions' do @checker.options['conditions'] = { 'subject' => '(foo' } expect(@checker).not_to be_valid @checker.options['conditions'] = { 'body' => '***' } expect(@checker).not_to be_valid @checker.options['conditions'] = { 'subject' => '\ARe:', 'body' => '(?<foo>http://\S+)' } expect(@checker).to be_valid end end describe '#check' do it 'should check for mails and save memory' do expect { @checker.check }.to change { Event.count }.by(2) expect(@checker.notified.sort).to eq(mails.map(&:message_id).sort) expect(@checker.lastseen).to eq(mails.each_with_object(@checker.make_seen) do |mail, seen| seen[mail.uidvalidity] = mail.uid end) expect(Event.last(2).map(&:payload)).to eq expected_payloads expect { @checker.check }.not_to(change { Event.count }) end it 'should narrow mails by To' do @checker.options['conditions']['to'] = 'John.Doe@*' expect { @checker.check }.to change { Event.count }.by(1) expect(@checker.notified.sort).to eq([mails.first.message_id]) expect(@checker.lastseen).to eq(mails.each_with_object(@checker.make_seen) do |mail, seen| seen[mail.uidvalidity] = mail.uid end) expect(Event.last.payload).to eq(expected_payloads.first) expect { @checker.check }.not_to(change { Event.count }) end it 'should not fail when a condition on Cc is given and a mail does not have the field' do @checker.options['conditions']['cc'] = 'John.Doe@*' expect do expect { @checker.check }.not_to(change { Event.count }) end.not_to raise_exception end it 'should perform regexp matching and save named captures' do @checker.options['conditions'].update( 'subject' => '\ARe: (?<a>.+)', 'body' => 'Some (?<b>.+) reply' ) expect { @checker.check }.to change { Event.count }.by(1) expect(@checker.notified.sort).to eq([mails.last.message_id]) expect(@checker.lastseen).to eq(mails.each_with_object(@checker.make_seen) do |mail, seen| seen[mail.uidvalidity] = mail.uid end) expect(Event.last.payload).to eq(expected_payloads.last.update( 'body' => "<div dir=\"ltr\">Some HTML reply<br></div>\n", 'matches' => { 'a' => 'some subject', 'b' => 'HTML' }, 'mime_type' => 'text/html' )) expect { @checker.check }.not_to(change { Event.count }) end it 'should narrow mails by has_attachment (true)' do @checker.options['conditions']['has_attachment'] = true expect { @checker.check }.to change { Event.count }.by(1) expect(Event.last.payload['subject']).to eq('Re: some subject') end it 'should narrow mails by has_attachment (false)' do @checker.options['conditions']['has_attachment'] = false expect { @checker.check }.to change { Event.count }.by(1) expect(Event.last.payload['subject']).to eq('some subject') end it 'should narrow mail parts by MIME types' do @checker.options['mime_types'] = %w[text/plain] @checker.options['conditions'].update( 'subject' => '\ARe: (?<a>.+)', 'body' => 'Some (?<b>.+) reply' ) expect { @checker.check }.not_to(change { Event.count }) expect(@checker.notified.sort).to eq([]) expect(@checker.lastseen).to eq(mails.each_with_object(@checker.make_seen) do |mail, seen| seen[mail.uidvalidity] = mail.uid end) end it 'should never mark mails as read unless mark_as_read is true' do mails.each do |mail| allow(mail).to receive(:mark_as_read).never end expect { @checker.check }.to change { Event.count }.by(2) end it 'should mark mails as read if mark_as_read is true' do @checker.options['mark_as_read'] = true mails.each do |mail| allow(mail).to receive(:mark_as_read).once end expect { @checker.check }.to change { Event.count }.by(2) end it 'should create just one event for multiple mails with the same Message-Id' do mails.first.message_id = mails.last.message_id @checker.options['mark_as_read'] = true mails.each do |mail| allow(mail).to receive(:mark_as_read).once end expect { @checker.check }.to change { Event.count }.by(1) end it 'should delete mails if delete is true' do @checker.options['delete'] = true mails.each do |mail| allow(mail).to receive(:delete).once end expect { @checker.check }.to change { Event.count }.by(2) end describe 'processing mails with a broken From header value' do before do # "from" patterns work against mail addresses and not # against text parts, so these mails should be skipped if a # "from" condition is given. # # Mail::Header#[]= does not accept an invalid value, so set it directly mails.first.header.fields.replace_field Mail::Field.new('from', '.') mails.last.header.fields.replace_field Mail::Field.new('from', '@') end it 'should ignore them without failing if a "from" condition is given' do @checker.options['conditions']['from'] = '*' expect { @checker.check }.not_to(change { Event.count }) end end describe 'with event_headers' do let(:expected_headers) do [ { 'mime_version' => '1.0', 'x_foo' => "test1-1\ntest1-2" }, { 'mime_version' => '1.0', 'x_foo' => "test2-1\ntest2-2" } ] end before do expected_payloads.zip(expected_headers) do |payload, headers| payload['headers'] = headers end @checker.options['event_headers'] = %w[mime-version x-foo] @checker.options['event_headers_style'] = 'snakecased' @checker.save! end it 'should check for mails and emit events with headers' do expect { @checker.check }.to change { Event.count }.by(2) expect(@checker.notified.sort).to eq(mails.map(&:message_id).sort) expect(@checker.lastseen).to eq(mails.each_with_object(@checker.make_seen) do |mail, seen| seen[mail.uidvalidity] = mail.uid end) expect(Event.last(2).map(&:payload)).to match expected_payloads expect { @checker.check }.not_to(change { Event.count }) end end describe 'with include_raw_mail' do before do @checker.options['include_raw_mail'] = true @checker.save! end it 'should check for mails and emit events with raw_mail' do expect { @checker.check }.to change { Event.count }.by(2) expect(@checker.notified.sort).to eq(mails.map(&:message_id).sort) expect(@checker.lastseen).to eq(mails.each_with_object(@checker.make_seen) do |mail, seen| seen[mail.uidvalidity] = mail.uid end) expect(Event.last(2).map(&:payload)).to match(expected_payloads.map.with_index do |payload, i| payload.merge( 'raw_mail' => satisfy { |d| Base64.decode64(d) == mails[i].encoded } ) end) expect { @checker.check }.not_to(change { Event.count }) end end end end describe 'Agents::ImapFolderAgent::Message::Scrubbed' do before do @class = Class.new do def subject "broken\xB7subject\xB6" end def body "broken\xB7body\xB6" end include Agents::ImapFolderAgent::Message::Scrubbed end @object = @class.new end describe '#scrubbed' do it 'should return a scrubbed string' do expect(@object.scrubbed(:subject)).to eq('broken<b7>subject<b6>') expect(@object.scrubbed(:body)).to eq('broken<b7>body<b6>') end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/java_script_agent_spec.rb
spec/models/agents/java_script_agent_spec.rb
require 'rails_helper' describe Agents::JavaScriptAgent do before do @valid_params = { name: "somename", options: { code: "Agent.check = function() { this.createEvent({ 'message': 'hi' }); };", } } @agent = Agents::JavaScriptAgent.new(@valid_params) @agent.user = users(:jane) @agent.save! end describe "validations" do it "requires 'code'" do expect(@agent).to be_valid @agent.options['code'] = '' expect(@agent).not_to be_valid @agent.options.delete('code') expect(@agent).not_to be_valid end it "checks for a valid 'language', but allows nil" do expect(@agent).to be_valid @agent.options['language'] = '' expect(@agent).to be_valid @agent.options.delete('language') expect(@agent).to be_valid @agent.options['language'] = 'foo' expect(@agent).not_to be_valid %w[javascript JavaScript coffeescript CoffeeScript].each do |valid_language| @agent.options['language'] = valid_language expect(@agent).to be_valid end end it "accepts a credential, but it must exist" do expect(@agent).to be_valid @agent.options['code'] = 'credential:foo' expect(@agent).not_to be_valid users(:jane).user_credentials.create! credential_name: "foo", credential_value: "bar" expect(@agent.reload).to be_valid end end describe "#working?" do describe "when expected_update_period_in_days is set" do it "returns false when more than expected_update_period_in_days have passed since the last event creation" do @agent.options['expected_update_period_in_days'] = 1 @agent.save! expect(@agent).not_to be_working @agent.check expect(@agent.reload).to be_working three_days_from_now = 3.days.from_now allow(Time).to receive(:now) { three_days_from_now } expect(@agent).not_to be_working end end describe "when expected_receive_period_in_days is set" do it "returns false when more than expected_receive_period_in_days have passed since the last event was received" do @agent.options['expected_receive_period_in_days'] = 1 @agent.save! expect(@agent).not_to be_working Agents::JavaScriptAgent.async_receive @agent.id, [events(:bob_website_agent_event).id] expect(@agent.reload).to be_working two_days_from_now = 2.days.from_now allow(Time).to receive(:now) { two_days_from_now } expect(@agent.reload).not_to be_working end end end describe "executing code" do it "works by default" do @agent.options = @agent.default_options @agent.options['make_event'] = true @agent.save! expect { expect { @agent.receive([events(:bob_website_agent_event)]) @agent.check }.not_to(change { AgentLog.count }) }.to change { Event.count }.by(2) end describe "using credentials as code" do before do @agent.user.user_credentials.create credential_name: 'code-foo', credential_value: 'Agent.check = function() { this.log("ran it"); };' @agent.options['code'] = "credential:code-foo\n\n" @agent.save! end it "accepts credentials" do @agent.check expect(AgentLog.last.message).to eq("ran it") end it "logs an error when the credential goes away" do @agent.user.user_credentials.delete_all @agent.reload.check expect(AgentLog.last.message).to eq("Unable to find credential") end end describe "error handling" do it "should log an error when V8 has issues" do @agent.options['code'] = 'syntax error!' @agent.save! expect { expect { @agent.check }.not_to raise_error }.to change { AgentLog.count }.by(1) expect(AgentLog.last.message).to match(/Unexpected identifier/) expect(AgentLog.last.level).to eq(4) end it "should log an error when JavaScript throws" do @agent.options['code'] = 'Agent.check = function() { throw "oh no"; };' @agent.save! expect { expect { @agent.check }.not_to raise_error }.to change { AgentLog.count }.by(1) expect(AgentLog.last.message).to match(/oh no/) expect(AgentLog.last.level).to eq(4) end end describe "getMemory" do it "won't store NaNs" do @agent.options['code'] = 'Agent.check = function() { this.memory("foo", NaN); };' @agent.save! @agent.check expect(@agent.memory['foo']).to eq('NaN') # string @agent.save! expect { @agent.reload.memory }.not_to raise_error end it "it stores an Array" do @agent.options['code'] = 'Agent.check = function() { var arr = [1,2]; this.memory("foo", arr); };' @agent.save! @agent.check expect(@agent.memory['foo']).to eq([1, 2]) @agent.save! expect { @agent.reload.memory }.not_to raise_error end it "it stores a Hash" do @agent.options['code'] = 'Agent.check = function() { var obj = {}; obj["one"] = 1; obj["two"] = [1,2]; this.memory("foo", obj); };' @agent.save! @agent.check expect(@agent.memory['foo']).to eq({ "one" => 1, "two" => [1, 2] }) @agent.save! expect { @agent.reload.memory }.not_to raise_error end it "it stores a nested Hash" do @agent.options['code'] = 'Agent.check = function() { var u = {}; u["one"] = 1; u["two"] = 2; var obj = {}; obj["three"] = 3; obj["four"] = u; this.memory("foo", obj); };' @agent.save! @agent.check expect(@agent.memory['foo']).to eq({ "three" => 3, "four" => { "one" => 1, "two" => 2 } }) @agent.save! expect { @agent.reload.memory }.not_to raise_error end it "it stores null" do @agent.options['code'] = 'Agent.check = function() { this.memory("foo", "test"); this.memory("foo", null); };' @agent.save! @agent.check expect(@agent.memory['foo']).to eq(nil) @agent.save! expect { @agent.reload.memory }.not_to raise_error end it "it stores false" do @agent.options['code'] = 'Agent.check = function() { this.memory("foo", "test"); this.memory("foo", false); };' @agent.save! @agent.check expect(@agent.memory['foo']).to eq(false) @agent.save! expect { @agent.reload.memory }.not_to raise_error end end describe "setMemory" do it "stores an object" do @agent.options['code'] = 'Agent.check = function() { var u = {}; u["one"] = 1; u["two"] = 2; this.setMemory(u); };' @agent.save! @agent.check expect(@agent.memory).to eq({ "one" => 1, "two" => 2 }) @agent.save! expect { @agent.reload.memory }.not_to raise_error end end describe "deleteKey" do it "deletes a memory key" do @agent.memory = { foo: "baz" } @agent.options['code'] = 'Agent.check = function() { this.deleteKey("foo"); };' @agent.save! @agent.check expect(@agent.memory['foo']).to be_nil expect { @agent.reload.memory }.not_to raise_error end it "returns the string value of the deleted key" do @agent.memory = { foo: "baz" } @agent.options['code'] = 'Agent.check = function() { this.createEvent({ message: this.deleteKey("foo")}); };' @agent.save! @agent.check created_event = @agent.events.last expect(created_event.payload).to eq('message' => "baz") end it "returns the hash value of the deleted key" do @agent.memory = { foo: { baz: 'test' } } @agent.options['code'] = 'Agent.check = function() { this.createEvent({ message: this.deleteKey("foo")}); };' @agent.save! @agent.check created_event = @agent.events.last expect(created_event.payload).to eq('message' => { 'baz' => 'test' }) end end describe "creating events" do it "creates events with this.createEvent in the JavaScript environment" do @agent.options['code'] = 'Agent.check = function() { this.createEvent({ message: "This is an event!", stuff: { foo: 5 } }); };' @agent.save! expect { expect { @agent.check }.not_to(change { AgentLog.count }) }.to change { Event.count }.by(1) created_event = @agent.events.last expect(created_event.payload).to eq({ 'message' => "This is an event!", 'stuff' => { 'foo' => 5 } }) end end describe "logging" do it "can output AgentLogs with this.log and this.error in the JavaScript environment" do @agent.options['code'] = 'Agent.check = function() { this.log("woah"); this.error("WOAH!"); };' @agent.save! expect { expect { @agent.check }.not_to raise_error }.to change { AgentLog.count }.by(2) log1, log2 = AgentLog.last(2) expect(log1.message).to eq("woah") expect(log1.level).to eq(3) expect(log2.message).to eq("WOAH!") expect(log2.level).to eq(4) end end describe "escaping and unescaping HTML" do it "can escape and unescape html with this.escapeHtml and this.unescapeHtml in the javascript environment" do @agent.options['code'] = 'Agent.check = function() { this.createEvent({ escaped: this.escapeHtml(\'test \"escaping\" <characters>\'), unescaped: this.unescapeHtml(\'test &quot;unescaping&quot; &lt;characters&gt;\')}); };' @agent.save! expect { expect { @agent.check }.not_to(change { AgentLog.count }) }.to change { Event.count }.by(1) created_event = @agent.events.last expect(created_event.payload).to eq({ 'escaped' => 'test &quot;escaping&quot; &lt;characters&gt;', 'unescaped' => 'test "unescaping" <characters>' }) end end describe "getting incoming events" do it "can access incoming events in the JavaScript enviroment via this.incomingEvents" do event = Event.new event.agent = agents(:bob_rain_notifier_agent) event.payload = { data: "Something you should know about" } event.save! event.reload @agent.options['code'] = <<-JS Agent.receive = function() { var events = this.incomingEvents(); for(var i = 0; i < events.length; i++) { this.createEvent({ 'message': 'I got an event!', 'event_was': events[i].payload }); } } JS @agent.save! expect { expect { @agent.receive([events(:bob_website_agent_event), event]) }.not_to(change { AgentLog.count }) }.to change { Event.count }.by(2) created_event = @agent.events.first expect(created_event.payload).to eq({ 'message' => "I got an event!", 'event_was' => { 'data' => "Something you should know about" } }) end end describe "getting and setting memory, getting options" do it "can access options via this.options and work with memory via this.memory" do @agent.options['code'] = <<-JS Agent.check = function() { if (this.options('make_event')) { var callCount = this.memory('callCount') || 0; this.memory('callCount', callCount + 1); } }; JS @agent.save! expect { expect { @agent.check expect(@agent.memory['callCount']).not_to be_present @agent.options['make_event'] = true @agent.check expect(@agent.memory['callCount']).to eq(1) @agent.check expect(@agent.memory['callCount']).to eq(2) @agent.memory['callCount'] = 20 @agent.check expect(@agent.memory['callCount']).to eq(21) }.not_to(change { AgentLog.count }) }.not_to(change { Event.count }) end end describe "using CoffeeScript" do it "will accept a 'language' of 'CoffeeScript'" do @agent.options['code'] = 'Agent.check = -> this.log("hello from coffeescript")' @agent.options['language'] = 'CoffeeScript' @agent.save! expect { @agent.check }.not_to raise_error expect(AgentLog.last.message).to eq("hello from coffeescript") end end describe "user credentials" do it "can access an existing credential" do @agent.send(:set_credential, 'test', 'hello') @agent.options['code'] = 'Agent.check = function() { this.log(this.credential("test")); };' @agent.save! @agent.check expect(AgentLog.last.message).to eq("hello") end it "will create a new credential" do @agent.options['code'] = 'Agent.check = function() { this.credential("test","1234"); };' @agent.save! expect { @agent.check }.to change(UserCredential, :count).by(1) end it "updates an existing credential" do @agent.send(:set_credential, 'test', 1234) @agent.options['code'] = 'Agent.check = function() { this.credential("test","12345"); };' @agent.save! expect { @agent.check }.to change(UserCredential, :count).by(0) expect(@agent.user.user_credentials.last.credential_value).to eq('12345') end end end describe "KVS" do before do Agents::KeyValueStoreAgent.create!( name: "kvs1", options: { key: "{{ key }}", value: "{{ value }}", variable: "var1", }, memory: { x: "Huginn", }, user: users(:jane), control_targets: [@agent] ) Agents::KeyValueStoreAgent.create!( name: "kvs2", options: { key: "{{ key }}", value: "{{ value }}", variable: "var2", }, memory: { y: "Muninn", }, user: users(:jane), control_targets: [@agent] ) end it "can be accessed via Agent.kvs()" do @agent.options['code'] = <<~JS Agent.check = function() { this.createEvent({ message: `I got values from KVS: ${this.kvs.var1["x"]} and ${this.kvs.var2["y"]}.` }); }; JS @agent.save! expect { @agent.check }.to change { @agent.events.count }.by(1) created_event = @agent.events.last expect(created_event.payload).to eq("message" => "I got values from KVS: Huginn and Muninn.") end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/google_translation_agent_spec.rb
spec/models/agents/google_translation_agent_spec.rb
require 'rails_helper' describe Agents::GoogleTranslationAgent, :vcr do before do @valid_params = { name: "somename", options: { to: "sv", from: "en", google_api_key: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', expected_receive_period_in_days: 1, content: { text: "{{message}}", content: "{{xyz}}" } } } @checker = Agents::GoogleTranslationAgent.new(@valid_params) @checker.user = users(:jane) @checker.save! @event = Event.new @event.agent = agents(:jane_weather_agent) @event.payload = { message: "hey what are you doing", xyz: "do tell more" } end describe "#receive" do it "checks if it can handle multiple events" do event1 = Event.new event1.agent = agents(:bob_weather_agent) event1.payload = { xyz: "value1", message: "value2" } expect { @checker.receive([@event,event1]) }.to change { Event.count }.by(2) end end describe "#working?" do it "checks if events have been received within expected receive period" do expect(@checker).not_to be_working Agents::GoogleTranslationAgent.async_receive @checker.id, [@event.id] expect(@checker.reload).to be_working two_days_from_now = 2.days.from_now allow(Time).to receive(:now) { two_days_from_now } expect(@checker.reload).not_to be_working end end describe "validation" do before do expect(@checker).to be_valid end it "should validate presence of content key" do @checker.options[:content] = nil expect(@checker).not_to be_valid end it "should validate presence of expected_receive_period_in_days key" do @checker.options[:expected_receive_period_in_days] = nil expect(@checker).not_to be_valid end it "should validate presence of google_api_key" do @checker.options[:google_api_key] = nil expect(@checker).not_to be_valid end it "should validate presence of 'to' key" do @checker.options[:to] = "" expect(@checker).not_to be_valid end it "should validate the value of 'mode' key" do @checker.options[:mode] = "clean" expect(@checker).to be_valid @checker.options[:mode] = "merge" expect(@checker).to be_valid @checker.options[:mode] = "clear" expect(@checker).not_to be_valid end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/csv_agent_spec.rb
spec/models/agents/csv_agent_spec.rb
require 'rails_helper' describe Agents::CsvAgent do before(:each) do @valid_params = { 'mode' => 'parse', 'separator' => ',', 'use_fields' => '', 'output' => 'event_per_row', 'with_header' => 'true', 'data_path' => '$.data', 'data_key' => 'data' } @checker = Agents::CsvAgent.new(:name => 'somename', :options => @valid_params) @checker.user = users(:jane) @checker.save! @lfa = Agents::LocalFileAgent.new(name: 'local', options: {path: '{{}}', watch: 'false', append: 'false', mode: 'read'}) @lfa.user = users(:jane) @lfa.save! end it_behaves_like 'FileHandlingConsumer' context '#validate_options' do it 'is valid with the given options' do expect(@checker).to be_valid end it "requires with_header to be either 'true' or 'false'" do @checker.options['with_header'] = 'true' expect(@checker).to be_valid @checker.options['with_header'] = 'false' expect(@checker).to be_valid @checker.options['with_header'] = 'test' expect(@checker).not_to be_valid end it "data_path has to be set in serialize mode" do @checker.options['mode'] = 'serialize' @checker.options['data_path'] = '' expect(@checker).not_to be_valid end end context '#working' do it 'is not working without having received an event' do expect(@checker).not_to be_working end it 'is working after receiving an event without error' do @checker.last_receive_at = Time.now expect(@checker).to be_working end end context '#receive' do after(:all) do FileUtils.rm(File.join(Rails.root, 'tmp', 'csv')) end def event_with_contents(contents) path = File.join(Rails.root, 'tmp', 'csv') File.open(path, 'w') do |f| f.write(contents) end Event.new(payload: { 'file_pointer' => {'agent_id' => @lfa.id, 'file' => path } }, user_id: @checker.user_id) end context "agent options" do let(:with_headers) { event_with_contents("one,two\n1,2\n2,3") } let(:without_headers) { event_with_contents("1,2\n2,3") } context "output" do it "creates one event per row" do @checker.options['output'] = 'event_per_row' expect { @checker.receive([with_headers]) }.to change(Event, :count).by(2) expect(Event.last.payload).to eq(@checker.options['data_key'] => {'one' => '2', 'two' => '3'}) end it "creates one event per file" do @checker.options['output'] = 'event_per_file' expect { @checker.receive([with_headers]) }.to change(Event, :count).by(1) expect(Event.last.payload).to eq(@checker.options['data_key'] => [{"one"=>"1", "two"=>"2"}, {"one"=>"2", "two"=>"3"}]) end end context "with_header" do it "works without headers" do @checker.options['with_header'] = 'false' expect { @checker.receive([without_headers]) }.to change(Event, :count).by(2) expect(Event.last.payload).to eq({@checker.options['data_key']=>["2", "3"]}) end it "works without headers and event_per_file" do @checker.options['with_header'] = 'false' @checker.options['output'] = 'event_per_file' expect { @checker.receive([without_headers]) }.to change(Event, :count).by(1) expect(Event.last.payload).to eq({@checker.options['data_key']=>[['1', '2'], ["2", "3"]]}) end end context "use_fields" do it "extracts the specified columns" do @checker.options['use_fields'] = 'one' expect { @checker.receive([with_headers]) }.to change(Event, :count).by(2) expect(Event.last.payload).to eq(@checker.options['data_key'] => {'one' => '2'}) end end context "data_path" do it "can receive the CSV via a regular event" do @checker.options['data_path'] = '$.data' event = Event.new(payload: {'data' => "one,two\r\n1,2\r\n2,3"}) expect { @checker.receive([event]) }.to change(Event, :count).by(2) expect(Event.last.payload).to eq(@checker.options['data_key'] => {'one' => '2', 'two' => '3'}) end end end context "handling different CSV formats" do it "works with windows line endings" do event = event_with_contents("one,two\r\n1,2\r\n2,3") expect { @checker.receive([event]) }.to change(Event, :count).by(2) expect(Event.last.payload).to eq(@checker.options['data_key'] => {'one' => '2', 'two' => '3'}) end it "works with OSX line endings" do event = event_with_contents("one,two\r1,2\r2,3") expect { @checker.receive([event]) }.to change(Event, :count).by(2) expect(Event.last.payload).to eq(@checker.options['data_key'] => {'one' => '2', 'two' => '3'}) end it "handles quotes correctly" do event = event_with_contents("\"one\",\"two\"\n1,2\n\"\"\"2, two\",3") expect { @checker.receive([event]) }.to change(Event, :count).by(2) expect(Event.last.payload).to eq(@checker.options['data_key'] => {'one' => '"2, two', 'two' => '3'}) end it "works with tab seperated csv" do event = event_with_contents("one\ttwo\r\n1\t2\r\n2\t3") @checker.options['separator'] = '\\t' expect { @checker.receive([event]) }.to change(Event, :count).by(2) expect(Event.last.payload).to eq(@checker.options['data_key'] => {'one' => '2', 'two' => '3'}) end end context "serializing" do before(:each) do @checker.options['mode'] = 'serialize' @checker.options['data_path'] = '$.data' @checker.options['data_key'] = 'data' end it "writes headers when with_header is true" do event = Event.new(payload: { 'data' => {'key' => 'value', 'key2' => 'value2', 'key3' => 'value3'} }) expect { @checker.receive([event])}.to change(Event, :count).by(1) expect(Event.last.payload).to eq('data' => "\"key\",\"key2\",\"key3\"\n\"value\",\"value2\",\"value3\"\n") end it "writes one row per received event" do event = Event.new(payload: { 'data' => {'key' => 'value', 'key2' => 'value2', 'key3' => 'value3'} }) event2 = Event.new(payload: { 'data' => {'key' => '2value', 'key2' => '2value2', 'key3' => '2value3'} }) expect { @checker.receive([event, event2])}.to change(Event, :count).by(1) expect(Event.last.payload).to eq('data' => "\"key\",\"key2\",\"key3\"\n\"value\",\"value2\",\"value3\"\n\"2value\",\"2value2\",\"2value3\"\n") end it "accepts multiple rows per event" do event = Event.new(payload: { 'data' => [{'key' => 'value', 'key2' => 'value2', 'key3' => 'value3'}, {'key' => '2value', 'key2' => '2value2', 'key3' => '2value3'}] }) expect { @checker.receive([event])}.to change(Event, :count).by(1) expect(Event.last.payload).to eq('data' => "\"key\",\"key2\",\"key3\"\n\"value\",\"value2\",\"value3\"\n\"2value\",\"2value2\",\"2value3\"\n") end it "does not write the headers when with_header is false" do @checker.options['with_header'] = 'false' event = Event.new(payload: { 'data' => {'key' => 'value', 'key2' => 'value2', 'key3' => 'value3'} }) expect { @checker.receive([event])}.to change(Event, :count).by(1) expect(Event.last.payload).to eq('data' => "\"value\",\"value2\",\"value3\"\n") end it "only serialize the keys specified in use_fields" do @checker.options['use_fields'] = 'key2, key3' event = Event.new(payload: { 'data' => {'key' => 'value', 'key2' => 'value2', 'key3' => 'value3'} }) expect { @checker.receive([event])}.to change(Event, :count).by(1) expect(Event.last.payload).to eq('data' => "\"key2\",\"key3\"\n\"value2\",\"value3\"\n") end it "respects the order of use_fields" do @checker.options['use_fields'] = 'key3, key' event = Event.new(payload: { 'data' => {'key' => 'value', 'key2' => 'value2', 'key3' => 'value3'} }) expect { @checker.receive([event])}.to change(Event, :count).by(1) expect(Event.last.payload).to eq('data' => "\"key3\",\"key\"\n\"value3\",\"value\"\n") end it "respects use_fields and writes no header" do @checker.options['with_header'] = 'false' @checker.options['use_fields'] = 'key2, key3' event = Event.new(payload: { 'data' => {'key' => 'value', 'key2' => 'value2', 'key3' => 'value3'} }) expect { @checker.receive([event])}.to change(Event, :count).by(1) expect(Event.last.payload).to eq('data' => "\"value2\",\"value3\"\n") end context "arrays" do it "does not write a header" do @checker.options['with_header'] = 'false' event = Event.new(payload: { 'data' => ['value1', 'value2'] }) event2 = Event.new(payload: { 'data' => ['value3', 'value4'] }) expect { @checker.receive([event, event2])}.to change(Event, :count).by(1) expect(Event.last.payload).to eq('data' => "\"value1\",\"value2\"\n\"value3\",\"value4\"\n") end it "handles nested arrays" do event = Event.new(payload: { 'data' => [['value1', 'value2'], ['value3', 'value4']] }) expect { @checker.receive([event])}.to change(Event, :count).by(1) expect(Event.last.payload).to eq('data' => "\"value1\",\"value2\"\n\"value3\",\"value4\"\n") end end end end context '#event_description' do it "works with event_per_row and headers" do @checker.options['output'] = 'event_per_row' @checker.options['with_header'] = 'true' description = @checker.event_description expect(description).not_to match(/\n\s+\[\n/) expect(description).to include(": {\n") end it "works with event_per_file and without headers" do @checker.options['output'] = 'event_per_file' @checker.options['with_header'] = 'false' description = @checker.event_description expect(description).to match(/\n\s+\[\n/) expect(description).not_to include(": {\n") end it "shows dummy CSV when in serialize mode" do @checker.options['mode'] = 'serialize' description = @checker.event_description expect(description).to include('"generated\",\"csv') end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/s3_agent_spec.rb
spec/models/agents/s3_agent_spec.rb
require 'rails_helper' describe Agents::S3Agent do before(:each) do @valid_params = { 'mode' => 'read', 'access_key_id' => '32343242', 'access_key_secret' => '1231312', 'watch' => 'false', 'bucket' => 'testbucket', 'region' => 'us-east-1', 'filename' => 'test.txt', 'data' => '{{ data }}' } @checker = Agents::S3Agent.new(:name => "somename", :options => @valid_params) @checker.user = users(:jane) @checker.save! end describe "#validate_options" do it "requires the bucket to be set" do @checker.options['bucket'] = '' expect(@checker).not_to be_valid end it "requires watch to be present" do @checker.options['watch'] = '' expect(@checker).not_to be_valid end it "requires watch to be either 'true' or 'false'" do @checker.options['watch'] = 'true' expect(@checker).to be_valid @checker.options['watch'] = 'false' expect(@checker).to be_valid @checker.options['watch'] = 'test' expect(@checker).not_to be_valid end it "requires region to be present" do @checker.options['region'] = '' expect(@checker).not_to be_valid end it "requires mode to be set to 'read' or 'write'" do @checker.options['mode'] = 'write' expect(@checker).to be_valid @checker.options['mode'] = '' expect(@checker).not_to be_valid end it "requires 'filename' in 'write' mode" do @checker.options['mode'] = 'write' @checker.options['filename'] = '' expect(@checker).not_to be_valid end it "requires 'data' in 'write' mode" do @checker.options['mode'] = 'write' @checker.options['data'] = '' expect(@checker).not_to be_valid end end describe "#validating" do it "validates the key" do expect(@checker).to receive(:client) { Aws::S3::Client.new(stub_responses: { list_buckets: ['SignatureDoesNotMatch'] }) } expect(@checker.validate_access_key_id).to be_falsy end it "validates the secret" do expect(@checker).to receive(:buckets) { true } expect(@checker.validate_access_key_secret).to be_truthy end end it "completes the buckets" do expect(@checker).to receive(:buckets) { [OpenStruct.new(name: 'test'), OpenStruct.new(name: 'test2')]} expect(@checker.complete_bucket).to eq([{text: 'test', id: 'test'}, {text: 'test2', id: 'test2'}]) end context "#working" do it "is working with no recent errors" do @checker.last_check_at = Time.now expect(@checker).to be_working end end context "#check" do context "not watching" do it "emits an event for every file" do expect(@checker).to receive(:get_bucket_contents) { {"test"=>"231232", "test2"=>"4564545"} } expect { @checker.check }.to change(Event, :count).by(2) expect(Event.last.payload).to eq({"file_pointer" => {"file"=>"test2", "agent_id"=> @checker.id}}) end end context "watching" do before(:each) do @checker.options['watch'] = 'true' end it "does not emit any events on the first run" do contents = {"test"=>"231232", "test2"=>"4564545"} expect(@checker).to receive(:get_bucket_contents) { contents } expect { @checker.check }.not_to change(Event, :count) expect(@checker.memory).to eq('seen_contents' => contents) end context "detecting changes" do before(:each) do contents = {"test"=>"231232", "test2"=>"4564545"} expect(@checker).to receive(:get_bucket_contents) { contents } expect { @checker.check }.not_to change(Event, :count) @checker.last_check_at = Time.now end it "emits events for removed files" do contents = {"test"=>"231232"} expect(@checker).to receive(:get_bucket_contents) { contents } expect { @checker.check }.to change(Event, :count).by(1) expect(Event.last.payload).to eq({"file_pointer" => {"file" => "test2", "agent_id"=> @checker.id}, "event_type" => "removed"}) end it "emits events for modified files" do contents = {"test"=>"231232", "test2"=>"changed"} expect(@checker).to receive(:get_bucket_contents) { contents } expect { @checker.check }.to change(Event, :count).by(1) expect(Event.last.payload).to eq({"file_pointer" => {"file" => "test2", "agent_id"=> @checker.id}, "event_type" => "modified"}) end it "emits events for added files" do contents = {"test"=>"231232", "test2"=>"4564545", "test3" => "31231231"} expect(@checker).to receive(:get_bucket_contents) { contents } expect { @checker.check }.to change(Event, :count).by(1) expect(Event.last.payload).to eq({"file_pointer" => {"file" => "test3", "agent_id"=> @checker.id}, "event_type" => "added"}) end end context "error handling" do it "handles AccessDenied exceptions" do expect(@checker).to receive(:client) { Aws::S3::Client.new(stub_responses: { list_objects: ['AccessDenied'] }) } expect { @checker.check }.to change(AgentLog, :count).by(1) expect(AgentLog.last.message).to match(/Could not access 'testbucket' Aws::S3::Errors::AccessDenied/) end it "handles generic S3 exceptions" do expect(@checker).to receive(:client) { Aws::S3::Client.new(stub_responses: { list_objects: ['PermanentRedirect'] }) } expect { @checker.check }.to change(AgentLog, :count).by(1) expect(AgentLog.last.message).to eq("Aws::S3::Errors::PermanentRedirect: stubbed-response-error-message") end end end end it "get_io returns a StringIO object" do stringio =StringIO.new mock_response = double() expect(mock_response).to receive(:body) { stringio } mock_client = double() expect(mock_client).to receive(:get_object).with(bucket: 'testbucket', key: 'testfile') { mock_response } expect(@checker).to receive(:client) { mock_client } @checker.get_io('testfile') end context "#get_bucket_contents" do it "returns a hash with the contents of the bucket" do mock_response = double() expect(mock_response).to receive(:contents) { [OpenStruct.new(key: 'test', etag: '231232'), OpenStruct.new(key: 'test2', etag: '4564545')] } mock_client = double() expect(mock_client).to receive(:list_objects).with(bucket: 'testbucket') { [mock_response] } expect(@checker).to receive(:client) { mock_client } expect(@checker.send(:get_bucket_contents)).to eq({"test"=>"231232", "test2"=>"4564545"}) end end context "#client" do it "initializes the S3 client correctly" do mock_credential = double() expect(Aws::Credentials).to receive(:new).with('32343242', '1231312') { mock_credential } expect(Aws::S3::Client).to receive(:new).with(credentials: mock_credential, region: 'us-east-1') @checker.send(:client) end end context "#event_description" do it "should include event_type when watch is set to true" do @checker.options['watch'] = 'true' expect(@checker.event_description).to include('event_type') end it "should not include event_type when watch is set to false" do @checker.options['watch'] = 'false' expect(@checker.event_description).not_to include('event_type') end end context "#receive" do before(:each) do @checker.options['mode'] = 'write' @checker.options['filename'] = 'file.txt' @checker.options['data'] = '{{ data }}' end it "writes the data at data into a file" do client_mock = double() expect(client_mock).to receive(:put_object).with(bucket: @checker.options['bucket'], key: @checker.options['filename'], body: 'hello world!') expect(@checker).to receive(:client) { client_mock } event = Event.new(payload: {'data' => 'hello world!'}) @checker.receive([event]) end it "does nothing when mode is set to 'read'" do @checker.options['mode'] = 'read' event = Event.new(payload: {'data' => 'hello world!'}) @checker.receive([event]) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/peak_detector_agent_spec.rb
spec/models/agents/peak_detector_agent_spec.rb
require 'rails_helper' describe Agents::PeakDetectorAgent do before do @valid_params = { 'name' => "my peak detector agent", 'options' => { 'expected_receive_period_in_days' => "2", 'group_by_path' => "filter", 'value_path' => "count", 'message' => "A peak was found", 'min_events' => "4" } } @agent = Agents::PeakDetectorAgent.new(@valid_params) @agent.user = users(:bob) @agent.save! end describe "#receive" do it "tracks and groups by the group_by_path" do events = build_events(:keys => ['count', 'filter'], :values => [[1, "something"], [2, "something"], [3, "else"]]) @agent.receive events expect(@agent.memory['data']['something'].map(&:first)).to eq([1, 2]) expect(@agent.memory['data']['something'].last.last).to be_within(10).of((100 - 1).hours.ago.to_i) expect(@agent.memory['data']['else'].first.first).to eq(3) expect(@agent.memory['data']['else'].first.last).to be_within(10).of((100 - 2).hours.ago.to_i) end it "works without a group_by_path as well" do @agent.options['group_by_path'] = "" events = build_events(:keys => ['count'], :values => [[1], [2]]) @agent.receive events expect(@agent.memory['data']['no_group'].map(&:first)).to eq([1, 2]) end it "keeps a rolling window of data" do @agent.options['window_duration_in_days'] = 5/24.0 @agent.receive build_events(:keys => ['count'], :values => [1, 2, 3, 4, 5, 6, 7, 8].map {|i| [i]}, :pattern => { 'filter' => "something" }) expect(@agent.memory['data']['something'].map(&:first)).to eq([4, 5, 6, 7, 8]) end it "finds peaks" do build_events(:keys => ['count'], :values => [5, 6, 4, 5, 4, 5, 15, 11, # peak 8, 50, # ignored because it's too close to the first peak 4, 5].map {|i| [i]}, :pattern => { 'filter' => "something" }).each.with_index do |event, index| expect { @agent.receive([event]) }.to change { @agent.events.count }.by( index == 6 ? 1 : 0 ) end expect(@agent.events.last.payload['peak']).to eq(15.0) expect(@agent.memory['peaks']['something'].length).to eq(1) end it "keeps a rolling window of peaks" do @agent.options['min_peak_spacing_in_days'] = 1/24.0 @agent.receive build_events(:keys => ['count'], :values => [1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1, 1, 1, 1, 10, 1].map {|i| [i]}, :pattern => { 'filter' => "something" }) expect(@agent.memory['peaks']['something'].length).to eq(2) end it 'waits and accumulates min events before triggering for peaks' do @agent.options['min_peak_spacing_in_days'] = 1/24.0 @agent.options['min_events'] = '10' @agent.receive build_events(:keys => ['count'], :values => [1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1, 1, 1, 1, 10, 1].map {|i| [i]}, :pattern => { 'filter' => "something" }) expect(@agent.memory['peaks']['something'].length).to eq(1) end it 'raised an exception if the extracted data can not be casted to a float' do event = Event.new(payload: {count: ["not working"]}) expect { @agent.receive([event]) }.to raise_error(NoMethodError, /undefined method `to_f'/) end end describe "validation" do before do expect(@agent).to be_valid end it "should validate presence of message" do @agent.options['message'] = nil expect(@agent).not_to be_valid end it "should validate presence of expected_receive_period_in_days" do @agent.options['expected_receive_period_in_days'] = "" expect(@agent).not_to be_valid end it "should validate presence of value_path" do @agent.options['value_path'] = "" expect(@agent).not_to be_valid end it "should validate search_url" do @agent.options['search_url'] = 'https://twitter.com/' expect(@agent).not_to be_valid @agent.options['search_url'] = 'https://twitter.com/{q}' expect(@agent).to be_valid end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/pdf_agent_spec.rb
spec/models/agents/pdf_agent_spec.rb
require 'rails_helper' describe Agents::PdfInfoAgent do let(:agent) do _agent = Agents::PdfInfoAgent.new(name: "PDF Info Agent") _agent.user = users(:bob) _agent.sources << agents(:bob_website_agent) _agent.save! _agent end describe "#receive" do before do @event = Event.new(payload: {'url' => 'http://mypdf.com'}) end it "should call HyPDF" do expect { expect(agent).to receive(:open).with('http://mypdf.com') { "data" } expect(HyPDF).to receive(:pdfinfo).with('data') { {title: "Huginn"} } agent.receive([@event]) }.to change { Event.count }.by(1) event = Event.last expect(event.payload[:title]).to eq('Huginn') end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/scheduler_agent_spec.rb
spec/models/agents/scheduler_agent_spec.rb
require 'rails_helper' describe Agents::SchedulerAgent do let(:valid_params) { { name: 'Example', options: { 'action' => 'run', 'schedule' => '0 * * * *' }, } } let(:agent) { described_class.create!(valid_params) { |agent| agent.user = users(:bob) } } it_behaves_like AgentControllerConcern describe "validation" do it "should validate schedule" do expect(agent).to be_valid agent.options.delete('schedule') expect(agent).not_to be_valid agent.options['schedule'] = nil expect(agent).not_to be_valid agent.options['schedule'] = '' expect(agent).not_to be_valid agent.options['schedule'] = '0' expect(agent).not_to be_valid agent.options['schedule'] = '*/15 * * * * * *' expect(agent).not_to be_valid agent.options['schedule'] = '*/1 * * * *' expect(agent).to be_valid agent.options['schedule'] = '*/1 * * *' expect(agent).not_to be_valid allow(agent).to receive(:second_precision_enabled) { true } agent.options['schedule'] = '*/15 * * * * *' expect(agent).to be_valid allow(agent).to receive(:second_precision_enabled) { false } agent.options['schedule'] = '*/10 * * * * *' expect(agent).not_to be_valid agent.options['schedule'] = '5/30 * * * * *' expect(agent).not_to be_valid agent.options['schedule'] = '*/15 * * * * *' expect(agent).to be_valid agent.options['schedule'] = '15,45 * * * * *' expect(agent).to be_valid agent.options['schedule'] = '0 * * * * *' expect(agent).to be_valid end end describe "save" do it "should delete memory['scheduled_at'] if and only if options is changed" do time = Time.now.to_i agent.memory['scheduled_at'] = time agent.save expect(agent.memory['scheduled_at']).to eq(time) agent.memory['scheduled_at'] = time # Currently agent.options[]= is not detected agent.options = { 'action' => 'run', 'schedule' => '*/5 * * * *' } agent.save expect(agent.memory['scheduled_at']).to be_nil end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/commander_agent_spec.rb
spec/models/agents/commander_agent_spec.rb
require 'rails_helper' describe Agents::CommanderAgent do let(:target) { agents(:bob_website_agent) } let(:valid_params) { { name: 'Example', schedule: 'every_1h', options: { 'action' => 'run', }, user: users(:bob), control_targets: [target] } } let(:agent) { described_class.create!(valid_params) } it_behaves_like AgentControllerConcern describe "check" do it "should command targets" do allow(Agent).to receive(:async_check).with(target.id).once { nil } agent.check end end describe "receive_events" do it "should command targets" do allow(Agent).to receive(:async_check).with(target.id).once { nil } event = Event.new event.agent = agents(:bob_rain_notifier_agent) event.payload = { 'url' => 'http://xkcd.com', 'link' => 'Random', } agent.receive([event]) end context "to configure" do let(:real_target) { Agents::TriggerAgent.create!( name: "somename", options: { expected_receive_period_in_days: 2, rules: [ { 'type' => 'field<value', 'value' => '200.0', 'path' => 'price', } ], keep_event: 'true' }, user: users(:bob) ) } let(:valid_params) { { name: 'Example', schedule: 'never', options: { 'action' => '{% if target.id == agent_id %}configure{% endif %}', 'configure_options' => { 'rules' => [ { 'type' => 'field<value', 'value' => "{{price}}", 'path' => 'price', } ] } }, user: users(:bob), control_targets: [target, real_target] } } it "should conditionally configure targets interpolating agent attributes" do expect { event = Event.new event.agent = agents(:bob_website_agent) event.payload = { 'price' => '198.0', 'agent_id' => real_target.id } agent.receive([event]) }.to change { real_target.options['rules'][0]['value'] }.from('200.0').to('198.0') & not_change { target.options } end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/twitter_search_agent_spec.rb
spec/models/agents/twitter_search_agent_spec.rb
require 'rails_helper' describe Agents::TwitterSearchAgent do before do # intercept the twitter API request stub_request(:any, /freebandnames.*[?&]tweet_mode=extended/). to_return(body: File.read(Rails.root.join("spec/data_fixtures/search_tweets.json")), headers: { 'Content-Type': 'application/json;charset=utf-8' }, status: 200) @opts = { search: "freebandnames", expected_update_period_in_days: "2", starting_at: "Jan 01 00:00:01 +0000 2000", max_results: '3' } end let(:checker) { _checker = Agents::TwitterSearchAgent.new(name: "search freebandnames", options: @opts) _checker.service = services(:generic) _checker.user = users(:bob) _checker.save! _checker } describe "#check" do it "should check for changes" do expect { checker.check }.to change { Event.count }.by(3) end end describe "#check with starting_at=future date" do it "should check for changes starting_at a future date, thus not find any" do opts = @opts.merge({ starting_at: "Jan 01 00:00:01 +0000 2999" }) checker = Agents::TwitterSearchAgent.new(name: "search freebandnames", options: opts) checker.service = services(:generic) checker.user = users(:bob) checker.save! expect { checker.check }.to change { Event.count }.by(0) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/google_calendar_publish_agent_spec.rb
spec/models/agents/google_calendar_publish_agent_spec.rb
require 'rails_helper' describe Agents::GoogleCalendarPublishAgent do let(:valid_params) do { 'expected_update_period_in_days' => '10', 'calendar_id' => calendar_id, 'google' => { 'key_file' => File.dirname(__FILE__) + '/../../data_fixtures/private.key', 'key_secret' => 'notasecret', 'service_account_email' => '1029936966326-ncjd7776pcspc98hsg82gsb56t3217ef@developer.gserviceaccount.com' } } end let(:agent) do _agent = Agents::GoogleCalendarPublishAgent.new(name: 'somename', options: valid_params) _agent.user = users(:jane) _agent.save! _agent end describe '#receive' do let(:message) do { 'visibility' => 'default', 'summary' => 'Awesome event', 'description' => 'An example event with text. Pro tip: DateTimes are in RFC3339', 'end' => { 'date_time' => '2014-10-02T11:00:00-05:00' }, 'start' => { 'date_time' => '2014-10-02T10:00:00-05:00' } } end let(:event) do _event = Event.new _event.agent = agents(:bob_manual_event_agent) _event.payload = { 'message' => message } _event.save! _event end let(:calendar_id) { 'sqv39gj35tc837gdns1g4d81cg@group.calendar.google.com' } let(:response_hash) do { 'kind' => 'calendar#event', 'etag' => '"2908684044040000"', 'id' => 'baz', 'status' => 'confirmed', 'html_link' => 'https://calendar.google.com/calendar/event?eid=foobar', 'created' => '2016-02-01T15:53:41.000Z', 'updated' => '2016-02-01T15:53:42.020Z', 'summary' => 'Awesome event', 'description' => 'An example event with text. Pro tip: DateTimes are in RFC3339', 'creator' => { 'email' => 'blah-foobar@developer.gserviceaccount.com' }, 'organizer' => { 'email' => calendar_id, 'display_name' => 'Huginn Location Log', 'self' => true }, 'start' => { 'date_time' => '2014-10-03T00:30:00+09:30' }, 'end' => { 'date_time' => '2014-10-03T01:30:00+09:30' }, 'i_cal_uid' => 'blah@google.com', 'sequence' => 0, 'reminders' => { 'use_default' => true } } end def setup_mock! fake_interface = double('fake_interface') expect(GoogleCalendar).to receive(:new).with(agent.interpolate_options(agent.options), Rails.logger) { fake_interface } expect(fake_interface).to receive(:publish_as).with(calendar_id, message) { response_hash } expect(fake_interface).to receive(:cleanup!) end describe 'when the calendar_id is in the options' do it 'should publish any payload it receives' do setup_mock! expect do agent.receive([event]) end.to change { agent.events.count }.by(1) expect(agent.events.last.payload).to eq({ 'success' => true, 'published_calendar_event' => response_hash, 'agent_id' => event.agent_id, 'event_id' => event.id }) end end describe 'with Liquid templating' do it 'should allow Liquid in the calendar_id' do setup_mock! agent.options['calendar_id'] = '{{ cal_id }}' agent.save! event.payload['cal_id'] = calendar_id event.save! agent.receive([event]) expect(agent.events.count).to eq(1) expect(agent.events.last.payload).to eq({ 'success' => true, 'published_calendar_event' => response_hash, 'agent_id' => event.agent_id, 'event_id' => event.id }) end it 'should allow Liquid in the key' do agent.options['google'].delete('key_file') agent.options['google']['key'] = '{% credential google_key %}' agent.save! users(:jane).user_credentials.create! credential_name: 'google_key', credential_value: 'something' agent.reload setup_mock! agent.receive([event]) expect(agent.events.count).to eq(1) end end end describe '#receive old style event' do let(:event) do _event = Event.new _event.agent = agents(:bob_manual_event_agent) _event.payload = { 'message' => { 'visibility' => 'default', 'summary' => 'Awesome event', 'description' => 'An example event with text. Pro tip: DateTimes are in RFC3339', 'end' => { 'dateTime' => '2014-10-02T11:00:00-05:00' }, 'start' => { 'dateTime' => '2014-10-02T10:00:00-05:00' } } } _event.save! _event end let(:calendar_id) { 'sqv39gj35tc837gdns1g4d81cg@group.calendar.google.com' } let(:message) do { 'visibility' => 'default', 'summary' => 'Awesome event', 'description' => 'An example event with text. Pro tip: DateTimes are in RFC3339', 'end' => { 'date_time' => '2014-10-02T11:00:00-05:00' }, 'start' => { 'date_time' => '2014-10-02T10:00:00-05:00' } } end let(:response_hash) do { 'kind' => 'calendar#event', 'etag' => '"2908684044040000"', 'id' => 'baz', 'status' => 'confirmed', 'html_link' => 'https://calendar.google.com/calendar/event?eid=foobar', 'created' => '2016-02-01T15:53:41.000Z', 'updated' => '2016-02-01T15:53:42.020Z', 'summary' => 'Awesome event', 'description' => 'An example event with text. Pro tip: DateTimes are in RFC3339', 'creator' => { 'email' => 'blah-foobar@developer.gserviceaccount.com' }, 'organizer' => { 'email' => calendar_id, 'display_name' => 'Huginn Location Log', 'self' => true }, 'start' => { 'date_time' => '2014-10-03T00:30:00+09:30' }, 'end' => { 'date_time' => '2014-10-03T01:30:00+09:30' }, 'i_cal_uid' => 'blah@google.com', 'sequence' => 0, 'reminders' => { 'use_default' => true } } end def setup_mock! fake_interface = double('fake_interface') expect(GoogleCalendar).to receive(:new).with(agent.interpolate_options(agent.options), Rails.logger) { fake_interface } allow(fake_interface).to receive(:publish_as).with(calendar_id, message) { response_hash } expect(fake_interface).to receive(:cleanup!) end describe 'when the calendar_id is in the options' do it 'should publish old style payload it receives' do setup_mock! expect do agent.receive([event]) end.to change { agent.events.count }.by(1) expect(agent.events.last.payload).to eq({ 'success' => true, 'published_calendar_event' => response_hash, 'agent_id' => event.agent_id, 'event_id' => event.id }) end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/ftpsite_agent_spec.rb
spec/models/agents/ftpsite_agent_spec.rb
require 'rails_helper' require 'time' describe Agents::FtpsiteAgent do describe "checking anonymous FTP" do before do @site = { 'expected_update_period_in_days' => 1, 'url' => "ftp://ftp.example.org/pub/releases/", 'patterns' => ["example*.tar.gz"], 'mode' => 'read', 'filename' => 'test', 'data' => '{{ data }}' } @checker = Agents::FtpsiteAgent.new(:name => "Example", :options => @site, :keep_events_for => 2.days) @checker.user = users(:bob) @checker.save! end context "#validate_options" do it "requires url to be a valid URI" do @checker.options['url'] = 'not_valid' expect(@checker).not_to be_valid end it "allows an URI without a path" do @checker.options['url'] = 'ftp://ftp.example.org' expect(@checker).to be_valid end it "does not check the url when liquid output markup is used" do @checker.options['url'] = 'ftp://{{ ftp_host }}' expect(@checker).to be_valid end it "requires patterns to be present and not empty array" do @checker.options['patterns'] = '' expect(@checker).not_to be_valid @checker.options['patterns'] = 'not an array' expect(@checker).not_to be_valid @checker.options['patterns'] = [] expect(@checker).not_to be_valid end it "when present timestamp must be parsable into a Time object instance" do @checker.options['timestamp'] = '2015-01-01 00:00:01' expect(@checker).to be_valid @checker.options['timestamp'] = 'error' expect(@checker).not_to be_valid end it "requires mode to be set to 'read' or 'write'" do @checker.options['mode'] = 'write' expect(@checker).to be_valid @checker.options['mode'] = '' expect(@checker).not_to be_valid end it 'automatically sets mode to read when the agent is a new record' do checker = Agents::FtpsiteAgent.new(name: 'test', options: @site.except('mode')) checker.user = users(:bob) expect(checker).to be_valid expect(checker.options['mode']).to eq('read') end it "requires 'filename' in 'write' mode" do @checker.options['mode'] = 'write' @checker.options['filename'] = '' expect(@checker).not_to be_valid end it "requires 'data' in 'write' mode" do @checker.options['mode'] = 'write' @checker.options['data'] = '' expect(@checker).not_to be_valid end end describe "#check" do before do allow(@checker).to receive(:each_entry) { |&block| block.call("example latest.tar.gz", Time.parse("2014-04-01T10:00:01Z")) block.call("example-1.0.tar.gz", Time.parse("2013-10-01T10:00:00Z")) block.call("example-1.1.tar.gz", Time.parse("2014-04-01T10:00:00Z")) } end it "should validate the integer fields" do @checker.options['expected_update_period_in_days'] = "nonsense" expect { @checker.save! }.to raise_error(/Invalid expected_update_period_in_days format/); @checker.options = @site end it "should check for changes and save known entries in memory" do expect { @checker.check }.to change { Event.count }.by(3) @checker.memory['known_entries'].tap { |known_entries| expect(known_entries.size).to eq(3) expect(known_entries.sort_by(&:last)).to eq([ ["example-1.0.tar.gz", "2013-10-01T10:00:00Z"], ["example-1.1.tar.gz", "2014-04-01T10:00:00Z"], ["example latest.tar.gz", "2014-04-01T10:00:01Z"], ]) } expect(Event.last(2).first.payload).to eq({ 'file_pointer' => { 'file' => 'example-1.1.tar.gz', 'agent_id' => @checker.id }, 'url' => 'ftp://ftp.example.org/pub/releases/example-1.1.tar.gz', 'filename' => 'example-1.1.tar.gz', 'timestamp' => '2014-04-01T10:00:00Z', }) expect { @checker.check }.not_to change { Event.count } allow(@checker).to receive(:each_entry) { |&block| block.call("example latest.tar.gz", Time.parse("2014-04-02T10:00:01Z")) # In the long list format the timestamp may look going # backwards after six months: Oct 01 10:00 -> Oct 01 2013 block.call("example-1.0.tar.gz", Time.parse("2013-10-01T00:00:00Z")) block.call("example-1.1.tar.gz", Time.parse("2014-04-01T10:00:00Z")) block.call("example-1.2.tar.gz", Time.parse("2014-04-02T10:00:00Z")) } expect { @checker.check }.to change { Event.count }.by(2) @checker.memory['known_entries'].tap { |known_entries| expect(known_entries.size).to eq(4) expect(known_entries.sort_by(&:last)).to eq([ ["example-1.0.tar.gz", "2013-10-01T00:00:00Z"], ["example-1.1.tar.gz", "2014-04-01T10:00:00Z"], ["example-1.2.tar.gz", "2014-04-02T10:00:00Z"], ["example latest.tar.gz", "2014-04-02T10:00:01Z"], ]) } expect(Event.last(2).first.payload).to eq({ 'file_pointer' => { 'file' => 'example-1.2.tar.gz', 'agent_id' => @checker.id }, 'url' => 'ftp://ftp.example.org/pub/releases/example-1.2.tar.gz', 'filename' => 'example-1.2.tar.gz', 'timestamp' => '2014-04-02T10:00:00Z', }) expect(Event.last.payload).to eq({ 'file_pointer' => { 'file' => 'example latest.tar.gz', 'agent_id' => @checker.id }, 'url' => 'ftp://ftp.example.org/pub/releases/example%20latest.tar.gz', 'filename' => 'example latest.tar.gz', 'timestamp' => '2014-04-02T10:00:01Z', }) expect { @checker.check }.not_to change { Event.count } end end describe "#each_entry" do before do allow_any_instance_of(Net::FTP).to receive(:list).and_return [ # Windows format "04-02-14 10:01AM 288720748 example latest.tar.gz", "04-01-14 10:05AM 288720710 no-match-example.tar.gz" ] allow(@checker).to receive(:open_ftp).and_yield(Net::FTP.new) end it "filters out files that don't match the given format" do entries = [] @checker.each_entry { |a, b| entries.push [a, b] } expect(entries.size).to eq(1) filename, mtime = entries.first expect(filename).to eq('example latest.tar.gz') expect(mtime).to eq('2014-04-02T10:01:00Z') end it "filters out files that are older than the given date" do @checker.options['after'] = '2015-10-21' entries = [] @checker.each_entry { |a, b| entries.push [a, b] } expect(entries.size).to eq(0) end end context "#open_ftp" do before(:each) do @ftp_mock = double() allow(@ftp_mock).to receive(:close) allow(@ftp_mock).to receive(:connect).with('ftp.example.org', 21) allow(@ftp_mock).to receive(:passive=).with(true) allow(Net::FTP).to receive(:new) { @ftp_mock } end context 'with_path' do before(:each) { expect(@ftp_mock).to receive(:chdir).with('pub/releases') } it "logs in as anonymous when no user and password are given" do expect(@ftp_mock).to receive(:login).with('anonymous', 'anonymous@') expect { |b| @checker.open_ftp(@checker.base_uri, &b) }.to yield_with_args(@ftp_mock) end it "passes the provided user and password" do @checker.options['url'] = "ftp://user:password@ftp.example.org/pub/releases/" expect(@ftp_mock).to receive(:login).with('user', 'password') expect { |b| @checker.open_ftp(@checker.base_uri, &b) }.to yield_with_args(@ftp_mock) end end it "does not call chdir when no path is given" do @checker.options['url'] = "ftp://ftp.example.org/" expect(@ftp_mock).to receive(:login).with('anonymous', 'anonymous@') expect { |b| @checker.open_ftp(@checker.base_uri, &b) }.to yield_with_args(@ftp_mock) end end context "#get_io" do it "returns the contents of the file" do ftp_mock = double() expect(ftp_mock).to receive(:getbinaryfile).with('file', nil).and_yield('data') expect(@checker).to receive(:open_ftp).with(@checker.base_uri).and_yield(ftp_mock) expect(@checker.get_io('file').read).to eq('data') end it "uses the encoding specified in force_encoding to convert the data to UTF-8" do ftp_mock = double() expect(ftp_mock).to receive(:getbinaryfile).with('file', nil).and_yield('ümlaut'.force_encoding('ISO-8859-15')) expect(@checker).to receive(:open_ftp).with(@checker.base_uri).and_yield(ftp_mock) expect(@checker.get_io('file').read).to eq('ümlaut') end it "returns an empty StringIO instance when no data was read" do ftp_mock = double() expect(ftp_mock).to receive(:getbinaryfile).with('file', nil) expect(@checker).to receive(:open_ftp).with(@checker.base_uri).and_yield(ftp_mock) expect(@checker.get_io('file').length).to eq(0) end end context "#receive" do before(:each) do @checker.options['mode'] = 'write' @checker.options['filename'] = 'file.txt' @checker.options['data'] = '{{ data }}' @ftp_mock = double() @stringio = StringIO.new() allow(@checker).to receive(:open_ftp).with(@checker.base_uri).and_yield(@ftp_mock) end it "writes the data at data into a file" do expect(StringIO).to receive(:new).with('hello world🔥') { @stringio } expect(@ftp_mock).to receive(:storbinary).with('STOR file.txt', @stringio, Net::FTP::DEFAULT_BLOCKSIZE) event = Event.new(payload: {'data' => 'hello world🔥'}) @checker.receive([event]) end it "converts the string encoding when force_encoding is specified" do @checker.options['force_encoding'] = 'ISO-8859-1' expect(StringIO).to receive(:new).with('hello world?') { @stringio } expect(@ftp_mock).to receive(:storbinary).with('STOR file.txt', @stringio, Net::FTP::DEFAULT_BLOCKSIZE) event = Event.new(payload: {'data' => 'hello world🔥'}) @checker.receive([event]) end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/evernote_agent_spec.rb
spec/models/agents/evernote_agent_spec.rb
require 'rails_helper' describe Agents::EvernoteAgent do class FakeEvernoteNoteStore attr_accessor :notes, :tags, :notebooks def initialize @notes, @tags, @notebooks = [], [], [] end def createNote(note) note.attributes = OpenStruct.new(source: nil, sourceURL: nil) note.guid = @notes.length + 1 @notes << note note end def updateNote(note) note.attributes = OpenStruct.new(source: nil, sourceURL: nil) old_note = @notes.find {|en_note| en_note.guid == note.guid} @notes[@notes.index(old_note)] = note note end def getNote(guid, *other_args) @notes.find {|note| note.guid == guid} end def createNotebook(notebook) notebook.guid = @notebooks.length + 1 @notebooks << notebook notebook end def createTag(tag) tag.guid = @tags.length + 1 @tags << tag tag end def listNotebooks; @notebooks; end def listTags; @tags; end def getNoteTagNames(guid) getNote(guid).try(:tagNames) || [] end def findNotesMetadata(*args); end end let(:en_note_store) do FakeEvernoteNoteStore.new end before do allow_any_instance_of(Agents::EvernoteAgent).to receive(:evernote_note_store) { en_note_store } end describe "#receive" do context "when mode is set to 'update'" do before do @options = { :mode => "update", :include_xhtml_content => "false", :expected_update_period_in_days => "2", :note => { :title => "{{title}}", :content => "{{content}}", :notebook => "{{notebook}}", :tagNames => "{{tag1}}, {{tag2}}" } } @agent = Agents::EvernoteAgent.new(:name => "evernote updater", :options => @options) @agent.service = services(:generic) @agent.user = users(:bob) @agent.save! @event = Event.new @event.agent = agents(:bob_website_agent) @event.payload = { :title => "xkcd Survey", :content => "The xkcd Survey: Big Data for a Big Planet", :notebook => "xkcd", :tag1 => "funny", :tag2 => "data" } @event.save! tag1 = OpenStruct.new(name: "funny") tag2 = OpenStruct.new(name: "data") [tag1, tag2].each { |tag| en_note_store.createTag(tag) } end it "adds a note for any payload it receives" do allow(en_note_store).to receive(:findNotesMetadata) { OpenStruct.new(notes: []) } Agents::EvernoteAgent.async_receive(@agent.id, [@event.id]) expect(en_note_store.notes.size).to eq(1) expect(en_note_store.notes.first.title).to eq("xkcd Survey") expect(en_note_store.notebooks.size).to eq(1) expect(en_note_store.tags.size).to eq(2) expect(@agent.events.count).to eq(1) expect(@agent.events.first.payload).to eq({ "title" => "xkcd Survey", "notebook" => "xkcd", "tags" => ["funny", "data"], "source" => nil, "source_url" => nil }) end context "a note with the same title and notebook exists" do before do note1 = OpenStruct.new(title: "xkcd Survey", notebookGuid: 1) note2 = OpenStruct.new(title: "Footprints", notebookGuid: 1) [note1, note2].each { |note| en_note_store.createNote(note) } en_note_store.createNotebook(OpenStruct.new(name: "xkcd")) allow(en_note_store).to receive(:findNotesMetadata) { OpenStruct.new(notes: [note1]) } end it "updates the existing note" do Agents::EvernoteAgent.async_receive(@agent.id, [@event.id]) expect(en_note_store.notes.size).to eq(2) expect(en_note_store.getNote(1).tagNames).to eq(["funny", "data"]) expect(@agent.events.count).to eq(1) end end context "include_xhtml_content is set to 'true'" do before do @agent.options[:include_xhtml_content] = "true" @agent.save! end it "creates an event with note content wrapped in ENML" do allow(en_note_store).to receive(:findNotesMetadata) { OpenStruct.new(notes: []) } Agents::EvernoteAgent.async_receive(@agent.id, [@event.id]) payload = @agent.events.first.payload expect(payload[:content]).to eq( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" \ "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">" \ "<en-note>The xkcd Survey: Big Data for a Big Planet</en-note>" ) end end end end describe "#check" do context "when mode is set to 'read'" do before do @options = { :mode => "read", :include_xhtml_content => "false", :expected_update_period_in_days => "2", :note => { :title => "", :content => "", :notebook => "xkcd", :tagNames => "funny, comic" } } @checker = Agents::EvernoteAgent.new(:name => "evernote reader", :options => @options) @checker.service = services(:generic) @checker.user = users(:bob) @checker.schedule = "every_2h" @checker.save! @checker.created_at = 1.minute.ago en_note_store.createNote( OpenStruct.new(title: "xkcd Survey", notebookGuid: 1, updated: 2.minutes.ago.to_i * 1000, tagNames: ["funny", "comic"]) ) en_note_store.createNotebook(OpenStruct.new(name: "xkcd")) tag1 = OpenStruct.new(name: "funny") tag2 = OpenStruct.new(name: "comic") [tag1, tag2].each { |tag| en_note_store.createTag(tag) } allow(en_note_store).to receive(:findNotesMetadata) { notes = en_note_store.notes.select do |note| note.notebookGuid == 1 && %w(funny comic).all? { |tag_name| note.tagNames.include?(tag_name) } end OpenStruct.new(notes: notes) } end context "the first time it checks" do it "returns only notes created/updated since it was created" do expect { @checker.check }.to change { Event.count }.by(0) end end context "on subsequent checks" do it "returns notes created/updated since the last time it checked" do expect { @checker.check }.to change { Event.count }.by(0) future_time = (Time.now + 1.minute).to_i * 1000 en_note_store.createNote( OpenStruct.new(title: "Footprints", notebookGuid: 1, tagNames: ["funny", "comic", "recent"], updated: future_time)) en_note_store.createNote( OpenStruct.new(title: "something else", notebookGuid: 2, tagNames: ["funny", "comic"], updated: future_time)) expect { @checker.check }.to change { Event.count }.by(1) end it "returns notes tagged since the last time it checked" do en_note_store.createNote( OpenStruct.new(title: "Footprints", notebookGuid: 1, tagNames: [], created: Time.now.to_i * 1000, updated: Time.now.to_i * 1000)) @checker.check en_note_store.getNote(2).tagNames = ["funny", "comic"] expect { @checker.check }.to change { Event.count }.by(1) end end end end describe "#validation" do before do @options = { :mode => "update", :include_xhtml_content => "false", :expected_update_period_in_days => "2", :note => { :title => "{{title}}", :content => "{{content}}", :notebook => "{{notebook}}", :tagNames => "{{tag1}}, {{tag2}}" } } @agent = Agents::EvernoteAgent.new(:name => "evernote updater", :options => @options) @agent.service = services(:generic) @agent.user = users(:bob) @agent.save! expect(@agent).to be_valid end it "requires the mode to be 'update' or 'read'" do @agent.options[:mode] = "" expect(@agent).not_to be_valid end context "mode is set to 'update'" do before do @agent.options[:mode] = "update" end it "requires some note parameter to be present" do @agent.options[:note].keys.each { |k| @agent.options[:note][k] = "" } expect(@agent).not_to be_valid end it "requires schedule to be 'never'" do @agent.schedule = 'never' expect(@agent).to be_valid @agent.schedule = 'every_1m' expect(@agent).not_to be_valid end end context "mode is set to 'read'" do before do @agent.options[:mode] = "read" end it "requires a schedule to be set" do @agent.schedule = 'every_1m' expect(@agent).to be_valid @agent.schedule = 'never' expect(@agent).not_to be_valid end end end # api wrapper classes describe Agents::EvernoteAgent::NoteStore do let(:note_store) { Agents::EvernoteAgent::NoteStore.new(en_note_store) } let(:note1) { OpenStruct.new(title: "first note") } let(:note2) { OpenStruct.new(title: "second note") } before do en_note_store.createNote(note1) en_note_store.createNote(note2) end describe "#create_note" do it "creates a note with given params in evernote note store" do note_store.create_note(title: "third note") expect(en_note_store.notes.size).to eq(3) expect(en_note_store.notes.last.title).to eq("third note") end it "returns a note" do expect(note_store.create_note(title: "third note")).to be_a(Agents::EvernoteAgent::Note) end end describe "#update_note" do it "updates an existing note with given params" do note_store.update_note(guid: 1, content: "some words") expect(en_note_store.notes.first.content).not_to be_nil expect(en_note_store.notes.size).to eq(2) end it "returns a note" do expect(note_store.update_note(guid: 1, content: "some words")).to be_a(Agents::EvernoteAgent::Note) end end describe "#find_note" do it "gets a note with the given guid" do note = note_store.find_note(2) expect(note.title).to eq("second note") expect(note).to be_a(Agents::EvernoteAgent::Note) end end describe "#find_tags" do let(:tag1) { OpenStruct.new(name: "tag1") } let(:tag2) { OpenStruct.new(name: "tag2") } let(:tag3) { OpenStruct.new(name: "tag3") } before do [tag1, tag2, tag3].each { |tag| en_note_store.createTag(tag) } end it "finds tags with the given guids" do expect(note_store.find_tags([1,3])).to eq([tag1, tag3]) end end describe "#find_notebook" do let(:notebook1) { OpenStruct.new(name: "notebook1") } let(:notebook2) { OpenStruct.new(name: "notebook2") } before do [notebook1, notebook2].each {|notebook| en_note_store.createNotebook(notebook)} end it "finds a notebook with given name" do expect(note_store.find_notebook(name: "notebook1")).to eq(notebook1) expect(note_store.find_notebook(name: "notebook3")).to be_nil end it "finds a notebook with a given guid" do expect(note_store.find_notebook(guid: 2)).to eq(notebook2) expect(note_store.find_notebook(guid: 3)).to be_nil end end describe "#create_or_update_note" do let(:notebook1) { OpenStruct.new(name: "first notebook")} before do en_note_store.createNotebook(notebook1) end context "a note with given title and notebook does not exist" do before do allow(en_note_store).to receive(:findNotesMetadata) { OpenStruct.new(notes: []) } end it "creates a note" do result = note_store.create_or_update_note(title: "third note", notebook: "first notebook") expect(result).to be_a(Agents::EvernoteAgent::Note) expect(en_note_store.getNote(3)).to_not be_nil end it "also creates the notebook if it does not exist" do note_store.create_or_update_note(title: "third note", notebook: "second notebook") expect(note_store.find_notebook(name: "second notebook")).to_not be_nil end end context "such a note does exist" do let(:note) { OpenStruct.new(title: "a note", notebookGuid: 1) } before do en_note_store.createNote(note) allow(en_note_store).to receive(:findNotesMetadata) { OpenStruct.new(notes: [note]) } end it "updates the note" do prior_note_count = en_note_store.notes.size result = note_store.create_or_update_note( title: "a note", notebook: "first notebook", content: "test content") expect(result).to be_a(Agents::EvernoteAgent::Note) expect(en_note_store.notes.size).to eq(prior_note_count) expect(en_note_store.getNote(3).content).to include("test content") end end end end describe Agents::EvernoteAgent::NoteStore::Search do let(:note_store) { Agents::EvernoteAgent::NoteStore.new(en_note_store) } let(:note1) { OpenStruct.new(title: "first note", notebookGuid: 1, tagNames: ["funny", "comic"], updated: Time.now) } let(:note2) { OpenStruct.new(title: "second note", tagNames: ["funny", "comic"], updated: Time.now) } let(:note3) { OpenStruct.new(title: "third note", notebookGuid: 1, updated: Time.now - 2.minutes) } let(:search) do Agents::EvernoteAgent::NoteStore::Search.new(note_store, { tagNames: ["funny", "comic"], notebook: "xkcd" }) end let(:search_with_time) do Agents::EvernoteAgent::NoteStore::Search.new(note_store, { notebook: "xkcd", last_checked_at: Time.now - 1.minute }) end let(:search_with_time_and_tags) do Agents::EvernoteAgent::NoteStore::Search.new(note_store, { notebook: "xkcd", tagNames: ["funny", "comic"], notes_with_tags: [1], last_checked_at: Time.now - 1.minute }) end before do en_note_store.createTag(OpenStruct.new(name: "funny")) en_note_store.createTag(OpenStruct.new(name: "comic")) en_note_store.createNotebook(OpenStruct.new(name: "xkcd")) [note1, note2, note3].each { |note| en_note_store.createNote(note) } end describe "#note_guids" do it "returns the guids of notes satisfying search options" do allow(en_note_store).to receive(:findNotesMetadata) { OpenStruct.new(notes: [note1]) } result = search.note_guids expect(result.size).to eq(1) expect(result.first).to eq(1) end end describe "#notes" do context "last_checked_at is not set" do it "returns notes satisfying the search options" do allow(en_note_store).to receive(:findNotesMetadata) { OpenStruct.new(notes: [note1]) } result = search.notes expect(result.size).to eq(1) expect(result.first.title).to eq("first note") expect(result.first).to be_a(Agents::EvernoteAgent::Note) end end context "last_checked_at is set" do context "notes_with_tags is not set" do it "only returns notes updated since then" do allow(en_note_store).to receive(:findNotesMetadata) { OpenStruct.new(notes: [note1, note3]) } result = search_with_time.notes expect(result.size).to eq(1) expect(result.first.title).to eq("first note") end end context "notes_with_tags is set" do it "returns notes updated since then or notes with recently added tags" do note3.tagNames = ["funny", "comic"] allow(en_note_store).to receive(:findNotesMetadata) { OpenStruct.new(notes: [note1, note3]) } result = search_with_time_and_tags.notes expect(result.size).to eq(2) expect(result.last.title).to eq("third note") end end end end describe "#create_filter" do it "builds an evernote search filter using search grammar" do filter = search.create_filter expect(filter.words).to eq("notebook:\"xkcd\" tag:funny tag:comic") end end end describe Agents::EvernoteAgent::Note do let(:resource) { OpenStruct.new(mime: "image/png", attributes: OpenStruct.new(sourceURL: "http://imgs.xkcd.com/comics/xkcd_survey.png", fileName: "xkcd_survey.png")) } let(:en_note_attributes) { OpenStruct.new(source: "web.clip", sourceURL: "http://xkcd.com/1572/") } let(:en_note) { OpenStruct.new(title: "xkcd Survey", tagNames: ["funny", "data"], content: "The xkcd Survey: Big Data for a Big Planet", attributes: en_note_attributes, resources: [resource]) } describe "#attr" do let(:note) { Agents::EvernoteAgent::Note.new(en_note, "xkcd", ["funny", "data"]) } context "when no option is set" do it "returns a hash with title, tags, notebook, source and source url" do expect(note.attr).to eq( { title: en_note.title, notebook: "xkcd", tags: ["funny", "data"], source: en_note.attributes.source, source_url: en_note.attributes.sourceURL } ) end end context "when include_content is set to true" do it "includes content" do note_attr = note.attr(include_content: true) expect(note_attr[:content]).to eq( "The xkcd Survey: Big Data for a Big Planet" ) end end context "when include_resources is set to true" do it "includes resources" do note_attr = note.attr(include_resources: true) expect(note_attr[:resources].first).to eq( { url: resource.attributes.sourceURL, name: resource.attributes.fileName, mime_type: resource.mime } ) end end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/email_digest_agent_spec.rb
spec/models/agents/email_digest_agent_spec.rb
require 'rails_helper' describe Agents::EmailDigestAgent do it_behaves_like EmailConcern def get_message_part(mail, content_type) mail.body.parts.find { |p| p.content_type.match content_type }.body.raw_source end before do @checker = Agents::EmailDigestAgent.new(:name => "something", :options => {:expected_receive_period_in_days => "2", :subject => "something interesting"}) @checker.user = users(:bob) @checker.save! @checker1 = Agents::EmailDigestAgent.new(:name => "something", :options => {:expected_receive_period_in_days => "2", :subject => "something interesting", :content_type => "text/plain"}) @checker1.user = users(:bob) @checker1.save! end after do ActionMailer::Base.deliveries = [] end describe "#receive" do it "queues any payloads it receives" do event1 = Event.new event1.agent = agents(:bob_rain_notifier_agent) event1.payload = {:data => "Something you should know about"} event1.save! event2 = Event.new event2.agent = agents(:bob_weather_agent) event2.payload = {:data => "Something else you should know about"} event2.save! Agents::EmailDigestAgent.async_receive(@checker.id, [event1.id, event2.id]) expect(@checker.reload.memory['events']).to match([event1.id, event2.id]) end end describe "#check" do it "should send an email" do Agents::EmailDigestAgent.async_check(@checker.id) expect(ActionMailer::Base.deliveries).to eq([]) payloads = [ {:data => "Something you should know about"}, {:title => "Foo", :url => "http://google.com", :bar => 2}, {"message" => "hi", :woah => "there"}, {"test" => 2} ] events = payloads.map do |payload| Event.new.tap do |event| event.agent = agents(:bob_weather_agent) event.payload = payload event.save! end end Agents::DigestAgent.async_receive(@checker.id, events.map(&:id)) @checker.sources << agents(:bob_weather_agent) Agents::DigestAgent.async_check(@checker.id) expect(ActionMailer::Base.deliveries.last.to).to eq(["bob@example.com"]) expect(ActionMailer::Base.deliveries.last.subject).to eq("something interesting") expect(get_message_part(ActionMailer::Base.deliveries.last, /plain/).strip).to eq("Event\n data: Something you should know about\n\nFoo\n bar: 2\n url: http://google.com\n\nhi\n woah: there\n\nEvent\n test: 2") expect(@checker.reload.memory[:events]).to be_empty end it "logs and re-raises mailer errors" do expect(SystemMailer).to receive(:send_message).with(anything) { raise Net::SMTPAuthenticationError.new("Wrong password") } @checker.memory[:events] = [1] @checker.save! expect { Agents::EmailDigestAgent.async_check(@checker.id) }.to raise_error(/Wrong password/) expect(@checker.reload.memory[:events]).not_to be_empty expect(@checker.logs.last.message).to match(/Error sending digest mail .* Wrong password/) end it "can receive complex events and send them on" do stub_request(:any, /pirateweather/).to_return(:body => File.read(Rails.root.join("spec/data_fixtures/weather.json")), :status => 200) @checker.sources << agents(:bob_weather_agent) Agent.async_check(agents(:bob_weather_agent).id) Agent.receive! expect(@checker.reload.memory[:events]).not_to be_empty Agents::EmailDigestAgent.async_check(@checker.id) plain_email_text = get_message_part(ActionMailer::Base.deliveries.last, /plain/).strip html_email_text = get_message_part(ActionMailer::Base.deliveries.last, /html/).strip expect(plain_email_text).to match(/avehumidity/) expect(html_email_text).to match(/avehumidity/) expect(@checker.reload.memory[:events]).to be_empty end it "should send email with correct content type" do Agents::EmailDigestAgent.async_check(@checker1.id) expect(ActionMailer::Base.deliveries).to eq([]) @checker1.memory[:events] = [1, 2, 3, 4] @checker1.save! Agents::EmailDigestAgent.async_check(@checker1.id) expect(ActionMailer::Base.deliveries.last.content_type).to eq("text/plain; charset=UTF-8") end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/read_file_agent_spec.rb
spec/models/agents/read_file_agent_spec.rb
require 'rails_helper' describe Agents::ReadFileAgent do before(:each) do @valid_params = { 'data_key' => 'data', } @checker = Agents::ReadFileAgent.new(:name => 'somename', :options => @valid_params) @checker.user = users(:jane) @checker.save! end it_behaves_like 'FileHandlingConsumer' context '#validate_options' do it 'is valid with the given options' do expect(@checker).to be_valid end it "requires data_key to be present" do @checker.options['data_key'] = '' expect(@checker).not_to be_valid end end context '#working' do it 'is not working without having received an event' do expect(@checker).not_to be_working end it 'is working after receiving an event without error' do @checker.last_receive_at = Time.now expect(@checker).to be_working end end context '#receive' do it "emits an event with the contents of the receives files" do event = Event.new(payload: {file_pointer: {agent_id: 111, file: 'test'}}) io_mock = double() expect(@checker).to receive(:get_io).with(event) { StringIO.new("testdata") } expect { @checker.receive([event]) }.to change(Event, :count).by(1) expect(Event.last.payload).to eq('data' => 'testdata') end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/key_value_store_agent_spec.rb
spec/models/agents/key_value_store_agent_spec.rb
require "rails_helper" describe Agents::KeyValueStoreAgent do let(:value_template) { "{{ _event_ | as_object }}" } let(:agent) do Agents::KeyValueStoreAgent.create!( name: "somename", options: { key: "{{ id }}", value: value_template, variable: "kvs", max_keys: 3, }, user: users(:jane) ) end let(:source_agent) do agents(:jane_weather_agent) end def create_event(payload) source_agent.events.create!(payload:) end let(:events) do [ create_event({ id: 1, name: "foo" }), create_event({ id: 2, name: "bar" }), create_event({ id: 3, name: "baz" }), create_event({ id: 1, name: "FOO" }), create_event({ id: 4, name: "quux" }), ] end describe "validation" do before do expect(agent).to be_valid end it "should validate key" do # empty key is OK agent.options[:key] = "" expect(agent).to be_valid agent.options.delete(:key) expect(agent).not_to be_valid end it "should validate value" do agent.options[:value] = "" expect(agent).to be_valid agent.options.delete(:value) expect(agent).not_to be_valid end it "should validate variable" do agent.options[:variable] = "1abc" expect(agent).not_to be_valid agent.options[:variable] = "" expect(agent).not_to be_valid agent.options[:variable] = {} expect(agent).not_to be_valid agent.options.delete(:variable) expect(agent).not_to be_valid end it "should validate max_keys" do agent.options.delete(:max_keys) expect(agent).to be_valid expect(agent.max_keys).to eq 100 agent.options[:max_keys] = 0 expect(agent).not_to be_valid end end describe "#receive" do it "receives and updates the storage" do agent.receive(events[0..2]) expect(agent.reload.memory).to match( { "1" => { id: 1, name: "foo" }, "2" => { id: 2, name: "bar" }, "3" => { id: 3, name: "baz" }, } ) agent.receive([events[3]]) expect(agent.reload.memory).to match( { "1" => { id: 1, name: "FOO" }, "2" => { id: 2, name: "bar" }, "3" => { id: 3, name: "baz" }, } ) agent.receive([events[4]]) # The key "bar" should have been removed because it is the oldest. expect(agent.reload.memory).to match( { "1" => { id: 1, name: "FOO" }, "3" => { id: 3, name: "baz" }, "4" => { id: 4, name: "quux" }, } ) expect { agent.receive([create_event({ name: "empty key" })]) }.not_to(change { agent.reload.memory }) end describe "empty value" do let(:value_template) { "{{ name | as_object }}" } it "deletes the key" do agent.receive(events[0..2]) expect(agent.reload.memory).to match( { "1" => "foo", "2" => "bar", "3" => "baz", } ) agent.receive([create_event({ id: 1, name: "" })]) expect(agent.reload.memory).to match( { "2" => "bar", "3" => "baz", } ) agent.receive([create_event({ id: 2, name: [] })]) expect(agent.reload.memory).to match( { "3" => "baz", } ) agent.receive([create_event({ id: 3, name: {} })]) expect(agent.reload.memory).to eq({}) end end describe "using _value_" do let(:value_template) { "{% if _value_ %}{{ _value_ }}, {% endif %}{{ name }}" } it "represents the existing value" do agent.receive(events[0..2]) expect(agent.reload.memory).to match( { "1" => "foo", "2" => "bar", "3" => "baz", } ) agent.receive([events[3]]) expect(agent.reload.memory).to match( { "1" => "foo, FOO", "2" => "bar", "3" => "baz", } ) end end end describe "control target" do let(:value_template) { "{{ name }}" } before do agent.receive(events[0..2]) end let!(:target_agent) do agents(:jane_website_agent).tap { |target_agent| target_agent.options[:url] = "https://example.com/{{ kvs['3'] }}" target_agent.controllers << agent target_agent.save! } end it "can refer to the storage" do expect(target_agent.interpolated[:url]).to eq "https://example.com/baz" end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/weibo_user_agent_spec.rb
spec/models/agents/weibo_user_agent_spec.rb
# encoding: utf-8 require 'rails_helper' describe Agents::WeiboUserAgent do before do # intercept the twitter API request for @tectonic's user profile stub_request(:any, /api.weibo.com/).to_return(:body => File.read(Rails.root.join("spec/data_fixtures/one_weibo.json")), :status => 200) @opts = { :uid => "123456", :expected_update_period_in_days => "2", :app_key => "asdfe", :app_secret => "asdfe", :access_token => "asdfe" } @checker = Agents::WeiboUserAgent.new(:name => "123456 fetcher", :options => @opts) @checker.user = users(:bob) @checker.save! end describe "#check" do it "should check for changes" do expect { @checker.check }.to change { Event.count }.by(1) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/pushover_agent_spec.rb
spec/models/agents/pushover_agent_spec.rb
require 'rails_helper' describe Agents::PushoverAgent do before do @checker = Agents::PushoverAgent.new(name: 'Some Name', options: { token: 'x', user: 'x', message: "{{ message | default: text | default: 'Some Message' }}", device: "{{ device | default: 'Some Device' }}", title: "{{ title | default: 'Some Message Title' }}", url: "{{ url | default: 'http://someurl.com' }}", url_title: "{{ url_title | default: 'Some Url Title' }}", priority: "{{ priority | default: 0 }}", timestamp: "{{ timestamp | default: 'false' }}", sound: "{{ sound | default: 'pushover' }}", retry: "{{ retry | default: 0 }}", expire: "{{ expire | default: 0 }}", expected_receive_period_in_days: '1' }) @checker.user = users(:bob) @checker.save! @event = Event.new @event.agent = agents(:bob_weather_agent) @event.payload = { message: 'Looks like its going to rain' } @event.save! @sent_notifications = [] allow_any_instance_of(Agents::PushoverAgent).to receive(:send_notification) { |agent, notification| @sent_notifications << notification } end describe '#receive' do it 'should make sure multiple events are being received' do event1 = Event.new event1.agent = agents(:bob_rain_notifier_agent) event1.payload = { message: 'Some message' } event1.save! event2 = Event.new event2.agent = agents(:bob_weather_agent) event2.payload = { message: 'Some other message' } event2.save! @checker.receive([@event,event1,event2]) expect(@sent_notifications[0]['message']).to eq('Looks like its going to rain') expect(@sent_notifications[1]['message']).to eq('Some message') expect(@sent_notifications[2]['message']).to eq('Some other message') end it 'should make sure event message overrides default message' do event = Event.new event.agent = agents(:bob_rain_notifier_agent) event.payload = { message: 'Some new message'} event.save! @checker.receive([event]) expect(@sent_notifications[0]['message']).to eq('Some new message') end it 'should make sure event text overrides default message' do event = Event.new event.agent = agents(:bob_rain_notifier_agent) event.payload = { text: 'Some new text'} event.save! @checker.receive([event]) expect(@sent_notifications[0]['message']).to eq('Some new text') end it 'should make sure event title overrides default title' do event = Event.new event.agent = agents(:bob_rain_notifier_agent) event.payload = { message: 'Some message', title: 'Some new title' } event.save! @checker.receive([event]) expect(@sent_notifications[0]['title']).to eq('Some new title') end it 'should make sure event url overrides default url' do event = Event.new event.agent = agents(:bob_rain_notifier_agent) event.payload = { message: 'Some message', url: 'Some new url' } event.save! @checker.receive([event]) expect(@sent_notifications[0]['url']).to eq('Some new url') end it 'should make sure event url_title overrides default url_title' do event = Event.new event.agent = agents(:bob_rain_notifier_agent) event.payload = { message: 'Some message', url_title: 'Some new url_title' } event.save! @checker.receive([event]) expect(@sent_notifications[0]['url_title']).to eq('Some new url_title') end it 'should make sure event priority overrides default priority' do event = Event.new event.agent = agents(:bob_rain_notifier_agent) event.payload = { message: 'Some message', priority: '1' } event.save! @checker.receive([event]) expect(@sent_notifications[0]['priority']).to eq('1') end it 'should make sure event timestamp overrides default timestamp' do event = Event.new event.agent = agents(:bob_rain_notifier_agent) event.payload = { message: 'Some message', timestamp: 'false' } event.save! @checker.receive([event]) expect(@sent_notifications[0]['timestamp']).to eq('false') end it 'should make sure event sound overrides default sound' do event = Event.new event.agent = agents(:bob_rain_notifier_agent) event.payload = { message: 'Some message', sound: 'Some new sound' } event.save! @checker.receive([event]) expect(@sent_notifications[0]['sound']).to eq('Some new sound') end it 'should make sure event retry overrides default retry' do event = Event.new event.agent = agents(:bob_rain_notifier_agent) event.payload = { message: 'Some message', retry: 1 } event.save! @checker.receive([event]) expect(@sent_notifications[0]['retry']).to eq('1') end it 'should make sure event expire overrides default expire' do event = Event.new event.agent = agents(:bob_rain_notifier_agent) event.payload = { message: 'Some message', expire: '60' } event.save! @checker.receive([event]) expect(@sent_notifications[0]['expire']).to eq('60') end end describe '#working?' do it 'checks if events have been received within the expected receive period' do # No events received expect(@checker).not_to be_working Agents::PushoverAgent.async_receive @checker.id, [@event.id] # Just received events expect(@checker.reload).to be_working two_days_from_now = 2.days.from_now allow(Time).to receive(:now) { two_days_from_now } # More time has passed than the expected receive period without any new events expect(@checker.reload).not_to be_working end end describe "validation" do before do expect(@checker).to be_valid end it "should validate presence of token" do @checker.options[:token] = "" expect(@checker).not_to be_valid end it "should validate presence of user" do @checker.options[:user] = "" expect(@checker).not_to be_valid end it "should validate presence of expected_receive_period_in_days" do @checker.options[:expected_receive_period_in_days] = "" expect(@checker).not_to be_valid end it "should make sure device is optional" do @checker.options[:device] = "" expect(@checker).to be_valid end it "should make sure title is optional" do @checker.options[:title] = "" expect(@checker).to be_valid end it "should make sure url is optional" do @checker.options[:url] = "" expect(@checker).to be_valid end it "should make sure url_title is optional" do @checker.options[:url_title] = "" expect(@checker).to be_valid end it "should make sure priority is optional" do @checker.options[:priority] = "" expect(@checker).to be_valid end it "should make sure timestamp is optional" do @checker.options[:timestamp] = "" expect(@checker).to be_valid end it "should make sure sound is optional" do @checker.options[:sound] = "" expect(@checker).to be_valid end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agents/stubhub_agent_spec.rb
spec/models/agents/stubhub_agent_spec.rb
require 'rails_helper' describe Agents::StubhubAgent do let(:name) { 'Agent Name' } let(:url) { 'https://www.stubhub.com/event/name-1-1-2014-12345' } let(:parsed_body) { JSON.parse(body)['response']['docs'][0] } let(:valid_params) { { 'url' => parsed_body['url'] } } let(:body) { File.read(Rails.root.join('spec/data_fixtures/stubhub_data.json')) } let(:stubhub_event_id) { 12345 } let(:response_payload) { { 'url' => url, 'name' => parsed_body['seo_description_en_US'], 'date' => parsed_body['event_date_local'], 'max_price' => parsed_body['maxPrice'], 'min_price' => parsed_body['minPrice'], 'total_postings' => parsed_body['totalPostings'], 'total_tickets' => parsed_body['totalTickets'], 'venue_name' => parsed_body['venue_name'] } } before do stub_request(:get, "https://www.stubhub.com/listingCatalog/select/?q=%2B%20stubhubDocumentType:event%0D%0A%2B%20event_id:#{stubhub_event_id}%0D%0A&rows=10&start=0&wt=json"). to_return(:status => 200, :body => body, :headers => {}) @stubhub_agent = described_class.new(name: name, options: valid_params) @stubhub_agent.user = users(:jane) @stubhub_agent.save! end describe "#check" do it 'should create an event' do expect { @stubhub_agent.check }.to change { Event.count }.by(1) end it 'should properly parse the response' do event = @stubhub_agent.check expect(event.payload).to eq(response_payload) end end describe "validations" do before do expect(@stubhub_agent).to be_valid end it "should require a url" do @stubhub_agent.options['url'] = nil expect(@stubhub_agent).not_to be_valid end end describe "#working?" do it "checks if events have been received within the expected receive period" do expect(@stubhub_agent).not_to be_working Agents::StubhubAgent.async_check @stubhub_agent.id expect(@stubhub_agent.reload).to be_working two_days_from_now = 2.days.from_now allow(Time).to receive(:now) { two_days_from_now } expect(@stubhub_agent.reload).not_to be_working end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/features/form_configurable_feature_spec.rb
spec/features/form_configurable_feature_spec.rb
require 'capybara_helper' describe "form configuring agents", js: true do it 'completes fields with predefined array values' do login_as(users(:bob)) visit edit_agent_path(agents(:bob_csv_agent)) check('Propagate immediately') select2("serialize", from: "Mode", match: :first) end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/features/scenario_import_spec.rb
spec/features/scenario_import_spec.rb
require 'rails_helper' describe ScenarioImportsController do let(:user) { users(:bob) } before do login_as(user) end it 'renders the import form' do visit new_scenario_imports_path expect(page).to have_text('Import a Public Scenario') end it 'requires a URL or file uplaod' do visit new_scenario_imports_path click_on 'Start Import' expect(page).to have_text('Please provide either a Scenario JSON File or a Public Scenario URL.') end it 'imports a scenario that does not exist yet' do visit new_scenario_imports_path attach_file('Option 2: Upload a Scenario JSON File', File.join(Rails.root, 'data/default_scenario.json')) click_on 'Start Import' expect(page).to have_text('This scenario has a few agents to get you started. Feel free to change them or delete them as you see fit!') expect(page).not_to have_text('This Scenario already exists in your system.') check('I confirm that I want to import these Agents.') click_on 'Finish Import' expect(page).to have_text('Import successful!') end it 'asks to accept conflicts when the scenario was modified' do DefaultScenarioImporter.seed(user) agent = user.agents.where(name: 'Rain Notifier').first agent.options['expected_receive_period_in_days'] = 9001 agent.save! visit new_scenario_imports_path attach_file('Option 2: Upload a Scenario JSON File', File.join(Rails.root, 'data/default_scenario.json')) click_on 'Start Import' expect(page).to have_text('This Scenario already exists in your system.') expect(page).to have_text('9001') check('I confirm that I want to import these Agents.') click_on 'Finish Import' expect(page).to have_text('Import successful!') end it 'imports a scenario which requires a service' do visit new_scenario_imports_path attach_file('Option 2: Upload a Scenario JSON File', File.join(Rails.root, 'spec/data_fixtures/twitter_scenario.json')) click_on 'Start Import' check('I confirm that I want to import these Agents.') expect { click_on 'Finish Import' }.to change(Scenario, :count).by(1) expect(page).to have_text('Import successful!') end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/features/admin_users_spec.rb
spec/features/admin_users_spec.rb
require 'rails_helper' describe Admin::UsersController do it "requires to be signed in as an admin" do login_as(users(:bob)) visit admin_users_path expect(page).to have_text('Admin access required to view that page.') end context "as an admin" do before :each do login_as(users(:jane)) end it "lists all users" do visit admin_users_path expect(page).to have_text('bob') expect(page).to have_text('jane') end it "allows to delete a user" do visit admin_users_path find(:css, "a[href='/admin/users/#{users(:bob).id}']").click expect(page).to have_text("User 'bob' was deleted.") expect(page).to have_no_text('bob@example.com') end context "creating new users" do it "follow the 'new user' link" do visit admin_users_path click_on('New User') expect(page).to have_text('Create new User') end it "creates a new user" do visit new_admin_user_path fill_in 'Email', with: 'test@test.com' fill_in 'Username', with: 'usertest' fill_in 'Password', with: '12345678' fill_in 'Password confirmation', with: '12345678' click_on 'Create User' expect(page).to have_text("User 'usertest' was successfully created.") expect(page).to have_text('test@test.com') end it "requires the passwords to match" do visit new_admin_user_path fill_in 'Email', with: 'test@test.com' fill_in 'Username', with: 'usertest' fill_in 'Password', with: '12345678' fill_in 'Password confirmation', with: 'no_match' click_on 'Create User' expect(page).to have_text("Password confirmation doesn't match") end end context "updating existing users" do it "follows the edit link" do visit admin_users_path click_on('bob') expect(page).to have_text('Edit User') end it "updates an existing user" do visit edit_admin_user_path(users(:bob)) check 'Admin' click_on 'Update User' expect(page).to have_text("User 'bob' was successfully updated.") visit edit_admin_user_path(users(:bob)) expect(page).to have_checked_field('Admin') end it "requires the passwords to match when changing them" do visit edit_admin_user_path(users(:bob)) fill_in 'Password', with: '12345678' fill_in 'Password confirmation', with: 'no_match' click_on 'Update User' expect(page).to have_text("Password confirmation doesn't match") end end context "(de)activating users" do it "does not show deactivation buttons for the current user" do visit admin_users_path expect(page).to have_no_css("a[href='/admin/users/#{users(:jane).id}/deactivate']") end it "deactivates an existing user" do visit admin_users_path expect(page).to have_no_text('inactive') find(:css, "a[href='/admin/users/#{users(:bob).id}/deactivate']").click expect(page).to have_text('inactive') users(:bob).reload expect(users(:bob)).not_to be_active end it "activates an existing user" do users(:bob).deactivate! visit admin_users_path find(:css, "a[href='/admin/users/#{users(:bob).id}/activate']").click expect(page).to have_no_text('inactive') users(:bob).reload expect(users(:bob)).to be_active end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/features/create_an_agent_spec.rb
spec/features/create_an_agent_spec.rb
require 'rails_helper' describe "Creating a new agent", js: true do before(:each) do login_as(users(:bob)) end it "creates an agent" do visit "/" page.find("a", text: "Agents").hover click_on("New Agent") select_agent_type("Trigger Agent") fill_in(:agent_name, with: "Test Trigger Agent") click_on "Save" expect(page).to have_text("Test Trigger Agent") end context "with associated agents" do let!(:bob_scheduler_agent) { Agents::SchedulerAgent.create!( user: users(:bob), name: 'Example Scheduler', options: { 'action' => 'run', 'schedule' => '0 * * * *' }, ) } let!(:bob_weather_agent) { agents(:bob_weather_agent) } let!(:bob_formatting_agent) { agents(:bob_formatting_agent).tap { |agent| # Make this valid agent.options['instructions']['foo'] = 'bar' agent.save! } } it "creates an agent with a source and a receiver" do visit "/" page.find("a", text: "Agents").hover click_on("New Agent") select_agent_type("Trigger Agent") fill_in(:agent_name, with: "Test Trigger Agent") select2("SF Weather", from: 'Sources') select2("Formatting Agent", from: 'Receivers') click_on "Save" expect(page).to have_text("Test Trigger Agent") agent = Agent.find_by(name: "Test Trigger Agent") expect(agent.sources).to eq([bob_weather_agent]) expect(agent.receivers).to eq([bob_formatting_agent]) end it "creates an agent with a control target" do visit "/" page.find("a", text: "Agents").hover click_on("New Agent") select_agent_type("Scheduler Agent") fill_in(:agent_name, with: "Test Scheduler Agent") select2("SF Weather", from: 'Control targets') click_on "Save" expect(page).to have_text("Test Scheduler Agent") agent = Agent.find_by(name: "Test Scheduler Agent") expect(agent.control_targets).to eq([bob_weather_agent]) end it "creates an agent with a controller" do visit "/" page.find("a", text: "Agents").hover click_on("New Agent") select_agent_type("Weather Agent") fill_in(:agent_name, with: "Test Weather Agent") select2("Example Scheduler", from: 'Controllers') click_on "Save" expect(page).to have_text("Test Weather Agent") agent = Agent.find_by(name: "Test Weather Agent") expect(agent.controllers).to eq([bob_scheduler_agent]) end end it "creates an alert if a new agent with invalid json is submitted" do visit "/" page.find("a", text: "Agents").hover click_on("New Agent") select_agent_type("Trigger Agent") fill_in(:agent_name, with: "Test Trigger Agent") click_on("Toggle View") fill_in(:agent_options, with: '{ "expected_receive_period_in_days": "2" "keep_event": "false" }') expect(get_alert_text_from { click_on "Save" }).to have_text("Sorry, there appears to be an error in your JSON input. Please fix it before continuing.") end context "displaying the correct information" do before(:each) do visit new_agent_path end it "shows all options for agents that can be scheduled, create and receive events" do select_agent_type("Website Agent scrapes") expect(page).not_to have_content('This type of Agent cannot create events.') end it "does not show the target select2 field when the agent can not create events" do select_agent_type("Email Agent") expect(page).to have_content('This type of Agent cannot create events.') end end it "allows to click on on the agent name in select2 tags" do visit new_agent_path select_agent_type("Website Agent scrapes") select2("SF Weather", from: 'Sources') click_on "SF Weather" expect(page).to have_content "Editing your WeatherAgent" end context "clearing unsupported fields of agents" do before do visit new_agent_path end it "does not send previously configured sources when the current agent does not support them" do select_agent_type("Website Agent scrapes") select2("SF Weather", from: 'Sources') select_agent_type("Webhook Agent") fill_in(:agent_name, with: "No sources") click_on "Save" expect(page).to have_content("No sources") agent = Agent.find_by(name: "No sources") expect(agent.sources).to eq([]) end it "does not send previously configured control targets when the current agent does not support them" do select_agent_type("Commander Agent") select2("SF Weather", from: 'Control targets') select_agent_type("Webhook Agent") fill_in(:agent_name, with: "No control targets") click_on "Save" expect(page).to have_content("No control targets") agent = Agent.find_by(name: "No control targets") expect(agent.control_targets).to eq([]) end it "does not send previously configured receivers when the current agent does not support them" do select_agent_type("Website Agent scrapes") sleep 0.5 select2("ZKCD", from: 'Receivers') select_agent_type("Email Agent") fill_in(:agent_name, with: "No receivers") click_on "Save" expect(page).to have_content("No receivers") agent = Agent.find_by(name: "No receivers") expect(agent.receivers).to eq([]) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/features/undefined_agents_spec.rb
spec/features/undefined_agents_spec.rb
require 'capybara_helper' describe "handling undefined agents" do before do login_as(users(:bob)) agent = agents(:bob_website_agent) agent.update_attribute(:type, 'Agents::UndefinedAgent') end it 'renders the error page' do visit agents_path expect(page).to have_text("Error: Agent(s) are 'missing in action'") expect(page).to have_text('Undefined Agent') end it 'deletes all undefined agents' do visit agents_path click_on('Delete Missing Agents') expect(page).to have_text('Your Agents') end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/features/edit_an_agent_spec.rb
spec/features/edit_an_agent_spec.rb
require 'rails_helper' describe "Editing an agent", js: true do it "creates an alert if a agent with invalid json is submitted" do login_as(users(:bob)) visit("/agents/#{agents(:bob_website_agent).id}/edit") click_on("Toggle View") fill_in(:agent_options, with: '{ "expected_receive_period_in_days": "2" "keep_event": "false" }') expect(get_alert_text_from { click_on "Save" }).to have_text("Sorry, there appears to be an error in your JSON input. Please fix it before continuing.") end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/features/dry_running_spec.rb
spec/features/dry_running_spec.rb
require 'rails_helper' describe "Dry running an Agent", js: true do let(:agent) { agents(:bob_website_agent) } let(:formatting_agent) { agents(:bob_formatting_agent) } let(:user) { users(:bob) } let(:emitter) { agents(:bob_weather_agent) } before(:each) do login_as(user) end def open_dry_run_modal(agent) visit edit_agent_path(agent) click_on("Dry Run") expect(page).to have_text('Event to send') end context 'successful dry runs' do before do stub_request(:get, "http://xkcd.com/"). with(:headers => {'Accept-Encoding'=>'gzip,deflate', 'User-Agent'=>'Huginn - https://github.com/huginn/huginn'}). to_return(:status => 200, :body => File.read(Rails.root.join("spec/data_fixtures/xkcd.html")), :headers => {}) end it 'opens the dry run modal even when clicking on the refresh icon' do visit edit_agent_path(agent) find('.agent-dry-run-button span.glyphicon').click expect(page).to have_text('Event to send (Optional)') end it 'shows the dry run pop up without previous events and selects the events tab when a event was created' do open_dry_run_modal(agent) click_on("Dry Run") expect(page).to have_text('Biologists play reverse') expect(page).to have_selector(:css, 'li[role="presentation"].active a[href="#tabEvents"]') end it 'shows the dry run pop up with previous events and allows use previously received event' do emitter.events << Event.new(payload: {url: "http://xkcd.com/"}) agent.sources << emitter agent.options.merge!('url' => '', 'url_from_event' => '{{url}}') agent.save! open_dry_run_modal(agent) find('.dry-run-event-sample').click within(:css, '.modal .builder') do expect(page).to have_text('http://xkcd.com/') end click_on("Dry Run") expect(page).to have_text('Biologists play reverse') expect(page).to have_selector(:css, 'li[role="presentation"].active a[href="#tabEvents"]') end it 'sends escape characters correctly to the backend' do emitter.events << Event.new(payload: {data: "Line 1\nLine 2\nLine 3"}) formatting_agent.sources << emitter formatting_agent.options.merge!('instructions' => {'data' => "{{data | newline_to_br | strip_newlines | split: '<br />' | join: ','}}"}) formatting_agent.save! open_dry_run_modal(formatting_agent) find('.dry-run-event-sample').click within(:css, '.modal .builder') do expect(page).to have_text('Line 1\nLine 2\nLine 3') end click_on("Dry Run") expect(page).to have_text('Line 1,Line 2,Line 3') expect(page).to have_selector(:css, 'li[role="presentation"].active a[href="#tabEvents"]') end end it 'shows the dry run pop up without previous events and selects the log tab when no event was created' do stub_request(:get, "http://xkcd.com/"). with(:headers => {'Accept-Encoding'=>'gzip,deflate', 'User-Agent'=>'Huginn - https://github.com/huginn/huginn'}). to_return(:status => 200, :body => "", :headers => {}) open_dry_run_modal(agent) click_on("Dry Run") expect(page).to have_text('Dry Run started') expect(page).to have_selector(:css, 'li[role="presentation"].active a[href="#tabLog"]') end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/features/toggle_visibility_of_disabled_agents.rb
spec/features/toggle_visibility_of_disabled_agents.rb
require 'capybara_helper' describe "Toggling the visibility of an agent", js: true do it "hides them if they are disabled" do login_as(users(:bob)) visit("/agents") expect { click_on("Show/Hide Disabled Agents") }.to change{ find_all(".table-striped tr").count }.by(-1) end it "shows them when they are hidden" do login_as(users(:bob)) visit("/agents") click_on("Show/Hide Disabled Agents") expect { click_on("Show/Hide Disabled Agents") }.to change{ find_all(".table-striped tr").count }.by(1) end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/migrations/20161124061256_convert_website_agent_template_for_merge_spec.rb
spec/migrations/20161124061256_convert_website_agent_template_for_merge_spec.rb
load 'spec/rails_helper.rb' load File.join('db/migrate', File.basename(__FILE__, '_spec.rb') + '.rb') describe ConvertWebsiteAgentTemplateForMerge do let :old_extract do { 'url' => { 'css' => "#comic img", 'value' => "@src" }, 'title' => { 'css' => "#comic img", 'value' => "@alt" }, 'hovertext' => { 'css' => "#comic img", 'value' => "@title" } } end let :new_extract do { 'url' => { 'css' => "#comic img", 'value' => "@src" }, 'title' => { 'css' => "#comic img", 'value' => "@alt" }, 'hovertext' => { 'css' => "#comic img", 'value' => "@title", 'hidden' => true } } end let :reverted_extract do old_extract end let :old_template do { 'url' => '{{url}}', 'title' => '{{ title }}', 'description' => '{{ hovertext }}', 'comment' => '{{ comment }}' } end let :new_template do { 'description' => '{{ hovertext }}', 'comment' => '{{ comment }}' } end let :reverted_template do old_template.merge('url' => '{{ url }}') end let :valid_options do { 'name' => "XKCD", 'expected_update_period_in_days' => "2", 'type' => "html", 'url' => "{{ url | default: 'http://xkcd.com/' }}", 'mode' => 'on_change', 'extract' => old_extract, 'template' => old_template } end let :agent do Agents::WebsiteAgent.create!( user: users(:bob), name: "xkcd", options: valid_options, keep_events_for: 2.days ) end describe 'up' do it 'should update extract and template options for an existing WebsiteAgent' do expect(agent.options).to include('extract' => old_extract, 'template' => old_template) ConvertWebsiteAgentTemplateForMerge.new.up agent.reload expect(agent.options).to include('extract' => new_extract, 'template' => new_template) end end describe 'down' do let :valid_options do super().merge('extract' => new_extract, 'template' => new_template) end it 'should revert extract and template options for an updated WebsiteAgent' do expect(agent.options).to include('extract' => new_extract, 'template' => new_template) ConvertWebsiteAgentTemplateForMerge.new.down agent.reload expect(agent.options).to include('extract' => reverted_extract, 'template' => reverted_template) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/migrations/20161124065838_add_templates_to_resolve_url_spec.rb
spec/migrations/20161124065838_add_templates_to_resolve_url_spec.rb
load 'spec/rails_helper.rb' load File.join('db/migrate', File.basename(__FILE__, '_spec.rb') + '.rb') describe AddTemplatesToResolveUrl do let :valid_options do { 'name' => "XKCD", 'expected_update_period_in_days' => "2", 'type' => "html", 'url' => "http://xkcd.com", 'mode' => 'on_change', 'extract' => { 'url' => { 'css' => "#comic img", 'value' => "@src" }, 'title' => { 'css' => "#comic img", 'value' => "@alt" }, 'hovertext' => { 'css' => "#comic img", 'value' => "@title" } } } end let :agent do Agents::WebsiteAgent.create!( user: users(:bob), name: "xkcd", options: valid_options, keep_events_for: 2.days ) end it 'should add a template for an existing WebsiteAgent with `url`' do expect(agent.options).not_to include('template') AddTemplatesToResolveUrl.new.up agent.reload expect(agent.options).to include( 'template' => { 'url' => '{{ url | to_uri: _response_.url }}' } ) end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/lib/gemfile_helper_spec.rb
spec/lib/gemfile_helper_spec.rb
require 'rails_helper' describe GemfileHelper do context 'parse_each_agent_gem' do VALID_STRINGS = [ ['huginn_nlp_agents(~> 0.2.1)', [ ['huginn_nlp_agents', '~> 0.2.1'] ]], ['huginn_nlp_agents(~> 0.2.1, git: http://github.com/dsander/huginn.git, branch: agents_in_gems)', [['huginn_nlp_agents', '~> 0.2.1', git: 'http://github.com/dsander/huginn.git', branch: 'agents_in_gems']] ], ['huginn_nlp_agents(~> 0.2.1, git: http://github.com/dsander/huginn.git, ref: 2342asdab) , huginn_nlp_agents(~> 0.2.1)', [ ['huginn_nlp_agents', '~> 0.2.1', git: 'http://github.com/dsander/huginn.git', ref: '2342asdab'], ['huginn_nlp_agents', '~> 0.2.1'] ]], ['huginn_nlp_agents(~> 0.2.1, path: /tmp/test)', [ ['huginn_nlp_agents', '~> 0.2.1', path: '/tmp/test'] ]], ['huginn_nlp_agents', [ ['huginn_nlp_agents'] ]], ['huginn_nlp_agents, test(0.1), test2(github: test2/huginn_test)', [ ['huginn_nlp_agents'], ['test', '0.1'], ['test2', github: 'test2/huginn_test'] ]], ['huginn_nlp_agents(git: http://github.com/dsander/huginn.git, ref: 2342asdab)', [ ['huginn_nlp_agents', git: 'http://github.com/dsander/huginn.git', ref: '2342asdab'] ]], ] it 'parses valid gem strings correctly' do VALID_STRINGS.each do |string, outcomes| GemfileHelper.parse_each_agent_gem(string) do |args| expect(args).to eq(outcomes.shift) end end end it 'does nothing when nil is passed' do expect { |b| GemfileHelper.parse_each_agent_gem(nil, &b) }.not_to yield_control end it 'does nothing when an empty string is passed' do expect { |b| GemfileHelper.parse_each_agent_gem('', &b) }.not_to yield_control end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/lib/delayed_job_worker_spec.rb
spec/lib/delayed_job_worker_spec.rb
require 'rails_helper' describe DelayedJobWorker do before do @djw = DelayedJobWorker.new end it "should run" do expect_any_instance_of(Delayed::Worker).to receive(:start) @djw.run end it "should stop" do expect_any_instance_of(Delayed::Worker).to receive(:start) @djw.run expect_any_instance_of(Delayed::Worker).to receive(:stop) @djw.stop end context "#setup_worker" do it "should return an array with an instance of itself" do workers = DelayedJobWorker.setup_worker expect(workers).to be_a(Array) expect(workers.first).to be_a(DelayedJobWorker) expect(workers.first.id).to eq('DelayedJobWorker') end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/lib/time_tracker_spec.rb
spec/lib/time_tracker_spec.rb
require 'rails_helper' describe TimeTracker do describe "#track" do it "tracks execution time" do tracked_result = TimeTracker.track { sleep(0.01) } expect(tracked_result.elapsed_time).to satisfy {|v| v > 0.01 && v < 0.1} end it "returns the proc return value" do tracked_result = TimeTracker.track { 42 } expect(tracked_result.result).to eq(42) end it "returns an object that behaves like the proc result" do tracked_result = TimeTracker.track { 42 } expect(tracked_result.to_i).to eq(42) expect(tracked_result + 1).to eq(43) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/lib/liquid_migrator_spec.rb
spec/lib/liquid_migrator_spec.rb
require 'rails_helper' describe LiquidMigrator do describe "converting JSONPath strings" do it "should work" do expect(LiquidMigrator.convert_string("$.data", true)).to eq("{{data}}") expect(LiquidMigrator.convert_string("$.data.test", true)).to eq("{{data.test}}") expect(LiquidMigrator.convert_string("$first_title", true)).to eq("{{first_title}}") end it "should ignore strings which just contain a JSONPath" do expect(LiquidMigrator.convert_string("$.data")).to eq("$.data") expect(LiquidMigrator.convert_string("$first_title")).to eq("$first_title") expect(LiquidMigrator.convert_string(" $.data", true)).to eq(" $.data") expect(LiquidMigrator.convert_string("lorem $.data", true)).to eq("lorem $.data") end it "should raise an exception when encountering complex JSONPaths" do expect { LiquidMigrator.convert_string("$.data.test.*", true) }. to raise_error("JSONPath '$.data.test.*' is too complex, please check your migration.") end end describe "converting escaped JSONPath strings" do it "should work" do expect(LiquidMigrator.convert_string("Weather looks like <$.conditions> according to the forecast at <$.pretty_date.time>")).to eq( "Weather looks like {{conditions}} according to the forecast at {{pretty_date.time}}" ) end it "should convert the 'escape' method correctly" do expect(LiquidMigrator.convert_string("Escaped: <escape $.content.name>\nNot escaped: <$.content.name>")).to eq( "Escaped: {{content.name | uri_escape}}\nNot escaped: {{content.name}}" ) end it "should raise an exception when encountering complex JSONPaths" do expect { LiquidMigrator.convert_string("Received <$.content.text.*> from <$.content.name> .") }. to raise_error("JSONPath '$.content.text.*' is too complex, please check your migration.") end end describe "migrating a hash" do it "should convert every attribute" do expect(LiquidMigrator.convert_hash({'a' => "$.data", 'b' => "This is a <$.test>"})).to eq( {'a' => "$.data", 'b' => "This is a {{test}}"} ) end it "should work with leading_dollarsign_is_jsonpath" do expect(LiquidMigrator.convert_hash({'a' => "$.data", 'b' => "This is a <$.test>"}, leading_dollarsign_is_jsonpath: true)).to eq( {'a' => "{{data}}", 'b' => "This is a {{test}}"} ) end it "should use the corresponding *_path attributes when using merge_path_attributes"do expect(LiquidMigrator.convert_hash({'a' => "default", 'a_path' => "$.data"}, {leading_dollarsign_is_jsonpath: true, merge_path_attributes: true})).to eq( {'a' => "{{data}}"} ) end it "should raise an exception when encountering complex JSONPaths" do expect { LiquidMigrator.convert_hash({'b' => "This is <$.complex[2]>"}) }. to raise_error("JSONPath '$.complex[2]' is too complex, please check your migration.") end end describe "migrating the 'make_message' format" do it "should work" do expect(LiquidMigrator.convert_make_message('<message>')).to eq('{{message}}') expect(LiquidMigrator.convert_make_message('<new.message>')).to eq('{{new.message}}') expect(LiquidMigrator.convert_make_message('Hello <world>. How is <nested.life>')).to eq('Hello {{world}}. How is {{nested.life}}') end end describe "migrating an actual agent" do before do valid_params = { 'auth_token' => 'token', 'room_name' => 'test', 'room_name_path' => '', 'username' => "Huginn", 'username_path' => '$.username', 'message' => "Hello from Huginn!", 'message_path' => '$.message', 'notify' => false, 'notify_path' => '', 'color' => 'yellow', 'color_path' => '', } @agent = Agents::HipchatAgent.new(:name => "somename", :options => valid_params) @agent.user = users(:jane) @agent.save! end it "should work" do LiquidMigrator.convert_all_agent_options(@agent) expect(@agent.reload.options).to eq({"auth_token" => 'token', 'color' => 'yellow', 'notify' => false, 'room_name' => 'test', 'username' => '{{username}}', 'message' => '{{message}}'}) end it "should work with nested hashes" do @agent.options['very'] = {'nested' => '$.value'} LiquidMigrator.convert_all_agent_options(@agent) expect(@agent.reload.options).to eq({"auth_token" => 'token', 'color' => 'yellow', 'very' => {'nested' => '{{value}}'}, 'notify' => false, 'room_name' => 'test', 'username' => '{{username}}', 'message' => '{{message}}'}) end it "should work with nested arrays" do @agent.options['array'] = ["one", "$.two"] LiquidMigrator.convert_all_agent_options(@agent) expect(@agent.reload.options).to eq({"auth_token" => 'token', 'color' => 'yellow', 'array' => ['one', '{{two}}'], 'notify' => false, 'room_name' => 'test', 'username' => '{{username}}', 'message' => '{{message}}'}) end it "should raise an exception when encountering complex JSONPaths" do @agent.options['username_path'] = "$.very.complex[*]" expect { LiquidMigrator.convert_all_agent_options(@agent) }. to raise_error("JSONPath '$.very.complex[*]' is too complex, please check your migration.") end it "should work with the human task agent" do valid_params = { 'expected_receive_period_in_days' => 2, 'trigger_on' => "event", 'hit' => { 'assignments' => 1, 'title' => "Sentiment evaluation", 'description' => "Please rate the sentiment of this message: '<$.message>'", 'reward' => 0.05, 'lifetime_in_seconds' => 24 * 60 * 60, 'questions' => [ { 'type' => "selection", 'key' => "sentiment", 'name' => "Sentiment", 'required' => "true", 'question' => "Please select the best sentiment value:", 'selections' => [ { 'key' => "happy", 'text' => "Happy" }, { 'key' => "sad", 'text' => "Sad" }, { 'key' => "neutral", 'text' => "Neutral" } ] }, { 'type' => "free_text", 'key' => "feedback", 'name' => "Have any feedback for us?", 'required' => "false", 'question' => "Feedback", 'default' => "Type here...", 'min_length' => "2", 'max_length' => "2000" } ] } } @agent = Agents::HumanTaskAgent.new(:name => "somename", :options => valid_params) @agent.user = users(:jane) LiquidMigrator.convert_all_agent_options(@agent) expect(@agent.reload.options['hit']['description']).to eq("Please rate the sentiment of this message: '{{message}}'") end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/lib/agent_runner_spec.rb
spec/lib/agent_runner_spec.rb
require 'rails_helper' # RSpec-Mocks is extremely unstable when threads are heavily involved, so stick with RR here. require 'rr' describe AgentRunner do context "without traps" do before do RR.stub.instance_of(Rufus::Scheduler).every RR.stub.instance_of(AgentRunner).set_traps @agent_runner = AgentRunner.new end after(:each) do @agent_runner.stop AgentRunner.class_variable_set(:@@agents, []) RR.reset end context "#run" do before do RR.mock(@agent_runner).run_workers end it "runs until stop is called" do RR.mock.instance_of(Rufus::Scheduler).join Thread.new { while @agent_runner.instance_variable_get(:@running) != false do sleep 0.1; @agent_runner.stop end } @agent_runner.run end it "handles signals" do @agent_runner.instance_variable_set(:@signal_queue, ['TERM']) @agent_runner.run end end context "#load_workers" do before do AgentRunner.class_variable_set(:@@agents, [HuginnScheduler, DelayedJobWorker]) end it "loads all workers" do workers = @agent_runner.send(:load_workers) expect(workers).to be_a(Hash) expect(workers.keys).to eq(['HuginnScheduler', 'DelayedJobWorker']) end it "loads only the workers specified in the :only option" do agent_runner = AgentRunner.new(only: HuginnScheduler) workers = agent_runner.send(:load_workers) expect(workers.keys).to eq(['HuginnScheduler']) agent_runner.stop end it "does not load workers specified in the :except option" do agent_runner = AgentRunner.new(except: HuginnScheduler) workers = agent_runner.send(:load_workers) expect(workers.keys).to eq(['DelayedJobWorker']) agent_runner.stop end end context "running workers" do before do AgentRunner.class_variable_set(:@@agents, [HuginnScheduler, DelayedJobWorker]) RR.stub.instance_of(HuginnScheduler).setup RR.stub.instance_of(DelayedJobWorker).setup end context "#run_workers" do it "runs all the workers" do RR.mock.instance_of(HuginnScheduler).run! RR.mock.instance_of(DelayedJobWorker).run! @agent_runner.send(:run_workers) end it "kills no long active workers" do RR.mock.instance_of(HuginnScheduler).run! RR.mock.instance_of(DelayedJobWorker).run! @agent_runner.send(:run_workers) AgentRunner.class_variable_set(:@@agents, [DelayedJobWorker]) RR.mock.instance_of(HuginnScheduler).stop! @agent_runner.send(:run_workers) end end context "#restart_dead_workers" do before do RR.mock.instance_of(HuginnScheduler).run! RR.mock.instance_of(DelayedJobWorker).run! @agent_runner.send(:run_workers) end it "restarts dead workers" do RR.stub.instance_of(HuginnScheduler).thread { OpenStruct.new(alive?: false) } RR.mock.instance_of(HuginnScheduler).run! @agent_runner.send(:restart_dead_workers) end end end end context "#set_traps" do it "sets traps for INT TERM and QUIT" do agent_runner = AgentRunner.new RR.mock(Signal).trap('INT') RR.mock(Signal).trap('TERM') RR.mock(Signal).trap('QUIT') agent_runner.set_traps agent_runner.stop end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/lib/utils_spec.rb
spec/lib/utils_spec.rb
require 'rails_helper' describe Utils do describe "#unindent" do it "unindents to the level of the greatest consistant indention" do expect(Utils.unindent(<<-MD)).to eq("Hello World") Hello World MD expect(Utils.unindent(<<-MD)).to eq("Hello World\nThis is\nnot indented") Hello World This is not indented MD expect(Utils.unindent(<<-MD)).to eq("Hello World\n This is\n indented\nthough") Hello World This is indented though MD expect(Utils.unindent("Hello\n I am indented")).to eq("Hello\n I am indented") a = " Events will have the fields you specified. Your options look like:\n\n {\n \"url\": {\n \"css\": \"#comic img\",\n \"value\": \"@src\"\n },\n \"title\": {\n \"css\": \"#comic img\",\n \"value\": \"@title\"\n }\n }\"\n" expect(Utils.unindent(a)).to eq("Events will have the fields you specified. Your options look like:\n\n {\n \"url\": {\n\"css\": \"#comic img\",\n\"value\": \"@src\"\n },\n \"title\": {\n\"css\": \"#comic img\",\n\"value\": \"@title\"\n }\n }\"") end end describe "#interpolate_jsonpaths" do let(:payload) { { :there => { :world => "WORLD" }, :works => "should work" } } it "interpolates jsonpath expressions between matching <>'s" do expect(Utils.interpolate_jsonpaths("hello <$.there.world> this <escape works>", payload)).to eq("hello WORLD this should+work") end it "optionally supports treating values that start with '$' as raw JSONPath" do expect(Utils.interpolate_jsonpaths("$.there.world", payload)).to eq("$.there.world") expect(Utils.interpolate_jsonpaths("$.there.world", payload, :leading_dollarsign_is_jsonpath => true)).to eq("WORLD") end end describe "#recursively_interpolate_jsonpaths" do it "interpolates all string values in a structure" do struct = { :int => 5, :string => "this <escape $.works>", :array => ["<works>", "now", "<$.there.world>"], :deep => { :string => "hello <there.world>", :hello => :world } } data = { :there => { :world => "WORLD" }, :works => "should work" } expect(Utils.recursively_interpolate_jsonpaths(struct, data)).to eq({ :int => 5, :string => "this should+work", :array => ["should work", "now", "WORLD"], :deep => { :string => "hello WORLD", :hello => :world } }) end end describe "#value_at" do it "returns the value at a JSON path" do expect(Utils.value_at({ :foo => { :bar => :baz }}.to_json, "foo.bar")).to eq("baz") expect(Utils.value_at({ :foo => { :bar => { :bing => 2 } }}, "foo.bar.bing")).to eq(2) expect(Utils.value_at({ :foo => { :bar => { :bing => 2 } }}, "foo.bar[?(@.bing == 2)].bing")).to eq(2) end it "returns nil when the path cannot be followed" do expect(Utils.value_at({ :foo => { :bar => :baz }}, "foo.bing")).to be_nil end end describe "#values_at" do it "returns arrays of matching values" do expect(Utils.values_at({ :foo => { :bar => :baz }}, "foo.bar")).to eq(%w[baz]) expect(Utils.values_at({ :foo => [ { :bar => :baz }, { :bar => :bing } ]}, "foo[*].bar")).to eq(%w[baz bing]) expect(Utils.values_at({ :foo => [ { :bar => :baz }, { :bar => :bing } ]}, "foo[*].bar")).to eq(%w[baz bing]) end it "should allow escaping" do expect(Utils.values_at({ :foo => { :bar => "escape this!?" }}, "escape $.foo.bar")).to eq(["escape+this%21%3F"]) end end describe "#jsonify" do it "escapes </script> tags in the output JSON" do cleaned_json = Utils.jsonify(:foo => "bar", :xss => "</script><script>alert('oh no!')</script>") expect(cleaned_json).not_to include("</script>") expect(cleaned_json).to include('\\u003c/script\\u003e') end it "html_safes the output unless :skip_safe is passed in" do expect(Utils.jsonify({:foo => "bar"})).to be_html_safe expect(Utils.jsonify({:foo => "bar"}, :skip_safe => false)).to be_html_safe expect(Utils.jsonify({:foo => "bar"}, :skip_safe => true)).not_to be_html_safe end end describe "#pretty_jsonify" do it "escapes </script> tags in the output JSON" do cleaned_json = Utils.pretty_jsonify(:foo => "bar", :xss => "</script><script>alert('oh no!')</script>") expect(cleaned_json).not_to include("</script>") expect(cleaned_json).to include("<\\/script>") end end describe "#sort_tuples!" do let(:tuples) { time = Time.now [ [2, "a", time - 1], # 0 [2, "b", time - 1], # 1 [1, "b", time - 1], # 2 [1, "b", time], # 3 [1, "a", time], # 4 [2, "a", time + 1], # 5 [2, "a", time], # 6 ] } it "sorts tuples like arrays by default" do expected = tuples.values_at(4, 2, 3, 0, 6, 5, 1) Utils.sort_tuples!(tuples) expect(tuples).to eq expected end it "sorts tuples in order specified: case 1" do # order by x1 asc, x2 desc, c3 asc orders = [false, true, false] expected = tuples.values_at(2, 3, 4, 1, 0, 6, 5) Utils.sort_tuples!(tuples, orders) expect(tuples).to eq expected end it "sorts tuples in order specified: case 2" do # order by x1 desc, x2 asc, c3 desc orders = [true, false, true] expected = tuples.values_at(5, 6, 0, 1, 4, 3, 2) Utils.sort_tuples!(tuples, orders) expect(tuples).to eq expected end it "always succeeds in sorting even if it finds pairs of incomparable objects" do time = Time.now tuples = [ [2, "a", time - 1], # 0 [1, "b", nil], # 1 [1, "b", time], # 2 ["2", nil, time], # 3 [1, nil, time], # 4 [nil, "a", time + 1], # 5 [2, "a", time], # 6 ] orders = [true, false, true] expected = tuples.values_at(3, 6, 0, 4, 2, 1, 5) Utils.sort_tuples!(tuples, orders) expect(tuples).to eq expected end end context "#parse_duration" do it "works with correct arguments" do expect(Utils.parse_duration('2.days')).to eq(2.days) expect(Utils.parse_duration('2.seconds')).to eq(2) expect(Utils.parse_duration('2')).to eq(2) end it "returns nil when passed nil" do expect(Utils.parse_duration(nil)).to be_nil end it "warns and returns nil when not parseable" do expect(STDERR).to receive(:puts).with("WARNING: Invalid duration format: 'bogus'") expect(Utils.parse_duration('bogus')).to be_nil end end context "#if_present" do it "returns nil when passed nil" do expect(Utils.if_present(nil, :to_i)).to be_nil end it "calls the specified method when the argument is present" do argument = double() expect(argument).to receive(:to_i) { 1 } expect(Utils.if_present(argument, :to_i)).to eq(1) end end describe ".normalize_uri" do it 'should accept a URI with an IDN hostname, malformed path, query, and fragment parts' do uri = Utils.normalize_uri("http://\u{3042}/\u{3042}?a[]=%2F&b=\u{3042}#100%") expect(uri).to be_a(URI::HTTP) expect(uri.to_s).to eq "http://xn--l8j/%E3%81%82?a[]=%2F&b=%E3%81%82#100%25" end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/lib/google_calendar_spec.rb
spec/lib/google_calendar_spec.rb
require 'rails_helper' describe GoogleCalendar do it '#open does not mask exception in initlize' do allow(Google::Apis::CalendarV3::CalendarService).to receive(:new) do raise "test exception" end expect { GoogleCalendar.open({'google' => {}}, Rails.logger) {} }.to raise_error(/test exception/) end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/lib/location_spec.rb
spec/lib/location_spec.rb
require 'rails_helper' describe Location do let(:location) { Location.new( lat: BigDecimal('2.0'), lng: BigDecimal('3.0'), radius: 300, speed: 2, course: 30) } it "converts values to Float" do expect(location.lat).to be_a Float expect(location.lat).to eq 2.0 expect(location.lng).to be_a Float expect(location.lng).to eq 3.0 expect(location.radius).to be_a Float expect(location.radius).to eq 300.0 expect(location.speed).to be_a Float expect(location.speed).to eq 2.0 expect(location.course).to be_a Float expect(location.course).to eq 30.0 end it "provides hash-style access to its properties with both symbol and string keys" do expect(location[:lat]).to be_a Float expect(location[:lat]).to eq 2.0 expect(location['lat']).to be_a Float expect(location['lat']).to eq 2.0 end it "has a convenience accessor for combined latitude and longitude" do expect(location.latlng).to eq "2.0,3.0" end it "does not allow hash-style assignment" do expect { location[:lat] = 2.0 }.to raise_error(NoMethodError) end it "ignores invalid values" do location2 = Location.new( lat: 2, lng: 3, radius: -1, speed: -1, course: -1) expect(location2.radius).to be_nil expect(location2.speed).to be_nil expect(location2.course).to be_nil end it "considers a location empty if either latitude or longitude is missing" do expect(Location.new.empty?).to be_truthy expect(Location.new(lat: 2, radius: 1).present?).to be_falsy expect(Location.new(lng: 3, radius: 1).present?).to be_falsy end it "is droppable" do { '{{location.lat}}' => '2.0', '{{location.latitude}}' => '2.0', '{{location.lng}}' => '3.0', '{{location.longitude}}' => '3.0', '{{location.latlng}}' => '2.0,3.0', }.each { |template, result| expect(Liquid::Template.parse(template).render('location' => location.to_liquid)).to eq(result), "expected #{template.inspect} to expand to #{result.inspect}" } end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/lib/huginn_scheduler_spec.rb
spec/lib/huginn_scheduler_spec.rb
require 'rails_helper' require 'huginn_scheduler' describe HuginnScheduler do before(:each) do @rufus_scheduler = Rufus::Scheduler.new @scheduler = HuginnScheduler.new allow(@scheduler).to receive(:setup) @scheduler.setup!(@rufus_scheduler, Mutex.new) end after(:each) do @rufus_scheduler.shutdown(:wait) end it "schould register the schedules with the rufus scheduler and run" do expect(@rufus_scheduler).to receive(:join) scheduler = HuginnScheduler.new scheduler.setup!(@rufus_scheduler, Mutex.new) scheduler.run end it "should run scheduled agents" do expect(Agent).to receive(:run_schedule).with('every_1h') expect_any_instance_of(IO).to receive(:puts).with('Queuing schedule for every_1h') @scheduler.send(:run_schedule, 'every_1h') end it "should propagate events" do expect(Agent).to receive(:receive!) expect_any_instance_of(IO).to receive(:puts) @scheduler.send(:propagate!) end it "schould clean up expired events" do expect(Event).to receive(:cleanup_expired!) expect_any_instance_of(IO).to receive(:puts) @scheduler.send(:cleanup_expired_events!) end describe "#hour_to_schedule_name" do it "for 0h" do expect(@scheduler.send(:hour_to_schedule_name, 0)).to eq('midnight') end it "for the forenoon" do expect(@scheduler.send(:hour_to_schedule_name, 6)).to eq('6am') end it "for 12h" do expect(@scheduler.send(:hour_to_schedule_name, 12)).to eq('noon') end it "for the afternoon" do expect(@scheduler.send(:hour_to_schedule_name, 17)).to eq('5pm') end end describe "cleanup_failed_jobs!" do before do 3.times do |i| Delayed::Job.create(failed_at: Time.now - i.minutes) end @keep = Delayed::Job.order(:failed_at)[1] end it "work with set FAILED_JOBS_TO_KEEP env variable" do expect { @scheduler.send(:cleanup_failed_jobs!) }.to change(Delayed::Job, :count).by(-1) expect { @scheduler.send(:cleanup_failed_jobs!) }.to change(Delayed::Job, :count).by(0) expect(@keep.id).to eq(Delayed::Job.order(:failed_at)[0].id) end it "work without the FAILED_JOBS_TO_KEEP env variable" do old = ENV['FAILED_JOBS_TO_KEEP'] ENV['FAILED_JOBS_TO_KEEP'] = nil expect { @scheduler.send(:cleanup_failed_jobs!) }.to change(Delayed::Job, :count).by(0) ENV['FAILED_JOBS_TO_KEEP'] = old end end context "#setup_worker" do it "should return an array with an instance of itself" do workers = HuginnScheduler.setup_worker expect(workers).to be_a(Array) expect(workers.first).to be_a(HuginnScheduler) expect(workers.first.id).to eq('HuginnScheduler') end end end describe Rufus::Scheduler do before :each do Agent.delete_all @taoe, Thread.abort_on_exception = Thread.abort_on_exception, false @oso, @ose, $stdout, $stderr = $stdout, $stderr, StringIO.new, StringIO.new @scheduler = Rufus::Scheduler.new allow_any_instance_of(Agents::SchedulerAgent).to receive(:second_precision_enabled) { true } @agent1 = Agents::SchedulerAgent.new(name: 'Scheduler 1', options: { action: 'run', schedule: '*/1 * * * * *' }).tap { |a| a.user = users(:bob) a.save! } @agent2 = Agents::SchedulerAgent.new(name: 'Scheduler 2', options: { action: 'run', schedule: '*/1 * * * * *' }).tap { |a| a.user = users(:bob) a.save! } end after :each do @scheduler.shutdown(:wait) Thread.abort_on_exception = @taoe $stdout, $stderr = @oso, @ose end describe '#schedule_scheduler_agents' do it 'registers active SchedulerAgents' do @scheduler.schedule_scheduler_agents expect(@scheduler.scheduler_agent_jobs.map(&:scheduler_agent).sort_by(&:id)).to eq([@agent1, @agent2]) end it 'unregisters disabled SchedulerAgents' do @scheduler.schedule_scheduler_agents @agent1.update!(disabled: true) @scheduler.schedule_scheduler_agents expect(@scheduler.scheduler_agent_jobs.map(&:scheduler_agent)).to eq([@agent2]) end it 'unregisters deleted SchedulerAgents' do @scheduler.schedule_scheduler_agents @agent2.delete @scheduler.schedule_scheduler_agents expect(@scheduler.scheduler_agent_jobs.map(&:scheduler_agent)).to eq([@agent1]) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/lib/agents_exporter_spec.rb
spec/lib/agents_exporter_spec.rb
require 'rails_helper' describe AgentsExporter do describe "#as_json" do let(:name) { "My set of Agents" } let(:description) { "These Agents work together nicely!" } let(:guid) { "some-guid" } let(:tag_fg_color) { "#ffffff" } let(:tag_bg_color) { "#000000" } let(:icon) { 'Camera' } let(:source_url) { "http://yourhuginn.com/scenarios/2/export.json" } let(:agent_list) { [agents(:jane_weather_agent), agents(:jane_rain_notifier_agent)] } let(:exporter) { AgentsExporter.new( agents: agent_list, name: name, description: description, source_url: source_url, guid: guid, tag_fg_color: tag_fg_color, tag_bg_color: tag_bg_color, icon: icon) } it "outputs a structure containing name, description, the date, all agents & their links" do data = exporter.as_json expect(data[:name]).to eq(name) expect(data[:description]).to eq(description) expect(data[:source_url]).to eq(source_url) expect(data[:guid]).to eq(guid) expect(data[:schema_version]).to eq(1) expect(data[:tag_fg_color]).to eq(tag_fg_color) expect(data[:tag_bg_color]).to eq(tag_bg_color) expect(data[:icon]).to eq(icon) expect(Time.parse(data[:exported_at])).to be_within(2).of(Time.now.utc) expect(data[:links]).to eq([{ :source => guid_order(agent_list, :jane_weather_agent), :receiver => guid_order(agent_list, :jane_rain_notifier_agent)}]) expect(data[:control_links]).to eq([]) expect(data[:agents]).to eq(agent_list.sort_by{|a| a.guid}.map { |agent| exporter.agent_as_json(agent) }) expect(data[:agents].all? { |agent_json| agent_json[:guid].present? && agent_json[:type].present? && agent_json[:name].present? }).to be_truthy expect(data[:agents][guid_order(agent_list, :jane_weather_agent)]).not_to have_key(:propagate_immediately) # can't receive events expect(data[:agents][guid_order(agent_list, :jane_rain_notifier_agent)]).not_to have_key(:schedule) # can't be scheduled end it "does not output links to other agents outside of the incoming set" do Link.create!(:source_id => agents(:jane_weather_agent).id, :receiver_id => agents(:jane_website_agent).id) Link.create!(:source_id => agents(:jane_website_agent).id, :receiver_id => agents(:jane_rain_notifier_agent).id) expect(exporter.as_json[:links]).to eq([{ :source => guid_order(agent_list, :jane_weather_agent), :receiver => guid_order(agent_list, :jane_rain_notifier_agent) }]) end it "outputs control links to agents within the incoming set, but not outside it" do agents(:jane_rain_notifier_agent).control_targets = [agents(:jane_weather_agent), agents(:jane_twitter_user_agent)] agents(:jane_rain_notifier_agent).save! expect(exporter.as_json[:control_links]).to eq([{ :controller => guid_order(agent_list, :jane_rain_notifier_agent), :control_target => guid_order(agent_list, :jane_weather_agent) }]) end end describe "#filename" do it "strips special characters" do expect(AgentsExporter.new(:name => "ƏfooƐƕƺbar").filename).to eq("foo-bar.json") end it "strips punctuation" do expect(AgentsExporter.new(:name => "foo,bar").filename).to eq("foo-bar.json") end it "strips leading and trailing dashes" do expect(AgentsExporter.new(:name => ",foo,").filename).to eq("foo.json") end it "has a default when options[:name] is nil" do expect(AgentsExporter.new(:name => nil).filename).to eq("exported-agents.json") end it "has a default when the result is empty" do expect(AgentsExporter.new(:name => "").filename).to eq("exported-agents.json") expect(AgentsExporter.new(:name => "Ə").filename).to eq("exported-agents.json") expect(AgentsExporter.new(:name => "-").filename).to eq("exported-agents.json") expect(AgentsExporter.new(:name => ",,").filename).to eq("exported-agents.json") end end def guid_order(agent_list, agent_name) agent_list.map{|a|a.guid}.sort.find_index(agents(agent_name).guid) end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/lib/rdbms_functions.rb
lib/rdbms_functions.rb
module RdbmsFunctions def rdbms_date_add(source, unit, amount) adapter_type = ActiveRecord::Base.connection.adapter_name.downcase.to_sym case adapter_type when :mysql, :mysql2 "DATE_ADD(`#{source}`, INTERVAL #{amount} #{unit})" when :postgresql "(#{source} + INTERVAL '#{amount} #{unit}')" else raise NotImplementedError, "Unknown adapter type '#{adapter_type}'" end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/lib/setup_tools.rb
lib/setup_tools.rb
require 'open3' require 'io/console' require 'securerandom' require 'shellwords' require 'active_support/core_ext/object/blank' module SetupTools def capture(cmd, opts = {}) if opts.delete(:no_stderr) o, s = Open3.capture2(cmd, opts) else o, s = Open3.capture2e(cmd, opts) end o.strip end def grab_config_with_cmd!(cmd, opts = {}) config_data = capture(cmd, opts) $config = {} if config_data !~ /has no config vars/ config_data.split("\n").map do |line| next if line =~ /^\s*(#|$)/ # skip comments and empty lines first_equal_sign = line.index('=') raise "Invalid line found in config: #{line}" unless first_equal_sign $config[line.slice(0, first_equal_sign)] = line.slice(first_equal_sign + 1, line.length) end end end def print_config if $config.length > 0 puts puts "Your current config:" $config.each do |key, value| puts ' ' + key + ' ' * (25 - [key.length, 25].min) + '= ' + value end end end def set_defaults! unless $config['APP_SECRET_TOKEN'] puts "Setting up APP_SECRET_TOKEN..." set_value 'APP_SECRET_TOKEN', SecureRandom.hex(64) end set_value 'RAILS_ENV', "production" set_value 'FORCE_SSL', "true" set_value 'USE_GRAPHVIZ_DOT', 'dot' unless $config['INVITATION_CODE'] puts "You need to set an invitation code for your Huginn instance. If you plan to share this instance, you will" puts "tell this code to anyone who you'd like to invite. If you won't share it, then just set this to something" puts "that people will not guess." invitation_code = nag("What code would you like to use?") set_value 'INVITATION_CODE', invitation_code end end def confirm_app_name(app_name) unless yes?("Your app name is '#{app_name}'. Is this correct?", default: :yes) puts "Well, then I'm not sure what to do here, sorry." exit 1 end end # expects set_env(key, value) to be defined. def set_value(key, value, options = {}) if $config[key].nil? || $config[key] == '' || ($config[key] != value && options[:force] != false) puts "Setting #{key} to #{value}" unless options[:silent] puts set_env(key, value) $config[key] = value end end def ask(question, opts = {}) print question + " " STDOUT.flush (opts[:noecho] ? STDIN.noecho(&:gets) : gets).strip end def nag(question, opts = {}) answer = '' while answer.length == 0 answer = ask(question, opts) end answer end def yes?(question, opts = {}) if opts[:default].to_s[0...1] == "y" (ask(question + " (Y/n)").presence || "yes") =~ /^y/i else ask(question + " (y/n)") =~ /^y/i end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/lib/google_calendar.rb
lib/google_calendar.rb
require 'googleauth' require 'google/apis/calendar_v3' class GoogleCalendar def initialize(config, logger) @config = config if @config['google']['key'].present? # https://github.com/google/google-auth-library-ruby/issues/65 # https://github.com/google/google-api-ruby-client/issues/370 ENV['GOOGLE_PRIVATE_KEY'] = @config['google']['key'] ENV['GOOGLE_CLIENT_EMAIL'] = @config['google']['service_account_email'] ENV['GOOGLE_ACCOUNT_TYPE'] = 'service_account' elsif @config['google']['key_file'].present? ENV['GOOGLE_APPLICATION_CREDENTIALS'] = @config['google']['key_file'] end @logger ||= logger # https://github.com/google/google-api-ruby-client/blob/master/MIGRATING.md @calendar = Google::Apis::CalendarV3::CalendarService.new # https://developers.google.com/api-client-library/ruby/auth/service-accounts # https://developers.google.com/identity/protocols/application-default-credentials scopes = [Google::Apis::CalendarV3::AUTH_CALENDAR] @authorization = Google::Auth.get_application_default(scopes) @logger.info("Setup") @logger.debug @calendar.inspect end def self.open(*args, &block) instance = new(*args) block.call(instance) ensure instance&.cleanup! end def auth_as @authorization.fetch_access_token! @calendar.authorization = @authorization end # who - String: email of user to add event # details - JSON String: see https://developers.google.com/google-apps/calendar/v3/reference/events/insert def publish_as(who, details) auth_as @logger.info("Attempting to create event for " + who) @logger.debug details.to_yaml event = Google::Apis::CalendarV3::Event.new(**details.deep_symbolize_keys) ret = @calendar.insert_event( who, event, send_notifications: true ) @logger.debug ret.to_yaml ret.to_h end def events_as(who, date) auth_as date ||= Date.today @logger.info("Attempting to receive events for "+who) @logger.debug details.to_yaml ret = @calendar.list_events( who ) @logger.debug ret.to_yaml ret.to_h end def cleanup! ENV.delete('GOOGLE_PRIVATE_KEY') ENV.delete('GOOGLE_CLIENT_EMAIL') ENV.delete('GOOGLE_ACCOUNT_TYPE') ENV.delete('GOOGLE_APPLICATION_CREDENTIALS') end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/lib/agent_runner.rb
lib/agent_runner.rb
require 'cgi' require 'json' require 'rufus-scheduler' require 'pp' require 'twitter' class AgentRunner @@agents = [] def initialize(options = {}) @workers = {} @signal_queue = [] @options = options @options[:only] = [@options[:only]].flatten if @options[:only] @options[:except] = [@options[:except]].flatten if @options[:except] @mutex = Mutex.new @scheduler = Rufus::Scheduler.new(frequency: ENV['SCHEDULER_FREQUENCY'].presence || 0.3) @scheduler.every 5 do restart_dead_workers if @running end @scheduler.every 60 do run_workers if @running end set_traps end def stop puts "Stopping AgentRunner..." unless Rails.env.test? @running = false @workers.each_pair do |_, w| w.stop! end @scheduler.stop end def run @running = true run_workers while @running if signal = @signal_queue.shift handle_signal(signal) end sleep 0.25 end @scheduler.join end def set_traps %w(INT TERM QUIT).each do |signal| Signal.trap(signal) { @signal_queue << signal } end end def self.register(agent) @@agents << agent unless @@agents.include?(agent) end def self.with_connection ActiveRecord::Base.connection_pool.with_connection do yield end end private def run_workers workers = load_workers new_worker_ids = workers.keys current_worker_ids = @workers.keys (current_worker_ids - new_worker_ids).each do |outdated_worker_id| puts "Killing #{outdated_worker_id}" unless Rails.env.test? @workers[outdated_worker_id].stop! @workers.delete(outdated_worker_id) end (new_worker_ids - current_worker_ids).each do |new_worker_id| puts "Starting #{new_worker_id}" unless Rails.env.test? @workers[new_worker_id] = workers[new_worker_id] @workers[new_worker_id].setup!(@scheduler, @mutex) @workers[new_worker_id].run! end end def load_workers workers = {} @@agents.each do |klass| next if @options[:only] && !@options[:only].include?(klass) next if @options[:except] && @options[:except].include?(klass) AgentRunner.with_connection do (klass.setup_worker || []) end.each do |agent_worker| workers[agent_worker.id] = agent_worker end end workers end def restart_dead_workers @workers.each_pair do |id, worker| if !worker.restarting && worker.thread && !worker.thread.alive? puts "Restarting #{id.to_s}" unless Rails.env.test? @workers[id].run! end end end def handle_signal(signal) case signal when 'INT', 'TERM', 'QUIT' stop end end end require 'agents/twitter_stream_agent' require 'agents/jabber_agent' require 'agents/local_file_agent' require 'huginn_scheduler' require 'delayed_job_worker'
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/lib/utils.rb
lib/utils.rb
require 'jsonpath' require 'cgi' require 'uri' require 'addressable/uri' module Utils def self.unindent(s) s = s.gsub(/\t/, ' ').chomp min = ((s.split("\n").find {|l| l !~ /^\s*$/ })[/^\s+/, 0] || "").length if min > 0 s.gsub(/^#{" " * min}/, "") else s end end def self.pretty_print(struct, indent = true) output = JSON.pretty_generate(struct) if indent output.gsub(/\n/i, "\n ") else output end end class << self def normalize_uri(uri) URI.parse(uri) rescue URI::Error => e begin auri = Addressable::URI.parse(uri.to_s) rescue StandardError # Do not leak Addressable::URI::InvalidURIError which # callers might not expect. raise e else # Addressable::URI#normalize! modifies the query and # fragment components beyond escaping unsafe characters, so # avoid using it. Otherwise `?a[]=%2F` would be normalized # as `?a%5B%5D=/`, for example. auri.site = auri.normalized_site auri.path = auri.normalized_path auri.query &&= escape_uri_unsafe_characters(auri.query) auri.fragment &&= escape_uri_unsafe_characters(auri.fragment) URI.parse(auri.to_s) end end private def escape_uri_unsafe_characters(string) string.gsub(/(?!%[\h\H]{2})[^\-_.!~*'()a-zA-Z\d;\/?:@&=+$,\[\]]+/) { |unsafe| unsafe.bytes.each_with_object(String.new) { |uc, s| s << '%%%02X' % uc } }.force_encoding(Encoding::US_ASCII) end end def self.interpolate_jsonpaths(value, data, options = {}) if options[:leading_dollarsign_is_jsonpath] && value[0] == '$' Utils.values_at(data, value).first.to_s else value.gsub(/<[^>]+>/).each { |jsonpath| Utils.values_at(data, jsonpath[1..-2]).first.to_s } end end def self.recursively_interpolate_jsonpaths(struct, data, options = {}) case struct when Hash struct.inject({}) {|memo, (key, value)| memo[key] = recursively_interpolate_jsonpaths(value, data, options); memo } when Array struct.map {|elem| recursively_interpolate_jsonpaths(elem, data, options) } when String interpolate_jsonpaths(struct, data, options) else struct end end def self.value_at(data, path) values_at(data, path).first end def self.values_at(data, path) if path =~ /\Aescape / path.gsub!(/\Aescape /, '') escape = true else escape = false end result = JsonPath.new(path).on(data.is_a?(String) ? data : data.to_json) if escape result.map {|r| CGI::escape r } else result end end # Output JSON that is ready for inclusion into HTML. If you simply use to_json on an object, the # presence of </script> in the valid JSON can break the page and allow XSS attacks. # Optionally, pass `:skip_safe => true` to not call html_safe on the output. def self.jsonify(thing, options = {}) json = thing.to_json.gsub('</', '<\/') if !options[:skip_safe] json.html_safe else json end end def self.pretty_jsonify(thing) JSON.pretty_generate(thing).gsub('</', '<\/') end class TupleSorter class SortableTuple attr_reader :array # The <=> method will call orders[n] to determine if the nth element # should be compared in descending order. def initialize(array, orders = []) @array = array @orders = orders end def <=> other other = other.array @array.each_with_index do |e, i| o = other[i] case cmp = e <=> o || e.to_s <=> o.to_s when 0 next else return @orders[i] ? -cmp : cmp end end 0 end end class << self def sort!(array, orders = []) array.sort_by! do |e| SortableTuple.new(e, orders) end end end end def self.sort_tuples!(array, orders = []) TupleSorter.sort!(array, orders) end def self.parse_duration(string) return nil if string.blank? case string.strip when /\A(\d+)\.(\w+)\z/ $1.to_i.send($2.to_s) when /\A(\d+)\z/ $1.to_i else STDERR.puts "WARNING: Invalid duration format: '#{string.strip}'" nil end end def self.if_present(string, method) if string.present? string.send(method) else nil end end def self.rebase_hrefs(html, base_uri) base_uri = normalize_uri(base_uri) HtmlTransformer.replace_uris(html) { |url| base_uri.merge(normalize_uri(url)).to_s } end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/lib/agents_exporter.rb
lib/agents_exporter.rb
class AgentsExporter attr_accessor :options def initialize(options) self.options = options end # Filename should have no commas or special characters to support Content-Disposition on older browsers. def filename ((options[:name] || '').downcase.gsub(/[^a-z0-9_-]/, '-').gsub(/-+/, '-').gsub(/^-|-$/, '').presence || 'exported-agents') + ".json" end def as_json(opts = {}) { schema_version: 1, name: options[:name].presence || 'No name provided', description: options[:description].presence || 'No description provided', source_url: options[:source_url], guid: options[:guid], tag_fg_color: options[:tag_fg_color], tag_bg_color: options[:tag_bg_color], icon: options[:icon], exported_at: Time.now.utc.iso8601, agents: agents.map { |agent| agent_as_json(agent) }, links: links, control_links: control_links } end def agents options[:agents].sort_by{|agent| agent.guid}.to_a end def links agent_ids = agents.map(&:id) contained_links = agents.map.with_index do |agent, index| agent.links_as_source.where(receiver_id: agent_ids).map do |link| { source: index, receiver: agent_ids.index(link.receiver_id) } end end contained_links.flatten.compact end def control_links agent_ids = agents.map(&:id) contained_controller_links = agents.map.with_index do |agent, index| agent.control_links_as_controller.where(control_target_id: agent_ids).map do |control_link| { controller: index, control_target: agent_ids.index(control_link.control_target_id) } end end contained_controller_links.flatten.compact end def agent_as_json(agent) { :type => agent.type, :name => agent.name, :disabled => agent.disabled, :guid => agent.guid, :options => agent.options }.tap do |options| options[:schedule] = agent.schedule if agent.can_be_scheduled? options[:keep_events_for] = agent.keep_events_for if agent.can_create_events? options[:propagate_immediately] = agent.propagate_immediately if agent.can_receive_events? end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/lib/location.rb
lib/location.rb
require 'liquid' Location = Struct.new(:lat, :lng, :radius, :speed, :course) class Location include LiquidDroppable protected :[]= def initialize(data = {}) super() case data when Array raise ArgumentError, 'unsupported location data' unless data.size == 2 self.lat, self.lng = data when Hash, Location data.each { |key, value| case key.to_sym when :lat, :latitude self.lat = value when :lng, :longitude self.lng = value when :radius self.radius = value when :speed self.speed = value when :course self.course = value end } else raise ArgumentError, 'unsupported location data' end yield self if block_given? end def lat=(value) self[:lat] = floatify(value) { |f| if f.abs <= 90 f else raise ArgumentError, 'out of bounds' end } end alias latitude lat alias latitude= lat= def lng=(value) self[:lng] = floatify(value) { |f| if f.abs <= 180 f else raise ArgumentError, 'out of bounds' end } end alias longitude lng alias longitude= lng= def radius=(value) self[:radius] = floatify(value) { |f| f if f >= 0 } end def speed=(value) self[:speed] = floatify(value) { |f| f if f >= 0 } end def course=(value) self[:course] = floatify(value) { |f| f if (0..360).cover?(f) } end def present? lat && lng end def empty? !present? end def latlng "#{lat},#{lng}" end private def floatify(value) case value when nil, '' nil else float = Float(value) if block_given? yield(float) else float end end end public def to_liquid Drop.new(self) end class Drop < LiquidDroppable::Drop KEYS = Location.members.map(&:to_s).concat(%w[latitude longitude latlng]) def liquid_method_missing(key) if KEYS.include?(key) @object.__send__(key) end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/lib/feedjira_extension.rb
lib/feedjira_extension.rb
require 'feedjira' require 'digest' require 'mail' module FeedjiraExtension AUTHOR_ATTRS = %i[name email uri] LINK_ATTRS = %i[href rel type hreflang title length] ENCLOSURE_ATTRS = %i[url type length] class Author < Struct.new(*AUTHOR_ATTRS) def empty? all?(&:nil?) end def to_json(options = nil) each_pair.flat_map { |key, value| if value.presence case key when :email "<#{value}>" when :uri "(#{value})" else value end else [] end }.join(' ').to_json(options) end end class AtomAuthor < Author include SAXMachine AUTHOR_ATTRS.each do |attr| element attr end end class RssAuthor < Author include SAXMachine def content=(content) @content = content begin addr = Mail::Address.new(content) rescue self.name = content else self.name = addr.name rescue nil self.email = addr.address rescue nil end end value :content end class ITunesRssOwner < Author include SAXMachine element :'itunes:name', as: :name element :'itunes:email', as: :email end class Enclosure include SAXMachine ENCLOSURE_ATTRS.each do |attr| attribute attr end def to_json(options = nil) ENCLOSURE_ATTRS.each_with_object({}) { |key, hash| if value = __send__(key) hash[key] = value end }.to_json(options) end end class AtomLink include SAXMachine LINK_ATTRS.each do |attr| attribute attr end def empty? LINK_ATTRS.all? { |attr| __send__(attr).nil? } end def to_json(options = nil) LINK_ATTRS.each_with_object({}) { |key, hash| if value = __send__(key) hash[key] = value end }.to_json(options) end end class RssLinkElement include SAXMachine value :href def empty? !href.is_a?(String) end def to_json(options = nil) case href when String { href: href } else # Ignore non-string values, because SaxMachine leaks its # internal value :no_buffer when the content of an element # is empty. {} end.to_json(options) end end module HasAuthors def self.included(mod) mod.module_exec do case name when /RSS/ %w[ itunes:author dc:creator author managingEditor ].each do |name| sax_config.top_level_elements[name].clear elements name, class: RssAuthor, as: :_authors end else elements :author, class: AtomAuthor, as: :_authors end def authors _authors.reject(&:empty?) end end end end module HasEnclosure def self.included(mod) mod.module_exec do sax_config.top_level_elements['enclosure'].clear element :enclosure, class: Enclosure def image_enclosure case enclosure.try!(:type) when %r{\Aimage/} enclosure end end def image @image ||= image_enclosure.try!(:url) end end end end module HasLinks def self.included(mod) mod.module_exec do sax_config.top_level_elements['link'].clear sax_config.collection_elements['link'].clear case name when /RSS/ elements :link, class: RssLinkElement, as: :rss_links case name when /FeedBurner/ elements :'atok10:link', class: AtomLink, as: :atom_links def _links [*rss_links, *atom_links] end else alias_method :_links, :rss_links end prepend( Module.new { def url super || (alternate_link || links.first).try!(:href) end } ) when /Atom/ elements :link, class: AtomLink, as: :_links def url (alternate_link || links.first).try!(:href) end end def links _links.reject(&:empty?) end def alternate_link links.find { |link| link.is_a?(AtomLink) && link.rel == 'alternate' && (link.type == 'text/html'|| link.type.nil?) } end end end end module HasTimestamps attr_reader :published, :updated # Keep the "oldest" publish time found def published=(value) parsed = parse_datetime(value) @published = parsed if !@published || parsed < @published end # Keep the most recent update time found def updated=(value) parsed = parse_datetime(value) @updated = parsed if !@updated || parsed > @updated end def date_published published.try(:iso8601) end def last_updated (updated || published).try(:iso8601) end private def parse_datetime(string) DateTime.parse(string) rescue nil end end module FeedEntryExtensions def self.included(mod) mod.module_exec do include HasAuthors include HasEnclosure include HasLinks include HasTimestamps end end def id entry_id || @dc_identifier || Digest::MD5.hexdigest(content || summary || '') end end module FeedExtensions def self.included(mod) mod.module_exec do include HasAuthors include HasEnclosure include HasLinks include HasTimestamps element :id, as: :feed_id element :generator elements :rights element :published element :updated element :icon if /RSS/ === name element :guid, as: :feed_id element :copyright element :pubDate, as: :published element :'dc:date', as: :published element :lastBuildDate, as: :updated element :image, value: :url, as: :icon def copyright @copyright || super end if /ITunes/ === name sax_config.collection_elements['itunes:owner'].clear elements :"itunes:owner", as: :_itunes_owners, class: ITunesRssOwner private :_itunes_owners def itunes_owners _itunes_owners.reject(&:empty?) end end else element :subtitle, as: :description unless method_defined?(:description) end sax_config.collection_elements.each_value do |collection_elements| collection_elements.each do |collection_element| collection_element.accessor == 'entries' && (entry_class = collection_element.data_class).is_a?(Class) or next entry_class.send :include, FeedEntryExtensions end end end end def copyright rights.join("\n").presence end end Feedjira.parsers.each do |feed_class| feed_class.send :include, FeedExtensions end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/lib/liquid_migrator.rb
lib/liquid_migrator.rb
module LiquidMigrator def self.convert_all_agent_options(agent) agent.options = self.convert_hash(agent.options, {:merge_path_attributes => true, :leading_dollarsign_is_jsonpath => true}) agent.save! end def self.convert_hash(hash, options={}) options = {:merge_path_attributes => false, :leading_dollarsign_is_jsonpath => false}.merge options keys_to_remove = [] hash.tap do |hash| hash.each_pair do |key, value| case value.class.to_s when 'String', 'FalseClass', 'TrueClass' path_key = "#{key}_path" if options[:merge_path_attributes] && !hash[path_key].nil? # replace the value if the path is present value = hash[path_key] if hash[path_key].present? # in any case delete the path attibute keys_to_remove << path_key end hash[key] = LiquidMigrator.convert_string value, options[:leading_dollarsign_is_jsonpath] when 'ActiveSupport::HashWithIndifferentAccess' hash[key] = convert_hash(hash[key], options) when 'Array' hash[key] = hash[key].collect { |k| if k.class == String convert_string(k, options[:leading_dollarsign_is_jsonpath]) else convert_hash(k, options) end } end end # remove the unneeded *_path attributes end.select { |k, v| !keys_to_remove.include? k } end def self.convert_string(string, leading_dollarsign_is_jsonpath=false) if string == true || string == false # there might be empty *_path attributes for boolean defaults string elsif string[0] == '$' && leading_dollarsign_is_jsonpath # in most cases a *_path attribute convert_json_path string else # migrate the old interpolation syntax to the new liquid based string.gsub(/<([^>]+)>/).each do match = $1 if match =~ /\Aescape / # convert the old escape syntax to a liquid filter self.convert_json_path(match.gsub(/\Aescape /, '').strip, ' | uri_escape') else self.convert_json_path(match.strip) end end end end def self.convert_make_message(string) string.gsub(/<([^>]+)>/, "{{\\1}}") end def self.convert_json_path(string, filter = "") check_path(string) if string.start_with? '$.' "{{#{string[2..-1]}#{filter}}}" else "{{#{string[1..-1]}#{filter}}}" end end def self.check_path(string) if string !~ /\A(\$\.?)?(\w+\.)*(\w+)\Z/ raise "JSONPath '#{string}' is too complex, please check your migration." end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/lib/huginn_scheduler.rb
lib/huginn_scheduler.rb
require 'rufus/scheduler' class Rufus::Scheduler SCHEDULER_AGENT_TAG = Agents::SchedulerAgent.name class Job # Store an ID of SchedulerAgent in this job. def scheduler_agent_id=(id) self[:scheduler_agent_id] = id end # Extract an ID of SchedulerAgent if any. def scheduler_agent_id self[:scheduler_agent_id] end # Return a SchedulerAgent tied to this job. Return nil if it is # not found or disabled. def scheduler_agent agent_id = scheduler_agent_id or return nil Agent.of_type(Agents::SchedulerAgent).active.find_by(id: agent_id) end end # Get all jobs tied to any SchedulerAgent def scheduler_agent_jobs jobs(tag: SCHEDULER_AGENT_TAG) end # Get a job tied to a given SchedulerAgent def scheduler_agent_job(agent) scheduler_agent_jobs.find { |job| job.scheduler_agent_id == agent.id } end # Schedule or reschedule a job for a given SchedulerAgent and return # the running job. Return nil if unscheduled. def schedule_scheduler_agent(agent) job = scheduler_agent_job(agent) if agent.unavailable? if job puts "Unscheduling SchedulerAgent##{agent.id} (disabled)" job.unschedule end nil else if job return job if agent.memory['scheduled_at'] == job.scheduled_at.to_i puts "Rescheduling SchedulerAgent##{agent.id}" job.unschedule else puts "Scheduling SchedulerAgent##{agent.id}" end agent_id = agent.id job = schedule_cron agent.options['schedule'], tag: SCHEDULER_AGENT_TAG do |job| job.scheduler_agent_id = agent_id if scheduler_agent = job.scheduler_agent scheduler_agent.control! else puts "Unscheduling SchedulerAgent##{job.scheduler_agent_id} (disabled or deleted)" job.unschedule end end # Make sure the job is associated with a SchedulerAgent before # it is triggered. job.scheduler_agent_id = agent_id agent.memory['scheduled_at'] = job.scheduled_at.to_i agent.save job end end # Schedule or reschedule jobs for all SchedulerAgents and unschedule # orphaned jobs if any. def schedule_scheduler_agents scheduled_jobs = Agent.of_type(Agents::SchedulerAgent).map { |scheduler_agent| schedule_scheduler_agent(scheduler_agent) }.compact (scheduler_agent_jobs - scheduled_jobs).each { |job| puts "Unscheduling SchedulerAgent##{job.scheduler_agent_id} (orphaned)" job.unschedule } end end class HuginnScheduler < LongRunnable::Worker include LongRunnable FAILED_JOBS_TO_KEEP = 100 SCHEDULE_TO_CRON = { '1m' => '*/1 * * * *', '2m' => '*/2 * * * *', '5m' => '*/5 * * * *', '10m' => '*/10 * * * *', '30m' => '*/30 * * * *', '1h' => '0 * * * *', '2h' => '0 */2 * * *', '5h' => '0 */5 * * *', '12h' => '0 */12 * * *', '1d' => '0 0 * * *', '2d' => '0 0 */2 * *', '7d' => '0 0 * * 1', } def setup Time.zone = ENV['TIMEZONE'].presence || 'Pacific Time (US & Canada)' tzinfo_friendly_timezone = Time.zone.tzinfo.identifier # Schedule event propagation. every '1m' do propagate! end # Schedule event cleanup. every ENV['EVENT_EXPIRATION_CHECK'].presence || '6h' do cleanup_expired_events! end # Schedule failed job cleanup. every '1h' do cleanup_failed_jobs! end # Schedule repeating events. SCHEDULE_TO_CRON.keys.each do |schedule| cron "#{SCHEDULE_TO_CRON[schedule]} #{tzinfo_friendly_timezone}" do run_schedule "every_#{schedule}" end end # Schedule events for specific times. 24.times do |hour| cron "0 #{hour} * * * " + tzinfo_friendly_timezone do run_schedule hour_to_schedule_name(hour) end end # Schedule Scheduler Agents every '1m' do @scheduler.schedule_scheduler_agents end end def run @scheduler.join end def self.setup_worker [new(id: self.to_s)] end private def run_schedule(time) with_mutex do puts "Queuing schedule for #{time}" AgentRunScheduleJob.perform_later(time) end end def propagate! with_mutex do return unless AgentPropagateJob.can_enqueue? puts "Queuing event propagation" AgentPropagateJob.perform_later end end def cleanup_expired_events! with_mutex do puts "Running event cleanup" AgentCleanupExpiredJob.perform_later end end def cleanup_failed_jobs! num_to_keep = (ENV['FAILED_JOBS_TO_KEEP'].presence || FAILED_JOBS_TO_KEEP).to_i first_to_delete = Delayed::Job.where.not(failed_at: nil).order("failed_at DESC").offset(num_to_keep).limit(1).pluck(:failed_at).first Delayed::Job.where(["failed_at <= ?", first_to_delete]).delete_all if first_to_delete.present? end def hour_to_schedule_name(hour) if hour == 0 "midnight" elsif hour < 12 "#{hour}am" elsif hour == 12 "noon" else "#{hour - 12}pm" end end def with_mutex mutex.synchronize do ActiveRecord::Base.connection_pool.with_connection do yield end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/lib/json_with_indifferent_access.rb
lib/json_with_indifferent_access.rb
class JsonWithIndifferentAccess def self.load(json) ActiveSupport::HashWithIndifferentAccess.new(JSON.parse(json || '{}')) rescue JSON::ParserError Rails.logger.error "Unparsable JSON in JsonWithIndifferentAccess: #{json}" { 'error' => 'unparsable json detected during de-serialization' } end def self.dump(hash) JSON.dump(hash) end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/lib/delayed_job_worker.rb
lib/delayed_job_worker.rb
class DelayedJobWorker < LongRunnable::Worker include LongRunnable def run @dj = Delayed::Worker.new @dj.start end def stop @dj.stop if @dj end def self.setup_worker [new(id: self.to_s)] end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/lib/gemfile_helper.rb
lib/gemfile_helper.rb
class GemfileHelper class << self def rails_env ENV['RAILS_ENV'] || case File.basename($0) when 'rspec' 'test' when 'rake' 'test' if ARGV.any?(/\Aspec(?:\z|:)/) end || 'development' end def load_dotenv root = Pathname.new(__dir__).parent dotenv_dir = (root / 'vendor/gems').glob('dotenv-[0-9]*').last yield dotenv_dir.to_s if block_given? return if ENV['ON_HEROKU'] == 'true' $:.unshift dotenv_dir.join('lib').to_s require "dotenv" $:.shift sanity_check Dotenv.load( root.join(".env.local"), root.join(".env.#{rails_env}"), root.join(".env") ) end GEM_NAME = /[A-Za-z0-9.\-_]+/ GEM_OPTIONS = /(.+?)\s*(?:,\s*(.+?))?/ GEM_SEPARATOR = /\s*(?:,|\z)/ GEM_REGULAR_EXPRESSION = /(#{GEM_NAME})(?:\(#{GEM_OPTIONS}\))?#{GEM_SEPARATOR}/ def parse_each_agent_gem(string) return unless string string.scan(GEM_REGULAR_EXPRESSION).each do |name, version, args| if version =~ /\w+:/ args = "#{version},#{args}" version = nil end yield [name, version, parse_gem_args(args)].compact end end private def parse_gem_args(args) return nil unless args args.scan(/(\w+):\s*(.+?)#{GEM_SEPARATOR}/).to_h { |key, value| [key.to_sym, value] } end def sanity_check(env) return if ENV['CI'] == 'true' || ENV['APP_SECRET_TOKEN'] || !env.empty? # .env is not necessary in bundle update/lock; this helps Renovate return if (File.basename($0) in 'bundle' | 'bundler') && (ARGV.first in 'lock' | 'update') puts warning require "shellwords" puts "command: #{[$0, *ARGV].shelljoin}" raise "Could not load huginn settings from .env file." end def warning <<~EOF Could not load huginn settings from .env file. Make sure to copy the .env.example to .env and change it to match your configuration. Capistrano 2 users: Make sure shared files are symlinked before bundle runs: before 'bundle:install', 'deploy:symlink_configs' EOF end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false