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/db/migrate/20140515211100_create_services.rb
db/migrate/20140515211100_create_services.rb
class CreateServices < ActiveRecord::Migration[4.2] def change create_table :services do |t| t.integer :user_id, null: false t.string :provider, null: false t.string :name, null: false t.text :token, null: false t.text :secret t.text :refresh_token t.datetime :expires_at t.boolean :global, default: false t.text :options t.timestamps end add_index :services, :user_id add_index :services, [:user_id, :global] end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20140403043556_add_disabled_to_agent.rb
db/migrate/20140403043556_add_disabled_to_agent.rb
class AddDisabledToAgent < ActiveRecord::Migration[4.2] def change add_column :agents, :disabled, :boolean, :default => false, :null => false end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20140509170420_create_scenarios.rb
db/migrate/20140509170420_create_scenarios.rb
class CreateScenarios < ActiveRecord::Migration[4.2] def change create_table :scenarios do |t| t.string :name, :null => false t.integer :user_id, :null => false t.timestamps end add_column :users, :scenario_count, :integer, :null => false, :default => 0 end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20140820003139_add_tag_color_to_scenarios.rb
db/migrate/20140820003139_add_tag_color_to_scenarios.rb
class AddTagColorToScenarios < ActiveRecord::Migration[4.2] def change add_column :scenarios, :tag_bg_color, :string add_column :scenarios, :tag_fg_color, :string end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20160302095413_add_deactivated_at_to_users.rb
db/migrate/20160302095413_add_deactivated_at_to_users.rb
class AddDeactivatedAtToUsers < ActiveRecord::Migration[4.2] def change add_column :users, :deactivated_at, :datetime add_index :users, :deactivated_at end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20140213053001_add_event_id_at_creation_to_links.rb
db/migrate/20140213053001_add_event_id_at_creation_to_links.rb
class AddEventIdAtCreationToLinks < ActiveRecord::Migration[4.2] class Link < ActiveRecord::Base; end class Event < ActiveRecord::Base; end def up add_column :links, :event_id_at_creation, :integer, :null => false, :default => 0 Link.all.find_each do |link| last_event_id = execute( <<-SQL SELECT #{ActiveRecord::Base.connection.quote_column_name('id')} FROM #{ActiveRecord::Base.connection.quote_table_name('events')} WHERE events.agent_id = #{link.source_id} ORDER BY events.id DESC limit 1 SQL ).first.to_a.first if last_event_id.nil? link.event_id_at_creation = Event.last.id else link.event_id_at_creation = last_event_id end link.save end end def down remove_column :links, :event_id_at_creation end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20160807000122_remove_queue_from_email_digest_agent_memory.rb
db/migrate/20160807000122_remove_queue_from_email_digest_agent_memory.rb
class RemoveQueueFromEmailDigestAgentMemory < ActiveRecord::Migration[4.2] def up Agents::EmailDigestAgent.find_each do |agent| agent.memory.delete("queue") agent.save!(validate: false) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20140809211540_remove_service_index_on_user_id.rb
db/migrate/20140809211540_remove_service_index_on_user_id.rb
class RemoveServiceIndexOnUserId < ActiveRecord::Migration[4.2] def change remove_index :services, :user_id end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20160224120316_add_mode_option_to_ftpsite_agents.rb
db/migrate/20160224120316_add_mode_option_to_ftpsite_agents.rb
class AddModeOptionToFtpsiteAgents < ActiveRecord::Migration[4.2] def up Agents::FtpsiteAgent.find_each do |agent| agent.options['mode'] = 'read' agent.save!(validate: false) end end def down Agents::FtpsiteAgent.find_each do |agent| agent.options.delete 'mode' agent.save!(validate: false) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20130126080736_change_memory_to_long_text.rb
db/migrate/20130126080736_change_memory_to_long_text.rb
# PG allows arbitrarily long text fields but MySQL has default limits. Make those limits larger if we're using MySQL. class ChangeMemoryToLongText < ActiveRecord::Migration[4.2] def up if mysql? change_column :agents, :memory, :text, :limit => 4294967295 change_column :events, :payload, :text, :limit => 16777215 end end def down if mysql? change_column :agents, :memory, :text, :limit => 65535 change_column :events, :payload, :text, :limit => 65535 end end def mysql? ActiveRecord::Base.connection.adapter_name =~ /mysql/i end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20160405072512_post_agent_set_event_header_style.rb
db/migrate/20160405072512_post_agent_set_event_header_style.rb
class PostAgentSetEventHeaderStyle < ActiveRecord::Migration[4.2] def up Agent.of_type("Agents::PostAgent").each do |post_agent| if post_agent.send(:boolify, post_agent.options['emit_events']) && !post_agent.options.key?('event_headers_style') post_agent.options['event_headers_style'] = 'raw' post_agent.save! end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20131223032112_switch_to_json_serialization.rb
db/migrate/20131223032112_switch_to_json_serialization.rb
class SwitchToJsonSerialization < ActiveRecord::Migration[4.2] FIELDS = { :agents => [:options, :memory], :events => [:payload] } def up if data_exists? puts "This migration will update tables to use UTF-8 encoding and will update Agent and Event storage from YAML to JSON." puts "It should work, but please make a backup before proceeding!" print "Continue? (y/n) " STDOUT.flush exit unless STDIN.gets =~ /^y/i set_to_utf8 translate YAML, JSON end end def down if data_exists? translate JSON, YAML end end def set_to_utf8 if mysql? %w[agent_logs agents delayed_jobs events links users].each do |table_name| quoted_table_name = ActiveRecord::Base.connection.quote_table_name(table_name) execute "ALTER TABLE #{quoted_table_name} CONVERT TO CHARACTER SET utf8" end end end def mysql? ActiveRecord::Base.connection.adapter_name =~ /mysql/i end def data_exists? events = ActiveRecord::Base.connection.select_rows("SELECT count(*) FROM #{ActiveRecord::Base.connection.quote_table_name("events")}").first.first.to_i agents = ActiveRecord::Base.connection.select_rows("SELECT count(*) FROM #{ActiveRecord::Base.connection.quote_table_name("agents")}").first.first.to_i agents + events > 0 end def translate(from, to) FIELDS.each do |table, fields| quoted_table_name = ActiveRecord::Base.connection.quote_table_name(table) fields = fields.map { |f| ActiveRecord::Base.connection.quote_column_name(f) } page_start = 0 page_size = 1000 page_end = page_start + page_size begin rows = ActiveRecord::Base.connection.select_rows("SELECT id, #{fields.join(", ")} FROM #{quoted_table_name} WHERE id >= #{page_start} AND id < #{page_end}") puts "Grabbing rows of #{table} from #{page_start} to #{page_end}" rows.each do |row| id, *field_data = row yaml_fields = field_data.map { |f| from.load(f) }.map { |f| to.dump(f) } yaml_fields.map! {|f| f.encode('utf-8', 'binary', invalid: :replace, undef: :replace, replace: '??') } update_sql = "UPDATE #{quoted_table_name} SET #{fields.map {|f| "#{f}=?"}.join(", ")} WHERE id = ?" sanitized_update_sql = ActiveRecord::Base.send :sanitize_sql_array, [update_sql, *yaml_fields, id] ActiveRecord::Base.connection.execute sanitized_update_sql end page_start += page_size page_end += page_size end until rows.count == 0 end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20241027081918_website_agent_rename_array_to_single_array.rb
db/migrate/20241027081918_website_agent_rename_array_to_single_array.rb
class WebsiteAgentRenameArrayToSingleArray < ActiveRecord::Migration[6.1] def up Agents::WebsiteAgent.find_each do |agent| case extract = agent.options['extract'] when Hash extract.each_value do |details| if details.is_a?(Hash) && details.key?('array') details['single_array'] = details.delete('array') end end agent.save(validate: false) end end end def down Agents::WebsiteAgent.find_each do |agent| case extract = agent.options['extract'] when Hash extract.each_value do |details| if details.is_a?(Hash) && details.key?('single_array') details['array'] = details.delete('single_array') end end agent.save(validate: false) end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20230622140301_delete_empty_keys_and_values_from_key_value_store_agents.rb
db/migrate/20230622140301_delete_empty_keys_and_values_from_key_value_store_agents.rb
class DeleteEmptyKeysAndValuesFromKeyValueStoreAgents < ActiveRecord::Migration[6.1] def up Agents::KeyValueStoreAgent.find_each do |agent| agent.memory.delete_if { |key, value| key.empty? || value.nil? || value.try(:empty?) } agent.save! end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20161124065838_add_templates_to_resolve_url.rb
db/migrate/20161124065838_add_templates_to_resolve_url.rb
class AddTemplatesToResolveUrl < ActiveRecord::Migration[5.0] def up Agents::WebsiteAgent.find_each do |agent| if agent.event_keys.try!(:include?, 'url') agent.options['template'] = (agent.options['template'] || {}).tap { |template| template['url'] ||= '{{ url | to_uri: _response_.url }}' } agent.save!(validate: false) end end end def down # No need to revert end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20131227000021_add_cached_dates_to_agent.rb
db/migrate/20131227000021_add_cached_dates_to_agent.rb
class AddCachedDatesToAgent < ActiveRecord::Migration[4.2] def up add_column :agents, :last_event_at, :datetime execute "UPDATE agents SET last_event_at = (SELECT created_at FROM events WHERE events.agent_id = agents.id ORDER BY id DESC LIMIT 1)" add_column :agents, :last_error_log_at, :datetime execute "UPDATE agents SET last_error_log_at = (SELECT created_at FROM agent_logs WHERE agent_logs.agent_id = agents.id AND agent_logs.level >= 4 ORDER BY id DESC LIMIT 1)" end def down remove_column :agents, :last_event_at remove_column :agents, :last_error_log_at end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20150219213604_add_type_option_attribute_to_pushbullet_agents.rb
db/migrate/20150219213604_add_type_option_attribute_to_pushbullet_agents.rb
class AddTypeOptionAttributeToPushbulletAgents < ActiveRecord::Migration[4.2] def up Agents::PushbulletAgent.find_each do |agent| if agent.options['type'].nil? agent.options['type'] = 'note' agent.save! end end end def down Agents::PushbulletAgent.find_each do |agent| if agent.options['type'].present? agent.options.delete 'type' agent.save(validate: false) end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20140722131220_convert_efa_skip_agent.rb
db/migrate/20140722131220_convert_efa_skip_agent.rb
class ConvertEfaSkipAgent < ActiveRecord::Migration[4.2] def up Agent.where(type: 'Agents::EventFormattingAgent').each do |agent| agent.options_will_change! unless agent.options.delete('skip_agent').to_s == 'true' agent.options['instructions'] = { 'agent' => '{{agent.type}}' }.update(agent.options['instructions'] || {}) end agent.save! end end def down Agent.where(type: 'Agents::EventFormattingAgent').each do |agent| agent.options_will_change! agent.options['skip_agent'] = (agent.options['instructions'] || {})['agent'] == '{{agent.type}}' agent.save! end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20160108221620_website_agent_does_not_use_event_url.rb
db/migrate/20160108221620_website_agent_does_not_use_event_url.rb
class WebsiteAgentDoesNotUseEventUrl < ActiveRecord::Migration[4.2] def up # Until this migration, if a WebsiteAgent received Events and did not have a `url_from_event` option set, # it would use the `url` from the Event's payload. If the Event did not have a `url` in its payload, the # WebsiteAgent would do nothing. This migration assumes that if someone has wired a WebsiteAgent to receive Events # and has not set `url_from_event` or `data_from_event`, they were trying to use the Event's `url` payload, so we # set `url_from_event` to `{{ url }}` for them. Agents::WebsiteAgent.find_each do |agent| next unless agent.sources.count > 0 if !agent.options['data_from_event'].present? && !agent.options['url_from_event'].present? agent.options['url_from_event'] = '{{ url }}' agent.save! puts ">> Setting `url_from_event` on WebsiteAgent##{agent.id} to {{ url }} because it is wired" puts ">> to receive Events, and the WebsiteAgent no longer uses the Event's `url` value directly." end end end def down end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20121222074732_create_links.rb
db/migrate/20121222074732_create_links.rb
class CreateLinks < ActiveRecord::Migration[4.2] def change create_table :links do |t| t.integer :source_id t.integer :receiver_id t.timestamps end add_index :links, [:source_id, :receiver_id] end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20120919063304_add_username_to_users.rb
db/migrate/20120919063304_add_username_to_users.rb
class AddUsernameToUsers < ActiveRecord::Migration[4.2] class User < ActiveRecord::Base end def up add_column :users, :username, :string User.find_each do |user| user.update_attribute :username, user.email.gsub(/@.*$/, '') end change_column :users, :username, :string, :null => false add_index :users, :username, :unique => true end def down remove_column :users, :username end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20140811200922_add_uid_column_to_services.rb
db/migrate/20140811200922_add_uid_column_to_services.rb
class AddUidColumnToServices < ActiveRecord::Migration[4.2] def change add_column :services, :uid, :string add_index :services, :uid add_index :services, :provider end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20140121075418_create_user_credentials.rb
db/migrate/20140121075418_create_user_credentials.rb
class CreateUserCredentials < ActiveRecord::Migration[4.2] def change create_table :user_credentials do |t| t.integer :user_id, :null => false t.string :credential_name, :null => false t.text :credential_value, :null => false t.timestamps end add_index :user_credentials, [:user_id, :credential_name], :unique => true end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20140509170443_create_scenario_memberships.rb
db/migrate/20140509170443_create_scenario_memberships.rb
class CreateScenarioMemberships < ActiveRecord::Migration[4.2] def change create_table :scenario_memberships do |t| t.integer :agent_id, :null => false t.integer :scenario_id, :null => false t.timestamps end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20160607055850_change_events_order_to_events_list_order.rb
db/migrate/20160607055850_change_events_order_to_events_list_order.rb
class ChangeEventsOrderToEventsListOrder < ActiveRecord::Migration[4.2] def up Agents::DataOutputAgent.find_each do |agent| if value = agent.options.delete('events_order') agent.options['events_list_order'] = value agent.save!(validate: false) end end end def down Agents::DataOutputAgent.transaction do Agents::DataOutputAgent.find_each do |agent| if agent.options['events_order'] raise ActiveRecord::IrreversibleMigration, "Cannot revert migration because events_order is configured" end if value = agent.options.delete('events_list_order') agent.options['events_order'] = value agent.save!(validate: false) end end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20140730005210_convert_efa_skip_created_at.rb
db/migrate/20140730005210_convert_efa_skip_created_at.rb
class ConvertEfaSkipCreatedAt < ActiveRecord::Migration[4.2] def up Agent.where(type: 'Agents::EventFormattingAgent').each do |agent| agent.options_will_change! unless agent.options.delete('skip_created_at').to_s == 'true' agent.options['instructions'] = { 'created_at' => '{{created_at}}' }.update(agent.options['instructions'] || {}) end agent.save! end end def down Agent.where(type: 'Agents::EventFormattingAgent').each do |agent| agent.options_will_change! agent.options['skip_created_at'] = (agent.options['instructions'] || {})['created_at'] == '{{created_at}}' agent.save! end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20140531232016_add_fields_to_scenarios.rb
db/migrate/20140531232016_add_fields_to_scenarios.rb
class AddFieldsToScenarios < ActiveRecord::Migration[4.2] def change add_column :scenarios, :description, :text add_column :scenarios, :public, :boolean, :default => false, :null => false add_column :scenarios, :guid, :string change_column :scenarios, :guid, :string, :null => false add_column :scenarios, :source_url, :string end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20170307190555_add_min_events_option_to_peak_detector_agents.rb
db/migrate/20170307190555_add_min_events_option_to_peak_detector_agents.rb
class AddMinEventsOptionToPeakDetectorAgents < ActiveRecord::Migration[5.0] def up Agents::PeakDetectorAgent.find_each do |agent| if agent.options['min_events'].nil? agent.options['min_events'] = '4' agent.save(validate: false) end end end def down Agents::PeakDetectorAgent.find_each do |agent| if agent.options['min_events'].present? agent.options.delete 'min_events' agent.save(validate: false) end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20130819160603_create_agent_logs.rb
db/migrate/20130819160603_create_agent_logs.rb
class CreateAgentLogs < ActiveRecord::Migration[4.2] def change create_table :agent_logs do |t| t.integer :agent_id, :null => false t.text :message, :null => false t.integer :level, :default => 3, :null => false t.integer :inbound_event_id t.integer :outbound_event_id t.timestamps end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20170419073748_set_rss_content_type.rb
db/migrate/20170419073748_set_rss_content_type.rb
class SetRssContentType < ActiveRecord::Migration[5.0] def up Agents::DataOutputAgent.find_each do |agent| if agent.options['rss_content_type'].nil? agent.options['rss_content_type'] = 'text/xml' agent.save(validate: false) end end end def down Agents::DataOutputAgent.find_each do |agent| if agent.options.delete('rss_content_type') agent.save(validate: false) end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20140525150140_migrate_agents_to_service_authentication.rb
db/migrate/20140525150140_migrate_agents_to_service_authentication.rb
class MigrateAgentsToServiceAuthentication < ActiveRecord::Migration[4.2] def twitter_consumer_key(agent) agent.options['consumer_key'].presence || agent.credential('twitter_consumer_key') end def twitter_consumer_secret(agent) agent.options['consumer_secret'].presence || agent.credential('twitter_consumer_secret') end def twitter_oauth_token(agent) agent.options['oauth_token'].presence || agent.options['access_key'].presence || agent.credential('twitter_oauth_token') end def twitter_oauth_token_secret(agent) agent.options['oauth_token_secret'].presence || agent.options['access_secret'].presence || agent.credential('twitter_oauth_token_secret') end def up agents = Agent.where(type: ['Agents::TwitterUserAgent', 'Agents::TwitterStreamAgent', 'Agents::TwitterPublishAgent']).each do |agent| service = agent.user.services.create!( provider: 'twitter', name: "Migrated '#{agent.name}'", token: twitter_oauth_token(agent), secret: twitter_oauth_token_secret(agent) ) agent.service_id = service.id agent.save!(validate: false) end migrated = false if agents.length > 0 puts <<-EOF.strip_heredoc Your Twitter agents were successfully migrated. You need to update your .env file and add the following two lines: TWITTER_OAUTH_KEY=#{twitter_consumer_key(agents.first)} TWITTER_OAUTH_SECRET=#{twitter_consumer_secret(agents.first)} To authenticate new accounts with your twitter OAuth application you need to log in the to twitter application management page (https://apps.twitter.com/) and set the callback URL of your application to "http#{ENV['FORCE_SSL'] == 'true' ? 's' : ''}://#{ENV['DOMAIN']}/auth/twitter/callback" EOF migrated = true end sleep 20 if migrated end def down raise ActiveRecord::IrreversibleMigration, "Cannot revert migration to OAuth services" end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20120728215449_add_admin_to_users.rb
db/migrate/20120728215449_add_admin_to_users.rb
class AddAdminToUsers < ActiveRecord::Migration[4.2] def change add_column :users, :admin, :boolean, :default => false, :null => false end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20140603104211_rename_digest_email_to_email_digest.rb
db/migrate/20140603104211_rename_digest_email_to_email_digest.rb
class RenameDigestEmailToEmailDigest < ActiveRecord::Migration[4.2] def up sql = <<-SQL UPDATE #{ActiveRecord::Base.connection.quote_table_name('agents')} SET #{ActiveRecord::Base.connection.quote_column_name('type')} = 'Agents::EmailDigestAgent' WHERE #{ActiveRecord::Base.connection.quote_column_name('type')} = 'Agents::DigestEmailAgent' SQL execute sql end def down sql = <<-SQL UPDATE #{ActiveRecord::Base.connection.quote_table_name('agents')} SET #{ActiveRecord::Base.connection.quote_column_name('type')} = 'Agents::DigestEmailAgent' WHERE #{ActiveRecord::Base.connection.quote_column_name('type')} = 'Agents::EmailDigestAgent' SQL execute sql end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20140525150040_add_service_id_to_agents.rb
db/migrate/20140525150040_add_service_id_to_agents.rb
class AddServiceIdToAgents < ActiveRecord::Migration[4.2] def change add_column :agents, :service_id, :integer end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20130124050117_add_indexes.rb
db/migrate/20130124050117_add_indexes.rb
class AddIndexes < ActiveRecord::Migration[4.2] def change add_index :links, [:receiver_id, :source_id] end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/db/migrate/20150507153436_update_keep_events_for_to_be_in_seconds.rb
db/migrate/20150507153436_update_keep_events_for_to_be_in_seconds.rb
class UpdateKeepEventsForToBeInSeconds < ActiveRecord::Migration[4.2] class Agent < ActiveRecord::Base; end SECONDS_IN_DAY = 60 * 60 * 24 def up Agent.update_all ['keep_events_for = keep_events_for * ?', SECONDS_IN_DAY] end def down Agent.update_all ['keep_events_for = keep_events_for / ?', SECONDS_IN_DAY] end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/bin/twitter_stream.rb
bin/twitter_stream.rb
#!/usr/bin/env ruby # This process is used by TwitterStreamAgents to watch the Twitter stream in real time. It periodically checks for # new or changed TwitterStreamAgents and starts to follow the stream for them. It is typically run by foreman via # the included Procfile. require_relative './pre_runner_boot' AgentRunner.new(only: Agents::TwitterStreamAgent).run
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/bin/threaded.rb
bin/threaded.rb
#!/usr/bin/env ruby require_relative './pre_runner_boot' agent_runner = AgentRunner.new # We need to wait a bit to let delayed_job set it's traps so we can override them Thread.new do sleep 5 agent_runner.set_traps end agent_runner.run
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/bin/agent_runner.rb
bin/agent_runner.rb
#!/usr/bin/env ruby # This process is used to maintain Huginn's upkeep behavior, automatically running scheduled Agents and # periodically propagating and expiring Events. It also running TwitterStreamAgents and Agents that support long running # background jobs. require_relative './pre_runner_boot' AgentRunner.new(except: DelayedJobWorker).run
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/bin/pre_runner_boot.rb
bin/pre_runner_boot.rb
unless defined?(Rails) puts puts "Please run me with rails runner, for example:" puts " RAILS_ENV=production bundle exec rails runner bin/#{File.basename($0)}" puts exit 1 end Rails.configuration.cache_classes = true Dotenv.load if ENV['APP_SECRET_TOKEN'].blank?
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/bin/decrypt_backup.rb
bin/decrypt_backup.rb
#!/usr/bin/env ruby # If you're using the backup gem, described on the Huginn wiki and at doc/deployment/backup, then you can use this # utility to decrypt backups. in_file = ARGV.shift out_file = ARGV.shift || "decrypted_backup.tar" puts "About to decrypt #{in_file} and write it to #{out_file}." cmd = "bundle exec backup decrypt --encryptor openssl --base64 --salt --in #{in_file} --out #{out_file}" puts "Executing: #{cmd}" puts `#{cmd}`
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/bin/schedule.rb
bin/schedule.rb
#!/usr/bin/env ruby # This process is used to maintain Huginn's upkeep behavior, automatically running scheduled Agents and # periodically propagating and expiring Events. It's typically run via foreman and the included Procfile. require_relative './pre_runner_boot' AgentRunner.new(only: HuginnScheduler).run
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/capybara_helper.rb
spec/capybara_helper.rb
require 'rails_helper' require 'capybara/rails' require 'capybara-select-2' CAPYBARA_TIMEOUT = ENV['CI'] == 'true' ? 60 : 5 Capybara.javascript_driver = ENV['USE_HEADED_CHROME'] ? :selenium_chrome : :selenium_chrome_headless Capybara.default_max_wait_time = CAPYBARA_TIMEOUT RSpec.configure do |config| config.include Warden::Test::Helpers config.include AlertConfirmer, type: :feature config.include FeatureHelpers, type: :feature config.before(:suite) do Warden.test_mode! end config.after(:each) do Warden.test_reset! end end VCR.configure do |config| config.ignore_localhost = true end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/rails_helper.rb
spec/rails_helper.rb
ENV['RAILS_ENV'] ||= 'test' if ENV['COVERAGE'] require 'simplecov' SimpleCov.start 'rails' elsif ENV['CI'] == 'true' require 'simplecov' SimpleCov.start 'rails' do require 'simplecov-lcov' SimpleCov::Formatter::LcovFormatter.config do |c| c.report_with_single_file = true c.single_report_path = 'coverage/lcov.info' end formatter SimpleCov::Formatter::LcovFormatter add_filter %w[version.rb initializer.rb] end end # require File.expand_path('../config/environment', __dir__) require_relative '../config/environment' require 'rspec/rails' require 'webmock/rspec' WebMock.disable_net_connect!(allow_localhost: true) # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } ActiveRecord::Migration.maintain_test_schema! # Mix in shoulda matchers Shoulda::Matchers.configure do |config| config.integrate do |with| with.test_framework :rspec with.library :rails end end RSpec.configure do |config| config.mock_with :rspec # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = config.file_fixture_path = "#{::Rails.root}/spec/fixtures" # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. config.use_transactional_fixtures = true # rspec-rails 3 will no longer automatically infer an example group's spec type # from the file location. You can explicitly opt-in to this feature using this # snippet: config.infer_spec_type_from_file_location! # If true, the base class of anonymous controllers will be inferred # automatically. This will be the default behavior in future versions of # rspec-rails. config.infer_base_class_for_anonymous_controllers = false # These two settings work together to allow you to limit a spec run # to individual examples or groups you care about by tagging them with # `:focus` metadata. When nothing is tagged with `:focus`, all examples # get run. config.filter_run :focus if ENV['CI'] != 'true' config.run_all_when_everything_filtered = true # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = 'random' config.global_fixtures = :all config.render_views config.example_status_persistence_file_path = './spec/examples.txt' config.include Devise::Test::ControllerHelpers, type: :controller config.include SpecHelpers config.include ActiveSupport::Testing::TimeHelpers end require 'capybara_helper' if ENV['RSPEC_TASK'] != 'spec:nofeatures'
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/spec_helper.rb
spec/spec_helper.rb
# This file was generated by the `rails generate rspec:install` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # The generated `.rspec` file contains `--require spec_helper` which will cause # this file to always be loaded, without a need to explicitly require it in any # files. # # Given that it is always loaded, you are encouraged to keep this file as # light-weight as possible. Requiring heavyweight dependencies from this file # will add to the boot time of your test suite on EVERY test run, even for an # individual file that may not need all of that loaded. Instead, consider making # a separate helper file that requires the additional dependencies and performs # the additional setup, and require it from the spec files that actually need # it. # # See https://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end # This option will default to `:apply_to_host_groups` in RSpec 4 (and will # have no way to turn it off -- the option exists only for backwards # compatibility in RSpec 3). It causes shared context metadata to be # inherited by the metadata hash of host groups and examples, rather than # triggering implicit auto-inclusion in groups with matching metadata. config.shared_context_metadata_behavior = :apply_to_host_groups # The settings below are suggested to provide a good initial experience # with RSpec, but feel free to customize to your heart's content. =begin # This allows you to limit a spec run to individual examples or groups # you care about by tagging them with `:focus` metadata. When nothing # is tagged with `:focus`, all examples get run. RSpec also provides # aliases for `it`, `describe`, and `context` that include `:focus` # metadata: `fit`, `fdescribe` and `fcontext`, respectively. config.filter_run_when_matching :focus # Allows RSpec to persist some state between runs in order to support # the `--only-failures` and `--next-failure` CLI options. We recommend # you configure your source control system to ignore this file. config.example_status_persistence_file_path = "spec/examples.txt" # Limits the available syntax to the non-monkey patched syntax that is # recommended. For more details, see: # https://rspec.info/features/3-12/rspec-core/configuration/zero-monkey-patching-mode/ config.disable_monkey_patching! # Many RSpec users commonly either run the entire suite or an individual # file, and it's useful to allow more verbose output when running an # individual spec file. if config.files_to_run.one? # Use the documentation formatter for detailed output, # unless a formatter has already been configured # (e.g. via a command-line flag). config.default_formatter = "doc" end # Print the 10 slowest examples and example groups at the # end of the spec run, to help surface which specs are running # particularly slow. config.profile_examples = 10 # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = :random # Seed global randomization in this process using the `--seed` CLI option. # Setting this allows you to use `--seed` to deterministically reproduce # test failures related to randomization by passing the same `--seed` value # as the one that triggered the failure. Kernel.srand config.seed =end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/jobs/agent_reemit_job_spec.rb
spec/jobs/agent_reemit_job_spec.rb
require 'rails_helper' describe AgentReemitJob do subject { described_class.new } let(:agent) { agents(:bob_website_agent) } let(:agent_event) { events(:bob_website_agent_event) } it "re-emits all events created by the given Agent" do 2.times { agent_event.dup.save! } expect { subject.perform(agent, agent.most_recent_event.id) }.to change(Event, :count).by(3) last_event = Event.last expect(last_event.user).to eq(agent_event.user) expect(last_event.agent).to eq(agent_event.agent) expect(last_event.payload).to eq(agent_event.payload) end it "doesn't re-emit events created after the the most_recent_event_id" do 2.times { agent_event.dup.save! } # create one more most_recent_event = agent.most_recent_event.id agent_event.dup.save! expect { subject.perform(agent, most_recent_event, false) }.to change(Event, :count).by(3) last_event = Event.last expect(last_event.user).to eq(agent_event.user) expect(last_event.agent).to eq(agent_event.agent) expect(last_event.payload).to eq(agent_event.payload) end context "when delete_old_events set to true" do it "re-emits all events created by the given Agent and destroys originals" do original_events = [agent_event] 2.times do original_events << agent_event.dup.tap{ |e| e.save! } end expect { subject.perform(agent, agent.most_recent_event.id, true) }.to change(Event, :count).by(0) original_events.each { |e| expect(e.destroyed?) } last_event = Event.last expect(last_event.user).to eq(agent_event.user) expect(last_event.agent).to eq(agent_event.agent) expect(last_event.payload).to eq(agent_event.payload) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/jobs/agent_propagate_job_spec.rb
spec/jobs/agent_propagate_job_spec.rb
require 'rails_helper' describe AgentPropagateJob do it "calls Agent.receive! when run" do expect(Agent).to receive(:receive!) AgentPropagateJob.new.perform end context "#can_enqueue?" do it "is truthy when no propagation job is queued" do expect(AgentPropagateJob.can_enqueue?).to be_truthy end it "is falsy when a progation job is queued" do Delayed::Job.create!(queue: 'propagation') expect(AgentPropagateJob.can_enqueue?).to be_falsy end it "is truthy when a enqueued progation job failed" do Delayed::Job.create!(queue: 'propagation', failed_at: Time.now - 1.minute) expect(AgentPropagateJob.can_enqueue?).to be_truthy end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/support/alert_confirmer.rb
spec/support/alert_confirmer.rb
module AlertConfirmer def reject_confirm_from &block handle_js_modal 'confirm', false, &block end def accept_confirm_from &block handle_js_modal 'confirm', true, &block end def accept_alert_from &block handle_js_modal 'alert', true, &block end def get_alert_text_from &block handle_js_modal 'alert', true, true, &block get_modal_text 'alert' end def get_modal_text(name) page.evaluate_script "window.#{name}Msg;" end private def handle_js_modal name, return_val, wait_for_call = false, &block modal_called = "window.#{name}.called" page.execute_script " window.original_#{name}_function = window.#{name}; window.#{name} = function(msg) { window.#{name}Msg = msg; window.#{name}.called = true; return #{!!return_val}; }; #{modal_called} = false; window.#{name}Msg = null;" block.call if wait_for_call timed_out = false timeout_after = Time.now + Capybara.default_max_wait_time loop do if page.evaluate_script(modal_called).nil? raise 'appears that page has changed since this method has been called, please assert on page before calling this' end break if page.evaluate_script(modal_called) || (timed_out = Time.now > timeout_after) sleep 0.001 end raise "#{name} should have been called" if timed_out end ensure page.execute_script "window.#{name} = window.original_#{name}_function" end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/support/matchers.rb
spec/support/matchers.rb
RSpec::Matchers.define_negated_matcher :not_change, :change
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/support/spec_helpers.rb
spec/support/spec_helpers.rb
module SpecHelpers def build_events(options = {}) options[:values].map.with_index do |tuple, index| event = Event.new event.agent = agents(:bob_weather_agent) event.payload = (options[:pattern] || {}).dup.merge((options[:keys].zip(tuple)).inject({}) { |memo, (key, value)| memo[key] = value; memo }) event.created_at = (100 - index).hours.ago event.updated_at = (100 - index).hours.ago event end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/support/vcr_support.rb
spec/support/vcr_support.rb
require 'vcr' VCR.configure do |c| c.cassette_library_dir = 'spec/cassettes' c.allow_http_connections_when_no_cassette = false c.hook_into :webmock c.default_cassette_options = { record: :new_episodes} c.configure_rspec_metadata! end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/support/feature_helpers.rb
spec/support/feature_helpers.rb
module FeatureHelpers def select_agent_type(search) agent_name = search[/\A.*?Agent\b/] || search select2(agent_name, search:, from: "Type") # Wait for all parts of the Agent form to load: expect(page).to have_css("div.function_buttons") # Options editor expect(page).to have_css(".well.description > p") # Markdown description end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/support/fake_mqtt_server.rb
spec/support/fake_mqtt_server.rb
#!/usr/bin/env ruby # # This is a 'fake' MQTT server to help with testing client implementations # # See https://github.com/njh/ruby-mqtt/blob/master/spec/fake_server.rb # # It behaves in the following ways: # * Responses to CONNECT with a successful CONACK # * Responses to PUBLISH by echoing the packet back # * Responses to SUBSCRIBE with SUBACK and a PUBLISH to the topic # * Responses to PINGREQ with PINGRESP # * Responses to DISCONNECT by closing the socket # # It has the following restrictions # * Doesn't deal with timeouts # * Only handles a single connection at a time # $:.unshift File.dirname(__FILE__)+'/../lib' require 'logger' require 'socket' require 'mqtt' class MQTT::FakeServer attr_reader :address, :port attr_reader :last_publish attr_reader :thread attr_reader :pings_received attr_accessor :just_one attr_accessor :logger # Create a new fake MQTT server # # If no port is given, bind to a random port number # If no bind address is given, bind to localhost def initialize(bind_address='127.0.0.1') @address = bind_address end # Get the logger used by the server def logger @logger ||= Logger.new(STDOUT) end # Start the thread and open the socket that will process client connections def start @socket ||= TCPServer.new(@address, 0) @address = @socket.addr[3] @port = @socket.addr[1] @thread ||= Thread.new do logger.info "Started a fake MQTT server on #{@address}:#{@port}" @times = 0 loop do @times += 1 # Wait for a client to connect client = @socket.accept @pings_received = 0 handle_client(client) break if just_one end end end # Stop the thread and close the socket def stop logger.info "Stopping fake MQTT server" @thread.kill if @thread and @thread.alive? @thread = nil @socket.close unless @socket.nil? @socket = nil end # Start the server thread and wait for it to finish (possibly never) def run start begin @thread.join rescue Interrupt stop end end protected # Given a client socket, process MQTT packets from the client def handle_client(client) loop do packet = MQTT::Packet.read(client) logger.debug packet.inspect case packet when MQTT::Packet::Connect client.write MQTT::Packet::Connack.new(:return_code => 0) when MQTT::Packet::Publish client.write packet @last_publish = packet when MQTT::Packet::Subscribe client.write MQTT::Packet::Suback.new( :message_id => packet.message_id, :granted_qos => 0 ) topic = packet.topics[0][0] case @times when 1, ->x { x >= 3 } # Deliver retained messages client.write MQTT::Packet::Publish.new( :topic => topic, :payload => "did you know about #{topic}", :retain => true ) client.write MQTT::Packet::Publish.new( :topic => topic, :payload => "hello #{topic}", :retain => true ) when 2 # Deliver a still retained message client.write MQTT::Packet::Publish.new( :topic => topic, :payload => "hello #{topic}", :retain => true ) # Deliver a fresh message client.write MQTT::Packet::Publish.new( :topic => topic, :payload => "did you know about #{topic}", :retain => false ) end when MQTT::Packet::Pingreq client.write MQTT::Packet::Pingresp.new @pings_received += 1 when MQTT::Packet::Disconnect client.close break end end rescue MQTT::ProtocolException => e logger.warn "Protocol error, closing connection: #{e}" client.close end end if __FILE__ == $0 server = MQTT::FakeServer.new(MQTT::DEFAULT_PORT) server.logger.level = Logger::DEBUG server.run end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/support/shared_examples/liquid_interpolatable.rb
spec/support/shared_examples/liquid_interpolatable.rb
require 'rails_helper' shared_examples_for LiquidInterpolatable do before(:each) do @valid_params = { "normal" => "just some normal text", "variable" => "{{variable}}", "text" => "Some test with an embedded {{variable}}", "escape" => "This should be {{hello_world | uri_escape}}" } @checker = new_instance @checker.name = "somename" @checker.options = @valid_params @checker.user = users(:jane) @event = Event.new @event.agent = agents(:bob_weather_agent) @event.payload = { :variable => 'hello', :hello_world => "Hello world"} @event.save! end describe "interpolating liquid templates" do it "should work" do expect(@checker.interpolate_options(@checker.options, @event)).to eq({ "normal" => "just some normal text", "variable" => "hello", "text" => "Some test with an embedded hello", "escape" => "This should be Hello+world" }) end it "should work with arrays" do @checker.options = {"value" => ["{{variable}}", "Much array", "Hey, {{hello_world}}"]} expect(@checker.interpolate_options(@checker.options, @event)).to eq({ "value" => ["hello", "Much array", "Hey, Hello world"] }) end it "should work recursively" do @checker.options['hash'] = {'recursive' => "{{variable}}"} @checker.options['indifferent_hash'] = ActiveSupport::HashWithIndifferentAccess.new({'recursive' => "{{variable}}"}) expect(@checker.interpolate_options(@checker.options, @event)).to eq({ "normal" => "just some normal text", "variable" => "hello", "text" => "Some test with an embedded hello", "escape" => "This should be Hello+world", "hash" => {'recursive' => 'hello'}, "indifferent_hash" => {'recursive' => 'hello'}, }) end it "should work for strings" do expect(@checker.interpolate_string("{{variable}}", @event)).to eq("hello") expect(@checker.interpolate_string("{{variable}} you", @event)).to eq("hello you") end it "should use local variables while in a block" do @checker.options['locals'] = '{{_foo_}} {{_bar_}}' @checker.interpolation_context.tap { |context| expect(@checker.interpolated['locals']).to eq(' ') context.stack { context['_foo_'] = 'This is' context['_bar_'] = 'great.' expect(@checker.interpolated['locals']).to eq('This is great.') } expect(@checker.interpolated['locals']).to eq(' ') } end it "should use another self object while in a block" do @checker.options['properties'] = '{{_foo_}} {{_bar_}}' expect(@checker.interpolated['properties']).to eq(' ') @checker.interpolate_with({ '_foo_' => 'That was', '_bar_' => 'nice.' }) { expect(@checker.interpolated['properties']).to eq('That was nice.') } expect(@checker.interpolated['properties']).to eq(' ') end end describe "liquid tags" do context "%credential" do it "should work with existing credentials" do expect(@checker.interpolate_string("{% credential aws_key %}", {})).to eq('2222222222-jane') end it "should not raise an exception for undefined credentials" do expect { result = @checker.interpolate_string("{% credential unknown %}", {}) expect(result).to eq('') }.not_to raise_error end end context '%line_break' do it 'should convert {% line_break %} to actual line breaks' do expect(@checker.interpolate_string("test{% line_break %}second line", {})).to eq("test\nsecond line") end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/support/shared_examples/has_guid.rb
spec/support/shared_examples/has_guid.rb
require 'rails_helper' shared_examples_for HasGuid do it "gets created before_save, but only if it's not present" do instance = new_instance expect(instance.guid).to be_nil instance.save! expect(instance.guid).not_to be_nil expect { instance.save! }.not_to change { instance.reload.guid } end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/support/shared_examples/agent_controller_concern.rb
spec/support/shared_examples/agent_controller_concern.rb
require 'rails_helper' shared_examples_for AgentControllerConcern do describe "preconditions" do it "must be satisfied for these shared examples" do expect(agent.user).to eq(users(:bob)) expect(agent.control_action).to eq('run') end end describe "validation" do describe "of action" do it "should allow certain values" do ['run', 'enable', 'disable', '{{ action }}'].each { |action| agent.options['action'] = action expect(agent).to be_valid } end it "should disallow obviously bad values" do ['delete', nil, 1, true].each { |action| agent.options['action'] = action expect(agent).not_to be_valid } end it "should accept 'run' if all target agents are schedulable" do agent.control_targets = [agents(:bob_website_agent)] expect(agent).to be_valid end it "should reject 'run' if targets include an unschedulable agent" do agent.control_targets = [agents(:bob_rain_notifier_agent)] expect(agent).not_to be_valid end it "should not reject 'enable' or 'disable' no matter if targets include an unschedulable agent" do ['enable', 'disable'].each { |action| agent.options['action'] = action agent.control_targets = [agents(:bob_rain_notifier_agent)] expect(agent).to be_valid } end it "should ensure that 'configure_options' exists in options when the action is 'configure'" do agent.options['action'] = 'configure' expect(agent).not_to be_valid agent.options['configure_options'] = {} expect(agent).not_to be_valid agent.options['configure_options'] = { 'key' => 'value' } expect(agent).to be_valid end end end describe 'control_action' do it "returns options['action']" do expect(agent.control_action).to eq('run') ['run', 'enable', 'disable'].each { |action| agent.options['action'] = action expect(agent.control_action).to eq(action) } end it "returns the result of interpolation" do expect(agent.control_action).to eq('run') agent.options['action'] = '{{ "enable" }}' expect(agent.control_action).to eq('enable') end end describe "control!" do before do agent.control_targets = [agents(:bob_website_agent), agents(:bob_weather_agent)] agent.save! end it "should run targets" do control_target_ids = agent.control_targets.map(&:id) allow(Agent).to receive(:async_check).with(anything) { |id| control_target_ids.delete(id) } agent.control! expect(control_target_ids).to be_empty end it "should not run disabled targets" do control_target_ids = agent.control_targets.map(&:id) allow(Agent).to receive(:async_check).with(anything) { |id| control_target_ids.delete(id) } agent.control_targets.last.update!(disabled: true) agent.control! expect(control_target_ids).to eq [agent.control_targets.last.id] end it "should disable targets" do agent.options['action'] = 'disable' agent.save! agent.control_targets.first.update!(disabled: false) agent.control! expect(agent.control_targets.reload).to all(be_disabled) end it "should enable targets" do agent.options['action'] = 'enable' agent.save! agent.control_targets.first.update!(disabled: true) agent.control! expect(agent.control_targets.reload).to all(satisfy { |a| !a.disabled? }) end it "should enable targets and drop pending events" do agent.options['action'] = 'enable' agent.options['drop_pending_events'] = 'true' agent.save! agent.control_targets.first.update!(disabled: true) agent.control! # Find the maximum Event ID, which is what our control_targets should be set to when drop_pending_events is called. maximum_event_id = Event.maximum(:id) # Only test Agents which can_receive_events? because those are the only ones who will have had pending events dropped. agents_that_can_recieve_events = agent.control_targets.to_a.keep_if(&:can_receive_events?) expect(agents_that_can_recieve_events.collect(&:last_checked_event_id)).to all(eq(maximum_event_id)) # Ensure that the control_targets are not disabled. expect(agent.control_targets.reload).to all(satisfy { |a| !a.disabled? }) end it "should configure targets" do agent.options['action'] = 'configure' agent.options['configure_options'] = { 'url' => 'http://some-new-url.com/{{"something" | upcase}}' } agent.save! old_options = agents(:bob_website_agent).options agent.control! expect(agent.control_targets.reload).to all(satisfy { |a| a.options['url'] == 'http://some-new-url.com/SOMETHING' }) expect(agents(:bob_website_agent).reload.options).to eq(old_options.merge('url' => 'http://some-new-url.com/SOMETHING')) end it "should configure targets with nested objects" do agent.control_targets = [ agents(:bob_twitter_user_agent), # does not support a `template` option, but anyway agents(:bob_data_output_agent) ] agent.options['action'] = 'configure' agent.options['configure_options'] = { template: { item: { title: "changed" } } } agent.save! old_options = agents(:bob_data_output_agent).options agent.control! expect(agent.control_targets.reload).to all(satisfy { |a| a.options['template'] && a.options['template']['item'] && (a.options['template']['item']['title'] == 'changed') }) expect(agents(:bob_data_output_agent).reload.options).to eq(old_options.deep_merge(agent.options['configure_options'])) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/support/shared_examples/web_request_concern.rb
spec/support/shared_examples/web_request_concern.rb
require 'rails_helper' shared_examples_for WebRequestConcern do let(:agent) do _agent = described_class.new(:name => "some agent", :options => @valid_options || {}) _agent.user = users(:jane) _agent end describe "validations" do it "should be valid" do expect(agent).to be_valid end it "should validate user_agent" do agent.options['user_agent'] = nil expect(agent).to be_valid agent.options['user_agent'] = "" expect(agent).to be_valid agent.options['user_agent'] = "foo" expect(agent).to be_valid agent.options['user_agent'] = ["foo"] expect(agent).not_to be_valid agent.options['user_agent'] = 1 expect(agent).not_to be_valid end it "should validate headers" do agent.options['headers'] = "blah" expect(agent).not_to be_valid agent.options['headers'] = "" expect(agent).to be_valid agent.options['headers'] = {} expect(agent).to be_valid agent.options['headers'] = { 'foo' => 'bar' } expect(agent).to be_valid end it "should validate basic_auth" do agent.options['basic_auth'] = "foo:bar" expect(agent).to be_valid agent.options['basic_auth'] = ["foo", "bar"] expect(agent).to be_valid agent.options['basic_auth'] = "" expect(agent).to be_valid agent.options['basic_auth'] = nil expect(agent).to be_valid agent.options['basic_auth'] = "blah" expect(agent).not_to be_valid agent.options['basic_auth'] = ["blah"] expect(agent).not_to be_valid end it "should validate disable_ssl_verification" do agent.options['disable_ssl_verification'] = nil expect(agent).to be_valid agent.options['disable_ssl_verification'] = true expect(agent).to be_valid agent.options['disable_ssl_verification'] = false expect(agent).to be_valid agent.options['disable_ssl_verification'] = 'true' expect(agent).to be_valid agent.options['disable_ssl_verification'] = 'false' expect(agent).to be_valid agent.options['disable_ssl_verification'] = 'blah' expect(agent).not_to be_valid agent.options['disable_ssl_verification'] = 51 expect(agent).not_to be_valid end end describe "User-Agent" do before do @default_http_user_agent = ENV['DEFAULT_HTTP_USER_AGENT'] ENV['DEFAULT_HTTP_USER_AGENT'] = nil end after do ENV['DEFAULT_HTTP_USER_AGENT'] = @default_http_user_agent end it "should have the default value of Huginn" do expect(agent.user_agent).to eq('Huginn - https://github.com/huginn/huginn') end it "should be overridden by the environment variable if present" do ENV['DEFAULT_HTTP_USER_AGENT'] = 'Something' expect(agent.user_agent).to eq('Something') end it "should be overriden by the value in options if present" do agent.options['user_agent'] = 'Override' expect(agent.user_agent).to eq('Override') end end describe "#faraday" do it "should enable SSL verification by default" do expect(agent.faraday.ssl.verify).to eq(true) end it "should enable SSL verification when nil" do agent.options['disable_ssl_verification'] = nil expect(agent.faraday.ssl.verify).to eq(true) end it "should disable SSL verification if disable_ssl_verification option is 'true'" do agent.options['disable_ssl_verification'] = 'true' expect(agent.faraday.ssl.verify).to eq(false) end it "should disable SSL verification if disable_ssl_verification option is true" do agent.options['disable_ssl_verification'] = true expect(agent.faraday.ssl.verify).to eq(false) end it "should not disable SSL verification if disable_ssl_verification option is 'false'" do agent.options['disable_ssl_verification'] = 'false' expect(agent.faraday.ssl.verify).to eq(true) end it "should not disable SSL verification if disable_ssl_verification option is false" do agent.options['disable_ssl_verification'] = false expect(agent.faraday.ssl.verify).to eq(true) end it "should use faradays default params_encoder" do expect(agent.faraday.options.params_encoder).to eq(nil) agent.options['disable_url_encoding'] = 'false' expect(agent.faraday.options.params_encoder).to eq(nil) agent.options['disable_url_encoding'] = false expect(agent.faraday.options.params_encoder).to eq(nil) end it "should use WebRequestConcern::DoNotEncoder when disable_url_encoding is truthy" do agent.options['disable_url_encoding'] = true expect(agent.faraday.options.params_encoder).to eq(WebRequestConcern::DoNotEncoder) agent.options['disable_url_encoding'] = 'true' expect(agent.faraday.options.params_encoder).to eq(WebRequestConcern::DoNotEncoder) end describe "redirect follow" do it "should use FollowRedirects by default" do expect(agent.faraday.builder.handlers).to include(Faraday::FollowRedirects::Middleware) end it "should not use FollowRedirects when disabled" do agent.options['disable_redirect_follow'] = true expect(agent.faraday.builder.handlers).not_to include(Faraday::FollowRedirects::Middleware) end end end describe WebRequestConcern::DoNotEncoder do it "should not encode special characters" do expect(WebRequestConcern::DoNotEncoder.encode('GetRss?CategoryNr=39207' => 'test')).to eq('GetRss?CategoryNr=39207=test') end it "should work without a value present" do expect(WebRequestConcern::DoNotEncoder.encode('GetRss?CategoryNr=39207' => nil)).to eq('GetRss?CategoryNr=39207') end it "should work without an empty value" do expect(WebRequestConcern::DoNotEncoder.encode('GetRss?CategoryNr=39207' => '')).to eq('GetRss?CategoryNr=39207=') end it "should return the value when decoding" do expect(WebRequestConcern::DoNotEncoder.decode('val')).to eq(['val']) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/support/shared_examples/working_helpers.rb
spec/support/shared_examples/working_helpers.rb
require 'rails_helper' shared_examples_for WorkingHelpers do describe "recent_error_logs?" do it "returns true if last_error_log_at is near last_event_at" do agent = described_class.new agent.last_error_log_at = 10.minutes.ago agent.last_event_at = 10.minutes.ago expect(agent.recent_error_logs?).to be_truthy agent.last_error_log_at = 11.minutes.ago agent.last_event_at = 10.minutes.ago expect(agent.recent_error_logs?).to be_truthy agent.last_error_log_at = 5.minutes.ago agent.last_event_at = 10.minutes.ago expect(agent.recent_error_logs?).to be_truthy agent.last_error_log_at = 15.minutes.ago agent.last_event_at = 10.minutes.ago expect(agent.recent_error_logs?).to be_falsey agent.last_error_log_at = 2.days.ago agent.last_event_at = 10.minutes.ago expect(agent.recent_error_logs?).to be_falsey end end describe "received_event_without_error?" do before do @agent = described_class.new end it "should return false until the first event was received" do expect(@agent.received_event_without_error?).to eq(false) @agent.last_receive_at = Time.now expect(@agent.received_event_without_error?).to eq(true) end it "should return false when the last error occured after the last received event" do @agent.last_receive_at = Time.now - 1.minute @agent.last_error_log_at = Time.now expect(@agent.received_event_without_error?).to eq(false) end it "should return true when the last received event occured after the last error" do @agent.last_receive_at = Time.now @agent.last_error_log_at = Time.now - 1.minute expect(@agent.received_event_without_error?).to eq(true) end end describe "checked_without_error?" do before do @agent = described_class.new end it "should return false until the first time check ran" do expect(@agent.checked_without_error?).to eq(false) @agent.last_check_at = Time.now expect(@agent.checked_without_error?).to eq(true) end it "should return false when the last error occured after the check" do @agent.last_check_at = Time.now - 1.minute @agent.last_error_log_at = Time.now expect(@agent.checked_without_error?).to eq(false) end it "should return true when the last check occured after the last error" do @agent.last_check_at = Time.now @agent.last_error_log_at = Time.now - 1.minute expect(@agent.checked_without_error?).to eq(true) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/support/shared_examples/file_handling_consumer.rb
spec/support/shared_examples/file_handling_consumer.rb
require 'rails_helper' shared_examples_for 'FileHandlingConsumer' do let(:event) { Event.new(user: @checker.user, payload: {'file_pointer' => {'file' => 'text.txt', 'agent_id' => @checker.id}}) } it 'returns a file pointer' do expect(@checker.get_file_pointer('testfile')).to eq(file_pointer: { file: "testfile", agent_id: @checker.id}) end it 'get_io raises an exception when trying to access an agent of a different user' do @checker2 = @checker.dup @checker2.user = users(:bob) @checker2.save! event.payload['file_pointer']['agent_id'] = @checker2.id expect { @checker.get_io(event) }.to raise_error(ActiveRecord::RecordNotFound) end context '#has_file_pointer?' do it 'returns true if the event contains a file pointer' do expect(@checker.has_file_pointer?(event)).to be_truthy end it 'returns false if the event does not contain a file pointer' do expect(@checker.has_file_pointer?(Event.new)).to be_falsy end end it '#get_upload_io returns a Faraday::UploadIO instance' do io_mock = double() expect(@checker).to receive(:get_io).with(event) { StringIO.new("testdata") } upload_io = @checker.get_upload_io(event) expect(upload_io).to be_a(Faraday::UploadIO) expect(upload_io.content_type).to eq('text/plain') end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/support/shared_examples/email_concern.rb
spec/support/shared_examples/email_concern.rb
require 'rails_helper' shared_examples_for EmailConcern do let(:valid_options) { { :subject => "hello!", :expected_receive_period_in_days => "2" } } let(:agent) do _agent = described_class.new(:name => "some email agent", :options => valid_options) _agent.user = users(:jane) _agent end describe "validations" do it "should be valid" do expect(agent).to be_valid end it "should validate the presence of 'subject'" do agent.options['subject'] = '' expect(agent).not_to be_valid agent.options['subject'] = nil expect(agent).not_to be_valid end it "should validate the 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'] = nil expect(agent).not_to be_valid end it "should validate that recipients, when provided, is one or more valid email addresses or Liquid commands" do agent.options['recipients'] = '' expect(agent).to be_valid agent.options['recipients'] = nil expect(agent).to be_valid agent.options['recipients'] = 'bob@example.com' expect(agent).to be_valid agent.options['recipients'] = ['bob@example.com'] expect(agent).to be_valid agent.options['recipients'] = '{{ email }}' expect(agent).to be_valid agent.options['recipients'] = '{% if x %}a@x{% else %}b@y{% endif %}' expect(agent).to be_valid agent.options['recipients'] = ['bob@example.com', 'jane@example.com'] expect(agent).to be_valid agent.options['recipients'] = ['bob@example.com', 'example.com'] expect(agent).not_to be_valid agent.options['recipients'] = ['hi!'] expect(agent).not_to be_valid agent.options['recipients'] = { :foo => "bar" } expect(agent).not_to be_valid agent.options['recipients'] = "wut" expect(agent).not_to be_valid end end describe "#recipients" do it "defaults to the user's email address" do expect(agent.recipients).to eq([users(:jane).email]) end it "wraps a string with an array" do agent.options['recipients'] = 'bob@bob.com' expect(agent.recipients).to eq(['bob@bob.com']) end it "handles an array" do agent.options['recipients'] = ['bob@bob.com', 'jane@jane.com'] expect(agent.recipients).to eq(['bob@bob.com', 'jane@jane.com']) end it "interpolates" do agent.options['recipients'] = "{{ username }}@{{ domain }}" expect(agent.recipients('username' => 'bob', 'domain' => 'example.com')).to eq(["bob@example.com"]) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/concerns/dry_runnable_spec.rb
spec/concerns/dry_runnable_spec.rb
require 'rails_helper' describe DryRunnable do class Agents::SandboxedAgent < Agent default_schedule "3pm" can_dry_run! def check perform end def receive(events) events.each do |event| perform(event.payload['prefix']) end end private def perform(prefix = nil) log "Logging" create_event payload: { 'test' => "#{prefix}foo" } error "Recording error" create_event payload: { 'test' => "#{prefix}bar" } self.memory = { 'last_status' => 'ok', 'dry_run' => dry_run? } save! end end before do allow(Agents::SandboxedAgent).to receive(:valid_type?).with("Agents::SandboxedAgent") { true } @agent = Agents::SandboxedAgent.create(name: "some agent") { |agent| agent.user = users(:bob) } end def counts [users(:bob).agents.count, users(:bob).events.count, users(:bob).logs.count] end it "does not affect normal run, with dry_run? returning false" do before = counts after = before.zip([0, 2, 2]).map { |x, d| x + d } expect { @agent.check @agent.reload }.to change { counts }.from(before).to(after) expect(@agent.memory).to eq({ 'last_status' => 'ok', 'dry_run' => false }) payloads = @agent.events.reorder(:id).last(2).map(&:payload) expect(payloads).to eq([{ 'test' => 'foo' }, { 'test' => 'bar' }]) messages = @agent.logs.reorder(:id).last(2).map(&:message) expect(messages).to eq(['Logging', 'Recording error']) end it "does not perform dry-run if Agent does not support dry-run" do allow(@agent).to receive(:can_dry_run?) { false } results = nil expect { results = @agent.dry_run! @agent.reload }.not_to change { [@agent.memory, counts] } expect(results[:log]).to match(/\A\[\d\d:\d\d:\d\d\] INFO -- : Dry Run failed\n\[\d\d:\d\d:\d\d\] ERROR -- : Exception during dry-run. SandboxedAgent does not support dry-run: /) expect(results[:events]).to eq([]) expect(results[:memory]).to eq({}) end describe "dry_run!" do it "traps any destructive operations during a run" do results = nil expect { results = @agent.dry_run! @agent.reload }.not_to change { [@agent.memory, counts] } expect(results[:log]).to match(/\A\[\d\d:\d\d:\d\d\] INFO -- : Dry Run started\n\[\d\d:\d\d:\d\d\] INFO -- : Logging\n\[\d\d:\d\d:\d\d\] ERROR -- : Recording error\n/) expect(results[:events]).to eq([{ 'test' => 'foo' }, { 'test' => 'bar' }]) expect(results[:memory]).to eq({ 'last_status' => 'ok', 'dry_run' => true }) end it "traps any destructive operations during a run when an event is given" do results = nil expect { results = @agent.dry_run!(Event.new(payload: { 'prefix' => 'super' })) @agent.reload }.not_to change { [@agent.memory, counts] } expect(results[:log]).to match(/\A\[\d\d:\d\d:\d\d\] INFO -- : Dry Run started\n\[\d\d:\d\d:\d\d\] INFO -- : Logging\n\[\d\d:\d\d:\d\d\] ERROR -- : Recording error\n/) expect(results[:events]).to eq([{ 'test' => 'superfoo' }, { 'test' => 'superbar' }]) expect(results[:memory]).to eq({ 'last_status' => 'ok', 'dry_run' => true }) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/concerns/long_runnable_spec.rb
spec/concerns/long_runnable_spec.rb
require 'rails_helper' class TestWorker < LongRunnable::Worker def stop; end def terminate; end def runl; end end describe LongRunnable do class LongRunnableAgent < Agent include LongRunnable def default_options { test: 'test' } end end before(:each) do @agent = LongRunnableAgent.new end it 'start_worker? defaults to true' do expect(@agent.start_worker?).to be_truthy end it 'should build the worker_id' do expect(@agent.worker_id).to eq('LongRunnableAgent--bf21a9e8fbc5a3846fb05b4fa0859e0917b2202f') end context '#setup_worker' do it 'returns active agent workers' do expect(LongRunnableAgent).to receive(:active) { [@agent] } workers = LongRunnableAgent.setup_worker expect(workers.length).to eq(1) expect(workers.first).to be_a(LongRunnableAgent::Worker) expect(workers.first.agent).to eq(@agent) end it 'returns an empty array when no agent is active' do expect(LongRunnableAgent).to receive(:active) { [] } workers = LongRunnableAgent.setup_worker expect(workers.length).to eq(0) end end describe LongRunnable::Worker do before(:each) do @agent = double('agent') @stoppable_worker = TestWorker.new(agent: @agent, id: 'test1234') @worker = LongRunnable::Worker.new(agent: @agent, id: 'test1234') @scheduler = Rufus::Scheduler.new @worker.setup!(@scheduler, Mutex.new) @stoppable_worker.setup!(@scheduler, Mutex.new) end after(:each) do @worker.thread.terminate if @worker.thread && !@skip_thread_terminate @scheduler.shutdown(:wait) end it 'calls boolify of the agent' do expect(@agent).to receive(:boolify).with('true') { true } expect(@worker.boolify('true')).to be_truthy end it 'expects run to be overriden' do expect { @worker.run }.to raise_error(StandardError) end context '#run!' do it 'runs the agent worker' do expect(@worker).to receive(:run) @worker.run!.join end it 'stops when rescueing a SystemExit' do expect(@worker).to receive(:run) { raise SystemExit } expect(@worker).to receive(:stop!) @worker.run!.join end it 'creates an agent log entry for a generic exception' do allow(STDERR).to receive(:puts) expect(@worker).to receive(:run) { raise 'woups' } expect(@agent).to receive(:error).with(/woups/) @worker.run!.join end end context '#stop!' do it 'terminates the thread' do expect(@worker).to receive(:terminate_thread!) @worker.stop! end it 'gracefully stops the worker' do expect(@stoppable_worker).to receive(:stop) @stoppable_worker.stop! end end context '#terminate_thread!' do before do @skip_thread_terminate = true mock_thread = double('mock_thread') allow(@worker).to receive(:thread) { mock_thread } end it 'terminates the thread' do expect(@worker.thread).to receive(:terminate) expect(@worker.thread).not_to receive(:wakeup) expect(@worker.thread).to receive(:status) { 'run' } @worker.terminate_thread! end it 'wakes up sleeping threads after termination' do expect(@worker.thread).to receive(:terminate) expect(@worker.thread).to receive(:wakeup) expect(@worker.thread).to receive(:status) { 'sleep' } @worker.terminate_thread! end end context '#restart!' do it 'stops, setups and starts the worker' do expect(@worker).to receive(:stop!) expect(@worker).to receive(:setup!).with(@worker.scheduler, @worker.mutex) expect(@worker).to receive(:run!) expect(@worker).to receive(:puts).with(anything) { |text| expect(text).to match(/Restarting/) } @worker.restart! end end context 'scheduling' do it 'schedules tasks once' do expect(@worker.scheduler).to receive(:send).with(:schedule_in, 1.hour, tag: 'test1234') @worker.schedule_in 1.hour do noop; end end it 'schedules repeating tasks' do expect(@worker.scheduler).to receive(:send).with(:every, 1.hour, tag: 'test1234') @worker.every 1.hour do noop; end end it 'allows the cron syntax' do expect(@worker.scheduler).to receive(:send).with(:cron, '0 * * * *', tag: 'test1234') @worker.cron '0 * * * *' do noop; 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/concerns/twitter_concern_spec.rb
spec/concerns/twitter_concern_spec.rb
require 'rails_helper' describe TwitterConcern do class TestTwitterAgent < Agent include TwitterConcern end before do allow(TestTwitterAgent).to receive(:valid_type?).with("TestTwitterAgent") { true } @agent = TestTwitterAgent.create(name: "some agent") { |agent| agent.user = users(:bob) } end describe 'format_tweet' do let(:tweet_hash) { { created_at: "Wed Mar 01 01:52:07 +0000 2023", id: 9_000_000_000_000_000_000, id_str: "9000000000000000000", full_text: "Test &gt; Test &amp; https://t.co/XXXXXXXXXX &amp; Test &lt; https://t.co/YYYYYYYYYY", truncated: false, display_text_range: [ 0, 84 ], entities: { hashtags: [], symbols: [], user_mentions: [], urls: [ { url: "https://t.co/XXXXXXXXXX", expanded_url: "https://example.org/foo/bar/baz.html", display_url: "example.org/foo/bar/baz…", indices: [ 21, 44 ] }, { url: "https://t.co/YYYYYYYYYY", expanded_url: "https://example.com/quux/", display_url: "example.org/quux/", indices: [ 61, 84 ] } ] }, } } let(:expected) { { created_at: "Wed Mar 01 01:52:07 +0000 2023", id: 9_000_000_000_000_000_000, id_str: "9000000000000000000", full_text: "Test > Test & https://t.co/XXXXXXXXXX & Test < https://t.co/YYYYYYYYYY", expanded_text: "Test > Test & https://example.org/foo/bar/baz.html & Test < https://example.com/quux/", truncated: false, display_text_range: [ 0, 84 ], entities: { hashtags: [], symbols: [], user_mentions: [], urls: [ { url: "https://t.co/XXXXXXXXXX", expanded_url: "https://example.org/foo/bar/baz.html", display_url: "example.org/foo/bar/baz…", indices: [ 21, 44 ] }, { url: "https://t.co/YYYYYYYYYY", expanded_url: "https://example.com/quux/", display_url: "example.org/quux/", indices: [ 61, 84 ] } ] }, } } let(:input) { tweet_hash } subject { @agent.send(:format_tweet, input) } it "formats a tweet" do expect(subject).to eq(expected) end context "when a string key hash is given" do let(:input) { tweet_hash.deep_stringify_keys } it "formats a tweet" do expect(subject).to eq(expected) end end context "when a Twitter::Tweet object is given" do let(:input) { Twitter::Tweet.new(tweet_hash) } let(:expected) { super().then { |attrs| attrs.update(text: attrs[:full_text]) } } it "formats a tweet" do expect(subject).to eq(expected) end end context "when nil is given" do let(:input) { nil } it "raises an exception" do expect { subject }.to raise_exception(TypeError) end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/concerns/form_configurable_spec.rb
spec/concerns/form_configurable_spec.rb
require 'rails_helper' describe FormConfigurable do class Agent1 include FormConfigurable def validate_test true end def complete_test [{name: 'test', value: 1234}] end end class Agent2 < Agent end before(:all) do @agent1 = Agent1.new @agent2 = Agent2.new end it "#is_form_configurable" do expect(@agent1.is_form_configurable?).to be true expect(@agent2.is_form_configurable?).to be false end describe "#validete_option" do it "should call the validation method if it is defined" do expect(@agent1.validate_option('test')).to be true end it "should return false of the method is undefined" do expect(@agent1.validate_option('undefined')).to be false end end it "#complete_option" do expect(@agent1.complete_option('test')).to eq [{name: 'test', value: 1234}] end describe "#form_configurable" do it "should raise an ArgumentError for invalid options" do expect { Agent1.form_configurable(:test, invalid: true) }.to raise_error(ArgumentError) end it "should raise an ArgumentError when not providing an array with type: array" do expect { Agent1.form_configurable(:test, type: :array, values: 1) }.to raise_error(ArgumentError) end it "should not require any options for the default values" do expect { Agent1.form_configurable(:test) }.to change(Agent1, :form_configurable_attributes).by(['test']) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/concerns/liquid_interpolatable_spec.rb
spec/concerns/liquid_interpolatable_spec.rb
require 'rails_helper' require 'nokogiri' describe LiquidInterpolatable::Filters do before do @filter = Class.new do include LiquidInterpolatable::Filters end.new end describe 'uri_escape' do it 'should escape a string for use in URI' do expect(@filter.uri_escape('abc:/?=')).to eq('abc%3A%2F%3F%3D') end it 'should not raise an error when an operand is nil' do expect(@filter.uri_escape(nil)).to be_nil end end describe 'validations' do class Agents::InterpolatableAgent < Agent include LiquidInterpolatable def check create_event payload: {} end def validate_options interpolated['foo'] end end it "should finish without raising an exception" do agent = Agents::InterpolatableAgent.new(name: "test", options: { 'foo' => '{{bar}' }) expect(agent.valid?).to eq(false) expect(agent.errors[:options].first).to match(/not properly terminated/) end end describe 'unescape' do let(:agent) { Agents::InterpolatableAgent.new(name: "test") } it 'should unescape basic HTML entities' do agent.interpolation_context['something'] = '&#39;&lt;foo&gt; &amp; bar&#x27;' agent.options['cleaned'] = '{{ something | unescape }}' expect(agent.interpolated['cleaned']).to eq("'<foo> & bar'") end end describe "json" do let(:agent) { Agents::InterpolatableAgent.new(name: "test") } it 'serializes data to json' do agent.interpolation_context['something'] = { foo: 'bar' } agent.options['cleaned'] = '{{ something | json }}' expect(agent.interpolated['cleaned']).to eq('{"foo":"bar"}') end end describe 'to_xpath' do before do def @filter.to_xpath_roundtrip(string) Nokogiri::XML('').xpath(to_xpath(string)) end end it 'should escape a string for use in XPath expression' do [ 'abc'.freeze, %q('a"bc'dfa""fds''fa).freeze, ].each { |string| expect(@filter.to_xpath_roundtrip(string)).to eq(string) } end it 'should stringify a non-string operand' do expect(@filter.to_xpath_roundtrip(nil)).to eq('') expect(@filter.to_xpath_roundtrip(1)).to eq('1') end end describe 'to_uri' do before do @agent = Agents::InterpolatableAgent.new(name: "test", options: { 'foo' => '{% assign u = s | to_uri %}{{ u.path }}' }) @agent.interpolation_context['s'] = 'http://example.com/dir/1?q=test' end it 'should parse an absolute URI' do expect(@filter.to_uri('http://example.net/index.html', 'http://example.com/dir/1')).to eq(URI('http://example.net/index.html')) end it 'should parse an absolute URI with a base URI specified' do expect(@filter.to_uri('http://example.net/index.html', 'http://example.com/dir/1')).to eq(URI('http://example.net/index.html')) end it 'should parse a relative URI with a base URI specified' do expect(@filter.to_uri('foo/index.html', 'http://example.com/dir/1')).to eq(URI('http://example.com/dir/foo/index.html')) end it 'should parse an absolute URI with a base URI specified' do expect(@filter.to_uri('http://example.net/index.html', 'http://example.com/dir/1')).to eq(URI('http://example.net/index.html')) end it 'should stringify a non-string operand' do expect(@filter.to_uri(123, 'http://example.com/dir/1')).to eq(URI('http://example.com/dir/123')) end it 'should normalize a URL' do expect(@filter.to_uri('a[]', 'http://example.com/dir/1')).to eq(URI('http://example.com/dir/a%5B%5D')) end it 'should return a URI value in interpolation' do expect(@agent.interpolated['foo']).to eq('/dir/1') end it 'should return a URI value resolved against a base URI in interpolation' do @agent.options['foo'] = '{% assign u = s | to_uri:"http://example.com/dir/1" %}{{ u.path }}' @agent.interpolation_context['s'] = 'foo/index.html' expect(@agent.interpolated['foo']).to eq('/dir/foo/index.html') end it 'should normalize a URI value if an empty base URI is given' do @agent.options['foo'] = '{{ u | to_uri: b }}' @agent.interpolation_context['u'] = "\u{3042}" @agent.interpolation_context['b'] = "" expect(@agent.interpolated['foo']).to eq('%E3%81%82') @agent.interpolation_context['b'] = nil expect(@agent.interpolated['foo']).to eq('%E3%81%82') end end describe 'uri_expand' do before do stub_request(:head, 'https://t.co.x/aaaa') .to_return(status: 301, headers: { Location: 'https://bit.ly.x/bbbb' }) stub_request(:head, 'https://bit.ly.x/bbbb') .to_return(status: 301, headers: { Location: 'http://tinyurl.com.x/cccc' }) stub_request(:head, 'http://tinyurl.com.x/cccc') .to_return(status: 301, headers: { Location: 'http://www.example.com/welcome' }) stub_request(:head, 'http://www.example.com/welcome') .to_return(status: 200) (1..5).each do |i| stub_request(:head, "http://2many.x/#{i}") .to_return(status: 301, headers: { Location: "http://2many.x/#{i + 1}" }) end stub_request(:head, 'http://2many.x/6') .to_return(status: 301, headers: { 'Content-Length' => '5' }) end it 'should handle inaccessible URIs' do expect(@filter.uri_expand(nil)).to eq('') expect(@filter.uri_expand('')).to eq('') expect(@filter.uri_expand(5)).to eq('5') expect(@filter.uri_expand([])).to eq('%5B%5D') expect(@filter.uri_expand({})).to eq('%7B%7D') expect(@filter.uri_expand(URI('/'))).to eq('/') expect(@filter.uri_expand(URI('http:google.com'))).to eq('http:google.com') expect(@filter.uri_expand(URI('http:/google.com'))).to eq('http:/google.com') expect(@filter.uri_expand(URI('ftp://ftp.freebsd.org/pub/FreeBSD/README.TXT'))).to eq('ftp://ftp.freebsd.org/pub/FreeBSD/README.TXT') end it 'should follow redirects' do expect(@filter.uri_expand('https://t.co.x/aaaa')).to eq('http://www.example.com/welcome') end it 'should respect the limit for the number of redirects' do expect(@filter.uri_expand('http://2many.x/1')).to eq('http://2many.x/1') expect(@filter.uri_expand('http://2many.x/1', 6)).to eq('http://2many.x/6') end it 'should detect a redirect loop' do stub_request(:head, 'http://bad.x/aaaa') .to_return(status: 301, headers: { Location: 'http://bad.x/bbbb' }) stub_request(:head, 'http://bad.x/bbbb') .to_return(status: 301, headers: { Location: 'http://bad.x/aaaa' }) expect(@filter.uri_expand('http://bad.x/aaaa')).to eq('http://bad.x/aaaa') end it 'should be able to handle an FTP URL' do stub_request(:head, 'http://downloads.x/aaaa') .to_return(status: 301, headers: { Location: 'http://downloads.x/download?file=aaaa.zip' }) stub_request(:head, 'http://downloads.x/download') .with(query: { file: 'aaaa.zip' }) .to_return(status: 301, headers: { Location: 'ftp://downloads.x/pub/aaaa.zip' }) expect(@filter.uri_expand('http://downloads.x/aaaa')).to eq('ftp://downloads.x/pub/aaaa.zip') end describe 'used in interpolation' do before do @agent = Agents::InterpolatableAgent.new(name: "test") end it 'should follow redirects' do @agent.interpolation_context['short_url'] = 'https://t.co.x/aaaa' @agent.options['long_url'] = '{{ short_url | uri_expand }}' expect(@agent.interpolated['long_url']).to eq('http://www.example.com/welcome') end it 'should respect the limit for the number of redirects' do @agent.interpolation_context['short_url'] = 'http://2many.x/1' @agent.options['long_url'] = '{{ short_url | uri_expand }}' expect(@agent.interpolated['long_url']).to eq('http://2many.x/1') @agent.interpolation_context['short_url'] = 'http://2many.x/1' @agent.options['long_url'] = '{{ short_url | uri_expand:6 }}' expect(@agent.interpolated['long_url']).to eq('http://2many.x/6') end end end describe 'regex_replace_first' do let(:agent) { Agents::InterpolatableAgent.new(name: "test") } it 'should replace the first occurrence of a string using regex' do agent.interpolation_context['something'] = 'foobar foobar' agent.options['cleaned'] = '{{ something | regex_replace_first: "\S+bar", "foobaz" }}' expect(agent.interpolated['cleaned']).to eq('foobaz foobar') end it 'should support escaped characters' do agent.interpolation_context['something'] = "foo\\1\n\nfoo\\bar\n\nfoo\\baz" agent.options['test'] = "{{ something | regex_replace_first: '\\\\(\\w{2,})', '\\1\\\\' | regex_replace_first: '\\n+', '\\n' }}" expect(agent.interpolated['test']).to eq("foo\\1\nfoobar\\\n\nfoo\\baz") end end describe 'regex_extract' do let(:agent) { Agents::InterpolatableAgent.new(name: "test") } it 'should extract the matched part' do agent.interpolation_context['something'] = "foo BAR BAZ" agent.options['test'] = "{{ something | regex_extract: '[A-Z]+' }} / {{ something | regex_extract: '[A-Z]([A-Z]+)', 1 }} / {{ something | regex_extract: '(?<x>.)AZ', 'x' }}" expect(agent.interpolated['test']).to eq("BAR / AR / B") end it 'should return nil if not matched' do agent.interpolation_context['something'] = "foo BAR BAZ" agent.options['test'] = "{% assign var = something | regex_extract: '[A-Z][a-z]+' %}{% if var == nil %}nil{% else %}non-nil{% endif %}" expect(agent.interpolated['test']).to eq("nil") end end describe 'regex_replace' do let(:agent) { Agents::InterpolatableAgent.new(name: "test") } it 'should replace the all occurrences of a string using regex' do agent.interpolation_context['something'] = 'foobar foobar' agent.options['cleaned'] = '{{ something | regex_replace: "\S+bar", "foobaz" }}' expect(agent.interpolated['cleaned']).to eq('foobaz foobaz') end it 'should support escaped characters' do agent.interpolation_context['something'] = "foo\\1\n\nfoo\\bar\n\nfoo\\baz" agent.options['test'] = "{{ something | regex_replace: '\\\\(\\w{2,})', '\\1\\\\' | regex_replace: '\\n+', '\\n' }}" expect(agent.interpolated['test']).to eq("foo\\1\nfoobar\\\nfoobaz\\") end end describe 'regex_replace_first block' do let(:agent) { Agents::InterpolatableAgent.new(name: "test") } it 'should replace the first occurrence of a string using regex' do agent.interpolation_context['something'] = 'foobar zoobar' agent.options['cleaned'] = '{% regex_replace_first "(?<word>\S+)(?<suffix>bar)" in %}{{ something }}{% with %}{{ word | upcase }}{{ suffix }}{% endregex_replace_first %}' expect(agent.interpolated['cleaned']).to eq('FOObar zoobar') end it 'should be able to take a pattern in a variable' do agent.interpolation_context['something'] = 'foobar zoobar' agent.interpolation_context['pattern'] = "(?<word>\\S+)(?<suffix>bar)" agent.options['cleaned'] = '{% regex_replace_first pattern in %}{{ something }}{% with %}{{ word | upcase }}{{ suffix }}{% endregex_replace_first %}' expect(agent.interpolated['cleaned']).to eq('FOObar zoobar') end it 'should define a variable named "match" in a "with" block' do agent.interpolation_context['something'] = 'foobar zoobar' agent.interpolation_context['pattern'] = "(?<word>\\S+)(?<suffix>bar)" agent.options['cleaned'] = '{% regex_replace_first pattern in %}{{ something }}{% with %}{{ match.word | upcase }}{{ match["suffix"] }}{% endregex_replace_first %}' expect(agent.interpolated['cleaned']).to eq('FOObar zoobar') end end describe 'regex_replace block' do let(:agent) { Agents::InterpolatableAgent.new(name: "test") } it 'should replace the all occurrences of a string using regex' do agent.interpolation_context['something'] = 'foobar zoobar' agent.options['cleaned'] = '{% regex_replace "(?<word>\S+)(?<suffix>bar)" in %}{{ something }}{% with %}{{ word | upcase }}{{ suffix }}{% endregex_replace %}' expect(agent.interpolated['cleaned']).to eq('FOObar ZOObar') end end describe 'fromjson' do let(:agent) { Agents::InterpolatableAgent.new(name: "test") } it 'should parse a JSON string' do agent.interpolation_context['json'] = '{"array": ["a", "b", "c"], "number": 42}' agent.options['key'] = '{% assign obj = json | fromjson %}{{ obj["array"][1] }} and {{ obj.number }}' expect(agent.interpolated['key']).to eq('b and 42') end end context 'as_object' do let(:agent) { Agents::InterpolatableAgent.new(name: "test") } it 'returns an array that was splitted in liquid tags' do agent.interpolation_context['something'] = 'test,string,abc' agent.options['array'] = "{{something | split: ',' | as_object}}" expect(agent.interpolated['array']).to eq(['test', 'string', 'abc']) end it 'returns an object that was not modified in liquid' do agent.interpolation_context['something'] = { 'nested' => { 'abc' => 'test' } } agent.options['object'] = "{{something.nested | as_object}}" expect(agent.interpolated['object']).to eq({ "abc" => 'test' }) end context 'as_json' do def ensure_safety(obj) JSON.parse(JSON.dump(obj)) end it 'it converts "complex" objects' do agent.interpolation_context['something'] = { 'nested' => Service.new } agent.options['object'] = "{{something | as_object}}" expect(agent.interpolated['object']).to eq({ 'nested' => ensure_safety(Service.new.as_json) }) end it 'works with Agent::Drops' do agent.interpolation_context['something'] = agent agent.options['object'] = "{{something | as_object}}" expect(agent.interpolated['object']).to eq(ensure_safety(agent.to_liquid.as_json.stringify_keys)) end it 'works with Event::Drops' do event = Event.new(payload: { some: 'payload' }, agent:, created_at: Time.now) agent.interpolation_context['something'] = event agent.options['object'] = "{{something | as_object}}" expect(agent.interpolated['object']).to eq(ensure_safety(event.to_liquid.as_json.stringify_keys)) end it 'works with MatchDataDrops' do match = "test string".match(/\A(?<word>\w+)\s(.+?)\z/) agent.interpolation_context['something'] = match agent.options['object'] = "{{something | as_object}}" expect(agent.interpolated['object']).to eq(ensure_safety(match.to_liquid.as_json.stringify_keys)) end it 'works with URIDrops' do uri = URI.parse("https://google.com?q=test") agent.interpolation_context['something'] = uri agent.options['object'] = "{{something | as_object}}" expect(agent.interpolated['object']).to eq(ensure_safety(uri.to_liquid.as_json.stringify_keys)) end end end describe 'rebase_hrefs' do let(:agent) { Agents::InterpolatableAgent.new(name: "test") } let(:fragment) { <<~HTML } <ul> <li> <a href="downloads/file1"><img src="/images/iconA.png" srcset="/images/iconA.png 1x, /images/iconA@2x.png 2x">file1</a> </li> <li> <a href="downloads/file2"><img src="/images/iconA.png" srcset="/images/iconA.png 1x, /images/iconA@2x.png 2x">file2</a> </li> <li> <a href="downloads/file3"><img src="/images/iconB.png" srcset="/images/iconB.png 1x, /images/iconB@2x.png 2x">file3</a> </li> </ul> HTML let(:replaced_fragment) { <<~HTML } <ul> <li> <a href="http://example.com/support/downloads/file1"><img src="http://example.com/images/iconA.png" srcset="http://example.com/images/iconA.png 1x, http://example.com/images/iconA@2x.png 2x">file1</a> </li> <li> <a href="http://example.com/support/downloads/file2"><img src="http://example.com/images/iconA.png" srcset="http://example.com/images/iconA.png 1x, http://example.com/images/iconA@2x.png 2x">file2</a> </li> <li> <a href="http://example.com/support/downloads/file3"><img src="http://example.com/images/iconB.png" srcset="http://example.com/images/iconB.png 1x, http://example.com/images/iconB@2x.png 2x">file3</a> </li> </ul> HTML it 'rebases relative URLs in a fragment' do agent.interpolation_context['content'] = fragment agent.options['template'] = "{{ content | rebase_hrefs: 'http://example.com/support/files.html' }}" expect(agent.interpolated['template']).to eq(replaced_fragment) end end describe 'digest filters' do let(:agent) { Agents::InterpolatableAgent.new(name: "test") } it 'computes digest values from string input' do agent.interpolation_context['value'] = 'Huginn' agent.interpolation_context['key'] = 'Muninn' agent.options['template'] = "{{ value | md5 }}" expect(agent.interpolated['template']).to eq('5fca9fe120027bc87fa9923cc926f8fe') agent.options['template'] = "{{ value | sha1 }}" expect(agent.interpolated['template']).to eq('647d81f6dae6ff474cdcef3e9b74f038206af680') agent.options['template'] = "{{ value | sha256 }}" expect(agent.interpolated['template']).to eq('62c6099ec14502176974aadf0991525f50332ba552500556fea583ffdf0ba076') agent.options['template'] = "{{ value | hmac_sha1: key }}" expect(agent.interpolated['template']).to eq('9bd7cdebac134e06ba87258c28d2deea431407ac') agent.options['template'] = "{{ value | hmac_sha256: key }}" expect(agent.interpolated['template']).to eq('38b98bc2625a8cac33369f6204e784482be5e172b242699406270856a841d1ec') end end describe 'group_by' do let(:events) do [ { "date" => "2019-07-30", "type" => "Snap" }, { "date" => "2019-07-30", "type" => "Crackle" }, { "date" => "2019-07-29", "type" => "Pop" }, { "date" => "2019-07-29", "type" => "Bam" }, { "date" => "2019-07-29", "type" => "Pow" }, ] end it "should group an enumerable by the given attribute" do expect(@filter.group_by(events, "date")).to eq( [ { "name" => "2019-07-30", "items" => [ { "date" => "2019-07-30", "type" => "Snap" }, { "date" => "2019-07-30", "type" => "Crackle" } ] }, { "name" => "2019-07-29", "items" => [ { "date" => "2019-07-29", "type" => "Pop" }, { "date" => "2019-07-29", "type" => "Bam" }, { "date" => "2019-07-29", "type" => "Pow" } ] } ] ) end it "should leave non-groupables alone" do expect(@filter.group_by("some string", "anything")).to eq("some string") end end describe '_agent_' do let(:agent) { Agents::InterpolatableAgent.new(name: 'test', options: { 'foo' => '{{bar}}' }) } it 'computes digest values from string input' do agent.options['template'] = 'name={{ _agent_.name }} foo={{ _agent_.options.foo }}' expect(agent.interpolated['template']).to eq 'name=test foo={{bar}}' end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/concerns/inheritance_tracking_spec.rb
spec/concerns/inheritance_tracking_spec.rb
require 'rails_helper' require 'inheritance_tracking' describe InheritanceTracking do class Class1 include InheritanceTracking end class Class2 < Class1; end class Class3 < Class1; end it "tracks subclasses" do expect(Class1.subclasses).to eq([Class2, Class3]) end it "can be temporarily overridden with #with_subclasses" do Class1.with_subclasses(Class2) do expect(Class1.subclasses).to eq([Class2]) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/concerns/sortable_events_spec.rb
spec/concerns/sortable_events_spec.rb
require 'rails_helper' describe SortableEvents do let(:agent_class) { Class.new(Agent) do include SortableEvents default_schedule 'never' def self.valid_type?(name) true end end } def new_agent(events_order = nil) options = {} options['events_order'] = events_order if events_order agent_class.new(name: 'test', options: options) { |agent| agent.user = users(:bob) } end describe 'validations' do let(:agent_class) { Class.new(Agent) do include SortableEvents default_schedule 'never' def self.valid_type?(name) true end end } def new_agent(events_order = nil) options = {} options['events_order'] = events_order if events_order agent_class.new(name: 'test', options: options) { |agent| agent.user = users(:bob) } end it 'should allow events_order to be unspecified, null or an empty array' do expect(new_agent()).to be_valid expect(new_agent(nil)).to be_valid expect(new_agent([])).to be_valid end it 'should not allow events_order to be a non-array object' do agent = new_agent(0) expect(agent).not_to be_valid expect(agent.errors[:base]).to include(/events_order/) agent = new_agent('') expect(agent).not_to be_valid expect(agent.errors[:base]).to include(/events_order/) agent = new_agent({}) expect(agent).not_to be_valid expect(agent.errors[:base]).to include(/events_order/) end it 'should not allow events_order to be an array containing unexpected objects' do agent = new_agent(['{{key}}', 1]) expect(agent).not_to be_valid expect(agent.errors[:base]).to include(/events_order/) agent = new_agent(['{{key1}}', ['{{key2}}', 'unknown']]) expect(agent).not_to be_valid expect(agent.errors[:base]).to include(/events_order/) end it 'should allow events_order to be an array containing strings and valid tuples' do agent = new_agent(['{{key1}}', ['{{key2}}'], ['{{key3}}', 'number']]) expect(agent).to be_valid agent = new_agent(['{{key1}}', ['{{key2}}'], ['{{key3}}', 'number'], ['{{key4}}', 'time', true]]) expect(agent).to be_valid end end describe 'sort_events' do let(:payloads) { [ { 'title' => 'TitleA', 'score' => 4, 'updated_on' => '7 Jul 2015' }, { 'title' => 'TitleB', 'score' => 2, 'updated_on' => '25 Jun 2014' }, { 'title' => 'TitleD', 'score' => 10, 'updated_on' => '10 Jan 2015' }, { 'title' => 'TitleC', 'score' => 10, 'updated_on' => '9 Feb 2015' }, ] } let(:events) { payloads.map { |payload| Event.new(payload: payload) } } it 'should sort events by a given key' do agent = new_agent(['{{title}}']) expect(agent.__send__(:sort_events, events).map { |e| e.payload['title'] }).to eq(%w[TitleA TitleB TitleC TitleD]) agent = new_agent([['{{title}}', 'string', true]]) expect(agent.__send__(:sort_events, events).map { |e| e.payload['title'] }).to eq(%w[TitleD TitleC TitleB TitleA]) end it 'should sort events by multiple keys' do agent = new_agent([['{{score}}', 'number'], '{{title}}']) expect(agent.__send__(:sort_events, events).map { |e| e.payload['title'] }).to eq(%w[TitleB TitleA TitleC TitleD]) agent = new_agent([['{{score}}', 'number'], ['{{title}}', 'string', true]]) expect(agent.__send__(:sort_events, events).map { |e| e.payload['title'] }).to eq(%w[TitleB TitleA TitleD TitleC]) end it 'should sort events by time' do agent = new_agent([['{{updated_on}}', 'time']]) expect(agent.__send__(:sort_events, events).map { |e| e.payload['title'] }).to eq(%w[TitleB TitleD TitleC TitleA]) end it 'should sort events stably' do agent = new_agent(['<constant>']) expect(agent.__send__(:sort_events, events).map { |e| e.payload['title'] }).to eq(%w[TitleA TitleB TitleD TitleC]) agent = new_agent([['<constant>', 'string', true]]) expect(agent.__send__(:sort_events, events).map { |e| e.payload['title'] }).to eq(%w[TitleA TitleB TitleD TitleC]) end it 'should support _index_' do agent = new_agent([['{{_index_}}', 'number', true]]) expect(agent.__send__(:sort_events, events).map { |e| e.payload['title'] }).to eq(%w[TitleC TitleD TitleB TitleA]) end end describe 'automatic event sorter' do describe 'declaration' do let(:passive_agent_class) { Class.new(Agent) do include SortableEvents cannot_create_events! end } let(:active_agent_class) { Class.new(Agent) do include SortableEvents end } describe 'can_order_created_events!' do it 'should refuse to work if called from an Agent that cannot create events' do expect { passive_agent_class.class_eval do can_order_created_events! end }.to raise_error('Cannot order events for agent that cannot create events') end it 'should work if called from an Agent that can create events' do expect { active_agent_class.class_eval do can_order_created_events! end }.not_to raise_error() end end describe 'can_order_created_events?' do it 'should return false unless an Agent declares can_order_created_events!' do expect(active_agent_class.can_order_created_events?).to eq(false) expect(active_agent_class.new.can_order_created_events?).to eq(false) end it 'should return true if an Agent declares can_order_created_events!' do active_agent_class.class_eval do can_order_created_events! end expect(active_agent_class.can_order_created_events?).to eq(true) expect(active_agent_class.new.can_order_created_events?).to eq(true) end end end describe 'behavior' do class Agents::EventOrderableAgent < Agent include SortableEvents default_schedule 'never' can_order_created_events! attr_accessor :payloads_to_emit def self.valid_type?(name) true end def check payloads_to_emit.each do |payload| create_event payload: payload end end def receive(events) events.each do |event| payloads_to_emit.each do |payload| create_event payload: payload.merge('title' => payload['title'] + event.payload['title_suffix']) end end end end let :new_agent do options = {} options['events_order'] = @events_order Agents::EventOrderableAgent.new(name: 'test', options: options) { |agent| agent.user = users(:bob) agent.payloads_to_emit = payloads } end let(:payloads) { [ { 'title' => 'TitleA', 'score' => 4, 'updated_on' => '7 Jul 2015' }, { 'title' => 'TitleB', 'score' => 2, 'updated_on' => '25 Jun 2014' }, { 'title' => 'TitleD', 'score' => 10, 'updated_on' => '10 Jan 2015' }, { 'title' => 'TitleC', 'score' => 10, 'updated_on' => '9 Feb 2015' }, ] } it 'should keep the order of created events unless events_order is specified' do [nil, []].each do |events_order| @events_order = events_order agent = new_agent agent.save! expect { agent.check }.to change { Event.count }.by(4) events = agent.events.last(4).sort_by(&:id) expect(events.map(&:payload)).to match_array(payloads) expect(events.map { |event| event.payload['title'] }).to eq(%w[TitleA TitleB TitleD TitleC]) end end it 'should sort events created in check() in the order specified in events_order' do @events_order = [['{{score}}', 'number'], ['{{title}}', 'string', true]] agent = new_agent agent.save! expect { agent.check }.to change { Event.count }.by(4) events = agent.events.last(4).sort_by(&:id) expect(events.map(&:payload)).to match_array(payloads) expect(events.map { |event| event.payload['title'] }).to eq(%w[TitleB TitleA TitleD TitleC]) end it 'should sort events created in receive() in the order specified in events_order' do @events_order = [['{{score}}', 'number'], ['{{title}}', 'string', true]] agent = new_agent agent.save! expect { agent.receive([Event.new(payload: { 'title_suffix' => ' [new]' }), Event.new(payload: { 'title_suffix' => ' [popular]' })]) }.to change { Event.count }.by(8) events = agent.events.last(8).sort_by(&:id) expect(events.map { |event| event.payload['title'] }).to eq([ 'TitleB [new]', 'TitleA [new]', 'TitleD [new]', 'TitleC [new]', 'TitleB [popular]', 'TitleA [popular]', 'TitleD [popular]', 'TitleC [popular]', ]) end describe 'with the include_sort_info option enabled' do let :new_agent do agent = super() agent.options['include_sort_info'] = true agent end it 'should add sort_info to events created in check() when events_order is not specified' do agent = new_agent agent.save! expect { agent.check }.to change { Event.count }.by(4) events = agent.events.last(4).sort_by(&:id) expect(events.map { |event| event.payload['title'] }).to eq(%w[TitleA TitleB TitleD TitleC]) expect(events.map { |event| event.payload['sort_info'] }).to eq((1..4).map{ |pos| { 'position' => pos, 'count' => 4 } }) end it 'should add sort_info to events created in check() when events_order is specified' do @events_order = [['{{score}}', 'number'], ['{{title}}', 'string', true]] agent = new_agent agent.save! expect { agent.check }.to change { Event.count }.by(4) events = agent.events.last(4).sort_by(&:id) expect(events.map { |event| event.payload['title'] }).to eq(%w[TitleB TitleA TitleD TitleC]) expect(events.map { |event| event.payload['sort_info'] }).to eq((1..4).map{ |pos| { 'position' => pos, 'count' => 4 } }) end it 'should add sort_info to events created in receive() when events_order is specified' do @events_order = [['{{score}}', 'number'], ['{{title}}', 'string', true]] agent = new_agent agent.save! expect { agent.receive([Event.new(payload: { 'title_suffix' => ' [new]' }), Event.new(payload: { 'title_suffix' => ' [popular]' })]) }.to change { Event.count }.by(8) events = agent.events.last(8).sort_by(&:id) expect(events.map { |event| event.payload['title'] }).to eq([ 'TitleB [new]', 'TitleA [new]', 'TitleD [new]', 'TitleC [new]', 'TitleB [popular]', 'TitleA [popular]', 'TitleD [popular]', 'TitleC [popular]', ]) expect(events.map { |event| event.payload['sort_info'] }).to eq((1..4).map{ |pos| { 'position' => pos, 'count' => 4 } } * 2) 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/routing/webhooks_controller_spec.rb
spec/routing/webhooks_controller_spec.rb
require 'rails_helper' describe "routing for web requests", :type => :routing do it "routes to handle_request" do resulting_params = { :user_id => "6", :agent_id => "2", :secret => "foobar" } expect(get("/users/6/web_requests/2/foobar")).to route_to("web_requests#handle_request", resulting_params) expect(post("/users/6/web_requests/2/foobar")).to route_to("web_requests#handle_request", resulting_params) expect(put("/users/6/web_requests/2/foobar")).to route_to("web_requests#handle_request", resulting_params) expect(delete("/users/6/web_requests/2/foobar")).to route_to("web_requests#handle_request", resulting_params) end it "supports the legacy /webhooks/ route" do expect(post("/users/6/webhooks/2/foobar")).to route_to("web_requests#handle_request", :user_id => "6", :agent_id => "2", :secret => "foobar") end it "routes with format" do expect(get("/users/6/web_requests/2/foobar.json")).to route_to("web_requests#handle_request", { :user_id => "6", :agent_id => "2", :secret => "foobar", :format => "json" }) expect(get("/users/6/web_requests/2/foobar.atom")).to route_to("web_requests#handle_request", { :user_id => "6", :agent_id => "2", :secret => "foobar", :format => "atom" }) end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/presenters/form_configurable_agent_presenter_spec.rb
spec/presenters/form_configurable_agent_presenter_spec.rb
require 'rails_helper' describe FormConfigurableAgentPresenter do include RSpecHtmlMatchers class FormConfigurableAgentPresenterAgent < Agent include FormConfigurable form_configurable :string, roles: :validatable form_configurable :number, type: :number, html_options: { min: 0 } form_configurable :text, type: :text, roles: :completable form_configurable :boolean, type: :boolean form_configurable :array, type: :array, values: [1, 2, 3] form_configurable :json, type: :json end before(:all) do @presenter = FormConfigurableAgentPresenter.new(FormConfigurableAgentPresenterAgent.new, ActionController::Base.new.view_context) end it "works for the type :string" do expect(@presenter.option_field_for(:string)).to( have_tag( 'input', with: { 'data-attribute': 'string', role: 'validatable form-configurable', type: 'text', name: 'agent[options][string]' } ) ) end it "works for the type :number" do expect(@presenter.option_field_for(:number)).to( have_tag( 'input', with: { 'data-attribute': 'number', role: 'form-configurable', type: 'number', name: 'agent[options][number]', min: '0', } ) ) end it "works for the type :text" do expect(@presenter.option_field_for(:text)).to( have_tag( 'textarea', with: { 'data-attribute': 'text', role: 'completable form-configurable', name: 'agent[options][text]' } ) ) end it "works for the type :boolean" do expect(@presenter.option_field_for(:boolean)).to( have_tag( 'input', with: { 'data-attribute': 'boolean', role: 'form-configurable', name: 'agent[options][boolean_radio]', type: 'radio' } ) ) end it "works for the type :array" do expect(@presenter.option_field_for(:array)).to( have_tag( 'select', with: { 'data-attribute': 'array', role: 'completable form-configurable', name: 'agent[options][array]' } ) ) end it "works for the type :json" do expect(@presenter.option_field_for(:json)).to( have_tag( 'textarea', with: { 'data-attribute': 'json', role: 'form-configurable', name: 'agent[options][json]', class: 'live-json-editor', } ) ) end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/helpers/markdown_helper_spec.rb
spec/helpers/markdown_helper_spec.rb
require 'rails_helper' describe MarkdownHelper do describe '#markdown' do it 'renders HTML from a markdown text' do expect(markdown('# Header')).to match(/<h1>Header<\/h1>/) expect(markdown('## Header 2')).to match(/<h2>Header 2<\/h2>/) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/helpers/jobs_helper_spec.rb
spec/helpers/jobs_helper_spec.rb
require 'rails_helper' describe JobsHelper do let(:job) { Delayed::Job.new } describe '#status' do it "works for failed jobs" do job.failed_at = Time.now expect(status(job)).to eq('<span class="label label-danger">failed</span>') end it "works for running jobs" do job.locked_at = Time.now job.locked_by = 'test' expect(status(job)).to eq('<span class="label label-info">running</span>') end it "works for queued jobs" do expect(status(job)).to eq('<span class="label label-warning">queued</span>') end end describe '#relative_distance_of_time_in_words' do it "in the past" do expect(relative_distance_of_time_in_words(Time.now-5.minutes)).to eq('5m ago') end it "in the future" do expect(relative_distance_of_time_in_words(Time.now+5.minutes)).to eq('in 5m') end end describe "#agent_from_job" do context "when handler does not contain job_data" do before do job.handler = "--- !ruby/object:AgentCheckJob\narguments:\n- 1\n" end it "finds the agent for AgentCheckJob" do expect(agent_from_job(job)).to eq(false) end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/helpers/scenario_helper_spec.rb
spec/helpers/scenario_helper_spec.rb
require 'rails_helper' describe ScenarioHelper do let(:scenario) { users(:bob).scenarios.build(name: 'Scene', tag_fg_color: '#AAAAAA', tag_bg_color: '#000000') } describe '#style_colors' do it 'returns a css style-formated version of the scenario foreground and background colors' do expect(style_colors(scenario)).to eq("color:#AAAAAA;background-color:#000000") end it 'defauls foreground and background colors' do scenario.tag_fg_color = nil scenario.tag_bg_color = nil expect(style_colors(scenario)).to eq("color:#FFFFFF;background-color:#5BC0DE") end end describe '#scenario_label' do it 'creates a scenario label with the scenario name' do expect(scenario_label(scenario)).to eq( '<span class="label scenario" style="color:#AAAAAA;background-color:#000000">Scene</span>' ) end it 'creates a scenario label with the given text' do expect(scenario_label(scenario, 'Other')).to eq( '<span class="label scenario" style="color:#AAAAAA;background-color:#000000">Other</span>' ) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/helpers/dot_helper_spec.rb
spec/helpers/dot_helper_spec.rb
require 'rails_helper' describe DotHelper do describe "with example Agents" do class Agents::DotFoo < Agent default_schedule "2pm" def check create_event :payload => {} end end class Agents::DotBar < Agent cannot_be_scheduled! def check create_event :payload => {} end end before do allow(Agents::DotFoo).to receive(:valid_type?).with("Agents::DotFoo") { true } allow(Agents::DotBar).to receive(:valid_type?).with("Agents::DotBar") { true } end describe "#agents_dot" do before do @agents = [ @foo = Agents::DotFoo.new(name: "foo").tap { |agent| agent.user = users(:bob) agent.save! }, @bar1 = Agents::DotBar.new(name: "bar1").tap { |agent| agent.user = users(:bob) agent.sources << @foo agent.save! }, @bar2 = Agents::DotBar.new(name: "bar2").tap { |agent| agent.user = users(:bob) agent.sources << @foo agent.propagate_immediately = true agent.disabled = true agent.save! }, @bar3 = Agents::DotBar.new(name: "bar3").tap { |agent| agent.user = users(:bob) agent.sources << @bar2 agent.save! }, ] @foo.reload @bar2.reload # Fix the order of receivers @agents.each do |agent| expect(agent).to receive(:receivers).and_wrap_original { |orig| orig.call.order(:id) } end end it "generates a DOT script" do expect(agents_dot(@agents)).to match(%r{ \A digraph \x20 "Agent \x20 Event \x20 Flow" \{ node \[ [^\]]+ \]; edge \[ [^\]]+ \]; (?<foo>\w+) \[label=foo\]; \k<foo> -> (?<bar1>\w+) \[style=dashed\]; \k<foo> -> (?<bar2>\w+) \[color="\#999999"\]; \k<bar1> \[label=bar1\]; \k<bar2> \[label=bar2,style="rounded,dashed",color="\#999999",fontcolor="\#999999"\]; \k<bar2> -> (?<bar3>\w+) \[style=dashed,color="\#999999"\]; \k<bar3> \[label=bar3\]; \} \z }x) end it "generates a richer DOT script" do expect(agents_dot(@agents, rich: true)).to match(%r{ \A digraph \x20 "Agent \x20 Event \x20 Flow" \{ (graph \[ [^\]]+ \];)? node \[ [^\]]+ \]; edge \[ [^\]]+ \]; (?<foo>\w+) \[label=foo,tooltip="Dot \x20 Foo",URL="#{Regexp.quote(agent_path(@foo))}"\]; \k<foo> -> (?<bar1>\w+) \[style=dashed\]; \k<foo> -> (?<bar2>\w+) \[color="\#999999"\]; \k<bar1> \[label=bar1,tooltip="Dot \x20 Bar",URL="#{Regexp.quote(agent_path(@bar1))}"\]; \k<bar2> \[label=bar2,tooltip="Dot \x20 Bar",URL="#{Regexp.quote(agent_path(@bar2))}",style="rounded,dashed",color="\#999999",fontcolor="\#999999"\]; \k<bar2> -> (?<bar3>\w+) \[style=dashed,color="\#999999"\]; \k<bar3> \[label=bar3,tooltip="Dot \x20 Bar",URL="#{Regexp.quote(agent_path(@bar3))}"\]; \} \z }x) end end end describe "DotHelper::DotDrawer" do describe "#id" do it "properly escapes double quotaion and backslash" do expect(DotHelper::DotDrawer.draw(foo: "") { id('hello\\"') }).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/helpers/application_helper_spec.rb
spec/helpers/application_helper_spec.rb
require 'rails_helper' describe ApplicationHelper do describe '#icon_tag' do it 'returns a Glyphicon icon element' do icon = icon_tag('glyphicon-help') expect(icon).to be_html_safe expect(Nokogiri(icon).at('span.glyphicon.glyphicon-help')).to be_a Nokogiri::XML::Element end it 'returns a Glyphicon icon element with an addidional class' do icon = icon_tag('glyphicon-help', class: 'text-info') expect(icon).to be_html_safe expect(Nokogiri(icon).at('span.glyphicon.glyphicon-help.text-info')).to be_a Nokogiri::XML::Element end it 'returns a FontAwesome icon element' do icon = icon_tag('fa-copy') expect(icon).to be_html_safe expect(Nokogiri(icon).at('i.fa-solid.fa-copy')).to be_a Nokogiri::XML::Element end it 'returns a FontAwesome icon element with an additional class' do icon = icon_tag('fa-copy', class: 'text-info') expect(icon).to be_html_safe expect(Nokogiri(icon).at('i.fa-solid.fa-copy.text-info')).to be_a Nokogiri::XML::Element end it 'returns a FontAwesome brand icon element' do icon = icon_tag('fa-github', class: 'fa-brands') expect(icon).to be_html_safe expect(Nokogiri(icon).at('i.fa-brands.fa-github')).to be_a Nokogiri::XML::Element end end describe '#nav_link' do it 'returns a nav link' do allow(self).to receive(:current_page?).with('/things') { false } nav = nav_link('Things', '/things') a = Nokogiri(nav).at('li:not(.active) > a[href="/things"]') expect(a.text.strip).to eq('Things') end it 'returns an active nav link' do allow(self).to receive(:current_page?).with('/things') { true } nav = nav_link('Things', '/things') expect(nav).to be_html_safe a = Nokogiri(nav).at('li.active > a[href="/things"]') expect(a).to be_a Nokogiri::XML::Element expect(a.text.strip).to eq('Things') end describe 'with block' do it 'returns a nav link with menu' do allow(self).to receive(:current_page?).with('/things') { false } allow(self).to receive(:current_page?).with('/things/stuff') { false } nav = nav_link('Things', '/things') { nav_link('Stuff', '/things/stuff') } expect(nav).to be_html_safe a0 = Nokogiri(nav).at('li.dropdown.dropdown-hover:not(.active) > a[href="/things"]') expect(a0).to be_a Nokogiri::XML::Element expect(a0.text.strip).to eq('Things') a1 = Nokogiri(nav).at('li.dropdown.dropdown-hover:not(.active) > li:not(.active) > a[href="/things/stuff"]') expect(a1).to be_a Nokogiri::XML::Element expect(a1.text.strip).to eq('Stuff') end it 'returns an active nav link with menu' do allow(self).to receive(:current_page?).with('/things') { true } allow(self).to receive(:current_page?).with('/things/stuff') { false } nav = nav_link('Things', '/things') { nav_link('Stuff', '/things/stuff') } expect(nav).to be_html_safe a0 = Nokogiri(nav).at('li.dropdown.dropdown-hover.active > a[href="/things"]') expect(a0).to be_a Nokogiri::XML::Element expect(a0.text.strip).to eq('Things') a1 = Nokogiri(nav).at('li.dropdown.dropdown-hover.active > li:not(.active) > a[href="/things/stuff"]') expect(a1).to be_a Nokogiri::XML::Element expect(a1.text.strip).to eq('Stuff') end it 'returns an active nav link with menu when on a child page' do allow(self).to receive(:current_page?).with('/things') { false } allow(self).to receive(:current_page?).with('/things/stuff') { true } nav = nav_link('Things', '/things') { nav_link('Stuff', '/things/stuff') } expect(nav).to be_html_safe a0 = Nokogiri(nav).at('li.dropdown.dropdown-hover.active > a[href="/things"]') expect(a0).to be_a Nokogiri::XML::Element expect(a0.text.strip).to eq('Things') a1 = Nokogiri(nav).at('li.dropdown.dropdown-hover.active > li:not(.active) > a[href="/things/stuff"]') expect(a1).to be_a Nokogiri::XML::Element expect(a1.text.strip).to eq('Stuff') end end end describe '#yes_no' do it 'returns a label "Yes" if any truthy value is given' do [true, Object.new].each { |value| label = yes_no(value) expect(label).to be_html_safe expect(Nokogiri(label).text).to eq 'Yes' } end it 'returns a label "No" if any falsy value is given' do [false, nil].each { |value| label = yes_no(value) expect(label).to be_html_safe expect(Nokogiri(label).text).to eq 'No' } end end describe '#working' do before do @agent = agents(:jane_website_agent) end it 'returns a label "Disabled" if a given agent is disabled' do allow(@agent).to receive(:disabled?) { true } label = working(@agent) expect(label).to be_html_safe expect(Nokogiri(label).text).to eq 'Disabled' end it 'returns a label "Missing Gems" if a given agent has dependencies missing' do allow(@agent).to receive(:dependencies_missing?) { true } label = working(@agent) expect(label).to be_html_safe expect(Nokogiri(label).text).to eq 'Missing Gems' end it 'returns a label "Yes" if a given agent is working' do allow(@agent).to receive(:working?) { true } label = working(@agent) expect(label).to be_html_safe expect(Nokogiri(label).text).to eq 'Yes' end it 'returns a label "No" if a given agent is not working' do allow(@agent).to receive(:working?) { false } label = working(@agent) expect(label).to be_html_safe expect(Nokogiri(label).text).to eq 'No' end end describe '#omniauth_provider_icon' do it 'returns a correct icon tag for Twitter' do icon = omniauth_provider_icon(:twitter) expect(icon).to be_html_safe elem = Nokogiri(icon).at('i.fa-brands.fa-twitter') expect(elem).to be_a Nokogiri::XML::Element end it 'returns a correct icon tag for GitHub' do icon = omniauth_provider_icon(:github) expect(icon).to be_html_safe elem = Nokogiri(icon).at('i.fa-brands.fa-github') expect(elem).to be_a Nokogiri::XML::Element end it 'returns a correct icon tag for other services' do icon = omniauth_provider_icon(:evernote) expect(icon).to be_html_safe elem = Nokogiri(icon).at('i.fa-solid.fa-lock') expect(elem).to be_a Nokogiri::XML::Element end end describe '#highlighted?' do it 'understands hl=6-8' do allow(params).to receive(:[]).with(:hl) { '6-8' } expect((1..10).select { |i| highlighted?(i) }).to eq [6, 7, 8] end it 'understands hl=1,3-4,9' do allow(params).to receive(:[]).with(:hl) { '1,3-4,9' } expect((1..10).select { |i| highlighted?(i) }).to eq [1, 3, 4, 9] end it 'understands hl=8-' do allow(params).to receive(:[]).with(:hl) { '8-' } expect((1..10).select { |i| highlighted?(i) }).to eq [8, 9, 10] end it 'understands hl=-2' do allow(params).to receive(:[]).with(:hl) { '-2' } expect((1..10).select { |i| highlighted?(i) }).to eq [1, 2] end it 'understands hl=-' do allow(params).to receive(:[]).with(:hl) { '-' } expect((1..10).select { |i| highlighted?(i) }).to eq [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] end it 'is OK with no hl' do allow(params).to receive(:[]).with(:hl) { nil } expect((1..10).select { |i| highlighted?(i) }).to be_empty end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/importers/scenario_import_spec.rb
spec/importers/scenario_import_spec.rb
require 'rails_helper' describe ScenarioImport do let(:user) { users(:bob) } let(:guid) { "somescenarioguid" } let(:tag_fg_color) { "#ffffff" } let(:tag_bg_color) { "#000000" } let(:icon) { 'Star' } let(:description) { "This is a cool Huginn Scenario that does something useful!" } let(:name) { "A useful Scenario" } let(:source_url) { "http://example.com/scenarios/2/export.json" } let(:weather_agent_options) { { 'api_key' => 'some-api-key', 'location' => '42.3601,-71.0589' } } let(:trigger_agent_options) { { 'expected_receive_period_in_days' => 2, 'rules' => [{ 'type' => "regex", 'value' => "rain|storm", 'path' => "conditions", }], 'message' => "Looks like rain!" } } let(:valid_parsed_weather_agent_data) do { :type => "Agents::WeatherAgent", :name => "a weather agent", :schedule => "5pm", :keep_events_for => 14.days, :disabled => true, :guid => "a-weather-agent", :options => weather_agent_options } end let(:valid_parsed_trigger_agent_data) do { :type => "Agents::TriggerAgent", :name => "listen for weather", :keep_events_for => 0, :propagate_immediately => true, :disabled => false, :guid => "a-trigger-agent", :options => trigger_agent_options } end let(:valid_parsed_twitter_user_agent_data) do { type: "Agents::TwitterUserAgent", name: "Twitter test", schedule: "every_1h", keep_events_for: 0, propagate_immediately: true, disabled: false, guid: "a-twitter-user-agent", options: { username: "bob", expected_update_period_in_days: 2 } } end let(:valid_parsed_data) do { schema_version: 1, name: name, description: description, guid: guid, tag_fg_color: tag_fg_color, tag_bg_color: tag_bg_color, icon: icon, source_url: source_url, exported_at: 2.days.ago.utc.iso8601, agents: [ valid_parsed_weather_agent_data, valid_parsed_trigger_agent_data ], links: [ { :source => 0, :receiver => 1 } ], control_links: [] } end let(:valid_data) { valid_parsed_data.to_json } let(:invalid_data) { { :name => "some scenario missing a guid" }.to_json } describe "initialization" do it "is initialized with an attributes hash" do expect(ScenarioImport.new(:url => "http://google.com").url).to eq("http://google.com") end end describe "validations" do subject do _import = ScenarioImport.new _import.set_user(user) _import end it "is not valid when none of file, url, or data are present" do expect(subject).not_to be_valid expect(subject).to have(1).error_on(:base) expect(subject.errors[:base]).to include("Please provide either a Scenario JSON File or a Public Scenario URL.") end describe "data" do it "should be invalid with invalid data" do subject.data = invalid_data expect(subject).not_to be_valid expect(subject).to have(1).error_on(:base) subject.data = "foo" expect(subject).not_to be_valid expect(subject).to have(1).error_on(:base) # It also clears the data when invalid expect(subject.data).to be_nil end it "should be valid with valid data" do subject.data = valid_data expect(subject).to be_valid end end describe "url" do it "should be invalid with an unreasonable URL" do subject.url = "foo" expect(subject).not_to be_valid expect(subject).to have(1).error_on(:url) expect(subject.errors[:url]).to include("appears to be invalid") end it "should be invalid when the referenced url doesn't contain a scenario" do stub_request(:get, "http://example.com/scenarios/1/export.json").to_return(:status => 200, :body => invalid_data) subject.url = "http://example.com/scenarios/1/export.json" expect(subject).not_to be_valid expect(subject.errors[:base]).to include("The provided data does not appear to be a valid Scenario.") end it "should be valid when the url points to a valid scenario" do stub_request(:get, "http://example.com/scenarios/1/export.json").to_return(:status => 200, :body => valid_data) subject.url = "http://example.com/scenarios/1/export.json" expect(subject).to be_valid end end describe "file" do it "should be invalid when the uploaded file doesn't contain a scenario" do subject.file = StringIO.new("foo") expect(subject).not_to be_valid expect(subject.errors[:base]).to include("The provided data does not appear to be a valid Scenario.") subject.file = StringIO.new(invalid_data) expect(subject).not_to be_valid expect(subject.errors[:base]).to include("The provided data does not appear to be a valid Scenario.") end it "should be valid with a valid uploaded scenario" do subject.file = StringIO.new(valid_data) expect(subject).to be_valid end end end describe "#dangerous?" do it "returns false on most Agents" do expect(ScenarioImport.new(:data => valid_data)).not_to be_dangerous end it "returns true if a ShellCommandAgent is present" do valid_parsed_data[:agents][0][:type] = "Agents::ShellCommandAgent" expect(ScenarioImport.new(:data => valid_parsed_data.to_json)).to be_dangerous end end describe "#import and #generate_diff" do let(:scenario_import) do _import = ScenarioImport.new(:data => valid_data) _import.set_user users(:bob) _import end context "when this scenario has never been seen before" do describe "#import" do it "makes a new scenario" do expect { scenario_import.import(:skip_agents => true) }.to change { users(:bob).scenarios.count }.by(1) expect(scenario_import.scenario.name).to eq(name) expect(scenario_import.scenario.description).to eq(description) expect(scenario_import.scenario.guid).to eq(guid) expect(scenario_import.scenario.tag_fg_color).to eq(tag_fg_color) expect(scenario_import.scenario.tag_bg_color).to eq(tag_bg_color) expect(scenario_import.scenario.icon).to eq(icon) expect(scenario_import.scenario.source_url).to eq(source_url) expect(scenario_import.scenario.public).to be_falsey end it "creates the Agents" do expect { scenario_import.import }.to change { users(:bob).agents.count }.by(2) weather_agent = scenario_import.scenario.agents.find_by(:guid => "a-weather-agent") trigger_agent = scenario_import.scenario.agents.find_by(:guid => "a-trigger-agent") expect(weather_agent.name).to eq("a weather agent") expect(weather_agent.schedule).to eq("5pm") expect(weather_agent.keep_events_for).to eq(14.days) expect(weather_agent.propagate_immediately).to be_falsey expect(weather_agent).to be_disabled expect(weather_agent.memory).to be_empty expect(weather_agent.options).to eq(weather_agent_options) expect(trigger_agent.name).to eq("listen for weather") expect(trigger_agent.sources).to eq([weather_agent]) expect(trigger_agent.schedule).to be_nil expect(trigger_agent.keep_events_for).to eq(0) expect(trigger_agent.propagate_immediately).to be_truthy expect(trigger_agent).not_to be_disabled expect(trigger_agent.memory).to be_empty expect(trigger_agent.options).to eq(trigger_agent_options) end it "creates new Agents, even if one already exists with the given guid (so that we don't overwrite a user's work outside of the scenario)" do agents(:bob_weather_agent).update_attribute :guid, "a-weather-agent" expect { scenario_import.import }.to change { users(:bob).agents.count }.by(2) end context "when the schema_version is less than 1" do before do valid_parsed_weather_agent_data[:keep_events_for] = 2 valid_parsed_data.delete(:schema_version) end it "translates keep_events_for from days to seconds" do scenario_import.import expect(scenario_import.errors).to be_empty weather_agent = scenario_import.scenario.agents.find_by(:guid => "a-weather-agent") trigger_agent = scenario_import.scenario.agents.find_by(:guid => "a-trigger-agent") expect(weather_agent.keep_events_for).to eq(2.days) expect(trigger_agent.keep_events_for).to eq(0) end end describe "with control links" do it 'creates the links' do valid_parsed_data[:control_links] = [ { :controller => 1, :control_target => 0 } ] expect { scenario_import.import }.to change { users(:bob).agents.count }.by(2) weather_agent = scenario_import.scenario.agents.find_by(:guid => "a-weather-agent") trigger_agent = scenario_import.scenario.agents.find_by(:guid => "a-trigger-agent") expect(trigger_agent.sources).to eq([weather_agent]) expect(weather_agent.controllers.to_a).to eq([trigger_agent]) expect(trigger_agent.control_targets.to_a).to eq([weather_agent]) end it "doesn't crash without any control links" do valid_parsed_data.delete(:control_links) expect { scenario_import.import }.to change { users(:bob).agents.count }.by(2) weather_agent = scenario_import.scenario.agents.find_by(:guid => "a-weather-agent") trigger_agent = scenario_import.scenario.agents.find_by(:guid => "a-trigger-agent") expect(trigger_agent.sources).to eq([weather_agent]) end end end describe "#generate_diff" do it "returns AgentDiff objects for the incoming Agents" do expect(scenario_import).to be_valid agent_diffs = scenario_import.agent_diffs weather_agent_diff = agent_diffs[0] trigger_agent_diff = agent_diffs[1] valid_parsed_weather_agent_data.each do |key, value| if key == :type value = value.split("::").last end expect(weather_agent_diff).to respond_to(key) field = weather_agent_diff.send(key) expect(field).to be_a(ScenarioImport::AgentDiff::FieldDiff) expect(field.incoming).to eq(value) expect(field.updated).to eq(value) expect(field.current).to be_nil end expect(weather_agent_diff).not_to respond_to(:propagate_immediately) valid_parsed_trigger_agent_data.each do |key, value| if key == :type value = value.split("::").last end expect(trigger_agent_diff).to respond_to(key) field = trigger_agent_diff.send(key) expect(field).to be_a(ScenarioImport::AgentDiff::FieldDiff) expect(field.incoming).to eq(value) expect(field.updated).to eq(value) expect(field.current).to be_nil end expect(trigger_agent_diff).not_to respond_to(:schedule) end end end context "when an a scenario already exists with the given guid for the importing user" do let!(:existing_scenario) do _existing_scenerio = users(:bob).scenarios.build(:name => "an existing scenario", :description => "something") _existing_scenerio.guid = guid _existing_scenerio.save! agents(:bob_weather_agent).update_attribute :guid, "a-weather-agent" agents(:bob_weather_agent).scenarios << _existing_scenerio _existing_scenerio end describe "#import" do it "uses the existing scenario, updating its data" do expect { scenario_import.import(:skip_agents => true) expect(scenario_import.scenario).to eq(existing_scenario) }.not_to change { users(:bob).scenarios.count } existing_scenario.reload expect(existing_scenario.guid).to eq(guid) expect(existing_scenario.tag_fg_color).to eq(tag_fg_color) expect(existing_scenario.tag_bg_color).to eq(tag_bg_color) expect(existing_scenario.icon).to eq(icon) expect(existing_scenario.description).to eq(description) expect(existing_scenario.name).to eq(name) expect(existing_scenario.source_url).to eq(source_url) expect(existing_scenario.public).to be_falsey end it "updates any existing agents in the scenario, and makes new ones as needed" do expect(scenario_import).to be_valid expect { scenario_import.import }.to change { users(:bob).agents.count }.by(1) # One, because the weather agent already existed. weather_agent = existing_scenario.agents.find_by(:guid => "a-weather-agent") trigger_agent = existing_scenario.agents.find_by(:guid => "a-trigger-agent") expect(weather_agent).to eq(agents(:bob_weather_agent)) expect(weather_agent.name).to eq("a weather agent") expect(weather_agent.schedule).to eq("5pm") expect(weather_agent.keep_events_for).to eq(14.days) expect(weather_agent.propagate_immediately).to be_falsey expect(weather_agent).to be_disabled expect(weather_agent.memory).to be_empty expect(weather_agent.options).to eq(weather_agent_options) expect(trigger_agent.name).to eq("listen for weather") expect(trigger_agent.sources).to eq([weather_agent]) expect(trigger_agent.schedule).to be_nil expect(trigger_agent.keep_events_for).to eq(0) expect(trigger_agent.propagate_immediately).to be_truthy expect(trigger_agent).not_to be_disabled expect(trigger_agent.memory).to be_empty expect(trigger_agent.options).to eq(trigger_agent_options) end it "honors updates coming from the UI" do scenario_import.merges = { "0" => { "name" => "updated name", "schedule" => "6pm", "keep_events_for" => 2.days.to_i.to_s, "disabled" => "false", "options" => weather_agent_options.merge("api_key" => "foo").to_json } } expect(scenario_import).to be_valid expect(scenario_import.import).to be_truthy weather_agent = existing_scenario.agents.find_by(:guid => "a-weather-agent") expect(weather_agent.name).to eq("updated name") expect(weather_agent.schedule).to eq("6pm") expect(weather_agent.keep_events_for).to eq(2.days.to_i) expect(weather_agent).not_to be_disabled expect(weather_agent.options).to eq(weather_agent_options.merge("api_key" => "foo")) end it "adds errors when updated agents are invalid" do scenario_import.merges = { "0" => { "name" => "", "schedule" => "foo", "keep_events_for" => 2.days.to_i.to_s, "options" => weather_agent_options.merge("api_key" => "").to_json } } expect(scenario_import.import).to be_falsey errors = scenario_import.errors.full_messages.to_sentence expect(errors).to match(/Name can't be blank/) expect(errors).to match(/api_key is required/) expect(errors).to match(/Schedule is not a valid schedule/) end end describe "#generate_diff" do it "returns AgentDiff objects that include 'current' values from any agents that already exist" do agent_diffs = scenario_import.agent_diffs weather_agent_diff = agent_diffs[0] trigger_agent_diff = agent_diffs[1] # Already exists expect(weather_agent_diff.agent).to eq(agents(:bob_weather_agent)) valid_parsed_weather_agent_data.each do |key, value| next if key == :type expect(weather_agent_diff.send(key).current).to eq(agents(:bob_weather_agent).send(key)) end # Doesn't exist yet valid_parsed_trigger_agent_data.each do |key, value| expect(trigger_agent_diff.send(key).current).to be_nil end end context "when the schema_version is less than 1" do it "translates keep_events_for from days to seconds" do valid_parsed_data.delete(:schema_version) valid_parsed_data[:agents] = [valid_parsed_weather_agent_data.merge(keep_events_for: 5)] scenario_import.merges = { "0" => { "name" => "a new name", "schedule" => "6pm", "keep_events_for" => 2.days.to_i.to_s, "disabled" => "true", "options" => weather_agent_options.merge("api_key" => "foo").to_json } } expect(scenario_import).to be_valid weather_agent_diff = scenario_import.agent_diffs[0] expect(weather_agent_diff.name.current).to eq(agents(:bob_weather_agent).name) expect(weather_agent_diff.name.incoming).to eq('a weather agent') expect(weather_agent_diff.name.updated).to eq('a new name') expect(weather_agent_diff.keep_events_for.current).to eq(45.days.to_i) expect(weather_agent_diff.keep_events_for.incoming).to eq(5.days.to_i) expect(weather_agent_diff.keep_events_for.updated).to eq(2.days.to_i.to_s) end end it "sets the 'updated' FieldDiff values based on any feedback from the user" do scenario_import.merges = { "0" => { "name" => "a new name", "schedule" => "6pm", "keep_events_for" => 2.days.to_s, "disabled" => "true", "options" => weather_agent_options.merge("api_key" => "foo").to_json }, "1" => { "name" => "another new name" } } expect(scenario_import).to be_valid agent_diffs = scenario_import.agent_diffs weather_agent_diff = agent_diffs[0] trigger_agent_diff = agent_diffs[1] expect(weather_agent_diff.name.current).to eq(agents(:bob_weather_agent).name) expect(weather_agent_diff.name.incoming).to eq(valid_parsed_weather_agent_data[:name]) expect(weather_agent_diff.name.updated).to eq("a new name") expect(weather_agent_diff.schedule.updated).to eq("6pm") expect(weather_agent_diff.keep_events_for.current).to eq(45.days) expect(weather_agent_diff.keep_events_for.updated).to eq(2.days.to_s) expect(weather_agent_diff.disabled.updated).to eq("true") expect(weather_agent_diff.options.updated).to eq(weather_agent_options.merge("api_key" => "foo")) end it "adds errors on validation when updated options are unparsable" do scenario_import.merges = { "0" => { "options" => '{' } } expect(scenario_import).not_to be_valid expect(scenario_import).to have(1).error_on(:base) end end end context "when Bob imports Jane's scenario" do let!(:existing_scenario) do _existing_scenerio = users(:jane).scenarios.build(:name => "an existing scenario", :description => "something") _existing_scenerio.guid = guid _existing_scenerio.save! _existing_scenerio end describe "#import" do it "makes a new scenario for Bob" do expect { scenario_import.import(:skip_agents => true) }.to change { users(:bob).scenarios.count }.by(1) expect(Scenario.where(guid: guid).count).to eq(2) expect(scenario_import.scenario.name).to eq(name) expect(scenario_import.scenario.description).to eq(description) expect(scenario_import.scenario.guid).to eq(guid) expect(scenario_import.scenario.tag_fg_color).to eq(tag_fg_color) expect(scenario_import.scenario.tag_bg_color).to eq(tag_bg_color) expect(scenario_import.scenario.icon).to eq(icon) expect(scenario_import.scenario.source_url).to eq(source_url) expect(scenario_import.scenario.public).to be_falsey end it "does not change Jane's scenario" do expect { scenario_import.import(:skip_agents => true) }.not_to change { users(:jane).scenarios } expect(users(:jane).scenarios.find_by(guid: guid)).to eq(existing_scenario) end end end context "agents which require a service" do let(:service) { services(:generic) } let(:valid_parsed_services) do data = valid_parsed_data data[:agents] = [valid_parsed_twitter_user_agent_data, valid_parsed_trigger_agent_data] data end let(:valid_parsed_services_data) { valid_parsed_services.to_json } let(:services_scenario_import) { _import = ScenarioImport.new(:data => valid_parsed_services_data) _import.set_user users(:bob) _import } describe "#generate_diff" do it "should check if the agent requires a service" do agent_diffs = services_scenario_import.agent_diffs twitter_user_agent_diff = agent_diffs[0] expect(twitter_user_agent_diff.requires_service?).to eq(true) end it "should add an error when no service is selected" do expect(services_scenario_import.import).to eq(false) expect(services_scenario_import.errors[:base].length).to eq(1) end end describe "#import" do it "should import" do services_scenario_import.merges = { "0" => { "service_id" => service.id.to_s, } } expect { expect(services_scenario_import.import).to eq(true) }.to change { users(:bob).agents.count }.by(2) 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/importers/default_scenario_importer_spec.rb
spec/importers/default_scenario_importer_spec.rb
require 'rails_helper' describe DefaultScenarioImporter do let(:user) { users(:bob) } describe '.import' do it 'imports a set of agents to get the user going when they are first created' do expect(DefaultScenarioImporter).to receive(:seed).with(kind_of(User)) allow(ENV).to receive(:[]) { nil } allow(ENV).to receive(:[]).with('IMPORT_DEFAULT_SCENARIO_FOR_ALL_USERS') { 'true' } DefaultScenarioImporter.import(user) end it 'can be turned off' do allow(DefaultScenarioImporter).to receive(:seed) { fail "seed should not have been called"} allow(ENV).to receive(:[]) { nil } allow(ENV).to receive(:[]).with('IMPORT_DEFAULT_SCENARIO_FOR_ALL_USERS') { 'false' } DefaultScenarioImporter.import(user) end it 'is turned off for existing instances of Huginn' do allow(DefaultScenarioImporter).to receive(:seed) { fail "seed should not have been called"} allow(ENV).to receive(:[]) { nil } allow(ENV).to receive(:[]).with('IMPORT_DEFAULT_SCENARIO_FOR_ALL_USERS') { nil } DefaultScenarioImporter.import(user) end end describe '.seed' do it 'imports a set of agents to get the user going when they are first created' do expect { DefaultScenarioImporter.seed(user) }.to change(user.agents, :count).by(7) end it 'respects an environment variable that specifies a path or URL to a different scenario' do allow(ENV).to receive(:[]) { nil } allow(ENV).to receive(:[]).with('DEFAULT_SCENARIO_FILE') { File.join(Rails.root, "spec", "fixtures", "test_default_scenario.json") } expect { DefaultScenarioImporter.seed(user) }.to change(user.agents, :count).by(3) end it 'can not be turned off' do allow(ENV).to receive(:[]) { nil } allow(ENV).to receive(:[]).with('IMPORT_DEFAULT_SCENARIO_FOR_ALL_USERS') { 'true' } expect { DefaultScenarioImporter.seed(user) }.to change(user.agents, :count).by(7) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/db/seeds/admin_and_default_scenario_spec.rb
spec/db/seeds/admin_and_default_scenario_spec.rb
require 'rails_helper' require_relative '../../../db/seeds/seeder' describe Seeder do before do stub_puts_to_prevent_spew_in_spec_output end describe '.seed' do before(:each) do User.delete_all expect(User.count).to eq(0) end it 'imports a default scenario' do expect { Seeder.seed }.to change(Agent, :count).by(7) end it 'creates an admin' do expect { Seeder.seed }.to change(User, :count).by(1) expect(User.last).to be_admin end it 'can be run multiple times and exit normally' do Seeder.seed expect(Seeder).to receive(:exit) Seeder.seed end end def stub_puts_to_prevent_spew_in_spec_output allow(Seeder).to receive(:puts).with(anything) allow(Seeder).to receive(:puts) end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/controllers/logs_controller_spec.rb
spec/controllers/logs_controller_spec.rb
require 'rails_helper' describe LogsController do describe "GET index" do it "can filter by Agent" do sign_in users(:bob) get :index, params: {:agent_id => agents(:bob_weather_agent).id} expect(assigns(:logs).length).to eq(agents(:bob_weather_agent).logs.length) expect(assigns(:logs).all? {|i| expect(i.agent).to eq(agents(:bob_weather_agent)) }).to be_truthy end it "only loads Agents owned by the current user" do sign_in users(:bob) expect { get :index, params: {:agent_id => agents(:jane_weather_agent).id} }.to raise_error(ActiveRecord::RecordNotFound) end end describe "DELETE clear" do it "deletes all logs for a specific Agent" do agents(:bob_weather_agent).last_error_log_at = 2.hours.ago sign_in users(:bob) expect { delete :clear, params: {:agent_id => agents(:bob_weather_agent).id} }.to change { AgentLog.count }.by(-1 * agents(:bob_weather_agent).logs.count) expect(assigns(:logs).length).to eq(0) expect(agents(:bob_weather_agent).reload.logs.count).to eq(0) expect(agents(:bob_weather_agent).last_error_log_at).to be_nil end it "only deletes logs for an Agent owned by the current user" do sign_in users(:bob) expect { delete :clear, params: {:agent_id => agents(:jane_weather_agent).id} }.to raise_error(ActiveRecord::RecordNotFound) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/controllers/web_requests_controller_spec.rb
spec/controllers/web_requests_controller_spec.rb
require 'rails_helper' describe WebRequestsController do class Agents::WebRequestReceiverAgent < Agent cannot_receive_events! cannot_be_scheduled! def receive_web_request(params, method, format) if params.delete(:secret) == options[:secret] memory[:web_request_values] = params memory[:web_request_format] = format memory[:web_request_method] = method ["success", (options[:status] || 200).to_i, memory['content_type'], memory['response_headers']] else ["failure", 404] end end end before do allow(Agents::WebRequestReceiverAgent).to receive(:valid_type?).with("Agents::WebRequestReceiverAgent") { true } @agent = Agents::WebRequestReceiverAgent.new(:name => "something", :options => { :secret => "my_secret" }) @agent.user = users(:bob) @agent.save! end it "should not require login to receive a web request" do expect(@agent.last_web_request_at).to be_nil post :handle_request, params: {:user_id => users(:bob).to_param, :agent_id => @agent.id, :secret => "my_secret", :key => "value", :another_key => "5"} expect(@agent.reload.last_web_request_at).to be_within(2).of(Time.now) expect(response.body).to eq("success") expect(response).to be_successful end it "should call receive_web_request" do post :handle_request, params: {:user_id => users(:bob).to_param, :agent_id => @agent.id, :secret => "my_secret", :key => "value", :another_key => "5"} @agent.reload expect(@agent.memory[:web_request_values]).to eq({ 'key' => "value", 'another_key' => "5" }) expect(@agent.memory[:web_request_format]).to eq("text/html") expect(@agent.memory[:web_request_method]).to eq("post") expect(response.body).to eq("success") expect(response.headers['Content-Type']).to eq('text/plain; charset=utf-8') expect(response).to be_successful post :handle_request, params: {:user_id => users(:bob).to_param, :agent_id => @agent.id, :secret => "not_my_secret", :no => "go"} expect(@agent.reload.memory[:web_request_values]).not_to eq({ 'no' => "go" }) expect(response.body).to eq("failure") expect(response).to be_not_found end it "should accept gets" do get :handle_request, params: {:user_id => users(:bob).to_param, :agent_id => @agent.id, :secret => "my_secret", :key => "value", :another_key => "5"} @agent.reload expect(@agent.memory[:web_request_values]).to eq({ 'key' => "value", 'another_key' => "5" }) expect(@agent.memory[:web_request_format]).to eq("text/html") expect(@agent.memory[:web_request_method]).to eq("get") expect(response.body).to eq("success") expect(response).to be_successful end it "should pass through the received format" do get :handle_request, params: {:user_id => users(:bob).to_param, :agent_id => @agent.id, :secret => "my_secret", :key => "value", :another_key => "5"}, :format => :json @agent.reload expect(@agent.memory[:web_request_values]).to eq({ 'key' => "value", 'another_key' => "5" }) expect(@agent.memory[:web_request_format]).to eq("application/json") expect(@agent.memory[:web_request_method]).to eq("get") post :handle_request, params: {:user_id => users(:bob).to_param, :agent_id => @agent.id, :secret => "my_secret", :key => "value", :another_key => "5"}, :format => :xml @agent.reload expect(@agent.memory[:web_request_values]).to eq({ 'key' => "value", 'another_key' => "5" }) expect(@agent.memory[:web_request_format]).to eq("application/xml") expect(@agent.memory[:web_request_method]).to eq("post") put :handle_request, params: {:user_id => users(:bob).to_param, :agent_id => @agent.id, :secret => "my_secret", :key => "value", :another_key => "5"}, :format => :atom @agent.reload expect(@agent.memory[:web_request_values]).to eq({ 'key' => "value", 'another_key' => "5" }) expect(@agent.memory[:web_request_format]).to eq("application/atom+xml") expect(@agent.memory[:web_request_method]).to eq("put") end it "can accept a content-type to return" do @agent.memory['content_type'] = 'application/json' @agent.save! get :handle_request, params: {:user_id => users(:bob).to_param, :agent_id => @agent.id, :secret => "my_secret", :key => "value", :another_key => "5"} expect(response.headers['Content-Type']).to eq('application/json; charset=utf-8') end it "can accept custom response headers to return" do @agent.memory['response_headers'] = {"Access-Control-Allow-Origin" => "*"} @agent.save! get :handle_request, params: {:user_id => users(:bob).to_param, :agent_id => @agent.id, :secret => "my_secret", :key => "value", :another_key => "5"} expect(response.headers['Access-Control-Allow-Origin']).to eq('*') end it "can accept multiple custom response headers to return" do @agent.memory['response_headers'] = {"Access-Control-Allow-Origin" => "*", "X-My-Custom-Header" => "hello"} @agent.save! get :handle_request, params: {:user_id => users(:bob).to_param, :agent_id => @agent.id, :secret => "my_secret", :key => "value", :another_key => "5"} expect(response.headers['Access-Control-Allow-Origin']).to eq('*') expect(response.headers['X-My-Custom-Header']).to eq('hello') end it 'should redirect correctly' do @agent.options['status'] = 302 @agent.save post :handle_request, params: {:user_id => users(:bob).to_param, :agent_id => @agent.id, :secret => "my_secret"}, format: :json expect(response).to redirect_to('success') end it "should fail on incorrect users" do post :handle_request, params: {:user_id => users(:jane).to_param, :agent_id => @agent.id, :secret => "my_secret", :no => "go"} expect(response).to be_not_found end it "should fail on incorrect agents" do post :handle_request, params: {:user_id => users(:bob).to_param, :agent_id => 454545, :secret => "my_secret", :no => "go"} expect(response).to be_not_found end describe "legacy update_location endpoint" do before do @agent = Agent.build_for_type("Agents::UserLocationAgent", users(:bob), name: "something", options: { secret: "my_secret" }) @agent.save! end it "should create events without requiring login" do post :update_location, params: {user_id: users(:bob).to_param, secret: "my_secret", longitude: 123, latitude: 45, something: "else"} 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 "should only consider Agents::UserLocationAgents for the given user" do @jane_agent = Agent.build_for_type("Agents::UserLocationAgent", users(:jane), name: "something", options: { secret: "my_secret" }) @jane_agent.save! post :update_location, params: {user_id: users(:bob).to_param, secret: "my_secret", longitude: 123, latitude: 45, something: "else"} expect(@agent.events.last.payload).to eq({ 'longitude' => "123", 'latitude' => "45", 'something' => "else" }) expect(@jane_agent.events).to be_empty end it "should raise a 404 error when given an invalid user id" do post :update_location, params: {user_id: "123", secret: "not_my_secret", longitude: 123, latitude: 45, something: "else"} expect(response).to be_not_found end it "should only look at agents with the given secret" do @agent2 = Agent.build_for_type("Agents::UserLocationAgent", users(:bob), name: "something", options: { secret: "my_secret2" }) @agent2.save! expect { post :update_location, params: {user_id: users(:bob).to_param, secret: "my_secret2", longitude: 123, latitude: 45, something: "else"} expect(@agent2.events.last.payload).to eq({ 'longitude' => "123", 'latitude' => "45", 'something' => "else" }) }.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/controllers/agents_controller_spec.rb
spec/controllers/agents_controller_spec.rb
require 'rails_helper' describe AgentsController do def valid_attributes(options = {}) { :type => "Agents::WebsiteAgent", :name => "Something", :options => agents(:bob_website_agent).options, :source_ids => [agents(:bob_weather_agent).id, ""] }.merge(options) end describe "GET index" do it "only returns Agents for the current user" do sign_in users(:bob) get :index expect(assigns(:agents).all? {|i| expect(i.user).to eq(users(:bob)) }).to be_truthy end it "should not show disabled agents if the cookie is set" do @request.cookies["huginn_view_only_enabled_agents"] = "true" sign_in users(:bob) get :index expect(assigns(:agents).map(&:disabled).uniq).to eq([false]) end end describe "POST handle_details_post" do it "passes control to handle_details_post on the agent" do sign_in users(:bob) post :handle_details_post, params: {:id => agents(:bob_manual_event_agent).to_param, :payload => { :foo => "bar" }.to_json} expect(JSON.parse(response.body)).to eq({ "success" => true }) expect(agents(:bob_manual_event_agent).events.last.payload).to eq({ 'foo' => "bar" }) end it "can only be accessed by the Agent's owner" do sign_in users(:jane) expect { post :handle_details_post, params: {:id => agents(:bob_manual_event_agent).to_param, :payload => { :foo => :bar }.to_json} }.to raise_error(ActiveRecord::RecordNotFound) end end describe "POST run" do it "triggers Agent.async_check with the Agent's ID" do sign_in users(:bob) expect(Agent).to receive(:async_check).with(agents(:bob_manual_event_agent).id) post :run, params: {:id => agents(:bob_manual_event_agent).to_param} end it "can only be accessed by the Agent's owner" do sign_in users(:jane) expect { post :run, params: {:id => agents(:bob_manual_event_agent).to_param} }.to raise_error(ActiveRecord::RecordNotFound) end end describe "POST reemit_events" do let(:agent) { agents(:bob_website_agent) } let(:params) { { :id => agent.to_param } } it "enqueues an AgentReemitJob" do expect(AgentReemitJob).to receive(:perform_later).with(agent, agent.most_recent_event.id, false) sign_in users(:bob) post :reemit_events, params: params end context "when agent has no events" do let(:agent) { agents(:bob_weather_agent) } it "does not enqueue an AgentReemitJob" do expect(AgentReemitJob).not_to receive(:perform_later) sign_in users(:bob) post :reemit_events, params: params end end context "when delete_old_events passed" do it "enqueues an AgentReemitJob with delete_old_events set to true" do expect(AgentReemitJob).to receive(:perform_later).with(agent, agent.most_recent_event.id, true) sign_in users(:bob) post :reemit_events, params: params.merge('delete_old_events' => '1') end end it "can only be accessed by the Agent's owner" do sign_in users(:jane) expect { post :reemit_events, params: {:id => agents(:bob_website_agent).to_param} }.to raise_error(ActiveRecord::RecordNotFound) end end describe "POST remove_events" do it "deletes all events created by the given Agent" do sign_in users(:bob) agent_event = events(:bob_website_agent_event).id other_event = events(:jane_website_agent_event).id post :remove_events, params: {:id => agents(:bob_website_agent).to_param} expect(Event.where(:id => agent_event).count).to eq(0) expect(Event.where(:id => other_event).count).to eq(1) end it "can only be accessed by the Agent's owner" do sign_in users(:jane) expect { post :remove_events, params: {:id => agents(:bob_website_agent).to_param} }.to raise_error(ActiveRecord::RecordNotFound) end end describe "PUT toggle_visibility" do it "should set the cookie" do sign_in users(:jane) put :toggle_visibility expect(response.cookies["huginn_view_only_enabled_agents"]).to eq("true") end it "should delete the cookie" do @request.cookies["huginn_view_only_enabled_agents"] = "true" sign_in users(:jane) put :toggle_visibility expect(response.cookies["huginn_view_only_enabled_agents"]).to be_nil end end describe "POST propagate" do before(:each) do sign_in users(:bob) end it "runs event propagation for all Agents" do expect(Agent).to receive(:receive!).and_call_original post :propagate end it "does not run the propagation when a job is already enqueued" do expect(AgentPropagateJob).to receive(:can_enqueue?) { false } post :propagate expect(flash[:notice]).to eq('Event propagation is already scheduled to run.') end end describe "GET show" do it "only shows Agents for the current user" do sign_in users(:bob) get :show, params: {:id => agents(:bob_website_agent).to_param} expect(assigns(:agent)).to eq(agents(:bob_website_agent)) expect { get :show, params: {:id => agents(:jane_website_agent).to_param} }.to raise_error(ActiveRecord::RecordNotFound) end end describe "GET new" do describe "with :id" do it "opens a clone of a given Agent" do sign_in users(:bob) get :new, params: {:id => agents(:bob_website_agent).to_param} expect(assigns(:agent).attributes).to eq(users(:bob).agents.build_clone(agents(:bob_website_agent)).attributes) end it "only allows the current user to clone his own Agent" do sign_in users(:bob) expect { get :new, params: {:id => agents(:jane_website_agent).to_param} }.to raise_error(ActiveRecord::RecordNotFound) end end describe "with a scenario_id" do it 'populates the assigned agent with the scenario' do sign_in users(:bob) get :new, params: {:scenario_id => scenarios(:bob_weather).id} expect(assigns(:agent).scenario_ids).to eq([scenarios(:bob_weather).id]) end it "does not see other user's scenarios" do sign_in users(:bob) get :new, params: {:scenario_id => scenarios(:jane_weather).id} expect(assigns(:agent).scenario_ids).to eq([]) end end end describe "GET edit" do it "only shows Agents for the current user" do sign_in users(:bob) get :edit, params: {:id => agents(:bob_website_agent).to_param} expect(assigns(:agent)).to eq(agents(:bob_website_agent)) expect { get :edit, params: {:id => agents(:jane_website_agent).to_param} }.to raise_error(ActiveRecord::RecordNotFound) end end describe "POST create" do it "errors on bad types" do sign_in users(:bob) expect { post :create, params: {:agent => valid_attributes(:type => "Agents::ThisIsFake")} }.not_to change { users(:bob).agents.count } expect(assigns(:agent)).to be_a(Agent) expect(assigns(:agent)).to have(1).error_on(:type) sign_in users(:bob) expect { post :create, params: {:agent => valid_attributes(:type => "Object")} }.not_to change { users(:bob).agents.count } expect(assigns(:agent)).to be_a(Agent) expect(assigns(:agent)).to have(1).error_on(:type) sign_in users(:bob) expect { post :create, params: {:agent => valid_attributes(:type => "Agent")} }.not_to change { users(:bob).agents.count } expect(assigns(:agent)).to be_a(Agent) expect(assigns(:agent)).to have(1).error_on(:type) expect { post :create, params: {:agent => valid_attributes(:type => "User")} }.not_to change { users(:bob).agents.count } expect(assigns(:agent)).to be_a(Agent) expect(assigns(:agent)).to have(1).error_on(:type) end it "creates Agents for the current user" do sign_in users(:bob) expect { expect { post :create, params: {:agent => valid_attributes} }.to change { users(:bob).agents.count }.by(1) }.to change { Link.count }.by(1) expect(assigns(:agent)).to be_a(Agents::WebsiteAgent) end it "creates Agents and accepts specifing a target agent" do sign_in users(:bob) attributes = valid_attributes(service_id: 1) attributes[:receiver_ids] = attributes[:source_ids] expect { expect { post :create, params: {:agent => attributes} }.to change { users(:bob).agents.count }.by(1) }.to change { Link.count }.by(2) expect(assigns(:agent)).to be_a(Agents::WebsiteAgent) end it "shows errors" do sign_in users(:bob) expect { post :create, params: {:agent => valid_attributes(:name => "")} }.not_to change { users(:bob).agents.count } expect(assigns(:agent)).to have(1).errors_on(:name) expect(response).to render_template("new") end it "will not accept Agent sources owned by other users" do sign_in users(:bob) expect { expect { post :create, params: {:agent => valid_attributes(:source_ids => [agents(:jane_weather_agent).id])} }.not_to change { users(:bob).agents.count } }.not_to change { Link.count } end end describe "PUT update" do it "does not allow changing types" do sign_in users(:bob) post :update, params: {:id => agents(:bob_website_agent).to_param, :agent => valid_attributes(:type => "Agents::WeatherAgent")} expect(assigns(:agent)).to have(1).errors_on(:type) expect(response).to render_template("edit") end it "updates attributes on Agents for the current user" do sign_in users(:bob) post :update, params: {:id => agents(:bob_website_agent).to_param, :agent => valid_attributes(:name => "New name")} expect(response).to redirect_to(agents_path) expect(agents(:bob_website_agent).reload.name).to eq("New name") expect { post :update, params: {:id => agents(:jane_website_agent).to_param, :agent => valid_attributes(:name => "New name")} }.to raise_error(ActiveRecord::RecordNotFound) end it "accepts JSON requests" do sign_in users(:bob) post :update, params: {:id => agents(:bob_website_agent).to_param, :agent => valid_attributes(:name => "New name")}, :format => :json expect(agents(:bob_website_agent).reload.name).to eq("New name") expect(JSON.parse(response.body)['name']).to eq("New name") expect(response).to be_successful end it "will not accept Agent sources owned by other users" do sign_in users(:bob) post :update, params: {:id => agents(:bob_website_agent).to_param, :agent => valid_attributes(:source_ids => [agents(:jane_weather_agent).id])} expect(assigns(:agent)).to have(1).errors_on(:sources) end it "will not accept Scenarios owned by other users" do sign_in users(:bob) post :update, params: {:id => agents(:bob_website_agent).to_param, :agent => valid_attributes(:scenario_ids => [scenarios(:jane_weather).id])} expect(assigns(:agent)).to have(1).errors_on(:scenarios) end it "shows errors" do sign_in users(:bob) post :update, params: {:id => agents(:bob_website_agent).to_param, :agent => valid_attributes(:name => "")} expect(assigns(:agent)).to have(1).errors_on(:name) expect(response).to render_template("edit") end it 'does not allow to modify the agents user_id' do sign_in users(:bob) expect { post :update, params: {:id => agents(:bob_website_agent).to_param, :agent => valid_attributes(:user_id => users(:jane).id)} }.to raise_error(ActionController::UnpermittedParameters) end describe "redirecting back" do before do sign_in users(:bob) end it "can redirect back to the show path" do post :update, params: {:id => agents(:bob_website_agent).to_param, :agent => valid_attributes(:name => "New name"), :return => "show"} expect(response).to redirect_to(agent_path(agents(:bob_website_agent))) end it "redirect back to the index path by default" do post :update, params: {:id => agents(:bob_website_agent).to_param, :agent => valid_attributes(:name => "New name")} expect(response).to redirect_to(agents_path) end it "accepts return paths to scenarios" do post :update, params: {:id => agents(:bob_website_agent).to_param, :agent => valid_attributes(:name => "New name"), :return => "/scenarios/2"} expect(response).to redirect_to("/scenarios/2") end it "sanitizes return paths" do post :update, params: {:id => agents(:bob_website_agent).to_param, :agent => valid_attributes(:name => "New name"), :return => "/scenar"} expect(response).to redirect_to(agents_path) post :update, params: {:id => agents(:bob_website_agent).to_param, :agent => valid_attributes(:name => "New name"), :return => "http://google.com"} expect(response).to redirect_to(agents_path) post :update, params: {:id => agents(:bob_website_agent).to_param, :agent => valid_attributes(:name => "New name"), :return => "javascript:alert(1)"} expect(response).to redirect_to(agents_path) end end it "updates last_checked_event_id when drop_pending_events is given" do sign_in users(:bob) agent = agents(:bob_website_agent) agent.disabled = true agent.last_checked_event_id = nil agent.save! post :update, params: {id: agents(:bob_website_agent).to_param, agent: { disabled: 'false', drop_pending_events: 'true' }} agent.reload expect(agent.disabled).to eq(false) expect(agent.last_checked_event_id).to eq(Event.maximum(:id)) end end describe "PUT leave_scenario" do it "removes an Agent from the given Scenario for the current user" do sign_in users(:bob) expect(agents(:bob_weather_agent).scenarios).to include(scenarios(:bob_weather)) put :leave_scenario, params: {:id => agents(:bob_weather_agent).to_param, :scenario_id => scenarios(:bob_weather).to_param} expect(agents(:bob_weather_agent).scenarios).not_to include(scenarios(:bob_weather)) expect(Scenario.where(:id => scenarios(:bob_weather).id)).to exist expect { put :leave_scenario, params: {:id => agents(:jane_weather_agent).to_param, :scenario_id => scenarios(:jane_weather).to_param} }.to raise_error(ActiveRecord::RecordNotFound) end end describe "DELETE destroy" do it "destroys only Agents owned by the current user" do sign_in users(:bob) expect { delete :destroy, params: {:id => agents(:bob_website_agent).to_param} }.to change(Agent, :count).by(-1) expect { delete :destroy, params: {:id => agents(:jane_website_agent).to_param} }.to raise_error(ActiveRecord::RecordNotFound) end it "redirects correctly when the Agent is deleted from the Agent itself" do sign_in users(:bob) delete :destroy, params: {:id => agents(:bob_website_agent).to_param} expect(response).to redirect_to agents_path end it "redirects correctly when the Agent is deleted from a Scenario" do sign_in users(:bob) delete :destroy, params: {:id => agents(:bob_weather_agent).to_param, :return => scenario_path(scenarios(:bob_weather)).to_param} expect(response).to redirect_to scenario_path(scenarios(:bob_weather)) end end describe "#form_configurable actions" do before(:each) do @params = {attribute: 'auth_token', agent: valid_attributes(:type => "Agents::HipchatAgent", options: {auth_token: '12345'})} sign_in users(:bob) end describe "POST validate" do it "returns with status 200 when called with a valid option" do allow_any_instance_of(Agents::HipchatAgent).to receive(:validate_option) { true } post :validate, params: @params expect(response.status).to eq 200 end it "returns with status 403 when called with an invalid option" do allow_any_instance_of(Agents::HipchatAgent).to receive(:validate_option) { false } post :validate, params: @params expect(response.status).to eq 403 end end describe "POST complete" do it "callsAgent#complete_option and renders json" do allow_any_instance_of(Agents::HipchatAgent).to receive(:complete_option) { [{name: 'test', value: 1}] } post :complete, params: @params expect(response.status).to eq 200 expect(response.header['Content-Type']).to include('application/json') end end end describe "DELETE memory" do it "clears memory of the agent" do agent = agents(:bob_website_agent) agent.update!(memory: { "test" => 42 }) sign_in users(:bob) delete :destroy_memory, params: {id: agent.to_param} expect(agent.reload.memory).to eq({}) end it "does not clear memory of an agent not owned by the current user" do agent = agents(:jane_website_agent) agent.update!(memory: { "test" => 42 }) sign_in users(:bob) expect { delete :destroy_memory, params: {id: agent.to_param} }.to raise_error(ActiveRecord::RecordNotFound) expect(agent.reload.memory).to eq({ "test" => 42}) end end describe 'DELETE undefined' do it 'removes an undefined agent from the database' do sign_in users(:bob) agent = agents(:bob_website_agent) agent.update_attribute(:type, 'Agents::UndefinedAgent') agent2 = agents(:jane_website_agent) agent2.update_attribute(:type, 'Agents::UndefinedAgent') expect { delete :destroy_undefined }.to change { Agent.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/controllers/omniauth_callbacks_controller_spec.rb
spec/controllers/omniauth_callbacks_controller_spec.rb
require 'rails_helper' describe OmniauthCallbacksController do before do sign_in users(:bob) OmniAuth.config.test_mode = true request.env["devise.mapping"] = Devise.mappings[:user] end describe "accepting a callback url" do it "should update the user's credentials" do request.env["omniauth.auth"] = JSON.parse(File.read(Rails.root.join('spec/data_fixtures/services/twitter.json'))) expect { get :twitter }.to change { users(:bob).services.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/controllers/jobs_controller_spec.rb
spec/controllers/jobs_controller_spec.rb
require 'rails_helper' describe JobsController do describe "GET index" do before do async_handler_yaml = "--- !ruby/object:ActiveJob::QueueAdapters::DelayedJobAdapter::JobWrapper\njob_data:\n job_class: AgentCheckJob\n job_id: 123id\n queue_name: default\n arguments:\n - %d\n" Delayed::Job.create!(handler: async_handler_yaml % [agents(:jane_website_agent).id]) Delayed::Job.create!(handler: async_handler_yaml % [agents(:bob_website_agent).id]) Delayed::Job.create!(handler: async_handler_yaml % [agents(:jane_weather_agent).id]) agents(:jane_website_agent).destroy Delayed::Job.create!(handler: async_handler_yaml % [agents(:bob_weather_agent).id], locked_at: Time.now, locked_by: 'test') expect(Delayed::Job.count).to be > 0 end it "does not allow normal users" do expect(users(:bob)).not_to be_admin sign_in users(:bob) expect(get(:index)).to redirect_to(root_path) end it "returns all jobs" do expect(users(:jane)).to be_admin sign_in users(:jane) get :index expect(assigns(:jobs).length).to eq(4) end end describe "DELETE destroy" do before do @not_running = Delayed::Job.create @running = Delayed::Job.create(locked_at: Time.now, locked_by: 'test') sign_in users(:jane) end it "destroy a job which is not running" do expect { delete :destroy, params: {id: @not_running.id} }.to change(Delayed::Job, :count).by(-1) end it "does not destroy a running job" do expect { delete :destroy, params: {id: @running.id} }.to change(Delayed::Job, :count).by(0) end end describe "PUT run" do before do @not_running = Delayed::Job.create(run_at: Time.now - 1.hour) @running = Delayed::Job.create(locked_at: Time.now, locked_by: 'test') @failed = Delayed::Job.create(run_at: Time.now - 1.hour, locked_at: Time.now, failed_at: Time.now) sign_in users(:jane) end it "queue a job which is not running" do expect { put :run, params: {id: @not_running.id} }.to change { @not_running.reload.run_at } end it "queue a job that failed" do expect { put :run, params: {id: @failed.id} }.to change { @failed.reload.run_at } end it "not queue a running job" do expect { put :run, params: {id: @running.id} }.not_to change { @not_running.reload.run_at } end end describe "DELETE destroy_failed" do before do @failed = Delayed::Job.create(failed_at: Time.now - 1.minute) @running = Delayed::Job.create(locked_at: Time.now, locked_by: 'test') @pending = Delayed::Job.create sign_in users(:jane) end it "just destroy failed jobs" do expect { delete :destroy_failed }.to change(Delayed::Job, :count).by(-1) end end describe "DELETE destroy_all" do before do @failed = Delayed::Job.create(failed_at: Time.now - 1.minute) @running = Delayed::Job.create(locked_at: Time.now, locked_by: 'test') @pending = Delayed::Job.create sign_in users(:jane) end it "destroys all jobs" do expect { delete :destroy_all }.to change(Delayed::Job, :count).by(-2) expect(Delayed::Job.find(@running.id)).to be end end describe "POST retry_queued" do before do @not_running = Delayed::Job.create(run_at: Time.zone.now - 1.hour) @not_running.update_attribute(:attempts, 1) sign_in users(:jane) end it "run the queued job" do expect(Delayed::Job.last.run_at.to_i).not_to be_within(2).of(Time.zone.now.to_i) post :retry_queued expect(Delayed::Job.last.run_at.to_i).to be_within(2).of(Time.zone.now.to_i) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/controllers/user_credentials_controller_spec.rb
spec/controllers/user_credentials_controller_spec.rb
require 'rails_helper' describe UserCredentialsController do def valid_attributes(options = {}) { :credential_name => "some_name", :credential_value => "some_value" }.merge(options) end before do sign_in users(:bob) @file = fixture_file_upload('user_credentials.json') end describe "GET index" do it "only returns UserCredentials for the current user" do get :index expect(assigns(:user_credentials).all? {|i| expect(i.user).to eq(users(:bob)) }).to be_truthy end end describe "GET edit" do it "only shows UserCredentials for the current user" do get :edit, params: {:id => user_credentials(:bob_aws_secret).to_param} expect(assigns(:user_credential)).to eq(user_credentials(:bob_aws_secret)) expect { get :edit, params: {:id => user_credentials(:jane_aws_secret).to_param} }.to raise_error(ActiveRecord::RecordNotFound) end end describe "Post import" do it "asserts user credentials were created for current user only" do post :import, params: {:file => @file} expect(controller.current_user.id).to eq(users(:bob).id) expect(controller.current_user.user_credentials).to eq(users(:bob).user_credentials) end it "asserts that primary id in json file is ignored" do post :import, params: {:file => @file} expect(controller.current_user.user_credentials.last.id).not_to eq(24) end it "duplicate credential name shows an error that it is not saved" do file1 = fixture_file_upload('multiple_user_credentials.json') post :import, params: {:file => file1} expect(flash[:notice]).to eq("One or more of the uploaded credentials was not imported due to an error. Perhaps an existing credential had the same name?") expect(response).to redirect_to(user_credentials_path) end end describe "POST create" do it "creates UserCredentials for the current user" do expect { post :create, params: {:user_credential => valid_attributes} }.to change { users(:bob).user_credentials.count }.by(1) end it "shows errors" do expect { post :create, params: {:user_credential => valid_attributes(:credential_name => "")} }.not_to change { users(:bob).user_credentials.count } expect(assigns(:user_credential)).to have(1).errors_on(:credential_name) expect(response).to render_template("new") end it "will not create UserCredentials for other users" do expect { post :create, params: {:user_credential => valid_attributes(:user_id => users(:jane).id)} }.to raise_error(ActionController::UnpermittedParameters) end end describe "PUT update" do it "updates attributes on UserCredentials for the current user" do post :update, params: {:id => user_credentials(:bob_aws_key).to_param, :user_credential => { :credential_name => "new_name" }} expect(response).to redirect_to(user_credentials_path) expect(user_credentials(:bob_aws_key).reload.credential_name).to eq("new_name") expect { post :update, params: {:id => user_credentials(:jane_aws_key).to_param, :user_credential => { :credential_name => "new_name" }} }.to raise_error(ActiveRecord::RecordNotFound) expect(user_credentials(:jane_aws_key).reload.credential_name).not_to eq("new_name") end it "shows errors" do post :update, params: {:id => user_credentials(:bob_aws_key).to_param, :user_credential => { :credential_name => "" }} expect(assigns(:user_credential)).to have(1).errors_on(:credential_name) expect(response).to render_template("edit") end end describe "DELETE destroy" do it "destroys only UserCredentials owned by the current user" do expect { delete :destroy, params: {:id => user_credentials(:bob_aws_key).to_param} }.to change(UserCredential, :count).by(-1) expect { delete :destroy, params: {:id => user_credentials(:jane_aws_key).to_param} }.to raise_error(ActiveRecord::RecordNotFound) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/controllers/events_controller_spec.rb
spec/controllers/events_controller_spec.rb
require 'rails_helper' describe EventsController do before do expect(Event.where(:user_id => users(:bob).id).count).to be > 0 expect(Event.where(:user_id => users(:jane).id).count).to be > 0 end describe "GET index" do it "only returns Events created by Agents of the current user" do sign_in users(:bob) get :index expect(assigns(:events).all? {|i| expect(i.user).to eq(users(:bob)) }).to be_truthy end it "can filter by Agent" do sign_in users(:bob) get :index, params: {:agent_id => agents(:bob_website_agent)} expect(assigns(:events).length).to eq(agents(:bob_website_agent).events.length) expect(assigns(:events).all? {|i| expect(i.agent).to eq(agents(:bob_website_agent)) }).to be_truthy expect { get :index, params: {:agent_id => agents(:jane_website_agent)} }.to raise_error(ActiveRecord::RecordNotFound) end end describe "GET show" do it "only shows Events for the current user" do sign_in users(:bob) get :show, params: {:id => events(:bob_website_agent_event).to_param} expect(assigns(:event)).to eq(events(:bob_website_agent_event)) expect { get :show, params: {:id => events(:jane_website_agent_event).to_param} }.to raise_error(ActiveRecord::RecordNotFound) end end describe "POST reemit" do before do request.env["HTTP_REFERER"] = "/events" sign_in users(:bob) end it "clones and re-emits events" do expect { post :reemit, params: {:id => events(:bob_website_agent_event).to_param} }.to change { Event.count }.by(1) expect(Event.last.payload).to eq(events(:bob_website_agent_event).payload) expect(Event.last.agent).to eq(events(:bob_website_agent_event).agent) expect(Event.last.created_at.to_i).to be_within(2).of(Time.now.to_i) end it "can only re-emit Events for the current user" do expect { post :reemit, params: {:id => events(:jane_website_agent_event).to_param} }.to raise_error(ActiveRecord::RecordNotFound) end end describe "DELETE destroy" do it "only deletes events for the current user" do sign_in users(:bob) expect { delete :destroy, params: {:id => events(:bob_website_agent_event).to_param} }.to change { Event.count }.by(-1) expect { delete :destroy, params: {:id => events(:jane_website_agent_event).to_param} }.to raise_error(ActiveRecord::RecordNotFound) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/controllers/scenario_imports_controller_spec.rb
spec/controllers/scenario_imports_controller_spec.rb
require 'rails_helper' describe ScenarioImportsController do before do sign_in users(:bob) end describe "GET new" do it "initializes a new ScenarioImport and renders new" do get :new expect(assigns(:scenario_import)).to be_a(ScenarioImport) expect(response).to render_template(:new) end end describe "POST create" do it "initializes a ScenarioImport for current_user, passing in params" do post :create, params: {:scenario_import => { :url => "bad url" }} expect(assigns(:scenario_import).user).to eq(users(:bob)) expect(assigns(:scenario_import).url).to eq("bad url") expect(assigns(:scenario_import)).not_to be_valid expect(response).to render_template(:new) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/controllers/services_controller_spec.rb
spec/controllers/services_controller_spec.rb
require 'rails_helper' describe ServicesController do before do sign_in users(:bob) end describe "GET index" do it "only returns sevices of the current user" do get :index expect(assigns(:services).all? {|i| expect(i.user).to eq(users(:bob)) }).to eq(true) end end describe "POST toggle_availability" do it "should work for service of the user" do post :toggle_availability, params: {:id => services(:generic).to_param} expect(assigns(:service)).to eq(services(:generic)) redirect_to(services_path) end it "should not work for a service of another user" do expect { post :toggle_availability, params: {:id => services(:global).to_param} }.to raise_error(ActiveRecord::RecordNotFound) end end describe "DELETE destroy" do it "destroys only services owned by the current user" do expect { delete :destroy, params: {:id => services(:generic).to_param} }.to change(Service, :count).by(-1) expect { delete :destroy, params: {:id => services(:global).to_param} }.to raise_error(ActiveRecord::RecordNotFound) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/controllers/scenarios_controller_spec.rb
spec/controllers/scenarios_controller_spec.rb
require 'rails_helper' describe ScenariosController do def valid_attributes(options = {}) { :name => "some_name" }.merge(options) end before do sign_in users(:bob) end describe "GET index" do it "only returns Scenarios for the current user" do get :index expect(assigns(:scenarios).all? {|i| expect(i.user).to eq(users(:bob)) }).to be_truthy end end describe "GET show" do it "only shows Scenarios for the current user" do get :show, params: {:id => scenarios(:bob_weather).to_param} expect(assigns(:scenario)).to eq(scenarios(:bob_weather)) expect { get :show, params: {:id => scenarios(:jane_weather).to_param} }.to raise_error(ActiveRecord::RecordNotFound) end it "loads Agents for the requested Scenario" do get :show, params: {:id => scenarios(:bob_weather).to_param} expect(assigns(:agents).pluck(:id).sort).to eq(scenarios(:bob_weather).agents.pluck(:id).sort) end end describe "GET share" do it "only displays Scenario share information for the current user" do get :share, params: {:id => scenarios(:bob_weather).to_param} expect(assigns(:scenario)).to eq(scenarios(:bob_weather)) expect { get :share, params: {:id => scenarios(:jane_weather).to_param} }.to raise_error(ActiveRecord::RecordNotFound) end end describe "GET export" do it "returns a JSON file download from an instantiated AgentsExporter" do get :export, params: {:id => scenarios(:bob_weather).to_param} expect(assigns(:exporter).options[:name]).to eq(scenarios(:bob_weather).name) expect(assigns(:exporter).options[:description]).to eq(scenarios(:bob_weather).description) expect(assigns(:exporter).options[:agents]).to eq(scenarios(:bob_weather).agents) expect(assigns(:exporter).options[:guid]).to eq(scenarios(:bob_weather).guid) expect(assigns(:exporter).options[:tag_fg_color]).to eq(scenarios(:bob_weather).tag_fg_color) expect(assigns(:exporter).options[:tag_bg_color]).to eq(scenarios(:bob_weather).tag_bg_color) expect(assigns(:exporter).options[:source_url]).to be_falsey expect(response.headers['Content-Disposition']).to eq('attachment; filename="bob-s-weather-alert-scenario.json"') expect(response.headers['Content-Type']).to eq('application/json; charset=utf-8') expect(JSON.parse(response.body)["name"]).to eq(scenarios(:bob_weather).name) end it "only exports private Scenarios for the current user" do get :export, params: {:id => scenarios(:bob_weather).to_param} expect(assigns(:scenario)).to eq(scenarios(:bob_weather)) expect { get :export, params: {:id => scenarios(:jane_weather).to_param} }.to raise_error(ActiveRecord::RecordNotFound) end describe "public exports" do before do scenarios(:jane_weather).update_attribute :public, true end it "exports public scenarios for other users when logged in" do get :export, params: {:id => scenarios(:jane_weather).to_param} expect(assigns(:scenario)).to eq(scenarios(:jane_weather)) expect(assigns(:exporter).options[:source_url]).to eq(export_scenario_url(scenarios(:jane_weather))) end it "exports public scenarios for other users when logged out" do sign_out :user get :export, params: {:id => scenarios(:jane_weather).to_param} expect(assigns(:scenario)).to eq(scenarios(:jane_weather)) expect(assigns(:exporter).options[:source_url]).to eq(export_scenario_url(scenarios(:jane_weather))) end end end describe "GET edit" do it "only shows Scenarios for the current user" do get :edit, params: {:id => scenarios(:bob_weather).to_param} expect(assigns(:scenario)).to eq(scenarios(:bob_weather)) expect { get :edit, params: {:id => scenarios(:jane_weather).to_param} }.to raise_error(ActiveRecord::RecordNotFound) end end describe "POST create" do it "creates Scenarios for the current user" do expect { post :create, params: {:scenario => valid_attributes} }.to change { users(:bob).scenarios.count }.by(1) end it "shows errors" do expect { post :create, params: {:scenario => valid_attributes(:name => "")} }.not_to change { users(:bob).scenarios.count } expect(assigns(:scenario)).to have(1).errors_on(:name) expect(response).to render_template("new") end it "will not create Scenarios for other users" do expect { post :create, params: {:scenario => valid_attributes(:user_id => users(:jane).id)} }.to raise_error(ActionController::UnpermittedParameters) end end describe "PUT update" do it "updates attributes on Scenarios for the current user" do post :update, params: {:id => scenarios(:bob_weather).to_param, :scenario => { :name => "new_name", :public => "1" }} expect(response).to redirect_to(scenario_path(scenarios(:bob_weather))) expect(scenarios(:bob_weather).reload.name).to eq("new_name") expect(scenarios(:bob_weather)).to be_public expect { post :update, params: {:id => scenarios(:jane_weather).to_param, :scenario => { :name => "new_name" }} }.to raise_error(ActiveRecord::RecordNotFound) expect(scenarios(:jane_weather).reload.name).not_to eq("new_name") end it "shows errors" do post :update, params: {:id => scenarios(:bob_weather).to_param, :scenario => { :name => "" }} expect(assigns(:scenario)).to have(1).errors_on(:name) expect(response).to render_template("edit") end it 'adds an agent to the scenario' do expect { post :update, params: {:id => scenarios(:bob_weather).to_param, :scenario => { :name => "new_name", :public => "1", agent_ids: scenarios(:bob_weather).agent_ids + [agents(:bob_website_agent).id] }} }.to change { scenarios(:bob_weather).reload.agent_ids.length }.by(1) end end describe 'PUT enable_or_disable_all_agents' do it 'updates disabled on all agents in a scenario for the current user' do @params = {"scenario"=>{"disabled"=>"true"}, "commit"=>"Yes", "id"=> scenarios(:bob_weather).id} put :enable_or_disable_all_agents, params: @params expect(agents(:bob_rain_notifier_agent).disabled).to eq(true) expect(response).to redirect_to(scenario_path(scenarios(:bob_weather))) end end describe "DELETE destroy" do it "destroys only Scenarios owned by the current user" do expect { delete :destroy, params: {:id => scenarios(:bob_weather).to_param} }.to change(Scenario, :count).by(-1) expect { delete :destroy, params: {:id => scenarios(:jane_weather).to_param} }.to raise_error(ActiveRecord::RecordNotFound) end it "passes the mode to the model" do expect { delete :destroy, params: {id: scenarios(:bob_weather).to_param, mode: 'all_agents'} }.to change(Agent, :count).by(-2) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/controllers/concerns/sortable_table_spec.rb
spec/controllers/concerns/sortable_table_spec.rb
require 'rails_helper' describe SortableTable do class SortableTestController attr_accessor :params def self.helper(foo) end include SortableTable public :set_table_sort public :table_sort end describe "#set_table_sort" do let(:controller) { SortableTestController.new } let(:default) { { column2: :asc }} let(:options) { { sorts: %w[column1 column2], default: default } } it "uses a default when no sort is given" do controller.params = {} controller.set_table_sort options expect(controller.table_sort).to eq(default) end it "applies the given sort when one is passed in" do controller.params = { sort: "column1.desc" } controller.set_table_sort options expect(controller.table_sort).to eq({ column1: :desc }) controller.params = { sort: "column1.asc" } controller.set_table_sort options expect(controller.table_sort).to eq({ column1: :asc }) controller.params = { sort: "column2.desc" } controller.set_table_sort options expect(controller.table_sort).to eq({ column2: :desc }) end it "ignores unknown directions" do controller.params = { sort: "column1.foo" } controller.set_table_sort options expect(controller.table_sort).to eq({ column1: :asc }) controller.params = { sort: "column1.foo drop tables" } controller.set_table_sort options expect(controller.table_sort).to eq({ column1: :asc }) end it "ignores unknown columns" do controller.params = { sort: "foo.asc" } controller.set_table_sort options expect(controller.table_sort).to eq(default) controller.params = { sort: ";drop table;.asc" } controller.set_table_sort options expect(controller.table_sort).to eq(default) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/controllers/agents/dry_runs_controller_spec.rb
spec/controllers/agents/dry_runs_controller_spec.rb
require 'rails_helper' describe Agents::DryRunsController do def valid_attributes(options = {}) { type: "Agents::WebsiteAgent", name: "Something", options: agents(:bob_website_agent).options, source_ids: [agents(:bob_weather_agent).id, ""] }.merge(options) end before do sign_in users(:bob) end describe "GET index" do it "does not load any events without specifing sources" do get :index, params: { type: 'Agents::WebsiteAgent', source_ids: [] } expect(assigns(:events)).to eq([]) end context "does not load events when the agent is owned by a different user" do before do @agent = agents(:jane_website_agent) @agent.sources << @agent @agent.save! expect(@agent.events.count).not_to be(0) end it "for new agents" do get :index, params: { type: 'Agents::WebsiteAgent', source_ids: [@agent.id] } expect(assigns(:events)).to eq([]) end it "for existing agents" do expect(@agent.events.count).not_to be(0) expect { get :index, params: { agent_id: @agent } }.to raise_error(NoMethodError) end end context "loads the most recent events" do before do @agent = agents(:bob_website_agent) @agent.sources << @agent @agent.save! end it "load the most recent events when providing source ids" do get :index, params: { type: 'Agents::WebsiteAgent', source_ids: [@agent.id] } expect(assigns(:events)).to eq([@agent.events.first]) end it "loads the most recent events for a saved agent" do get :index, params: { agent_id: @agent } expect(assigns(:events)).to eq([@agent.events.first]) end end end describe "POST create" do before do stub_request(:any, /xkcd/).to_return(body: File.read(Rails.root.join("spec/data_fixtures/xkcd.html")), status: 200) end it "does not actually create any agent, event or log" do expect { post :create, params: { agent: valid_attributes } }.not_to change { [users(:bob).agents.count, users(:bob).events.count, users(:bob).logs.count] } results = assigns(:results) expect(results[:log]).to be_a(String) expect(results[:log]).to include('Extracting html at') expect(results[:events]).to be_a(Array) expect(results[:events].length).to eq(1) expect(results[:events].map(&:class)).to eq([ActiveSupport::HashWithIndifferentAccess]) expect(results[:memory]).to be_a(Hash) end it "does not actually update an agent" do agent = agents(:bob_weather_agent) expect { post :create, params: { agent_id: agent, agent: valid_attributes(name: 'New Name') } }.not_to change { [users(:bob).agents.count, users(:bob).events.count, users(:bob).logs.count, agent.name, agent.updated_at] } end it "accepts an event" do agent = agents(:bob_website_agent) agent.options['url_from_event'] = '{{ url }}' agent.save! url_from_event = "http://xkcd.com/?from_event=1".freeze expect { post :create, params: { agent_id: agent.id, event: { url: url_from_event }.to_json } }.not_to change { [users(:bob).agents.count, users(:bob).events.count, users(:bob).logs.count, agent.name, agent.updated_at] } results = assigns(:results) expect(results[:log]).to match(/^\[\d\d:\d\d:\d\d\] INFO -- : Fetching #{Regexp.quote(url_from_event)}$/) end it "uses the memory of an existing Agent" do valid_params = { name: "somename", options: { code: "Agent.check = function() { this.createEvent({ 'message': this.memory('fu') }); };", } } agent = Agents::JavaScriptAgent.new(valid_params) agent.memory = { fu: "bar" } agent.user = users(:bob) agent.save! post :create, params: { agent_id: agent, agent: valid_params } results = assigns(:results) expect(results[:events][0]).to eql({ "message" => "bar" }) end it 'sets created_at of the dry-runned event' do agent = agents(:bob_formatting_agent) agent.options['instructions'] = { 'created_at' => '{{created_at | date: "%a, %b %d, %y"}}' } agent.save post :create, params: { agent_id: agent, event: { test: 1 }.to_json } results = assigns(:results) expect(results[:events]).to be_a(Array) expect(results[:events].length).to eq(1) expect(results[:events].first['created_at']).to eq(Date.today.strftime('%a, %b %d, %y')) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/controllers/admin/users_controller_spec.rb
spec/controllers/admin/users_controller_spec.rb
require 'rails_helper' describe Admin::UsersController do describe 'POST #create' do context 'with valid user params' do it 'imports the default scenario for the new user' do expect(DefaultScenarioImporter).to receive(:import).with(kind_of(User)) sign_in users(:jane) post :create, params: {:user => {username: 'jdoe', email: 'jdoe@example.com', password: 's3cr3t55', password_confirmation: 's3cr3t55', admin: false }} end end context 'with invalid user params' do it 'does not import the default scenario' do allow(DefaultScenarioImporter).to receive(:import).with(kind_of(User)) { fail "Should not attempt import" } sign_in users(:jane) post :create, params: {:user => {username: 'user'}} end end end describe 'GET #switch_to_user' do it "switches to another user" do sign_in users(:jane) get :switch_to_user, params: {:id => users(:bob).id} expect(response).to redirect_to(agents_path) expect(subject.session[:original_admin_user_id]).to eq(users(:jane).id) end it "does not switch if not admin" do sign_in users(:bob) get :switch_to_user, params: {:id => users(:jane).id} expect(response).to redirect_to(root_path) end end describe 'GET #switch_back' do it "switches to another user and back" do sign_in users(:jane) get :switch_to_user, params: {:id => users(:bob).id} expect(response).to redirect_to(agents_path) expect(subject.session[:original_admin_user_id]).to eq(users(:jane).id) get :switch_back expect(response).to redirect_to(admin_users_path) expect(subject.session[:original_admin_user_id]).to be_nil end it "does not switch_back without having switched" do sign_in users(:bob) get :switch_back expect(response).to redirect_to(root_path) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/controllers/users/registrations_controller_spec.rb
spec/controllers/users/registrations_controller_spec.rb
require 'rails_helper' module Users describe RegistrationsController do describe "POST create" do before do @request.env["devise.mapping"] = Devise.mappings[:user] end context 'with valid params' do it "imports the default scenario for the new user" do expect(DefaultScenarioImporter).to receive(:import).with(kind_of(User)) post :create, params: { :user => {username: 'jdoe', email: 'jdoe@example.com', password: 's3cr3t55', password_confirmation: 's3cr3t55', invitation_code: 'try-huginn'} } end end context 'with invalid params' do it "does not import the default scenario" do allow(DefaultScenarioImporter).to receive(:import).with(kind_of(User)) { fail "Should not attempt import" } setup_controller_for_warden post :create, params: {:user => {}} end it 'does not allow to set the admin flag' do expect { post :create, params: {:user => {admin: 'true'}} }.to raise_error(ActionController::UnpermittedParameters) 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/agent_log_spec.rb
spec/models/agent_log_spec.rb
# -*- coding: utf-8 -*- require 'rails_helper' describe AgentLog do describe "validations" do before do @log = AgentLog.new(:agent => agents(:jane_website_agent), :message => "The agent did something", :level => 3) expect(@log).to be_valid end it "requires an agent" do @log.agent = nil expect(@log).not_to be_valid expect(@log).to have(1).error_on(:agent) end it "requires a message" do @log.message = "" expect(@log).not_to be_valid @log.message = nil expect(@log).not_to be_valid expect(@log).to have(1).error_on(:message) end it "requires a valid log level" do @log.level = nil expect(@log).not_to be_valid expect(@log).to have(1).error_on(:level) @log.level = -1 expect(@log).not_to be_valid expect(@log).to have(1).error_on(:level) @log.level = 5 expect(@log).not_to be_valid expect(@log).to have(1).error_on(:level) @log.level = 4 expect(@log).to be_valid @log.level = 0 expect(@log).to be_valid end end it "replaces invalid byte sequences in a message" do log = AgentLog.new(:agent => agents(:jane_website_agent), level: 3) log.message = "\u{3042}\xffA\x95" expect { log.save! }.not_to raise_error expect(log.message).to eq("\u{3042}<ff>A\<95>") end it "truncates message to a reasonable length" do log = AgentLog.new(:agent => agents(:jane_website_agent), :level => 3) log.message = "a" * 11_000 log.save! expect(log.message.length).to eq(10_000) end describe "#log_for_agent" do it "creates AgentLogs" do log = AgentLog.log_for_agent(agents(:jane_website_agent), "some message", :level => 4, :outbound_event => events(:jane_website_agent_event)) expect(log).not_to be_new_record expect(log.agent).to eq(agents(:jane_website_agent)) expect(log.outbound_event).to eq(events(:jane_website_agent_event)) expect(log.message).to eq("some message") expect(log.level).to eq(4) end it "cleans up old logs when there are more than log_length" do allow(AgentLog).to receive(:log_length) { 4 } AgentLog.log_for_agent(agents(:jane_website_agent), "message 1") AgentLog.log_for_agent(agents(:jane_website_agent), "message 2") AgentLog.log_for_agent(agents(:jane_website_agent), "message 3") AgentLog.log_for_agent(agents(:jane_website_agent), "message 4") expect(agents(:jane_website_agent).logs.order("agent_logs.id desc").first.message).to eq("message 4") expect(agents(:jane_website_agent).logs.order("agent_logs.id desc").last.message).to eq("message 1") AgentLog.log_for_agent(agents(:jane_website_agent), "message 5") expect(agents(:jane_website_agent).logs.order("agent_logs.id desc").first.message).to eq("message 5") expect(agents(:jane_website_agent).logs.order("agent_logs.id desc").last.message).to eq("message 2") AgentLog.log_for_agent(agents(:jane_website_agent), "message 6") expect(agents(:jane_website_agent).logs.order("agent_logs.id desc").first.message).to eq("message 6") expect(agents(:jane_website_agent).logs.order("agent_logs.id desc").last.message).to eq("message 3") end it "updates Agents' last_error_log_at when an error is logged" do AgentLog.log_for_agent(agents(:jane_website_agent), "some message", :level => 3, :outbound_event => events(:jane_website_agent_event)) expect(agents(:jane_website_agent).reload.last_error_log_at).to be_nil AgentLog.log_for_agent(agents(:jane_website_agent), "some message", :level => 4, :outbound_event => events(:jane_website_agent_event)) expect(agents(:jane_website_agent).reload.last_error_log_at.to_i).to be_within(2).of(Time.now.to_i) end it "accepts objects as well as strings" do log = AgentLog.log_for_agent(agents(:jane_website_agent), events(:bob_website_agent_event).payload) expect(log.message).to include('"title"=>"foo"') end end describe "#log_length" do it "defaults to 200" do expect(AgentLog.log_length).to eq(200) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/agent_spec.rb
spec/models/agent_spec.rb
require 'rails_helper' describe Agent do it_behaves_like WorkingHelpers describe '.active/inactive' do let(:agent) { agents(:jane_website_agent) } it 'is active per default' do expect(Agent.active).to include(agent) expect(Agent.inactive).not_to include(agent) end it 'is not active when disabled' do agent.update_attribute(:disabled, true) expect(Agent.active).not_to include(agent) expect(Agent.inactive).to include(agent) end it 'is not active when deactivated' do agent.update_attribute(:deactivated, true) expect(Agent.active).not_to include(agent) expect(Agent.inactive).to include(agent) end it 'is not active when disabled and deactivated' do agent.update_attribute(:disabled, true) agent.update_attribute(:deactivated, true) expect(Agent.active).not_to include(agent) expect(Agent.inactive).to include(agent) end end describe ".bulk_check" do before do @weather_agent_count = Agents::WeatherAgent.where(schedule: "midnight", disabled: false).count end it "should run all Agents with the given schedule" do expect(Agents::WeatherAgent).to receive(:async_check).with(anything).exactly(@weather_agent_count).times Agents::WeatherAgent.bulk_check("midnight") end it "should skip disabled Agents" do agents(:bob_weather_agent).update_attribute :disabled, true expect(Agents::WeatherAgent).to receive(:async_check).with(anything).exactly(@weather_agent_count - 1).times Agents::WeatherAgent.bulk_check("midnight") end it "should skip agents of deactivated accounts" do agents(:bob_weather_agent).user.deactivate! expect(Agents::WeatherAgent).to receive(:async_check).with(anything).exactly(@weather_agent_count - 1).times Agents::WeatherAgent.bulk_check("midnight") end end describe ".run_schedule" do before do expect(Agents::WeatherAgent.count).to be > 0 expect(Agents::WebsiteAgent.count).to be > 0 end it "runs agents with the given schedule" do weather_agent_ids = [agents(:bob_weather_agent), agents(:jane_weather_agent)].map(&:id) expect(Agents::WeatherAgent).to receive(:async_check) { |agent_id| weather_agent_ids.delete(agent_id) }.twice expect(Agents::WebsiteAgent).to receive(:async_check).with(agents(:bob_website_agent).id) Agent.run_schedule("midnight") expect(weather_agent_ids).to be_empty end it "groups agents by type" do expect(Agents::WeatherAgent).to receive(:bulk_check).with("midnight").once expect(Agents::WebsiteAgent).to receive(:bulk_check).with("midnight").once Agent.run_schedule("midnight") end it "ignores unknown types" do Agent.where(id: agents(:bob_weather_agent).id).update_all type: 'UnknownTypeAgent' expect(Agents::WeatherAgent).to receive(:bulk_check).with("midnight").once expect(Agents::WebsiteAgent).to receive(:bulk_check).with("midnight").once Agent.run_schedule("midnight") end it "only runs agents with the given schedule" do expect(Agents::WebsiteAgent).not_to receive(:async_check) Agent.run_schedule("blah") end it "will not run the 'never' schedule" do agents(:bob_weather_agent).update_attribute 'schedule', 'never' expect(Agents::WebsiteAgent).not_to receive(:async_check) Agent.run_schedule("never") end end describe "credential" do let(:agent) { agents(:bob_weather_agent) } it "should return the value of the credential when credential is present" do expect(agent.credential("aws_secret")).to eq(user_credentials(:bob_aws_secret).credential_value) end it "should return nil when credential is not present" do expect(agent.credential("non_existing_credential")).to eq(nil) end it "should memoize the load" do count = 0 allow_any_instance_of(UserCredential).to receive(:credential_value) { count += 1 }.and_return("foo") expect { expect(agent.credential("aws_secret")).to eq("foo") }.to change { count }.by(1) expect { expect(agent.credential("aws_secret")).to eq("foo") }.not_to change { count } agent.reload expect { expect(agent.credential("aws_secret")).to eq("foo") }.to change { count }.by(1) expect { expect(agent.credential("aws_secret")).to eq("foo") }.not_to change { count } end end describe "changes to type" do it "validates types" do source = Agent.new source.type = "Agents::WeatherAgent" expect(source).to have(0).errors_on(:type) source.type = "Agents::WebsiteAgent" expect(source).to have(0).errors_on(:type) source.type = "Agents::Fake" expect(source).to have(1).error_on(:type) end it "disallows changes to type once a record has been saved" do source = agents(:bob_website_agent) source.type = "Agents::WeatherAgent" expect(source).to have(1).error_on(:type) end it "should know about available types" do expect(Agent.types).to include(Agents::WeatherAgent, Agents::WebsiteAgent) end end describe "with an example Agent" do class Agents::SomethingSource < Agent default_schedule "2pm" def check create_event payload: {} end def validate_options errors.add(:base, "bad is bad") if options[:bad] end end class Agents::CannotBeScheduled < Agent cannot_be_scheduled! def receive(events) events.each do |_event| create_event payload: { events_received: 1 } end end end before do allow(Agents::SomethingSource).to receive(:valid_type?).with("Agents::SomethingSource") { true } allow(Agents::CannotBeScheduled).to receive(:valid_type?).with("Agents::CannotBeScheduled") { true } end describe Agents::SomethingSource do let(:new_instance) do agent = Agents::SomethingSource.new(name: "some agent") agent.user = users(:bob) agent end it_behaves_like LiquidInterpolatable it_behaves_like HasGuid end describe ".short_type" do it "returns a short name without 'Agents::'" do expect(Agents::SomethingSource.new.short_type).to eq("SomethingSource") expect(Agents::CannotBeScheduled.new.short_type).to eq("CannotBeScheduled") end end describe ".default_schedule" do it "stores the default on the class" do expect(Agents::SomethingSource.default_schedule).to eq("2pm") expect(Agents::SomethingSource.new.default_schedule).to eq("2pm") end it "sets the default on new instances, allows setting new schedules, and prevents invalid schedules" do @checker = Agents::SomethingSource.new(name: "something") @checker.user = users(:bob) expect(@checker.schedule).to eq("2pm") @checker.save! expect(@checker.reload.schedule).to eq("2pm") @checker.update_attribute :schedule, "5pm" expect(@checker.reload.schedule).to eq("5pm") expect(@checker.reload.schedule).to eq("5pm") @checker.schedule = "this_is_not_real" expect(@checker).to have(1).errors_on(:schedule) end it "should have an empty schedule if it cannot_be_scheduled" do @checker = Agents::CannotBeScheduled.new(name: "something") @checker.user = users(:bob) expect(@checker.schedule).to be_nil expect(@checker).to be_valid @checker.schedule = "5pm" @checker.save! expect(@checker.schedule).to be_nil @checker.schedule = "5pm" expect(@checker).to have(0).errors_on(:schedule) expect(@checker.schedule).to be_nil end end describe "#create_event" do before do @checker = Agents::SomethingSource.new(name: "something") @checker.user = users(:bob) @checker.save! end it "should use the checker's user" do @checker.check expect(Event.last.user).to eq(@checker.user) end it "should log an error if the Agent has been marked with 'cannot_create_events!'" do expect(@checker).to receive(:can_create_events?) { false } expect { @checker.check }.not_to change { Event.count } expect(@checker.logs.first.message).to match(/cannot create events/i) end end describe ".async_check" do before do @checker = Agents::SomethingSource.new(name: "something") @checker.user = users(:bob) @checker.save! end it "records last_check_at and calls check on the given Agent" do expect(@checker).to receive(:check).once { @checker.options[:new] = true } allow(Agent).to receive(:find).with(@checker.id) { @checker } expect(@checker.last_check_at).to be_nil Agents::SomethingSource.async_check(@checker.id) expect(@checker.reload.last_check_at).to be_within(2).of(Time.now) expect(@checker.reload.options[:new]).to be_truthy # Show that we save options end it "should log exceptions" do expect(@checker).to receive(:check).once { raise "foo" } expect(Agent).to receive(:find).with(@checker.id) { @checker } expect { Agents::SomethingSource.async_check(@checker.id) }.to raise_error(RuntimeError) log = @checker.logs.first expect(log.message).to match(/Exception/) expect(log.level).to eq(4) end it "should not run disabled Agents" do expect(Agent).to receive(:find).with(agents(:bob_weather_agent).id) { agents(:bob_weather_agent) } expect(agents(:bob_weather_agent)).not_to receive(:check) agents(:bob_weather_agent).update_attribute :disabled, true Agent.async_check(agents(:bob_weather_agent).id) end end describe ".receive!" do before do stub_request(:any, /pirateweather/).to_return(body: File.read(Rails.root.join("spec/data_fixtures/weather.json")), status: 200) end it "should use available events" do Agent.async_check(agents(:bob_weather_agent).id) expect(Agent).to receive(:async_receive).with(agents(:bob_rain_notifier_agent).id, anything).once Agent.receive! end it "should not propagate to disabled Agents" do Agent.async_check(agents(:bob_weather_agent).id) agents(:bob_rain_notifier_agent).update_attribute :disabled, true expect(Agent).not_to receive(:async_receive).with(agents(:bob_rain_notifier_agent).id, anything) Agent.receive! end it "should not propagate to Agents with unknown types" do Agent.async_check(agents(:jane_weather_agent).id) Agent.async_check(agents(:bob_weather_agent).id) Agent.where(id: agents(:bob_rain_notifier_agent).id).update_all type: 'UnknownTypeAgent' expect(Agent).not_to receive(:async_receive).with(agents(:bob_rain_notifier_agent).id, anything) expect(Agent).to receive(:async_receive).with(agents(:jane_rain_notifier_agent).id, anything).once Agent.receive! end it "should not propagate from Agents with unknown types" do Agent.async_check(agents(:jane_weather_agent).id) Agent.async_check(agents(:bob_weather_agent).id) Agent.where(id: agents(:bob_weather_agent).id).update_all type: 'UnknownTypeAgent' expect(Agent).not_to receive(:async_receive).with(agents(:bob_rain_notifier_agent).id, anything) expect(Agent).to receive(:async_receive).with(agents(:jane_rain_notifier_agent).id, anything).once Agent.receive! end it "should log exceptions" do count = 0 allow_any_instance_of(Agents::TriggerAgent).to receive(:receive) { count += 1 raise "foo" } Agent.async_check(agents(:bob_weather_agent).id) expect { Agent.async_receive(agents(:bob_rain_notifier_agent).id, [agents(:bob_weather_agent).events.last.id]) }.to raise_error(RuntimeError) log = agents(:bob_rain_notifier_agent).logs.first expect(log.message).to match(/Exception/) expect(log.level).to eq(4) expect(count).to eq 1 end it "should track when events have been seen and not received them again" do count = 0 allow_any_instance_of(Agents::TriggerAgent).to receive(:receive) { count += 1 } Agent.async_check(agents(:bob_weather_agent).id) expect { Agent.receive! }.to change { agents(:bob_rain_notifier_agent).reload.last_checked_event_id } expect { Agent.receive! }.not_to change { agents(:bob_rain_notifier_agent).reload.last_checked_event_id } expect(count).to eq 1 end it "should not run consumers that have nothing to do" do anything Agent.receive! end it "should group events" do count = 0 allow_any_instance_of(Agents::TriggerAgent).to receive(:receive) { |_agent, events| count += 1 expect(events.map(&:user).map(&:username).uniq.length).to eq(1) } Agent.async_check(agents(:bob_weather_agent).id) Agent.async_check(agents(:jane_weather_agent).id) Agent.receive! expect(count).to eq 2 end it "should call receive for each event when no_bulk_receive! is used" do count = 0 allow_any_instance_of(Agents::TriggerAgent).to receive(:receive).with(anything) { count += 1 } allow(Agents::TriggerAgent).to receive(:no_bulk_receive?) { true } Agent.async_check(agents(:bob_weather_agent).id) Agent.async_check(agents(:bob_weather_agent).id) Agent.receive! expect(count).to eq 2 end it "should ignore events that were created before a particular Link" do agent2 = Agents::SomethingSource.new(name: "something") agent2.user = users(:bob) agent2.save! agent2.check count = 0 allow_any_instance_of(Agents::TriggerAgent).to receive(:receive) { count += 1 } agents(:bob_weather_agent).check # bob_weather_agent makes an event expect { Agent.receive! # event gets propagated }.to change { agents(:bob_rain_notifier_agent).reload.last_checked_event_id } # This agent creates a few events before we link to it, but after our last check. agent2.check agent2.check # Now we link to it. agents(:bob_rain_notifier_agent).sources << agent2 expect(agent2.links_as_source.first.event_id_at_creation).to eq(agent2.events.reorder("events.id desc").first.id) expect { Agent.receive! # but we don't receive those events because they're too old }.not_to change { agents(:bob_rain_notifier_agent).reload.last_checked_event_id } # Now a new event is created by agent2 agent2.check expect { Agent.receive! # and we receive it }.to change { agents(:bob_rain_notifier_agent).reload.last_checked_event_id } expect(count).to eq 2 end it "should not run agents of deactivated accounts" do agents(:bob_weather_agent).user.deactivate! Agent.async_check(agents(:bob_weather_agent).id) expect(Agent).not_to receive(:async_receive).with(agents(:bob_rain_notifier_agent).id, anything) Agent.receive! end end describe ".async_receive" do it "should not run disabled Agents" do expect(Agent).to receive(:find).with(agents(:bob_rain_notifier_agent).id) { agents(:bob_rain_notifier_agent) } expect(agents(:bob_rain_notifier_agent)).not_to receive(:receive) agents(:bob_rain_notifier_agent).update_attribute :disabled, true Agent.async_receive(agents(:bob_rain_notifier_agent).id, [1, 2, 3]) end end describe "creating a new agent and then calling .receive!" do it "should not backfill events for a newly created agent" do Event.delete_all sender = Agents::SomethingSource.new(name: "Sending Agent") sender.user = users(:bob) sender.save! sender.create_event payload: {} sender.create_event payload: {} expect(sender.events.count).to eq(2) receiver = Agents::CannotBeScheduled.new(name: "Receiving Agent") receiver.user = users(:bob) receiver.sources << sender receiver.save! expect(receiver.events.count).to eq(0) Agent.receive! expect(receiver.events.count).to eq(0) sender.create_event payload: {} Agent.receive! expect(receiver.events.count).to eq(1) end end describe "creating agents with propagate_immediately = true" do it "should schedule subagent events immediately" do Event.delete_all sender = Agents::SomethingSource.new(name: "Sending Agent") sender.user = users(:bob) sender.save! receiver = Agents::CannotBeScheduled.new( name: "Receiving Agent", ) receiver.propagate_immediately = true receiver.user = users(:bob) receiver.sources << sender receiver.save! sender.create_event payload: { "message" => "new payload" } expect(sender.events.count).to eq(1) expect(receiver.events.count).to eq(1) # should be true without calling Agent.receive! end it "should only schedule receiving agents that are set to propagate_immediately" do Event.delete_all sender = Agents::SomethingSource.new(name: "Sending Agent") sender.user = users(:bob) sender.save! im_receiver = Agents::CannotBeScheduled.new( name: "Immediate Receiving Agent", ) im_receiver.propagate_immediately = true im_receiver.user = users(:bob) im_receiver.sources << sender im_receiver.save! slow_receiver = Agents::CannotBeScheduled.new( name: "Slow Receiving Agent", ) slow_receiver.user = users(:bob) slow_receiver.sources << sender slow_receiver.save! sender.create_event payload: { "message" => "new payload" } expect(sender.events.count).to eq(1) expect(im_receiver.events.count).to eq(1) # we should get the quick one # but not the slow one expect(slow_receiver.events.count).to eq(0) Agent.receive! # now we should have one in both expect(im_receiver.events.count).to eq(1) expect(slow_receiver.events.count).to eq(1) end end describe "validations" do it "calls validate_options" do agent = Agents::SomethingSource.new(name: "something") agent.user = users(:bob) agent.options[:bad] = true expect(agent).to have(1).error_on(:base) agent.options[:bad] = false expect(agent).to have(0).errors_on(:base) end it "makes options symbol-indifferent before validating" do agent = Agents::SomethingSource.new(name: "something") agent.user = users(:bob) agent.options["bad"] = true expect(agent).to have(1).error_on(:base) agent.options["bad"] = false expect(agent).to have(0).errors_on(:base) end it "makes memory symbol-indifferent before validating" do agent = Agents::SomethingSource.new(name: "something") agent.user = users(:bob) agent.memory["bad"] = 2 agent.save expect(agent.memory[:bad]).to eq(2) end it "should work when assigned a hash or JSON string" do agent = Agents::SomethingSource.new(name: "something") agent.memory = {} expect(agent.memory).to eq({}) expect(agent.memory["foo"]).to be_nil agent.memory = "" expect(agent.memory["foo"]).to be_nil expect(agent.memory).to eq({}) agent.memory = '{"hi": "there"}' expect(agent.memory).to eq({ "hi" => "there" }) agent.memory = '{invalid}' expect(agent.memory).to eq({ "hi" => "there" }) expect(agent).to have(1).errors_on(:memory) agent.memory = "{}" expect(agent.memory["foo"]).to be_nil expect(agent.memory).to eq({}) expect(agent).to have(0).errors_on(:memory) agent.options = "{}" expect(agent.options["foo"]).to be_nil expect(agent.options).to eq({}) expect(agent).to have(0).errors_on(:options) agent.options = '{"hi": 2}' expect(agent.options["hi"]).to eq(2) expect(agent).to have(0).errors_on(:options) agent.options = '{"hi": wut}' expect(agent.options["hi"]).to eq(2) expect(agent).to have(1).errors_on(:options) expect(agent.errors_on(:options)).to include("was assigned invalid JSON") agent.options = 5 expect(agent.options["hi"]).to eq(2) expect(agent).to have(1).errors_on(:options) expect(agent.errors_on(:options)).to include("cannot be set to an instance of #{2.class}") # Integer (ruby >=2.4) or Fixnum (ruby <2.4) end it "should not allow source agents owned by other people" do agent = Agents::SomethingSource.new(name: "something") agent.user = users(:bob) agent.source_ids = [agents(:bob_weather_agent).id] expect(agent).to have(0).errors_on(:sources) agent.source_ids = [agents(:jane_weather_agent).id] expect(agent).to have(1).errors_on(:sources) agent.user = users(:jane) expect(agent).to have(0).errors_on(:sources) end it "should not allow target agents owned by other people" do agent = Agents::SomethingSource.new(name: "something") agent.user = users(:bob) agent.receiver_ids = [agents(:bob_weather_agent).id] expect(agent).to have(0).errors_on(:receivers) agent.receiver_ids = [agents(:jane_weather_agent).id] expect(agent).to have(1).errors_on(:receivers) agent.user = users(:jane) expect(agent).to have(0).errors_on(:receivers) end it "should not allow controller agents owned by other people" do agent = Agents::SomethingSource.new(name: "something") agent.user = users(:bob) agent.controller_ids = [agents(:bob_weather_agent).id] expect(agent).to have(0).errors_on(:controllers) agent.controller_ids = [agents(:jane_weather_agent).id] expect(agent).to have(1).errors_on(:controllers) agent.user = users(:jane) expect(agent).to have(0).errors_on(:controllers) end it "should not allow control target agents owned by other people" do agent = Agents::CannotBeScheduled.new(name: "something") agent.user = users(:bob) agent.control_target_ids = [agents(:bob_weather_agent).id] expect(agent).to have(0).errors_on(:control_targets) agent.control_target_ids = [agents(:jane_weather_agent).id] expect(agent).to have(1).errors_on(:control_targets) agent.user = users(:jane) expect(agent).to have(0).errors_on(:control_targets) end it "should not allow scenarios owned by other people" do agent = Agents::SomethingSource.new(name: "something") agent.user = users(:bob) agent.scenario_ids = [scenarios(:bob_weather).id] expect(agent).to have(0).errors_on(:scenarios) agent.scenario_ids = [scenarios(:bob_weather).id, scenarios(:jane_weather).id] expect(agent).to have(1).errors_on(:scenarios) agent.scenario_ids = [scenarios(:jane_weather).id] expect(agent).to have(1).errors_on(:scenarios) agent.user = users(:jane) expect(agent).to have(0).errors_on(:scenarios) end it "validates keep_events_for" do agent = Agents::SomethingSource.new(name: "something") agent.user = users(:bob) expect(agent).to be_valid agent.keep_events_for = nil expect(agent).to have(1).errors_on(:keep_events_for) agent.keep_events_for = 1000 expect(agent).to have(1).errors_on(:keep_events_for) agent.keep_events_for = "" expect(agent).to have(1).errors_on(:keep_events_for) agent.keep_events_for = 5.days.to_i expect(agent).to be_valid agent.keep_events_for = 0 expect(agent).to be_valid agent.keep_events_for = 365.days.to_i expect(agent).to be_valid # Rails seems to call to_i on the input. This guards against future changes to that behavior. agent.keep_events_for = "drop table;" expect(agent.keep_events_for).to eq(0) end end describe "cleaning up now-expired events" do before do @time = "2014-01-01 01:00:00 +00:00" travel_to @time do @agent = Agents::SomethingSource.new(name: "something") @agent.keep_events_for = 5.days @agent.user = users(:bob) @agent.save! @event = @agent.create_event payload: { "hello" => "world" } expect(@event.expires_at.to_i).to be_within(2).of(5.days.from_now.to_i) end end describe "when keep_events_for has not changed" do it "does nothing" do expect(@agent).not_to receive(:update_event_expirations!) @agent.options[:foo] = "bar1" @agent.save! @agent.options[:foo] = "bar1" @agent.keep_events_for = 5.days @agent.save! end end describe "when keep_events_for is changed" do it "updates events' expires_at" do travel_to @time do expect { @agent.options[:foo] = "bar1" @agent.keep_events_for = 3.days @agent.save! }.to change { @event.reload.expires_at } expect(@event.expires_at.to_i).to be_within(2).of(3.days.from_now.to_i) end end it "updates events relative to their created_at" do @event.update_attribute :created_at, 2.days.ago expect(@event.reload.created_at.to_i).to be_within(2).of(2.days.ago.to_i) expect { @agent.options[:foo] = "bar2" @agent.keep_events_for = 3.days @agent.save! }.to change { @event.reload.expires_at } expect(@event.expires_at.to_i).to be_within(60 * 61).of(1.days.from_now.to_i) # The larger time is to deal with daylight savings end it "nulls out expires_at when keep_events_for is set to 0" do expect { @agent.options[:foo] = "bar" @agent.keep_events_for = 0 @agent.save! }.to change { @event.reload.expires_at }.to(nil) end end end describe "Agent.build_clone" do before do Event.delete_all @sender = Agents::SomethingSource.new( name: 'Agent (2)', options: { foo: 'bar2' }, schedule: '5pm' ) @sender.user = users(:bob) @sender.save! @sender.create_event payload: {} @sender.create_event payload: {} expect(@sender.events.count).to eq(2) @receiver = Agents::CannotBeScheduled.new( name: 'Agent', options: { foo: 'bar3' }, keep_events_for: 3.days, propagate_immediately: true ) @receiver.user = users(:bob) @receiver.sources << @sender @receiver.memory[:test] = 1 @receiver.save! end it "should create a clone of a given agent for editing" do sender_clone = users(:bob).agents.build_clone(@sender) expect(sender_clone.attributes).to eq(Agent.new.attributes .update(@sender.slice(:user_id, :type, :options, :schedule, :keep_events_for, :propagate_immediately)) .update('name' => 'Agent (2) (2)', 'options' => { 'foo' => 'bar2' })) expect(sender_clone.source_ids).to eq([]) receiver_clone = users(:bob).agents.build_clone(@receiver) expect(receiver_clone.attributes).to eq(Agent.new.attributes .update(@receiver.slice(:user_id, :type, :options, :schedule, :keep_events_for, :propagate_immediately)) .update('name' => 'Agent (3)', 'options' => { 'foo' => 'bar3' })) expect(receiver_clone.source_ids).to eq([@sender.id]) end end end describe ".trigger_web_request" do class Agents::WebRequestReceiver < Agent cannot_be_scheduled! end before do allow(Agents::WebRequestReceiver).to receive(:valid_type?).with("Agents::WebRequestReceiver") { true } end context "when .receive_web_request is defined" do before do @agent = Agents::WebRequestReceiver.new(name: "something") @agent.user = users(:bob) @agent.save! def @agent.receive_web_request(params, method, format) memory['last_request'] = [params, method, format] ['Ok!', 200] end end it "calls the .receive_web_request hook, updates last_web_request_at, and saves" do request = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { some_param: "some_value" }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'text/html' }) @agent.trigger_web_request(request) expect(@agent.reload.memory['last_request']).to eq([{ "some_param" => "some_value" }, "post", "text/html"]) expect(@agent.last_web_request_at.to_i).to be_within(1).of(Time.now.to_i) end end context "when .receive_web_request is defined with just request" do before do @agent = Agents::WebRequestReceiver.new(name: "something") @agent.user = users(:bob) @agent.save! def @agent.receive_web_request(request) memory['last_request'] = [request.params, request.method_symbol.to_s, request.format, { 'HTTP_X_CUSTOM_HEADER' => request.headers['HTTP_X_CUSTOM_HEADER'] }] ['Ok!', 200] end end it "calls the .trigger_web_request with headers, and they get passed to .receive_web_request" do request = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { some_param: "some_value" }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'text/html', 'HTTP_X_CUSTOM_HEADER' => "foo" }) @agent.trigger_web_request(request) expect(@agent.reload.memory['last_request']).to eq([{ "some_param" => "some_value" }, "post", "text/html", { 'HTTP_X_CUSTOM_HEADER' => "foo" }]) expect(@agent.last_web_request_at.to_i).to be_within(1).of(Time.now.to_i) end end context "when .receive_webhook is defined" do before do @agent = Agents::WebRequestReceiver.new(name: "something") @agent.user = users(:bob) @agent.save! def @agent.receive_webhook(params) memory['last_webhook_request'] = params ['Ok!', 200] end end it "outputs a deprecation warning and calls .receive_webhook with the params" do request = ActionDispatch::Request.new({ 'action_dispatch.request.request_parameters' => { some_param: "some_value" }, 'REQUEST_METHOD' => "POST", 'HTTP_ACCEPT' => 'text/html' }) expect(Rails.logger).to receive(:warn).with("DEPRECATED: The .receive_webhook method is deprecated, please switch your Agent to use .receive_web_request.") @agent.trigger_web_request(request) expect(@agent.reload.memory['last_webhook_request']).to eq({ "some_param" => "some_value" }) expect(@agent.last_web_request_at.to_i).to be_within(1).of(Time.now.to_i) end end end describe "scopes" do describe "of_type" do it "should accept classes" do agents = Agent.of_type(Agents::WebsiteAgent) expect(agents).to include(agents(:bob_website_agent)) expect(agents).to include(agents(:jane_website_agent)) expect(agents).not_to include(agents(:bob_weather_agent)) end it "should accept strings" do agents = Agent.of_type("Agents::WebsiteAgent") expect(agents).to include(agents(:bob_website_agent)) expect(agents).to include(agents(:jane_website_agent)) expect(agents).not_to include(agents(:bob_weather_agent)) end it "should accept instances of an Agent" do
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
true
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/scenario_spec.rb
spec/models/scenario_spec.rb
require 'rails_helper' describe Scenario do let(:new_instance) { users(:bob).scenarios.build(:name => "some scenario") } it_behaves_like HasGuid describe "validations" do before do expect(new_instance).to be_valid end it "validates the presence of name" do new_instance.name = '' expect(new_instance).not_to be_valid end it "validates the presence of user" do new_instance.user = nil expect(new_instance).not_to be_valid end it "validates tag_fg_color is hex color" do new_instance.tag_fg_color = '#N07H3X' expect(new_instance).not_to be_valid new_instance.tag_fg_color = '#BADA55' expect(new_instance).to be_valid end it "allows nil tag_fg_color" do new_instance.tag_fg_color = nil expect(new_instance).to be_valid end it "validates tag_bg_color is hex color" do new_instance.tag_bg_color = '#N07H3X' expect(new_instance).not_to be_valid new_instance.tag_bg_color = '#BADA55' expect(new_instance).to be_valid end it "allows nil tag_bg_color" do new_instance.tag_bg_color = nil expect(new_instance).to be_valid end it "only allows Agents owned by user" do new_instance.agent_ids = [agents(:bob_website_agent).id] expect(new_instance).to be_valid new_instance.agent_ids = [agents(:jane_website_agent).id] expect(new_instance).not_to be_valid end end describe "counters" do it "maintains a counter cache on user" do expect { new_instance.save! }.to change { users(:bob).reload.scenario_count }.by(1) expect { new_instance.destroy }.to change { users(:bob).reload.scenario_count }.by(-1) end end context '#unique_agents' do it "equals agents when no agents are shared" do agent_ids = scenarios(:bob_weather).agents.map(&:id).sort unique_agent_ids = scenarios(:bob_weather).send(:unique_agent_ids).sort expect(agent_ids).to eq(unique_agent_ids) end it "includes only agents that are not present in two scnearios" do unique_agent_ids = scenarios(:jane_weather).send(:unique_agent_ids) expect(unique_agent_ids).to eq([agents(:jane_rain_notifier_agent).id]) end it "returns no agents when all are also used in a different scenario" do expect(scenarios(:jane_weather_duplicate).send(:unique_agent_ids)).to eq([]) end end context '#destroy_with_mode' do it "only destroys the scenario when no mode is passed" do expect { scenarios(:jane_weather).destroy_with_mode('') }.not_to change(Agent, :count) end it "only destroys unique agents when 'unique_agents' is passed" do expect { scenarios(:jane_weather).destroy_with_mode('unique_agents') }.to change(Agent, :count).by(-1) end it "destroys all agents when 'all_agents' is passed" do expect { scenarios(:jane_weather).destroy_with_mode('all_agents') }.to change(Agent, :count).by(-2) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/service_spec.rb
spec/models/service_spec.rb
require 'rails_helper' describe Service do before(:each) do @user = users(:bob) end describe "#toggle_availability!" do it "should toggle the global flag" do @service = services(:generic) expect(@service.global).to eq(false) @service.toggle_availability! expect(@service.global).to eq(true) @service.toggle_availability! expect(@service.global).to eq(false) end it "disconnects agents and disables them if the previously global service is made private again" do agent = agents(:bob_twitter_user_agent) jane_agent = agents(:jane_twitter_user_agent) service = agent.service service.toggle_availability! expect(service.agents.length).to eq(2) service.toggle_availability! jane_agent.reload expect(jane_agent.service_id).to be_nil expect(jane_agent.disabled).to be true service.reload expect(service.agents.length).to eq(1) end end it "disables all agents before beeing destroyed" do agent = agents(:bob_twitter_user_agent) service = agent.service service.destroy agent.reload expect(agent.service_id).to be_nil expect(agent.disabled).to be true end describe "preparing for a request" do before(:each) do @service = services(:generic) end it "should not update the token if the token never expires" do @service.expires_at = nil expect(@service.prepare_request).to eq(nil) end it "should not update the token if the token is still valid" do @service.expires_at = Time.now + 1.hour expect(@service.prepare_request).to eq(nil) end it "should call refresh_token! if the token expired" do allow(@service).to receive(:refresh_token!) { @service } @service.expires_at = Time.now - 1.hour expect(@service.prepare_request).to eq(@service) end end describe "updating the access token" do before(:each) do @service = services(:generic) end it "should return the correct endpoint" do @service.provider = 'google' expect(@service.send(:endpoint).to_s).to eq("https://oauth2.googleapis.com/token") end it "should update the token" do stub_request(:post, "https://oauth2.googleapis.com/token?client_id=googleclientid&client_secret=googleclientsecret&grant_type=refresh_token&refresh_token=refreshtokentest"). to_return(:status => 200, :body => '{"expires_in":1209600,"access_token": "NEWTOKEN"}', :headers => {}) @service.provider = 'google' @service.refresh_token = 'refreshtokentest' @service.refresh_token! expect(@service.token).to eq('NEWTOKEN') end end describe "creating services via omniauth" do it "should work with twitter services" do twitter = JSON.parse(File.read(Rails.root.join('spec/data_fixtures/services/twitter.json'))) expect { service = @user.services.initialize_or_update_via_omniauth(twitter) service.save! }.to change { @user.services.count }.by(1) service = @user.services.first expect(service.name).to eq('johnqpublic') expect(service.uid).to eq('123456') expect(service.provider).to eq('twitter') expect(service.token).to eq('a1b2c3d4...') expect(service.secret).to eq('abcdef1234') end it "should work with github services" do signals = JSON.parse(File.read(Rails.root.join('spec/data_fixtures/services/github.json'))) expect { service = @user.services.initialize_or_update_via_omniauth(signals) service.save! }.to change { @user.services.count }.by(1) service = @user.services.first expect(service.provider).to eq('github') expect(service.name).to eq('dsander') expect(service.uid).to eq('12345') expect(service.token).to eq('agithubtoken') end end describe 'omniauth options provider registry for non-conforming omniauth responses' do describe '.register_options_provider' do before do Service.register_options_provider('test-omniauth-provider') do |omniauth| { name: omniauth['special_field'] } end end after do Service.option_providers.delete('test-omniauth-provider') end it 'allows gem developers to add their own options provider to the registry' do actual_options = Service.get_options({ 'provider' => 'test-omniauth-provider', 'special_field' => 'A Great Name' }) expect(actual_options[:name]).to eq('A Great Name') 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/user_credential_spec.rb
spec/models/user_credential_spec.rb
require 'rails_helper' describe UserCredential do describe "validation" do it { should validate_uniqueness_of(:credential_name).scoped_to(:user_id) } it { should validate_presence_of(:credential_name) } it { should validate_presence_of(:credential_value) } it { should validate_presence_of(:user_id) } end describe "cleaning fields" do it "should trim whitespace" do user_credential = user_credentials(:bob_aws_key) user_credential.credential_name = " new name " user_credential.credential_value = " new value " user_credential.save! expect(user_credential.credential_name).to eq("new name") expect(user_credential.credential_value).to eq("new value") end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/event_spec.rb
spec/models/event_spec.rb
require 'rails_helper' describe Event do describe ".with_location" do it "selects events with location" do event = events(:bob_website_agent_event) event.lat = 2 event.lng = 3 event.save! expect(Event.with_location.pluck(:id)).to eq([event.id]) event.lat = nil event.save! expect(Event.with_location).to be_empty end end describe "#location" do it "returns a default hash when an event does not have a location" do event = events(:bob_website_agent_event) expect(event.location).to eq(Location.new( lat: nil, lng: nil, radius: 0.0, speed: nil, course: nil )) end it "returns a hash containing location information" do event = events(:bob_website_agent_event) event.lat = 2 event.lng = 3 event.payload = { radius: 300, speed: 0.5, course: 90.0, } event.save! expect(event.location).to eq(Location.new( lat: 2.0, lng: 3.0, radius: 0.0, speed: 0.5, course: 90.0 )) end end describe "#reemit" do it "creates a new event identical to itself" do events(:bob_website_agent_event).lat = 2 events(:bob_website_agent_event).lng = 3 events(:bob_website_agent_event).created_at = 2.weeks.ago expect { events(:bob_website_agent_event).reemit! }.to change { Event.count }.by(1) expect(Event.last.payload).to eq(events(:bob_website_agent_event).payload) expect(Event.last.agent).to eq(events(:bob_website_agent_event).agent) expect(Event.last.lat).to eq(2) expect(Event.last.lng).to eq(3) expect(Event.last.created_at.to_i).to be_within(2).of(Time.now.to_i) end end describe ".cleanup_expired!" do it "removes any Events whose expired_at date is non-null and in the past, updating Agent counter caches" do half_hour_event = agents(:jane_weather_agent).create_event expires_at: 20.minutes.from_now one_hour_event = agents(:bob_weather_agent).create_event expires_at: 1.hours.from_now two_hour_event = agents(:jane_weather_agent).create_event expires_at: 2.hours.from_now three_hour_event = agents(:jane_weather_agent).create_event expires_at: 3.hours.from_now non_expiring_event = agents(:bob_weather_agent).create_event({}) initial_bob_count = agents(:bob_weather_agent).reload.events_count initial_jane_count = agents(:jane_weather_agent).reload.events_count current_time = Time.now allow(Time).to receive(:now) { current_time } Event.cleanup_expired! expect(Event.find_by_id(half_hour_event.id)).not_to be_nil expect(Event.find_by_id(one_hour_event.id)).not_to be_nil expect(Event.find_by_id(two_hour_event.id)).not_to be_nil expect(Event.find_by_id(three_hour_event.id)).not_to be_nil expect(Event.find_by_id(non_expiring_event.id)).not_to be_nil expect(agents(:bob_weather_agent).reload.events_count).to eq(initial_bob_count) expect(agents(:jane_weather_agent).reload.events_count).to eq(initial_jane_count) current_time = 119.minutes.from_now # move almost 2 hours into the future Event.cleanup_expired! expect(Event.find_by_id(half_hour_event.id)).to be_nil expect(Event.find_by_id(one_hour_event.id)).to be_nil expect(Event.find_by_id(two_hour_event.id)).not_to be_nil expect(Event.find_by_id(three_hour_event.id)).not_to be_nil expect(Event.find_by_id(non_expiring_event.id)).not_to be_nil expect(agents(:bob_weather_agent).reload.events_count).to eq(initial_bob_count - 1) expect(agents(:jane_weather_agent).reload.events_count).to eq(initial_jane_count - 1) current_time = 2.minutes.from_now # move 2 minutes further into the future Event.cleanup_expired! expect(Event.find_by_id(two_hour_event.id)).to be_nil expect(Event.find_by_id(three_hour_event.id)).not_to be_nil expect(Event.find_by_id(non_expiring_event.id)).not_to be_nil expect(agents(:bob_weather_agent).reload.events_count).to eq(initial_bob_count - 1) expect(agents(:jane_weather_agent).reload.events_count).to eq(initial_jane_count - 2) end it "doesn't touch Events with no expired_at" do event = Event.new event.agent = agents(:jane_weather_agent) event.expires_at = nil event.save! current_time = Time.now allow(Time).to receive(:now) { current_time } Event.cleanup_expired! expect(Event.find_by_id(event.id)).not_to be_nil current_time = 2.days.from_now Event.cleanup_expired! expect(Event.find_by_id(event.id)).not_to be_nil end it "always keeps the latest Event regardless of its expires_at value only if the database is MySQL" do Event.delete_all event1 = agents(:jane_weather_agent).create_event expires_at: 1.minute.ago event2 = agents(:bob_weather_agent).create_event expires_at: 1.minute.ago Event.cleanup_expired! case ActiveRecord::Base.connection.adapter_name when /\Amysql/i expect(Event.all.pluck(:id)).to eq([event2.id]) else expect(Event.all.pluck(:id)).to be_empty end end end describe "after destroy" do it "nullifies any dependent AgentLogs" do expect(agent_logs(:log_for_jane_website_agent).outbound_event_id).to be_present expect(agent_logs(:log_for_bob_website_agent).outbound_event_id).to be_present agent_logs(:log_for_bob_website_agent).outbound_event.destroy expect(agent_logs(:log_for_jane_website_agent).reload.outbound_event_id).to be_present expect(agent_logs(:log_for_bob_website_agent).reload.outbound_event_id).to be_nil end end describe "caches" do describe "when an event is created" do it "updates a counter cache on agent" do expect { agents(:jane_weather_agent).events.create!(user: users(:jane)) }.to change { agents(:jane_weather_agent).reload.events_count }.by(1) end it "updates last_event_at on agent" do expect { agents(:jane_weather_agent).events.create!(user: users(:jane)) }.to change { agents(:jane_weather_agent).reload.last_event_at } end end describe "when an event is updated" do it "does not touch the last_event_at on the agent" do event = agents(:jane_weather_agent).events.create!(user: users(:jane)) agents(:jane_weather_agent).update_attribute :last_event_at, 2.days.ago expect { event.update_attribute :payload, { 'hello' => 'world' } }.not_to change { agents(:jane_weather_agent).reload.last_event_at } end end end end describe Event::Drop do def interpolate(string, event) event.agent.interpolate_string(string, event.to_liquid) end before do @event = Event.new @event.agent = agents(:jane_weather_agent) @event.created_at = Time.now @event.payload = { 'title' => 'some title', 'url' => 'http://some.site.example.org/', } @event.lat = 2 @event.lng = 3 @event.save! end it 'should be created via Agent#to_liquid' do expect(@event.to_liquid.class).to be(Event::Drop) end it 'should have attributes of its payload' do t = '{{title}}: {{url}}' expect(interpolate(t, @event)).to eq('some title: http://some.site.example.org/') end it 'should use created_at from the payload if it exists' do created_at = @event.created_at - 86400 # Avoid timezone issue by using %s @event.payload['created_at'] = created_at.strftime("%s") @event.save! t = '{{created_at | date:"%s" }}' expect(interpolate(t, @event)).to eq(created_at.strftime("%s")) end it 'should be iteratable' do # to_liquid returns self t = "{% for pair in to_liquid %}{{pair | join:':' }}\n{% endfor %}" expect(interpolate(t, @event)).to eq("title:some title\nurl:http://some.site.example.org/\n") end it 'should have agent' do t = '{{agent.name}}' expect(interpolate(t, @event)).to eq('SF Weather') end it 'should have created_at' do t = '{{created_at | date:"%FT%T%z" }}' expect(interpolate(t, @event)).to eq(@event.created_at.strftime("%FT%T%z")) end it 'should have _location_' do t = '{{_location_.lat}},{{_location_.lng}}' expect(interpolate(t, @event)).to eq("2.0,3.0") end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/user_spec.rb
spec/models/user_spec.rb
require 'rails_helper' describe User do let(:bob) { users(:bob) } describe "validations" do describe "invitation_code" do context "when configured to use invitation codes" do before do allow(User).to receive(:using_invitation_code?) {true} end it "only accepts valid invitation codes" do User::INVITATION_CODES.each do |v| should allow_value(v).for(:invitation_code) end end it "can reject invalid invitation codes" do %w['foo', 'bar'].each do |v| should_not allow_value(v).for(:invitation_code) end end it "requires no authentication code when requires_no_invitation_code! is called" do u = User.new(username: 'test', email: 'test@test.com', password: '12345678', password_confirmation: '12345678') u.requires_no_invitation_code! expect(u).to be_valid end end context "when configured not to use invitation codes" do before do allow(User).to receive(:using_invitation_code?) {false} end it "skips this validation" do %w['foo', 'bar', nil, ''].each do |v| should allow_value(v).for(:invitation_code) end end end end end context '#deactivate!' do it "deactivates the user and all her agents" do agent = agents(:jane_website_agent) users(:jane).deactivate! agent.reload expect(agent.deactivated).to be_truthy expect(users(:jane).deactivated_at).not_to be_nil end end context '#activate!' do before do users(:bob).deactivate! end it 'activates the user and all his agents' do agent = agents(:bob_website_agent) users(:bob).activate! agent.reload expect(agent.deactivated).to be_falsy expect(users(:bob).deactivated_at).to be_nil end end context '#undefined_agent_types' do it 'returns an empty array when no agents are undefined' do expect(bob.undefined_agent_types).to be_empty end it 'returns the undefined agent types' do agent = agents(:bob_website_agent) agent.update_attribute(:type, 'Agents::UndefinedAgent') expect(bob.undefined_agent_types).to match_array(['Agents::UndefinedAgent']) end end context '#undefined_agents' do it 'returns an empty array when no agents are undefined' do expect(bob.undefined_agents).to be_empty end it 'returns the undefined agent types' do agent = agents(:bob_website_agent) agent.update_attribute(:type, 'Agents::UndefinedAgent') expect(bob.undefined_agents).not_to be_empty expect(bob.undefined_agents.first).to be_a(Agent) end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/spec/models/concerns/oauthable.rb
spec/models/concerns/oauthable.rb
require 'rails_helper' module Agents class OauthableTestAgent < Agent include Oauthable end end shared_examples_for Oauthable do before(:each) do @agent = described_class.new(:name => "somename") @agent.user = users(:jane) end it "should be oauthable" do expect(@agent.oauthable?).to eq(true) end describe "valid_services_for" do it "should return all available services without specifying valid_oauth_providers" do @agent = Agents::OauthableTestAgent.new expect(@agent.valid_services_for(users(:bob)).collect(&:id).sort).to eq([services(:generic), services(:twitter), services(:global)].collect(&:id).sort) end it "should filter the services based on the agent defaults" do expect(@agent.valid_services_for(users(:bob)).to_a).to eq(Service.where(provider: @agent.valid_oauth_providers)) 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/change_detector_agent_spec.rb
spec/models/agents/change_detector_agent_spec.rb
require 'rails_helper' describe Agents::ChangeDetectorAgent do def create_event(output=nil) event = Event.new event.agent = agents(:jane_weather_agent) event.payload = { :command => 'some-command', :output => output } event.save! event end before do @valid_params = { :property => "{{output}}", :expected_update_period_in_days => "1", } @checker = Agents::ChangeDetectorAgent.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 property" do @checker.options[:property] = 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 "#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 changed" 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 no change" do @event.payload[:output] = "2014-07-01" @checker.receive([@event]) expect { @checker.receive([@event]) }.to change(Event, :count).by(0) end end describe "#receive using last_property to track lowest value" do before :each do @event = create_event("100") end before do # Evaluate the output as number and detect a new lowest value @checker.options['property'] = '{% assign drop = last_property | minus: output %}{% if last_property == blank or drop > 0 %}{{ output | default: last_property }}{% else %}{{ last_property }}{% endif %}' end it "creates events when the value drops" do @checker.receive([@event]) event = create_event("90") expect { @checker.receive([event]) }.to change(Event, :count).by(1) expect(@checker.memory['last_property']).to eq "90" end it "does not create event when the value does not change" do @checker.receive([@event]) event = create_event("100") expect { @checker.receive([event]) }.not_to change(Event, :count) expect(@checker.memory['last_property']).to eq "100" end it "does not create event when the value rises" do @checker.receive([@event]) event = create_event("110") expect { @checker.receive([event]) }.not_to change(Event, :count) expect(@checker.memory['last_property']).to eq "100" end it "does not create event when the value is blank" do @checker.receive([@event]) event = create_event("") expect { @checker.receive([event]) }.not_to change(Event, :count) expect(@checker.memory['last_property']).to eq "100" end it "creates events when memory is empty" do expect { @checker.receive([@event]) }.to change(Event, :count).by(1) expect(@checker.memory['last_property']).to eq "100" end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false