CombinedText
stringlengths
4
3.42M
module DTK; class ComponentMetaFile module UpdateModelMixin def update_model() self.class.add_components_from_r8meta(@container_idh,@config_agent_type,@impl_idh,@input_hash) end end module UpdateModelClassMixin #TODO: make private after removing all non class references to it def add_components_from_r8meta(container_idh,config_agent_type,impl_idh,meta_hash) impl_id = impl_idh.get_id() remote_link_defs = Hash.new cmps_hash = meta_hash.inject({}) do |h, (r8_hash_cmp_ref,cmp_info)| info = Hash.new cmp_info.each do |k,v| case k when "external_link_defs" v.each{|ld|(ld["possible_links"]||[]).each{|pl|pl.values.first["type"] = "external"}} #TODO: temp hack to put in type = "external" parsed_link_def = LinkDef.parse_serialized_form_local(v,config_agent_type,remote_link_defs) (info["link_def"] ||= Hash.new).merge!(parsed_link_def) when "link_defs" parsed_link_def = LinkDef.parse_serialized_form_local(v,config_agent_type,remote_link_defs) (info["link_def"] ||= Hash.new).merge!(parsed_link_def) else info[k] = v end end info.merge!("implementation_id" => impl_id) cmp_ref = component_ref(config_agent_type,r8_hash_cmp_ref) h.merge(cmp_ref => info) end #process the link defs for remote components process_remote_link_defs!(cmps_hash,remote_link_defs,container_idh) #data_source_update_hash form used so can annotate subcomponents with "is complete" so will delete items that are removed module_branch_idh = impl_idh.create_object().get_module_branch().id_handle() db_update_hash = db_update_form(cmps_hash,module_branch_idh) Model.input_hash_content_into_model(container_idh,db_update_hash) sp_hash = { :cols => [:id,:display_name], :filter => [:and,[:oneof,:ref,cmps_hash.keys],[:eq,:library_library_id,container_idh.get_id()]] } component_idhs = Model.get_objs(container_idh.create_childMH(:component),sp_hash).map{|r|r.id_handle()} component_idhs end private def db_update_form(cmps_input_hash,module_branch_idh) mark_as_complete_constraint = {:module_branch_id=>module_branch_idh.get_id()} #so only delete extra components that belong to same module cmp_db_update_hash = cmps_input_hash.inject(DBUpdateHash.new) do |h,(ref,hash_assigns)| h.merge(ref => db_update_form_aux(:component,hash_assigns)) end.mark_as_complete(mark_as_complete_constraint) {"component" => cmp_db_update_hash} end def db_update_form_aux(model_name,hash_assigns) ret = DBUpdateHash.new children_model_names = DB_REL_DEF[model_name][:one_to_many]||[] hash_assigns.each do |key,child_hash| if children_model_names.include?(key.to_sym) child_model_name = key.to_sym ret[key] = child_hash.inject(DBUpdateHash.new) do |h,(ref,child_hash_assigns)| h.merge(ref => db_update_form_aux(child_model_name,child_hash_assigns)) end ret[key].mark_as_complete() else ret[key] = child_hash end end ret end def component_ref_from_cmp_type(config_agent_type,component_type) "#{config_agent_type}-#{component_type}" end def component_ref(config_agent_type,r8_hash_cmp_ref) #TODO: may be better to have these prefixes already in r8 meta file "#{config_agent_type}-#{r8_hash_cmp_ref}" end #updates both cmps_hash and remote_link_defs def process_remote_link_defs!(cmps_hash,remote_link_defs,library_idh) return if remote_link_defs.empty? #process all remote_link_defs in this module remote_link_defs.each do |remote_cmp_type,remote_link_def| config_agent_type = remote_link_def.values.first[:config_agent_type] remote_cmp_ref = component_ref_from_cmp_type(config_agent_type,remote_cmp_type) if cmp_pointer = cmps_hash[remote_cmp_ref] (cmp_pointer["link_def"] ||= Hash.new).merge!(remote_link_def) remote_link_defs.delete(remote_cmp_type) end end #process remaining remote_link_defs to see if in stored modules return if remote_link_defs.empty? sp_hash = { :cols => [:id,:ref,:component_type], :filter => [:oneof,:component_type,remote_link_defs.keys] } stored_remote_cmps = library_idh.create_object().get_children_objs(:component,sp_hash,:keep_ref_cols=>true) ndx_stored_remote_cmps = stored_remote_cmps.inject({}){|h,cmp|h.merge(cmp[:component_type] => cmp)} remote_link_defs.each do |remote_cmp_type,remote_link_def| if remote_cmp = ndx_stored_remote_cmps[remote_cmp_type] remote_cmp_ref = remote_cmp[:ref] cmp_pointer = cmps_hash[remote_cmp_ref] ||= {"link_def" => Hash.new} cmp_pointer["link_def"].merge!(remote_link_def) remote_link_defs.delete(remote_cmp_type) end end #if any remote_link_defs left they are dangling refs remote_link_defs.keys.each do |remote_cmp_type| Log.error("link def references a remote component (#{remote_cmp_type}) that does not exist") end end end end; end fixed bug where increemntal container update did not delete empty children module DTK; class ComponentMetaFile module UpdateModelMixin def update_model() self.class.add_components_from_r8meta(@container_idh,@config_agent_type,@impl_idh,@input_hash) end end module UpdateModelClassMixin #TODO: make private after removing all non class references to it def add_components_from_r8meta(container_idh,config_agent_type,impl_idh,meta_hash) impl_id = impl_idh.get_id() remote_link_defs = Hash.new cmps_hash = meta_hash.inject({}) do |h, (r8_hash_cmp_ref,cmp_info)| info = Hash.new cmp_info.each do |k,v| case k when "external_link_defs" v.each{|ld|(ld["possible_links"]||[]).each{|pl|pl.values.first["type"] = "external"}} #TODO: temp hack to put in type = "external" parsed_link_def = LinkDef.parse_serialized_form_local(v,config_agent_type,remote_link_defs) (info["link_def"] ||= Hash.new).merge!(parsed_link_def) when "link_defs" parsed_link_def = LinkDef.parse_serialized_form_local(v,config_agent_type,remote_link_defs) (info["link_def"] ||= Hash.new).merge!(parsed_link_def) else info[k] = v end end info.merge!("implementation_id" => impl_id) cmp_ref = component_ref(config_agent_type,r8_hash_cmp_ref) h.merge(cmp_ref => info) end #process the link defs for remote components process_remote_link_defs!(cmps_hash,remote_link_defs,container_idh) #data_source_update_hash form used so can annotate subcomponents with "is complete" so will delete items that are removed module_branch_idh = impl_idh.create_object().get_module_branch().id_handle() db_update_hash = db_update_form(cmps_hash,module_branch_idh) Model.input_hash_content_into_model(container_idh,db_update_hash) sp_hash = { :cols => [:id,:display_name], :filter => [:and,[:oneof,:ref,cmps_hash.keys],[:eq,:library_library_id,container_idh.get_id()]] } component_idhs = Model.get_objs(container_idh.create_childMH(:component),sp_hash).map{|r|r.id_handle()} component_idhs end private def db_update_form(cmps_input_hash,module_branch_idh) mark_as_complete_constraint = {:module_branch_id=>module_branch_idh.get_id()} #so only delete extra components that belong to same module cmp_db_update_hash = cmps_input_hash.inject(DBUpdateHash.new) do |h,(ref,hash_assigns)| h.merge(ref => db_update_form_aux(:component,hash_assigns)) end.mark_as_complete(mark_as_complete_constraint) {"component" => cmp_db_update_hash} end def db_update_form_aux(model_name,hash_assigns) ret = DBUpdateHash.new children_model_names = DB_REL_DEF[model_name][:one_to_many]||[] hash_assigns.each do |key,child_hash| if children_model_names.include?(key.to_sym) child_model_name = key.to_sym ret[key] = child_hash.inject(DBUpdateHash.new) do |h,(ref,child_hash_assigns)| h.merge(ref => db_update_form_aux(child_model_name,child_hash_assigns)) end ret[key].mark_as_complete() else ret[key] = child_hash end end #mark as complete any child taht does not appear in hash_assigns (children_model_names.map{|r|r.to_s} - hash_assigns.keys).each do |key| ret[key] = DBUpdateHash.new().mark_as_complete() end ret end def component_ref_from_cmp_type(config_agent_type,component_type) "#{config_agent_type}-#{component_type}" end def component_ref(config_agent_type,r8_hash_cmp_ref) #TODO: may be better to have these prefixes already in r8 meta file "#{config_agent_type}-#{r8_hash_cmp_ref}" end #updates both cmps_hash and remote_link_defs def process_remote_link_defs!(cmps_hash,remote_link_defs,library_idh) return if remote_link_defs.empty? #process all remote_link_defs in this module remote_link_defs.each do |remote_cmp_type,remote_link_def| config_agent_type = remote_link_def.values.first[:config_agent_type] remote_cmp_ref = component_ref_from_cmp_type(config_agent_type,remote_cmp_type) if cmp_pointer = cmps_hash[remote_cmp_ref] (cmp_pointer["link_def"] ||= Hash.new).merge!(remote_link_def) remote_link_defs.delete(remote_cmp_type) end end #process remaining remote_link_defs to see if in stored modules return if remote_link_defs.empty? sp_hash = { :cols => [:id,:ref,:component_type], :filter => [:oneof,:component_type,remote_link_defs.keys] } stored_remote_cmps = library_idh.create_object().get_children_objs(:component,sp_hash,:keep_ref_cols=>true) ndx_stored_remote_cmps = stored_remote_cmps.inject({}){|h,cmp|h.merge(cmp[:component_type] => cmp)} remote_link_defs.each do |remote_cmp_type,remote_link_def| if remote_cmp = ndx_stored_remote_cmps[remote_cmp_type] remote_cmp_ref = remote_cmp[:ref] cmp_pointer = cmps_hash[remote_cmp_ref] ||= {"link_def" => Hash.new} cmp_pointer["link_def"].merge!(remote_link_def) remote_link_defs.delete(remote_cmp_type) end end #if any remote_link_defs left they are dangling refs remote_link_defs.keys.each do |remote_cmp_type| Log.error("link def references a remote component (#{remote_cmp_type}) that does not exist") end end end end; end
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'evt-log' s.version = '2.1.0.0' s.summary = 'Logging to STD IO with levels, tagging, and coloring' s.description = ' ' s.authors = ['The Eventide Project'] s.email = 'opensource@eventide-project.org' s.homepage = 'https://github.com/eventide-project/log' s.licenses = ['MIT'] s.require_paths = ['lib'] s.files = Dir.glob('{lib}/**/*') s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 2.3.3' s.add_runtime_dependency 'evt-initializer' s.add_runtime_dependency 'evt-dependency' s.add_runtime_dependency 'evt-telemetry' s.add_runtime_dependency 'evt-clock' s.add_runtime_dependency 'terminal_colors' s.add_development_dependency 'test_bench' end Package version is increased from 2.1.0.0 to 2.1.1.0 # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'evt-log' s.version = '2.1.1.0' s.summary = 'Logging to STD IO with levels, tagging, and coloring' s.description = ' ' s.authors = ['The Eventide Project'] s.email = 'opensource@eventide-project.org' s.homepage = 'https://github.com/eventide-project/log' s.licenses = ['MIT'] s.require_paths = ['lib'] s.files = Dir.glob('{lib}/**/*') s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 2.3.3' s.add_runtime_dependency 'evt-initializer' s.add_runtime_dependency 'evt-dependency' s.add_runtime_dependency 'evt-telemetry' s.add_runtime_dependency 'evt-clock' s.add_runtime_dependency 'terminal_colors' s.add_development_dependency 'test_bench' end
require File.dirname(__FILE__) + '/../spec_helper' require 'database_cleaner/active_record/transaction' require 'database_cleaner/data_mapper/transaction' require 'database_cleaner/mongo_mapper/truncation' require 'database_cleaner/mongoid/truncation' require 'database_cleaner/couch_potato/truncation' require 'database_cleaner/neo4j/transaction' module DatabaseCleaner describe Base do describe "autodetect" do #Cache all ORMs, we'll need them later but not now. before(:all) do Temp_AR = ::ActiveRecord if defined?(::ActiveRecord) and not defined?(Temp_AR) Temp_DM = ::DataMapper if defined?(::DataMapper) and not defined?(Temp_DM) Temp_MM = ::MongoMapper if defined?(::MongoMapper) and not defined?(Temp_MM) Temp_MO = ::Mongoid if defined?(::Mongoid) and not defined?(Temp_MO) Temp_CP = ::CouchPotato if defined?(::CouchPotato) and not defined?(Temp_CP) Temp_SQ = ::Sequel if defined?(::Sequel) and not defined?(Temp_SQ) Temp_MP = ::Moped if defined?(::Moped) and not defined?(Temp_MP) Temp_RS = ::Redis if defined?(::Redis) and not defined?(Temp_RS) Temp_OH = ::Ohm if defined?(::Ohm) and not defined?(Temp_OH) Temp_NJ = ::Neo4j if defined?(::Neo4j) and not defined?(Temp_NJ) end #Remove all ORM mocks and restore from cache after(:all) do Object.send(:remove_const, 'ActiveRecord') if defined?(::ActiveRecord) Object.send(:remove_const, 'DataMapper') if defined?(::DataMapper) Object.send(:remove_const, 'MongoMapper') if defined?(::MongoMapper) Object.send(:remove_const, 'Mongoid') if defined?(::Mongoid) Object.send(:remove_const, 'CouchPotato') if defined?(::CouchPotato) Object.send(:remove_const, 'Sequel') if defined?(::Sequel) Object.send(:remove_const, 'Moped') if defined?(::Moped) Object.send(:remove_const, 'Ohm') if defined?(::Ohm) Object.send(:remove_const, 'Redis') if defined?(::Redis) Object.send(:remove_const, 'Neo4j') if defined?(::Neo4j) # Restore ORMs ::ActiveRecord = Temp_AR if defined? Temp_AR ::DataMapper = Temp_DM if defined? Temp_DM ::MongoMapper = Temp_MM if defined? Temp_MM ::Mongoid = Temp_MO if defined? Temp_MO ::CouchPotato = Temp_CP if defined? Temp_CP ::Sequel = Temp_SQ if defined? Temp_SQ ::Moped = Temp_MP if defined? Temp_MP ::Ohm = Temp_OH if defined? Temp_OH ::Redis = Temp_RS if defined? Temp_RS ::Neo4j = Temp_NJ if defined? Temp_NJ end #reset the orm mocks before(:each) do Object.send(:remove_const, 'ActiveRecord') if defined?(::ActiveRecord) Object.send(:remove_const, 'DataMapper') if defined?(::DataMapper) Object.send(:remove_const, 'MongoMapper') if defined?(::MongoMapper) Object.send(:remove_const, 'Mongoid') if defined?(::Mongoid) Object.send(:remove_const, 'CouchPotato') if defined?(::CouchPotato) Object.send(:remove_const, 'Sequel') if defined?(::Sequel) Object.send(:remove_const, 'Moped') if defined?(::Moped) Object.send(:remove_const, 'Ohm') if defined?(::Ohm) Object.send(:remove_const, 'Redis') if defined?(::Redis) Object.send(:remove_const, 'Neo4j') if defined?(::Neo4j) end let(:cleaner) { DatabaseCleaner::Base.new :autodetect } it "should raise an error when no ORM is detected" do running { cleaner }.should raise_error(DatabaseCleaner::NoORMDetected) end it "should detect ActiveRecord first" do Object.const_set('ActiveRecord','Actively mocking records.') Object.const_set('DataMapper', 'Mapping data mocks') Object.const_set('MongoMapper', 'Mapping mock mongos') Object.const_set('Mongoid', 'Mongoid mock') Object.const_set('CouchPotato', 'Couching mock potatos') Object.const_set('Sequel', 'Sequel mock') Object.const_set('Moped', 'Moped mock') Object.const_set('Ohm', 'Ohm mock') Object.const_set('Redis', 'Redis mock') Object.const_set('Neo4j', 'Neo4j mock') cleaner.orm.should eq :active_record cleaner.should be_auto_detected end it "should detect DataMapper second" do Object.const_set('DataMapper', 'Mapping data mocks') Object.const_set('MongoMapper', 'Mapping mock mongos') Object.const_set('Mongoid', 'Mongoid mock') Object.const_set('CouchPotato', 'Couching mock potatos') Object.const_set('Sequel', 'Sequel mock') Object.const_set('Moped', 'Moped mock') Object.const_set('Ohm', 'Ohm mock') Object.const_set('Redis', 'Redis mock') Object.const_set('Neo4j', 'Neo4j mock') cleaner.orm.should eq :data_mapper cleaner.should be_auto_detected end it "should detect MongoMapper third" do Object.const_set('MongoMapper', 'Mapping mock mongos') Object.const_set('Mongoid', 'Mongoid mock') Object.const_set('CouchPotato', 'Couching mock potatos') Object.const_set('Sequel', 'Sequel mock') Object.const_set('Moped', 'Moped mock') Object.const_set('Ohm', 'Ohm mock') Object.const_set('Redis', 'Redis mock') Object.const_set('Neo4j', 'Neo4j mock') cleaner.orm.should eq :mongo_mapper cleaner.should be_auto_detected end it "should detect Mongoid fourth" do Object.const_set('Mongoid', 'Mongoid mock') Object.const_set('CouchPotato', 'Couching mock potatos') Object.const_set('Sequel', 'Sequel mock') Object.const_set('Moped', 'Moped mock') Object.const_set('Ohm', 'Ohm mock') Object.const_set('Redis', 'Redis mock') Object.const_set('Neo4j', 'Neo4j mock') cleaner.orm.should eq :mongoid cleaner.should be_auto_detected end it "should detect CouchPotato fifth" do Object.const_set('CouchPotato', 'Couching mock potatos') Object.const_set('Sequel', 'Sequel mock') Object.const_set('Moped', 'Moped mock') Object.const_set('Ohm', 'Ohm mock') Object.const_set('Redis', 'Redis mock') Object.const_set('Neo4j', 'Neo4j mock') cleaner.orm.should eq :couch_potato cleaner.should be_auto_detected end it "should detect Sequel sixth" do Object.const_set('Sequel', 'Sequel mock') Object.const_set('Moped', 'Moped mock') Object.const_set('Ohm', 'Ohm mock') Object.const_set('Redis', 'Redis mock') Object.const_set('Neo4j', 'Neo4j mock') cleaner.orm.should eq :sequel cleaner.should be_auto_detected end it 'detects Moped seventh' do Object.const_set('Moped', 'Moped mock') cleaner.orm.should eq :moped cleaner.should be_auto_detected end it 'detects Ohm eighth' do Object.const_set('Ohm', 'Ohm mock') Object.const_set('Redis', 'Redis mock') Object.const_set('Neo4j', 'Neo4j mock') cleaner.orm.should eq :ohm cleaner.should be_auto_detected end it 'detects Redis ninth' do Object.const_set('Redis', 'Redis mock') Object.const_set('Neo4j', 'Neo4j mock') cleaner.orm.should eq :redis cleaner.should be_auto_detected end it 'detects Neo4j tenth' do Object.const_set('Neo4j', 'Neo4j mock') cleaner.orm.should eq :neo4j cleaner.should be_auto_detected end end describe "orm_module" do it "should ask ::DatabaseCleaner what the module is for its orm" do orm = double("orm") mockule = double("module") cleaner = ::DatabaseCleaner::Base.new cleaner.should_receive(:orm).and_return(orm) ::DatabaseCleaner.should_receive(:orm_module).with(orm).and_return(mockule) cleaner.send(:orm_module).should eq mockule end end describe "comparison" do it "should be equal if orm, connection and strategy are the same" do strategy = mock("strategy") strategy.stub!(:to_ary => [strategy]) one = DatabaseCleaner::Base.new(:active_record,:connection => :default) one.strategy = strategy two = DatabaseCleaner::Base.new(:active_record,:connection => :default) two.strategy = strategy one.should eq two two.should eq one end it "should not be equal if orm are not the same" do strategy = mock("strategy") strategy.stub!(:to_ary => [strategy]) one = DatabaseCleaner::Base.new(:mongo_id,:connection => :default) one.strategy = strategy two = DatabaseCleaner::Base.new(:active_record,:connection => :default) two.strategy = strategy one.should_not eq two two.should_not eq one end it "should not be equal if connection are not the same" do one = DatabaseCleaner::Base.new(:active_record,:connection => :default) one.strategy = :truncation two = DatabaseCleaner::Base.new(:active_record,:connection => :other) two.strategy = :truncation one.should_not eq two two.should_not eq one end end describe "initialization" do context "db specified" do subject { ::DatabaseCleaner::Base.new(:active_record,:connection => :my_db) } it "should store db from :connection in params hash" do subject.db.should eq :my_db end end describe "orm" do it "should store orm" do cleaner = ::DatabaseCleaner::Base.new :a_orm cleaner.orm.should eq :a_orm end it "converts string to symbols" do cleaner = ::DatabaseCleaner::Base.new "mongoid" cleaner.orm.should eq :mongoid end it "is autodetected if orm is not provided" do cleaner = ::DatabaseCleaner::Base.new cleaner.should be_auto_detected end it "is autodetected if you specify :autodetect" do cleaner = ::DatabaseCleaner::Base.new "autodetect" cleaner.should be_auto_detected end it "should default to autodetect upon initalisation" do subject.should be_auto_detected end end end describe "db" do it "should default to :default" do subject.db.should eq :default end it "should return any stored db value" do subject.stub(:strategy_db=) subject.db = :test_db subject.db.should eq :test_db end it "should pass db to any specified strategy" do subject.should_receive(:strategy_db=).with(:a_new_db) subject.db = :a_new_db end end describe "strategy_db=" do let(:strategy) { mock("strategy").tap{|strategy| strategy.stub!(:to_ary => [strategy]) } } before(:each) do subject.strategy = strategy end it "should check that strategy supports db specification" do strategy.should_receive(:respond_to?).with(:db=).and_return(true) strategy.stub(:db=) subject.strategy_db = :a_db end context "when strategy supports db specification" do before(:each) { strategy.stub(:respond_to?).with(:db=).and_return true } it "should pass db to the strategy" do strategy.should_receive(:db=).with(:a_db) subject.strategy_db = :a_db end end context "when strategy doesn't supports db specification" do before(:each) { strategy.stub(:respond_to?).with(:db=).and_return false } it "should check to see if db is :default" do db = double("default") db.should_receive(:==).with(:default).and_return(true) subject.strategy_db = db end it "should raise an argument error when db isn't default" do db = double("a db") expect{ subject.strategy_db = db }.to raise_error ArgumentError end end end describe "clean_with" do let (:strategy) { double("strategy",:clean => true) } before(:each) { subject.stub(:create_strategy).with(anything).and_return(strategy) } it "should pass all arguments to create_strategy" do subject.should_receive(:create_strategy).with(:lorum, :dollar, :amet, :ipsum => "random").and_return(strategy) subject.clean_with :lorum, :dollar, :amet, { :ipsum => "random" } end it "should invoke clean on the created strategy" do strategy.should_receive(:clean) subject.clean_with :strategy end it "should return the strategy" do subject.clean_with( :strategy ).should eq strategy end end describe "clean_with!" do let (:strategy) { double("strategy",:clean => true) } before(:each) { subject.stub(:create_strategy).with(anything).and_return(strategy) } it "should pass all arguments to create_strategy" do subject.should_receive(:create_strategy).with(:lorum, :dollar, :amet, :ipsum => "random").and_return(strategy) subject.clean_with! :lorum, :dollar, :amet, { :ipsum => "random" } end it "should invoke clean on the created strategy" do strategy.should_receive(:clean) subject.clean_with! :strategy end it "should return the strategy" do subject.clean_with!( :strategy ).should eq strategy end end describe "create_strategy" do let(:strategy_class) { double("strategy_class",:new => double("instance")) } before :each do subject.stub(:orm_strategy).and_return(strategy_class) end it "should pass the first argument to orm_strategy" do subject.should_receive(:orm_strategy).with(:strategy).and_return(Object) subject.create_strategy :strategy end it "should pass the remainding argument to orm_strategy.new" do strategy_class.should_receive(:new).with(:params => {:lorum => "ipsum"}) subject.create_strategy :strategy, {:params => {:lorum => "ipsum"}} end it "should return the resulting strategy" do subject.create_strategy( :strategy ).should eq strategy_class.new end end describe "strategy=" do let(:mock_strategy) { mock("strategy").tap{|strategy| strategy.stub!(:to_ary => [strategy]) } } it "should proxy symbolised strategies to create_strategy" do subject.should_receive(:create_strategy).with(:symbol) subject.strategy = :symbol end it "should proxy params with symbolised strategies" do subject.should_receive(:create_strategy).with(:symbol,:param => "one") subject.strategy= :symbol, {:param => "one"} end it "should accept strategy objects" do expect{ subject.strategy = mock_strategy }.to_not raise_error end it "should raise argument error when params given with strategy Object" do expect{ subject.strategy = double("object"), {:param => "one"} }.to raise_error ArgumentError end it "should attempt to set strategy db" do subject.stub(:db).and_return(:my_db) subject.should_receive(:set_strategy_db).with(mock_strategy, :my_db) subject.strategy = mock_strategy end it "should return the stored strategy" do result = subject.strategy = mock_strategy result.should eq mock_strategy end end describe "strategy" do subject { ::DatabaseCleaner::Base.new :a_orm } it "returns a null strategy when strategy is not set and undetectable" do subject.strategy.should eq DatabaseCleaner::NullStrategy end it "returns the set strategy" do strategum = mock("strategy").tap{|strategy| strategy.stub!(:to_ary => [strategy]) } subject.strategy = strategum subject.strategy.should eq strategum end end describe "orm=" do it "should stored the desired orm" do subject.orm.should_not eq :desired_orm subject.orm = :desired_orm subject.orm.should eq :desired_orm end end describe "orm" do let(:mock_orm) { double("orm") } it "should return orm if orm set" do subject.instance_variable_set "@orm", mock_orm subject.orm.should eq mock_orm end context "orm isn't set" do before(:each) { subject.instance_variable_set "@orm", nil } it "should run autodetect if orm isn't set" do subject.should_receive(:autodetect) subject.orm end it "should return the result of autodetect if orm isn't set" do subject.stub(:autodetect).and_return(mock_orm) subject.orm.should eq mock_orm end end end describe "proxy methods" do let (:strategy) { double("strategy") } before(:each) do subject.stub(:strategy).and_return(strategy) end describe "start" do it "should proxy start to the strategy" do strategy.should_receive(:start) subject.start end end describe "clean" do it "should proxy clean to the strategy" do strategy.should_receive(:clean) subject.clean end end describe "clean!" do it "should proxy clean! to the strategy clean" do strategy.should_receive(:clean) subject.clean! end end describe "cleaning" do it "should proxy cleaning to the strategy" do strategy.should_receive(:cleaning) subject.cleaning { } end end end describe "auto_detected?" do it "should return true unless @autodetected is nil" do subject.instance_variable_set("@autodetected","not nil") subject.auto_detected?.should be_true end it "should return false if @autodetect is nil" do subject.instance_variable_set("@autodetected",nil) subject.auto_detected?.should be_false end end describe "orm_strategy" do let (:strategy_class) { double("strategy_class") } before(:each) do subject.stub(:orm_module).and_return(strategy_class) end context "in response to a LoadError" do before(:each) { subject.should_receive(:require).with(anything).and_raise(LoadError) } it "should raise UnknownStrategySpecified" do expect { subject.send(:orm_strategy,:a_strategy) }.to raise_error UnknownStrategySpecified end it "should ask orm_module if it will list available_strategies" do strategy_class.should_receive(:respond_to?).with(:available_strategies) subject.stub(:orm_module).and_return(strategy_class) expect { subject.send(:orm_strategy,:a_strategy) }.to raise_error UnknownStrategySpecified end it "should use available_strategies (for the error message) if its available" do strategy_class.stub(:respond_to?).with(:available_strategies).and_return(true) strategy_class.should_receive(:available_strategies).and_return([]) subject.stub(:orm_module).and_return(strategy_class) expect { subject.send(:orm_strategy,:a_strategy) }.to raise_error UnknownStrategySpecified end end it "should return the constant of the Strategy class requested" do strategy_strategy_class = double("strategy strategy_class") subject.stub(:require).with(anything).and_return(true) strategy_class.should_receive(:const_get).with("Cunningplan").and_return(strategy_strategy_class) subject.send(:orm_strategy, :cunningplan).should eq strategy_strategy_class end end describe 'set_default_orm_strategy' do it 'sets strategy to :transaction for ActiveRecord' do cleaner = DatabaseCleaner::Base.new(:active_record) cleaner.strategy.should be_instance_of DatabaseCleaner::ActiveRecord::Transaction end it 'sets strategy to :transaction for DataMapper' do cleaner = DatabaseCleaner::Base.new(:data_mapper) cleaner.strategy.should be_instance_of DatabaseCleaner::DataMapper::Transaction end it 'sets strategy to :truncation for MongoMapper' do cleaner = DatabaseCleaner::Base.new(:mongo_mapper) cleaner.strategy.should be_instance_of DatabaseCleaner::MongoMapper::Truncation end it 'sets strategy to :truncation for Mongoid' do cleaner = DatabaseCleaner::Base.new(:mongoid) cleaner.strategy.should be_instance_of DatabaseCleaner::Mongoid::Truncation end it 'sets strategy to :truncation for CouchPotato' do cleaner = DatabaseCleaner::Base.new(:couch_potato) cleaner.strategy.should be_instance_of DatabaseCleaner::CouchPotato::Truncation end it 'sets strategy to :transaction for Sequel' do cleaner = DatabaseCleaner::Base.new(:sequel) cleaner.strategy.should be_instance_of DatabaseCleaner::Sequel::Transaction end it 'sets strategy to :truncation for Moped' do cleaner = DatabaseCleaner::Base.new(:moped) cleaner.strategy.should be_instance_of DatabaseCleaner::Moped::Truncation end it 'sets strategy to :truncation for Ohm' do cleaner = DatabaseCleaner::Base.new(:ohm) cleaner.strategy.should be_instance_of DatabaseCleaner::Ohm::Truncation end it 'sets strategy to :truncation for Redis' do cleaner = DatabaseCleaner::Base.new(:redis) cleaner.strategy.should be_instance_of DatabaseCleaner::Redis::Truncation end it 'sets strategy to :transaction for Neo4j' do cleaner = DatabaseCleaner::Base.new(:neo4j) cleaner.strategy.should be_instance_of DatabaseCleaner::Neo4j::Transaction end end end end Code style. require File.dirname(__FILE__) + '/../spec_helper' require 'database_cleaner/active_record/transaction' require 'database_cleaner/data_mapper/transaction' require 'database_cleaner/mongo_mapper/truncation' require 'database_cleaner/mongoid/truncation' require 'database_cleaner/couch_potato/truncation' require 'database_cleaner/neo4j/transaction' module DatabaseCleaner describe Base do describe "autodetect" do #Cache all ORMs, we'll need them later but not now. before(:all) do Temp_AR = ::ActiveRecord if defined?(::ActiveRecord) and not defined?(Temp_AR) Temp_DM = ::DataMapper if defined?(::DataMapper) and not defined?(Temp_DM) Temp_MM = ::MongoMapper if defined?(::MongoMapper) and not defined?(Temp_MM) Temp_MO = ::Mongoid if defined?(::Mongoid) and not defined?(Temp_MO) Temp_CP = ::CouchPotato if defined?(::CouchPotato) and not defined?(Temp_CP) Temp_SQ = ::Sequel if defined?(::Sequel) and not defined?(Temp_SQ) Temp_MP = ::Moped if defined?(::Moped) and not defined?(Temp_MP) Temp_RS = ::Redis if defined?(::Redis) and not defined?(Temp_RS) Temp_OH = ::Ohm if defined?(::Ohm) and not defined?(Temp_OH) Temp_NJ = ::Neo4j if defined?(::Neo4j) and not defined?(Temp_NJ) end #Remove all ORM mocks and restore from cache after(:all) do Object.send(:remove_const, 'ActiveRecord') if defined?(::ActiveRecord) Object.send(:remove_const, 'DataMapper') if defined?(::DataMapper) Object.send(:remove_const, 'MongoMapper') if defined?(::MongoMapper) Object.send(:remove_const, 'Mongoid') if defined?(::Mongoid) Object.send(:remove_const, 'CouchPotato') if defined?(::CouchPotato) Object.send(:remove_const, 'Sequel') if defined?(::Sequel) Object.send(:remove_const, 'Moped') if defined?(::Moped) Object.send(:remove_const, 'Ohm') if defined?(::Ohm) Object.send(:remove_const, 'Redis') if defined?(::Redis) Object.send(:remove_const, 'Neo4j') if defined?(::Neo4j) # Restore ORMs ::ActiveRecord = Temp_AR if defined? Temp_AR ::DataMapper = Temp_DM if defined? Temp_DM ::MongoMapper = Temp_MM if defined? Temp_MM ::Mongoid = Temp_MO if defined? Temp_MO ::CouchPotato = Temp_CP if defined? Temp_CP ::Sequel = Temp_SQ if defined? Temp_SQ ::Moped = Temp_MP if defined? Temp_MP ::Ohm = Temp_OH if defined? Temp_OH ::Redis = Temp_RS if defined? Temp_RS ::Neo4j = Temp_NJ if defined? Temp_NJ end #reset the orm mocks before(:each) do Object.send(:remove_const, 'ActiveRecord') if defined?(::ActiveRecord) Object.send(:remove_const, 'DataMapper') if defined?(::DataMapper) Object.send(:remove_const, 'MongoMapper') if defined?(::MongoMapper) Object.send(:remove_const, 'Mongoid') if defined?(::Mongoid) Object.send(:remove_const, 'CouchPotato') if defined?(::CouchPotato) Object.send(:remove_const, 'Sequel') if defined?(::Sequel) Object.send(:remove_const, 'Moped') if defined?(::Moped) Object.send(:remove_const, 'Ohm') if defined?(::Ohm) Object.send(:remove_const, 'Redis') if defined?(::Redis) Object.send(:remove_const, 'Neo4j') if defined?(::Neo4j) end let(:cleaner) { DatabaseCleaner::Base.new :autodetect } it "should raise an error when no ORM is detected" do running { cleaner }.should raise_error(DatabaseCleaner::NoORMDetected) end it "should detect ActiveRecord first" do Object.const_set('ActiveRecord','Actively mocking records.') Object.const_set('DataMapper', 'Mapping data mocks') Object.const_set('MongoMapper', 'Mapping mock mongos') Object.const_set('Mongoid', 'Mongoid mock') Object.const_set('CouchPotato', 'Couching mock potatos') Object.const_set('Sequel', 'Sequel mock') Object.const_set('Moped', 'Moped mock') Object.const_set('Ohm', 'Ohm mock') Object.const_set('Redis', 'Redis mock') Object.const_set('Neo4j', 'Neo4j mock') cleaner.orm.should eq :active_record cleaner.should be_auto_detected end it "should detect DataMapper second" do Object.const_set('DataMapper', 'Mapping data mocks') Object.const_set('MongoMapper', 'Mapping mock mongos') Object.const_set('Mongoid', 'Mongoid mock') Object.const_set('CouchPotato', 'Couching mock potatos') Object.const_set('Sequel', 'Sequel mock') Object.const_set('Moped', 'Moped mock') Object.const_set('Ohm', 'Ohm mock') Object.const_set('Redis', 'Redis mock') Object.const_set('Neo4j', 'Neo4j mock') cleaner.orm.should eq :data_mapper cleaner.should be_auto_detected end it "should detect MongoMapper third" do Object.const_set('MongoMapper', 'Mapping mock mongos') Object.const_set('Mongoid', 'Mongoid mock') Object.const_set('CouchPotato', 'Couching mock potatos') Object.const_set('Sequel', 'Sequel mock') Object.const_set('Moped', 'Moped mock') Object.const_set('Ohm', 'Ohm mock') Object.const_set('Redis', 'Redis mock') Object.const_set('Neo4j', 'Neo4j mock') cleaner.orm.should eq :mongo_mapper cleaner.should be_auto_detected end it "should detect Mongoid fourth" do Object.const_set('Mongoid', 'Mongoid mock') Object.const_set('CouchPotato', 'Couching mock potatos') Object.const_set('Sequel', 'Sequel mock') Object.const_set('Moped', 'Moped mock') Object.const_set('Ohm', 'Ohm mock') Object.const_set('Redis', 'Redis mock') Object.const_set('Neo4j', 'Neo4j mock') cleaner.orm.should eq :mongoid cleaner.should be_auto_detected end it "should detect CouchPotato fifth" do Object.const_set('CouchPotato', 'Couching mock potatos') Object.const_set('Sequel', 'Sequel mock') Object.const_set('Moped', 'Moped mock') Object.const_set('Ohm', 'Ohm mock') Object.const_set('Redis', 'Redis mock') Object.const_set('Neo4j', 'Neo4j mock') cleaner.orm.should eq :couch_potato cleaner.should be_auto_detected end it "should detect Sequel sixth" do Object.const_set('Sequel', 'Sequel mock') Object.const_set('Moped', 'Moped mock') Object.const_set('Ohm', 'Ohm mock') Object.const_set('Redis', 'Redis mock') Object.const_set('Neo4j', 'Neo4j mock') cleaner.orm.should eq :sequel cleaner.should be_auto_detected end it 'detects Moped seventh' do Object.const_set('Moped', 'Moped mock') cleaner.orm.should eq :moped cleaner.should be_auto_detected end it 'detects Ohm eighth' do Object.const_set('Ohm', 'Ohm mock') Object.const_set('Redis', 'Redis mock') Object.const_set('Neo4j', 'Neo4j mock') cleaner.orm.should eq :ohm cleaner.should be_auto_detected end it 'detects Redis ninth' do Object.const_set('Redis', 'Redis mock') Object.const_set('Neo4j', 'Neo4j mock') cleaner.orm.should eq :redis cleaner.should be_auto_detected end it 'detects Neo4j tenth' do Object.const_set('Neo4j', 'Neo4j mock') cleaner.orm.should eq :neo4j cleaner.should be_auto_detected end end describe "orm_module" do it "should ask ::DatabaseCleaner what the module is for its orm" do orm = double("orm") mockule = double("module") cleaner = ::DatabaseCleaner::Base.new cleaner.should_receive(:orm).and_return(orm) ::DatabaseCleaner.should_receive(:orm_module).with(orm).and_return(mockule) cleaner.send(:orm_module).should eq mockule end end describe "comparison" do it "should be equal if orm, connection and strategy are the same" do strategy = mock("strategy") strategy.stub!(:to_ary => [strategy]) one = DatabaseCleaner::Base.new(:active_record,:connection => :default) one.strategy = strategy two = DatabaseCleaner::Base.new(:active_record,:connection => :default) two.strategy = strategy one.should eq two two.should eq one end it "should not be equal if orm are not the same" do strategy = mock("strategy") strategy.stub!(:to_ary => [strategy]) one = DatabaseCleaner::Base.new(:mongo_id, :connection => :default) one.strategy = strategy two = DatabaseCleaner::Base.new(:active_record, :connection => :default) two.strategy = strategy one.should_not eq two two.should_not eq one end it "should not be equal if connection are not the same" do one = DatabaseCleaner::Base.new(:active_record, :connection => :default) one.strategy = :truncation two = DatabaseCleaner::Base.new(:active_record, :connection => :other) two.strategy = :truncation one.should_not eq two two.should_not eq one end end describe "initialization" do context "db specified" do subject { ::DatabaseCleaner::Base.new(:active_record,:connection => :my_db) } it "should store db from :connection in params hash" do subject.db.should eq :my_db end end describe "orm" do it "should store orm" do cleaner = ::DatabaseCleaner::Base.new :a_orm cleaner.orm.should eq :a_orm end it "converts string to symbols" do cleaner = ::DatabaseCleaner::Base.new "mongoid" cleaner.orm.should eq :mongoid end it "is autodetected if orm is not provided" do cleaner = ::DatabaseCleaner::Base.new cleaner.should be_auto_detected end it "is autodetected if you specify :autodetect" do cleaner = ::DatabaseCleaner::Base.new "autodetect" cleaner.should be_auto_detected end it "should default to autodetect upon initalisation" do subject.should be_auto_detected end end end describe "db" do it "should default to :default" do subject.db.should eq :default end it "should return any stored db value" do subject.stub(:strategy_db=) subject.db = :test_db subject.db.should eq :test_db end it "should pass db to any specified strategy" do subject.should_receive(:strategy_db=).with(:a_new_db) subject.db = :a_new_db end end describe "strategy_db=" do let(:strategy) { mock("strategy").tap{|strategy| strategy.stub!(:to_ary => [strategy]) } } before(:each) do subject.strategy = strategy end it "should check that strategy supports db specification" do strategy.should_receive(:respond_to?).with(:db=).and_return(true) strategy.stub(:db=) subject.strategy_db = :a_db end context "when strategy supports db specification" do before(:each) { strategy.stub(:respond_to?).with(:db=).and_return true } it "should pass db to the strategy" do strategy.should_receive(:db=).with(:a_db) subject.strategy_db = :a_db end end context "when strategy doesn't supports db specification" do before(:each) { strategy.stub(:respond_to?).with(:db=).and_return false } it "should check to see if db is :default" do db = double("default") db.should_receive(:==).with(:default).and_return(true) subject.strategy_db = db end it "should raise an argument error when db isn't default" do db = double("a db") expect{ subject.strategy_db = db }.to raise_error ArgumentError end end end describe "clean_with" do let (:strategy) { double("strategy",:clean => true) } before(:each) { subject.stub(:create_strategy).with(anything).and_return(strategy) } it "should pass all arguments to create_strategy" do subject.should_receive(:create_strategy).with(:lorum, :dollar, :amet, :ipsum => "random").and_return(strategy) subject.clean_with :lorum, :dollar, :amet, { :ipsum => "random" } end it "should invoke clean on the created strategy" do strategy.should_receive(:clean) subject.clean_with :strategy end it "should return the strategy" do subject.clean_with( :strategy ).should eq strategy end end describe "clean_with!" do let (:strategy) { double("strategy",:clean => true) } before(:each) { subject.stub(:create_strategy).with(anything).and_return(strategy) } it "should pass all arguments to create_strategy" do subject.should_receive(:create_strategy).with(:lorum, :dollar, :amet, :ipsum => "random").and_return(strategy) subject.clean_with! :lorum, :dollar, :amet, { :ipsum => "random" } end it "should invoke clean on the created strategy" do strategy.should_receive(:clean) subject.clean_with! :strategy end it "should return the strategy" do subject.clean_with!( :strategy ).should eq strategy end end describe "create_strategy" do let(:strategy_class) { double("strategy_class",:new => double("instance")) } before :each do subject.stub(:orm_strategy).and_return(strategy_class) end it "should pass the first argument to orm_strategy" do subject.should_receive(:orm_strategy).with(:strategy).and_return(Object) subject.create_strategy :strategy end it "should pass the remainding argument to orm_strategy.new" do strategy_class.should_receive(:new).with(:params => {:lorum => "ipsum"}) subject.create_strategy :strategy, {:params => {:lorum => "ipsum"}} end it "should return the resulting strategy" do subject.create_strategy( :strategy ).should eq strategy_class.new end end describe "strategy=" do let(:mock_strategy) { mock("strategy").tap{|strategy| strategy.stub!(:to_ary => [strategy]) } } it "should proxy symbolised strategies to create_strategy" do subject.should_receive(:create_strategy).with(:symbol) subject.strategy = :symbol end it "should proxy params with symbolised strategies" do subject.should_receive(:create_strategy).with(:symbol,:param => "one") subject.strategy= :symbol, {:param => "one"} end it "should accept strategy objects" do expect{ subject.strategy = mock_strategy }.to_not raise_error end it "should raise argument error when params given with strategy Object" do expect{ subject.strategy = double("object"), {:param => "one"} }.to raise_error ArgumentError end it "should attempt to set strategy db" do subject.stub(:db).and_return(:my_db) subject.should_receive(:set_strategy_db).with(mock_strategy, :my_db) subject.strategy = mock_strategy end it "should return the stored strategy" do result = subject.strategy = mock_strategy result.should eq mock_strategy end end describe "strategy" do subject { ::DatabaseCleaner::Base.new :a_orm } it "returns a null strategy when strategy is not set and undetectable" do subject.strategy.should eq DatabaseCleaner::NullStrategy end it "returns the set strategy" do strategum = mock("strategy").tap{|strategy| strategy.stub!(:to_ary => [strategy]) } subject.strategy = strategum subject.strategy.should eq strategum end end describe "orm=" do it "should stored the desired orm" do subject.orm.should_not eq :desired_orm subject.orm = :desired_orm subject.orm.should eq :desired_orm end end describe "orm" do let(:mock_orm) { double("orm") } it "should return orm if orm set" do subject.instance_variable_set "@orm", mock_orm subject.orm.should eq mock_orm end context "orm isn't set" do before(:each) { subject.instance_variable_set "@orm", nil } it "should run autodetect if orm isn't set" do subject.should_receive(:autodetect) subject.orm end it "should return the result of autodetect if orm isn't set" do subject.stub(:autodetect).and_return(mock_orm) subject.orm.should eq mock_orm end end end describe "proxy methods" do let (:strategy) { double("strategy") } before(:each) do subject.stub(:strategy).and_return(strategy) end describe "start" do it "should proxy start to the strategy" do strategy.should_receive(:start) subject.start end end describe "clean" do it "should proxy clean to the strategy" do strategy.should_receive(:clean) subject.clean end end describe "clean!" do it "should proxy clean! to the strategy clean" do strategy.should_receive(:clean) subject.clean! end end describe "cleaning" do it "should proxy cleaning to the strategy" do strategy.should_receive(:cleaning) subject.cleaning { } end end end describe "auto_detected?" do it "should return true unless @autodetected is nil" do subject.instance_variable_set("@autodetected","not nil") subject.auto_detected?.should be_true end it "should return false if @autodetect is nil" do subject.instance_variable_set("@autodetected",nil) subject.auto_detected?.should be_false end end describe "orm_strategy" do let (:strategy_class) { double("strategy_class") } before(:each) do subject.stub(:orm_module).and_return(strategy_class) end context "in response to a LoadError" do before(:each) { subject.should_receive(:require).with(anything).and_raise(LoadError) } it "should raise UnknownStrategySpecified" do expect { subject.send(:orm_strategy,:a_strategy) }.to raise_error UnknownStrategySpecified end it "should ask orm_module if it will list available_strategies" do strategy_class.should_receive(:respond_to?).with(:available_strategies) subject.stub(:orm_module).and_return(strategy_class) expect { subject.send(:orm_strategy,:a_strategy) }.to raise_error UnknownStrategySpecified end it "should use available_strategies (for the error message) if its available" do strategy_class.stub(:respond_to?).with(:available_strategies).and_return(true) strategy_class.should_receive(:available_strategies).and_return([]) subject.stub(:orm_module).and_return(strategy_class) expect { subject.send(:orm_strategy,:a_strategy) }.to raise_error UnknownStrategySpecified end end it "should return the constant of the Strategy class requested" do strategy_strategy_class = double("strategy strategy_class") subject.stub(:require).with(anything).and_return(true) strategy_class.should_receive(:const_get).with("Cunningplan").and_return(strategy_strategy_class) subject.send(:orm_strategy, :cunningplan).should eq strategy_strategy_class end end describe 'set_default_orm_strategy' do it 'sets strategy to :transaction for ActiveRecord' do cleaner = DatabaseCleaner::Base.new(:active_record) cleaner.strategy.should be_instance_of DatabaseCleaner::ActiveRecord::Transaction end it 'sets strategy to :transaction for DataMapper' do cleaner = DatabaseCleaner::Base.new(:data_mapper) cleaner.strategy.should be_instance_of DatabaseCleaner::DataMapper::Transaction end it 'sets strategy to :truncation for MongoMapper' do cleaner = DatabaseCleaner::Base.new(:mongo_mapper) cleaner.strategy.should be_instance_of DatabaseCleaner::MongoMapper::Truncation end it 'sets strategy to :truncation for Mongoid' do cleaner = DatabaseCleaner::Base.new(:mongoid) cleaner.strategy.should be_instance_of DatabaseCleaner::Mongoid::Truncation end it 'sets strategy to :truncation for CouchPotato' do cleaner = DatabaseCleaner::Base.new(:couch_potato) cleaner.strategy.should be_instance_of DatabaseCleaner::CouchPotato::Truncation end it 'sets strategy to :transaction for Sequel' do cleaner = DatabaseCleaner::Base.new(:sequel) cleaner.strategy.should be_instance_of DatabaseCleaner::Sequel::Transaction end it 'sets strategy to :truncation for Moped' do cleaner = DatabaseCleaner::Base.new(:moped) cleaner.strategy.should be_instance_of DatabaseCleaner::Moped::Truncation end it 'sets strategy to :truncation for Ohm' do cleaner = DatabaseCleaner::Base.new(:ohm) cleaner.strategy.should be_instance_of DatabaseCleaner::Ohm::Truncation end it 'sets strategy to :truncation for Redis' do cleaner = DatabaseCleaner::Base.new(:redis) cleaner.strategy.should be_instance_of DatabaseCleaner::Redis::Truncation end it 'sets strategy to :transaction for Neo4j' do cleaner = DatabaseCleaner::Base.new(:neo4j) cleaner.strategy.should be_instance_of DatabaseCleaner::Neo4j::Transaction end end end end
Added cv2avs_spec require 'spec_helper' describe Datacash::Nodes::Cv2Avs do describe "#to_xml" do subject { MultiXml.parse(described_class.new.to_xml) } it "should have a root element of 'Cv2Avs'" do subject.should have_key('Cv2Avs') end end end
require 'spec_helper' describe "Song Forms" do let(:artist_name) { "Person with a Face" } let(:genre_1_name) { "New Age Garbage" } let(:genre_2_name) { "Hippity Hop" } let(:song_name) { "That One with the Guitar" } let!(:genre_1) { Genre.create(name: genre_1_name) } let!(:genre_2) { Genre.create(name: genre_2_name) } describe "/songs/new" do before do visit "/songs/new" end context "without an existing artist" do it "creates a new song and a new artist and associates them" do fill_in "Name", with: song_name check "New Age Garbage" fill_in "Artist Name", with: artist_name click_on "Create" expect(page).to have_content(song_name) expect(page).to have_content(artist_name) expect(page).to have_content(genre_1_name) expect(page).to have_content("Successfully created song.") end end context "with an existing artist" do before do artist = Artist.create(name: artist_name) end it "creates a new song and associates it with an existing artist" do fill_in "Name", with: song_name # binding.pry check "Hippity Hop" fill_in "Artist Name", with: artist_name click_on "Create" expect(page).to have_content(song_name) expect(page).to have_content(artist_name) expect(page).to have_content(genre_1_name) expect(page).to have_content("Successfully created song.") end end end describe "/songs/:slug/edit" do before do @song = Song.create(name: song_name) artist = Artist.create(name: artist_name) @song.song_genres.create(genre: genre_1) @song.artist = artist @song.save visit "/songs/#{@song.slug}/edit" end context "changing a song's artist" do it "updates the song's artist" do fill_in "Artist Name", with: "Some Nobody" click_on "Save" expect(page).to have_content("Song successfully updated.") expect(page).to have_content(song_name) expect(page).to have_content("Some Nobody") end end context "changing a song's genres" do it "has a checkbox element on the form" do expect(page.body).to include("checkbox") end it "updates the song's genres" do uncheck "New Age Garbage" check "Hippity Hop" click_on "Save" expect(page).to have_content("Song successfully updated.") expect(page).to have_content(song_name) expect(page).to have_content(artist_name) end end end end removed comment require 'spec_helper' describe "Song Forms" do let(:artist_name) { "Person with a Face" } let(:genre_1_name) { "New Age Garbage" } let(:genre_2_name) { "Hippity Hop" } let(:song_name) { "That One with the Guitar" } let!(:genre_1) { Genre.create(name: genre_1_name) } let!(:genre_2) { Genre.create(name: genre_2_name) } describe "/songs/new" do before do visit "/songs/new" end context "without an existing artist" do it "creates a new song and a new artist and associates them" do fill_in "Name", with: song_name check "New Age Garbage" fill_in "Artist Name", with: artist_name click_on "Create" expect(page).to have_content(song_name) expect(page).to have_content(artist_name) expect(page).to have_content(genre_1_name) expect(page).to have_content("Successfully created song.") end end context "with an existing artist" do before do artist = Artist.create(name: artist_name) end it "creates a new song and associates it with an existing artist" do fill_in "Name", with: song_name check "Hippity Hop" fill_in "Artist Name", with: artist_name click_on "Create" expect(page).to have_content(song_name) expect(page).to have_content(artist_name) expect(page).to have_content(genre_1_name) expect(page).to have_content("Successfully created song.") end end end describe "/songs/:slug/edit" do before do @song = Song.create(name: song_name) artist = Artist.create(name: artist_name) @song.song_genres.create(genre: genre_1) @song.artist = artist @song.save visit "/songs/#{@song.slug}/edit" end context "changing a song's artist" do it "updates the song's artist" do fill_in "Artist Name", with: "Some Nobody" click_on "Save" expect(page).to have_content("Song successfully updated.") expect(page).to have_content(song_name) expect(page).to have_content("Some Nobody") end end context "changing a song's genres" do it "has a checkbox element on the form" do expect(page.body).to include("checkbox") end it "updates the song's genres" do uncheck "New Age Garbage" check "Hippity Hop" click_on "Save" expect(page).to have_content("Song successfully updated.") expect(page).to have_content(song_name) expect(page).to have_content(artist_name) end end end end
require "spec_helper" feature %q{ As a payment administrator I want to capture multiple payments quickly from the one page } do include AuthenticationWorkflow include WebHelper background do @user = create(:user) @product = create(:simple_product) @distributor = create(:distributor_enterprise) @order_cycle = create(:simple_order_cycle, distributors: [@distributor], variants: [@product.master]) @order = create(:order_with_totals_and_distribution, user: @user, distributor: @distributor, order_cycle: @order_cycle, state: 'complete', payment_state: 'balance_due') # ensure order has a payment to capture @order.finalize! create :check_payment, order: @order, amount: @order.total end scenario "creating an order with distributor and order cycle", js: true do order_cycle = create(:order_cycle) distributor = order_cycle.distributors.first product = order_cycle.products.first login_to_admin_section visit '/admin/orders' click_link 'New Order' page.should have_content 'ADD PRODUCT' targetted_select2_search product.name, from: '#add_variant_id', dropdown_css: '.select2-drop' click_link 'Add' page.has_selector? "table.index tbody[data-hook='admin_order_form_line_items'] tr" # Wait for JS page.should have_selector 'td', text: product.name select distributor.name, from: 'order_distributor_id' select order_cycle.name, from: 'order_order_cycle_id' click_button 'Update' page.should have_selector 'h1', text: 'Customer Details' o = Spree::Order.last o.distributor.should == distributor o.order_cycle.should == order_cycle end scenario "can add a product to an existing order", js: true do login_to_admin_section visit '/admin/orders' page.find('td.actions a.icon-edit').click targetted_select2_search @product.name, from: ".variant_autocomplete", dropdown_css: ".select2-search" click_icon :plus page.should have_selector 'td', text: @product.name @order.line_items(true).map(&:product).should include @product end scenario "can't add products to an order outside the order's hub and order cycle", js: true do product = create(:simple_product) login_to_admin_section visit '/admin/orders' page.find('td.actions a.icon-edit').click page.should_not have_select2_option product.name, from: ".variant_autocomplete", dropdown_css: ".select2-search" end scenario "can't change distributor or order cycle once order has been finalized" do @order.update_attributes order_cycle_id: nil login_to_admin_section visit '/admin/orders' page.find('td.actions a.icon-edit').click page.should have_no_select 'order_distributor_id' page.should have_no_select 'order_order_cycle_id' page.should have_selector 'p', text: "Distributor: #{@order.distributor.name}" page.should have_selector 'p', text: "Order cycle: None" end scenario "capture multiple payments from the orders index page" do # d.cook: could also test for an order that has had payment voided, then a new check payment created but not yet captured. But it's not critical and I know it works anyway. login_to_admin_section visit '/admin/orders' current_path.should == spree.admin_orders_path # click the 'capture' link for the order page.find("[data-action=capture][href*=#{@order.number}]").click flash_message.should == "Payment Updated" # check the order was captured @order.reload @order.payment_state.should == "paid" # we should still be on the same page current_path.should == spree.admin_orders_path end context "as an enterprise manager" do let(:coordinator1) { create(:distributor_enterprise) } let(:coordinator2) { create(:distributor_enterprise) } let!(:order_cycle1) { create(:order_cycle, coordinator: coordinator1) } let!(:order_cycle2) { create(:simple_order_cycle, coordinator: coordinator2) } let(:supplier1) { order_cycle1.suppliers.first } let(:supplier2) { order_cycle1.suppliers.last } let(:distributor1) { order_cycle1.distributors.first } let(:distributor2) { order_cycle1.distributors.last } let(:product) { order_cycle1.products.first } before(:each) do @enterprise_user = create_enterprise_user @enterprise_user.enterprise_roles.build(enterprise: supplier1).save @enterprise_user.enterprise_roles.build(enterprise: coordinator1).save @enterprise_user.enterprise_roles.build(enterprise: distributor1).save login_to_admin_as @enterprise_user end scenario "creating an order with distributor and order cycle", js: true do visit '/admin/orders' click_link 'New Order' expect(page).to have_content 'ADD PRODUCT' targetted_select2_search product.name, from: '#add_variant_id', dropdown_css: '.select2-drop' click_link 'Add' page.has_selector? "table.index tbody[data-hook='admin_order_form_line_items'] tr" # Wait for JS expect(page).to have_selector 'td', text: product.name expect(page).to have_select 'order_distributor_id', with_options: [distributor1.name] expect(page).to_not have_select 'order_distributor_id', with_options: [distributor2.name] expect(page).to have_select 'order_order_cycle_id', with_options: [order_cycle1.name] expect(page).to_not have_select 'order_order_cycle_id', with_options: [order_cycle2.name] select distributor1.name, from: 'order_distributor_id' select order_cycle1.name, from: 'order_order_cycle_id' click_button 'Update' expect(page).to have_selector 'h1', text: 'Customer Details' o = Spree::Order.last expect(o.distributor).to eq distributor1 expect(o.order_cycle).to eq order_cycle1 end end end TEMP: spit out variables in failing oc spec require "spec_helper" feature %q{ As a payment administrator I want to capture multiple payments quickly from the one page } do include AuthenticationWorkflow include WebHelper background do @user = create(:user) @product = create(:simple_product) @distributor = create(:distributor_enterprise) @order_cycle = create(:simple_order_cycle, distributors: [@distributor], variants: [@product.master]) @order = create(:order_with_totals_and_distribution, user: @user, distributor: @distributor, order_cycle: @order_cycle, state: 'complete', payment_state: 'balance_due') # ensure order has a payment to capture @order.finalize! create :check_payment, order: @order, amount: @order.total end scenario "creating an order with distributor and order cycle", js: true do order_cycle = create(:order_cycle) distributor = order_cycle.distributors.first product = order_cycle.products.first login_to_admin_section visit '/admin/orders' click_link 'New Order' page.should have_content 'ADD PRODUCT' targetted_select2_search product.name, from: '#add_variant_id', dropdown_css: '.select2-drop' click_link 'Add' page.has_selector? "table.index tbody[data-hook='admin_order_form_line_items'] tr" # Wait for JS page.should have_selector 'td', text: product.name select distributor.name, from: 'order_distributor_id' select order_cycle.name, from: 'order_order_cycle_id' click_button 'Update' page.should have_selector 'h1', text: 'Customer Details' o = Spree::Order.last o.distributor.should == distributor o.order_cycle.should == order_cycle end scenario "can add a product to an existing order", js: true do login_to_admin_section visit '/admin/orders' page.find('td.actions a.icon-edit').click targetted_select2_search @product.name, from: ".variant_autocomplete", dropdown_css: ".select2-search" click_icon :plus page.should have_selector 'td', text: @product.name @order.line_items(true).map(&:product).should include @product end scenario "can't add products to an order outside the order's hub and order cycle", js: true do product = create(:simple_product) login_to_admin_section visit '/admin/orders' page.find('td.actions a.icon-edit').click page.should_not have_select2_option product.name, from: ".variant_autocomplete", dropdown_css: ".select2-search" end scenario "can't change distributor or order cycle once order has been finalized" do @order.update_attributes order_cycle_id: nil login_to_admin_section visit '/admin/orders' page.find('td.actions a.icon-edit').click page.should have_no_select 'order_distributor_id' page.should have_no_select 'order_order_cycle_id' page.should have_selector 'p', text: "Distributor: #{@order.distributor.name}" page.should have_selector 'p', text: "Order cycle: None" end scenario "capture multiple payments from the orders index page" do # d.cook: could also test for an order that has had payment voided, then a new check payment created but not yet captured. But it's not critical and I know it works anyway. login_to_admin_section visit '/admin/orders' current_path.should == spree.admin_orders_path # click the 'capture' link for the order page.find("[data-action=capture][href*=#{@order.number}]").click flash_message.should == "Payment Updated" # check the order was captured @order.reload @order.payment_state.should == "paid" # we should still be on the same page current_path.should == spree.admin_orders_path end context "as an enterprise manager" do let(:coordinator1) { create(:distributor_enterprise) } let(:coordinator2) { create(:distributor_enterprise) } let!(:order_cycle1) { create(:order_cycle, coordinator: coordinator1) } let!(:order_cycle2) { create(:simple_order_cycle, coordinator: coordinator2) } let(:supplier1) { order_cycle1.suppliers.first } let(:supplier2) { order_cycle1.suppliers.last } let(:distributor1) { order_cycle1.distributors.first } let(:distributor2) { order_cycle1.distributors.last } let(:product) { order_cycle1.products.first } before(:each) do @enterprise_user = create_enterprise_user @enterprise_user.enterprise_roles.build(enterprise: supplier1).save @enterprise_user.enterprise_roles.build(enterprise: coordinator1).save @enterprise_user.enterprise_roles.build(enterprise: distributor1).save login_to_admin_as @enterprise_user end scenario "creating an order with distributor and order cycle", js: true do visit '/admin/orders' click_link 'New Order' expect(page).to have_content 'ADD PRODUCT' targetted_select2_search product.name, from: '#add_variant_id', dropdown_css: '.select2-drop' puts "c1: " + coordinator1.id.to_s + " "+ coordinator1.name puts "c2: " + coordinator2.id.to_s + " "+ coordinator2.name puts "s1: " + supplier1.id.to_s + " "+ supplier1.name puts "s2: " + supplier2.id.to_s + " "+ supplier2.name puts "d1: " + distributor1.id.to_s + " "+ distributor1.name puts "d2: " + distributor2.id.to_s + " "+ distributor2.name order_cycle1.distributors.each do |distributor| puts "oc1d: " + distributor.id.to_s + " "+ distributor.name end Enterprise.is_distributor.managed_by(@enterprise_user).each do |distributor| puts "eud: " + distributor.id.to_s + " "+ distributor.name end click_link 'Add' page.has_selector? "table.index tbody[data-hook='admin_order_form_line_items'] tr" # Wait for JS expect(page).to have_selector 'td', text: product.name expect(page).to have_select 'order_distributor_id', with_options: [distributor1.name] expect(page).to_not have_select 'order_distributor_id', with_options: [distributor2.name] expect(page).to have_select 'order_order_cycle_id', with_options: [order_cycle1.name] expect(page).to_not have_select 'order_order_cycle_id', with_options: [order_cycle2.name] select distributor1.name, from: 'order_distributor_id' select order_cycle1.name, from: 'order_order_cycle_id' click_button 'Update' expect(page).to have_selector 'h1', text: 'Customer Details' o = Spree::Order.last expect(o.distributor).to eq distributor1 expect(o.order_cycle).to eq order_cycle1 end end end
require 'rails_helper.rb' Create a failure test for creating posts require 'rails_helper.rb' feature 'Creating Posts' do scenario 'Can create post' do visit '/' click_link 'Create Post' fill_in 'Title', with: 'title' fill_in 'Content', with: 'post content' click_button 'Create' expect(page).to have_content 'title' expect(page).to have_content 'post content' end end
require 'spec_helper' # In general, updating database objects occurs faster than Ember transitions. # Because of this I have littered sleeps throughout the code to make sure the # transition finishes before asserting there was a UI update. feature "Event streaming", js: true do let!(:author) { FactoryGirl.create :user } let!(:paper) { author.papers.create! short_title: 'foo bar', journal: Journal.create! } let(:upload_task) { author.papers.first.tasks_for_type(UploadManuscriptTask).first } before do sign_in_page = SignInPage.visit sign_in_page.sign_in author.email end scenario "On the dashboard page" do # Weird race condition if this test doesn't run first. sleep 0.3 expect(page).to have_no_selector(".completed") upload_task.completed = true upload_task.save expect(page).to have_css(".card-completed", count: 1) end describe "manuscript manager" do before do edit_paper = EditPaperPage.visit paper edit_paper.navigate_to_task_manager end let(:submission_phase) { paper.phases.find_by_name("Submission Data") } scenario "creating a new message task" do mt = submission_phase.tasks.new title: "Wicked Message Card", type: "MessageTask", body: "Hi there!", role: "user" mt.participants << author mt.save! phase = all('.column').detect {|p| p.find('h2').text == "Submission Data" } within phase do expect(page).to have_content "Wicked Message Card" end end scenario "creating a new task" do submission_phase.tasks.create title: "Wicked Awesome Card", type: "Task", body: "Hi there!", role: "admin" phase = all('.column').detect {|p| p.find('h2').text == "Submission Data" } within phase do expect(page).to have_content "Wicked Awesome Card" end end end describe "message tasks" do before do edit_paper = EditPaperPage.visit paper edit_paper.navigate_to_task_manager submission_phase = paper.phases.find_by_name("Submission Data") @mt = submission_phase.tasks.new title: "Wicked Message Card", type: "MessageTask", body: "Hi there!", role: "user" @mt.participants << author @mt.save! find('.card-content', text: "Wicked Message Card").click end scenario "marking complete" do checkbox = find("#task_completed") expect(checkbox).to_not be_checked @mt.completed = true @mt.save sleep 0.3 expect(checkbox).to be_checked end scenario "adding new comments" do sleep 0.3 @mt.comments.create body: "Hey-o", commenter_id: author.id within '.message-comments' do expect(page).to have_content "Hey-o" end end scenario "adding new participants" do sleep 0.3 @mt.participants << FactoryGirl.create(:user) @mt.save expect(all('.user-thumbnail').count).to eq(2) end end describe "tasks" do scenario "enter declarations" do edit_paper = EditPaperPage.visit paper edit_paper.view_card('Enter Declarations') sleep 0.3 survey = Survey.first survey.answer = "Hello!" survey.save expect(all('textarea').map(&:value)).to include("Hello!") end scenario "marking a task completed" do edit_paper = EditPaperPage.visit paper edit_paper.view_card('Upload Manuscript') checkbox = find("#task_completed") expect(checkbox).to_not be_checked upload_task.completed = true upload_task.save sleep 0.3 expect(checkbox).to be_checked end end scenario "On the edit paper page" do EditPaperPage.visit paper expect(page).to have_no_selector(".completed") upload_task.completed = true upload_task.save expect(page).to have_css(".card-completed", count: 1) end end Remove sleeps from event_stream_spec. require 'spec_helper' feature "Event streaming", js: true do let!(:author) { FactoryGirl.create :user } let!(:paper) { author.papers.create! short_title: 'foo bar', journal: Journal.create! } let(:upload_task) { author.papers.first.tasks_for_type(UploadManuscriptTask).first } before do sign_in_page = SignInPage.visit sign_in_page.sign_in author.email end scenario "On the dashboard page" do expect(page).to have_css(".dashboard-header") expect(page).to have_no_selector(".completed") upload_task.completed = true upload_task.save expect(page).to have_css(".card-completed", count: 1) end describe "manuscript manager" do before do edit_paper = EditPaperPage.visit paper edit_paper.navigate_to_task_manager end let(:submission_phase) { paper.phases.find_by_name("Submission Data") } scenario "creating a new message task" do mt = submission_phase.tasks.new title: "Wicked Message Card", type: "MessageTask", body: "Hi there!", role: "user" mt.participants << author mt.save! phase = all('.column').detect {|p| p.find('h2').text == "Submission Data" } within phase do expect(page).to have_content "Wicked Message Card" end end scenario "creating a new task" do submission_phase.tasks.create title: "Wicked Awesome Card", type: "Task", body: "Hi there!", role: "admin" phase = all('.column').detect {|p| p.find('h2').text == "Submission Data" } within phase do expect(page).to have_content "Wicked Awesome Card" end end end describe "message tasks" do before do edit_paper = EditPaperPage.visit paper edit_paper.navigate_to_task_manager submission_phase = paper.phases.find_by_name("Submission Data") @mt = submission_phase.tasks.new title: "Wicked Message Card", type: "MessageTask", body: "Hi there!", role: "user" @mt.participants << author @mt.save! find('.card-content', text: "Wicked Message Card").click expect(page).to have_css(".overlay-content") end scenario "marking complete" do expect(page).to have_css("#task_completed:not(:checked)") @mt.completed = true @mt.save expect(page).to have_css("#task_completed:checked") end scenario "adding new comments" do @mt.comments.create body: "Hey-o", commenter_id: author.id within '.message-comments' do expect(page).to have_content "Hey-o" end end scenario "adding new participants" do @mt.participants << FactoryGirl.create(:user) @mt.save expect(all('.user-thumbnail').count).to eq(2) end end describe "tasks" do scenario "enter declarations" do edit_paper = EditPaperPage.visit paper edit_paper.view_card('Enter Declarations') expect(page).to have_css(".overlay-content") survey = Survey.first survey.answer = "Hello!" survey.save expect(all('textarea').map(&:value)).to include("Hello!") end scenario "marking a task completed" do edit_paper = EditPaperPage.visit paper edit_paper.view_card('Upload Manuscript') expect(page).to have_css("#task_completed:not(:checked)") upload_task.completed = true upload_task.save expect(page).to have_css("#task_completed:checked") end end scenario "On the edit paper page" do EditPaperPage.visit paper expect(page).to have_no_selector(".completed") upload_task.completed = true upload_task.save expect(page).to have_css(".card-completed", count: 1) end end
require 'rails_helper' include ResponsiveHelpers describe "the header" do before :each do Capybara.current_driver = :selenium visit '/' end it "shows the Mapping PoliceViolence link" do expect(find('.navbar-header')).to have_content('MAPPING POLICE VIOLENCE') end it "links to the cities page" do within('.navbar-header') do click_link 'STATES & CITIES' end expect(page).to have_content 'City Comparison Tool' end it "links to the reports page" do within('.navbar-header') do click_link 'REPORTS' end expect(page).to have_content 'Police Violence Reports' end describe 'phone layout' do before :each do resize_window_to_mobile end it "shows the Mapping PoliceViolence link" do expect(find('.navbar-header')).to have_content('MAPPING POLICE VIOLENCE') end end end test wip require 'rails_helper' include ResponsiveHelpers describe "the header" do before :each do Capybara.current_driver = :selenium visit '/' end it "shows the Mapping PoliceViolence link" do expect(find('.navbar-header')).to have_content('MAPPING POLICE VIOLENCE') end it "links to the cities page" do within('.navbar-header') do click_link 'STATES & CITIES' end expect(page).to have_content 'City Comparison Tool' end it "links to the reports page" do within('.navbar-header') do click_link 'REPORTS' end expect(page).to have_content 'Police Violence Reports' end describe 'phone layout' do before :each do resize_window_to_mobile end # it "displays the hamburger icon" do # expect(page.should have_css("navbar-toggle[display:none]")) # end end end
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'spec_helper' describe Google::Compute::Server do before(:each) do @mock_api_client=mock(Google::APIClient, :authorization= =>{}, :auto_refresh_token= =>{}) @mock_api_client.stub!(:discovered_api).and_return(mock_compute) Google::APIClient.stub!(:new).and_return(@mock_api_client) end let(:client) do Google::Compute::Client.from_json(mock_data_file(Google::Compute::Client)) end it_should_behave_like Google::Compute::Resource it "#get should return an individual Server" do @mock_api_client.should_receive(:execute). with(:api_method=>mock_compute.instances.get, :parameters=>{:instance=>"mock-instance", :project=>"mock-project", :zone=>"mock-zone"},:body_object=>nil). and_return(mock_response(Google::Compute::Server)) instance = client.instances.get(:name=>'mock-instance', :zone=>"mock-zone") instance.should be_a_kind_of Google::Compute::Server instance.name.should eq('mock-instance') instance.disks.should be_a_kind_of(Array) instance.network_interfaces.should be_a_kind_of(Array) end it "#list should return an array of Servers" do @mock_api_client.should_receive(:execute). with(:api_method=>mock_compute.instances.list, :parameters=>{:project=>"mock-project", :zone=>"mock-zone"},:body_object=>nil). and_return(mock_response(Google::Compute::Server,true)) instances = client.instances.list(:zone=>"mock-zone") instances.should_not be_empty instances.all?{|i| i.is_a?(Google::Compute::Server)}.should be_true end it "#create should create an server" do project_url ='https://www.googleapis.com/compute/v1beta15/projects/google.com:wf-test' zone = project_url + '/zones/europe-west1-a' disk = project_url + zone + '/disks/temp-disk' machine_type = project_url + '/global/machineTypes/n1-highcpu-2' image = 'https://www.googleapis.com/compute/v1beta15/projects/google/global/images/centos-6-2-v20120326' network = project_url + '/global/networks/api-network' access_config = {"name" => "External NAT", "type" => "ONE_TO_ONE_NAT"} @mock_api_client.should_receive(:execute). with(:api_method=>mock_compute.instances.insert, :parameters=>{:project=>"mock-project", :zone=>"mock-zone"}, :body_object=>{:name =>'mock-instance', :image => image, :zone => "mock-zone", :disks => [disk], :machineType => machine_type, :metadata =>{'items'=>[{'key'=>'someKey','value'=>'someValue'}]}, :networkInterfaces => [{'network'=>network, 'accessConfigs' => [access_config] }] }). and_return(mock_response(Google::Compute::ZoneOperation)) o = client.instances.create(:name=>'mock-instance', :image=> image, :machineType =>machine_type, :disks=>[disk], :metadata=>{'items'=>[{'key'=>'someKey','value'=>'someValue'}]}, :zone=>"mock-zone", :networkInterfaces => [{'network'=>network, 'accessConfigs' => [access_config] }] ) end it "#delete should delete an server" do @mock_api_client.should_receive(:execute). with(:api_method=>mock_compute.instances.delete, :parameters=>{:project=>"mock-project", :instance=>'mock-instance', :zone=>"mock-zone"}, :body_object=>nil). and_return(mock_response(Google::Compute::ZoneOperation)) o = client.instances.delete(:instance=>'mock-instance', :zone=>"mock-zone") end describe "with a specific server" do before(:each) do Google::Compute::Resource.any_instance.stub(:update!) end let(:instance) do Google::Compute::Server.new(mock_hash(Google::Compute::Server). merge(:dispatcher=>client.dispatcher)) end it "#addAccessConfig should add access config to an existing server" do end it "#deleteAccessConfig should delete access config to an existing server" do end it "#serialPort should return serial port output of an existing server" do zone = "https://www.googleapis.com/compute/v1beta15/projects/mock-project/zones/mock-zone" @mock_api_client.should_receive(:execute). with(:api_method=>mock_compute.instances.get_serial_port_output, :parameters=>{:project=>"mock-project",:instance=>'mock-instance', :zone=>zone}, :body_object=>nil). and_return(mock_response(Google::Compute::SerialPortOutput)) instance.serial_port_output.should be_a_kind_of(Google::Compute::SerialPortOutput) instance.serial_port_output.contents.should_not be_empty end end end cleanup # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'spec_helper' describe Google::Compute::Server do before(:each) do @mock_api_client=mock(Google::APIClient, :authorization= =>{}, :auto_refresh_token= =>{}) @mock_api_client.stub!(:discovered_api).and_return(mock_compute) Google::APIClient.stub!(:new).and_return(@mock_api_client) end let(:client) do Google::Compute::Client.from_json(mock_data_file(Google::Compute::Client)) end it_should_behave_like Google::Compute::Resource it "#get should return an individual Server" do @mock_api_client.should_receive(:execute). with(:api_method=>mock_compute.instances.get, :parameters=>{:instance=>"mock-instance", :project=>"mock-project", :zone=>"mock-zone"},:body_object=>nil). and_return(mock_response(Google::Compute::Server)) instance = client.instances.get(:name=>'mock-instance', :zone=>"mock-zone") instance.should be_a_kind_of Google::Compute::Server instance.name.should eq('mock-instance') instance.disks.should be_a_kind_of(Array) instance.network_interfaces.should be_a_kind_of(Array) end it "#list should return an array of Servers" do @mock_api_client.should_receive(:execute). with(:api_method=>mock_compute.instances.list, :parameters=>{:project=>"mock-project", :zone=>"mock-zone"},:body_object=>nil). and_return(mock_response(Google::Compute::Server,true)) instances = client.instances.list(:zone=>"mock-zone") instances.should_not be_empty instances.all?{|i| i.is_a?(Google::Compute::Server)}.should be_true end it "#create should create an server" do project_url ='https://www.googleapis.com/compute/v1beta15/projects/mock-project' zone = project_url + '/zones/europe-west1-a' disk = project_url + zone + '/disks/mock-disk' machine_type = project_url + '/global/machineTypes/n1-highcpu-2' image = 'https://www.googleapis.com/compute/v1beta15/projects/centos-cloud/global/images/centos-6-vYYYYMMDD' network = project_url + '/global/networks/api-network' access_config = {"name" => "External NAT", "type" => "ONE_TO_ONE_NAT"} @mock_api_client.should_receive(:execute). with(:api_method=>mock_compute.instances.insert, :parameters=>{:project=>"mock-project", :zone=>"mock-zone"}, :body_object=>{:name =>'mock-instance', :image => image, :zone => "mock-zone", :disks => [disk], :machineType => machine_type, :metadata =>{'items'=>[{'key'=>'someKey','value'=>'someValue'}]}, :networkInterfaces => [{'network'=>network, 'accessConfigs' => [access_config] }] }). and_return(mock_response(Google::Compute::ZoneOperation)) o = client.instances.create(:name=>'mock-instance', :image=> image, :machineType =>machine_type, :disks=>[disk], :metadata=>{'items'=>[{'key'=>'someKey','value'=>'someValue'}]}, :zone=>"mock-zone", :networkInterfaces => [{'network'=>network, 'accessConfigs' => [access_config] }] ) end it "#delete should delete an server" do @mock_api_client.should_receive(:execute). with(:api_method=>mock_compute.instances.delete, :parameters=>{:project=>"mock-project", :instance=>'mock-instance', :zone=>"mock-zone"}, :body_object=>nil). and_return(mock_response(Google::Compute::ZoneOperation)) o = client.instances.delete(:instance=>'mock-instance', :zone=>"mock-zone") end describe "with a specific server" do before(:each) do Google::Compute::Resource.any_instance.stub(:update!) end let(:instance) do Google::Compute::Server.new(mock_hash(Google::Compute::Server). merge(:dispatcher=>client.dispatcher)) end it "#addAccessConfig should add access config to an existing server" do end it "#deleteAccessConfig should delete access config to an existing server" do end it "#serialPort should return serial port output of an existing server" do zone = "https://www.googleapis.com/compute/v1beta15/projects/mock-project/zones/mock-zone" @mock_api_client.should_receive(:execute). with(:api_method=>mock_compute.instances.get_serial_port_output, :parameters=>{:project=>"mock-project",:instance=>'mock-instance', :zone=>zone}, :body_object=>nil). and_return(mock_response(Google::Compute::SerialPortOutput)) instance.serial_port_output.should be_a_kind_of(Google::Compute::SerialPortOutput) instance.serial_port_output.contents.should_not be_empty end end end
# frozen_string_literal: true require "spec_helper" describe GraphQL::Authorization do module AuthTest class Box attr_reader :value def initialize(value:) @value = value end end class BaseArgument < GraphQL::Schema::Argument def visible?(context) super && (context[:hide] ? @name != "hidden" : true) end def accessible?(context) super && (context[:hide] ? @name != "inaccessible" : true) end def authorized?(parent_object, value, context) super && parent_object != :hide2 end end class BaseInputObjectArgument < BaseArgument def authorized?(parent_object, value, context) super && parent_object != :hide3 end end class BaseInputObject < GraphQL::Schema::InputObject argument_class BaseInputObjectArgument end class BaseField < GraphQL::Schema::Field def initialize(*args, edge_class: nil, **kwargs, &block) @edge_class = edge_class super(*args, **kwargs, &block) end def to_graphql field_defn = super if @edge_class field_defn.edge_class = @edge_class end field_defn end argument_class BaseArgument def visible?(context) super && (context[:hide] ? @name != "hidden" : true) end def accessible?(context) super && (context[:hide] ? @name != "inaccessible" : true) end def authorized?(object, args, context) if object == :raise raise GraphQL::UnauthorizedFieldError.new("raised authorized field error", object: object) end super && object != :hide && object != :replace end end class BaseObject < GraphQL::Schema::Object field_class BaseField end module BaseInterface include GraphQL::Schema::Interface end class BaseEnumValue < GraphQL::Schema::EnumValue def initialize(*args, role: nil, **kwargs) @role = role super(*args, **kwargs) end def visible?(context) super && (context[:hide] ? @role != :hidden : true) end end class BaseEnum < GraphQL::Schema::Enum enum_value_class(BaseEnumValue) end module HiddenInterface include BaseInterface def self.visible?(ctx) super && !ctx[:hide] end def self.resolve_type(obj, ctx) HiddenObject end end module HiddenDefaultInterface include BaseInterface # visible? will call the super method def self.resolve_type(obj, ctx) HiddenObject end end class HiddenObject < BaseObject implements HiddenInterface implements HiddenDefaultInterface def self.visible?(ctx) super && !ctx[:hide] end field :some_field, String, null: true end class RelayObject < BaseObject def self.visible?(ctx) super && !ctx[:hidden_relay] end def self.accessible?(ctx) super && !ctx[:inaccessible_relay] end def self.authorized?(_val, ctx) super && !ctx[:unauthorized_relay] end field :some_field, String, null: true end # TODO test default behavior for abstract types, # that they check their concrete types module InaccessibleInterface include BaseInterface def self.accessible?(ctx) super && !ctx[:hide] end def self.resolve_type(obj, ctx) InaccessibleObject end end module InaccessibleDefaultInterface include BaseInterface # accessible? will call the super method def self.resolve_type(obj, ctx) InaccessibleObject end field :some_field, String, null: true end class InaccessibleObject < BaseObject implements InaccessibleInterface implements InaccessibleDefaultInterface def self.accessible?(ctx) super && !ctx[:hide] end field :some_field, String, null: true end class UnauthorizedObject < BaseObject def self.authorized?(value, context) if context[:raise] raise GraphQL::UnauthorizedError.new("raised authorized object error", object: value.object) end super && !context[:hide] end field :value, String, null: false, method: :itself end class UnauthorizedBox < BaseObject # Hide `"a"` def self.authorized?(value, context) super && value != "a" end field :value, String, null: false, method: :itself end module UnauthorizedInterface include BaseInterface def self.resolve_type(obj, ctx) if obj.is_a?(String) UnauthorizedCheckBox else raise "Unexpected value: #{obj.inspect}" end end end class UnauthorizedCheckBox < BaseObject implements UnauthorizedInterface # This authorized check returns a lazy object, it should be synced by the runtime. def self.authorized?(value, context) if !value.is_a?(String) raise "Unexpected box value: #{value.inspect}" end is_authed = super && value != "a" # Make it many levels nested just to make sure we support nested lazy objects Box.new(value: Box.new(value: Box.new(value: Box.new(value: is_authed)))) end field :value, String, null: false, method: :itself end class IntegerObject < BaseObject def self.authorized?(obj, ctx) if !obj.is_a?(Integer) raise "Unexpected IntegerObject: #{obj}" end is_allowed = !(ctx[:unauthorized_relay] || obj == ctx[:exclude_integer]) Box.new(value: Box.new(value: is_allowed)) end field :value, Integer, null: false, method: :itself end class IntegerObjectEdge < GraphQL::Types::Relay::BaseEdge node_type(IntegerObject) end class IntegerObjectConnection < GraphQL::Types::Relay::BaseConnection edge_type(IntegerObjectEdge) end # This object responds with `replaced => false`, # but if its replacement value is used, it gives `replaced => true` class Replaceable def replacement { replaced: true } end def replaced false end end class ReplacedObject < BaseObject def self.authorized?(obj, ctx) super && !ctx[:replace_me] end field :replaced, Boolean, null: false end class LandscapeFeature < BaseEnum value "MOUNTAIN" value "STREAM", role: :unauthorized value "FIELD", role: :inaccessible value "TAR_PIT", role: :hidden end class AddInput < BaseInputObject argument :left, Integer, required: true argument :right, Integer, required: true end class Query < BaseObject def self.authorized?(obj, ctx) !ctx[:query_unauthorized] end field :hidden, Integer, null: false field :unauthorized, Integer, null: true, method: :itself field :int2, Integer, null: true do argument :int, Integer, required: false argument :hidden, Integer, required: false argument :inaccessible, Integer, required: false argument :unauthorized, Integer, required: false end def int2(**args) args[:unauthorized] || 1 end field :landscape_feature, LandscapeFeature, null: false do argument :string, String, required: false argument :enum, LandscapeFeature, required: false end def landscape_feature(string: nil, enum: nil) string || enum end field :landscape_features, [LandscapeFeature], null: false do argument :strings, [String], required: false argument :enums, [LandscapeFeature], required: false end def landscape_features(strings: [], enums: []) strings + enums end def empty_array; []; end field :hidden_object, HiddenObject, null: false, resolver_method: :itself field :hidden_interface, HiddenInterface, null: false, resolver_method: :itself field :hidden_default_interface, HiddenDefaultInterface, null: false, resolver_method: :itself field :hidden_connection, RelayObject.connection_type, null: :false, resolver_method: :empty_array field :hidden_edge, RelayObject.edge_type, null: :false, resolver_method: :edge_object field :inaccessible, Integer, null: false, method: :object_id field :inaccessible_object, InaccessibleObject, null: false, resolver_method: :itself field :inaccessible_interface, InaccessibleInterface, null: false, resolver_method: :itself field :inaccessible_default_interface, InaccessibleDefaultInterface, null: false, resolver_method: :itself field :inaccessible_connection, RelayObject.connection_type, null: :false, resolver_method: :empty_array field :inaccessible_edge, RelayObject.edge_type, null: :false, resolver_method: :edge_object field :unauthorized_object, UnauthorizedObject, null: true, resolver_method: :itself field :unauthorized_connection, RelayObject.connection_type, null: false, resolver_method: :array_with_item field :unauthorized_edge, RelayObject.edge_type, null: false, resolver_method: :edge_object def edge_object OpenStruct.new(node: 100) end def array_with_item [1] end field :unauthorized_lazy_box, UnauthorizedBox, null: true do argument :value, String, required: true end def unauthorized_lazy_box(value:) # Make it extra nested, just for good measure. Box.new(value: Box.new(value: value)) end field :unauthorized_list_items, [UnauthorizedObject], null: true def unauthorized_list_items [self, self] end field :unauthorized_lazy_check_box, UnauthorizedCheckBox, null: true, resolver_method: :unauthorized_lazy_box do argument :value, String, required: true end field :unauthorized_interface, UnauthorizedInterface, null: true, resolver_method: :unauthorized_lazy_box do argument :value, String, required: true end field :unauthorized_lazy_list_interface, [UnauthorizedInterface, null: true], null: true def unauthorized_lazy_list_interface ["z", Box.new(value: Box.new(value: "z2")), "a", Box.new(value: "a")] end field :integers, IntegerObjectConnection, null: false def integers [1,2,3] end field :lazy_integers, IntegerObjectConnection, null: false def lazy_integers Box.new(value: Box.new(value: [1,2,3])) end field :replaced_object, ReplacedObject, null: false def replaced_object Replaceable.new end field :add_inputs, Integer, null: true do argument :input, AddInput, required: true end def add_inputs(input:) input[:left] + input[:right] end end class DoHiddenStuff < GraphQL::Schema::RelayClassicMutation def self.visible?(ctx) super && (ctx[:hidden_mutation] ? false : true) end end class DoHiddenStuff2 < GraphQL::Schema::Mutation def self.visible?(ctx) super && !ctx[:hidden_mutation] end field :some_return_field, String, null: true end class DoInaccessibleStuff < GraphQL::Schema::RelayClassicMutation def self.accessible?(ctx) super && (ctx[:inaccessible_mutation] ? false : true) end end class DoUnauthorizedStuff < GraphQL::Schema::RelayClassicMutation def self.authorized?(obj, ctx) super && (ctx[:unauthorized_mutation] ? false : true) end end class Mutation < BaseObject field :do_hidden_stuff, mutation: DoHiddenStuff field :do_hidden_stuff2, mutation: DoHiddenStuff2 field :do_inaccessible_stuff, mutation: DoInaccessibleStuff field :do_unauthorized_stuff, mutation: DoUnauthorizedStuff end class Schema < GraphQL::Schema if TESTING_INTERPRETER use GraphQL::Execution::Interpreter use GraphQL::Analysis::AST else # Opt in to accessible? checks query_analyzer GraphQL::Authorization::Analyzer end query(Query) mutation(Mutation) lazy_resolve(Box, :value) def self.unauthorized_object(err) if err.object.respond_to?(:replacement) err.object.replacement elsif err.object == :replace 33 elsif err.object == :raise_from_object raise GraphQL::ExecutionError, err.message else raise GraphQL::ExecutionError, "Unauthorized #{err.type.graphql_name}: #{err.object.inspect}" end end # use GraphQL::Backtrace end class SchemaWithFieldHook < GraphQL::Schema if TESTING_INTERPRETER use GraphQL::Execution::Interpreter use GraphQL::Analysis::AST end query(Query) def self.unauthorized_field(err) if err.object == :replace 42 elsif err.object == :raise raise GraphQL::ExecutionError, "#{err.message} in field #{err.field.graphql_name}" else raise GraphQL::ExecutionError, "Unauthorized field #{err.field.graphql_name} on #{err.type.graphql_name}: #{err.object}" end end end end def auth_execute(*args) AuthTest::Schema.execute(*args) end describe "applying the visible? method" do it "works in queries" do res = auth_execute(" { int int2 } ", context: { hide: true }) assert_equal 1, res["errors"].size end it "applies return type visibility to fields" do error_queries = { "hiddenObject" => "{ hiddenObject { __typename } }", "hiddenInterface" => "{ hiddenInterface { __typename } }", "hiddenDefaultInterface" => "{ hiddenDefaultInterface { __typename } }", } error_queries.each do |name, q| hidden_res = auth_execute(q, context: { hide: true}) assert_equal ["Field '#{name}' doesn't exist on type 'Query'"], hidden_res["errors"].map { |e| e["message"] } visible_res = auth_execute(q) # Both fields exist; the interface resolves to the object type, though assert_equal "HiddenObject", visible_res["data"][name]["__typename"] end end it "uses the mutation for derived fields, inputs and outputs" do query = "mutation { doHiddenStuff(input: {}) { __typename } }" res = auth_execute(query, context: { hidden_mutation: true }) assert_equal ["Field 'doHiddenStuff' doesn't exist on type 'Mutation'"], res["errors"].map { |e| e["message"] } # `#resolve` isn't implemented, so this errors out: assert_raises GraphQL::RequiredImplementationMissingError do auth_execute(query) end introspection_q = <<-GRAPHQL { t1: __type(name: "DoHiddenStuffInput") { name } t2: __type(name: "DoHiddenStuffPayload") { name } } GRAPHQL hidden_introspection_res = auth_execute(introspection_q, context: { hidden_mutation: true }) assert_nil hidden_introspection_res["data"]["t1"] assert_nil hidden_introspection_res["data"]["t2"] visible_introspection_res = auth_execute(introspection_q) assert_equal "DoHiddenStuffInput", visible_introspection_res["data"]["t1"]["name"] assert_equal "DoHiddenStuffPayload", visible_introspection_res["data"]["t2"]["name"] end it "works with Schema::Mutation" do query = "mutation { doHiddenStuff2 { __typename } }" res = auth_execute(query, context: { hidden_mutation: true }) assert_equal ["Field 'doHiddenStuff2' doesn't exist on type 'Mutation'"], res["errors"].map { |e| e["message"] } # `#resolve` isn't implemented, so this errors out: assert_raises GraphQL::RequiredImplementationMissingError do auth_execute(query) end end it "uses the base type for edges and connections" do query = <<-GRAPHQL { hiddenConnection { __typename } hiddenEdge { __typename } } GRAPHQL hidden_res = auth_execute(query, context: { hidden_relay: true }) assert_equal 2, hidden_res["errors"].size visible_res = auth_execute(query) assert_equal "RelayObjectConnection", visible_res["data"]["hiddenConnection"]["__typename"] assert_equal "RelayObjectEdge", visible_res["data"]["hiddenEdge"]["__typename"] end it "treats hidden enum values as non-existant, even in lists" do hidden_res_1 = auth_execute <<-GRAPHQL, context: { hide: true } { landscapeFeature(enum: TAR_PIT) } GRAPHQL assert_equal ["Argument 'enum' on Field 'landscapeFeature' has an invalid value (TAR_PIT). Expected type 'LandscapeFeature'."], hidden_res_1["errors"].map { |e| e["message"] } hidden_res_2 = auth_execute <<-GRAPHQL, context: { hide: true } { landscapeFeatures(enums: [STREAM, TAR_PIT]) } GRAPHQL assert_equal ["Argument 'enums' on Field 'landscapeFeatures' has an invalid value ([STREAM, TAR_PIT]). Expected type '[LandscapeFeature!]'."], hidden_res_2["errors"].map { |e| e["message"] } success_res = auth_execute <<-GRAPHQL, context: { hide: false } { landscapeFeature(enum: TAR_PIT) landscapeFeatures(enums: [STREAM, TAR_PIT]) } GRAPHQL assert_equal "TAR_PIT", success_res["data"]["landscapeFeature"] assert_equal ["STREAM", "TAR_PIT"], success_res["data"]["landscapeFeatures"] end it "refuses to resolve to hidden enum values" do assert_raises(GraphQL::EnumType::UnresolvedValueError) do auth_execute <<-GRAPHQL, context: { hide: true } { landscapeFeature(string: "TAR_PIT") } GRAPHQL end assert_raises(GraphQL::EnumType::UnresolvedValueError) do auth_execute <<-GRAPHQL, context: { hide: true } { landscapeFeatures(strings: ["STREAM", "TAR_PIT"]) } GRAPHQL end end it "works in introspection" do res = auth_execute <<-GRAPHQL, context: { hide: true, hidden_mutation: true } { query: __type(name: "Query") { fields { name args { name } } } hiddenObject: __type(name: "HiddenObject") { name } hiddenInterface: __type(name: "HiddenInterface") { name } landscapeFeatures: __type(name: "LandscapeFeature") { enumValues { name } } } GRAPHQL query_field_names = res["data"]["query"]["fields"].map { |f| f["name"] } refute_includes query_field_names, "int" int2_arg_names = res["data"]["query"]["fields"].find { |f| f["name"] == "int2" }["args"].map { |a| a["name"] } assert_equal ["int", "inaccessible", "unauthorized"], int2_arg_names assert_nil res["data"]["hiddenObject"] assert_nil res["data"]["hiddenInterface"] visible_landscape_features = res["data"]["landscapeFeatures"]["enumValues"].map { |v| v["name"] } assert_equal ["MOUNTAIN", "STREAM", "FIELD"], visible_landscape_features end end if !TESTING_INTERPRETER # This isn't supported when running the interpreter describe "applying the accessible? method" do it "works with fields and arguments" do queries = { "{ inaccessible }" => ["Some fields in this query are not accessible: inaccessible"], "{ int2(inaccessible: 1) }" => ["Some fields in this query are not accessible: int2"], } queries.each do |query_str, errors| res = auth_execute(query_str, context: { hide: true }) assert_equal errors, res.fetch("errors").map { |e| e["message"] } res = auth_execute(query_str, context: { hide: false }) refute res.key?("errors") end end it "works with return types" do queries = { "{ inaccessibleObject { __typename } }" => ["Some fields in this query are not accessible: inaccessibleObject"], "{ inaccessibleInterface { __typename } }" => ["Some fields in this query are not accessible: inaccessibleInterface"], "{ inaccessibleDefaultInterface { __typename } }" => ["Some fields in this query are not accessible: inaccessibleDefaultInterface"], } queries.each do |query_str, errors| res = auth_execute(query_str, context: { hide: true }) assert_equal errors, res["errors"].map { |e| e["message"] } res = auth_execute(query_str, context: { hide: false }) refute res.key?("errors") end end it "works with mutations" do query = "mutation { doInaccessibleStuff(input: {}) { __typename } }" res = auth_execute(query, context: { inaccessible_mutation: true }) assert_equal ["Some fields in this query are not accessible: doInaccessibleStuff"], res["errors"].map { |e| e["message"] } assert_raises GraphQL::RequiredImplementationMissingError do auth_execute(query) end end it "works with edges and connections" do query = <<-GRAPHQL { inaccessibleConnection { __typename } inaccessibleEdge { __typename } } GRAPHQL inaccessible_res = auth_execute(query, context: { inaccessible_relay: true }) assert_equal ["Some fields in this query are not accessible: inaccessibleConnection, inaccessibleEdge"], inaccessible_res["errors"].map { |e| e["message"] } accessible_res = auth_execute(query) refute accessible_res.key?("errors") end end end describe "applying the authorized? method" do it "halts on unauthorized objects, replacing the object with nil" do query = "{ unauthorizedObject { __typename } }" hidden_response = auth_execute(query, context: { hide: true }) assert_nil hidden_response["data"].fetch("unauthorizedObject") visible_response = auth_execute(query, context: {}) assert_equal({ "__typename" => "UnauthorizedObject" }, visible_response["data"]["unauthorizedObject"]) end it "halts on unauthorized mutations" do query = "mutation { doUnauthorizedStuff(input: {}) { __typename } }" res = auth_execute(query, context: { unauthorized_mutation: true }) assert_nil res["data"].fetch("doUnauthorizedStuff") assert_raises GraphQL::RequiredImplementationMissingError do auth_execute(query) end end describe "field level authorization" do describe "unauthorized field" do describe "with an unauthorized field hook configured" do describe "when the hook returns a value" do it "replaces the response with the return value of the unauthorized field hook" do query = "{ unauthorized }" response = AuthTest::SchemaWithFieldHook.execute(query, root_value: :replace) assert_equal 42, response["data"].fetch("unauthorized") end end describe "when the field hook raises an error" do it "returns nil" do query = "{ unauthorized }" response = AuthTest::SchemaWithFieldHook.execute(query, root_value: :hide) assert_nil response["data"].fetch("unauthorized") end it "adds the error to the errors key" do query = "{ unauthorized }" response = AuthTest::SchemaWithFieldHook.execute(query, root_value: :hide) assert_equal ["Unauthorized field unauthorized on Query: hide"], response["errors"].map { |e| e["message"] } end end describe "when the field authorization raises an UnauthorizedFieldError" do it "receives the raised error" do query = "{ unauthorized }" response = AuthTest::SchemaWithFieldHook.execute(query, root_value: :raise) assert_equal ["raised authorized field error in field unauthorized"], response["errors"].map { |e| e["message"] } end end end describe "with an unauthorized field hook not configured" do describe "When the object hook replaces the field" do it "delegates to the unauthorized object hook, which replaces the object" do query = "{ unauthorized }" response = AuthTest::Schema.execute(query, root_value: :replace) assert_equal 33, response["data"].fetch("unauthorized") end end describe "When the object hook raises an error" do it "returns nil" do query = "{ unauthorized }" response = AuthTest::Schema.execute(query, root_value: :hide) assert_nil response["data"].fetch("unauthorized") end it "adds the error to the errors key" do query = "{ unauthorized }" response = AuthTest::Schema.execute(query, root_value: :hide) assert_equal ["Unauthorized Query: :hide"], response["errors"].map { |e| e["message"] } end end end end describe "authorized field" do it "returns the field data" do query = "{ unauthorized }" response = AuthTest::SchemaWithFieldHook.execute(query, root_value: 1) assert_equal 1, response["data"].fetch("unauthorized") end end end it "halts on unauthorized fields, using the parent object" do query = "{ unauthorized }" hidden_response = auth_execute(query, root_value: :hide) assert_nil hidden_response["data"].fetch("unauthorized") visible_response = auth_execute(query, root_value: 1) assert_equal 1, visible_response["data"]["unauthorized"] end it "halts on unauthorized arguments, using the parent object" do query = "{ int2(unauthorized: 5) }" hidden_response = auth_execute(query, root_value: :hide2) assert_nil hidden_response["data"].fetch("int2") visible_response = auth_execute(query) assert_equal 5, visible_response["data"]["int2"] end it "halts on unauthorized input object arguments, using the parent object" do query = "{ addInputs(input: { left: 3, right: 2 }) }" hidden_field_argument_response = auth_execute(query, root_value: :hide2) assert_nil hidden_field_argument_response["data"].fetch("addInputs") assert_equal ["Unauthorized Query: :hide2"], hidden_field_argument_response["errors"].map { |e| e["message"] } hidden_input_obj_argument_response = auth_execute(query, root_value: :hide3) assert_nil hidden_input_obj_argument_response["data"].fetch("addInputs") assert_equal ["Unauthorized Query: :hide3"], hidden_input_obj_argument_response["errors"].map { |e| e["message"] } visible_response = auth_execute(query) assert_equal 5, visible_response["data"]["addInputs"] refute visible_response.key?("errors") end it "works with edges and connections" do query = <<-GRAPHQL { unauthorizedConnection { __typename edges { __typename node { __typename } } nodes { __typename } } unauthorizedEdge { __typename node { __typename } } } GRAPHQL unauthorized_res = auth_execute(query, context: { unauthorized_relay: true }) conn = unauthorized_res["data"].fetch("unauthorizedConnection") assert_equal "RelayObjectConnection", conn.fetch("__typename") # This is tricky: the previous behavior was to replace the _whole_ # list with `nil`. This was due to an implementation detail: # The list field's return value (an array of integers) was wrapped # _before_ returning, and during this wrapping, a cascading error # caused the entire field to be nilled out. # # In the interpreter, each list item is contained and the error doesn't propagate # up to the whole list. # # Originally, I thought that this was a _feature_ that obscured list entries. # But really, look at the test below: you don't get this "feature" if # you use `edges { node }`, so it can't be relied on in any way. # # All that to say, in the interpreter, `nodes` and `edges { node }` behave # the same. # # TODO revisit the docs for this. failed_nodes_value = TESTING_INTERPRETER ? [nil] : nil assert_equal failed_nodes_value, conn.fetch("nodes") assert_equal [{"node" => nil, "__typename" => "RelayObjectEdge"}], conn.fetch("edges") edge = unauthorized_res["data"].fetch("unauthorizedEdge") assert_nil edge.fetch("node") assert_equal "RelayObjectEdge", edge["__typename"] unauthorized_object_paths = [ ["unauthorizedConnection", "edges", 0, "node"], TESTING_INTERPRETER ? ["unauthorizedConnection", "nodes", 0] : ["unauthorizedConnection", "nodes"], ["unauthorizedEdge", "node"] ] assert_equal unauthorized_object_paths, unauthorized_res["errors"].map { |e| e["path"] } authorized_res = auth_execute(query) conn = authorized_res["data"].fetch("unauthorizedConnection") assert_equal "RelayObjectConnection", conn.fetch("__typename") assert_equal [{"__typename"=>"RelayObject"}], conn.fetch("nodes") assert_equal [{"node" => {"__typename" => "RelayObject"}, "__typename" => "RelayObjectEdge"}], conn.fetch("edges") edge = authorized_res["data"].fetch("unauthorizedEdge") assert_equal "RelayObject", edge.fetch("node").fetch("__typename") assert_equal "RelayObjectEdge", edge["__typename"] end it "authorizes _after_ resolving lazy objects" do query = <<-GRAPHQL { a: unauthorizedLazyBox(value: "a") { value } b: unauthorizedLazyBox(value: "b") { value } } GRAPHQL unauthorized_res = auth_execute(query) assert_nil unauthorized_res["data"].fetch("a") assert_equal "b", unauthorized_res["data"]["b"]["value"] end it "authorizes items in a list" do query = <<-GRAPHQL { unauthorizedListItems { __typename } } GRAPHQL unauthorized_res = auth_execute(query, context: { hide: true }) assert_nil unauthorized_res["data"]["unauthorizedListItems"] authorized_res = auth_execute(query, context: { hide: false }) assert_equal 2, authorized_res["data"]["unauthorizedListItems"].size end it "syncs lazy objects from authorized? checks" do query = <<-GRAPHQL { a: unauthorizedLazyCheckBox(value: "a") { value } b: unauthorizedLazyCheckBox(value: "b") { value } } GRAPHQL unauthorized_res = auth_execute(query) assert_nil unauthorized_res["data"].fetch("a") assert_equal "b", unauthorized_res["data"]["b"]["value"] # Also, the custom handler was called: assert_equal ["Unauthorized UnauthorizedCheckBox: \"a\""], unauthorized_res["errors"].map { |e| e["message"] } end it "Works for lazy connections" do query = <<-GRAPHQL { lazyIntegers { edges { node { value } } } } GRAPHQL res = auth_execute(query) assert_equal [1,2,3], res["data"]["lazyIntegers"]["edges"].map { |e| e["node"]["value"] } end it "Works for eager connections" do query = <<-GRAPHQL { integers { edges { node { value } } } } GRAPHQL res = auth_execute(query) assert_equal [1,2,3], res["data"]["integers"]["edges"].map { |e| e["node"]["value"] } end it "filters out individual nodes by value" do query = <<-GRAPHQL { integers { edges { node { value } } } } GRAPHQL res = auth_execute(query, context: { exclude_integer: 1 }) assert_equal [nil,2,3], res["data"]["integers"]["edges"].map { |e| e["node"] && e["node"]["value"] } assert_equal ["Unauthorized IntegerObject: 1"], res["errors"].map { |e| e["message"] } end it "works with lazy values / interfaces" do query = <<-GRAPHQL query($value: String!){ unauthorizedInterface(value: $value) { ... on UnauthorizedCheckBox { value } } } GRAPHQL res = auth_execute(query, variables: { value: "a"}) assert_nil res["data"]["unauthorizedInterface"] res2 = auth_execute(query, variables: { value: "b"}) assert_equal "b", res2["data"]["unauthorizedInterface"]["value"] end it "works with lazy values / lists of interfaces" do query = <<-GRAPHQL { unauthorizedLazyListInterface { ... on UnauthorizedCheckBox { value } } } GRAPHQL res = auth_execute(query) # An error from two, values from the others assert_equal ["Unauthorized UnauthorizedCheckBox: \"a\"", "Unauthorized UnauthorizedCheckBox: \"a\""], res["errors"].map { |e| e["message"] } assert_equal [{"value" => "z"}, {"value" => "z2"}, nil, nil], res["data"]["unauthorizedLazyListInterface"] end describe "with an unauthorized field hook configured" do it "replaces objects from the unauthorized_object hook" do query = "{ replacedObject { replaced } }" res = auth_execute(query, context: { replace_me: true }) assert_equal true, res["data"]["replacedObject"]["replaced"] res = auth_execute(query, context: { replace_me: false }) assert_equal false, res["data"]["replacedObject"]["replaced"] end it "works when the query hook returns false and there's no root object" do query = "{ __typename }" res = auth_execute(query) assert_equal "Query", res["data"]["__typename"] unauth_res = auth_execute(query, context: { query_unauthorized: true }) assert_nil unauth_res["data"] assert_equal [{"message"=>"Unauthorized Query: nil"}], unauth_res["errors"] end describe "when the object authorization raises an UnauthorizedFieldError" do it "receives the raised error" do query = "{ unauthorizedObject { value } }" response = auth_execute(query, context: { raise: true }, root_value: :raise_from_object) assert_equal ["raised authorized object error"], response["errors"].map { |e| e["message"] } end end end end describe "returning false" do class FalseSchema < GraphQL::Schema class Query < GraphQL::Schema::Object def self.authorized?(obj, ctx) false end field :int, Integer, null: false def int 1 end end query(Query) if TESTING_INTERPRETER use GraphQL::Execution::Interpreter use GraphQL::Analysis::AST end end it "works out-of-the-box" do res = FalseSchema.execute("{ int }") assert_nil res.fetch("data") refute res.key?("errors") end end end Revert "Authorize arguments of input objects, too" # frozen_string_literal: true require "spec_helper" describe GraphQL::Authorization do module AuthTest class Box attr_reader :value def initialize(value:) @value = value end end class BaseArgument < GraphQL::Schema::Argument def visible?(context) super && (context[:hide] ? @name != "hidden" : true) end def accessible?(context) super && (context[:hide] ? @name != "inaccessible" : true) end def authorized?(parent_object, value, context) super && parent_object != :hide2 end end <<<<<<< HEAD class BaseInputObjectArgument < BaseArgument def authorized?(parent_object, value, context) super && parent_object != :hide3 end end class BaseInputObject < GraphQL::Schema::InputObject argument_class BaseInputObjectArgument end ======= >>>>>>> Revert "Authorize arguments of input objects, too" class BaseField < GraphQL::Schema::Field def initialize(*args, edge_class: nil, **kwargs, &block) @edge_class = edge_class super(*args, **kwargs, &block) end def to_graphql field_defn = super if @edge_class field_defn.edge_class = @edge_class end field_defn end argument_class BaseArgument def visible?(context) super && (context[:hide] ? @name != "hidden" : true) end def accessible?(context) super && (context[:hide] ? @name != "inaccessible" : true) end def authorized?(object, args, context) if object == :raise raise GraphQL::UnauthorizedFieldError.new("raised authorized field error", object: object) end super && object != :hide && object != :replace end end class BaseObject < GraphQL::Schema::Object field_class BaseField end module BaseInterface include GraphQL::Schema::Interface end class BaseEnumValue < GraphQL::Schema::EnumValue def initialize(*args, role: nil, **kwargs) @role = role super(*args, **kwargs) end def visible?(context) super && (context[:hide] ? @role != :hidden : true) end end class BaseEnum < GraphQL::Schema::Enum enum_value_class(BaseEnumValue) end module HiddenInterface include BaseInterface def self.visible?(ctx) super && !ctx[:hide] end def self.resolve_type(obj, ctx) HiddenObject end end module HiddenDefaultInterface include BaseInterface # visible? will call the super method def self.resolve_type(obj, ctx) HiddenObject end end class HiddenObject < BaseObject implements HiddenInterface implements HiddenDefaultInterface def self.visible?(ctx) super && !ctx[:hide] end field :some_field, String, null: true end class RelayObject < BaseObject def self.visible?(ctx) super && !ctx[:hidden_relay] end def self.accessible?(ctx) super && !ctx[:inaccessible_relay] end def self.authorized?(_val, ctx) super && !ctx[:unauthorized_relay] end field :some_field, String, null: true end # TODO test default behavior for abstract types, # that they check their concrete types module InaccessibleInterface include BaseInterface def self.accessible?(ctx) super && !ctx[:hide] end def self.resolve_type(obj, ctx) InaccessibleObject end end module InaccessibleDefaultInterface include BaseInterface # accessible? will call the super method def self.resolve_type(obj, ctx) InaccessibleObject end field :some_field, String, null: true end class InaccessibleObject < BaseObject implements InaccessibleInterface implements InaccessibleDefaultInterface def self.accessible?(ctx) super && !ctx[:hide] end field :some_field, String, null: true end class UnauthorizedObject < BaseObject def self.authorized?(value, context) if context[:raise] raise GraphQL::UnauthorizedError.new("raised authorized object error", object: value.object) end super && !context[:hide] end field :value, String, null: false, method: :itself end class UnauthorizedBox < BaseObject # Hide `"a"` def self.authorized?(value, context) super && value != "a" end field :value, String, null: false, method: :itself end module UnauthorizedInterface include BaseInterface def self.resolve_type(obj, ctx) if obj.is_a?(String) UnauthorizedCheckBox else raise "Unexpected value: #{obj.inspect}" end end end class UnauthorizedCheckBox < BaseObject implements UnauthorizedInterface # This authorized check returns a lazy object, it should be synced by the runtime. def self.authorized?(value, context) if !value.is_a?(String) raise "Unexpected box value: #{value.inspect}" end is_authed = super && value != "a" # Make it many levels nested just to make sure we support nested lazy objects Box.new(value: Box.new(value: Box.new(value: Box.new(value: is_authed)))) end field :value, String, null: false, method: :itself end class IntegerObject < BaseObject def self.authorized?(obj, ctx) if !obj.is_a?(Integer) raise "Unexpected IntegerObject: #{obj}" end is_allowed = !(ctx[:unauthorized_relay] || obj == ctx[:exclude_integer]) Box.new(value: Box.new(value: is_allowed)) end field :value, Integer, null: false, method: :itself end class IntegerObjectEdge < GraphQL::Types::Relay::BaseEdge node_type(IntegerObject) end class IntegerObjectConnection < GraphQL::Types::Relay::BaseConnection edge_type(IntegerObjectEdge) end # This object responds with `replaced => false`, # but if its replacement value is used, it gives `replaced => true` class Replaceable def replacement { replaced: true } end def replaced false end end class ReplacedObject < BaseObject def self.authorized?(obj, ctx) super && !ctx[:replace_me] end field :replaced, Boolean, null: false end class LandscapeFeature < BaseEnum value "MOUNTAIN" value "STREAM", role: :unauthorized value "FIELD", role: :inaccessible value "TAR_PIT", role: :hidden end class Query < BaseObject def self.authorized?(obj, ctx) !ctx[:query_unauthorized] end field :hidden, Integer, null: false field :unauthorized, Integer, null: true, method: :itself field :int2, Integer, null: true do argument :int, Integer, required: false argument :hidden, Integer, required: false argument :inaccessible, Integer, required: false argument :unauthorized, Integer, required: false end def int2(**args) args[:unauthorized] || 1 end field :landscape_feature, LandscapeFeature, null: false do argument :string, String, required: false argument :enum, LandscapeFeature, required: false end def landscape_feature(string: nil, enum: nil) string || enum end field :landscape_features, [LandscapeFeature], null: false do argument :strings, [String], required: false argument :enums, [LandscapeFeature], required: false end def landscape_features(strings: [], enums: []) strings + enums end def empty_array; []; end field :hidden_object, HiddenObject, null: false, resolver_method: :itself field :hidden_interface, HiddenInterface, null: false, resolver_method: :itself field :hidden_default_interface, HiddenDefaultInterface, null: false, resolver_method: :itself field :hidden_connection, RelayObject.connection_type, null: :false, resolver_method: :empty_array field :hidden_edge, RelayObject.edge_type, null: :false, resolver_method: :edge_object field :inaccessible, Integer, null: false, method: :object_id field :inaccessible_object, InaccessibleObject, null: false, resolver_method: :itself field :inaccessible_interface, InaccessibleInterface, null: false, resolver_method: :itself field :inaccessible_default_interface, InaccessibleDefaultInterface, null: false, resolver_method: :itself field :inaccessible_connection, RelayObject.connection_type, null: :false, resolver_method: :empty_array field :inaccessible_edge, RelayObject.edge_type, null: :false, resolver_method: :edge_object field :unauthorized_object, UnauthorizedObject, null: true, resolver_method: :itself field :unauthorized_connection, RelayObject.connection_type, null: false, resolver_method: :array_with_item field :unauthorized_edge, RelayObject.edge_type, null: false, resolver_method: :edge_object def edge_object OpenStruct.new(node: 100) end def array_with_item [1] end field :unauthorized_lazy_box, UnauthorizedBox, null: true do argument :value, String, required: true end def unauthorized_lazy_box(value:) # Make it extra nested, just for good measure. Box.new(value: Box.new(value: value)) end field :unauthorized_list_items, [UnauthorizedObject], null: true def unauthorized_list_items [self, self] end field :unauthorized_lazy_check_box, UnauthorizedCheckBox, null: true, resolver_method: :unauthorized_lazy_box do argument :value, String, required: true end field :unauthorized_interface, UnauthorizedInterface, null: true, resolver_method: :unauthorized_lazy_box do argument :value, String, required: true end field :unauthorized_lazy_list_interface, [UnauthorizedInterface, null: true], null: true def unauthorized_lazy_list_interface ["z", Box.new(value: Box.new(value: "z2")), "a", Box.new(value: "a")] end field :integers, IntegerObjectConnection, null: false def integers [1,2,3] end field :lazy_integers, IntegerObjectConnection, null: false def lazy_integers Box.new(value: Box.new(value: [1,2,3])) end field :replaced_object, ReplacedObject, null: false def replaced_object Replaceable.new end end class DoHiddenStuff < GraphQL::Schema::RelayClassicMutation def self.visible?(ctx) super && (ctx[:hidden_mutation] ? false : true) end end class DoHiddenStuff2 < GraphQL::Schema::Mutation def self.visible?(ctx) super && !ctx[:hidden_mutation] end field :some_return_field, String, null: true end class DoInaccessibleStuff < GraphQL::Schema::RelayClassicMutation def self.accessible?(ctx) super && (ctx[:inaccessible_mutation] ? false : true) end end class DoUnauthorizedStuff < GraphQL::Schema::RelayClassicMutation def self.authorized?(obj, ctx) super && (ctx[:unauthorized_mutation] ? false : true) end end class Mutation < BaseObject field :do_hidden_stuff, mutation: DoHiddenStuff field :do_hidden_stuff2, mutation: DoHiddenStuff2 field :do_inaccessible_stuff, mutation: DoInaccessibleStuff field :do_unauthorized_stuff, mutation: DoUnauthorizedStuff end class Schema < GraphQL::Schema if TESTING_INTERPRETER use GraphQL::Execution::Interpreter use GraphQL::Analysis::AST else # Opt in to accessible? checks query_analyzer GraphQL::Authorization::Analyzer end query(Query) mutation(Mutation) lazy_resolve(Box, :value) def self.unauthorized_object(err) if err.object.respond_to?(:replacement) err.object.replacement elsif err.object == :replace 33 elsif err.object == :raise_from_object raise GraphQL::ExecutionError, err.message else raise GraphQL::ExecutionError, "Unauthorized #{err.type.graphql_name}: #{err.object.inspect}" end end # use GraphQL::Backtrace end class SchemaWithFieldHook < GraphQL::Schema if TESTING_INTERPRETER use GraphQL::Execution::Interpreter use GraphQL::Analysis::AST end query(Query) def self.unauthorized_field(err) if err.object == :replace 42 elsif err.object == :raise raise GraphQL::ExecutionError, "#{err.message} in field #{err.field.graphql_name}" else raise GraphQL::ExecutionError, "Unauthorized field #{err.field.graphql_name} on #{err.type.graphql_name}: #{err.object}" end end end end def auth_execute(*args) AuthTest::Schema.execute(*args) end describe "applying the visible? method" do it "works in queries" do res = auth_execute(" { int int2 } ", context: { hide: true }) assert_equal 1, res["errors"].size end it "applies return type visibility to fields" do error_queries = { "hiddenObject" => "{ hiddenObject { __typename } }", "hiddenInterface" => "{ hiddenInterface { __typename } }", "hiddenDefaultInterface" => "{ hiddenDefaultInterface { __typename } }", } error_queries.each do |name, q| hidden_res = auth_execute(q, context: { hide: true}) assert_equal ["Field '#{name}' doesn't exist on type 'Query'"], hidden_res["errors"].map { |e| e["message"] } visible_res = auth_execute(q) # Both fields exist; the interface resolves to the object type, though assert_equal "HiddenObject", visible_res["data"][name]["__typename"] end end it "uses the mutation for derived fields, inputs and outputs" do query = "mutation { doHiddenStuff(input: {}) { __typename } }" res = auth_execute(query, context: { hidden_mutation: true }) assert_equal ["Field 'doHiddenStuff' doesn't exist on type 'Mutation'"], res["errors"].map { |e| e["message"] } # `#resolve` isn't implemented, so this errors out: assert_raises GraphQL::RequiredImplementationMissingError do auth_execute(query) end introspection_q = <<-GRAPHQL { t1: __type(name: "DoHiddenStuffInput") { name } t2: __type(name: "DoHiddenStuffPayload") { name } } GRAPHQL hidden_introspection_res = auth_execute(introspection_q, context: { hidden_mutation: true }) assert_nil hidden_introspection_res["data"]["t1"] assert_nil hidden_introspection_res["data"]["t2"] visible_introspection_res = auth_execute(introspection_q) assert_equal "DoHiddenStuffInput", visible_introspection_res["data"]["t1"]["name"] assert_equal "DoHiddenStuffPayload", visible_introspection_res["data"]["t2"]["name"] end it "works with Schema::Mutation" do query = "mutation { doHiddenStuff2 { __typename } }" res = auth_execute(query, context: { hidden_mutation: true }) assert_equal ["Field 'doHiddenStuff2' doesn't exist on type 'Mutation'"], res["errors"].map { |e| e["message"] } # `#resolve` isn't implemented, so this errors out: assert_raises GraphQL::RequiredImplementationMissingError do auth_execute(query) end end it "uses the base type for edges and connections" do query = <<-GRAPHQL { hiddenConnection { __typename } hiddenEdge { __typename } } GRAPHQL hidden_res = auth_execute(query, context: { hidden_relay: true }) assert_equal 2, hidden_res["errors"].size visible_res = auth_execute(query) assert_equal "RelayObjectConnection", visible_res["data"]["hiddenConnection"]["__typename"] assert_equal "RelayObjectEdge", visible_res["data"]["hiddenEdge"]["__typename"] end it "treats hidden enum values as non-existant, even in lists" do hidden_res_1 = auth_execute <<-GRAPHQL, context: { hide: true } { landscapeFeature(enum: TAR_PIT) } GRAPHQL assert_equal ["Argument 'enum' on Field 'landscapeFeature' has an invalid value (TAR_PIT). Expected type 'LandscapeFeature'."], hidden_res_1["errors"].map { |e| e["message"] } hidden_res_2 = auth_execute <<-GRAPHQL, context: { hide: true } { landscapeFeatures(enums: [STREAM, TAR_PIT]) } GRAPHQL assert_equal ["Argument 'enums' on Field 'landscapeFeatures' has an invalid value ([STREAM, TAR_PIT]). Expected type '[LandscapeFeature!]'."], hidden_res_2["errors"].map { |e| e["message"] } success_res = auth_execute <<-GRAPHQL, context: { hide: false } { landscapeFeature(enum: TAR_PIT) landscapeFeatures(enums: [STREAM, TAR_PIT]) } GRAPHQL assert_equal "TAR_PIT", success_res["data"]["landscapeFeature"] assert_equal ["STREAM", "TAR_PIT"], success_res["data"]["landscapeFeatures"] end it "refuses to resolve to hidden enum values" do assert_raises(GraphQL::EnumType::UnresolvedValueError) do auth_execute <<-GRAPHQL, context: { hide: true } { landscapeFeature(string: "TAR_PIT") } GRAPHQL end assert_raises(GraphQL::EnumType::UnresolvedValueError) do auth_execute <<-GRAPHQL, context: { hide: true } { landscapeFeatures(strings: ["STREAM", "TAR_PIT"]) } GRAPHQL end end it "works in introspection" do res = auth_execute <<-GRAPHQL, context: { hide: true, hidden_mutation: true } { query: __type(name: "Query") { fields { name args { name } } } hiddenObject: __type(name: "HiddenObject") { name } hiddenInterface: __type(name: "HiddenInterface") { name } landscapeFeatures: __type(name: "LandscapeFeature") { enumValues { name } } } GRAPHQL query_field_names = res["data"]["query"]["fields"].map { |f| f["name"] } refute_includes query_field_names, "int" int2_arg_names = res["data"]["query"]["fields"].find { |f| f["name"] == "int2" }["args"].map { |a| a["name"] } assert_equal ["int", "inaccessible", "unauthorized"], int2_arg_names assert_nil res["data"]["hiddenObject"] assert_nil res["data"]["hiddenInterface"] visible_landscape_features = res["data"]["landscapeFeatures"]["enumValues"].map { |v| v["name"] } assert_equal ["MOUNTAIN", "STREAM", "FIELD"], visible_landscape_features end end if !TESTING_INTERPRETER # This isn't supported when running the interpreter describe "applying the accessible? method" do it "works with fields and arguments" do queries = { "{ inaccessible }" => ["Some fields in this query are not accessible: inaccessible"], "{ int2(inaccessible: 1) }" => ["Some fields in this query are not accessible: int2"], } queries.each do |query_str, errors| res = auth_execute(query_str, context: { hide: true }) assert_equal errors, res.fetch("errors").map { |e| e["message"] } res = auth_execute(query_str, context: { hide: false }) refute res.key?("errors") end end it "works with return types" do queries = { "{ inaccessibleObject { __typename } }" => ["Some fields in this query are not accessible: inaccessibleObject"], "{ inaccessibleInterface { __typename } }" => ["Some fields in this query are not accessible: inaccessibleInterface"], "{ inaccessibleDefaultInterface { __typename } }" => ["Some fields in this query are not accessible: inaccessibleDefaultInterface"], } queries.each do |query_str, errors| res = auth_execute(query_str, context: { hide: true }) assert_equal errors, res["errors"].map { |e| e["message"] } res = auth_execute(query_str, context: { hide: false }) refute res.key?("errors") end end it "works with mutations" do query = "mutation { doInaccessibleStuff(input: {}) { __typename } }" res = auth_execute(query, context: { inaccessible_mutation: true }) assert_equal ["Some fields in this query are not accessible: doInaccessibleStuff"], res["errors"].map { |e| e["message"] } assert_raises GraphQL::RequiredImplementationMissingError do auth_execute(query) end end it "works with edges and connections" do query = <<-GRAPHQL { inaccessibleConnection { __typename } inaccessibleEdge { __typename } } GRAPHQL inaccessible_res = auth_execute(query, context: { inaccessible_relay: true }) assert_equal ["Some fields in this query are not accessible: inaccessibleConnection, inaccessibleEdge"], inaccessible_res["errors"].map { |e| e["message"] } accessible_res = auth_execute(query) refute accessible_res.key?("errors") end end end describe "applying the authorized? method" do it "halts on unauthorized objects, replacing the object with nil" do query = "{ unauthorizedObject { __typename } }" hidden_response = auth_execute(query, context: { hide: true }) assert_nil hidden_response["data"].fetch("unauthorizedObject") visible_response = auth_execute(query, context: {}) assert_equal({ "__typename" => "UnauthorizedObject" }, visible_response["data"]["unauthorizedObject"]) end it "halts on unauthorized mutations" do query = "mutation { doUnauthorizedStuff(input: {}) { __typename } }" res = auth_execute(query, context: { unauthorized_mutation: true }) assert_nil res["data"].fetch("doUnauthorizedStuff") assert_raises GraphQL::RequiredImplementationMissingError do auth_execute(query) end end describe "field level authorization" do describe "unauthorized field" do describe "with an unauthorized field hook configured" do describe "when the hook returns a value" do it "replaces the response with the return value of the unauthorized field hook" do query = "{ unauthorized }" response = AuthTest::SchemaWithFieldHook.execute(query, root_value: :replace) assert_equal 42, response["data"].fetch("unauthorized") end end describe "when the field hook raises an error" do it "returns nil" do query = "{ unauthorized }" response = AuthTest::SchemaWithFieldHook.execute(query, root_value: :hide) assert_nil response["data"].fetch("unauthorized") end it "adds the error to the errors key" do query = "{ unauthorized }" response = AuthTest::SchemaWithFieldHook.execute(query, root_value: :hide) assert_equal ["Unauthorized field unauthorized on Query: hide"], response["errors"].map { |e| e["message"] } end end describe "when the field authorization raises an UnauthorizedFieldError" do it "receives the raised error" do query = "{ unauthorized }" response = AuthTest::SchemaWithFieldHook.execute(query, root_value: :raise) assert_equal ["raised authorized field error in field unauthorized"], response["errors"].map { |e| e["message"] } end end end describe "with an unauthorized field hook not configured" do describe "When the object hook replaces the field" do it "delegates to the unauthorized object hook, which replaces the object" do query = "{ unauthorized }" response = AuthTest::Schema.execute(query, root_value: :replace) assert_equal 33, response["data"].fetch("unauthorized") end end describe "When the object hook raises an error" do it "returns nil" do query = "{ unauthorized }" response = AuthTest::Schema.execute(query, root_value: :hide) assert_nil response["data"].fetch("unauthorized") end it "adds the error to the errors key" do query = "{ unauthorized }" response = AuthTest::Schema.execute(query, root_value: :hide) assert_equal ["Unauthorized Query: :hide"], response["errors"].map { |e| e["message"] } end end end end describe "authorized field" do it "returns the field data" do query = "{ unauthorized }" response = AuthTest::SchemaWithFieldHook.execute(query, root_value: 1) assert_equal 1, response["data"].fetch("unauthorized") end end end it "halts on unauthorized fields, using the parent object" do query = "{ unauthorized }" hidden_response = auth_execute(query, root_value: :hide) assert_nil hidden_response["data"].fetch("unauthorized") visible_response = auth_execute(query, root_value: 1) assert_equal 1, visible_response["data"]["unauthorized"] end it "halts on unauthorized arguments, using the parent object" do query = "{ int2(unauthorized: 5) }" hidden_response = auth_execute(query, root_value: :hide2) assert_nil hidden_response["data"].fetch("int2") visible_response = auth_execute(query) assert_equal 5, visible_response["data"]["int2"] end it "works with edges and connections" do query = <<-GRAPHQL { unauthorizedConnection { __typename edges { __typename node { __typename } } nodes { __typename } } unauthorizedEdge { __typename node { __typename } } } GRAPHQL unauthorized_res = auth_execute(query, context: { unauthorized_relay: true }) conn = unauthorized_res["data"].fetch("unauthorizedConnection") assert_equal "RelayObjectConnection", conn.fetch("__typename") # This is tricky: the previous behavior was to replace the _whole_ # list with `nil`. This was due to an implementation detail: # The list field's return value (an array of integers) was wrapped # _before_ returning, and during this wrapping, a cascading error # caused the entire field to be nilled out. # # In the interpreter, each list item is contained and the error doesn't propagate # up to the whole list. # # Originally, I thought that this was a _feature_ that obscured list entries. # But really, look at the test below: you don't get this "feature" if # you use `edges { node }`, so it can't be relied on in any way. # # All that to say, in the interpreter, `nodes` and `edges { node }` behave # the same. # # TODO revisit the docs for this. failed_nodes_value = TESTING_INTERPRETER ? [nil] : nil assert_equal failed_nodes_value, conn.fetch("nodes") assert_equal [{"node" => nil, "__typename" => "RelayObjectEdge"}], conn.fetch("edges") edge = unauthorized_res["data"].fetch("unauthorizedEdge") assert_nil edge.fetch("node") assert_equal "RelayObjectEdge", edge["__typename"] unauthorized_object_paths = [ ["unauthorizedConnection", "edges", 0, "node"], TESTING_INTERPRETER ? ["unauthorizedConnection", "nodes", 0] : ["unauthorizedConnection", "nodes"], ["unauthorizedEdge", "node"] ] assert_equal unauthorized_object_paths, unauthorized_res["errors"].map { |e| e["path"] } authorized_res = auth_execute(query) conn = authorized_res["data"].fetch("unauthorizedConnection") assert_equal "RelayObjectConnection", conn.fetch("__typename") assert_equal [{"__typename"=>"RelayObject"}], conn.fetch("nodes") assert_equal [{"node" => {"__typename" => "RelayObject"}, "__typename" => "RelayObjectEdge"}], conn.fetch("edges") edge = authorized_res["data"].fetch("unauthorizedEdge") assert_equal "RelayObject", edge.fetch("node").fetch("__typename") assert_equal "RelayObjectEdge", edge["__typename"] end it "authorizes _after_ resolving lazy objects" do query = <<-GRAPHQL { a: unauthorizedLazyBox(value: "a") { value } b: unauthorizedLazyBox(value: "b") { value } } GRAPHQL unauthorized_res = auth_execute(query) assert_nil unauthorized_res["data"].fetch("a") assert_equal "b", unauthorized_res["data"]["b"]["value"] end it "authorizes items in a list" do query = <<-GRAPHQL { unauthorizedListItems { __typename } } GRAPHQL unauthorized_res = auth_execute(query, context: { hide: true }) assert_nil unauthorized_res["data"]["unauthorizedListItems"] authorized_res = auth_execute(query, context: { hide: false }) assert_equal 2, authorized_res["data"]["unauthorizedListItems"].size end it "syncs lazy objects from authorized? checks" do query = <<-GRAPHQL { a: unauthorizedLazyCheckBox(value: "a") { value } b: unauthorizedLazyCheckBox(value: "b") { value } } GRAPHQL unauthorized_res = auth_execute(query) assert_nil unauthorized_res["data"].fetch("a") assert_equal "b", unauthorized_res["data"]["b"]["value"] # Also, the custom handler was called: assert_equal ["Unauthorized UnauthorizedCheckBox: \"a\""], unauthorized_res["errors"].map { |e| e["message"] } end it "Works for lazy connections" do query = <<-GRAPHQL { lazyIntegers { edges { node { value } } } } GRAPHQL res = auth_execute(query) assert_equal [1,2,3], res["data"]["lazyIntegers"]["edges"].map { |e| e["node"]["value"] } end it "Works for eager connections" do query = <<-GRAPHQL { integers { edges { node { value } } } } GRAPHQL res = auth_execute(query) assert_equal [1,2,3], res["data"]["integers"]["edges"].map { |e| e["node"]["value"] } end it "filters out individual nodes by value" do query = <<-GRAPHQL { integers { edges { node { value } } } } GRAPHQL res = auth_execute(query, context: { exclude_integer: 1 }) assert_equal [nil,2,3], res["data"]["integers"]["edges"].map { |e| e["node"] && e["node"]["value"] } assert_equal ["Unauthorized IntegerObject: 1"], res["errors"].map { |e| e["message"] } end it "works with lazy values / interfaces" do query = <<-GRAPHQL query($value: String!){ unauthorizedInterface(value: $value) { ... on UnauthorizedCheckBox { value } } } GRAPHQL res = auth_execute(query, variables: { value: "a"}) assert_nil res["data"]["unauthorizedInterface"] res2 = auth_execute(query, variables: { value: "b"}) assert_equal "b", res2["data"]["unauthorizedInterface"]["value"] end it "works with lazy values / lists of interfaces" do query = <<-GRAPHQL { unauthorizedLazyListInterface { ... on UnauthorizedCheckBox { value } } } GRAPHQL res = auth_execute(query) # An error from two, values from the others assert_equal ["Unauthorized UnauthorizedCheckBox: \"a\"", "Unauthorized UnauthorizedCheckBox: \"a\""], res["errors"].map { |e| e["message"] } assert_equal [{"value" => "z"}, {"value" => "z2"}, nil, nil], res["data"]["unauthorizedLazyListInterface"] end describe "with an unauthorized field hook configured" do it "replaces objects from the unauthorized_object hook" do query = "{ replacedObject { replaced } }" res = auth_execute(query, context: { replace_me: true }) assert_equal true, res["data"]["replacedObject"]["replaced"] res = auth_execute(query, context: { replace_me: false }) assert_equal false, res["data"]["replacedObject"]["replaced"] end it "works when the query hook returns false and there's no root object" do query = "{ __typename }" res = auth_execute(query) assert_equal "Query", res["data"]["__typename"] unauth_res = auth_execute(query, context: { query_unauthorized: true }) assert_nil unauth_res["data"] assert_equal [{"message"=>"Unauthorized Query: nil"}], unauth_res["errors"] end describe "when the object authorization raises an UnauthorizedFieldError" do it "receives the raised error" do query = "{ unauthorizedObject { value } }" response = auth_execute(query, context: { raise: true }, root_value: :raise_from_object) assert_equal ["raised authorized object error"], response["errors"].map { |e| e["message"] } end end end end describe "returning false" do class FalseSchema < GraphQL::Schema class Query < GraphQL::Schema::Object def self.authorized?(obj, ctx) false end field :int, Integer, null: false def int 1 end end query(Query) if TESTING_INTERPRETER use GraphQL::Execution::Interpreter use GraphQL::Analysis::AST end end it "works out-of-the-box" do res = FalseSchema.execute("{ int }") assert_nil res.fetch("data") refute res.key?("errors") end end end
# # Copyright (c) 2010-2011 RightScale Inc # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. require File.join(File.dirname(__FILE__), 'spec_helper') describe RightScale::BundleQueue do include RightScale::SpecHelper it_should_behave_like 'mocks shutdown request' before(:each) do @mutex = Mutex.new @queue_closed = false @audit = flexmock('audit') @audit.should_receive(:update_status).and_return(true) @contexts = [] @sequences = {} @required_completion_order = {} @run_sequence_names = {} @multi_threaded = false @threads_started = [] end after(:each) do ::RightScale::Log.has_errors?.should be_false end shared_examples_for 'a bundle queue' do # Mocks thread queues and the supporting object graph. # # === Parameters # options[:count](Fixnum):: number of sequences to mock # options[:decommission](Boolean):: true for decommission bundle # # === Block # yields sequence index and must return a unique [sequence_name, thread_name] pair or else a single value for both # # === Return # true: always true def mock_sequence(options = { :count => 1, :decommission => false }) names = [] count = options[:count] || 1 decommission = options[:decommission] || false thread_name = nil count.times do |sequence_index| name_pair = yield(sequence_index) # require thread_name, sequence_name from caller if name_pair.kind_of?(Array) thread_name ||= name_pair.first sequence_name = name_pair.last else thread_name ||= ::RightScale::ExecutableBundle::DEFAULT_THREAD_NAME sequence_name = name_pair.to_s end names << sequence_name sequence_callback = nil bundle = flexmock("bundle #{sequence_name}", :name => sequence_name, :thread_name => thread_name) bundle.should_receive(:to_json).and_return("[\"some json\"]") context = flexmock("context #{sequence_name}", :audit => @audit, :payload => bundle, :decommission => decommission, :succeeded => true, :thread_name => thread_name, :sequence_name => sequence_name) @contexts << context sequence = flexmock("sequence #{sequence_name}", :context => context) sequence.should_receive(:callback).and_return { |callback| sequence_callback = callback; true } sequence.should_receive(:errback).and_return(true) sequence.should_receive(:run).and_return do @mutex.synchronize do @threads_started << Thread.current.object_id unless @threads_started.include?(Thread.current.object_id) end @mutex.synchronize do # note that the sequence die timer nils the required completion # order to make threads go away (before the overall timeout fires) raise "timeout" if @required_completion_order.nil? @required_completion_order[thread_name].first.should == sequence_name @run_sequence_names[thread_name] ||= [] @run_sequence_names[thread_name] << sequence_name @required_completion_order[thread_name].shift @required_completion_order.delete(thread_name) if @required_completion_order[thread_name].empty? end # simulate callback from spawned process' exit handler on next tick. EM.next_tick { sequence_callback.call } end @sequences[thread_name] ||= {} @sequences[thread_name][sequence_name] = sequence end # require that queued sequences complete in a known order. @required_completion_order[thread_name] ||= [] @required_completion_order[thread_name] += names end def add_sequence_die_timer # run_em_test timeout is 5 EM.add_timer(4.5) { @mutex.synchronize { @required_completion_order = nil } } end it 'should default to non active' do mock_sequence { 'never run by inactive queue' } # ensure inactive queue doesn't leak bundle queue stuff to EM run_em_test do @queue.push(@contexts.shift) EM.add_timer(0.2) { EM.stop } end @queue.active?.should be_false @queue_closed.should be_false @run_sequence_names.empty?.should be_true @required_completion_order.should == { ::RightScale::ExecutableBundle::DEFAULT_THREAD_NAME => ['never run by inactive queue'] } end it 'should run all bundles once active' do # enough sequences/threads to make it interesting. thread_name_count = 4 sequence_count = 4 thread_name_count.times do |thread_name_index| mock_sequence(:count => sequence_count) do |sequence_index| [0 == thread_name_index ? ::RightScale::ExecutableBundle::DEFAULT_THREAD_NAME : "thread #{thread_name_index}", "sequence ##{sequence_index + 1}"] end end # push some contexts pre-activation and the rest post-activation. (@contexts.size / 2).times { @queue.push(@contexts.shift) } run_em_test do add_sequence_die_timer @queue.activate @contexts.size.times { @queue.push(@contexts.shift) } @queue.close end @queue_closed.should be_true @run_sequence_names.values.flatten.size.should == thread_name_count * sequence_count @required_completion_order.should == {} @threads_started.size.should == (@multi_threaded ? thread_name_count : 1) end it 'should not be active upon closing' do mock_sequence { 'queued before activation' } mock_sequence { 'never runs after deactivation' } run_em_test do add_sequence_die_timer @queue.push(@contexts.shift) @queue.activate @queue.close @queue.push(@contexts.shift) end @queue_closed.should be_true @queue.active?.should be_false @run_sequence_names.values.flatten.size.should == 1 @required_completion_order.should == { ::RightScale::ExecutableBundle::DEFAULT_THREAD_NAME => ['never runs after deactivation'] } end it 'should process the shutdown bundle' do # prepare multiple contexts which must finish before decommissioning. thread_name_count = 3 sequence_count = 3 thread_name_count.times do |thread_name_index| mock_sequence(:count => sequence_count) do |sequence_index| [0 == thread_name_index ? ::RightScale::ExecutableBundle::DEFAULT_THREAD_NAME : "thread #{thread_name_index}", "sequence ##{sequence_index + 1}"] end end # default thread will be restarted to run decommission bundle after all # running threads are closed by shutdown bundle (including default thread). count_before_decommission = @contexts.size mock_sequence { 'ignored due to decommissioning and not a decommission bundle' } mock_sequence(:decommission => true) { 'decommission bundle' } mock_sequence { 'never runs after decommission closes queue' } @required_completion_order[::RightScale::ExecutableBundle::DEFAULT_THREAD_NAME].delete('ignored due to decommissioning and not a decommission bundle') shutdown_processed = false flexmock(@mock_shutdown_request). should_receive(:process). and_return do shutdown_processed = true @contexts.size.times { @queue.push(@contexts.shift) } @queue.close true end flexmock(@mock_shutdown_request).should_receive(:immediately?).and_return { shutdown_processed } run_em_test do add_sequence_die_timer @queue.activate count_before_decommission.times { @queue.push(@contexts.shift) } @queue.push(::RightScale::MultiThreadBundleQueue::SHUTDOWN_BUNDLE) end shutdown_processed.should be_true @queue_closed.should be_true @run_sequence_names.values.flatten.size.should == count_before_decommission + 1 @run_sequence_names[::RightScale::ExecutableBundle::DEFAULT_THREAD_NAME].last.should == 'decommission bundle' @required_completion_order.should == { ::RightScale::ExecutableBundle::DEFAULT_THREAD_NAME => ['never runs after decommission closes queue'] } @threads_started.size.should == (@multi_threaded ? (thread_name_count + 1) : 1) end end describe RightScale::SingleThreadBundleQueue do it_should_behave_like 'a bundle queue' before(:each) do @queue = RightScale::SingleThreadBundleQueue.new { @queue_closed = true; EM.stop } sequences = @sequences flexmock(@queue).should_receive(:create_sequence).and_return { |context| sequences[context.thread_name][context.sequence_name] } end end describe RightScale::MultiThreadBundleQueue do it_should_behave_like 'a bundle queue' before(:each) do @queue = RightScale::MultiThreadBundleQueue.new { @queue_closed = true; EM.stop } sequences = @sequences flexmock(@queue).should_receive(:create_thread_queue).with(String, Proc).and_return do |thread_name, continuation| thread_queue = RightScale::SingleThreadBundleQueue.new(thread_name, &continuation) flexmock(thread_queue).should_receive(:create_sequence).and_return { |context| sequences[context.thread_name][context.sequence_name] } thread_queue end @multi_threaded = true end end end changed from using flexmock in bundle_queue_spec to workaround seg fault issue # # Copyright (c) 2010-2011 RightScale Inc # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. require File.join(File.dirname(__FILE__), 'spec_helper') module RightScale module BundleQueueSpec # note that we changed from using flexmock for Bundle, OperationContext and # ExecutableSequence for the multi-threaded tests due to a Ruby 1.8.7 issue # which appears to cause dynamically typed objects (i.e. flexmocked) to have # their type garbage collected before the object, but (probably) only when # the object is released on a different thread than that which defined the # dynamic type. types, logically, are not thread-local but dynamic types are # a strange animal because there is generally only ever one object # associated with that type. # # more specifically, we were seeing a segmentation fault during the time # when the thread's stack was being garbage collected and the type (i.e. # class) of the object being recycled could not be determined by Ruby's # garbage collector. class MockBundle attr_reader :name, :thread_name def initialize(name, thread_name) @name = name @thread_name = thread_name end def to_json; "[\"some json\"]"; end end class MockContext attr_reader :audit, :payload, :decommission, :succeeded, :thread_name, :sequence_name def initialize(audit, payload, decommission, succeeded, thread_name, sequence_name) @audit = audit @payload = payload @decommission = decommission @succeeded = succeeded @thread_name = thread_name @sequence_name = sequence_name end end class MockSequence attr_reader :context def initialize(context, &block) @context = context @callback = nil @errback = nil @runner = block end def callback(&block) @callback = block if block @callback end def errback(&block) @errback = block if block @errback end def run; @runner.call(self); end end end end describe RightScale::BundleQueue do include RightScale::SpecHelper it_should_behave_like 'mocks shutdown request' before(:each) do @mutex = Mutex.new @queue_closed = false @audit = flexmock('audit') @audit.should_receive(:update_status).and_return(true) @contexts = [] @sequences = {} @required_completion_order = {} @run_sequence_names = {} @multi_threaded = false @threads_started = [] end after(:each) do ::RightScale::Log.has_errors?.should be_false end shared_examples_for 'a bundle queue' do # Mocks thread queues and the supporting object graph. # # === Parameters # options[:count](Fixnum):: number of sequences to mock # options[:decommission](Boolean):: true for decommission bundle # # === Block # yields sequence index and must return a unique [sequence_name, thread_name] pair or else a single value for both # # === Return # true: always true def mock_sequence(options = { :count => 1, :decommission => false }) names = [] count = options[:count] || 1 decommission = options[:decommission] || false thread_name = nil count.times do |sequence_index| name_pair = yield(sequence_index) # require thread_name, sequence_name from caller if name_pair.kind_of?(Array) thread_name ||= name_pair.first sequence_name = name_pair.last else thread_name ||= ::RightScale::ExecutableBundle::DEFAULT_THREAD_NAME sequence_name = name_pair.to_s end names << sequence_name sequence_callback = nil bundle = ::RightScale::BundleQueueSpec::MockBundle.new(sequence_name, thread_name) context = ::RightScale::BundleQueueSpec::MockContext.new(@audit, bundle, decommission, true, thread_name, sequence_name) @contexts << context sequence = ::RightScale::BundleQueueSpec::MockSequence.new(context) do |sequence| @mutex.synchronize do @threads_started << Thread.current.object_id unless @threads_started.include?(Thread.current.object_id) end @mutex.synchronize do # note that the sequence die timer nils the required completion # order to make threads go away (before the overall timeout fires) raise "timeout" if @required_completion_order.nil? @required_completion_order[thread_name].first.should == sequence_name @run_sequence_names[thread_name] ||= [] @run_sequence_names[thread_name] << sequence_name @required_completion_order[thread_name].shift @required_completion_order.delete(thread_name) if @required_completion_order[thread_name].empty? end # simulate callback from spawned process' exit handler on next tick. EM.next_tick { sequence.callback.call } end @sequences[thread_name] ||= {} @sequences[thread_name][sequence_name] = sequence end # require that queued sequences complete in a known order. @required_completion_order[thread_name] ||= [] @required_completion_order[thread_name] += names end def add_sequence_die_timer # run_em_test timeout is 5 EM.add_timer(4.5) { @mutex.synchronize { @required_completion_order = nil } } end it 'should default to non active' do mock_sequence { 'never run by inactive queue' } # ensure inactive queue doesn't leak bundle queue stuff to EM run_em_test do @queue.push(@contexts.shift) EM.add_timer(0.2) { EM.stop } end @queue.active?.should be_false @queue_closed.should be_false @run_sequence_names.empty?.should be_true @required_completion_order.should == { ::RightScale::ExecutableBundle::DEFAULT_THREAD_NAME => ['never run by inactive queue'] } end it 'should run all bundles once active' do # enough sequences/threads to make it interesting. thread_name_count = 4 sequence_count = 4 thread_name_count.times do |thread_name_index| mock_sequence(:count => sequence_count) do |sequence_index| [0 == thread_name_index ? ::RightScale::ExecutableBundle::DEFAULT_THREAD_NAME : "thread #{thread_name_index}", "sequence ##{sequence_index + 1}"] end end # push some contexts pre-activation and the rest post-activation. (@contexts.size / 2).times { @queue.push(@contexts.shift) } run_em_test do add_sequence_die_timer @queue.activate @contexts.size.times { @queue.push(@contexts.shift) } @queue.close end @queue_closed.should be_true @run_sequence_names.values.flatten.size.should == thread_name_count * sequence_count @required_completion_order.should == {} @threads_started.size.should == (@multi_threaded ? thread_name_count : 1) end it 'should not be active upon closing' do mock_sequence { 'queued before activation' } mock_sequence { 'never runs after deactivation' } run_em_test do add_sequence_die_timer @queue.push(@contexts.shift) @queue.activate @queue.close @queue.push(@contexts.shift) end @queue_closed.should be_true @queue.active?.should be_false @run_sequence_names.values.flatten.size.should == 1 @required_completion_order.should == { ::RightScale::ExecutableBundle::DEFAULT_THREAD_NAME => ['never runs after deactivation'] } end it 'should process the shutdown bundle' do # prepare multiple contexts which must finish before decommissioning. thread_name_count = 3 sequence_count = 3 thread_name_count.times do |thread_name_index| mock_sequence(:count => sequence_count) do |sequence_index| [0 == thread_name_index ? ::RightScale::ExecutableBundle::DEFAULT_THREAD_NAME : "thread #{thread_name_index}", "sequence ##{sequence_index + 1}"] end end # default thread will be restarted to run decommission bundle after all # running threads are closed by shutdown bundle (including default thread). count_before_decommission = @contexts.size mock_sequence { 'ignored due to decommissioning and not a decommission bundle' } mock_sequence(:decommission => true) { 'decommission bundle' } mock_sequence { 'never runs after decommission closes queue' } @required_completion_order[::RightScale::ExecutableBundle::DEFAULT_THREAD_NAME].delete('ignored due to decommissioning and not a decommission bundle') shutdown_processed = false flexmock(@mock_shutdown_request). should_receive(:process). and_return do shutdown_processed = true @contexts.size.times { @queue.push(@contexts.shift) } @queue.close true end flexmock(@mock_shutdown_request).should_receive(:immediately?).and_return { shutdown_processed } run_em_test do add_sequence_die_timer @queue.activate count_before_decommission.times { @queue.push(@contexts.shift) } @queue.push(::RightScale::MultiThreadBundleQueue::SHUTDOWN_BUNDLE) end shutdown_processed.should be_true @queue_closed.should be_true @run_sequence_names.values.flatten.size.should == count_before_decommission + 1 @run_sequence_names[::RightScale::ExecutableBundle::DEFAULT_THREAD_NAME].last.should == 'decommission bundle' @required_completion_order.should == { ::RightScale::ExecutableBundle::DEFAULT_THREAD_NAME => ['never runs after decommission closes queue'] } @threads_started.size.should == (@multi_threaded ? (thread_name_count + 1) : 1) end end describe RightScale::SingleThreadBundleQueue do it_should_behave_like 'a bundle queue' before(:each) do @queue = RightScale::SingleThreadBundleQueue.new { @queue_closed = true; EM.stop } sequences = @sequences flexmock(@queue).should_receive(:create_sequence).and_return { |context| sequences[context.thread_name][context.sequence_name] } end end describe RightScale::MultiThreadBundleQueue do it_should_behave_like 'a bundle queue' before(:each) do @queue = RightScale::MultiThreadBundleQueue.new { @queue_closed = true; EM.stop } sequences = @sequences flexmock(@queue).should_receive(:create_thread_queue).with(String, Proc).and_return do |thread_name, continuation| thread_queue = RightScale::SingleThreadBundleQueue.new(thread_name, &continuation) flexmock(thread_queue).should_receive(:create_sequence).and_return { |context| sequences[context.thread_name][context.sequence_name] } thread_queue end @multi_threaded = true end end end
Add failing spec to test TravisCI require 'spec_helper' describe ROM::Roda::Plugin do it 'uses load_path relative to application by default' do subject.should_receive(:load_files).with(File.expand_path('models')) class RelativeLoadPathExample < Roda plugin :rom, :memory, load_path: 'models' end end end
require 'daywalker' require 'open-uri' require 'json' class Legislator < ActiveRecord::Base has_many :committees, :through => :committee_memberships has_many :committee_memberships has_many :parent_committees, :through => :committee_memberships, :source => :committee, :conditions => 'parent_id IS NULL' has_many :subcommittees, :through => :committee_memberships, :source => :committee, :conditions => 'parent_id IS NOT NULL' validates_presence_of :bioguide_id, :district, :state, :name named_scope :active, :conditions => {:in_office => true} named_scope :filter, lambda {|conditions| conditions.delete('house') unless ['house', 'senate'].include?(conditions[:house]) {:conditions => conditions} } def self.sort(fields) cols = ['name', 'state', 'district', 'gender', 'party'] fields.sort {|a, b| cols.index(a) <=> cols.index(b)} end def self.field_for(legislators, column) field = {} legislators.each do |legislator| field[legislator.bioguide_id] = case column when 'committees' legislator.parent_committees.map {|committee| %Q{<a href="#" class="filter">#{committee.short_name}</a>} }.join(', ') when 'district' "#{legislator.house.capitalize} - #{legislator.district}" else legislator.send column end end field end def self.update Daywalker.api_key = api_key api_legislators = Daywalker::Legislator.all created_count = 0 updated_count = 0 mistakes = [] api_legislators.each do |api_legislator| legislator = Legislator.find_or_initialize_by_bioguide_id api_legislator.bioguide_id if legislator.new_record? created_count += 1 puts "[Legislator #{legislator.bioguide_id}] Created" else updated_count += 1 puts "[Legislator #{legislator.bioguide_id}] Updated" end legislator.attributes = { :house => house_for(api_legislator), :gender => gender_for(api_legislator), :name => name_for(api_legislator), :district => district_for(api_legislator), :state => api_legislator.state, :party => party_for(api_legislator), :in_office => api_legislator.in_office, :crp_id => api_legislator.crp_id, :govtrack_id => api_legislator.govtrack_id, :votesmart_id => api_legislator.votesmart_id, :fec_id => api_legislator.fec_id } begin open "http://services.sunlightlabs.com/api/committees.allForLegislator?apikey=#{api_key}&bioguide_id=#{legislator.bioguide_id}" do |response| committees = JSON.parse(response.read) committees['response']['committees'].each do |comm| committee = Committee.find_or_initialize_by_keyword comm['committee']['id'] committee.attributes = {:chamber => comm['committee']['chamber'], :name => comm['committee']['name']} puts " [Committee #{committee.new_record? ? 'Created' : 'Updated'}] #{committee.name}" committee.save! unless membership = legislator.committee_memberships.find_by_committee_id(committee.id) membership = legislator.committee_memberships.build :committee_id => committee.id puts " - Added Membership" end if comm['committee']['subcommittees'] comm['committee']['subcommittees'].each do |subcomm| subcommittee = Committee.find_or_initialize_by_keyword subcomm['committee']['id'] subcommittee.attributes = {:chamber => subcomm['committee']['chamber'], :name => subcomm['committee']['name'], :parent_id => committee.id} puts " [Subcommittee #{subcommittee.new_record? ? 'Created' : 'Updated'}] #{subcommittee.name}" subcommittee.save! unless membership = legislator.committee_memberships.find_by_committee_id(subcommittee.id) membership = legislator.committee_memberships.build :committee_id => subcommittee.id puts " - Added Membership" end end end end end rescue OpenURI::HTTPError => e mistakes << "Error getting committees for legislator #{legislator.bioguide_id}" end legislator.save! end success_msg = "#{created_count} legislators created, #{updated_count} updated" success_msg << "\n" + mistakes.join("\n") if mistakes.any? ['SUCCESS', success_msg] rescue => e ['FAILED', e.inspect] end private # Some Daywalker-specific transformations def self.house_for(api_legislator) { :representative => 'house', :senator => 'senate', nil => 'house' }[api_legislator.title] end def self.name_for(api_legislator) "#{api_legislator.first_name} #{api_legislator.last_name}" end def self.district_for(api_legislator) api_legislator.district.to_s.titleize end def self.party_for(api_legislator) api_legislator.party.to_s.first.capitalize end def self.gender_for(api_legislator) api_legislator.gender.to_s.first.capitalize end end class Committee < ActiveRecord::Base has_many :legislators, :through => :committee_memberships has_many :committee_memberships has_many :subcommittees, :class_name => 'Committee', :foreign_key => :parent_id belongs_to :parent_committee, :class_name => 'Committee', :foreign_key => :parent_id def short_name name.sub /^[\w\s]+ommm?ittee on /, '' end end class CommitteeMembership < ActiveRecord::Base belongs_to :committee belongs_to :legislator end Expanded committee short-name abbreviator to handle a possible 'the' prefix require 'daywalker' require 'open-uri' require 'json' class Legislator < ActiveRecord::Base has_many :committees, :through => :committee_memberships has_many :committee_memberships has_many :parent_committees, :through => :committee_memberships, :source => :committee, :conditions => 'parent_id IS NULL' has_many :subcommittees, :through => :committee_memberships, :source => :committee, :conditions => 'parent_id IS NOT NULL' validates_presence_of :bioguide_id, :district, :state, :name named_scope :active, :conditions => {:in_office => true} named_scope :filter, lambda {|conditions| conditions.delete('house') unless ['house', 'senate'].include?(conditions[:house]) {:conditions => conditions} } def self.sort(fields) cols = ['name', 'state', 'district', 'gender', 'party'] fields.sort {|a, b| cols.index(a) <=> cols.index(b)} end def self.field_for(legislators, column) field = {} legislators.each do |legislator| field[legislator.bioguide_id] = case column when 'committees' legislator.parent_committees.map {|committee| %Q{<a href="#" class="filter">#{committee.short_name}</a>} }.join(', ') when 'district' "#{legislator.house.capitalize} - #{legislator.district}" else legislator.send column end end field end def self.update Daywalker.api_key = api_key api_legislators = Daywalker::Legislator.all created_count = 0 updated_count = 0 mistakes = [] api_legislators.each do |api_legislator| legislator = Legislator.find_or_initialize_by_bioguide_id api_legislator.bioguide_id if legislator.new_record? created_count += 1 puts "[Legislator #{legislator.bioguide_id}] Created" else updated_count += 1 puts "[Legislator #{legislator.bioguide_id}] Updated" end legislator.attributes = { :house => house_for(api_legislator), :gender => gender_for(api_legislator), :name => name_for(api_legislator), :district => district_for(api_legislator), :state => api_legislator.state, :party => party_for(api_legislator), :in_office => api_legislator.in_office, :crp_id => api_legislator.crp_id, :govtrack_id => api_legislator.govtrack_id, :votesmart_id => api_legislator.votesmart_id, :fec_id => api_legislator.fec_id } begin open "http://services.sunlightlabs.com/api/committees.allForLegislator?apikey=#{api_key}&bioguide_id=#{legislator.bioguide_id}" do |response| committees = JSON.parse(response.read) committees['response']['committees'].each do |comm| committee = Committee.find_or_initialize_by_keyword comm['committee']['id'] committee.attributes = {:chamber => comm['committee']['chamber'], :name => comm['committee']['name']} puts " [Committee #{committee.new_record? ? 'Created' : 'Updated'}] #{committee.name}" committee.save! unless membership = legislator.committee_memberships.find_by_committee_id(committee.id) membership = legislator.committee_memberships.build :committee_id => committee.id puts " - Added Membership" end if comm['committee']['subcommittees'] comm['committee']['subcommittees'].each do |subcomm| subcommittee = Committee.find_or_initialize_by_keyword subcomm['committee']['id'] subcommittee.attributes = {:chamber => subcomm['committee']['chamber'], :name => subcomm['committee']['name'], :parent_id => committee.id} puts " [Subcommittee #{subcommittee.new_record? ? 'Created' : 'Updated'}] #{subcommittee.name}" subcommittee.save! unless membership = legislator.committee_memberships.find_by_committee_id(subcommittee.id) membership = legislator.committee_memberships.build :committee_id => subcommittee.id puts " - Added Membership" end end end end end rescue OpenURI::HTTPError => e mistakes << "Error getting committees for legislator #{legislator.bioguide_id}" end legislator.save! end success_msg = "#{created_count} legislators created, #{updated_count} updated" success_msg << "\n" + mistakes.join("\n") if mistakes.any? ['SUCCESS', success_msg] rescue => e ['FAILED', e.inspect] end private # Some Daywalker-specific transformations def self.house_for(api_legislator) { :representative => 'house', :senator => 'senate', nil => 'house' }[api_legislator.title] end def self.name_for(api_legislator) "#{api_legislator.first_name} #{api_legislator.last_name}" end def self.district_for(api_legislator) api_legislator.district.to_s.titleize end def self.party_for(api_legislator) api_legislator.party.to_s.first.capitalize end def self.gender_for(api_legislator) api_legislator.gender.to_s.first.capitalize end end class Committee < ActiveRecord::Base has_many :legislators, :through => :committee_memberships has_many :committee_memberships has_many :subcommittees, :class_name => 'Committee', :foreign_key => :parent_id belongs_to :parent_committee, :class_name => 'Committee', :foreign_key => :parent_id def short_name name.sub /^[\w\s]+ommm?ittee on (the )?/, '' end end class CommitteeMembership < ActiveRecord::Base belongs_to :committee belongs_to :legislator end
require 'sinatra' require 'json' get '/' do haml :index, :format => :html5 end get '/:params' do |p| content_type :json { :params => p }.to_json end post '/' do content_type :json { :params => params }.to_json end get put post delete require 'sinatra' require 'json' get '/' do if params.empty? haml :index, :format => :html5 else content_type :json {:get => params}.to_json end end post '/' do content_type :json {:post => params}.to_json end put '/' do content_type :json {:put => params}.to_json end delete '/' do content_type :json {:delete => params}.to_json end
require File.join(File.dirname(__FILE__), 'test_helper') class AlterTableTest < ActiveRecord::TestCase def setup create_model_table! end def teardown drop_model_table end def test_add_column alter_model_table do |t| t.add_column 'name', :string end assert_column 'name', :string end def test_add_multiple_columns assert_queries(1) do alter_model_table do |t| t.add_column 'name', :string t.add_column 'age', :integer end end end private def create_model_table ActiveRecord::Base.connection.create_table('users') do |t| end end def create_model_table! @retry = true ActiveRecord::Migration.verbose = false begin create_model_table rescue ActiveRecord::StatementInvalid drop_model_table if @retry @retry = false retry end end end def drop_model_table ActiveRecord::Base.connection.drop_table('users') end def alter_model_table ActiveRecord::Base.connection.alter_table(model.table_name) do |t| yield(t) end end def assert_column name, expected_type, options = {} column = model.columns.find { |c| name == c.name } flunk "Expected column %s not found" % name unless name assert_equal expected_type, column.type assert_equal options[:default], column.default if options.has_key?(:default) assert_equal options[:primary], column.primary if options.has_key?(:primary) assert_equal options[:sql_type], column.sql_type if options.has_key?(:sql_type) assert_equal options[:limit], column.limit if options.has_key?(:limit) assert_equal options[:scale], column.scale if options.has_key?(:scale) assert_equal options[:precision], column.precision if options.has_key?(:precision) end end def model returning Class.new(ActiveRecord::Base) do |c| c.table_name = 'users' end end Test remove column require File.join(File.dirname(__FILE__), 'test_helper') class AlterTableTest < ActiveRecord::TestCase def setup create_model_table! end def teardown drop_model_table end def test_add_column alter_model_table do |t| t.add_column 'name', :string end assert_column 'name', :string end def test_remove_column alter_model_table do |t| t.add_column 'age', :integer end assert_column 'age', :integer alter_model_table do |t| t.remove_column 'age' end assert_no_column 'age' end def test_add_multiple_columns assert_queries(1) do alter_model_table do |t| t.add_column 'name', :string t.add_column 'age', :integer end end end private def create_model_table ActiveRecord::Base.connection.create_table('users') do |t| end end def create_model_table! @retry = true ActiveRecord::Migration.verbose = false begin create_model_table rescue ActiveRecord::StatementInvalid drop_model_table if @retry @retry = false retry end end end def drop_model_table ActiveRecord::Base.connection.drop_table('users') end def alter_model_table ActiveRecord::Base.connection.alter_table(model.table_name) do |t| yield(t) end end def assert_column name, expected_type, options = {} column = model.columns.find { |c| name == c.name } flunk "Expected column %s not found" % name unless name assert_equal expected_type, column.type assert_equal options[:default], column.default if options.has_key?(:default) assert_equal options[:primary], column.primary if options.has_key?(:primary) assert_equal options[:sql_type], column.sql_type if options.has_key?(:sql_type) assert_equal options[:limit], column.limit if options.has_key?(:limit) assert_equal options[:scale], column.scale if options.has_key?(:scale) assert_equal options[:precision], column.precision if options.has_key?(:precision) end def assert_no_column name column = model.columns.find { |c| name == c.name } assert_nil column, "Expected not to have found a column %s" % name end end def model returning Class.new(ActiveRecord::Base) do |c| c.table_name = 'users' end end
module Iridium VERSION = "0.9.0.rc1" end Bump version module Iridium VERSION = "0.9.0" end
require 'spec_helper' describe Staccato::Pageview do let(:tracker) {Staccato.tracker('UA-XXXX-Y', '555')} context "with all options" do let(:pageview) do Staccato::Pageview.new(tracker, { :hostname => 'mysite.com', :path => '/foobar', :title => 'FooBar' }) end it 'has a hostname' do expect(pageview.hostname).to eq('mysite.com') end it 'has a path' do expect(pageview.path).to eq('/foobar') end it 'has a title' do expect(pageview.title).to eq('FooBar') end it 'has all params' do expect(pageview.params).to eq({ 'v' => 1, 'tid' => 'UA-XXXX-Y', 'cid' => '555', 't' => 'pageview', 'dh' => 'mysite.com', 'dp' => '/foobar', 'dt' => 'FooBar' }) end end context "with extra options" do let(:pageview) do Staccato::Pageview.new(tracker, { :hostname => 'mysite.com', :path => '/foobar', :title => 'FooBar', :action => 'play' }) end it 'has all params' do expect(pageview.params).to eq({ 'v' => 1, 'tid' => 'UA-XXXX-Y', 'cid' => '555', 't' => 'pageview', 'dh' => 'mysite.com', 'dp' => '/foobar', 'dt' => 'FooBar' }) end end context "with no options" do let(:pageview) do Staccato::Pageview.new(tracker, {}) end it 'has required params' do expect(pageview.params).to eq({ 'v' => 1, 'tid' => 'UA-XXXX-Y', 'cid' => '555', 't' => 'pageview' }) end end context "with experiment_* options" do let(:pageview) do Staccato::Pageview.new(tracker, { experiment_id: 'ac67afa889', experiment_variant: 'c' }) end it 'has experiment id and variant' do expect(pageview.params).to eq({ 'v' => 1, 'tid' => 'UA-XXXX-Y', 'cid' => '555', 't' => 'pageview', 'xid' => 'ac67afa889', 'xvar' => 'c' }) end end context "with session control" do let(:pageview) do Staccato::Pageview.new(tracker, { session_start: true }) end it 'has session control param' do expect(pageview.params).to eq({ 'v' => 1, 'tid' => 'UA-XXXX-Y', 'cid' => '555', 't' => 'pageview', 'sc' => 'start' }) end end context "with some custom dimensions" do let(:pageview) do Staccato::Pageview.new(tracker) end before(:each) do pageview.add_custom_dimension(19, 'Apple') pageview.add_custom_dimension(8, 'Samsung') end it 'has custom dimensions' do expect(pageview.params).to eq({ 'v' => 1, 'tid' => 'UA-XXXX-Y', 'cid' => '555', 't' => 'pageview', 'cd19' => 'Apple', 'cd8' => 'Samsung' }) end end context "with some custom metrics" do let(:pageview) do Staccato::Pageview.new(tracker) end before(:each) do pageview.add_custom_metric(12, 42) pageview.add_custom_metric(1, 11) end it 'has custom dimensions' do expect(pageview.params).to eq({ 'v' => 1, 'tid' => 'UA-XXXX-Y', 'cid' => '555', 't' => 'pageview', 'cm12' => 42, 'cm1' => 11 }) end end end correct a mistaken spec description require 'spec_helper' describe Staccato::Pageview do let(:tracker) {Staccato.tracker('UA-XXXX-Y', '555')} context "with all options" do let(:pageview) do Staccato::Pageview.new(tracker, { :hostname => 'mysite.com', :path => '/foobar', :title => 'FooBar' }) end it 'has a hostname' do expect(pageview.hostname).to eq('mysite.com') end it 'has a path' do expect(pageview.path).to eq('/foobar') end it 'has a title' do expect(pageview.title).to eq('FooBar') end it 'has all params' do expect(pageview.params).to eq({ 'v' => 1, 'tid' => 'UA-XXXX-Y', 'cid' => '555', 't' => 'pageview', 'dh' => 'mysite.com', 'dp' => '/foobar', 'dt' => 'FooBar' }) end end context "with extra options" do let(:pageview) do Staccato::Pageview.new(tracker, { :hostname => 'mysite.com', :path => '/foobar', :title => 'FooBar', :action => 'play' }) end it 'has all params' do expect(pageview.params).to eq({ 'v' => 1, 'tid' => 'UA-XXXX-Y', 'cid' => '555', 't' => 'pageview', 'dh' => 'mysite.com', 'dp' => '/foobar', 'dt' => 'FooBar' }) end end context "with no options" do let(:pageview) do Staccato::Pageview.new(tracker, {}) end it 'has required params' do expect(pageview.params).to eq({ 'v' => 1, 'tid' => 'UA-XXXX-Y', 'cid' => '555', 't' => 'pageview' }) end end context "with experiment_* options" do let(:pageview) do Staccato::Pageview.new(tracker, { experiment_id: 'ac67afa889', experiment_variant: 'c' }) end it 'has experiment id and variant' do expect(pageview.params).to eq({ 'v' => 1, 'tid' => 'UA-XXXX-Y', 'cid' => '555', 't' => 'pageview', 'xid' => 'ac67afa889', 'xvar' => 'c' }) end end context "with session control" do let(:pageview) do Staccato::Pageview.new(tracker, { session_start: true }) end it 'has session control param' do expect(pageview.params).to eq({ 'v' => 1, 'tid' => 'UA-XXXX-Y', 'cid' => '555', 't' => 'pageview', 'sc' => 'start' }) end end context "with some custom dimensions" do let(:pageview) do Staccato::Pageview.new(tracker) end before(:each) do pageview.add_custom_dimension(19, 'Apple') pageview.add_custom_dimension(8, 'Samsung') end it 'has custom dimensions' do expect(pageview.params).to eq({ 'v' => 1, 'tid' => 'UA-XXXX-Y', 'cid' => '555', 't' => 'pageview', 'cd19' => 'Apple', 'cd8' => 'Samsung' }) end end context "with some custom metrics" do let(:pageview) do Staccato::Pageview.new(tracker) end before(:each) do pageview.add_custom_metric(12, 42) pageview.add_custom_metric(1, 11) end it 'has custom metrics' do expect(pageview.params).to eq({ 'v' => 1, 'tid' => 'UA-XXXX-Y', 'cid' => '555', 't' => 'pageview', 'cm12' => 42, 'cm1' => 11 }) end end end
#-- # Copyright (c) 2010 Michael Berkovich, Geni Inc # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #++ class Wf::Filter < ActiveRecord::Base set_table_name :wf_filters serialize :data ############################################################################# # Basics ############################################################################# def initialize(model_class) super() self.model_class_name = model_class.to_s end def dup super.tap {|ii| ii.conditions = self.conditions.dup} end def before_save self.data = serialize_to_params self.type = self.class.name end def after_find @errors = {} deserialize_from_params(self.data) end ############################################################################# # Defaults ############################################################################# def show_export_options? Wf::Config.exporting_enabled? end def show_save_options? Wf::Config.saving_enabled? end def match @match ||= :all end def key @key ||= '' end def errors @errors ||= {} end def format @format ||= :html end def fields @fields ||= [] end ############################################################################# # a list of indexed fields where at least one of them has to be in a query # otherwise the filter may hang the database ############################################################################# def required_condition_keys [] end def model_class return nil unless model_class_name @model_class ||= model_class_name.constantize end def table_name model_class.table_name end def key=(new_key) @key = new_key end def match=(new_match) @match = new_match end ############################################################################# # Inner Joins come in a form of # [[joining_model_name, column_name], [joining_model_name, column_name]] ############################################################################# def inner_joins [] end def model_columns model_class.columns end def model_column_keys model_columns.collect{|col| col.name.to_sym} end def contains_column?(key) model_column_keys.index(key) != nil end def definition @definition ||= begin defs = {} model_columns.each do |col| defs[col.name.to_sym] = default_condition_definition_for(col.name, col.sql_type) end inner_joins.each do |inner_join| join_class = inner_join.first.to_s.camelcase.constantize join_class.columns.each do |col| defs[:"#{join_class.to_s.underscore}.#{col.name.to_sym}"] = default_condition_definition_for(col.name, col.sql_type) end end defs end end def container_by_sql_type(type) raise Wf::FilterException.new("Unsupported data type #{type}") unless Wf::Config.data_types[type] Wf::Config.data_types[type] end def default_condition_definition_for(name, sql_data_type) type = sql_data_type.split(" ").first.split("(").first.downcase containers = container_by_sql_type(type) operators = {} containers.each do |c| raise Wf::FilterException.new("Unsupported container implementation for #{c}") unless Wf::Config.containers[c] container_klass = Wf::Config.containers[c].constantize container_klass.operators.each do |o| operators[o] = c end end if name == "id" operators[:is_filtered_by] = :filter_list elsif "_id" == name[-3..-1] begin name[0..-4].camelcase.constantize operators[:is_filtered_by] = :filter_list rescue end end operators end def sorted_operators(opers) (Wf::Config.operator_order & opers.keys.collect{|o| o.to_s}) end def first_sorted_operator(opers) sorted_operators(opers).first.to_sym end def default_order 'id' end def order @order ||= default_order end def default_order_type 'desc' end def order_type @order_type ||= default_order_type end def order_model @order_model ||= begin order_parts = order.split('.') if order_parts.size > 1 order_parts.first.camelcase else model_class_name end end end def order_clause @order_clause ||= begin order_parts = order.split('.') if order_parts.size > 1 "#{order_parts.first.camelcase.constantize.table_name}.#{order_parts.last} #{order_type}" else "#{model_class_name.constantize.table_name}.#{order_parts.first} #{order_type}" end end end def column_sorted?(key) key.to_s == order end def default_per_page 30 end def per_page @per_page ||= default_per_page end def page @page ||= 1 end def default_per_page_options [10, 20, 30, 40, 50, 100] end def per_page_options @per_page_options ||= default_per_page_options.collect{ |n| [n.to_s, n.to_s] } end def match_options [["all", "all"], ["any", "any"]] end def order_type_options [["desc", "desc"], ["asc", "asc"]] end ############################################################################# # Can be overloaded for custom titles ############################################################################# def condition_title_for(key) title_parts = key.to_s.split('.') title = key.to_s.gsub(".", ": ").gsub("_", " ") title = title.split(" ").collect{|part| part.split("/").last.capitalize}.join(" ") if title_parts.size > 1 "Β» #{title}" else title end end def condition_options @condition_options ||= begin opts = [] definition.keys.each do |cond| opts << [condition_title_for(cond), cond.to_s] end opts = opts.sort_by{|opt| opt.first.gsub('Β»', 'zzz') } separated = [] opts.each_with_index do |opt, index| if index > 0 prev_opt_parts = opts[index-1].first.split(":") curr_opt_parts = opt.first.split(":") if (prev_opt_parts.size != curr_opt_parts.size) or (curr_opt_parts.size > 1 and (prev_opt_parts.first != curr_opt_parts.first)) key_parts = opt.last.split('.') separated << ["-------------- #{curr_opt_parts.first.gsub('Β» ', '')} --------------", "#{key_parts.first}.id"] end end separated << opt end separated end end def operator_options_for(condition_key) condition_key = condition_key.to_sym if condition_key.is_a?(String) opers = definition[condition_key] raise Wf::FilterException.new("Invalid condition #{condition_key} for filter #{self.class.name}") unless opers sorted_operators(opers).collect{|o| [o.to_s.gsub('_', ' '), o]} end # called by the list container, should be overloaded in a subclass def value_options_for(condition_key) [] end def container_for(condition_key, operator_key) condition_key = condition_key.to_sym if condition_key.is_a?(String) opers = definition[condition_key] raise Wf::FilterException.new("Invalid condition #{condition_key} for filter #{self.class.name}") unless opers oper = opers[operator_key] # if invalid operator_key was passed, use first operator oper = opers[first_sorted_operator(opers)] unless oper oper end def add_condition(condition_key, operator_key, values = []) add_condition_at(size, condition_key, operator_key, values) end def add_condition!(condition_key, operator_key, values = []) add_condition(condition_key, operator_key, values) self end def clone_with_condition(condition_key, operator_key, values = []) dup.add_condition!(condition_key, operator_key, values) end def valid_operator?(condition_key, operator_key) condition_key = condition_key.to_sym if condition_key.is_a?(String) opers = definition[condition_key] return false unless opers opers[operator_key]!=nil end def add_condition_at(index, condition_key, operator_key, values = []) values = [values] unless values.instance_of?(Array) values = values.collect{|v| v.to_s} condition_key = condition_key.to_sym if condition_key.is_a?(String) unless valid_operator?(condition_key, operator_key) opers = definition[condition_key] operator_key = first_sorted_operator(opers) end condition = Wf::FilterCondition.new(self, condition_key, operator_key, container_for(condition_key, operator_key), values) @conditions.insert(index, condition) end ############################################################################# # options always go in [NAME, KEY] format ############################################################################# def default_condition_key condition_options.first.last end ############################################################################# # options always go in [NAME, KEY] format ############################################################################# def default_operator_key(condition_key) operator_options_for(condition_key).first.last end def conditions=(new_conditions) @conditions = new_conditions end def conditions @conditions ||= [] end def condition_at(index) conditions[index] end def condition_by_key(key) conditions.each do |c| return c if c.key==key end nil end def size conditions.size end def add_default_condition_at(index) add_condition_at(index, default_condition_key, default_operator_key(default_condition_key)) end def remove_condition_at(index) conditions.delete_at(index) end def remove_all @conditions = [] end ############################################################################# # Serialization ############################################################################# def serialize_to_params(merge_params = {}) params = {} params[:wf_type] = self.class.name params[:wf_match] = match params[:wf_model] = model_class_name params[:wf_order] = order params[:wf_order_type] = order_type params[:wf_per_page] = per_page 0.upto(size - 1) do |index| condition = condition_at(index) condition.serialize_to_params(params, index) end params.merge(merge_params) end def to_url_params params = [] serialize_to_params.each do |name, value| params << "#{name.to_s}=#{ERB::Util.url_encode(value)}" end params.join("&") end def to_s to_url_params end ############################################################################# # allows to create a filter from params only ############################################################################# def self.deserialize_from_params(params) params[:wf_type] = self.name unless params[:wf_type] params[:wf_type].constantize.new(params[:wf_model]).deserialize_from_params(params) end def deserialize_from_params(params) @conditions = [] @match = params[:wf_match] || :all @key = params[:wf_key] || self.id.to_s self.model_class_name = params[:wf_model] if params[:wf_model] @per_page = params[:wf_per_page] || default_per_page @page = params[:page] || 1 @order_type = params[:wf_order_type] || default_order_type @order = params[:wf_order] || default_order self.id = params[:wf_id].to_i unless params[:wf_id].blank? self.name = params[:wf_name] unless params[:wf_name].blank? @fields = [] unless params[:wf_export_fields].blank? params[:wf_export_fields].split(",").each do |fld| @fields << fld.to_sym end end if params[:wf_export_format].blank? @format = :html else @format = params[:wf_export_format].to_sym end i = 0 while params["wf_c#{i}"] do conditon_key = params["wf_c#{i}"] operator_key = params["wf_o#{i}"] values = [] j = 0 while params["wf_v#{i}_#{j}"] do values << params["wf_v#{i}_#{j}"] j += 1 end i += 1 add_condition(conditon_key, operator_key.to_sym, values) end if params[:wf_submitted] == 'true' validate! end return self end ############################################################################# # Validations ############################################################################# def errors? (@errors and @errors.size > 0) end def empty? size == 0 end def has_condition?(key) condition_by_key(key) != nil end def valid_format? Wf::Config.default_export_formats.include?(format.to_s) end def required_conditions_met? return true if required_condition_keys.blank? sconditions = conditions.collect{|c| c.key.to_s} rconditions = required_condition_keys.collect{|c| c.to_s} not (sconditions & rconditions).empty? end def validate! @errors = {} 0.upto(size - 1) do |index| condition = condition_at(index) err = condition.validate @errors[index] = err if err end unless required_conditions_met? @errors[:filter] = "Filter must contain at least one of the following conditions: #{required_condition_keys.join(", ")}" end errors? end ############################################################################# # SQL Conditions ############################################################################# def sql_conditions @sql_conditions ||= begin if errors? all_sql_conditions = [" 1 = 2 "] else all_sql_conditions = [""] 0.upto(size - 1) do |index| condition = condition_at(index) sql_condition = condition.container.sql_condition unless sql_condition raise Wf::FilterException.new("Unsupported operator #{condition.operator_key} for container #{condition.container.class.name}") end if all_sql_conditions[0].size > 0 all_sql_conditions[0] << ( match.to_sym == :all ? " AND " : " OR ") end all_sql_conditions[0] << sql_condition[0] sql_condition[1..-1].each do |c| all_sql_conditions << c end end end all_sql_conditions end end def condition_models @condition_models ||= begin models = [] conditions.each do |condition| key_parts = condition.key.to_s.split('.') if key_parts.size > 1 models << key_parts.first.camelcase else models << model_class_name end end models << order_model models.uniq end end def debug_conditions(conds) all_conditions = [] conds.each_with_index do |c, i| cond = "" if i == 0 cond << "\"<b>#{c}</b>\"" else cond << "<br>&nbsp;&nbsp;&nbsp;<b>#{i})</b>&nbsp;" if c.is_a?(Array) cond << "[" cond << (c.collect{|v| "\"#{v.strip}\""}.join(", ")) cond << "]" elsif c.is_a?(Date) cond << "\"#{c.strftime("%Y-%m-%d")}\"" elsif c.is_a?(Time) cond << "\"#{c.strftime("%Y-%m-%d %H:%M:%S")}\"" elsif c.is_a?(Integer) cond << c.to_s else cond << "\"#{c}\"" end end all_conditions << cond end all_conditions end def debug_sql_conditions debug_conditions(sql_conditions) end ############################################################################# # Saved Filters ############################################################################# def saved_filters(include_default = true) @saved_filters ||= begin filters = [] if include_default filters = default_filters if (filters.size > 0) filters.insert(0, ["-- Select Default Filter --", "-1"]) end end if include_default conditions = ["type = ? and model_class_name = ?", self.class.name, self.model_class_name] else conditions = ["model_class_name = ?", self.model_class_name] end if Wf::Config.user_filters_enabled? conditions[0] << " and user_id = ? " if Wf::Config.current_user and Wf::Config.current_user.id conditions << Wf::Config.current_user.id else conditions << "0" end end user_filters = Wf::Filter.find(:all, :conditions => conditions) if user_filters.size > 0 filters << ["-- Select Saved Filter --", "-2"] if include_default user_filters.each do |filter| filters << [filter.name, filter.id.to_s] end end filters end end ############################################################################# # overload this method if you don't want to allow empty filters ############################################################################# def default_filter_if_empty nil end def handle_empty_filter! return unless empty? return if default_filter_if_empty.nil? load_filter!(default_filter_if_empty) end def default_filters [] end def default_filter_conditions(key) [] end def load_default_filter(key) default_conditions = default_filter_conditions(key) return if default_conditions.nil? or default_conditions.empty? unless default_conditions.first.is_a?(Array) add_condition(*default_conditions) return end default_conditions.each do |default_condition| add_condition(*default_condition) end end def reset! remove_all @sql_conditions = nil @results = nil end def load_filter!(key_or_id) reset! @key = key_or_id.to_s load_default_filter(key) return self unless empty? filter = Wf::Filter.find_by_id(key_or_id.to_i) raise Wf::FilterException.new("Invalid filter key #{key_or_id.to_s}") if filter.nil? filter end ############################################################################# # Export Filter Data ############################################################################# def export_formats formats = [] formats << ["-- Generic Formats --", -1] Wf::Config.default_export_formats.each do |frmt| formats << [frmt, frmt] end if custom_formats.size > 0 formats << ["-- Custom Formats --", -2] custom_formats.each do |frmt| formats << frmt end end formats end def custom_format? custom_formats.each do |frmt| return true if frmt[1].to_sym == format end false end def custom_formats [] end def process_custom_format "" end def joins @joins ||= begin required_joins = [] return nil if inner_joins.empty? inner_joins.each do |inner_join| join_model_name = inner_join.first.to_s.camelcase next unless condition_models.include?(join_model_name) join_table_name = join_model_name.constantize.table_name join_on_field = inner_join.last.to_s required_joins << "INNER JOIN #{join_table_name} ON #{join_table_name}.id = #{table_name}.#{join_on_field}" end required_joins end end def results @results ||= begin handle_empty_filter! recs = model_class.paginate(:order => order_clause, :page => page, :per_page => per_page, :conditions => sql_conditions, :joins => joins) recs.wf_filter = self recs end end # sums up the column for the given conditions def sum(column_name) model_class.sum(column_name, :conditions => sql_conditions) end end fixed will_fitler special character issue #-- # Copyright (c) 2010 Michael Berkovich, Geni Inc # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #++ class Wf::Filter < ActiveRecord::Base JOIN_NAME_INDICATOR = '>' set_table_name :wf_filters serialize :data ############################################################################# # Basics ############################################################################# def initialize(model_class) super() self.model_class_name = model_class.to_s end def dup super.tap {|ii| ii.conditions = self.conditions.dup} end def before_save self.data = serialize_to_params self.type = self.class.name end def after_find @errors = {} deserialize_from_params(self.data) end ############################################################################# # Defaults ############################################################################# def show_export_options? Wf::Config.exporting_enabled? end def show_save_options? Wf::Config.saving_enabled? end def match @match ||= :all end def key @key ||= '' end def errors @errors ||= {} end def format @format ||= :html end def fields @fields ||= [] end ############################################################################# # a list of indexed fields where at least one of them has to be in a query # otherwise the filter may hang the database ############################################################################# def required_condition_keys [] end def model_class return nil unless model_class_name @model_class ||= model_class_name.constantize end def table_name model_class.table_name end def key=(new_key) @key = new_key end def match=(new_match) @match = new_match end ############################################################################# # Inner Joins come in a form of # [[joining_model_name, column_name], [joining_model_name, column_name]] ############################################################################# def inner_joins [] end def model_columns model_class.columns end def model_column_keys model_columns.collect{|col| col.name.to_sym} end def contains_column?(key) model_column_keys.index(key) != nil end def definition @definition ||= begin defs = {} model_columns.each do |col| defs[col.name.to_sym] = default_condition_definition_for(col.name, col.sql_type) end inner_joins.each do |inner_join| join_class = inner_join.first.to_s.camelcase.constantize join_class.columns.each do |col| defs[:"#{join_class.to_s.underscore}.#{col.name.to_sym}"] = default_condition_definition_for(col.name, col.sql_type) end end defs end end def container_by_sql_type(type) raise Wf::FilterException.new("Unsupported data type #{type}") unless Wf::Config.data_types[type] Wf::Config.data_types[type] end def default_condition_definition_for(name, sql_data_type) type = sql_data_type.split(" ").first.split("(").first.downcase containers = container_by_sql_type(type) operators = {} containers.each do |c| raise Wf::FilterException.new("Unsupported container implementation for #{c}") unless Wf::Config.containers[c] container_klass = Wf::Config.containers[c].constantize container_klass.operators.each do |o| operators[o] = c end end if name == "id" operators[:is_filtered_by] = :filter_list elsif "_id" == name[-3..-1] begin name[0..-4].camelcase.constantize operators[:is_filtered_by] = :filter_list rescue end end operators end def sorted_operators(opers) (Wf::Config.operator_order & opers.keys.collect{|o| o.to_s}) end def first_sorted_operator(opers) sorted_operators(opers).first.to_sym end def default_order 'id' end def order @order ||= default_order end def default_order_type 'desc' end def order_type @order_type ||= default_order_type end def order_model @order_model ||= begin order_parts = order.split('.') if order_parts.size > 1 order_parts.first.camelcase else model_class_name end end end def order_clause @order_clause ||= begin order_parts = order.split('.') if order_parts.size > 1 "#{order_parts.first.camelcase.constantize.table_name}.#{order_parts.last} #{order_type}" else "#{model_class_name.constantize.table_name}.#{order_parts.first} #{order_type}" end end end def column_sorted?(key) key.to_s == order end def default_per_page 30 end def per_page @per_page ||= default_per_page end def page @page ||= 1 end def default_per_page_options [10, 20, 30, 40, 50, 100] end def per_page_options @per_page_options ||= default_per_page_options.collect{ |n| [n.to_s, n.to_s] } end def match_options [["all", "all"], ["any", "any"]] end def order_type_options [["desc", "desc"], ["asc", "asc"]] end ############################################################################# # Can be overloaded for custom titles ############################################################################# def condition_title_for(key) title_parts = key.to_s.split('.') title = key.to_s.gsub(".", ": ").gsub("_", " ") title = title.split(" ").collect{|part| part.split("/").last.capitalize}.join(" ") if title_parts.size > 1 "#{JOIN_NAME_INDICATOR} #{title}" else title end end def condition_options @condition_options ||= begin opts = [] definition.keys.each do |cond| opts << [condition_title_for(cond), cond.to_s] end opts = opts.sort_by{|opt| opt.first.gsub(JOIN_NAME_INDICATOR, 'zzz') } separated = [] opts.each_with_index do |opt, index| if index > 0 prev_opt_parts = opts[index-1].first.split(":") curr_opt_parts = opt.first.split(":") if (prev_opt_parts.size != curr_opt_parts.size) or (curr_opt_parts.size > 1 and (prev_opt_parts.first != curr_opt_parts.first)) key_parts = opt.last.split('.') separated << ["-------------- #{curr_opt_parts.first.gsub("#{JOIN_NAME_INDICATOR} ", '')} --------------", "#{key_parts.first}.id"] end end separated << opt end separated end end def operator_options_for(condition_key) condition_key = condition_key.to_sym if condition_key.is_a?(String) opers = definition[condition_key] raise Wf::FilterException.new("Invalid condition #{condition_key} for filter #{self.class.name}") unless opers sorted_operators(opers).collect{|o| [o.to_s.gsub('_', ' '), o]} end # called by the list container, should be overloaded in a subclass def value_options_for(condition_key) [] end def container_for(condition_key, operator_key) condition_key = condition_key.to_sym if condition_key.is_a?(String) opers = definition[condition_key] raise Wf::FilterException.new("Invalid condition #{condition_key} for filter #{self.class.name}") unless opers oper = opers[operator_key] # if invalid operator_key was passed, use first operator oper = opers[first_sorted_operator(opers)] unless oper oper end def add_condition(condition_key, operator_key, values = []) add_condition_at(size, condition_key, operator_key, values) end def add_condition!(condition_key, operator_key, values = []) add_condition(condition_key, operator_key, values) self end def clone_with_condition(condition_key, operator_key, values = []) dup.add_condition!(condition_key, operator_key, values) end def valid_operator?(condition_key, operator_key) condition_key = condition_key.to_sym if condition_key.is_a?(String) opers = definition[condition_key] return false unless opers opers[operator_key]!=nil end def add_condition_at(index, condition_key, operator_key, values = []) values = [values] unless values.instance_of?(Array) values = values.collect{|v| v.to_s} condition_key = condition_key.to_sym if condition_key.is_a?(String) unless valid_operator?(condition_key, operator_key) opers = definition[condition_key] operator_key = first_sorted_operator(opers) end condition = Wf::FilterCondition.new(self, condition_key, operator_key, container_for(condition_key, operator_key), values) @conditions.insert(index, condition) end ############################################################################# # options always go in [NAME, KEY] format ############################################################################# def default_condition_key condition_options.first.last end ############################################################################# # options always go in [NAME, KEY] format ############################################################################# def default_operator_key(condition_key) operator_options_for(condition_key).first.last end def conditions=(new_conditions) @conditions = new_conditions end def conditions @conditions ||= [] end def condition_at(index) conditions[index] end def condition_by_key(key) conditions.each do |c| return c if c.key==key end nil end def size conditions.size end def add_default_condition_at(index) add_condition_at(index, default_condition_key, default_operator_key(default_condition_key)) end def remove_condition_at(index) conditions.delete_at(index) end def remove_all @conditions = [] end ############################################################################# # Serialization ############################################################################# def serialize_to_params(merge_params = {}) params = {} params[:wf_type] = self.class.name params[:wf_match] = match params[:wf_model] = model_class_name params[:wf_order] = order params[:wf_order_type] = order_type params[:wf_per_page] = per_page 0.upto(size - 1) do |index| condition = condition_at(index) condition.serialize_to_params(params, index) end params.merge(merge_params) end def to_url_params params = [] serialize_to_params.each do |name, value| params << "#{name.to_s}=#{ERB::Util.url_encode(value)}" end params.join("&") end def to_s to_url_params end ############################################################################# # allows to create a filter from params only ############################################################################# def self.deserialize_from_params(params) params[:wf_type] = self.name unless params[:wf_type] params[:wf_type].constantize.new(params[:wf_model]).deserialize_from_params(params) end def deserialize_from_params(params) @conditions = [] @match = params[:wf_match] || :all @key = params[:wf_key] || self.id.to_s self.model_class_name = params[:wf_model] if params[:wf_model] @per_page = params[:wf_per_page] || default_per_page @page = params[:page] || 1 @order_type = params[:wf_order_type] || default_order_type @order = params[:wf_order] || default_order self.id = params[:wf_id].to_i unless params[:wf_id].blank? self.name = params[:wf_name] unless params[:wf_name].blank? @fields = [] unless params[:wf_export_fields].blank? params[:wf_export_fields].split(",").each do |fld| @fields << fld.to_sym end end if params[:wf_export_format].blank? @format = :html else @format = params[:wf_export_format].to_sym end i = 0 while params["wf_c#{i}"] do conditon_key = params["wf_c#{i}"] operator_key = params["wf_o#{i}"] values = [] j = 0 while params["wf_v#{i}_#{j}"] do values << params["wf_v#{i}_#{j}"] j += 1 end i += 1 add_condition(conditon_key, operator_key.to_sym, values) end if params[:wf_submitted] == 'true' validate! end return self end ############################################################################# # Validations ############################################################################# def errors? (@errors and @errors.size > 0) end def empty? size == 0 end def has_condition?(key) condition_by_key(key) != nil end def valid_format? Wf::Config.default_export_formats.include?(format.to_s) end def required_conditions_met? return true if required_condition_keys.blank? sconditions = conditions.collect{|c| c.key.to_s} rconditions = required_condition_keys.collect{|c| c.to_s} not (sconditions & rconditions).empty? end def validate! @errors = {} 0.upto(size - 1) do |index| condition = condition_at(index) err = condition.validate @errors[index] = err if err end unless required_conditions_met? @errors[:filter] = "Filter must contain at least one of the following conditions: #{required_condition_keys.join(", ")}" end errors? end ############################################################################# # SQL Conditions ############################################################################# def sql_conditions @sql_conditions ||= begin if errors? all_sql_conditions = [" 1 = 2 "] else all_sql_conditions = [""] 0.upto(size - 1) do |index| condition = condition_at(index) sql_condition = condition.container.sql_condition unless sql_condition raise Wf::FilterException.new("Unsupported operator #{condition.operator_key} for container #{condition.container.class.name}") end if all_sql_conditions[0].size > 0 all_sql_conditions[0] << ( match.to_sym == :all ? " AND " : " OR ") end all_sql_conditions[0] << sql_condition[0] sql_condition[1..-1].each do |c| all_sql_conditions << c end end end all_sql_conditions end end def condition_models @condition_models ||= begin models = [] conditions.each do |condition| key_parts = condition.key.to_s.split('.') if key_parts.size > 1 models << key_parts.first.camelcase else models << model_class_name end end models << order_model models.uniq end end def debug_conditions(conds) all_conditions = [] conds.each_with_index do |c, i| cond = "" if i == 0 cond << "\"<b>#{c}</b>\"" else cond << "<br>&nbsp;&nbsp;&nbsp;<b>#{i})</b>&nbsp;" if c.is_a?(Array) cond << "[" cond << (c.collect{|v| "\"#{v.strip}\""}.join(", ")) cond << "]" elsif c.is_a?(Date) cond << "\"#{c.strftime("%Y-%m-%d")}\"" elsif c.is_a?(Time) cond << "\"#{c.strftime("%Y-%m-%d %H:%M:%S")}\"" elsif c.is_a?(Integer) cond << c.to_s else cond << "\"#{c}\"" end end all_conditions << cond end all_conditions end def debug_sql_conditions debug_conditions(sql_conditions) end ############################################################################# # Saved Filters ############################################################################# def saved_filters(include_default = true) @saved_filters ||= begin filters = [] if include_default filters = default_filters if (filters.size > 0) filters.insert(0, ["-- Select Default Filter --", "-1"]) end end if include_default conditions = ["type = ? and model_class_name = ?", self.class.name, self.model_class_name] else conditions = ["model_class_name = ?", self.model_class_name] end if Wf::Config.user_filters_enabled? conditions[0] << " and user_id = ? " if Wf::Config.current_user and Wf::Config.current_user.id conditions << Wf::Config.current_user.id else conditions << "0" end end user_filters = Wf::Filter.find(:all, :conditions => conditions) if user_filters.size > 0 filters << ["-- Select Saved Filter --", "-2"] if include_default user_filters.each do |filter| filters << [filter.name, filter.id.to_s] end end filters end end ############################################################################# # overload this method if you don't want to allow empty filters ############################################################################# def default_filter_if_empty nil end def handle_empty_filter! return unless empty? return if default_filter_if_empty.nil? load_filter!(default_filter_if_empty) end def default_filters [] end def default_filter_conditions(key) [] end def load_default_filter(key) default_conditions = default_filter_conditions(key) return if default_conditions.nil? or default_conditions.empty? unless default_conditions.first.is_a?(Array) add_condition(*default_conditions) return end default_conditions.each do |default_condition| add_condition(*default_condition) end end def reset! remove_all @sql_conditions = nil @results = nil end def load_filter!(key_or_id) reset! @key = key_or_id.to_s load_default_filter(key) return self unless empty? filter = Wf::Filter.find_by_id(key_or_id.to_i) raise Wf::FilterException.new("Invalid filter key #{key_or_id.to_s}") if filter.nil? filter end ############################################################################# # Export Filter Data ############################################################################# def export_formats formats = [] formats << ["-- Generic Formats --", -1] Wf::Config.default_export_formats.each do |frmt| formats << [frmt, frmt] end if custom_formats.size > 0 formats << ["-- Custom Formats --", -2] custom_formats.each do |frmt| formats << frmt end end formats end def custom_format? custom_formats.each do |frmt| return true if frmt[1].to_sym == format end false end def custom_formats [] end def process_custom_format "" end def joins @joins ||= begin required_joins = [] return nil if inner_joins.empty? inner_joins.each do |inner_join| join_model_name = inner_join.first.to_s.camelcase next unless condition_models.include?(join_model_name) join_table_name = join_model_name.constantize.table_name join_on_field = inner_join.last.to_s required_joins << "INNER JOIN #{join_table_name} ON #{join_table_name}.id = #{table_name}.#{join_on_field}" end required_joins end end def results @results ||= begin handle_empty_filter! recs = model_class.paginate(:order => order_clause, :page => page, :per_page => per_page, :conditions => sql_conditions, :joins => joins) recs.wf_filter = self recs end end # sums up the column for the given conditions def sum(column_name) model_class.sum(column_name, :conditions => sql_conditions) end end
require "spec_helper" describe Notifications do describe "shipped" do before :all do @user = FactoryGirl.create(:user) end let(:mail) { Notifications.shipped(@user) } it "renders the headers" do mail.subject.should eq("Your SeedPod is on its way!") mail.to.should eq([@user.email]) mail.from.should eq(["greetings@getseedpod.com"]) end it "renders the body" do mail.body.encoded.should match("Hi #{@user.name},") end end end fix test flicker on name encoding require "spec_helper" describe Notifications do describe "shipped" do before :all do @user = FactoryGirl.create(:user) end let(:mail) { Notifications.shipped(@user) } it "renders the headers" do mail.subject.should eq("Your SeedPod is on its way!") mail.to.should eq([@user.email]) mail.from.should eq(["greetings@getseedpod.com"]) end it "renders the body" do mail.body.encoded.should match("Hi #{CGI.escapeHTML(@user.name)},") end end end
RSpec.describe Regexp, "#random_example" do def self.random_example_matches(*regexps) regexps.each do |regexp| it "random example for /#{regexp.source}/" do random_example = regexp.random_example expect(random_example).to be_a String # Not an Array! expect(random_example).to match(Regexp.new("\\A(?:#{regexp.source})\\z", regexp.options)) end end end context "smoke tests" do # Just a few "smoke tests", to ensure the basic method isn't broken. # Testing of the RegexpExamples::Parser class is all covered by Regexp#examples test already. random_example_matches( /\w{10}/, /(we(need(to(go(deeper)?)?)?)?) \1/, /case insensitive/i ) end end Test for random_example with OrGroup Missing test area for 100% coverage RSpec.describe Regexp, "#random_example" do def self.random_example_matches(*regexps) regexps.each do |regexp| it "random example for /#{regexp.source}/" do random_example = regexp.random_example expect(random_example).to be_a String # Not an Array! expect(random_example).to match(Regexp.new("\\A(?:#{regexp.source})\\z", regexp.options)) end end end context "smoke tests" do # Just a few "smoke tests", to ensure the basic method isn't broken. # Testing of the RegexpExamples::Parser class is all covered by Regexp#examples test already. random_example_matches( /\w{10}/, /(we(need(to(go(deeper)?)?)?)?) \1/, /case insensitive/i, /front seat|back seat/, # Which seat will I take?? ) end end
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Generator do subject(:generator) do described_class.new(cop_identifier, 'your_id', output: stdout) end let(:stdout) { StringIO.new } let(:cop_identifier) { 'Style/FakeCop' } before do allow(File).to receive(:write) stub_const('HOME_DIR', Dir.pwd) end describe '#write_source' do include_context 'cli spec behavior' it 'generates a helpful source file with the name filled in' do generated_source = <<~RUBY # frozen_string_literal: true # TODO: when finished, run `rake generate_cops_documentation` to update the docs module RuboCop module Cop module Style # TODO: Write cop description and example of bad / good code. For every # `SupportedStyle` and unique configuration, there needs to be examples. # Examples must have valid Ruby syntax. Do not use upticks. # # @example EnforcedStyle: bar (default) # # Description of the `bar` style. # # # bad # bad_bar_method # # # bad # bad_bar_method(args) # # # good # good_bar_method # # # good # good_bar_method(args) # # @example EnforcedStyle: foo # # Description of the `foo` style. # # # bad # bad_foo_method # # # bad # bad_foo_method(args) # # # good # good_foo_method # # # good # good_foo_method(args) # class FakeCop < Base # TODO: Implement the cop in here. # # In many cases, you can use a node matcher for matching node pattern. # See https://github.com/rubocop-hq/rubocop-ast/blob/master/lib/rubocop/ast/node_pattern.rb # # For example MSG = 'Use `#good_method` instead of `#bad_method`.' def_node_matcher :bad_method?, <<~PATTERN (send nil? :bad_method ...) PATTERN def on_send(node) return unless bad_method?(node) add_offense(node) end end end end end RUBY expect(File) .to receive(:write) .with('lib/rubocop/cop/style/fake_cop.rb', generated_source) generator.write_source expect(stdout.string) .to eq("[create] lib/rubocop/cop/style/fake_cop.rb\n") end it 'refuses to overwrite existing files' do new_cop = described_class.new('Layout/IndentationStyle', 'your_id') allow(new_cop).to receive(:exit!) expect { new_cop.write_source } .to output( 'rake new_cop: lib/rubocop/cop/layout/indentation_style.rb '\ "already exists!\n" ).to_stderr end end describe '#write_spec' do include_context 'cli spec behavior' it 'generates a helpful starting spec file with the class filled in' do generated_source = <<~SPEC # frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::FakeCop do subject(:cop) { described_class.new(config) } let(:config) { RuboCop::Config.new } # TODO: Write test code # # For example it 'registers an offense when using `#bad_method`' do expect_offense(<<~RUBY) bad_method ^^^^^^^^^^ Use `#good_method` instead of `#bad_method`. RUBY end it 'does not register an offense when using `#good_method`' do expect_no_offenses(<<~RUBY) good_method RUBY end end SPEC expect(File) .to receive(:write) .with('spec/rubocop/cop/style/fake_cop_spec.rb', generated_source) generator.write_spec end it 'refuses to overwrite existing files' do new_cop = described_class.new('Layout/IndentationStyle', 'your_id') allow(new_cop).to receive(:exit!) expect { new_cop.write_spec } .to output( 'rake new_cop: spec/rubocop/cop/layout/indentation_style_spec.rb '\ "already exists!\n" ).to_stderr end end describe '#todo' do it 'provides a checklist for implementing the cop' do expect(generator.todo).to eql(<<~TODO) Do 3 steps: 1. Add an entry to the "New features" section in CHANGELOG.md, e.g. "Add new `Style/FakeCop` cop. ([@your_id][])" 2. Modify the description of Style/FakeCop in config/default.yml 3. Implement your new cop in the generated file! TODO end end describe '.new' do it 'does not accept an unqualified cop' do expect { described_class.new('FakeCop', 'your_id') } .to raise_error(ArgumentError) .with_message('Specify a cop name with Department/Name style') end end describe '#inject_config' do let(:path) { @path } # rubocop:disable RSpec/InstanceVariable around do |example| Tempfile.create('rubocop-config.yml') do |file| @path = file.path example.run end end before do IO.write(path, <<~YAML) Style/Alias: Enabled: true Style/Lambda: Enabled: true Style/SpecialGlobalVars: Enabled: true YAML stub_const('RuboCop::Version::STRING', '0.58.2') end context 'when it is the middle in alphabetical order' do it 'inserts the cop' do expect(File).to receive(:write).with(path, <<~YAML) Style/Alias: Enabled: true Style/FakeCop: Description: 'TODO: Write a description of the cop.' Enabled: pending VersionAdded: '0.59' Style/Lambda: Enabled: true Style/SpecialGlobalVars: Enabled: true YAML generator.inject_config(config_file_path: path) expect(stdout.string) .to eq('[modify] A configuration for the cop is added into ' \ "#{path}.\n") end end context 'when it is the first in alphabetical order' do let(:cop_identifier) { 'Style/Aaa' } it 'inserts the cop' do expect(File).to receive(:write).with(path, <<~YAML) Style/Aaa: Description: 'TODO: Write a description of the cop.' Enabled: pending VersionAdded: '0.59' Style/Alias: Enabled: true Style/Lambda: Enabled: true Style/SpecialGlobalVars: Enabled: true YAML generator.inject_config(config_file_path: path) expect(stdout.string) .to eq('[modify] A configuration for the cop is added into ' \ "#{path}.\n") end end context 'when it is the last in alphabetical order' do let(:cop_identifier) { 'Style/Zzz' } it 'inserts the cop' do expect(File).to receive(:write).with(path, <<~YAML) Style/Alias: Enabled: true Style/Lambda: Enabled: true Style/SpecialGlobalVars: Enabled: true Style/Zzz: Description: 'TODO: Write a description of the cop.' Enabled: pending VersionAdded: '0.59' YAML generator.inject_config(config_file_path: path) expect(stdout.string) .to eq('[modify] A configuration for the cop is added into ' \ "#{path}.\n") end end context 'with version provided' do it 'uses the provided version' do expect(File).to receive(:write).with(path, <<~YAML) Style/Alias: Enabled: true Style/FakeCop: Description: 'TODO: Write a description of the cop.' Enabled: pending VersionAdded: '1.52' Style/Lambda: Enabled: true Style/SpecialGlobalVars: Enabled: true YAML generator.inject_config(config_file_path: path, version_added: '1.52') end end end describe '#snake_case' do it 'converts "Lint" to snake_case' do expect(generator.__send__(:snake_case, 'Lint')).to eq('lint') end it 'converts "FooBar" to snake_case' do expect(generator.__send__(:snake_case, 'FooBar')).to eq('foo_bar') end it 'converts "RSpec" to snake_case' do expect(generator.__send__(:snake_case, 'RSpec')).to eq('rspec') end end describe 'compliance with rubocop', :isolated_environment do include FileHelper around do |example| new_global = RuboCop::Cop::Registry.new( [RuboCop::Cop::InternalAffairs::NodeDestructuring] ) RuboCop::Cop::Registry.with_temporary_global(new_global) { example.run } end let(:config) do config = RuboCop::ConfigStore.new path = File.join(RuboCop::ConfigLoader::RUBOCOP_HOME, RuboCop::ConfigLoader::DOTFILE) config.options_config = path config end let(:options) { { formatters: [] } } let(:runner) { RuboCop::Runner.new(options, config) } it 'generates a cop file that has no offense' do generator.write_source expect(runner.run([])).to be true end # TODO: include it back after rubocop-rspec updated to support deep departments names xit 'generates a spec file that has no offense' do generator.write_spec expect(runner.run([])).to be true end end end Re-enable spec after rubocop-rspec 2.0 # frozen_string_literal: true RSpec.describe RuboCop::Cop::Generator do subject(:generator) do described_class.new(cop_identifier, 'your_id', output: stdout) end let(:stdout) { StringIO.new } let(:cop_identifier) { 'Style/FakeCop' } before do allow(File).to receive(:write) stub_const('HOME_DIR', Dir.pwd) end describe '#write_source' do include_context 'cli spec behavior' it 'generates a helpful source file with the name filled in' do generated_source = <<~RUBY # frozen_string_literal: true # TODO: when finished, run `rake generate_cops_documentation` to update the docs module RuboCop module Cop module Style # TODO: Write cop description and example of bad / good code. For every # `SupportedStyle` and unique configuration, there needs to be examples. # Examples must have valid Ruby syntax. Do not use upticks. # # @example EnforcedStyle: bar (default) # # Description of the `bar` style. # # # bad # bad_bar_method # # # bad # bad_bar_method(args) # # # good # good_bar_method # # # good # good_bar_method(args) # # @example EnforcedStyle: foo # # Description of the `foo` style. # # # bad # bad_foo_method # # # bad # bad_foo_method(args) # # # good # good_foo_method # # # good # good_foo_method(args) # class FakeCop < Base # TODO: Implement the cop in here. # # In many cases, you can use a node matcher for matching node pattern. # See https://github.com/rubocop-hq/rubocop-ast/blob/master/lib/rubocop/ast/node_pattern.rb # # For example MSG = 'Use `#good_method` instead of `#bad_method`.' def_node_matcher :bad_method?, <<~PATTERN (send nil? :bad_method ...) PATTERN def on_send(node) return unless bad_method?(node) add_offense(node) end end end end end RUBY expect(File) .to receive(:write) .with('lib/rubocop/cop/style/fake_cop.rb', generated_source) generator.write_source expect(stdout.string) .to eq("[create] lib/rubocop/cop/style/fake_cop.rb\n") end it 'refuses to overwrite existing files' do new_cop = described_class.new('Layout/IndentationStyle', 'your_id') allow(new_cop).to receive(:exit!) expect { new_cop.write_source } .to output( 'rake new_cop: lib/rubocop/cop/layout/indentation_style.rb '\ "already exists!\n" ).to_stderr end end describe '#write_spec' do include_context 'cli spec behavior' it 'generates a helpful starting spec file with the class filled in' do generated_source = <<~SPEC # frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::FakeCop do subject(:cop) { described_class.new(config) } let(:config) { RuboCop::Config.new } # TODO: Write test code # # For example it 'registers an offense when using `#bad_method`' do expect_offense(<<~RUBY) bad_method ^^^^^^^^^^ Use `#good_method` instead of `#bad_method`. RUBY end it 'does not register an offense when using `#good_method`' do expect_no_offenses(<<~RUBY) good_method RUBY end end SPEC expect(File) .to receive(:write) .with('spec/rubocop/cop/style/fake_cop_spec.rb', generated_source) generator.write_spec end it 'refuses to overwrite existing files' do new_cop = described_class.new('Layout/IndentationStyle', 'your_id') allow(new_cop).to receive(:exit!) expect { new_cop.write_spec } .to output( 'rake new_cop: spec/rubocop/cop/layout/indentation_style_spec.rb '\ "already exists!\n" ).to_stderr end end describe '#todo' do it 'provides a checklist for implementing the cop' do expect(generator.todo).to eql(<<~TODO) Do 3 steps: 1. Add an entry to the "New features" section in CHANGELOG.md, e.g. "Add new `Style/FakeCop` cop. ([@your_id][])" 2. Modify the description of Style/FakeCop in config/default.yml 3. Implement your new cop in the generated file! TODO end end describe '.new' do it 'does not accept an unqualified cop' do expect { described_class.new('FakeCop', 'your_id') } .to raise_error(ArgumentError) .with_message('Specify a cop name with Department/Name style') end end describe '#inject_config' do let(:path) { @path } # rubocop:disable RSpec/InstanceVariable around do |example| Tempfile.create('rubocop-config.yml') do |file| @path = file.path example.run end end before do IO.write(path, <<~YAML) Style/Alias: Enabled: true Style/Lambda: Enabled: true Style/SpecialGlobalVars: Enabled: true YAML stub_const('RuboCop::Version::STRING', '0.58.2') end context 'when it is the middle in alphabetical order' do it 'inserts the cop' do expect(File).to receive(:write).with(path, <<~YAML) Style/Alias: Enabled: true Style/FakeCop: Description: 'TODO: Write a description of the cop.' Enabled: pending VersionAdded: '0.59' Style/Lambda: Enabled: true Style/SpecialGlobalVars: Enabled: true YAML generator.inject_config(config_file_path: path) expect(stdout.string) .to eq('[modify] A configuration for the cop is added into ' \ "#{path}.\n") end end context 'when it is the first in alphabetical order' do let(:cop_identifier) { 'Style/Aaa' } it 'inserts the cop' do expect(File).to receive(:write).with(path, <<~YAML) Style/Aaa: Description: 'TODO: Write a description of the cop.' Enabled: pending VersionAdded: '0.59' Style/Alias: Enabled: true Style/Lambda: Enabled: true Style/SpecialGlobalVars: Enabled: true YAML generator.inject_config(config_file_path: path) expect(stdout.string) .to eq('[modify] A configuration for the cop is added into ' \ "#{path}.\n") end end context 'when it is the last in alphabetical order' do let(:cop_identifier) { 'Style/Zzz' } it 'inserts the cop' do expect(File).to receive(:write).with(path, <<~YAML) Style/Alias: Enabled: true Style/Lambda: Enabled: true Style/SpecialGlobalVars: Enabled: true Style/Zzz: Description: 'TODO: Write a description of the cop.' Enabled: pending VersionAdded: '0.59' YAML generator.inject_config(config_file_path: path) expect(stdout.string) .to eq('[modify] A configuration for the cop is added into ' \ "#{path}.\n") end end context 'with version provided' do it 'uses the provided version' do expect(File).to receive(:write).with(path, <<~YAML) Style/Alias: Enabled: true Style/FakeCop: Description: 'TODO: Write a description of the cop.' Enabled: pending VersionAdded: '1.52' Style/Lambda: Enabled: true Style/SpecialGlobalVars: Enabled: true YAML generator.inject_config(config_file_path: path, version_added: '1.52') end end end describe '#snake_case' do it 'converts "Lint" to snake_case' do expect(generator.__send__(:snake_case, 'Lint')).to eq('lint') end it 'converts "FooBar" to snake_case' do expect(generator.__send__(:snake_case, 'FooBar')).to eq('foo_bar') end it 'converts "RSpec" to snake_case' do expect(generator.__send__(:snake_case, 'RSpec')).to eq('rspec') end end describe 'compliance with rubocop', :isolated_environment do include FileHelper around do |example| new_global = RuboCop::Cop::Registry.new( [RuboCop::Cop::InternalAffairs::NodeDestructuring] ) RuboCop::Cop::Registry.with_temporary_global(new_global) { example.run } end let(:config) do config = RuboCop::ConfigStore.new path = File.join(RuboCop::ConfigLoader::RUBOCOP_HOME, RuboCop::ConfigLoader::DOTFILE) config.options_config = path config end let(:options) { { formatters: [] } } let(:runner) { RuboCop::Runner.new(options, config) } it 'generates a cop file that has no offense' do generator.write_source expect(runner.run([])).to be true end it 'generates a spec file that has no offense' do generator.write_spec expect(runner.run([])).to be true end end end
require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../fixtures/classes', __FILE__) require File.expand_path('../shared/iteration', __FILE__) describe "Hash#reject" do it "is equivalent to hsh.dup.delete_if" do h = new_hash(:a => 'a', :b => 'b', :c => 'd') h.reject { |k,v| k == 'd' }.should == (h.dup.delete_if { |k, v| k == 'd' }) all_args_reject = [] all_args_delete_if = [] h = new_hash(1 => 2, 3 => 4) h.reject { |*args| all_args_reject << args } h.delete_if { |*args| all_args_delete_if << args } all_args_reject.should == all_args_delete_if h = new_hash(1 => 2) # dup doesn't copy singleton methods def h.to_a() end h.reject { false }.to_a.should == [[1, 2]] end it "returns subclass instance for subclasses" do HashSpecs::MyHash[1 => 2, 3 => 4].reject { false }.should be_kind_of(HashSpecs::MyHash) HashSpecs::MyHash[1 => 2, 3 => 4].reject { true }.should be_kind_of(HashSpecs::MyHash) end it "taints the resulting hash" do h = new_hash(:a => 1).taint h.reject {false}.tainted?.should == true end it "processes entries with the same order as reject!" do h = new_hash(:a => 1, :b => 2, :c => 3, :d => 4) reject_pairs = [] reject_bang_pairs = [] h.dup.reject { |*pair| reject_pairs << pair } h.reject! { |*pair| reject_bang_pairs << pair } reject_pairs.should == reject_bang_pairs end it_behaves_like(:hash_iteration_no_block, :reject) end describe "Hash#reject!" do before(:each) do @hsh = new_hash(1 => 2, 3 => 4, 5 => 6) @empty = new_hash end it "is equivalent to delete_if if changes are made" do new_hash(:a => 2).reject! { |k,v| v > 1 }.should == new_hash(:a => 2).delete_if { |k, v| v > 1 } h = new_hash(1 => 2, 3 => 4) all_args_reject = [] all_args_delete_if = [] h.dup.reject! { |*args| all_args_reject << args } h.dup.delete_if { |*args| all_args_delete_if << args } all_args_reject.should == all_args_delete_if end it "returns nil if no changes were made" do new_hash(:a => 1).reject! { |k,v| v > 1 }.should == nil end it "processes entries with the same order as delete_if" do h = new_hash(:a => 1, :b => 2, :c => 3, :d => 4) reject_bang_pairs = [] delete_if_pairs = [] h.dup.reject! { |*pair| reject_bang_pairs << pair } h.dup.delete_if { |*pair| delete_if_pairs << pair } reject_bang_pairs.should == delete_if_pairs end ruby_version_is ""..."1.9" do it "raises a TypeError if called on a frozen instance" do lambda { HashSpecs.frozen_hash.reject! { false } }.should raise_error(TypeError) lambda { HashSpecs.empty_frozen_hash.reject! { true } }.should raise_error(TypeError) end end ruby_version_is "1.9" do it "raises a RuntimeError if called on a frozen instance that is modified" do lambda { HashSpecs.empty_frozen_hash.reject! { true } }.should raise_error(RuntimeError) end it "raises a RuntimeError if called on a frozen instance that would not be modified" do lambda { HashSpecs.frozen_hash.reject! { false } }.should raise_error(RuntimeError) end end ruby_version_is "" ... "1.8.7" do it "raises a LocalJumpError when called on a non-empty hash without a block" do lambda { @hsh.reject! }.should raise_error(LocalJumpError) end it "does not raise a LocalJumpError when called on an empty hash without a block" do @empty.reject!.should == nil end end ruby_version_is "1.8.7" do it "returns an Enumerator when called on a non-empty hash without a block" do @hsh.reject!.should be_an_instance_of(enumerator_class) end it "returns an Enumerator when called on an empty hash without a block" do @empty.reject!.should be_an_instance_of(enumerator_class) end end end Updated Hash#reject spec require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../fixtures/classes', __FILE__) require File.expand_path('../shared/iteration', __FILE__) describe "Hash#reject" do it "returns a new hash removing keys for which the block yields true" do h = new_hash(1=>false, 2=>true, 3=>false, 4=>true) h.reject { |k,v| v }.keys.sort.should == [1,3] end it "is equivalent to hsh.dup.delete_if" do h = new_hash(:a => 'a', :b => 'b', :c => 'd') h.reject { |k,v| k == 'd' }.should == (h.dup.delete_if { |k, v| k == 'd' }) all_args_reject = [] all_args_delete_if = [] h = new_hash(1 => 2, 3 => 4) h.reject { |*args| all_args_reject << args } h.delete_if { |*args| all_args_delete_if << args } all_args_reject.should == all_args_delete_if h = new_hash(1 => 2) # dup doesn't copy singleton methods def h.to_a() end h.reject { false }.to_a.should == [[1, 2]] end it "returns subclass instance for subclasses" do HashSpecs::MyHash[1 => 2, 3 => 4].reject { false }.should be_kind_of(HashSpecs::MyHash) HashSpecs::MyHash[1 => 2, 3 => 4].reject { true }.should be_kind_of(HashSpecs::MyHash) end it "taints the resulting hash" do h = new_hash(:a => 1).taint h.reject {false}.tainted?.should == true end it "processes entries with the same order as reject!" do h = new_hash(:a => 1, :b => 2, :c => 3, :d => 4) reject_pairs = [] reject_bang_pairs = [] h.dup.reject { |*pair| reject_pairs << pair } h.reject! { |*pair| reject_bang_pairs << pair } reject_pairs.should == reject_bang_pairs end it_behaves_like(:hash_iteration_no_block, :reject) end describe "Hash#reject!" do before(:each) do @hsh = new_hash (1 .. 10).each { |k| @hsh[k] = k.even? } @empty = new_hash end it "removes keys from self for which the block yields true" do @hsh.reject! { |k,v| v } @hsh.keys.sort.should == [1,3,5,7,9] end it "is equivalent to delete_if if changes are made" do @hsh.reject! { |k,v| v }.should == @hsh.delete_if { |k, v| v } h = new_hash(1 => 2, 3 => 4) all_args_reject = [] all_args_delete_if = [] h.dup.reject! { |*args| all_args_reject << args } h.dup.delete_if { |*args| all_args_delete_if << args } all_args_reject.should == all_args_delete_if end it "returns nil if no changes were made" do new_hash(:a => 1).reject! { |k,v| v > 1 }.should == nil end it "processes entries with the same order as delete_if" do h = new_hash(:a => 1, :b => 2, :c => 3, :d => 4) reject_bang_pairs = [] delete_if_pairs = [] h.dup.reject! { |*pair| reject_bang_pairs << pair } h.dup.delete_if { |*pair| delete_if_pairs << pair } reject_bang_pairs.should == delete_if_pairs end ruby_version_is ""..."1.9" do it "raises a TypeError if called on a frozen instance" do lambda { HashSpecs.frozen_hash.reject! { false } }.should raise_error(TypeError) lambda { HashSpecs.empty_frozen_hash.reject! { true } }.should raise_error(TypeError) end end ruby_version_is "1.9" do it "raises a RuntimeError if called on a frozen instance that is modified" do lambda { HashSpecs.empty_frozen_hash.reject! { true } }.should raise_error(RuntimeError) end it "raises a RuntimeError if called on a frozen instance that would not be modified" do lambda { HashSpecs.frozen_hash.reject! { false } }.should raise_error(RuntimeError) end end ruby_version_is "" ... "1.8.7" do it "raises a LocalJumpError when called on a non-empty hash without a block" do lambda { @hsh.reject! }.should raise_error(LocalJumpError) end it "does not raise a LocalJumpError when called on an empty hash without a block" do @empty.reject!.should == nil end end ruby_version_is "1.8.7" do it "returns an Enumerator when called on a non-empty hash without a block" do @hsh.reject!.should be_an_instance_of(enumerator_class) end it "returns an Enumerator when called on an empty hash without a block" do @empty.reject!.should be_an_instance_of(enumerator_class) end end end
require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../fixtures/classes', __FILE__) describe "Kernel#exec" do it "is a private method" do Kernel.should have_private_instance_method(:exec) end it "raises a SystemCallError if cmd cannot execute" do lambda { exec "" }.should raise_error(SystemCallError) end it "raises a SystemCallError if cmd cannot execute and contains '-'" do lambda { exec 'cmd-plugin' }.should raise_error(SystemCallError) end it "raises an ArgumentError if the cmd includes a null byte" do lambda { exec "\000" }.should raise_error(ArgumentError) end it "raises Errno::ENOENT if the script does not exist" do lambda { exec "bogus-noent-script.sh" }.should raise_error(Errno::ENOENT) end it "runs the specified command, replacing current process" do result = `#{RUBY_EXE} -e 'exec "echo hello"; puts "fail"'` result.should == "hello\n" end ruby_version_is "1.9.2" do it "passes environment vars to the child environment" do result = `#{RUBY_EXE} -e 'exec({"FOO" => "BAR"}, "echo $FOO"); puts "fail"'` result.should == "BAR\n" end end end describe "Kernel#exec" do before :each do @script = tmp("tmp.sh") touch @script end after :each do rm_r @script end it "raises Errno::EACCES when the file does not have execute permissions" do lambda { exec @script }.should raise_error(Errno::EACCES) end it "raises Errno::ACCES when passed a directory" do lambda { exec File.dirname(@script) }.should raise_error(Errno::EACCES) end end describe "Kernel.exec" do it "needs to be reviewed for spec completeness" end Change spec so that Kernel.exec runs in 1.9.3 as well require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../fixtures/classes', __FILE__) describe "Kernel#exec" do it "is a private method" do Kernel.should have_private_instance_method(:exec) end it "raises a SystemCallError if cmd cannot execute" do lambda { exec "" }.should raise_error(SystemCallError) end it "raises a SystemCallError if cmd cannot execute and contains '-'" do lambda { exec 'cmd-plugin' }.should raise_error(SystemCallError) end it "raises an ArgumentError if the cmd includes a null byte" do lambda { exec "\000" }.should raise_error(ArgumentError) end it "raises Errno::ENOENT if the script does not exist" do lambda { exec "bogus-noent-script.sh" }.should raise_error(Errno::ENOENT) end it "runs the specified command, replacing current process" do result = `#{RUBY_EXE} -e 'exec "echo hello"; puts "fail"'` result.should == "hello\n" end ruby_version_is "1.9.2" .. "1.9.3" do it "passes environment vars to the child environment" do result = `#{RUBY_EXE} -e 'exec({"FOO" => "BAR"}, "echo $FOO"); puts "fail"'` result.should == "BAR\n" end end end describe "Kernel#exec" do before :each do @script = tmp("tmp.sh") touch @script end after :each do rm_r @script end it "raises Errno::EACCES when the file does not have execute permissions" do lambda { exec @script }.should raise_error(Errno::EACCES) end it "raises Errno::ACCES when passed a directory" do lambda { exec File.dirname(@script) }.should raise_error(Errno::EACCES) end end describe "Kernel.exec" do it "needs to be reviewed for spec completeness" end
require 'spec_helper' describe 'Standalone migrations' do def write(file, content) raise "cannot write nil" unless file file = tmp_file(file) folder = File.dirname(file) `mkdir -p #{folder}` unless File.exist?(folder) File.open(file, 'w') { |f| f.write content } end def read(file) File.read(tmp_file(file)) end def migration(name) m = `cd spec/tmp/db/migrate && ls`.split("\n").detect { |m| m =~ /#{name}/ } m ? "db/migrate/#{m}" : m end def tmp_file(file) "spec/tmp/#{file}" end def schema ENV['SCHEMA'] end def run(cmd) result = `cd spec/tmp && #{cmd} 2>&1` raise result unless $?.success? result end def make_migration(name, options={}) task_name = options[:task_name] || 'db:new_migration' migration = run("rake #{task_name} name=#{name}").match(%r{db/migrate/\d+.*.rb})[0] content = read(migration) content.sub!(/def down.*?\send/m, "def down;puts 'DOWN-#{name}';end") content.sub!(/def up.*?\send/m, "def up;puts 'UP-#{name}';end") write(migration, content) migration.match(/\d{14}/)[0] end def write_rakefile(config=nil) write 'Rakefile', <<-TXT $LOAD_PATH.unshift '#{File.expand_path('lib')}' begin require "standalone_migrations" StandaloneMigrations::Tasks.load_tasks rescue LoadError => e puts "gem install standalone_migrations to get db:migrate:* tasks! (Error: \#{e})" end TXT end def write_multiple_migrations migration_superclass = if Rails::VERSION::MAJOR >= 5 "ActiveRecord::Migration[#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}]" else "ActiveRecord::Migration" end write_rakefile %{t.migrations = "db/migrations", "db/migrations2"} write "db/migrate/20100509095815_create_tests.rb", <<-TXT class CreateTests < #{migration_superclass} def up puts "UP-CreateTests" end def down puts "DOWN-CreateTests" end end TXT write "db/migrate/20100509095816_create_tests2.rb", <<-TXT class CreateTests2 < #{migration_superclass} def up puts "UP-CreateTests2" end def down puts "DOWN-CreateTests2" end end TXT end before do `rm -rf spec/tmp` if File.exist?('spec/tmp') `mkdir spec/tmp` write_rakefile write(schema, '') write 'db/config.yml', <<-TXT development: adapter: sqlite3 database: db/development.sql test: adapter: sqlite3 database: db/test.sql TXT end after(:all) do `rm -rf spec/tmp` if File.exist?('spec/tmp') end it "warns of deprecated folder structure" do warning = /DEPRECATED.* db\/migrate/ expect(run("rake db:create")).not_to match(warning) write('db/migrations/fooo.rb', 'xxx') expect(run("rake db:create --trace")).to match(warning) end describe 'db:create and drop' do it "should create the database and drop the database that was created" do run "rake db:create" run "rake db:drop" end end describe 'callbacks' do it 'runs the callbacks' do expect(StandaloneMigrations::Tasks).to receive(:configure) connection_established = false expect(ActiveRecord::Base).to receive(:establish_connection) do connection_established = true end expect(StandaloneMigrations).to receive(:run_on_load_callbacks) do expect(connection_established).to be true end Dir.chdir(File.join(File.dirname(__FILE__), "tmp")) do load "Rakefile" Rake::Task['standalone:connection'].invoke end end end describe 'db:new_migration' do it "fails if i do not add a name" do expect(lambda{ run("rake db:new_migration") }).to raise_error(/name=/) end it "generates a new migration with this name from ENV and timestamp" do expect(run("rake db:new_migration name=test_abc_env")).to match(%r{create(.*)db/migrate/\d+_test_abc_env\.rb}) expect(run("ls db/migrate")).to match(/^\d+_test_abc_env.rb$/) end it "generates a new migration with this name from args and timestamp" do expect(run("rake db:new_migration[test_abc_args]")).to match(%r{create(.*)db/migrate/\d+_test_abc_args\.rb}) expect(run("ls db/migrate")).to match(/^\d+_test_abc_args.rb$/) end it "generates a new migration with the name converted to the Rails migration format" do expect(run("rake db:new_migration name=MyNiceModel")).to match(%r{create(.*)db/migrate/\d+_my_nice_model\.rb}) expect(read(migration('my_nice_model'))).to match(/class MyNiceModel/) expect(run("ls db/migrate")).to match(/^\d+_my_nice_model.rb$/) end it "generates a new migration with name and options from ENV" do run("rake db:new_migration name=add_name_and_email_to_users options='name:string email:string'") expect(read(migration('add_name_and_email_to_users'))).to match(/add_column :users, :name, :string\n\s*add_column :users, :email, :string/) end it "generates a new migration with name and options from args" do run("rake db:new_migration[add_website_and_username_to_users,website:string/username:string]") expect(read(migration('add_website_and_username_to_users'))).to match(/add_column :users, :website, :string\n\s*add_column :users, :username, :string/) end end describe 'db:version' do it "should start with a new database version" do expect(run("rake db:version")).to match(/Current version: 0/) end it "should display the current version" do run("rake db:new_migration name=test_abc") run("rake --trace db:migrate") expect(run("rake db:version")).to match(/Current version: #{Time.now.year}/) end end describe 'db:migrate' do it "does nothing when no migrations are present" do expect(run("rake db:migrate")).not_to match(/Migrating/) end it "migrates if i add a migration" do run("rake db:new_migration name=xxx") expect(run("rake db:migrate")).to match(/Xxx: Migrating/i) end end describe 'db:migrate:down' do it "migrates down" do make_migration('xxx') sleep 1 version = make_migration('yyy') run 'rake db:migrate' result = run("rake db:migrate:down VERSION=#{version}") expect(result).not_to match(/Xxx: reverting/) expect(result).to match(/Yyy: reverting/) end it "fails without version" do make_migration('yyy') # Rails has a bug where it's sending a bad failure exception # https://github.com/rails/rails/issues/28905 expect(lambda{ run("rake db:migrate:down") }).to raise_error(/VERSION|version/) end end describe 'db:migrate:up' do it "migrates up" do make_migration('xxx') run 'rake db:migrate' sleep 1 version = make_migration('yyy') result = run("rake db:migrate:up VERSION=#{version}") expect(result).not_to match(/Xxx: migrating/) expect(result).to match(/Yyy: migrating/) end it "fails without version" do make_migration('yyy') # Rails has a bug where it's sending a bad failure exception # https://github.com/rails/rails/issues/28905 expect(lambda{ run("rake db:migrate:up") }).to raise_error(/VERSION|version/) end end describe 'db:rollback' do it "does nothing when no migrations have been run" do expect(run("rake db:version")).to match(/version: 0/) expect(run("rake db:rollback")).to eq('') expect(run("rake db:version")).to match(/version: 0/) end it "rolls back the last migration if one has been applied" do write_multiple_migrations run("rake db:migrate") expect(run("rake db:version")).to match(/version: 20100509095816/) expect(run("rake db:rollback")).to match(/revert/) expect(run("rake db:version")).to match(/version: 20100509095815/) end it "rolls back multiple migrations if the STEP argument is given" do write_multiple_migrations run("rake db:migrate") expect(run("rake db:version")).to match(/version: 20100509095816/) run("rake db:rollback STEP=2") =~ /revert/ expect(run("rake db:version")).to match(/version: 0/) end end describe 'schema:dump' do it "dumps the schema" do write(schema, '') run('rake db:schema:dump') expect(read(schema)).to match(/ActiveRecord/) end end describe 'db:schema:load' do it "loads the schema" do run('rake db:schema:dump') write(schema, read(schema)+"\nputs 'LOADEDDD'") result = run('rake db:schema:load') expect(result).to match(/LOADEDDD/) end it "loads all migrations" do make_migration('yyy') run "rake db:migrate" run "rake db:drop" run "rake db:create" run "rake db:schema:load" expect(run( "rake db:migrate").strip).to eq('') end end describe 'db:abort_if_pending_migrations' do it "passes when no migrations are pending" do expect(run("rake db:abort_if_pending_migrations").strip).to eq('') end it "fails when migrations are pending" do make_migration('yyy') expect(lambda{ run("rake db:abort_if_pending_migrations") }).to raise_error(/1 pending migration/) end end describe 'db:test:load' do it 'loads' do write(schema, "puts 'LOADEDDD'") expect(run("rake db:test:load")).to match(/LOADEDDD/) end it "fails without schema" do schema_path = "spec/tmp/#{schema}" `rm -rf #{schema_path}` if File.exist?(schema_path) expect(lambda{ run("rake db:test:load") }).to raise_error(/try again/) end end describe 'db:test:purge' do it "runs" do run('rake db:test:purge') end end describe "db:seed" do it "loads" do write("db/seeds.rb", "puts 'LOADEDDD'") expect(run("rake db:seed")).to match(/LOADEDDD/) end describe 'with non-default seed file' do let(:yaml_hash) do { "db" => { "seeds" => "db/seeds2.rb", } } end before do write(".standalone_migrations", yaml_hash.to_yaml) end it "loads" do write("db/seeds2.rb", "puts 'LOADEDDD'") expect(run("rake db:seed")).to match(/LOADEDDD/) end end it "does nothing without seeds" do expect(run("rake db:seed").length).to eq(0) end end describe "db:reset" do it "should not error when a seeds file does not exist" do make_migration('yyy') run('rake db:migrate DB=test') expect(lambda{ run("rake db:reset") }).not_to raise_error end end describe 'db:migrate when environment is specified' do it "runs when using the DB environment variable", :travis_error => true do make_migration('yyy') run('rake db:migrate RAILS_ENV=test') expect(run('rake db:version RAILS_ENV=test')).not_to match(/version: 0/) expect(run('rake db:version')).to match(/version: 0/) end it "should error on an invalid database", :travis_error => true do expect(lambda{ run("rake db:create RAILS_ENV=nonexistent")}).to raise_error(/rake aborted/) end end end Unset class level config var in specs and allow configure to rerun to pick up production config block require 'spec_helper' describe 'Standalone migrations' do def write(file, content) raise "cannot write nil" unless file file = tmp_file(file) folder = File.dirname(file) `mkdir -p #{folder}` unless File.exist?(folder) File.open(file, 'w') { |f| f.write content } end def read(file) File.read(tmp_file(file)) end def migration(name) m = `cd spec/tmp/db/migrate && ls`.split("\n").detect { |m| m =~ /#{name}/ } m ? "db/migrate/#{m}" : m end def tmp_file(file) "spec/tmp/#{file}" end def schema ENV['SCHEMA'] end def run(cmd) result = `cd spec/tmp && #{cmd} 2>&1` raise result unless $?.success? result end def make_migration(name, options={}) task_name = options[:task_name] || 'db:new_migration' migration = run("rake #{task_name} name=#{name}").match(%r{db/migrate/\d+.*.rb})[0] content = read(migration) content.sub!(/def down.*?\send/m, "def down;puts 'DOWN-#{name}';end") content.sub!(/def up.*?\send/m, "def up;puts 'UP-#{name}';end") write(migration, content) migration.match(/\d{14}/)[0] end def write_rakefile(config=nil) write 'Rakefile', <<-TXT $LOAD_PATH.unshift '#{File.expand_path('lib')}' begin require "standalone_migrations" StandaloneMigrations::Tasks.load_tasks rescue LoadError => e puts "gem install standalone_migrations to get db:migrate:* tasks! (Error: \#{e})" end TXT end def write_multiple_migrations migration_superclass = if Rails::VERSION::MAJOR >= 5 "ActiveRecord::Migration[#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}]" else "ActiveRecord::Migration" end write_rakefile %{t.migrations = "db/migrations", "db/migrations2"} write "db/migrate/20100509095815_create_tests.rb", <<-TXT class CreateTests < #{migration_superclass} def up puts "UP-CreateTests" end def down puts "DOWN-CreateTests" end end TXT write "db/migrate/20100509095816_create_tests2.rb", <<-TXT class CreateTests2 < #{migration_superclass} def up puts "UP-CreateTests2" end def down puts "DOWN-CreateTests2" end end TXT end before do StandaloneMigrations::Configurator.instance_variable_set(:@env_config, nil) `rm -rf spec/tmp` if File.exist?('spec/tmp') `mkdir spec/tmp` write_rakefile write(schema, '') write 'db/config.yml', <<-TXT development: adapter: sqlite3 database: db/development.sql test: adapter: sqlite3 database: db/test.sql production: adapter: sqlite3 database: db/production.sql TXT end after(:all) do `rm -rf spec/tmp` if File.exist?('spec/tmp') end it "warns of deprecated folder structure" do warning = /DEPRECATED.* db\/migrate/ expect(run("rake db:create")).not_to match(warning) write('db/migrations/fooo.rb', 'xxx') expect(run("rake db:create --trace")).to match(warning) end describe 'db:create and drop' do it "should create the database and drop the database that was created" do run "rake db:create" run "rake db:drop" end end describe 'callbacks' do it 'runs the callbacks' do expect(StandaloneMigrations::Tasks).to receive(:configure).and_call_original connection_established = false expect(ActiveRecord::Base).to receive(:establish_connection) do connection_established = true end expect(StandaloneMigrations).to receive(:run_on_load_callbacks) do expect(connection_established).to be true end Dir.chdir(File.join(File.dirname(__FILE__), "tmp")) do load "Rakefile" Rake::Task['standalone:connection'].invoke end end end describe 'db:new_migration' do it "fails if i do not add a name" do expect(lambda{ run("rake db:new_migration") }).to raise_error(/name=/) end it "generates a new migration with this name from ENV and timestamp" do expect(run("rake db:new_migration name=test_abc_env")).to match(%r{create(.*)db/migrate/\d+_test_abc_env\.rb}) expect(run("ls db/migrate")).to match(/^\d+_test_abc_env.rb$/) end it "generates a new migration with this name from args and timestamp" do expect(run("rake db:new_migration[test_abc_args]")).to match(%r{create(.*)db/migrate/\d+_test_abc_args\.rb}) expect(run("ls db/migrate")).to match(/^\d+_test_abc_args.rb$/) end it "generates a new migration with the name converted to the Rails migration format" do expect(run("rake db:new_migration name=MyNiceModel")).to match(%r{create(.*)db/migrate/\d+_my_nice_model\.rb}) expect(read(migration('my_nice_model'))).to match(/class MyNiceModel/) expect(run("ls db/migrate")).to match(/^\d+_my_nice_model.rb$/) end it "generates a new migration with name and options from ENV" do run("rake db:new_migration name=add_name_and_email_to_users options='name:string email:string'") expect(read(migration('add_name_and_email_to_users'))).to match(/add_column :users, :name, :string\n\s*add_column :users, :email, :string/) end it "generates a new migration with name and options from args" do run("rake db:new_migration[add_website_and_username_to_users,website:string/username:string]") expect(read(migration('add_website_and_username_to_users'))).to match(/add_column :users, :website, :string\n\s*add_column :users, :username, :string/) end end describe 'db:version' do it "should start with a new database version" do expect(run("rake db:version")).to match(/Current version: 0/) end it "should display the current version" do run("rake db:new_migration name=test_abc") run("rake --trace db:migrate") expect(run("rake db:version")).to match(/Current version: #{Time.now.year}/) end end describe 'db:migrate' do it "does nothing when no migrations are present" do expect(run("rake db:migrate")).not_to match(/Migrating/) end it "migrates if i add a migration" do run("rake db:new_migration name=xxx") expect(run("rake db:migrate")).to match(/Xxx: Migrating/i) end end describe 'db:migrate:down' do it "migrates down" do make_migration('xxx') sleep 1 version = make_migration('yyy') run 'rake db:migrate' result = run("rake db:migrate:down VERSION=#{version}") expect(result).not_to match(/Xxx: reverting/) expect(result).to match(/Yyy: reverting/) end it "fails without version" do make_migration('yyy') # Rails has a bug where it's sending a bad failure exception # https://github.com/rails/rails/issues/28905 expect(lambda{ run("rake db:migrate:down") }).to raise_error(/VERSION|version/) end end describe 'db:migrate:up' do it "migrates up" do make_migration('xxx') run 'rake db:migrate' sleep 1 version = make_migration('yyy') result = run("rake db:migrate:up VERSION=#{version}") expect(result).not_to match(/Xxx: migrating/) expect(result).to match(/Yyy: migrating/) end it "fails without version" do make_migration('yyy') # Rails has a bug where it's sending a bad failure exception # https://github.com/rails/rails/issues/28905 expect(lambda{ run("rake db:migrate:up") }).to raise_error(/VERSION|version/) end end describe 'db:rollback' do it "does nothing when no migrations have been run" do expect(run("rake db:version")).to match(/version: 0/) expect(run("rake db:rollback")).to eq('') expect(run("rake db:version")).to match(/version: 0/) end it "rolls back the last migration if one has been applied" do write_multiple_migrations run("rake db:migrate") expect(run("rake db:version")).to match(/version: 20100509095816/) expect(run("rake db:rollback")).to match(/revert/) expect(run("rake db:version")).to match(/version: 20100509095815/) end it "rolls back multiple migrations if the STEP argument is given" do write_multiple_migrations run("rake db:migrate") expect(run("rake db:version")).to match(/version: 20100509095816/) run("rake db:rollback STEP=2") =~ /revert/ expect(run("rake db:version")).to match(/version: 0/) end end describe 'schema:dump' do it "dumps the schema" do write(schema, '') run('rake db:schema:dump') expect(read(schema)).to match(/ActiveRecord/) end end describe 'db:schema:load' do it "loads the schema" do run('rake db:schema:dump') write(schema, read(schema)+"\nputs 'LOADEDDD'") result = run('rake db:schema:load') expect(result).to match(/LOADEDDD/) end it "loads all migrations" do make_migration('yyy') run "rake db:migrate" run "rake db:drop" run "rake db:create" run "rake db:schema:load" expect(run( "rake db:migrate").strip).to eq('') end end describe 'db:abort_if_pending_migrations' do it "passes when no migrations are pending" do expect(run("rake db:abort_if_pending_migrations").strip).to eq('') end it "fails when migrations are pending" do make_migration('yyy') expect(lambda{ run("rake db:abort_if_pending_migrations") }).to raise_error(/1 pending migration/) end end describe 'db:test:load' do it 'loads' do write(schema, "puts 'LOADEDDD'") expect(run("rake db:test:load")).to match(/LOADEDDD/) end it "fails without schema" do schema_path = "spec/tmp/#{schema}" `rm -rf #{schema_path}` if File.exist?(schema_path) expect(lambda{ run("rake db:test:load") }).to raise_error(/try again/) end end describe 'db:test:purge' do it "runs" do run('rake db:test:purge') end end describe "db:seed" do it "loads" do write("db/seeds.rb", "puts 'LOADEDDD'") expect(run("rake db:seed")).to match(/LOADEDDD/) end describe 'with non-default seed file' do let(:yaml_hash) do { "db" => { "seeds" => "db/seeds2.rb", } } end before do write(".standalone_migrations", yaml_hash.to_yaml) end it "loads" do write("db/seeds2.rb", "puts 'LOADEDDD'") expect(run("rake db:seed")).to match(/LOADEDDD/) end end it "does nothing without seeds" do expect(run("rake db:seed").length).to eq(0) end end describe "db:reset" do it "should not error when a seeds file does not exist" do make_migration('yyy') run('rake db:migrate DB=test') expect(lambda{ run("rake db:reset") }).not_to raise_error end end describe 'db:migrate when environment is specified' do it "runs when using the DB environment variable", :travis_error => true do make_migration('yyy') run('rake db:migrate RAILS_ENV=test') expect(run('rake db:version RAILS_ENV=test')).not_to match(/version: 0/) expect(run('rake db:version')).to match(/version: 0/) end it "should error on an invalid database", :travis_error => true do expect(lambda{ run("rake db:create RAILS_ENV=nonexistent")}).to raise_error(/rake aborted/) end end end
# # Be sure to run `pod lib lint AssetsPickerViewController.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'AssetsPickerViewController' s.version = '0.8.3' s.summary = 'Picker controller that supports multiple photos and videos written in Swift.' # This description is used to generate tags and improve search results. # * Think: What does it do? Why did you write it? What is the focus? # * Try to keep it short, snappy and to the point. # * Write the description between the DESC delimiters below. # * Finally, don't worry about the indent, CocoaPods strips it! s.description = <<-DESC Select multiple photos and videos. Can take photo or video during selection. Fully customizable UI. DESC s.homepage = 'https://github.com/DragonCherry/AssetsPickerViewController' # s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'DragonCherry' => 'dragoncherry@naver.com' } s.source = { :git => 'https://github.com/DragonCherry/AssetsPickerViewController.git', :tag => s.version.to_s } # s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>' s.ios.deployment_target = '9.0' s.source_files = 'AssetsPickerViewController/Classes/**/*' s.resource_bundles = { 'AssetsPickerViewController' => ['AssetsPickerViewController/Assets/*.*'] } # s.public_header_files = 'Pod/Classes/**/*.h' # s.frameworks = 'UIKit', 'MapKit' s.dependency 'PureLayout' s.dependency 'Dimmer' s.dependency 'FadeView' s.dependency 'AlamofireImage' s.dependency 'TinyLog' s.dependency 'OptionalTypes' s.dependency 'SwiftARGB' end updated podspec # # Be sure to run `pod lib lint AssetsPickerViewController.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'AssetsPickerViewController' s.version = '0.8.3' s.summary = 'Picker controller that supports multiple photos and videos written in Swift.' # This description is used to generate tags and improve search results. # * Think: What does it do? Why did you write it? What is the focus? # * Try to keep it short, snappy and to the point. # * Write the description between the DESC delimiters below. # * Finally, don't worry about the indent, CocoaPods strips it! s.description = <<-DESC Select multiple photos and videos. Can take photo or video during selection. Fully customizable UI. DESC s.homepage = 'https://github.com/DragonCherry/AssetsPickerViewController' s.screenshots = 'https://cloud.githubusercontent.com/assets/20486591/26525538/42b1d6dc-4395-11e7-9c16-b9abdb2e9247.PNG', 'https://cloud.githubusercontent.com/assets/20486591/26616648/1d385746-460b-11e7-9324-62ea634e2fcb.png' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'DragonCherry' => 'dragoncherry@naver.com' } s.source = { :git => 'https://github.com/DragonCherry/AssetsPickerViewController.git', :tag => s.version.to_s } s.social_media_url = 'https://www.linkedin.com/in/jeongyong/' s.ios.deployment_target = '9.0' s.source_files = 'AssetsPickerViewController/Classes/**/*' s.resource_bundles = { 'AssetsPickerViewController' => ['AssetsPickerViewController/Assets/*.*'] } # s.public_header_files = 'Pod/Classes/**/*.h' # s.frameworks = 'UIKit', 'MapKit' s.dependency 'PureLayout' s.dependency 'Dimmer' s.dependency 'FadeView' s.dependency 'AlamofireImage' s.dependency 'TinyLog' s.dependency 'OptionalTypes' s.dependency 'SwiftARGB' end
require File.expand_path("../../spec_helper.rb", __FILE__) describe UUIDTools::UUID, "when obtaining a MAC address" do before do @mac_address = UUIDTools::UUID.mac_address end it "should obtain a MAC address" do @mac_address.should_not be_nil end it "should cache the MAC address" do @mac_address.object_id.should == UUIDTools::UUID.mac_address.object_id end end Possible fix for #12. require File.expand_path("../../spec_helper.rb", __FILE__) def pending_if_root_required if @mac_address == nil output = `ifconfig -a 2>&1` if output =~ /inet/ && output =~ /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/ && output =~ /Warning: cannot open/ pending("Cannot get MAC address without root?") end end end describe UUIDTools::UUID, "when obtaining a MAC address" do before do @mac_address = UUIDTools::UUID.mac_address end it "should obtain a MAC address" do pending_if_root_required() @mac_address.should_not be_nil end it "should cache the MAC address" do pending_if_root_required() @mac_address.object_id.should == UUIDTools::UUID.mac_address.object_id end end
# variable_derefencer_spec.rb - specs for variable_derefencer require_relative 'spec_helper' describe VariableDerefencer do describe 'when empty stack frame' do let(:frames) { [{}] } let(:vref) { VariableDerefencer.new frames } subject { vref[:id] } it 'should be empty string' do subject.must_equal '' end end describe 'when given a single frame and matching symbol' do let(:frames) { [{devil: 'details'}] } let(:vref) { VariableDerefencer.new frames } subject { vref[:devil] } it 'should be details' do subject.must_equal 'details' end end describe 'when shadowing earlier variable' do let(:frames) { [{cat: 'pet'}, {}, {cat: 'evil'}] } let(:vref) { VariableDerefencer.new frames } subject { vref[:cat] } it 'should be evil' do subject.must_equal 'evil' end end describe 'decurlify :{var}' do let(:frames) { [{var: 'hello'}] } let(:vref) { VariableDerefencer.new frames } subject {vref.decurlify ":{var}" } it 'should be "var"' do subject.must_equal "var" end end describe 'decurlify unknown match or empty' do let(:frames) { [{var: 'hello'}] } let(:vref) { VariableDerefencer.new frames } subject {vref.decurlify "" } it 'should be ""' do subject.must_equal "" end end end \'added specs for interpolate_str for various types\' # variable_derefencer_spec.rb - specs for variable_derefencer require_relative 'spec_helper' describe VariableDerefencer do describe 'when empty stack frame' do let(:frames) { [{}] } let(:vref) { VariableDerefencer.new frames } subject { vref[:id] } it 'should be empty string' do subject.must_equal '' end end describe 'when given a single frame and matching symbol' do let(:frames) { [{devil: 'details'}] } let(:vref) { VariableDerefencer.new frames } subject { vref[:devil] } it 'should be details' do subject.must_equal 'details' end end describe 'when shadowing earlier variable' do let(:frames) { [{cat: 'pet'}, {}, {cat: 'evil'}] } let(:vref) { VariableDerefencer.new frames } subject { vref[:cat] } it 'should be evil' do subject.must_equal 'evil' end end describe 'decurlify :{var}' do let(:frames) { [{var: 'hello'}] } let(:vref) { VariableDerefencer.new frames } subject {vref.decurlify ":{var}" } it 'should be "var"' do subject.must_equal "var" end end describe 'decurlify unknown match or empty' do let(:frames) { [{var: 'hello'}] } let(:vref) { VariableDerefencer.new frames } subject {vref.decurlify "" } it 'should be ""' do subject.must_equal "" end end describe 'interpolate_str empty string' do let(:frames) { [{var: 'hello'}] } let(:vref) { VariableDerefencer.new frames } let(:str) { "" } subject { vref.interpolate_str str } it 'should be empty string' do subject.must_equal '' end end describe 'interpolate_str with noembedded vars' do let(:frames) { [{var: 'hello'}] } let(:vref) { VariableDerefencer.new frames } let(:str) { "var nice" } subject { vref.interpolate_str str } it 'should be equal original str' do subject.must_equal str end end describe 'interpolate_str "xxx:{var}yyy"' do let(:frames) { [{var: 'hello'}] } let(:vref) { VariableDerefencer.new frames } let(:str) { "xxx:{var}yyy" } subject { vref.interpolate_str str } it 'should be xxxhelloyyy' do subject.must_equal 'xxxhelloyyy' end end describe 'interpolate_str 2 variables' do let(:frames) { [{var: 'hello', name: 'Edward'}] } let(:vref) { VariableDerefencer.new frames } let(:str) { ":{var} there, :{name}" } subject { vref.interpolate_str str } it 'should be hello there, Edward' do subject.must_equal 'hello there, Edward' end end end
require 'rake/clean' PACKAGEDIR = "packages/" + PACKAGE.gsub("::", "/") TARGETPATH = PACKAGEDIR TARGET = PACKAGE.split("::").last GENERATED_SOURCES ||= [] GENERATED_SOURCES << ".corto/#{TARGET}__api.c" << ".corto/#{TARGET}__wrapper.c" << ".corto/#{TARGET}__meta.c" << ".corto/#{TARGET}__load.c" GENERATED_HEADERS ||=[] << "include/#{TARGET}__api.h" << "include/#{TARGET}__meta.h" << "include/#{TARGET}__type.h" PREFIX ||= TARGET CHDIR_SET = true Dir.chdir(File.dirname(Rake.application.rakefile)) GENFILE = Rake::FileList["#{TARGET}.*"][0] file ".corto/packages.txt" do verbose(false) sh "mkdir -p .corto" sh "touch .corto/packages.txt" end file "include/#{TARGET}__type.h" => [GENFILE, ".corto/packages.txt"] do verbose(false) sh "mkdir -p .corto" sh "touch .corto/#{TARGET}__wrapper.c" ret = system "corto pp #{GENFILE} --scope #{PACKAGE} --prefix #{PREFIX} --lang c" if !ret then sh "rm include/#{TARGET}__type.h" abort "\033[1;31m[ build failed ]\033[0;49m" end end task :default => "include/#{TARGET}__type.h" do require "./.corto/dep.rb" # Delay running inherited tasks - we first need to run # code generation for us to know which source files # have to be compiled. require "#{ENV['CORTO_BUILD']}/component" Rake::Task["prebuild"].invoke Rake::Task["binary"].invoke Rake::Task["postbuild"].invoke end clobber_count = 1 task :clobber do # Recursively call clobber, prevent infinite recursion if clobber_count == 1 then clobber_count += 1 require "#{ENV['CORTO_BUILD']}/component" Rake::Task["clobber"].reenable Rake::Task["clobber"].execute if File.exists?(".corto/dep.rb") sh "rake clobber -f .corto/dep.rb" end end end require "#{ENV['CORTO_BUILD']}/subrake" #324 Fix build require 'rake/clean' PACKAGEDIR = "packages/" + PACKAGE.gsub("::", "/") TARGETPATH = PACKAGEDIR TARGET = PACKAGE.split("::").last GENERATED_SOURCES ||= [] GENERATED_SOURCES << ".corto/#{TARGET}__api.c" << ".corto/#{TARGET}__wrapper.c" << ".corto/#{TARGET}__meta.c" << ".corto/#{TARGET}__load.c" GENERATED_HEADERS ||=[] << "include/#{TARGET}__api.h" << "include/#{TARGET}__meta.h" << "include/#{TARGET}__type.h" PREFIX ||= TARGET CHDIR_SET = true Dir.chdir(File.dirname(Rake.application.rakefile)) GENFILE = Rake::FileList["#{TARGET}.*"][0] file ".corto/packages.txt" do verbose(false) sh "mkdir -p .corto" sh "touch .corto/packages.txt" end file ".corto/components.txt" do verbose(false) sh "mkdir -p .corto" sh "touch .corto/components.txt" end file "include/#{TARGET}__type.h" => [GENFILE, ".corto/packages.txt", ".corto/components.txt"] do verbose(false) sh "mkdir -p .corto" sh "touch .corto/#{TARGET}__wrapper.c" ret = system "corto pp #{GENFILE} --scope #{PACKAGE} --prefix #{PREFIX} --lang c" if !ret then sh "rm include/#{TARGET}__type.h" abort "\033[1;31m[ build failed ]\033[0;49m" end end task :default => "include/#{TARGET}__type.h" do require "./.corto/dep.rb" # Delay running inherited tasks - we first need to run # code generation for us to know which source files # have to be compiled. require "#{ENV['CORTO_BUILD']}/component" Rake::Task["prebuild"].invoke Rake::Task["binary"].invoke Rake::Task["postbuild"].invoke end clobber_count = 1 task :clobber do # Recursively call clobber, prevent infinite recursion if clobber_count == 1 then clobber_count += 1 require "#{ENV['CORTO_BUILD']}/component" Rake::Task["clobber"].reenable Rake::Task["clobber"].execute if File.exists?(".corto/dep.rb") sh "rake clobber -f .corto/dep.rb" end end end require "#{ENV['CORTO_BUILD']}/subrake"
require 'nokogiri' require 'time' class Game include DataMapper::Resource property :id, Serial property :home_team, String property :away_team, String property :bbref_key, String #Β not necessarily bbref any more property :slug, String property :date, DateTime property :quality, Integer property :provider, String has n, :events attr_reader :players, :score def players=(players) @players = players end def events=(events) @events = events end def insert_into_db slug = "#{@date.month}#{@date.day}-#{@away_team}-#{@home_team}".downcase.gsub(" ", "-") game = self.class.create(:home_team => @home_team, :away_team => @away_team, :date => @date, :bbref_key => @bbref_key, :slug => slug, :provider => @provider) @events.each do |event| Event.create(:game_id => game.id, :player => event.player.id, :type => event.type, :time => event.time, :name => event.player.name, :team => event.player.team) end end def assess! @score = 0 fetch_events @score += 50 if overtime? @score += 20 if close_game? @score += 5 if high_shooting_pct? @score += 15 if very_high_scorer? high_scorers_bonus = (high_scorers * 5) high_scorers_bonus = 10 if high_scorers_bonus > 10 @score += high_scorers_bonus self.quality = @score self.save end def to_json fetch_events team_strings = [] players = [@team0_events.map { |p| Player.new(p.name, p.player, 0) }, @team1_events.map { |p| Player.new(p.name, p.player, 1) }] players.each do |team| str = team.map { |player| "\"#{player.id}\" : { \"name\" : \"#{player.name}\", \"team\" : #{player.team} }" }.join(",") team_strings << "{ #{str} }" end events_string = events.all.map { |event| "{ \"player\" : \"#{event.player}\", \"type\" : \"#{event.type}\", \"time\" : #{event.time}, \"team\" : #{event.team} }" } "{ \"teams\" : [\"#{away_team}\", \"#{home_team}\"], \"players\" : [#{team_strings.join(',')}], \"events\" : [#{events_string.join(',')}] }" end def day Time.new(date.year, date.month, date.day) end def fetch_events unless @team0_events && @team1_events @team0_events = self.events.all(:team => 0, :unique => true) @team1_events = self.events.all(:team => 1, :unique => true) end end def close_game? team0_score = @team0_events.reduce(0) do |score, event| score + value = case event.type.to_sym when :ftm then 1 when :fgm then 2 when :fgm3 then 3 else 0 end end team1_score = @team1_events.reduce(0) do |score, event| score + value = case event.type.to_sym when :ftm then 1 when :fgm then 2 when :fgm3 then 3 else 0 end end (team0_score - team1_score).abs <= 5 end def overtime? @team0_events.any? { |e| e.time > 2880 } end def players_with_points return @players_with_points if @players_with_points values = {} (@team0_events + @team1_events).each do |event| value = case event.type.to_sym when :ftm then 1 when :fgm2 then 2 when :fgm3 then 3 end values[event.player] ||= 0 values[event.player] += value if value end @players_with_points = values end def most_points players_with_points.values.max end def high_scorer? most_points >= 30 end def very_high_scorer? most_points >= 40 end def high_scorers players_with_points.values.select { |pts| pts >= 30 }.size end def high_shooting_pct? players_with_shooting_pct = {} (@team0_events + @team1_events).each do |event| type = event.type.to_sym players_with_shooting_pct[event.player] ||= { :fga => 0, :fgm => 0, :pct => 0 } players_with_shooting_pct[event.player][:fga] += 1 if type == :fga2 || type == :fga3 if type == :fgm2 || type == :fgm3 players_with_shooting_pct[event.player][:fgm] += 1 players_with_shooting_pct[event.player][:fga] += 1 end if players_with_shooting_pct[event.player][:fgm] > 0 && players_with_shooting_pct[event.player][:fga] > 0 players_with_shooting_pct[event.player][:pct] = (players_with_shooting_pct[event.player][:fgm] / players_with_shooting_pct[event.player][:fga].to_f) end end players_with_shooting_pct.values.any? { |v| v[:pct] >= 0.825 && v[:fga] >= 12 } end end Small tweak to game quality calculation require 'nokogiri' require 'time' class Game include DataMapper::Resource property :id, Serial property :home_team, String property :away_team, String property :bbref_key, String #Β not necessarily bbref any more property :slug, String property :date, DateTime property :quality, Integer property :provider, String has n, :events attr_reader :players, :score def players=(players) @players = players end def events=(events) @events = events end def insert_into_db slug = "#{@date.month}#{@date.day}-#{@away_team}-#{@home_team}".downcase.gsub(" ", "-") game = self.class.create(:home_team => @home_team, :away_team => @away_team, :date => @date, :bbref_key => @bbref_key, :slug => slug, :provider => @provider) @events.each do |event| Event.create(:game_id => game.id, :player => event.player.id, :type => event.type, :time => event.time, :name => event.player.name, :team => event.player.team) end end def assess! @score = 0 fetch_events @score += 50 if overtime? @score += 25 if close_game? @score += 5 if high_shooting_pct? @score += 10 if very_high_scorer? high_scorers_bonus = (high_scorers * 5) high_scorers_bonus = 10 if high_scorers_bonus > 10 @score += high_scorers_bonus self.quality = @score self.save end def to_json fetch_events team_strings = [] players = [@team0_events.map { |p| Player.new(p.name, p.player, 0) }, @team1_events.map { |p| Player.new(p.name, p.player, 1) }] players.each do |team| str = team.map { |player| "\"#{player.id}\" : { \"name\" : \"#{player.name}\", \"team\" : #{player.team} }" }.join(",") team_strings << "{ #{str} }" end events_string = events.all.map { |event| "{ \"player\" : \"#{event.player}\", \"type\" : \"#{event.type}\", \"time\" : #{event.time}, \"team\" : #{event.team} }" } "{ \"teams\" : [\"#{away_team}\", \"#{home_team}\"], \"players\" : [#{team_strings.join(',')}], \"events\" : [#{events_string.join(',')}] }" end def day Time.new(date.year, date.month, date.day) end def fetch_events unless @team0_events && @team1_events @team0_events = self.events.all(:team => 0, :unique => true) @team1_events = self.events.all(:team => 1, :unique => true) end end def close_game? team0_score = @team0_events.reduce(0) do |score, event| score + value = case event.type.to_sym when :ftm then 1 when :fgm then 2 when :fgm3 then 3 else 0 end end team1_score = @team1_events.reduce(0) do |score, event| score + value = case event.type.to_sym when :ftm then 1 when :fgm then 2 when :fgm3 then 3 else 0 end end (team0_score - team1_score).abs <= 5 end def overtime? @team0_events.any? { |e| e.time > 2880 } end def players_with_points return @players_with_points if @players_with_points values = {} (@team0_events + @team1_events).each do |event| value = case event.type.to_sym when :ftm then 1 when :fgm2 then 2 when :fgm3 then 3 end values[event.player] ||= 0 values[event.player] += value if value end @players_with_points = values end def most_points players_with_points.values.max end def high_scorer? most_points >= 30 end def very_high_scorer? most_points >= 40 end def high_scorers players_with_points.values.select { |pts| pts >= 25 }.size end def high_shooting_pct? players_with_shooting_pct = {} (@team0_events + @team1_events).each do |event| type = event.type.to_sym players_with_shooting_pct[event.player] ||= { :fga => 0, :fgm => 0, :pct => 0 } players_with_shooting_pct[event.player][:fga] += 1 if type == :fga2 || type == :fga3 if type == :fgm2 || type == :fgm3 players_with_shooting_pct[event.player][:fgm] += 1 players_with_shooting_pct[event.player][:fga] += 1 end if players_with_shooting_pct[event.player][:fgm] > 0 && players_with_shooting_pct[event.player][:fga] > 0 players_with_shooting_pct[event.player][:pct] = (players_with_shooting_pct[event.player][:fgm] / players_with_shooting_pct[event.player][:fga].to_f) end end players_with_shooting_pct.values.any? { |v| v[:pct] >= 0.825 && v[:fga] >= 12 } end end
# encoding: UTF-8 Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'spree_abandoned_cart_email' s.version = '0.0.3' s.summary = 'Abandoned cart email' s.description = 'Abandoned cart email' s.required_ruby_version = '>= 1.9.3' s.author = 'Richard Hart' s.email = 'richard@ur-ban.com' # s.homepage = 'http://www.spreecommerce.com' #s.files = `git ls-files`.split("\n") #s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.require_path = 'lib' s.requirements << 'none' s.add_dependency 'spree_core', '~> 2.2.0.beta' s.add_development_dependency 'capybara', '~> 2.1' s.add_development_dependency 'coffee-rails' s.add_development_dependency 'database_cleaner' s.add_development_dependency 'factory_girl', '~> 4.2' s.add_development_dependency 'ffaker' s.add_development_dependency 'rspec-rails', '~> 2.13' s.add_development_dependency 'sass-rails' s.add_development_dependency 'selenium-webdriver' s.add_development_dependency 'simplecov' s.add_development_dependency 'sqlite3' end Update spree_abandoned_cart_email.gemspec downgrade dependencies # encoding: UTF-8 Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'spree_abandoned_cart_email' s.version = '0.0.3' s.summary = 'Abandoned cart email' s.description = 'Abandoned cart email' s.required_ruby_version = '>= 1.9.3' s.author = 'Richard Hart' s.email = 'richard@ur-ban.com' # s.homepage = 'http://www.spreecommerce.com' #s.files = `git ls-files`.split("\n") #s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.require_path = 'lib' s.requirements << 'none' s.add_dependency 'spree_core', '~> 2.0.5' s.add_development_dependency 'capybara', '~> 2.1' s.add_development_dependency 'coffee-rails' s.add_development_dependency 'database_cleaner' s.add_development_dependency 'factory_girl', '~> 4.2' s.add_development_dependency 'ffaker' s.add_development_dependency 'rspec-rails', '~> 2.13' s.add_development_dependency 'sass-rails' s.add_development_dependency 'selenium-webdriver' s.add_development_dependency 'simplecov' s.add_development_dependency 'sqlite3' end
# encoding: UTF-8 Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'spree_single_page_checkout' s.version = '2.2.2' s.summary = 'TODO: Add gem summary here' s.description = 'TODO: Add (optional) gem description here' s.required_ruby_version = '>= 1.9.3' # s.author = 'You' # s.email = 'you@example.com' # s.homepage = 'http://www.spreecommerce.com' #s.files = `git ls-files`.split("\n") #s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.require_path = 'lib' s.requirements << 'none' s.add_dependency 'spree_core', '~> 2.2.2' s.add_development_dependency 'capybara', '~> 2.1' s.add_development_dependency 'coffee-rails' s.add_development_dependency 'database_cleaner' s.add_development_dependency 'factory_girl', '~> 4.4' s.add_development_dependency 'ffaker' s.add_development_dependency 'rspec-rails', '~> 2.13' s.add_development_dependency 'sass-rails' s.add_development_dependency 'selenium-webdriver' s.add_development_dependency 'simplecov' s.add_development_dependency 'sqlite3' end Updates gemspec # encoding: UTF-8 Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'spree_single_page_checkout' s.version = '2.2.2' s.summary = 'Single Page Checkout via Ajax' s.description = 'Spree Single Page Checkout' s.required_ruby_version = '>= 1.9.3' s.author = 'Mumoc' s.email = 'mumo.crls@gmail.com' s.require_path = 'lib' s.requirements << 'none' s.add_dependency 'spree_core', '~> 2.2.2' s.add_development_dependency 'capybara', '~> 2.1' s.add_development_dependency 'coffee-rails' s.add_development_dependency 'database_cleaner' s.add_development_dependency 'factory_girl', '~> 4.4' s.add_development_dependency 'ffaker' s.add_development_dependency 'rspec-rails', '~> 2.13' s.add_development_dependency 'sass-rails' s.add_development_dependency 'selenium-webdriver' s.add_development_dependency 'simplecov' s.add_development_dependency 'sqlite3' end
Remove extraneous draft from Publishing API The Publishing API contains a draft item for this particular document, so discard this in order to prevent a lock version conflict and allow the document collection to be republished. doc = Document.find(229878) PublishingApiDiscardDraftWorker.new.perform(doc.content_id, :en)
include_recipe "pivotal_workstation::virtualbox" dmg_package "Vagrant" do source "http://files.vagrantup.com/packages/be0bc66efc0c5919e92d8b79e973d9911f2a511f/Vagrant-1.0.5.dmg" checksum "d9ccdd454389f5830a8218c066c8f54c15d9d32ca6060bc42677b495aad08003" action :install type "pkg" owner WS_USER package_id "com.vagrant.vagrant" end recipes in sprout-osx-apps should not depend on pivotal_workstation include_recipe "sprout-osx-apps::virtualbox" dmg_package "Vagrant" do source "http://files.vagrantup.com/packages/be0bc66efc0c5919e92d8b79e973d9911f2a511f/Vagrant-1.0.5.dmg" checksum "d9ccdd454389f5830a8218c066c8f54c15d9d32ca6060bc42677b495aad08003" action :install type "pkg" owner WS_USER package_id "com.vagrant.vagrant" end
class FontImFellDoublePica < Cask version '3.00' sha256 :no_check url 'https://github.com/w0ng/googlefontdirectory/trunk/fonts/imfelldoublepica', :using => :svn, :revision => '50', :trust_cert => true homepage 'http://www.google.com/fonts/specimen/IM%20Fell%20Double%20Pica' font 'IMFeDPit28P.ttf' font 'IMFeDPrm28P.ttf' end version 'latest' for font-im-fell-double-pica.rb preserve known version in comment for later use class FontImFellDoublePica < Cask # version '3.00' version 'latest' sha256 :no_check url 'https://github.com/w0ng/googlefontdirectory/trunk/fonts/imfelldoublepica', :using => :svn, :revision => '50', :trust_cert => true homepage 'http://www.google.com/fonts/specimen/IM%20Fell%20Double%20Pica' font 'IMFeDPit28P.ttf' font 'IMFeDPrm28P.ttf' end
class FontNotoSansSundanese < Cask version 'latest' sha256 :no_check url 'https://www.google.com/get/noto/pkgs/NotoSansSundanese-unhinted.zip' homepage 'http://www.google.com/get/noto' font 'NotoSansSundanese-Regular.ttf' end :latest as sym font-noto-sans-sundanese class FontNotoSansSundanese < Cask version :latest sha256 :no_check url 'https://www.google.com/get/noto/pkgs/NotoSansSundanese-unhinted.zip' homepage 'http://www.google.com/get/noto' font 'NotoSansSundanese-Regular.ttf' end
class FontPetitFormalScript < Cask version '1.001' sha256 '9b80a05170bac7f372b7e00bc762fe14bafd4abdeb013747b189f66525cffe89' url 'https://googlefontdirectory.googlecode.com/hg-history/67342bc472599b4c32201ee4a002fe59a6447a42/ofl/petitformalscript/PetitFormalScript-Regular.ttf' homepage 'http://www.google.com/fonts/specimen/Petit%20Formal%20Script' font 'PetitFormalScript-Regular.ttf' end add license stanza, font-petit-formal-script class FontPetitFormalScript < Cask version '1.001' sha256 '9b80a05170bac7f372b7e00bc762fe14bafd4abdeb013747b189f66525cffe89' url 'https://googlefontdirectory.googlecode.com/hg-history/67342bc472599b4c32201ee4a002fe59a6447a42/ofl/petitformalscript/PetitFormalScript-Regular.ttf' homepage 'http://www.google.com/fonts/specimen/Petit%20Formal%20Script' license :ofl font 'PetitFormalScript-Regular.ttf' end
cask 'font-rotinonhsonni-serif' do version '4.002' sha256 'fd7f76b1043ec817b3fd109130eafd1db85a3249ca7d98014a16bd8c207488d2' url 'http://www.languagegeek.com/font/RotinonhSerif.zip' homepage 'http://www.languagegeek.com/font/fontdownload.html' font 'rotinonhSerif_4_2.ttf' font 'rotinonhSerifb_4_2.ttf' font 'rotinonhSerifbi_4_2.ttf' font 'rotinonhSerifi_4_2.ttf' end Update font-rotinonhsonni-serif to 4.2 (#839) cask 'font-rotinonhsonni-serif' do version '4.2' sha256 'fd7f76b1043ec817b3fd109130eafd1db85a3249ca7d98014a16bd8c207488d2' url 'http://www.languagegeek.com/font/RotinonhSerif.zip' name 'Rotinohnsonni Serif' homepage 'http://www.languagegeek.com/font/fontdownload.html' font "rotinonhSerif_#{version.dots_to_underscores}.ttf" font "rotinonhSerifb_#{version.dots_to_underscores}.ttf" font "rotinonhSerifbi_#{version.dots_to_underscores}.ttf" font "rotinonhSerifi_#{version.dots_to_underscores}.ttf" end
cask 'mongodb-compass-readonly' do version '1.21.0' sha256 '80ef5e017c6100e9013930643a587e2e149e082637f80ddf30ac617f11bd9611' url "https://downloads.mongodb.com/compass/mongodb-compass-readonly-#{version}-darwin-x64.dmg" appcast 'https://www.mongodb.com/download-center/compass' name 'MongoDB Compass Readonly' homepage 'https://www.mongodb.com/products/compass' app 'MongoDB Compass Readonly.app' end Update mongodb-compass-readonly from 1.21.0 to 1.21.1 (#82249) cask 'mongodb-compass-readonly' do version '1.21.1' sha256 '3b3d09f91d2c8f553a2e747cb288ba35a9fbbab52886529acf277035a10b62fe' url "https://downloads.mongodb.com/compass/mongodb-compass-readonly-#{version}-darwin-x64.dmg" appcast 'https://www.mongodb.com/download-center/compass' name 'MongoDB Compass Readonly' homepage 'https://www.mongodb.com/products/compass' app 'MongoDB Compass Readonly.app' end
cask "plasticscm-cloud-edition" do version "10.0.16.5459" sha256 "314b3d8e5ed92098f88d80cfe86a0dabd89df2038cabb13385a6d11be274f23c" url "https://s3.eu-west-2.amazonaws.com/plastic-releases/releases/#{version}/plasticscm/osx/plasticscm-cloud-#{version}.pkg.zip", verified: "s3.eu-west-2.amazonaws.com/plastic-releases/" name "PlasicSCM - a Cloud Edition" desc "Install PlasticSCM locally and join a Cloud Edition subscription" homepage "https://www.plasticscm.com/" livecheck do url "https://www.plasticscm.com/download/releasenotes/" strategy :page_match regex(/plastic\sscm\s-\srelease\snotes\s-\s(\d+(?:\.\d+)*)/i) end pkg "plasticscm-cloud-#{version}.pkg" uninstall launchctl: [ "com.codicesoftware.plasticscm.macplastic", "com.codicesoftware.plasticscm.server", ], quit: "com.codicesoftware.plasticscm", pkgutil: [ "com.codicesoftware.plasticscm.macplastic", "com.codicesoftware.plasticscm.server", ], delete: [ "/Applications/Gluon.app", "/Applications/PlasticSCM.app", "/Applications/PlasticSCMServer.app", ] end Update plasticscm-cloud-edition from 10.0.16.5459 to 10.0.16.5533 (#106482) cask "plasticscm-cloud-edition" do version "10.0.16.5533" sha256 "f23693dc5fba607ad667e27e8de5723bbe4531ab09269f40276ef8a830ad67f2" url "https://s3.eu-west-2.amazonaws.com/plastic-releases/releases/#{version}/plasticscm/osx/plasticscm-cloud-#{version}.pkg.zip", verified: "s3.eu-west-2.amazonaws.com/plastic-releases/" name "PlasicSCM - a Cloud Edition" desc "Install PlasticSCM locally and join a Cloud Edition subscription" homepage "https://www.plasticscm.com/" livecheck do url "https://www.plasticscm.com/download/releasenotes/" regex(/plastic\sscm\s-\srelease\snotes\s-\s(\d+(?:\.\d+)*)/i) end pkg "plasticscm-cloud-#{version}.pkg" uninstall launchctl: [ "com.codicesoftware.plasticscm.macplastic", "com.codicesoftware.plasticscm.server", ], quit: "com.codicesoftware.plasticscm", pkgutil: [ "com.codicesoftware.plasticscm.macplastic", "com.codicesoftware.plasticscm.server", ], delete: [ "/Applications/Gluon.app", "/Applications/PlasticSCM.app", "/Applications/PlasticSCMServer.app", ] end
# -*- coding: utf-8 -*- step ':pathにをクセスする' do |path| page.save_screenshot("tmp/poltergeist.png", full: true) visit path end step 'html' do p page.html end step 'screenshot:name' do |name| page.save_screenshot("tmp/poltergeist_#{name}.png") end step ':selectorγ‚’γ‚―γƒͺック' do |selector| find(selector).click end step 'γƒœγ‚Ώγƒ³:nameγ‚’γ‚―γƒͺック' do |name| click_button name end step 'amazonにログむン' do sleep(1) selector = '#OffAmazonPaymentsWidgets0' find(selector).click sleep(1) fill_in "ap_email", :with => ENV["AMAZON_PAYMENTS_TEST_USER_MAIL"] fill_in "ap_password", :with => ENV["AMAZON_PAYMENTS_TEST_USER_PASSWORD"] #click_button "Sign in using our secure server" #page.first(".signin-button-text").click selector = '.signin-button-text' find(selector).click sleep(3) end step 'amazonにポップをップログむン' do sleep(3) selector = '#OffAmazonPaymentsWidgets0' find(selector).click sleep(1) popup = page.driver.window_handles.last page.within_window popup do fill_in "ap_email", :with => ENV["AMAZON_PAYMENTS_TEST_USER_MAIL"] fill_in "ap_password", :with => ENV["AMAZON_PAYMENTS_TEST_USER_PASSWORD"] #click_button "Sign in using our secure server" selector = '.signin-button-text' find(selector).click end sleep(3) end step 'sleep :seconds' do |seconds| sleep seconds.to_i end step 'access_tokenを取得' do current_url =~ /access_token=([^&]*).*/ @access_token = URI.unescape( $1 ) end step 'order_reference_idを取得' do current_url =~ /access_token=([^&]*).*/ @order_reference_id = find('#orderReferenceId').value end step 'set_order_refernce_detailsを正しく呼べること' do @aor = Skirt::AmazonOrderReference.new @aor.amount = 10 @aor.amazon_order_reference_id = @order_reference_id response = @aor.set_order_refernce_details state = response["SetOrderReferenceDetailsResponse"]["SetOrderReferenceDetailsResult"]["OrderReferenceDetails"]["OrderReferenceStatus"]["State"] expect(state).to eq 'Draft' end step 'get_order_refernce_detailsを正しく呼べること' do @aor = Skirt::AmazonOrderReference.new @aor.amount = 10 @aor.amazon_order_reference_id = @order_reference_id sleep 1 response = @aor.get_order_reference_details(@order_reference_id, @access_token) state = response["GetOrderReferenceDetailsResponse"]["GetOrderReferenceDetailsResult"]["OrderReferenceDetails"]["OrderReferenceStatus"]["State"] expect(state).to eq 'Draft' end step "confirm_order_refernceを正しく呼べること" do @aor = Skirt::AmazonOrderReference.new @aor.amount = 10 @aor.amazon_order_reference_id = @order_reference_id @aor.set_order_refernce_details response = @aor.confirm_order_reference expect(response["ConfirmOrderReferenceResponse"]).to be_present end step "authorizeを正しく呼べること" do @aor = Skirt::AmazonOrderReference.new @aor.amount = 10 @aor.amazon_order_reference_id = @order_reference_id @aor.set_order_refernce_details @aor.confirm_order_reference response = @aor.authorize details = response["AuthorizeResponse"]["AuthorizeResult"]["AuthorizationDetails"] expect(details).to be_present end step "close_authorizeを正しく呼べること" do @aor.close_authorization expect(@aor.authorization_status).to eq 'Closed' end step "captureする" do response = @aor.capture end step "get_order_reference_detailsする" do response = @aor.get_order_reference_details(@aor.amazon_order_reference_id, nil) end step "get_authorization_detailsする" do response = @aor.get_authorization_details end step "0秒でauthorizeしてcaptureする" do @aor = Skirt::AmazonOrderReference.new @aor.amount = 10 @aor.amazon_order_reference_id = @order_reference_id @aor.set_order_refernce_details @aor.confirm_order_reference response = @aor.authorize(0) response = @aor.capture end step "save_and_authorizeを正しく呼べること" do @aor = Skirt::AmazonOrderReference.new @aor.amount = 10 @aor.amazon_order_reference_id = @order_reference_id response = @aor.save_and_authorize(@access_token) state = response["GetOrderReferenceDetailsResponse"]["GetOrderReferenceDetailsResult"]["OrderReferenceDetails"]["OrderReferenceStatus"]["State"] expect(state).to eq "Closed" end step "order_reference_statusが:statusであること" do |status| aor = Skirt::AmazonOrderReference.last expect(aor.order_reference_status).to eq status end step "authorization_statusが:statusであること" do |status| aor = Skirt::AmazonOrderReference.last expect(aor.authorization_status).to eq status end step "capture_statusが:statusであること" do |status| aor = Skirt::AmazonOrderReference.last expect(aor.capture_status).to eq status end step "cancelする" do @aor = Skirt::AmazonOrderReference.new @aor.amount = 10 @aor.amazon_order_reference_id = @order_reference_id @aor.set_order_refernce_details @aor.confirm_order_reference response = @aor.cancel end refactor # -*- coding: utf-8 -*- step ':pathにをクセスする' do |path| page.save_screenshot("tmp/poltergeist.png", full: true) visit path end step 'html' do p page.html end step 'screenshot:name' do |name| page.save_screenshot("tmp/poltergeist_#{name}.png") end step ':selectorγ‚’γ‚―γƒͺック' do |selector| find(selector).click end step 'γƒœγ‚Ώγƒ³:nameγ‚’γ‚―γƒͺック' do |name| click_button name end step 'amazonにログむン' do sleep(1) selector = '#OffAmazonPaymentsWidgets0' find(selector).click sleep(1) fill_in "ap_email", :with => ENV["AMAZON_PAYMENTS_TEST_USER_MAIL"] fill_in "ap_password", :with => ENV["AMAZON_PAYMENTS_TEST_USER_PASSWORD"] #click_button "Sign in using our secure server" #page.first(".signin-button-text").click selector = '.signin-button-text' find(selector).click sleep(3) end step 'amazonにポップをップログむン' do sleep(3) selector = '#OffAmazonPaymentsWidgets0' find(selector).click sleep(1) popup = page.driver.window_handles.last page.within_window popup do fill_in "ap_email", :with => ENV["AMAZON_PAYMENTS_TEST_USER_MAIL"] fill_in "ap_password", :with => ENV["AMAZON_PAYMENTS_TEST_USER_PASSWORD"] #click_button "Sign in using our secure server" selector = '.signin-button-text' find(selector).click end sleep(3) end step 'sleep :seconds' do |seconds| sleep seconds.to_i end step 'access_tokenを取得' do current_url =~ /access_token=([^&]*).*/ @access_token = URI.unescape( $1 ) end step 'order_reference_idを取得' do current_url =~ /access_token=([^&]*).*/ @order_reference_id = find('#orderReferenceId').value end step 'set_order_refernce_detailsを正しく呼べること' do @aor = Skirt::AmazonOrderReference.new @aor.amount = 10 @aor.amazon_order_reference_id = @order_reference_id response = @aor.set_order_refernce_details state = response["SetOrderReferenceDetailsResponse"]["SetOrderReferenceDetailsResult"]["OrderReferenceDetails"]["OrderReferenceStatus"]["State"] expect(state).to eq 'Draft' end step 'get_order_refernce_detailsを正しく呼べること' do @aor = Skirt::AmazonOrderReference.new @aor.amount = 10 @aor.amazon_order_reference_id = @order_reference_id sleep 1 response = @aor.get_order_reference_details(@order_reference_id, @access_token) state = response["GetOrderReferenceDetailsResponse"]["GetOrderReferenceDetailsResult"]["OrderReferenceDetails"]["OrderReferenceStatus"]["State"] expect(state).to eq 'Draft' end step "confirm_order_refernceを正しく呼べること" do @aor = Skirt::AmazonOrderReference.new @aor.amount = 10 @aor.amazon_order_reference_id = @order_reference_id @aor.set_order_refernce_details response = @aor.confirm_order_reference expect(response["ConfirmOrderReferenceResponse"]).to be_present end step "authorizeを正しく呼べること" do @aor = Skirt::AmazonOrderReference.new @aor.amount = 10 @aor.amazon_order_reference_id = @order_reference_id @aor.set_order_refernce_details @aor.confirm_order_reference response = @aor.authorize details = response["AuthorizeResponse"]["AuthorizeResult"]["AuthorizationDetails"] expect(details).to be_present end step "close_authorizeを正しく呼べること" do @aor.close_authorization expect(@aor.authorization_status).to eq 'Closed' end step "0秒でauthorizeしてcaptureする" do @aor = Skirt::AmazonOrderReference.new @aor.amount = 10 @aor.amazon_order_reference_id = @order_reference_id @aor.set_order_refernce_details @aor.confirm_order_reference response = @aor.authorize(0) response = @aor.capture end step "save_and_authorizeを正しく呼べること" do @aor = Skirt::AmazonOrderReference.new @aor.amount = 10 @aor.amazon_order_reference_id = @order_reference_id response = @aor.save_and_authorize(@access_token) state = response["GetOrderReferenceDetailsResponse"]["GetOrderReferenceDetailsResult"]["OrderReferenceDetails"]["OrderReferenceStatus"]["State"] expect(state).to eq "Closed" end step "order_reference_statusが:statusであること" do |status| aor = Skirt::AmazonOrderReference.last expect(aor.order_reference_status).to eq status end step "authorization_statusが:statusであること" do |status| aor = Skirt::AmazonOrderReference.last expect(aor.authorization_status).to eq status end step "capture_statusが:statusであること" do |status| aor = Skirt::AmazonOrderReference.last expect(aor.capture_status).to eq status end step "cancelする" do @aor = Skirt::AmazonOrderReference.new @aor.amount = 10 @aor.amazon_order_reference_id = @order_reference_id @aor.set_order_refernce_details @aor.confirm_order_reference response = @aor.cancel end
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe 'allow_values_for' do include ModelBuilder # Defines a model, create a validation and returns a raw matcher def define_and_validate(options={}) @model = define_model :product, :title => :string, :category => :string do validates_format_of :title, options end allow_values_for(:title) end describe 'messages' do before(:each){ @matcher = define_and_validate(:with => /X|Y|Z/) } it 'should contain a description' do @matcher = allow_values_for(:title, "X", "Y", "Z") @matcher.description.should == 'allow "X", "Y", and "Z" as values for title' end it 'should set is_valid? message' do @matcher.in("A").matches?(@model) @matcher.failure_message.should == 'Expected Product to be valid when title is set to "A"' end it 'should set allow_nil? message' do @matcher.allow_nil.matches?(@model) @matcher.failure_message.should == 'Expected Product to allow nil values for title' end it 'should set allow_blank? message' do @matcher.allow_blank.matches?(@model) @matcher.failure_message.should == 'Expected Product to allow blank values for title' end end describe 'matchers' do it { should define_and_validate(:with => /X|Y|Z/).in('X', 'Y', 'Z') } it { should_not define_and_validate(:with => /X|Y|Z/).in('A') } it { should define_and_validate(:with => /X|Y|Z/, :message => 'valid').in('X', 'Y', 'Z').message('valid') } create_optional_boolean_specs(:allow_nil, self, :with => /X|Y|Z/) create_optional_boolean_specs(:allow_blank, self, :with => /X|Y|Z/) end describe 'macros' do before(:each){ define_and_validate(:with => /X|Y|Z/) } should_allow_values_for :title, 'X' should_not_allow_values_for :title, 'A' describe 'deprecation' do it { should validate_format_of(:title, 'X') } should_not_validate_format_of :title, 'A' end end describe 'failures' do it "should fail if any of the values are valid on invalid cases" do define_and_validate(:with => /X|Y|Z/) lambda { should_not allow_values_for :title, 'A', 'X', 'B' }.should raise_error(Spec::Expectations::ExpectationNotMetError, /Did not expect Product to be valid/) end end end Improve test coverage for allow_values_for. require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe 'allow_values_for' do include ModelBuilder # Defines a model, create a validation and returns a raw matcher def define_and_validate(options={}) @model = define_model :product, :title => :string, :category => :string do validates_format_of :title, options end allow_values_for(:title) end describe 'messages' do before(:each){ @matcher = define_and_validate(:with => /X|Y|Z/) } it 'should contain a description' do @matcher = allow_values_for(:title, "X", "Y", "Z") @matcher.description.should == 'allow "X", "Y", and "Z" as values for title' end it 'should set is_valid? message' do @matcher.in("A").matches?(@model) @matcher.failure_message.should == 'Expected Product to be valid when title is set to "A"' end it 'should set allow_nil? message' do @matcher.allow_nil.matches?(@model) @matcher.failure_message.should == 'Expected Product to allow nil values for title' end it 'should set allow_blank? message' do @matcher.allow_blank.matches?(@model) @matcher.failure_message.should == 'Expected Product to allow blank values for title' end end describe 'matchers' do it { should define_and_validate(:with => /X|Y|Z/).in('X', 'Y', 'Z') } it { should_not define_and_validate(:with => /X|Y|Z/).in('A') } it { should define_and_validate(:with => /X|Y|Z/, :message => 'valid').in('X', 'Y', 'Z').message('valid') } create_optional_boolean_specs(:allow_nil, self, :with => /X|Y|Z/) create_optional_boolean_specs(:allow_blank, self, :with => /X|Y|Z/) end describe 'macros' do before(:each){ define_and_validate(:with => /X|Y|Z/) } should_allow_values_for :title, 'X' should_not_allow_values_for :title, 'A' describe 'deprecation' do it { should validate_format_of(:title, 'X') } should_not_validate_format_of :title, 'A' end end describe 'failures' do before(:each) do define_and_validate(:with => /X|Y|Z/) end it "should fail if any of the values are valid on invalid cases" do lambda { should_not allow_values_for :title, 'A', 'X', 'B' }.should raise_error(Spec::Expectations::ExpectationNotMetError, /Did not expect Product to be valid/) end it "should also fail if all values are valid" do lambda { should_not allow_values_for :title, 'X', 'Y', 'Z' }.should raise_error(Spec::Expectations::ExpectationNotMetError, /Did not expect Product to be valid/) end it "should not fail if all values are invalid" do lambda { should_not allow_values_for :title, 'A', 'B', 'C' }.should_not raise_error end end end
require File.join(File.dirname(File.expand_path(__FILE__)), 'spec_helper') describe "Sequel::Schema::Generator dump methods" do before do @d = Sequel::Database.new @g = Sequel::Schema::Generator end it "should allow the same table information to be converted to a string for evaling inside of another instance with the same result" do g = @g.new(@d) do Integer :a varchar :b column :dt, DateTime column :vc, :varchar primary_key :c foreign_key :d, :a foreign_key :e foreign_key [:d, :e], :name=>:cfk constraint :blah, "a=1" check :a=>1 unique [:e] index :a index [:c, :e] index [:b, :c], :type=>:hash index [:d], :unique=>true spatial_index :a full_text_index [:b, :c] end g2 = @g.new(@d) do instance_eval(g.dump_columns, __FILE__, __LINE__) instance_eval(g.dump_constraints, __FILE__, __LINE__) instance_eval(g.dump_indexes, __FILE__, __LINE__) end g.columns.should == g2.columns g.constraints.should == g2.constraints g.indexes.should == g2.indexes end it "should allow dumping indexes as separate add_index and drop_index methods" do g = @g.new(@d) do index :a index [:c, :e], :name=>:blah index [:b, :c], :unique=>true end g.dump_indexes(:add_index=>:t).should == (<<END_CODE).strip add_index :t, [:a] add_index :t, [:c, :e], :name=>:blah add_index :t, [:b, :c], :unique=>true END_CODE g.dump_indexes(:drop_index=>:t).should == (<<END_CODE).strip drop_index :t, [:a] drop_index :t, [:c, :e], :name=>:blah drop_index :t, [:b, :c], :unique=>true END_CODE end it "should raise an error if you try to dump a Generator that uses a constraint with a proc" do proc{@g.new(@d){check{a>1}}.dump_constraints}.should raise_error(Sequel::Error) end end describe "Sequel::Database dump methods" do before do @d = Sequel::Database.new @d.meta_def(:tables){|o| [:t1, :t2]} @d.meta_def(:schema) do |t, *o| case t when :t1, 't__t1', :t__t1.identifier [[:c1, {:db_type=>'integer', :primary_key=>true, :allow_null=>false}], [:c2, {:db_type=>'varchar(20)', :allow_null=>true}]] when :t2 [[:c1, {:db_type=>'integer', :primary_key=>true, :allow_null=>false}], [:c2, {:db_type=>'numeric', :primary_key=>true, :allow_null=>false}]] when :t5 [[:c1, {:db_type=>'blahblah', :allow_null=>true}]] end end end it "should support dumping table schemas as create_table method calls" do @d.dump_table_schema(:t1).should == "create_table(:t1) do\n primary_key :c1\n String :c2, :size=>20\nend" end it "should support dumping table schemas when given a string" do @d.dump_table_schema('t__t1').should == "create_table(\"t__t1\") do\n primary_key :c1\n String :c2, :size=>20\nend" end it "should support dumping table schemas when given an identifier" do @d.dump_table_schema(:t__t1.identifier).should == "create_table(\"t__t1\") do\n primary_key :c1\n String :c2, :size=>20\nend" end it "should dump non-Integer primary key columns with explicit :type" do @d.meta_def(:schema){|*s| [[:c1, {:db_type=>'bigint', :primary_key=>true, :allow_null=>true}]]} @d.dump_table_schema(:t6).should == "create_table(:t6) do\n primary_key :c1, :type=>Bignum\nend" end it "should handle foreign keys" do @d.meta_def(:schema){|*s| [[:c1, {:db_type=>'integer', :allow_null=>true}]]} @d.meta_def(:foreign_key_list){|*s| [{:columns=>[:c1], :table=>:t2, :key=>[:c2]}]} @d.dump_table_schema(:t6).should == "create_table(:t6) do\n foreign_key :c1, :t2, :key=>[:c2]\nend" end it "should handle primary keys that are also foreign keys" do @d.meta_def(:schema){|*s| [[:c1, {:db_type=>'integer', :primary_key=>true, :allow_null=>true}]]} @d.meta_def(:foreign_key_list){|*s| [{:columns=>[:c1], :table=>:t2, :key=>[:c2]}]} s = @d.dump_table_schema(:t6) s.should =~ /create_table\(:t6\) do\n primary_key :c1, / s.should =~ /:table=>:t2/ s.should =~ /:key=>\[:c2\]/ end it "should handle foreign key options" do @d.meta_def(:schema){|*s| [[:c1, {:db_type=>'integer', :allow_null=>true}]]} @d.meta_def(:foreign_key_list){|*s| [{:columns=>[:c1], :table=>:t2, :key=>[:c2], :on_delete=>:restrict, :on_update=>:set_null, :deferrable=>true}]} s = @d.dump_table_schema(:t6) s.should =~ /create_table\(:t6\) do\n foreign_key :c1, :t2, / s.should =~ /:key=>\[:c2\]/ s.should =~ /:on_delete=>:restrict/ s.should =~ /:on_update=>:set_null/ s.should =~ /:deferrable=>true/ end it "should handle foreign key options in the primary key" do @d.meta_def(:schema){|*s| [[:c1, {:db_type=>'integer', :primary_key=>true, :allow_null=>true}]]} @d.meta_def(:foreign_key_list){|*s| [{:columns=>[:c1], :table=>:t2, :key=>[:c2], :on_delete=>:restrict, :on_update=>:set_null, :deferrable=>true}]} s = @d.dump_table_schema(:t6) s.should =~ /create_table\(:t6\) do\n primary_key :c1, / s.should =~ /:table=>:t2/ s.should =~ /:key=>\[:c2\]/ s.should =~ /:on_delete=>:restrict/ s.should =~ /:on_update=>:set_null/ s.should =~ /:deferrable=>true/ end it "should omit foreign key options that are the same as defaults" do @d.meta_def(:schema){|*s| [[:c1, {:db_type=>'integer', :allow_null=>true}]]} @d.meta_def(:foreign_key_list){|*s| [{:columns=>[:c1], :table=>:t2, :key=>[:c2], :on_delete=>:no_action, :on_update=>:no_action, :deferrable=>false}]} s = @d.dump_table_schema(:t6) s.should =~ /create_table\(:t6\) do\n foreign_key :c1, :t2, / s.should =~ /:key=>\[:c2\]/ s.should_not =~ /:on_delete/ s.should_not =~ /:on_update/ s.should_not =~ /:deferrable/ end it "should omit foreign key options that are the same as defaults in the primary key" do @d.meta_def(:schema){|*s| [[:c1, {:db_type=>'integer', :primary_key=>true, :allow_null=>true}]]} @d.meta_def(:foreign_key_list){|*s| [{:columns=>[:c1], :table=>:t2, :key=>[:c2], :on_delete=>:no_action, :on_update=>:no_action, :deferrable=>false}]} s = @d.dump_table_schema(:t6) s.should =~ /create_table\(:t6\) do\n primary_key :c1, / s.should =~ /:table=>:t2/ s.should =~ /:key=>\[:c2\]/ s.should_not =~ /:on_delete/ s.should_not =~ /:on_update/ s.should_not =~ /:deferrable/ end it "should dump primary key columns with explicit :type equal to the database type when :same_db option is passed" do @d.meta_def(:schema){|*s| [[:c1, {:db_type=>'somedbspecifictype', :primary_key=>true, :allow_null=>false}]]} @d.dump_table_schema(:t7, :same_db => true).should == "create_table(:t7) do\n primary_key :c1, :type=>\"somedbspecifictype\"\nend" end it "should use a composite primary_key calls if there is a composite primary key" do @d.dump_table_schema(:t2).should == "create_table(:t2) do\n Integer :c1, :null=>false\n BigDecimal :c2, :null=>false\n \n primary_key [:c1, :c2]\nend" end it "should use a composite foreign_key calls if there is a composite foreign key" do @d.meta_def(:schema){|*s| [[:c1, {:db_type=>'integer'}], [:c2, {:db_type=>'integer'}]]} @d.meta_def(:foreign_key_list){|*s| [{:columns=>[:c1, :c2], :table=>:t2, :key=>[:c3, :c4]}]} @d.dump_table_schema(:t1).should == "create_table(:t1) do\n Integer :c1\n Integer :c2\n \n foreign_key [:c1, :c2], :t2, :key=>[:c3, :c4]\nend" end it "should include index information if available" do @d.meta_def(:indexes) do |t| {:i1=>{:columns=>[:c1], :unique=>false}, :t1_c2_c1_index=>{:columns=>[:c2, :c1], :unique=>true}} end @d.dump_table_schema(:t1).should == "create_table(:t1, :ignore_index_errors=>true) do\n primary_key :c1\n String :c2, :size=>20\n \n index [:c1], :name=>:i1\n index [:c2, :c1], :unique=>true\nend" end it "should support dumping the whole database as a migration" do @d.dump_schema_migration.should == <<-END_MIG Sequel.migration do up do create_table(:t1) do primary_key :c1 String :c2, :size=>20 end create_table(:t2) do Integer :c1, :null=>false BigDecimal :c2, :null=>false primary_key [:c1, :c2] end end down do drop_table(:t2, :t1) end end END_MIG end it "should sort table names when dumping a migration" do @d.meta_def(:tables){|o| [:t2, :t1]} @d.dump_schema_migration.should == <<-END_MIG Sequel.migration do up do create_table(:t1) do primary_key :c1 String :c2, :size=>20 end create_table(:t2) do Integer :c1, :null=>false BigDecimal :c2, :null=>false primary_key [:c1, :c2] end end down do drop_table(:t2, :t1) end end END_MIG end it "should sort table names topologically when dumping a migration with foreign keys" do @d.meta_def(:tables){|o| [:t1, :t2]} @d.meta_def(:schema) do |t| t == :t1 ? [[:c2, {:db_type=>'integer'}]] : [[:c1, {:db_type=>'integer', :primary_key=>true}]] end @d.meta_def(:foreign_key_list) do |t| t == :t1 ? [{:columns=>[:c2], :table=>:t2, :key=>[:c1]}] : [] end @d.dump_schema_migration.should == <<-END_MIG Sequel.migration do up do create_table(:t2) do primary_key :c1 end create_table(:t1) do foreign_key :c2, :t2, :key=>[:c1] end end down do drop_table(:t1, :t2) end end END_MIG end it "should handle circular dependencies when dumping a migration with foreign keys" do @d.meta_def(:tables){|o| [:t1, :t2]} @d.meta_def(:schema) do |t| t == :t1 ? [[:c2, {:db_type=>'integer'}]] : [[:c1, {:db_type=>'integer'}]] end @d.meta_def(:foreign_key_list) do |t| t == :t1 ? [{:columns=>[:c2], :table=>:t2, :key=>[:c1]}] : [{:columns=>[:c1], :table=>:t1, :key=>[:c2]}] end @d.dump_schema_migration.should == <<-END_MIG Sequel.migration do up do create_table(:t1) do Integer :c2 end create_table(:t2) do foreign_key :c1, :t1, :key=>[:c2] end alter_table(:t1) do add_foreign_key [:c2], :t2, :key=>[:c1] end end down do drop_table(:t2, :t1) end end END_MIG end it "should sort topologically even if the database raises an error when trying to parse foreign keys for a non-existent table" do @d.meta_def(:tables){|o| [:t1, :t2]} @d.meta_def(:schema) do |t| t == :t1 ? [[:c2, {:db_type=>'integer'}]] : [[:c1, {:db_type=>'integer', :primary_key=>true}]] end @d.meta_def(:foreign_key_list) do |t| raise Sequel::DatabaseError unless [:t1, :t2].include?(t) t == :t1 ? [{:columns=>[:c2], :table=>:t2, :key=>[:c1]}] : [] end @d.dump_schema_migration.should == <<-END_MIG Sequel.migration do up do create_table(:t2) do primary_key :c1 end create_table(:t1) do foreign_key :c2, :t2, :key=>[:c1] end end down do drop_table(:t1, :t2) end end END_MIG end it "should honor the :same_db option to not convert types" do @d.dump_table_schema(:t1, :same_db=>true).should == "create_table(:t1) do\n primary_key :c1\n column :c2, \"varchar(20)\"\nend" @d.dump_schema_migration(:same_db=>true).should == <<-END_MIG Sequel.migration do up do create_table(:t1) do primary_key :c1 column :c2, "varchar(20)" end create_table(:t2) do column :c1, "integer", :null=>false column :c2, "numeric", :null=>false primary_key [:c1, :c2] end end down do drop_table(:t2, :t1) end end END_MIG end it "should honor the :indexes => false option to not include indexes" do @d.meta_def(:indexes) do |t| {:i1=>{:columns=>[:c1], :unique=>false}, :t1_c2_c1_index=>{:columns=>[:c2, :c1], :unique=>true}} end @d.dump_table_schema(:t1, :indexes=>false).should == "create_table(:t1) do\n primary_key :c1\n String :c2, :size=>20\nend" @d.dump_schema_migration(:indexes=>false).should == <<-END_MIG Sequel.migration do up do create_table(:t1) do primary_key :c1 String :c2, :size=>20 end create_table(:t2) do Integer :c1, :null=>false BigDecimal :c2, :null=>false primary_key [:c1, :c2] end end down do drop_table(:t2, :t1) end end END_MIG end it "should have :indexes => false option disable foreign keys as well when dumping a whole migration" do @d.meta_def(:foreign_key_list) do |t| t == :t1 ? [{:columns=>[:c2], :table=>:t2, :key=>[:c1]}] : [] end @d.dump_schema_migration(:indexes=>false).should_not =~ /foreign_key/ end it "should have :foreign_keys option override :indexes => false disabling of foreign keys" do @d.meta_def(:foreign_key_list) do |t| t == :t1 ? [{:columns=>[:c2], :table=>:t2, :key=>[:c1]}] : [] end @d.dump_schema_migration(:indexes=>false, :foreign_keys=>true).should =~ /foreign_key/ end it "should support dumping just indexes as a migration" do @d.meta_def(:tables){|o| [:t1]} @d.meta_def(:indexes) do |t| {:i1=>{:columns=>[:c1], :unique=>false}, :t1_c2_c1_index=>{:columns=>[:c2, :c1], :unique=>true}} end @d.dump_indexes_migration.should == <<-END_MIG Sequel.migration do up do add_index :t1, [:c1], :ignore_errors=>true, :name=>:i1 add_index :t1, [:c2, :c1], :ignore_errors=>true, :unique=>true end down do drop_index :t1, [:c1], :ignore_errors=>true, :name=>:i1 drop_index :t1, [:c2, :c1], :ignore_errors=>true, :unique=>true end end END_MIG end it "should handle missing index parsing support when dumping index migration" do @d.meta_def(:tables){|o| [:t1]} @d.dump_indexes_migration.should == <<-END_MIG Sequel.migration do up do end down do end end END_MIG end it "should handle missing foreign key parsing support when dumping foreign key migration" do @d.meta_def(:tables){|o| [:t1]} @d.dump_foreign_key_migration.should == <<-END_MIG Sequel.migration do up do end end END_MIG end it "should support dumping just foreign_keys as a migration" do @d.meta_def(:tables){|o| [:t1, :t2, :t3]} @d.meta_def(:schema) do |t| t == :t1 ? [[:c2, {:db_type=>'integer'}]] : [[:c1, {:db_type=>'integer'}]] end @d.meta_def(:foreign_key_list) do |t, *a| case t when :t1 [{:columns=>[:c2], :table=>:t2, :key=>[:c1]}] when :t2 [{:columns=>[:c1, :c3], :table=>:t1, :key=>[:c2, :c4]}] else [] end end @d.dump_foreign_key_migration.should == <<-END_MIG Sequel.migration do up do alter_table(:t1) do add_foreign_key [:c2], :t2, :key=>[:c1] end alter_table(:t2) do add_foreign_key [:c1, :c3], :t1, :key=>[:c2, :c4] end end end END_MIG end it "should handle not null values and defaults" do @d.meta_def(:schema){|*s| [[:c1, {:db_type=>'date', :default=>"'now()'", :allow_null=>true}], [:c2, {:db_type=>'datetime', :allow_null=>false}]]} @d.dump_table_schema(:t3).should == "create_table(:t3) do\n Date :c1\n DateTime :c2, :null=>false\nend" end it "should handle converting common defaults" do @d.meta_def(:schema) do |t, *os| s = [[:c1, {:db_type=>'boolean', :default=>"false", :type=>:boolean, :allow_null=>true}], [:c2, {:db_type=>'varchar', :default=>"'blah'", :type=>:string, :allow_null=>true}], [:c3, {:db_type=>'integer', :default=>"-1", :type=>:integer, :allow_null=>true}], [:c4, {:db_type=>'float', :default=>"1.0", :type=>:float, :allow_null=>true}], [:c5, {:db_type=>'decimal', :default=>"100.50", :type=>:decimal, :allow_null=>true}], [:c6, {:db_type=>'blob', :default=>"'blah'", :type=>:blob, :allow_null=>true}], [:c7, {:db_type=>'date', :default=>"'2008-10-29'", :type=>:date, :allow_null=>true}], [:c8, {:db_type=>'datetime', :default=>"'2008-10-29 10:20:30'", :type=>:datetime, :allow_null=>true}], [:c9, {:db_type=>'time', :default=>"'10:20:30'", :type=>:time, :allow_null=>true}], [:c10, {:db_type=>'interval', :default=>"'6 weeks'", :type=>:interval, :allow_null=>true}]] s.each{|_, c| c[:ruby_default] = column_schema_to_ruby_default(c[:default], c[:type])} s end @d.dump_table_schema(:t4).gsub(/[+-]\d\d:\d\d"\)/, '")').should == "create_table(:t4) do\n TrueClass :c1, :default=>false\n String :c2, :default=>\"blah\"\n Integer :c3, :default=>-1\n Float :c4, :default=>1.0\n BigDecimal :c5, :default=>BigDecimal.new(\"0.1005E3\")\n File :c6, :default=>Sequel::SQL::Blob.new(\"blah\")\n Date :c7, :default=>Date.parse(\"2008-10-29\")\n DateTime :c8, :default=>DateTime.parse(\"2008-10-29T10:20:30\")\n Time :c9, :default=>Sequel::SQLTime.parse(\"10:20:30\"), :only_time=>true\n String :c10\nend" @d.dump_table_schema(:t4, :same_db=>true).gsub(/[+-]\d\d:\d\d"\)/, '")').should == "create_table(:t4) do\n column :c1, \"boolean\", :default=>false\n column :c2, \"varchar\", :default=>\"blah\"\n column :c3, \"integer\", :default=>-1\n column :c4, \"float\", :default=>1.0\n column :c5, \"decimal\", :default=>BigDecimal.new(\"0.1005E3\")\n column :c6, \"blob\", :default=>Sequel::SQL::Blob.new(\"blah\")\n column :c7, \"date\", :default=>Date.parse(\"2008-10-29\")\n column :c8, \"datetime\", :default=>DateTime.parse(\"2008-10-29T10:20:30\")\n column :c9, \"time\", :default=>Sequel::SQLTime.parse(\"10:20:30\")\n column :c10, \"interval\", :default=>\"'6 weeks'\".lit\nend" end it "should not use a '...'.lit as a fallback if using MySQL with the :same_db option" do @d.meta_def(:database_type){:mysql} @d.meta_def(:schema) do |t, *os| s = [[:c10, {:db_type=>'interval', :default=>"'6 weeks'", :type=>:interval, :allow_null=>true}]] s.each{|_, c| c[:ruby_default] = column_schema_to_ruby_default(c[:default], c[:type])} s end @d.dump_table_schema(:t5, :same_db=>true).should == "create_table(:t5) do\n column :c10, \"interval\"\nend" end it "should convert unknown database types to strings" do @d.dump_table_schema(:t5).should == "create_table(:t5) do\n String :c1\nend" end it "should convert many database types to ruby types" do types = %w"mediumint smallint int integer mediumint(6) smallint(7) int(8) integer(9) tinyint tinyint(2) bigint bigint(20) real float double boolean tinytext mediumtext longtext text clob date datetime timestamp time char character varchar varchar(255) varchar(30) bpchar string money decimal decimal(10,2) numeric numeric(15,3) number bytea tinyblob mediumblob longblob blob varbinary varbinary(10) binary binary(20) year" + ["double precision", "timestamp with time zone", "timestamp without time zone", "time with time zone", "time without time zone", "character varying(20)"] + %w"nvarchar ntext smalldatetime smallmoney binary varbinary nchar" + ["timestamp(6) without time zone", "timestamp(6) with time zone", "int(12) unsigned", 'bigint unsigned', 'tinyint(3) unsigned', 'identity', 'int identity'] @d.meta_def(:schema) do |t, *o| i = 0 types.map{|x| [:"c#{i+=1}", {:db_type=>x, :allow_null=>true}]} end @d.dump_table_schema(:x).should == (<<END_MIG).chomp create_table(:x) do Integer :c1 Integer :c2 Integer :c3 Integer :c4 Integer :c5 Integer :c6 Integer :c7 Integer :c8 Integer :c9 Integer :c10 Bignum :c11 Bignum :c12 Float :c13 Float :c14 Float :c15 TrueClass :c16 String :c17, :text=>true String :c18, :text=>true String :c19, :text=>true String :c20, :text=>true String :c21, :text=>true Date :c22 DateTime :c23 DateTime :c24 Time :c25, :only_time=>true String :c26, :fixed=>true String :c27, :fixed=>true String :c28 String :c29, :size=>255 String :c30, :size=>30 String :c31 String :c32 BigDecimal :c33, :size=>[19, 2] BigDecimal :c34 BigDecimal :c35, :size=>[10, 2] BigDecimal :c36 BigDecimal :c37, :size=>[15, 3] BigDecimal :c38 File :c39 File :c40 File :c41 File :c42 File :c43 File :c44 File :c45, :size=>10 File :c46 File :c47, :size=>20 Integer :c48 Float :c49 DateTime :c50 DateTime :c51 Time :c52, :only_time=>true Time :c53, :only_time=>true String :c54, :size=>20 String :c55 String :c56, :text=>true DateTime :c57 BigDecimal :c58, :size=>[19, 2] File :c59 File :c60 String :c61, :fixed=>true DateTime :c62, :size=>6 DateTime :c63, :size=>6 Integer :c64 Bignum :c65 Integer :c66 Integer :c67 Integer :c68 end END_MIG end end Add spec for :index_names option. require File.join(File.dirname(File.expand_path(__FILE__)), 'spec_helper') describe "Sequel::Schema::Generator dump methods" do before do @d = Sequel::Database.new @g = Sequel::Schema::Generator end it "should allow the same table information to be converted to a string for evaling inside of another instance with the same result" do g = @g.new(@d) do Integer :a varchar :b column :dt, DateTime column :vc, :varchar primary_key :c foreign_key :d, :a foreign_key :e foreign_key [:d, :e], :name=>:cfk constraint :blah, "a=1" check :a=>1 unique [:e] index :a index [:c, :e] index [:b, :c], :type=>:hash index [:d], :unique=>true spatial_index :a full_text_index [:b, :c] end g2 = @g.new(@d) do instance_eval(g.dump_columns, __FILE__, __LINE__) instance_eval(g.dump_constraints, __FILE__, __LINE__) instance_eval(g.dump_indexes, __FILE__, __LINE__) end g.columns.should == g2.columns g.constraints.should == g2.constraints g.indexes.should == g2.indexes end it "should allow dumping indexes as separate add_index and drop_index methods" do g = @g.new(@d) do index :a index [:c, :e], :name=>:blah index [:b, :c], :unique=>true end g.dump_indexes(:add_index=>:t).should == (<<END_CODE).strip add_index :t, [:a] add_index :t, [:c, :e], :name=>:blah add_index :t, [:b, :c], :unique=>true END_CODE g.dump_indexes(:drop_index=>:t).should == (<<END_CODE).strip drop_index :t, [:a] drop_index :t, [:c, :e], :name=>:blah drop_index :t, [:b, :c], :unique=>true END_CODE end it "should raise an error if you try to dump a Generator that uses a constraint with a proc" do proc{@g.new(@d){check{a>1}}.dump_constraints}.should raise_error(Sequel::Error) end end describe "Sequel::Database dump methods" do before do @d = Sequel::Database.new @d.meta_def(:tables){|o| [:t1, :t2]} @d.meta_def(:schema) do |t, *o| case t when :t1, 't__t1', :t__t1.identifier [[:c1, {:db_type=>'integer', :primary_key=>true, :allow_null=>false}], [:c2, {:db_type=>'varchar(20)', :allow_null=>true}]] when :t2 [[:c1, {:db_type=>'integer', :primary_key=>true, :allow_null=>false}], [:c2, {:db_type=>'numeric', :primary_key=>true, :allow_null=>false}]] when :t5 [[:c1, {:db_type=>'blahblah', :allow_null=>true}]] end end end it "should support dumping table schemas as create_table method calls" do @d.dump_table_schema(:t1).should == "create_table(:t1) do\n primary_key :c1\n String :c2, :size=>20\nend" end it "should support dumping table schemas when given a string" do @d.dump_table_schema('t__t1').should == "create_table(\"t__t1\") do\n primary_key :c1\n String :c2, :size=>20\nend" end it "should support dumping table schemas when given an identifier" do @d.dump_table_schema(:t__t1.identifier).should == "create_table(\"t__t1\") do\n primary_key :c1\n String :c2, :size=>20\nend" end it "should dump non-Integer primary key columns with explicit :type" do @d.meta_def(:schema){|*s| [[:c1, {:db_type=>'bigint', :primary_key=>true, :allow_null=>true}]]} @d.dump_table_schema(:t6).should == "create_table(:t6) do\n primary_key :c1, :type=>Bignum\nend" end it "should handle foreign keys" do @d.meta_def(:schema){|*s| [[:c1, {:db_type=>'integer', :allow_null=>true}]]} @d.meta_def(:foreign_key_list){|*s| [{:columns=>[:c1], :table=>:t2, :key=>[:c2]}]} @d.dump_table_schema(:t6).should == "create_table(:t6) do\n foreign_key :c1, :t2, :key=>[:c2]\nend" end it "should handle primary keys that are also foreign keys" do @d.meta_def(:schema){|*s| [[:c1, {:db_type=>'integer', :primary_key=>true, :allow_null=>true}]]} @d.meta_def(:foreign_key_list){|*s| [{:columns=>[:c1], :table=>:t2, :key=>[:c2]}]} s = @d.dump_table_schema(:t6) s.should =~ /create_table\(:t6\) do\n primary_key :c1, / s.should =~ /:table=>:t2/ s.should =~ /:key=>\[:c2\]/ end it "should handle foreign key options" do @d.meta_def(:schema){|*s| [[:c1, {:db_type=>'integer', :allow_null=>true}]]} @d.meta_def(:foreign_key_list){|*s| [{:columns=>[:c1], :table=>:t2, :key=>[:c2], :on_delete=>:restrict, :on_update=>:set_null, :deferrable=>true}]} s = @d.dump_table_schema(:t6) s.should =~ /create_table\(:t6\) do\n foreign_key :c1, :t2, / s.should =~ /:key=>\[:c2\]/ s.should =~ /:on_delete=>:restrict/ s.should =~ /:on_update=>:set_null/ s.should =~ /:deferrable=>true/ end it "should handle foreign key options in the primary key" do @d.meta_def(:schema){|*s| [[:c1, {:db_type=>'integer', :primary_key=>true, :allow_null=>true}]]} @d.meta_def(:foreign_key_list){|*s| [{:columns=>[:c1], :table=>:t2, :key=>[:c2], :on_delete=>:restrict, :on_update=>:set_null, :deferrable=>true}]} s = @d.dump_table_schema(:t6) s.should =~ /create_table\(:t6\) do\n primary_key :c1, / s.should =~ /:table=>:t2/ s.should =~ /:key=>\[:c2\]/ s.should =~ /:on_delete=>:restrict/ s.should =~ /:on_update=>:set_null/ s.should =~ /:deferrable=>true/ end it "should omit foreign key options that are the same as defaults" do @d.meta_def(:schema){|*s| [[:c1, {:db_type=>'integer', :allow_null=>true}]]} @d.meta_def(:foreign_key_list){|*s| [{:columns=>[:c1], :table=>:t2, :key=>[:c2], :on_delete=>:no_action, :on_update=>:no_action, :deferrable=>false}]} s = @d.dump_table_schema(:t6) s.should =~ /create_table\(:t6\) do\n foreign_key :c1, :t2, / s.should =~ /:key=>\[:c2\]/ s.should_not =~ /:on_delete/ s.should_not =~ /:on_update/ s.should_not =~ /:deferrable/ end it "should omit foreign key options that are the same as defaults in the primary key" do @d.meta_def(:schema){|*s| [[:c1, {:db_type=>'integer', :primary_key=>true, :allow_null=>true}]]} @d.meta_def(:foreign_key_list){|*s| [{:columns=>[:c1], :table=>:t2, :key=>[:c2], :on_delete=>:no_action, :on_update=>:no_action, :deferrable=>false}]} s = @d.dump_table_schema(:t6) s.should =~ /create_table\(:t6\) do\n primary_key :c1, / s.should =~ /:table=>:t2/ s.should =~ /:key=>\[:c2\]/ s.should_not =~ /:on_delete/ s.should_not =~ /:on_update/ s.should_not =~ /:deferrable/ end it "should dump primary key columns with explicit :type equal to the database type when :same_db option is passed" do @d.meta_def(:schema){|*s| [[:c1, {:db_type=>'somedbspecifictype', :primary_key=>true, :allow_null=>false}]]} @d.dump_table_schema(:t7, :same_db => true).should == "create_table(:t7) do\n primary_key :c1, :type=>\"somedbspecifictype\"\nend" end it "should use a composite primary_key calls if there is a composite primary key" do @d.dump_table_schema(:t2).should == "create_table(:t2) do\n Integer :c1, :null=>false\n BigDecimal :c2, :null=>false\n \n primary_key [:c1, :c2]\nend" end it "should use a composite foreign_key calls if there is a composite foreign key" do @d.meta_def(:schema){|*s| [[:c1, {:db_type=>'integer'}], [:c2, {:db_type=>'integer'}]]} @d.meta_def(:foreign_key_list){|*s| [{:columns=>[:c1, :c2], :table=>:t2, :key=>[:c3, :c4]}]} @d.dump_table_schema(:t1).should == "create_table(:t1) do\n Integer :c1\n Integer :c2\n \n foreign_key [:c1, :c2], :t2, :key=>[:c3, :c4]\nend" end it "should include index information if available" do @d.meta_def(:indexes) do |t| {:i1=>{:columns=>[:c1], :unique=>false}, :t1_c2_c1_index=>{:columns=>[:c2, :c1], :unique=>true}} end @d.dump_table_schema(:t1).should == "create_table(:t1, :ignore_index_errors=>true) do\n primary_key :c1\n String :c2, :size=>20\n \n index [:c1], :name=>:i1\n index [:c2, :c1], :unique=>true\nend" end it "should support dumping the whole database as a migration" do @d.dump_schema_migration.should == <<-END_MIG Sequel.migration do up do create_table(:t1) do primary_key :c1 String :c2, :size=>20 end create_table(:t2) do Integer :c1, :null=>false BigDecimal :c2, :null=>false primary_key [:c1, :c2] end end down do drop_table(:t2, :t1) end end END_MIG end it "should sort table names when dumping a migration" do @d.meta_def(:tables){|o| [:t2, :t1]} @d.dump_schema_migration.should == <<-END_MIG Sequel.migration do up do create_table(:t1) do primary_key :c1 String :c2, :size=>20 end create_table(:t2) do Integer :c1, :null=>false BigDecimal :c2, :null=>false primary_key [:c1, :c2] end end down do drop_table(:t2, :t1) end end END_MIG end it "should sort table names topologically when dumping a migration with foreign keys" do @d.meta_def(:tables){|o| [:t1, :t2]} @d.meta_def(:schema) do |t| t == :t1 ? [[:c2, {:db_type=>'integer'}]] : [[:c1, {:db_type=>'integer', :primary_key=>true}]] end @d.meta_def(:foreign_key_list) do |t| t == :t1 ? [{:columns=>[:c2], :table=>:t2, :key=>[:c1]}] : [] end @d.dump_schema_migration.should == <<-END_MIG Sequel.migration do up do create_table(:t2) do primary_key :c1 end create_table(:t1) do foreign_key :c2, :t2, :key=>[:c1] end end down do drop_table(:t1, :t2) end end END_MIG end it "should handle circular dependencies when dumping a migration with foreign keys" do @d.meta_def(:tables){|o| [:t1, :t2]} @d.meta_def(:schema) do |t| t == :t1 ? [[:c2, {:db_type=>'integer'}]] : [[:c1, {:db_type=>'integer'}]] end @d.meta_def(:foreign_key_list) do |t| t == :t1 ? [{:columns=>[:c2], :table=>:t2, :key=>[:c1]}] : [{:columns=>[:c1], :table=>:t1, :key=>[:c2]}] end @d.dump_schema_migration.should == <<-END_MIG Sequel.migration do up do create_table(:t1) do Integer :c2 end create_table(:t2) do foreign_key :c1, :t1, :key=>[:c2] end alter_table(:t1) do add_foreign_key [:c2], :t2, :key=>[:c1] end end down do drop_table(:t2, :t1) end end END_MIG end it "should sort topologically even if the database raises an error when trying to parse foreign keys for a non-existent table" do @d.meta_def(:tables){|o| [:t1, :t2]} @d.meta_def(:schema) do |t| t == :t1 ? [[:c2, {:db_type=>'integer'}]] : [[:c1, {:db_type=>'integer', :primary_key=>true}]] end @d.meta_def(:foreign_key_list) do |t| raise Sequel::DatabaseError unless [:t1, :t2].include?(t) t == :t1 ? [{:columns=>[:c2], :table=>:t2, :key=>[:c1]}] : [] end @d.dump_schema_migration.should == <<-END_MIG Sequel.migration do up do create_table(:t2) do primary_key :c1 end create_table(:t1) do foreign_key :c2, :t2, :key=>[:c1] end end down do drop_table(:t1, :t2) end end END_MIG end it "should honor the :same_db option to not convert types" do @d.dump_table_schema(:t1, :same_db=>true).should == "create_table(:t1) do\n primary_key :c1\n column :c2, \"varchar(20)\"\nend" @d.dump_schema_migration(:same_db=>true).should == <<-END_MIG Sequel.migration do up do create_table(:t1) do primary_key :c1 column :c2, "varchar(20)" end create_table(:t2) do column :c1, "integer", :null=>false column :c2, "numeric", :null=>false primary_key [:c1, :c2] end end down do drop_table(:t2, :t1) end end END_MIG end it "should honor the :index_names => false option to not include names of indexes" do @d.meta_def(:indexes) do |t| {:i1=>{:columns=>[:c1], :unique=>false}, :t1_c2_c1_index=>{:columns=>[:c2, :c1], :unique=>true}} end @d.dump_table_schema(:t1, :index_names=>false).should == "create_table(:t1, :ignore_index_errors=>true) do\n primary_key :c1\n String :c2, :size=>20\n \n index [:c1]\n index [:c2, :c1], :unique=>true\nend" @d.dump_schema_migration(:index_names=>false).should == <<-END_MIG Sequel.migration do up do create_table(:t1, :ignore_index_errors=>true) do primary_key :c1 String :c2, :size=>20 index [:c1] index [:c2, :c1], :unique=>true end create_table(:t2, :ignore_index_errors=>true) do Integer :c1, :null=>false BigDecimal :c2, :null=>false primary_key [:c1, :c2] index [:c1] index [:c2, :c1], :unique=>true end end down do drop_table(:t2, :t1) end end END_MIG end it "should honor the :index_names => :namespace option to include names of indexes with prepended table name" do @d.meta_def(:indexes) do |t| {:i1=>{:columns=>[:c1], :unique=>false}, :t1_c2_c1_index=>{:columns=>[:c2, :c1], :unique=>true}} end @d.dump_table_schema(:t1, :index_names=>:namespace).should == "create_table(:t1, :ignore_index_errors=>true) do\n primary_key :c1\n String :c2, :size=>20\n \n index [:c1], :name=>:t1_i1\n index [:c2, :c1], :unique=>true\nend" @d.dump_schema_migration(:index_names=>:namespace).should == <<-END_MIG Sequel.migration do up do create_table(:t1, :ignore_index_errors=>true) do primary_key :c1 String :c2, :size=>20 index [:c1], :name=>:t1_i1 index [:c2, :c1], :unique=>true end create_table(:t2, :ignore_index_errors=>true) do Integer :c1, :null=>false BigDecimal :c2, :null=>false primary_key [:c1, :c2] index [:c1], :name=>:t2_i1 index [:c2, :c1], :name=>:t2_t1_c2_c1_index, :unique=>true end end down do drop_table(:t2, :t1) end end END_MIG end it "should honor the :indexes => false option to not include indexes" do @d.meta_def(:indexes) do |t| {:i1=>{:columns=>[:c1], :unique=>false}, :t1_c2_c1_index=>{:columns=>[:c2, :c1], :unique=>true}} end @d.dump_table_schema(:t1, :indexes=>false).should == "create_table(:t1) do\n primary_key :c1\n String :c2, :size=>20\nend" @d.dump_schema_migration(:indexes=>false).should == <<-END_MIG Sequel.migration do up do create_table(:t1) do primary_key :c1 String :c2, :size=>20 end create_table(:t2) do Integer :c1, :null=>false BigDecimal :c2, :null=>false primary_key [:c1, :c2] end end down do drop_table(:t2, :t1) end end END_MIG end it "should have :indexes => false option disable foreign keys as well when dumping a whole migration" do @d.meta_def(:foreign_key_list) do |t| t == :t1 ? [{:columns=>[:c2], :table=>:t2, :key=>[:c1]}] : [] end @d.dump_schema_migration(:indexes=>false).should_not =~ /foreign_key/ end it "should have :foreign_keys option override :indexes => false disabling of foreign keys" do @d.meta_def(:foreign_key_list) do |t| t == :t1 ? [{:columns=>[:c2], :table=>:t2, :key=>[:c1]}] : [] end @d.dump_schema_migration(:indexes=>false, :foreign_keys=>true).should =~ /foreign_key/ end it "should support dumping just indexes as a migration" do @d.meta_def(:tables){|o| [:t1]} @d.meta_def(:indexes) do |t| {:i1=>{:columns=>[:c1], :unique=>false}, :t1_c2_c1_index=>{:columns=>[:c2, :c1], :unique=>true}} end @d.dump_indexes_migration.should == <<-END_MIG Sequel.migration do up do add_index :t1, [:c1], :ignore_errors=>true, :name=>:i1 add_index :t1, [:c2, :c1], :ignore_errors=>true, :unique=>true end down do drop_index :t1, [:c1], :ignore_errors=>true, :name=>:i1 drop_index :t1, [:c2, :c1], :ignore_errors=>true, :unique=>true end end END_MIG end it "should honor the :index_names => false option to not include names of indexes when dumping just indexes as a migration" do @d.meta_def(:tables){|o| [:t1]} @d.meta_def(:indexes) do |t| {:i1=>{:columns=>[:c1], :unique=>false}, :t1_c2_c1_index=>{:columns=>[:c2, :c1], :unique=>true}} end @d.dump_indexes_migration(:index_names=>false).should == <<-END_MIG Sequel.migration do up do add_index :t1, [:c1], :ignore_errors=>true add_index :t1, [:c2, :c1], :ignore_errors=>true, :unique=>true end down do drop_index :t1, [:c1], :ignore_errors=>true drop_index :t1, [:c2, :c1], :ignore_errors=>true, :unique=>true end end END_MIG end it "should honor the :index_names => :namespace option to include names of indexes with prepended table name when dumping just indexes as a migration" do @d.meta_def(:tables){|o| [:t1, :t2]} @d.meta_def(:indexes) do |t| {:i1=>{:columns=>[:c1], :unique=>false}, :t1_c2_c1_index=>{:columns=>[:c2, :c1], :unique=>true}} end @d.dump_indexes_migration(:index_names=>:namespace).should == <<-END_MIG Sequel.migration do up do add_index :t1, [:c1], :ignore_errors=>true, :name=>:t1_i1 add_index :t1, [:c2, :c1], :ignore_errors=>true, :unique=>true add_index :t2, [:c1], :ignore_errors=>true, :name=>:t2_i1 add_index :t2, [:c2, :c1], :ignore_errors=>true, :name=>:t2_t1_c2_c1_index, :unique=>true end down do drop_index :t2, [:c1], :ignore_errors=>true, :name=>:t2_i1 drop_index :t2, [:c2, :c1], :ignore_errors=>true, :name=>:t2_t1_c2_c1_index, :unique=>true drop_index :t1, [:c1], :ignore_errors=>true, :name=>:t1_i1 drop_index :t1, [:c2, :c1], :ignore_errors=>true, :unique=>true end end END_MIG end it "should handle missing index parsing support when dumping index migration" do @d.meta_def(:tables){|o| [:t1]} @d.dump_indexes_migration.should == <<-END_MIG Sequel.migration do up do end down do end end END_MIG end it "should handle missing foreign key parsing support when dumping foreign key migration" do @d.meta_def(:tables){|o| [:t1]} @d.dump_foreign_key_migration.should == <<-END_MIG Sequel.migration do up do end end END_MIG end it "should support dumping just foreign_keys as a migration" do @d.meta_def(:tables){|o| [:t1, :t2, :t3]} @d.meta_def(:schema) do |t| t == :t1 ? [[:c2, {:db_type=>'integer'}]] : [[:c1, {:db_type=>'integer'}]] end @d.meta_def(:foreign_key_list) do |t, *a| case t when :t1 [{:columns=>[:c2], :table=>:t2, :key=>[:c1]}] when :t2 [{:columns=>[:c1, :c3], :table=>:t1, :key=>[:c2, :c4]}] else [] end end @d.dump_foreign_key_migration.should == <<-END_MIG Sequel.migration do up do alter_table(:t1) do add_foreign_key [:c2], :t2, :key=>[:c1] end alter_table(:t2) do add_foreign_key [:c1, :c3], :t1, :key=>[:c2, :c4] end end end END_MIG end it "should handle not null values and defaults" do @d.meta_def(:schema){|*s| [[:c1, {:db_type=>'date', :default=>"'now()'", :allow_null=>true}], [:c2, {:db_type=>'datetime', :allow_null=>false}]]} @d.dump_table_schema(:t3).should == "create_table(:t3) do\n Date :c1\n DateTime :c2, :null=>false\nend" end it "should handle converting common defaults" do @d.meta_def(:schema) do |t, *os| s = [[:c1, {:db_type=>'boolean', :default=>"false", :type=>:boolean, :allow_null=>true}], [:c2, {:db_type=>'varchar', :default=>"'blah'", :type=>:string, :allow_null=>true}], [:c3, {:db_type=>'integer', :default=>"-1", :type=>:integer, :allow_null=>true}], [:c4, {:db_type=>'float', :default=>"1.0", :type=>:float, :allow_null=>true}], [:c5, {:db_type=>'decimal', :default=>"100.50", :type=>:decimal, :allow_null=>true}], [:c6, {:db_type=>'blob', :default=>"'blah'", :type=>:blob, :allow_null=>true}], [:c7, {:db_type=>'date', :default=>"'2008-10-29'", :type=>:date, :allow_null=>true}], [:c8, {:db_type=>'datetime', :default=>"'2008-10-29 10:20:30'", :type=>:datetime, :allow_null=>true}], [:c9, {:db_type=>'time', :default=>"'10:20:30'", :type=>:time, :allow_null=>true}], [:c10, {:db_type=>'interval', :default=>"'6 weeks'", :type=>:interval, :allow_null=>true}]] s.each{|_, c| c[:ruby_default] = column_schema_to_ruby_default(c[:default], c[:type])} s end @d.dump_table_schema(:t4).gsub(/[+-]\d\d:\d\d"\)/, '")').should == "create_table(:t4) do\n TrueClass :c1, :default=>false\n String :c2, :default=>\"blah\"\n Integer :c3, :default=>-1\n Float :c4, :default=>1.0\n BigDecimal :c5, :default=>BigDecimal.new(\"0.1005E3\")\n File :c6, :default=>Sequel::SQL::Blob.new(\"blah\")\n Date :c7, :default=>Date.parse(\"2008-10-29\")\n DateTime :c8, :default=>DateTime.parse(\"2008-10-29T10:20:30\")\n Time :c9, :default=>Sequel::SQLTime.parse(\"10:20:30\"), :only_time=>true\n String :c10\nend" @d.dump_table_schema(:t4, :same_db=>true).gsub(/[+-]\d\d:\d\d"\)/, '")').should == "create_table(:t4) do\n column :c1, \"boolean\", :default=>false\n column :c2, \"varchar\", :default=>\"blah\"\n column :c3, \"integer\", :default=>-1\n column :c4, \"float\", :default=>1.0\n column :c5, \"decimal\", :default=>BigDecimal.new(\"0.1005E3\")\n column :c6, \"blob\", :default=>Sequel::SQL::Blob.new(\"blah\")\n column :c7, \"date\", :default=>Date.parse(\"2008-10-29\")\n column :c8, \"datetime\", :default=>DateTime.parse(\"2008-10-29T10:20:30\")\n column :c9, \"time\", :default=>Sequel::SQLTime.parse(\"10:20:30\")\n column :c10, \"interval\", :default=>\"'6 weeks'\".lit\nend" end it "should not use a '...'.lit as a fallback if using MySQL with the :same_db option" do @d.meta_def(:database_type){:mysql} @d.meta_def(:schema) do |t, *os| s = [[:c10, {:db_type=>'interval', :default=>"'6 weeks'", :type=>:interval, :allow_null=>true}]] s.each{|_, c| c[:ruby_default] = column_schema_to_ruby_default(c[:default], c[:type])} s end @d.dump_table_schema(:t5, :same_db=>true).should == "create_table(:t5) do\n column :c10, \"interval\"\nend" end it "should convert unknown database types to strings" do @d.dump_table_schema(:t5).should == "create_table(:t5) do\n String :c1\nend" end it "should convert many database types to ruby types" do types = %w"mediumint smallint int integer mediumint(6) smallint(7) int(8) integer(9) tinyint tinyint(2) bigint bigint(20) real float double boolean tinytext mediumtext longtext text clob date datetime timestamp time char character varchar varchar(255) varchar(30) bpchar string money decimal decimal(10,2) numeric numeric(15,3) number bytea tinyblob mediumblob longblob blob varbinary varbinary(10) binary binary(20) year" + ["double precision", "timestamp with time zone", "timestamp without time zone", "time with time zone", "time without time zone", "character varying(20)"] + %w"nvarchar ntext smalldatetime smallmoney binary varbinary nchar" + ["timestamp(6) without time zone", "timestamp(6) with time zone", "int(12) unsigned", 'bigint unsigned', 'tinyint(3) unsigned', 'identity', 'int identity'] @d.meta_def(:schema) do |t, *o| i = 0 types.map{|x| [:"c#{i+=1}", {:db_type=>x, :allow_null=>true}]} end @d.dump_table_schema(:x).should == (<<END_MIG).chomp create_table(:x) do Integer :c1 Integer :c2 Integer :c3 Integer :c4 Integer :c5 Integer :c6 Integer :c7 Integer :c8 Integer :c9 Integer :c10 Bignum :c11 Bignum :c12 Float :c13 Float :c14 Float :c15 TrueClass :c16 String :c17, :text=>true String :c18, :text=>true String :c19, :text=>true String :c20, :text=>true String :c21, :text=>true Date :c22 DateTime :c23 DateTime :c24 Time :c25, :only_time=>true String :c26, :fixed=>true String :c27, :fixed=>true String :c28 String :c29, :size=>255 String :c30, :size=>30 String :c31 String :c32 BigDecimal :c33, :size=>[19, 2] BigDecimal :c34 BigDecimal :c35, :size=>[10, 2] BigDecimal :c36 BigDecimal :c37, :size=>[15, 3] BigDecimal :c38 File :c39 File :c40 File :c41 File :c42 File :c43 File :c44 File :c45, :size=>10 File :c46 File :c47, :size=>20 Integer :c48 Float :c49 DateTime :c50 DateTime :c51 Time :c52, :only_time=>true Time :c53, :only_time=>true String :c54, :size=>20 String :c55 String :c56, :text=>true DateTime :c57 BigDecimal :c58, :size=>[19, 2] File :c59 File :c60 String :c61, :fixed=>true DateTime :c62, :size=>6 DateTime :c63, :size=>6 Integer :c64 Bignum :c65 Integer :c66 Integer :c67 Integer :c68 end END_MIG end end
require 'rails_helper' describe 'Authentication' do subject { page } before(:all) { OmniAuth.config.test_mode = true } context 'sign in' do let(:company) { FactoryGirl::create(:company) } before do OmniAuth.config.add_mock(:stackexhange, credentials: { oauth_token: 123, refresh_token: 321, oauth_expires_at: Time.now + 1.day }) end context 'using stackexchange' do before do visit root_path click_on "Sign in StackExchange" end it 'should show log out button' do expect(subject).to have_content 'Log out' end end context 'company' do before do visit root_path click_on 'Sign in' end it 'should show log out button' do log_in(company.email, company.password) expect(subject).to have_content 'Log out' end it 'should show sign in button' do log_in(company.email, 'wrong_password') expect(subject).to have_content 'Log in' end end end def log_in(email, password) fill_in 'Email', with: email fill_in 'Password', with: password click_on 'Log in' end end Extending by sign up behavior. require 'rails_helper' describe 'Authentication' do subject { page } before(:all) { OmniAuth.config.test_mode = true } context 'sign in' do let(:company) { FactoryGirl::create(:company) } before do OmniAuth.config.add_mock(:stackexhange, credentials: { oauth_token: 123, refresh_token: 321, oauth_expires_at: Time.now + 1.day }) end context 'using stackexchange' do before do visit root_path click_on "Sign in StackExchange" end it 'should show log out button' do expect(subject).to have_content 'Log out' end end context 'company' do before do visit root_path click_on 'Sign in' end it 'should show log out button' do log_in(company.email, company.password) expect(subject).to have_content 'Log out' end it 'should show sign in button' do log_in(company.email, 'wrong_password') expect(subject).to have_content 'Log in' end end end context 'sign up' do let(:company) { FactoryGirl::build(:company) } context 'the company' do before do visit root_path click_on 'Sign up' fill_in 'Email', with: company.email fill_in 'Password', with: company.password fill_in 'Password confirmation', with: company.password click_on 'Sign up' end it 'should have a new company with this email' do expect(Company.where(email: company.email)).not_to be_empty end end end def log_in(email, password) fill_in 'Email', with: email fill_in 'Password', with: password click_on 'Log in' end end
require 'rails_helper' def set_up_suite include Devise::TestHelpers, type: :feature Capybara.current_driver = :selenium page.current_window.resize_to(1920, 1080) stub_oauth_edit end def fill_out_course_creator_form fill_in 'Course title:', with: 'My course' fill_in 'Course term:', with: 'Spring 2016' fill_in 'Course school:', with: 'University of Oklahoma' find('input[placeholder="Start date (YYYY-MM-DD)"]').set(Date.new(2015, 1, 4)) find('input[placeholder="End date (YYYY-MM-DD)"]').set(Date.new(2015, 2, 1)) click_button 'Create my Course!' end def interact_with_clone_form fill_in 'Course term:', with: 'Spring 2016' fill_in 'Course description:', with: 'A new course' find('input[placeholder="Start date (YYYY-MM-DD)"]').set(course.start) find('input[placeholder="End date (YYYY-MM-DD)"]').set(course.end) within('.wizard__form') { click_button 'Save New Course' } within('.sidebar') { expect(page).to have_content(term) } within('.primary') { expect(page).to have_content(desc) } click_button 'Save This Course' end def go_through_course_dates_and_timeline_dates find('attr[title="Wednesday"]', match: :first).click within('.wizard__panel.active') do expect(page).to have_css('button.dark[disabled=""]') end find('.wizard__form.course-dates input[type=checkbox]', match: :first).set(true) within('.wizard__panel.active') do expect(page).not_to have_css('button.dark[disabled=disabled]') end click_button 'Next' sleep 1 end def go_through_researchwrite_wizard go_through_course_dates_and_timeline_dates # Advance past the timeline date panel click_button 'Next' sleep 1 # Choose researchwrite option find('.wizard__option', match: :first).find('button', match: :first).click click_button 'Next' sleep 1 # Click through the offered choices find('.wizard__option', match: :first).find('button', match: :first).click # Training not graded click_button 'Next' sleep 1 click_button 'Next' # Default getting started options sleep 1 # Instructor prepares list find('.wizard__option', match: :first).find('button', match: :first).click click_button 'Next' sleep 1 find('.wizard__option', match: :first).find('button', match: :first).click # Traditional outline click_button 'Next' sleep 1 find('.wizard__option', match: :first).find('button', match: :first).click # Yes, medical articles click_button 'Next' sleep 1 find('.wizard__option', match: :first).find('button', match: :first).click # Work live from start click_button 'Next' sleep 1 click_button 'Next' # Default 2 peer reviews sleep 1 click_button 'Next' # No supplementary assignments sleep 1 click_button 'Next' # No DYK/GA sleep 1 click_button 'Submit' sleep 1 end describe 'New course creation and editing', type: :feature do before do set_up_suite end before :each do user = create(:user, id: 1, permissions: User::Permissions::INSTRUCTOR) create(:training_modules_users, user_id: user.id, training_module_id: 3, completed_at: Time.now) login_as(user, scope: :user) visit root_path end describe 'course workflow', js: true do let(:expected_course_blocks) { 27 } let(:module_name) { 'Wikipedia Essentials' } it 'should allow the user to create a course' do click_link 'Create Course' expect(page).to have_content 'Create a New Course' find('#course_title').set('My awesome new course - Foo 101') # If we click before filling out all require fields, only the invalid # fields get restyled to indicate the problem. click_button 'Create my Course!' expect(find('#course_title')['class']).not_to include('invalid title') expect(find('#course_school')['class']).to include('invalid school') expect(find('#course_term')['class']).to include('invalid term') # Now we fill out all the fields and continue. find('#course_school').set('University of Wikipedia, East Campus') find('#course_term').set('Fall 2015') find('#course_subject').set('Advanced Studies') find('#course_expected_students').set('500') find('textarea').set('In this course, we study things.') # TODO: test the date picker instead of just setting fields start_date = '2015-01-01' end_date = '2015-12-15' find('input[placeholder="Start date (YYYY-MM-DD)"]').set(start_date) find('input[placeholder="End date (YYYY-MM-DD)"]').set(end_date) sleep 1 # This click should create the course and start the wizard click_button 'Create my Course!' # Go through the wizard, checking necessary options. # This is the course dates screen sleep 3 # validate either blackout date chosen # or "no blackout dates" checkbox checked expect(page).to have_css('button.dark[disabled=""]') start_input = find('input.start', match: :first).value expect(start_input).to eq(start_date) # capybara doesn't like trying to click the calendar # to set a blackout date go_through_course_dates_and_timeline_dates sleep 1 # This is the timeline datepicker find('input.timeline_start').set(start_date) find('input.timeline_end').set(end_date) click_button 'Next' sleep 1 # This is the assignment type chooser # pick and choose page.all('.wizard__option')[1].first('button').click sleep 1 click_button 'Next' sleep 1 # pick 2 types of assignments page.all('div.wizard__option__checkbox')[1].click page.all('div.wizard__option__checkbox')[3].click sleep 1 click_button 'Next' # on the summary sleep 1 # go back to the pick and choose and choose different assignments page.all('button.wizard__option.summary')[3].click sleep 1 page.all('div.wizard__option__checkbox')[3].click page.all('div.wizard__option__checkbox')[2].click page.all('div.wizard__option__checkbox')[4].click sleep 1 click_button 'Summary' sleep 1 click_button 'Submit' # Now we're back at the timeline, having completed the wizard. sleep 1 expect(page).to have_content 'Week 1' expect(page).to have_content 'Week 2' # Edit course dates and save click_link 'Edit Course Dates' find('attr[title="Thursday"]', match: :first).click sleep 1 expect(Course.last.weekdays).to eq('0001100') click_link 'Done' sleep 1 within('.week-1 .week__week-add-delete') do accept_confirm do find('.week__delete-week').click end end # There should now be 4 weeks expect(page).not_to have_content 'Week 5' # Click edit, mark a gradeable and save it. find('.week-1').hover sleep 0.5 within('.week-1') do find('.block__edit-block').click find('p.graded input[type=checkbox]').set(true) sleep 1 click_button 'Save' end sleep 1 # Edit the gradeable. within('.grading__grading-container') do click_button 'Edit' sleep 1 all('input').last.set('50') sleep 1 click_button 'Save' sleep 1 expect(page).to have_content 'Value: 50%' end # Navigate back to overview, check relevant data, then delete course visit "/courses/#{Course.first.slug}" within('.sidebar') do expect(page).to have_content I18n.t('courses.instructor.other') end accept_prompt(with: 'My awesome new course - Foo 101') do find('button.danger', match: :first).click end expect(page).to have_content 'Looks like you don\'t have any courses' end it 'should not allow a second course with the same slug' do create(:course, id: 10001, title: 'Course', school: 'University', term: 'Term', slug: 'University/Course_(Term)', submitted: 0, listed: true, passcode: 'passcode', start: '2015-08-24'.to_date, end: '2015-12-15'.to_date, timeline_start: '2015-08-31'.to_date, timeline_end: '2015-12-15'.to_date) click_link 'Create Course' expect(page).to have_content 'Create a New Course' find('#course_title').set('Course') find('#course_school').set('University') find('#course_term').set('Term') find('#course_subject').set('Advanced Studies') start_date = '2015-01-01' end_date = '2015-12-15' find('input[placeholder="Start date (YYYY-MM-DD)"]').set(start_date) find('input[placeholder="End date (YYYY-MM-DD)"]').set(end_date) sleep 1 # This click should not successfully create a course. find('button.dark').click expect(page).to have_content 'This course already exists' expect(Course.all.count).to eq(1) end it 'should create a full-length research-write assignment' do create(:course, id: 10001, title: 'Course', school: 'University', term: 'Term', slug: 'University/Course_(Term)', submitted: 0, listed: true, passcode: 'passcode', start: '2015-08-24'.to_date, end: '2015-12-15'.to_date, timeline_start: '2015-08-31'.to_date, timeline_end: '2015-12-15'.to_date) create(:courses_user, user_id: 1, course_id: 10001, role: 1) # Visit timline and open wizard visit "/courses/#{Course.first.slug}/timeline/wizard" sleep 1 go_through_researchwrite_wizard sleep 1 expect(page).to have_content 'Week 14' # Now submit the course first('a.button').click prompt = page.driver.browser.switch_to.alert prompt.accept expect(page).to have_content 'Your course has been submitted.' Course.last.weeks.each_with_index do |week, i| expect(week.order).to eq(i + 1) end expect(Course.first.blocks.count).to eq(expected_course_blocks) end it 'should squeeze assignments into the course dates' do create(:course, id: 10001, title: 'Course', school: 'University', term: 'Term', slug: 'University/Course_(Term)', submitted: 0, listed: true, passcode: 'passcode', start: '2015-09-01'.to_date, end: '2015-10-09'.to_date, timeline_start: '2015-08-31'.to_date, # covers six calendar weeks timeline_end: '2015-10-09'.to_date) create(:courses_user, user_id: 1, course_id: 10001, role: 1) # Visit timline and open wizard visit "/courses/#{Course.first.slug}/timeline/wizard" sleep 1 go_through_researchwrite_wizard expect(page).to have_content 'Week 6' expect(page).not_to have_content 'Week 7' expect(Course.first.blocks.count).to eq(expected_course_blocks) within ".week-1 .block-kind-#{Block::KINDS['assignment']}" do expect(page).to have_content module_name end end end describe 'returning instructor creating a new course', js: true do it 'should have the option of starting with no timeline' do pending 'fixing the intermittent failures on travis-ci' create(:course, id: 1) create(:courses_user, course_id: 1, user_id: 1, role: CoursesUsers::Roles::INSTRUCTOR_ROLE) click_link 'Create Course' click_button 'Create New Course' fill_out_course_creator_form sleep 1 go_through_course_dates_and_timeline_dates # Advance past the timeline date panel first('button.dark').click sleep 1 # Last option for returning instructor is 'build your own' find('button', text: 'Build your own timeline').click first('button.dark').click sleep 1 # Proceed to the summary first('button.dark').click # Next sleep 1 # Finish the wizard first('button.dark').click expect(page).to have_content 'Add Assignment' sleep 1 # Add a week within '.timeline__week-nav .panel' do find('.week-nav__add-week').click end sleep 1 within '.timeline__weeks' do expect(page).to have_content 'Week 1' within '.week-1' do find('.week__add-block').click find('input.title').set('block title') within('.block__block-actions') do click_button 'Save' end sleep 1 end end # is it still there after reloading? visit current_path expect(page).to have_content 'Week 1' expect(page).to have_content 'block title' # Add Assignment button should not appear once there is timeline content. expect(page).not_to have_content 'Add Assignment' puts 'PASSED' fail 'this test passed β€” this time' end end after do logout Capybara.use_default_driver end end describe 'timeline editing', js: true do let!(:course) do create(:course, id: 10001, start: Date.new(2015, 1, 1), end: Date.new(2015, 2, 1), submitted: true, timeline_start: Date.new(2015, 1, 1), timeline_end: Date.new(2015, 2, 1), weekdays: '0111110') end let!(:user) { create(:user, permissions: User::Permissions::ADMIN) } let!(:c_user) { create(:courses_user, course_id: course.id, user_id: user.id) } let!(:week) { create(:week, course_id: course.id, order: 0) } let!(:week2) { create(:week, course_id: course.id, order: 1) } let!(:block) { create(:block, week_id: week.id, kind: Block::KINDS['assignment'], order: 0, title: 'Block 1') } let!(:block2) { create(:block, week_id: week.id, kind: Block::KINDS['in_class'], order: 1, title: 'Block 2') } let!(:block3) { create(:block, week_id: week.id, kind: Block::KINDS['in_class'], order: 2, title: 'Block 3') } let!(:block4) { create(:block, week_id: week2.id, kind: Block::KINDS['in_class'], order: 0, title: 'Block 4') } let!(:block5) { create(:block, week_id: week2.id, kind: Block::KINDS['in_class'], order: 1, title: 'Block 5') } let!(:block6) { create(:block, week_id: week2.id, kind: Block::KINDS['in_class'], order: 3, title: 'Block 6') } before do set_up_suite login_as user, scope: :user, run_callbacks: false end it 'disables reorder up/down buttons when it is the first or last block' do visit "/courses/#{Course.last.slug}/timeline" click_button 'Arrange Timeline' expect(find('.week-1 .week__block-list > li:first-child button:first-of-type')['disabled']) .to eq(nil) expect(find('.week-1 .week__block-list > li:first-child button:last-of-type')['disabled']) .to eq('true') expect(find('.week-2 .week__block-list > li:last-child button:first-of-type')['disabled']) .to eq('true') expect(find('.week-2 .week__block-list > li:last-child button:last-of-type')['disabled']) .to eq(nil) end it 'allows swapping places with a block' do visit "/courses/#{Course.last.slug}/timeline" click_button 'Arrange Timeline' find('.week-1 .week__block-list > li:nth-child(1) button:first-of-type').click # move down sleep 0.5 find('.week-1 .week__block-list > li:nth-child(2) button:first-of-type').click # move down again sleep 0.5 expect(find('.week-1 .week__block-list > li:nth-child(1)')).to have_content('Block 2') expect(find('.week-1 .week__block-list > li:nth-child(2)')).to have_content('Block 3') expect(find('.week-1 .week__block-list > li:nth-child(3)')).to have_content('Block 1') find('.week-1 .week__block-list > li:nth-child(3) button:last-of-type').click # move up sleep 0.5 find('.week-1 .week__block-list > li:nth-child(2) button:last-of-type').click # move up again sleep 0.5 expect(find('.week-1 .week__block-list > li:nth-child(1)')).to have_content('Block 1') expect(find('.week-1 .week__block-list > li:nth-child(2)')).to have_content('Block 2') expect(find('.week-1 .week__block-list > li:nth-child(3)')).to have_content('Block 3') end it 'allows moving blocks between weeks' do visit "/courses/#{Course.last.slug}/timeline" click_button 'Arrange Timeline' # move up to week 1 find('.week-2 .week__block-list > li:nth-child(1) button:last-of-type').click sleep 0.5 expect(find('.week-1 .week__block-list > li:nth-child(4)')).to have_content 'Block 4' # move back down to week 2 find('.week-1 .week__block-list > li:nth-child(4) button:first-of-type').click sleep 0.5 expect(find('.week-2 .week__block-list > li:nth-child(1)')).to have_content 'Block 4' end it 'allows user to save and discard changes' do visit "/courses/#{Course.last.slug}/timeline" click_button 'Arrange Timeline' # move up to week 1 find('.week-2 .week__block-list > li:nth-child(1) button:last-of-type').click click_button 'Save All' expect(find('.week-1 .week__block-list > li:nth-child(4)')).to have_content 'Block 4' # move down to week 2 and discard Changes click_button 'Arrange Timeline' find('.week-1 .week__block-list > li:nth-child(4) button:first-of-type').click click_button 'Discard All Changes' # still in week 1 expect(find('.week-1 .week__block-list > li:nth-child(4)')).to have_content 'Block 4' end end describe 'cloning a course', js: true do before do set_up_suite end let!(:course) do create(:course, id: 10001, start: 1.year.from_now.to_date, end: 2.years.from_now.to_date, submitted: true) end let!(:week) { create(:week, course_id: course.id) } let!(:block) { create(:block, week_id: week.id, due_date: course.start + 3.months) } let!(:gradeable) do create(:gradeable, gradeable_item_type: 'block', gradeable_item_id: block.id, points: 10) end let!(:user) { create(:user, permissions: User::Permissions::ADMIN) } let!(:c_user) { create(:courses_user, course_id: course.id, user_id: user.id) } let!(:term) { 'Spring 2016' } let!(:desc) { 'A new course' } it 'copies relevant attributes of an existing course' do pending 'fixing the intermittent failures on travis-ci' login_as user, scope: :user, run_callbacks: false visit root_path click_link 'Create Course' click_button 'Clone Previous Course' select course.title, from: 'reuse-existing-course-select' click_button 'Clone This Course' expect(page).to have_content 'Course Successfully Cloned' # interact_with_clone_form # form not working right now visit "/courses/#{Course.last.slug}" course.reload new_course = Course.last expect(Week.count).to eq(2) # make sure the weeks are distinct expect(new_course.blocks.first.content).to eq(course.blocks.first.content) expect(new_course.blocks.first.due_date) .to be_nil expect(new_course.blocks.first.gradeable.points).to eq(gradeable.points) expect(new_course.blocks.first.gradeable.gradeable_item_id) .to eq(new_course.blocks.first.id) expect(new_course.instructors.first).to eq(user) expect(new_course.submitted).to eq(false) expect(new_course.user_count).to be_zero expect(new_course.article_count).to be_zero puts 'PASSED' fail 'this test passed β€” this time' end after do logout Capybara.use_default_driver end end Fix a broken feature spec require 'rails_helper' def set_up_suite include Devise::TestHelpers, type: :feature Capybara.current_driver = :selenium page.current_window.resize_to(1920, 1080) stub_oauth_edit end def fill_out_course_creator_form fill_in 'Course title:', with: 'My course' fill_in 'Course term:', with: 'Spring 2016' fill_in 'Course school:', with: 'University of Oklahoma' find('input[placeholder="Start date (YYYY-MM-DD)"]').set(Date.new(2015, 1, 4)) find('input[placeholder="End date (YYYY-MM-DD)"]').set(Date.new(2015, 2, 1)) click_button 'Create my Course!' end def interact_with_clone_form fill_in 'Course term:', with: 'Spring 2016' fill_in 'Course description:', with: 'A new course' find('input[placeholder="Start date (YYYY-MM-DD)"]').set(course.start) find('input[placeholder="End date (YYYY-MM-DD)"]').set(course.end) within('.wizard__form') { click_button 'Save New Course' } within('.sidebar') { expect(page).to have_content(term) } within('.primary') { expect(page).to have_content(desc) } click_button 'Save This Course' end def go_through_course_dates_and_timeline_dates find('attr[title="Wednesday"]', match: :first).click within('.wizard__panel.active') do expect(page).to have_css('button.dark[disabled=""]') end find('.wizard__form.course-dates input[type=checkbox]', match: :first).set(true) within('.wizard__panel.active') do expect(page).not_to have_css('button.dark[disabled=disabled]') end click_button 'Next' sleep 1 end def go_through_researchwrite_wizard go_through_course_dates_and_timeline_dates # Advance past the timeline date panel click_button 'Next' sleep 1 # Choose researchwrite option find('.wizard__option', match: :first).find('button', match: :first).click click_button 'Next' sleep 1 # Click through the offered choices find('.wizard__option', match: :first).find('button', match: :first).click # Training not graded click_button 'Next' sleep 1 click_button 'Next' # Default getting started options sleep 1 # Instructor prepares list find('.wizard__option', match: :first).find('button', match: :first).click click_button 'Next' sleep 1 find('.wizard__option', match: :first).find('button', match: :first).click # Traditional outline click_button 'Next' sleep 1 find('.wizard__option', match: :first).find('button', match: :first).click # Yes, medical articles click_button 'Next' sleep 1 find('.wizard__option', match: :first).find('button', match: :first).click # Work live from start click_button 'Next' sleep 1 click_button 'Next' # Default 2 peer reviews sleep 1 click_button 'Next' # No supplementary assignments sleep 1 click_button 'Next' # No DYK/GA sleep 1 click_button 'Submit' sleep 1 end describe 'New course creation and editing', type: :feature do before do set_up_suite end before :each do user = create(:user, id: 1, permissions: User::Permissions::INSTRUCTOR) create(:training_modules_users, user_id: user.id, training_module_id: 3, completed_at: Time.now) login_as(user, scope: :user) visit root_path end describe 'course workflow', js: true do let(:expected_course_blocks) { 27 } let(:module_name) { 'Wikipedia Essentials' } it 'should allow the user to create a course' do click_link 'Create Course' expect(page).to have_content 'Create a New Course' find('#course_title').set('My awesome new course - Foo 101') # If we click before filling out all require fields, only the invalid # fields get restyled to indicate the problem. click_button 'Create my Course!' expect(find('#course_title')['class']).not_to include('invalid title') expect(find('#course_school')['class']).to include('invalid school') expect(find('#course_term')['class']).to include('invalid term') # Now we fill out all the fields and continue. find('#course_school').set('University of Wikipedia, East Campus') find('#course_term').set('Fall 2015') find('#course_subject').set('Advanced Studies') find('#course_expected_students').set('500') find('textarea').set('In this course, we study things.') # TODO: test the date picker instead of just setting fields start_date = '2015-01-01' end_date = '2015-12-15' find('input[placeholder="Start date (YYYY-MM-DD)"]').set(start_date) find('input[placeholder="End date (YYYY-MM-DD)"]').set(end_date) sleep 1 # This click should create the course and start the wizard click_button 'Create my Course!' # Go through the wizard, checking necessary options. # This is the course dates screen sleep 3 # validate either blackout date chosen # or "no blackout dates" checkbox checked expect(page).to have_css('button.dark[disabled=""]') start_input = find('input.start', match: :first).value expect(start_input).to eq(start_date) # capybara doesn't like trying to click the calendar # to set a blackout date go_through_course_dates_and_timeline_dates sleep 1 # This is the timeline datepicker find('input.timeline_start').set(start_date) find('input.timeline_end').set(end_date) click_button 'Next' sleep 1 # This is the assignment type chooser # pick and choose page.all('.wizard__option')[1].first('button').click sleep 1 click_button 'Next' sleep 1 # pick 2 types of assignments page.all('div.wizard__option__checkbox')[1].click page.all('div.wizard__option__checkbox')[3].click sleep 1 click_button 'Next' # on the summary sleep 1 # go back to the pick and choose and choose different assignments page.all('button.wizard__option.summary')[3].click sleep 1 page.all('div.wizard__option__checkbox')[3].click page.all('div.wizard__option__checkbox')[2].click page.all('div.wizard__option__checkbox')[4].click sleep 1 click_button 'Summary' sleep 1 click_button 'Submit' # Now we're back at the timeline, having completed the wizard. sleep 1 expect(page).to have_content 'Week 1' expect(page).to have_content 'Week 2' # Edit course dates and save click_link 'Edit Course Dates' find('attr[title="Thursday"]', match: :first).click sleep 1 expect(Course.last.weekdays).to eq('0001100') click_link 'Done' sleep 1 within('.week-1 .week__week-add-delete') do accept_confirm do find('.week__delete-week').click end end # There should now be 4 weeks expect(page).not_to have_content 'Week 5' # Click edit, mark a gradeable and save it. find('.week-1').hover sleep 0.5 within('.week-1') do find('.block__edit-block').click find('p.graded input[type=checkbox]').set(true) sleep 1 click_button 'Save' end sleep 1 # Edit the gradeable. within('.grading__grading-container') do click_button 'Edit' sleep 1 all('input').last.set('50') sleep 1 click_button 'Save' sleep 1 expect(page).to have_content 'Value: 50%' end # Navigate back to overview, check relevant data, then delete course visit "/courses/#{Course.first.slug}" within('.sidebar') do expect(page).to have_content I18n.t('courses.instructor.other') end accept_prompt(with: 'My awesome new course - Foo 101') do find('button.danger', match: :first).click end expect(page).to have_content 'Looks like you don\'t have any courses' end it 'should not allow a second course with the same slug' do create(:course, id: 10001, title: 'Course', school: 'University', term: 'Term', slug: 'University/Course_(Term)', submitted: 0, listed: true, passcode: 'passcode', start: '2015-08-24'.to_date, end: '2015-12-15'.to_date, timeline_start: '2015-08-31'.to_date, timeline_end: '2015-12-15'.to_date) click_link 'Create Course' expect(page).to have_content 'Create a New Course' find('#course_title').set('Course') find('#course_school').set('University') find('#course_term').set('Term') find('#course_subject').set('Advanced Studies') start_date = '2015-01-01' end_date = '2015-12-15' find('input[placeholder="Start date (YYYY-MM-DD)"]').set(start_date) find('input[placeholder="End date (YYYY-MM-DD)"]').set(end_date) sleep 1 # This click should not successfully create a course. find('button.dark').click expect(page).to have_content 'This course already exists' expect(Course.all.count).to eq(1) end it 'should create a full-length research-write assignment' do create(:course, id: 10001, title: 'Course', school: 'University', term: 'Term', slug: 'University/Course_(Term)', submitted: 0, listed: true, passcode: 'passcode', start: '2015-08-24'.to_date, end: '2015-12-15'.to_date, timeline_start: '2015-08-31'.to_date, timeline_end: '2015-12-15'.to_date) create(:courses_user, user_id: 1, course_id: 10001, role: 1) # Visit timline and open wizard visit "/courses/#{Course.first.slug}/timeline/wizard" sleep 1 go_through_researchwrite_wizard sleep 1 expect(page).to have_content 'Week 14' # Now submit the course first('a.button').click prompt = page.driver.browser.switch_to.alert prompt.accept expect(page).to have_content 'Your course has been submitted.' Course.last.weeks.each_with_index do |week, i| expect(week.order).to eq(i + 1) end expect(Course.first.blocks.count).to eq(expected_course_blocks) end it 'should squeeze assignments into the course dates' do create(:course, id: 10001, title: 'Course', school: 'University', term: 'Term', slug: 'University/Course_(Term)', submitted: 0, listed: true, passcode: 'passcode', start: '2015-09-01'.to_date, end: '2015-10-09'.to_date, timeline_start: '2015-08-31'.to_date, # covers six calendar weeks timeline_end: '2015-10-09'.to_date) create(:courses_user, user_id: 1, course_id: 10001, role: 1) # Visit timline and open wizard visit "/courses/#{Course.first.slug}/timeline/wizard" sleep 1 go_through_researchwrite_wizard expect(page).to have_content 'Week 6' expect(page).not_to have_content 'Week 7' expect(Course.first.blocks.count).to eq(expected_course_blocks) within ".week-1 .block-kind-#{Block::KINDS['assignment']}" do expect(page).to have_content module_name end end end describe 'returning instructor creating a new course', js: true do it 'should have the option of starting with no timeline' do pending 'fixing the intermittent failures on travis-ci' create(:course, id: 1) create(:courses_user, course_id: 1, user_id: 1, role: CoursesUsers::Roles::INSTRUCTOR_ROLE) click_link 'Create Course' click_button 'Create New Course' fill_out_course_creator_form sleep 1 go_through_course_dates_and_timeline_dates # Advance past the timeline date panel click_button 'Next' sleep 1 # Last option for returning instructor is 'build your own' find('button', text: 'Build your own timeline').click click_button 'Next' sleep 1 # Proceed to the summary click_button 'Next' sleep 1 # Finish the wizard click_button 'Submit' expect(page).to have_content 'Add Assignment' sleep 1 # Add a week within '.timeline__week-nav .panel' do find('.week-nav__add-week').click end sleep 1 within '.timeline__weeks' do expect(page).to have_content 'Week 1' within '.week-1' do find('.week__add-block').click find('input.title').set('block title') within('.block__block-actions') do click_button 'Save' end sleep 1 end end # is it still there after reloading? visit current_path expect(page).to have_content 'Week 1' expect(page).to have_content 'block title' # Add Assignment button should not appear once there is timeline content. expect(page).not_to have_content 'Add Assignment' puts 'PASSED' raise 'this test passed β€” this time' end end after do logout Capybara.use_default_driver end end describe 'timeline editing', js: true do let!(:course) do create(:course, id: 10001, start: Date.new(2015, 1, 1), end: Date.new(2015, 2, 1), submitted: true, timeline_start: Date.new(2015, 1, 1), timeline_end: Date.new(2015, 2, 1), weekdays: '0111110') end let!(:user) { create(:user, permissions: User::Permissions::ADMIN) } let!(:c_user) { create(:courses_user, course_id: course.id, user_id: user.id) } let!(:week) { create(:week, course_id: course.id, order: 0) } let!(:week2) { create(:week, course_id: course.id, order: 1) } let!(:block) { create(:block, week_id: week.id, kind: Block::KINDS['assignment'], order: 0, title: 'Block 1') } let!(:block2) { create(:block, week_id: week.id, kind: Block::KINDS['in_class'], order: 1, title: 'Block 2') } let!(:block3) { create(:block, week_id: week.id, kind: Block::KINDS['in_class'], order: 2, title: 'Block 3') } let!(:block4) { create(:block, week_id: week2.id, kind: Block::KINDS['in_class'], order: 0, title: 'Block 4') } let!(:block5) { create(:block, week_id: week2.id, kind: Block::KINDS['in_class'], order: 1, title: 'Block 5') } let!(:block6) { create(:block, week_id: week2.id, kind: Block::KINDS['in_class'], order: 3, title: 'Block 6') } before do set_up_suite login_as user, scope: :user, run_callbacks: false end it 'disables reorder up/down buttons when it is the first or last block' do visit "/courses/#{Course.last.slug}/timeline" click_button 'Arrange Timeline' expect(find('.week-1 .week__block-list > li:first-child button:first-of-type')['disabled']) .to eq(nil) expect(find('.week-1 .week__block-list > li:first-child button:last-of-type')['disabled']) .to eq('true') expect(find('.week-2 .week__block-list > li:last-child button:first-of-type')['disabled']) .to eq('true') expect(find('.week-2 .week__block-list > li:last-child button:last-of-type')['disabled']) .to eq(nil) end it 'allows swapping places with a block' do visit "/courses/#{Course.last.slug}/timeline" click_button 'Arrange Timeline' find('.week-1 .week__block-list > li:nth-child(1) button:first-of-type').click # move down sleep 0.5 find('.week-1 .week__block-list > li:nth-child(2) button:first-of-type').click # move down again sleep 0.5 expect(find('.week-1 .week__block-list > li:nth-child(1)')).to have_content('Block 2') expect(find('.week-1 .week__block-list > li:nth-child(2)')).to have_content('Block 3') expect(find('.week-1 .week__block-list > li:nth-child(3)')).to have_content('Block 1') find('.week-1 .week__block-list > li:nth-child(3) button:last-of-type').click # move up sleep 0.5 find('.week-1 .week__block-list > li:nth-child(2) button:last-of-type').click # move up again sleep 0.5 expect(find('.week-1 .week__block-list > li:nth-child(1)')).to have_content('Block 1') expect(find('.week-1 .week__block-list > li:nth-child(2)')).to have_content('Block 2') expect(find('.week-1 .week__block-list > li:nth-child(3)')).to have_content('Block 3') end it 'allows moving blocks between weeks' do visit "/courses/#{Course.last.slug}/timeline" click_button 'Arrange Timeline' # move up to week 1 find('.week-2 .week__block-list > li:nth-child(1) button:last-of-type').click sleep 0.5 expect(find('.week-1 .week__block-list > li:nth-child(4)')).to have_content 'Block 4' # move back down to week 2 find('.week-1 .week__block-list > li:nth-child(4) button:first-of-type').click sleep 0.5 expect(find('.week-2 .week__block-list > li:nth-child(1)')).to have_content 'Block 4' end it 'allows user to save and discard changes' do visit "/courses/#{Course.last.slug}/timeline" click_button 'Arrange Timeline' # move up to week 1 find('.week-2 .week__block-list > li:nth-child(1) button:last-of-type').click click_button 'Save All' expect(find('.week-1 .week__block-list > li:nth-child(4)')).to have_content 'Block 4' # move down to week 2 and discard Changes click_button 'Arrange Timeline' find('.week-1 .week__block-list > li:nth-child(4) button:first-of-type').click click_button 'Discard All Changes' # still in week 1 expect(find('.week-1 .week__block-list > li:nth-child(4)')).to have_content 'Block 4' end end describe 'cloning a course', js: true do before do set_up_suite end let!(:course) do create(:course, id: 10001, start: 1.year.from_now.to_date, end: 2.years.from_now.to_date, submitted: true) end let!(:week) { create(:week, course_id: course.id) } let!(:block) { create(:block, week_id: week.id, due_date: course.start + 3.months) } let!(:gradeable) do create(:gradeable, gradeable_item_type: 'block', gradeable_item_id: block.id, points: 10) end let!(:user) { create(:user, permissions: User::Permissions::ADMIN) } let!(:c_user) { create(:courses_user, course_id: course.id, user_id: user.id) } let!(:term) { 'Spring 2016' } let!(:desc) { 'A new course' } it 'copies relevant attributes of an existing course' do pending 'fixing the intermittent failures on travis-ci' login_as user, scope: :user, run_callbacks: false visit root_path click_link 'Create Course' click_button 'Clone Previous Course' select course.title, from: 'reuse-existing-course-select' click_button 'Clone This Course' expect(page).to have_content 'Course Successfully Cloned' # interact_with_clone_form # form not working right now visit "/courses/#{Course.last.slug}" course.reload new_course = Course.last expect(Week.count).to eq(2) # make sure the weeks are distinct expect(new_course.blocks.first.content).to eq(course.blocks.first.content) expect(new_course.blocks.first.due_date) .to be_nil expect(new_course.blocks.first.gradeable.points).to eq(gradeable.points) expect(new_course.blocks.first.gradeable.gradeable_item_id) .to eq(new_course.blocks.first.id) expect(new_course.instructors.first).to eq(user) expect(new_course.submitted).to eq(false) expect(new_course.user_count).to be_zero expect(new_course.article_count).to be_zero puts 'PASSED' fail 'this test passed β€” this time' end after do logout Capybara.use_default_driver end end
require "spec_helper" RSpec.feature "Example Feature Spec" do scenario "When using Rack Test, it works" do visit "/users" expect(page).to have_text("Log in with your Rails Portal (development) account.") end scenario "When using Chrome, it works", js: true do visit "/users" expect(page).to have_text("foobar") end end Correct expectation in feature spec require "spec_helper" RSpec.feature "Example Feature Spec" do scenario "When using Rack Test, it works" do visit "/users" expect(page).to have_text("Log in with your Rails Portal (development) account.") end scenario "When using Chrome, it works", js: true do visit "/users" expect(page).to have_text("Log in with your Rails Portal (development) account.") end end
require 'rails_helper' describe 'generate report', type: :feature, vcr: true do if Search.plos? it 'loads the visualization for a single article', js: true do visit '/' fill_in 'everything', with: 'cancer' click_button 'Search' expect(page).to have_content 'Cancer-Drug Associations: A Complex System' expect(page).to have_button('Preview List (0)', disabled: true) first('.article-info.cf').find('input.check-save-article').click expect(page).to have_button('Preview List (1)') find_button('Preview List (1)').click expect(page).to have_content 'Cancer-Drug Associations: A Complex System' expect(page).not_to have_content 'Cancer as a Complex Phenotype: Pattern of Cancer Distribution' click_button 'Create Report' expect(page).to have_content('Metrics Data') expect(page).to have_content('Visualizations') click_link('Visualizations') expect(page).to have_css('.line.chart svg') end it 'loads the visualization for multiple articles', js: true do visit '/' fill_in 'everything', with: 'cancer' click_button 'Search' expect(page).to have_content 'Cancer-Drug Associations: A Complex System' expect(page).to have_button('Preview List (0)', disabled: true) first('.article-info.cf').find('input.check-save-article').click all('.article-info.cf')[5].find('input.check-save-article').click expect(page).to have_button('Preview List (2)') find_button('Preview List (2)').click expect(page).to have_content 'Cancer-Drug Associations: A Complex System' expect(page).to have_content 'A Comparative Analysis of Gene-Expression Data of Multiple Cancer Types' expect(page).not_to have_content 'Cancer as a Complex Phenotype: Pattern of Cancer Distribution' click_button 'Create Report' expect(page).to have_content('Metrics Data') expect(page).to have_content('Visualizations') click_link('Visualizations') expect(page).to have_css('.bubble.chart svg') end elsif Search.crossref? it "loads the visualization for a single article", js: true do visit "/" fill_in "everything", with: "A Future Vision for PLOS Computational Biology" click_button "Search" expect(page).to have_content "A Future Vision for PLOS Computational Biology" expect(page).to have_button("Preview List (0)", disabled: true) first(".article-info.cf").find("input.check-save-article").click expect(page).to have_button("Preview List (1)") find_button("Preview List (1)").click expect(page).to have_content "A Future Vision for PLOS Computational Biology" expect(page).not_to have_content "What Do I Want from the Publisher of the Future?" click_button "Create Report" expect(page).to have_content("Metrics Data") expect(page).to have_content("Visualizations") click_link("Visualizations") expect(page).to have_css(".line.chart svg") end it "loads the visualization for a multiple articles", js: true do visit "/" fill_in "everything", with: "A Future Vision for PLOS Computational Biology" click_button "Search" first(".article-info.cf").find("input.check-save-article").click expect(page).to have_button("Preview List (1)") click_link("3") all(".article-info.cf")[12].find("input.check-save-article").click expect(page).to have_button("Preview List (2)") find_button("Preview List (2)").click expect(page).to have_content "A Future Vision for PLOS Computational Biology" expect(page).to have_content "New Methods Section in PLOS Computational Biology" expect(page).not_to have_content "What Do I Want from the Publisher of the Future?" click_button "Create Report" expect(page).to have_content("Metrics Data") expect(page).to have_content("Visualizations") click_link("Visualizations") expect(page).to have_css(".bubble.chart svg") end end end Ensure first AJAX request completes, before firing off another and possibly confusing Cart/VCR. require 'rails_helper' describe 'generate report', type: :feature, vcr: true do if Search.plos? it 'loads the visualization for a single article', js: true do visit '/' fill_in 'everything', with: 'cancer' click_button 'Search' expect(page).to have_content 'Cancer-Drug Associations: A Complex System' expect(page).to have_button('Preview List (0)', disabled: true) first('.article-info.cf').find('input.check-save-article').click expect(page).to have_button('Preview List (1)') find_button('Preview List (1)').click expect(page).to have_content 'Cancer-Drug Associations: A Complex System' expect(page).not_to have_content 'Cancer as a Complex Phenotype: Pattern of Cancer Distribution' click_button 'Create Report' expect(page).to have_content('Metrics Data') expect(page).to have_content('Visualizations') click_link('Visualizations') expect(page).to have_css('.line.chart svg') end it 'loads the visualization for multiple articles', js: true do visit '/' fill_in 'everything', with: 'cancer' click_button 'Search' expect(page).to have_content 'Cancer-Drug Associations: A Complex System' expect(page).to have_button('Preview List (0)', disabled: true) first('.article-info.cf').find('input.check-save-article').click expect(page).to have_button('Preview List (1)') all('.article-info.cf')[5].find('input.check-save-article').click expect(page).to have_button('Preview List (2)') find_button('Preview List (2)').click expect(page).to have_content 'Cancer-Drug Associations: A Complex System' expect(page).to have_content 'A Comparative Analysis of Gene-Expression Data of Multiple Cancer Types' expect(page).not_to have_content 'Cancer as a Complex Phenotype: Pattern of Cancer Distribution' click_button 'Create Report' expect(page).to have_content('Metrics Data') expect(page).to have_content('Visualizations') click_link('Visualizations') expect(page).to have_css('.bubble.chart svg') end elsif Search.crossref? it "loads the visualization for a single article", js: true do visit "/" fill_in "everything", with: "A Future Vision for PLOS Computational Biology" click_button "Search" expect(page).to have_content "A Future Vision for PLOS Computational Biology" expect(page).to have_button("Preview List (0)", disabled: true) first(".article-info.cf").find("input.check-save-article").click expect(page).to have_button("Preview List (1)") find_button("Preview List (1)").click expect(page).to have_content "A Future Vision for PLOS Computational Biology" expect(page).not_to have_content "What Do I Want from the Publisher of the Future?" click_button "Create Report" expect(page).to have_content("Metrics Data") expect(page).to have_content("Visualizations") click_link("Visualizations") expect(page).to have_css(".line.chart svg") end it "loads the visualization for a multiple articles", js: true do visit "/" fill_in "everything", with: "A Future Vision for PLOS Computational Biology" click_button "Search" first(".article-info.cf").find("input.check-save-article").click expect(page).to have_button("Preview List (1)") click_link("3") all(".article-info.cf")[12].find("input.check-save-article").click expect(page).to have_button("Preview List (2)") find_button("Preview List (2)").click expect(page).to have_content "A Future Vision for PLOS Computational Biology" expect(page).to have_content "New Methods Section in PLOS Computational Biology" expect(page).not_to have_content "What Do I Want from the Publisher of the Future?" click_button "Create Report" expect(page).to have_content("Metrics Data") expect(page).to have_content("Visualizations") click_link("Visualizations") expect(page).to have_css(".bubble.chart svg") end end end
# encoding: UTF-8 # # Author:: Kaustubh Deorukhkar (<kaustubh@clogeny.com>) # Copyright:: Copyright 2013-2020, Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "spec_helper" require "functional/resource/base" require "chef/mixin/shell_out" describe Chef::Resource::Cron, :requires_root, :unix_only do include Chef::Mixin::ShellOut # Platform specific validation routines. def cron_should_exists(cron_name, command) case ohai[:platform] when "aix", "opensolaris", "solaris2", "omnios" expect(shell_out("crontab -l #{new_resource.user} | grep \"#{cron_name}\"").exitstatus).to eq(0) expect(shell_out("crontab -l #{new_resource.user} | grep \"#{cron_name}\"").stdout.lines.to_a.size).to eq(1) expect(shell_out("crontab -l #{new_resource.user} | grep \"#{command}\"").exitstatus).to eq(0) expect(shell_out("crontab -l #{new_resource.user} | grep \"#{command}\"").stdout.lines.to_a.size).to eq(1) else expect(shell_out("crontab -l -u #{new_resource.user} | grep \"#{cron_name}\"").exitstatus).to eq(0) expect(shell_out("crontab -l #{new_resource.user} | grep \"#{cron_name}\"").stdout.lines.to_a.size).to eq(0) expect(shell_out("crontab -l -u #{new_resource.user} | grep \"#{command}\"").exitstatus).to eq(0) expect(shell_out("crontab -l #{new_resource.user} | grep \"#{command}\"").stdout.lines.to_a.size).to eq(0) end end def cron_should_not_exists(cron_name) case ohai[:platform] when "aix", "opensolaris", "solaris2", "omnios" expect(shell_out("crontab -l #{new_resource.user} | grep \"#{cron_name}\"").exitstatus).to eq(1) expect(shell_out("crontab -l #{new_resource.user} | grep \"#{new_resource.command}\"").stdout.lines.to_a.size).to eq(0) else expect(shell_out("crontab -l -u #{new_resource.user} | grep \"#{cron_name}\"").exitstatus).to eq(1) expect(shell_out("crontab -l -u #{new_resource.user} | grep \"#{new_resource.command}\"").stdout.lines.to_a.size).to eq(0) end end # Actual tests let(:new_resource) do new_resource = Chef::Resource::Cron.new("Chef functional test cron", run_context) new_resource.user "root" new_resource.minute "0" new_resource.command "/bin/true" new_resource end let(:provider) do provider = new_resource.provider_for_action(new_resource.action) provider end describe "create action" do after do new_resource.run_action(:delete) end it "should create a crontab entry" do new_resource.run_action(:create) cron_should_exists(new_resource.name, new_resource.command) end it "should create exactly one crontab entry" do 5.times { new_resource.run_action(:create) } cron_should_exists(new_resource.name, new_resource.command) end end describe "delete action" do before do new_resource.run_action(:create) end it "should delete a crontab entry" do # Note that test cron is created by previous test new_resource.run_action(:delete) cron_should_not_exists(new_resource.name) end end exclude_solaris = %w{solaris opensolaris solaris2 omnios}.include?(ohai[:platform]) describe "create action with various attributes", external: exclude_solaris do def create_and_validate_with_property(resource, attribute, value) if ohai[:platform] == "aix" expect { resource.run_action(:create) }.to raise_error(Chef::Exceptions::Cron, /Aix cron entry does not support environment variables. Please set them in script and use script in cron./) else resource.run_action(:create) # Verify if the cron is created successfully cron_attribute_should_exists(resource.name, attribute, value) end end def cron_attribute_should_exists(cron_name, attribute, value) return if %w{aix solaris}.include?(ohai[:platform]) # Test if the attribute exists on newly created cron cron_should_exists(cron_name, "") expect(shell_out("crontab -l -u #{new_resource.user} | grep '#{attribute.upcase}=\"#{value}\"'").exitstatus).to eq(0) end after do new_resource.run_action(:delete) end it "should create a crontab entry for mailto attribute" do new_resource.mailto "cheftest@example.com" create_and_validate_with_property(new_resource, "mailto", "cheftest@example.com") end it "should create a crontab entry for path attribute" do new_resource.path "/usr/local/bin" create_and_validate_with_property(new_resource, "path", "/usr/local/bin") end it "should create a crontab entry for shell attribute" do new_resource.shell "/bin/bash" create_and_validate_with_property(new_resource, "shell", "/bin/bash") end it "should create a crontab entry for home attribute" do new_resource.home "/home/opscode" create_and_validate_with_property(new_resource, "home", "/home/opscode") end %i{ home mailto path shell }.each do |attr| it "supports an empty string for #{attr} attribute" do new_resource.send(attr, "") create_and_validate_with_property(new_resource, attr.to_s, "") end end end describe "negative tests for create action" do after do new_resource.run_action(:delete) end it "should not create cron with invalid minute" do new_resource.minute "invalid" expect { new_resource.run_action(:create) }.to raise_error(Chef::Exceptions::ValidationFailed) cron_should_not_exists(new_resource.name) end it "should not create cron with invalid user" do new_resource.user "1-really-really-invalid-user-name" expect { new_resource.run_action(:create) }.to raise_error(Chef::Exceptions::Cron) cron_should_not_exists(new_resource.name) end end end Tweak functional spec order Signed-off-by: Tim Smith <764ef62106582a09ed09dfa0b6bff7c05fd7d1e4@chef.io> # encoding: UTF-8 # # Author:: Kaustubh Deorukhkar (<kaustubh@clogeny.com>) # Copyright:: Copyright 2013-2020, Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "spec_helper" require "functional/resource/base" require "chef/mixin/shell_out" describe Chef::Resource::Cron, :requires_root, :unix_only do include Chef::Mixin::ShellOut # Platform specific validation routines. def cron_should_exists(cron_name, command) case ohai[:platform] when "aix", "opensolaris", "solaris2", "omnios" expect(shell_out("crontab -l #{new_resource.user} | grep \"#{cron_name}\"").exitstatus).to eq(0) expect(shell_out("crontab -l #{new_resource.user} | grep \"#{cron_name}\"").stdout.lines.to_a.size).to eq(1) expect(shell_out("crontab -l #{new_resource.user} | grep \"#{command}\"").exitstatus).to eq(0) expect(shell_out("crontab -l #{new_resource.user} | grep \"#{command}\"").stdout.lines.to_a.size).to eq(1) else expect(shell_out("crontab -l -u #{new_resource.user} | grep \"#{cron_name}\"").exitstatus).to eq(0) expect(shell_out("crontab -l #{new_resource.user} | grep \"#{cron_name}\"").stdout.lines.to_a.size).to eq(0) expect(shell_out("crontab -l -u #{new_resource.user} | grep \"#{command}\"").exitstatus).to eq(0) expect(shell_out("crontab -l #{new_resource.user} | grep \"#{command}\"").stdout.lines.to_a.size).to eq(0) end end def cron_should_not_exists(cron_name) case ohai[:platform] when "aix", "opensolaris", "solaris2", "omnios" expect(shell_out("crontab -l #{new_resource.user} | grep \"#{cron_name}\"").exitstatus).to eq(1) expect(shell_out("crontab -l #{new_resource.user} | grep \"#{new_resource.command}\"").stdout.lines.to_a.size).to eq(0) else expect(shell_out("crontab -l -u #{new_resource.user} | grep \"#{cron_name}\"").exitstatus).to eq(1) expect(shell_out("crontab -l -u #{new_resource.user} | grep \"#{new_resource.command}\"").stdout.lines.to_a.size).to eq(0) end end # Actual tests let(:new_resource) do new_resource = Chef::Resource::Cron.new("Chef functional test cron", run_context) new_resource.user "root" new_resource.minute "0" new_resource.command "/bin/true" new_resource end let(:provider) do provider = new_resource.provider_for_action(new_resource.action) provider end describe "create action" do after do new_resource.run_action(:delete) end it "should create a crontab entry" do new_resource.run_action(:create) cron_should_exists(new_resource.name, new_resource.command) end it "should create exactly one crontab entry" do 5.times { new_resource.run_action(:create) } cron_should_exists(new_resource.name, new_resource.command) end end describe "delete action" do before do new_resource.run_action(:create) end it "should delete a crontab entry" do # Note that test cron is created by previous test new_resource.run_action(:delete) cron_should_not_exists(new_resource.name) end end exclude_solaris = %w{solaris opensolaris solaris2 omnios}.include?(ohai[:platform]) describe "create action with various attributes", external: exclude_solaris do def create_and_validate_with_property(resource, attribute, value) if ohai[:platform] == "aix" expect { resource.run_action(:create) }.to raise_error(Chef::Exceptions::Cron, /Aix cron entry does not support environment variables. Please set them in script and use script in cron./) else resource.run_action(:create) # Verify if the cron is created successfully cron_attribute_should_exists(resource.name, attribute, value) end end def cron_attribute_should_exists(cron_name, attribute, value) return if %w{aix solaris}.include?(ohai[:platform]) # Test if the attribute exists on newly created cron cron_should_exists(cron_name, "") expect(shell_out("crontab -l -u #{new_resource.user} | grep '#{attribute.upcase}=\"#{value}\"'").exitstatus).to eq(0) end after do new_resource.run_action(:delete) end it "should create a crontab entry for mailto attribute" do new_resource.mailto "cheftest@example.com" create_and_validate_with_property(new_resource, "mailto", "cheftest@example.com") end it "should create a crontab entry for path attribute" do new_resource.path "/usr/local/bin" create_and_validate_with_property(new_resource, "path", "/usr/local/bin") end it "should create a crontab entry for shell attribute" do new_resource.shell "/bin/bash" create_and_validate_with_property(new_resource, "shell", "/bin/bash") end it "should create a crontab entry for home attribute" do new_resource.home "/home/opscode" create_and_validate_with_property(new_resource, "home", "/home/opscode") end %i{ home mailto path shell }.each do |attr| it "supports an empty string for #{attr} attribute" do new_resource.send(attr, "") create_and_validate_with_property(new_resource, attr.to_s, "") end end end describe "negative tests for create action" do after do new_resource.run_action(:delete) end it "should not create cron with invalid minute" do expect { new_resource.run_action(:create) }.to raise_error(Chef::Exceptions::ValidationFailed) new_resource.minute "invalid" cron_should_not_exists(new_resource.name) end it "should not create cron with invalid user" do new_resource.user "1-really-really-invalid-user-name" expect { new_resource.run_action(:create) }.to raise_error(Chef::Exceptions::Cron) cron_should_not_exists(new_resource.name) end end end
require 'spec_helper' describe GreenhouseIo::Client do it "should have a base url for an API endpoint" do expect(GreenhouseIo::Client.base_uri).to eq("https://harvest.greenhouse.io/v1") end context "given an instance of GreenhouseIo::Client" do before do GreenhouseIo.configuration.symbolize_keys = true @client = GreenhouseIo::Client.new('123FakeToken') end describe "#initialize" do it "has an api_token" do expect(@client.api_token).to eq('123FakeToken') end it "uses the configuration value when token is not specified" do GreenhouseIo.configuration.api_token = '123FakeENV' default_client = GreenhouseIo::Client.new expect(default_client.api_token).to eq('123FakeENV') end end describe "#path_id" do context "given an id" do it "returns an id path" do output = @client.send(:path_id, 1) expect(output).to eq('/1') end end context "given no id" do it "returns nothing" do output = @client.send(:path_id) expect(output).to be_nil end end end describe "#set_rate_limits" do before do @headers = { 'x-ratelimit-limit' => '20', 'x-ratelimit-remaining' => '20' } end it "sets the rate limit" do @client.send(:set_rate_limits, @headers) expect(@client.rate_limit).to eq(20) end it "sets the remaining rate limit" do @client.send(:set_rate_limits, @headers) expect(@client.rate_limit_remaining).to eq(20) end end describe "#permitted_options" do let(:options) { GreenhouseIo::Client::PERMITTED_OPTIONS + [:where] } it "allows permitted options" do output = @client.send(:permitted_options, options) GreenhouseIo::Client::PERMITTED_OPTIONS.each do |option| expect(output).to include(option) end end it "discards non-permitted options" do output = @client.send(:permitted_options, options) expect(output).to_not include(:where) end end describe "#offices" do context "given no id" do before do VCR.use_cassette('client/offices') do @offices_response = @client.offices end end it "returns a response" do expect(@offices_response).to_not be_nil end it "returns an array of offices" do expect(@offices_response).to be_an_instance_of(Array) end it "returns office details" do expect(@offices_response.first).to have_key(:name) end end context "given an id" do before do VCR.use_cassette('client/office') do @office_response = @client.offices(220) end end it "returns a response" do expect(@office_response).to_not be_nil end it "returns an office hash" do expect(@office_response).to be_an_instance_of(Hash) end it "returns an office's details" do expect(@office_response).to have_key(:name) end end end describe "#departments" do context "given no id" do before do VCR.use_cassette('client/departments') do @departments_response = @client.departments end end it "returns a response" do expect(@departments_response).to_not be_nil end it "returns an array of departments" do expect(@departments_response).to be_an_instance_of(Array) end it "returns office details" do expect(@departments_response.first).to have_key(:name) end end context "given an id" do before do VCR.use_cassette('client/department') do @department_response = @client.departments(187) end end it "returns a response" do expect(@department_response).to_not be_nil end it "returns a department hash" do expect(@department_response).to be_an_instance_of(Hash) end it "returns a department's details" do expect(@department_response).to have_key(:name) end end end describe "#candidates" do context "given no id" do before do VCR.use_cassette('client/candidates') do @candidates_response = @client.candidates end end it "returns a response" do expect(@candidates_response).to_not be_nil end it "returns an array of candidates" do expect(@candidates_response).to be_an_instance_of(Array) end it "returns details of candidates" do expect(@candidates_response.first).to have_key(:first_name) end end context "given an id" do before do VCR.use_cassette('client/candidate') do @candidate_response = @client.candidates(1) end end it "returns a response" do expect(@candidate_response).to_not be_nil end it "returns a candidate hash" do expect(@candidate_response).to be_an_instance_of(Hash) end it "returns a candidate's details" do expect(@candidate_response).to have_key(:first_name) end end end describe "#activity_feed" do before do VCR.use_cassette('client/activity_feed') do @activity_feed = @client.activity_feed(1) end end it "returns a response" do expect(@activity_feed).to_not be_nil end it "returns an activity feed" do expect(@activity_feed).to be_an_instance_of(Hash) end it "returns details of the activity feed" do expect(@activity_feed).to have_key(:activities) end end describe "#applications" do context "given no id" do before do VCR.use_cassette('client/applications') do @applications = @client.applications end end it "returns a response" do expect(@applications).to_not be_nil end it "returns an array of applications" do expect(@applications).to be_an_instance_of(Array) end it "returns application details" do expect(@applications.first).to have_key(:person_id) end end context "given an id" do before do VCR.use_cassette('client/application') do @application = @client.applications(1) end end it "returns a response" do expect(@application).to_not be_nil end it "returns an application hash" do expect(@application).to be_an_instance_of(Hash) end it "returns an application's details" do expect(@application).to have_key(:person_id) end end context "given a job_id" do before do VCR.use_cassette('client/application_by_job_id') do @applications = @client.applications(nil, :job_id => 144371) end end it "returns a response" do expect(@applications).to_not be_nil end it "returns an array of applications" do expect(@applications).to be_an_instance_of(Array) expect(@applications.first).to be_an_instance_of(Hash) expect(@applications.first).to have_key(:prospect) end end end describe "#scorecards" do before do VCR.use_cassette('client/scorecards') do @scorecard = @client.scorecards(1) end end it "returns a response" do expect(@scorecard).to_not be_nil end it "returns an array of scorecards" do expect(@scorecard).to be_an_instance_of(Array) end it "returns details of the scorecards" do expect(@scorecard.first).to have_key(:interview) end end describe "#scheduled_interviews" do before do VCR.use_cassette('client/scheduled_interviews') do @scheduled_interviews = @client.scheduled_interviews(1) end end it "returns a response" do expect(@scheduled_interviews).to_not be_nil end it "returns an array of scheduled interviews" do expect(@scheduled_interviews).to be_an_instance_of(Array) end it "returns details of the interview" do expect(@scheduled_interviews.first).to have_key(:starts_at) end end describe "#jobs" do context "given no id" do before do VCR.use_cassette('client/jobs') do @jobs = @client.jobs end end it "returns a response" do expect(@jobs).to_not be_nil end it "returns an array of applications" do expect(@jobs).to be_an_instance_of(Array) end it "returns application details" do expect(@jobs.first).to have_key(:employment_type) end end context "given an id" do before do VCR.use_cassette('client/job') do @job = @client.jobs(4690) end end it "returns a response" do expect(@job).to_not be_nil end it "returns an application hash" do expect(@job).to be_an_instance_of(Hash) end it "returns an application's details" do expect(@job).to have_key(:employment_type) end end end describe "#stages" do before do VCR.use_cassette('client/stages') do @stages = @client.stages(4690) end end it "returns a response" do expect(@stages).to_not be_nil end it "returns an array of scheduled interviews" do expect(@stages).to be_an_instance_of(Array) end it "returns details of the interview" do expect(@stages.first).to have_key(:name) end end describe "#job_post" do before do VCR.use_cassette('client/job_post') do @job_post = @client.job_post(4690) end end it "returns a response" do expect(@job_post).to_not be_nil end it "returns an array of scheduled interviews" do expect(@job_post).to be_an_instance_of(Hash) end it "returns details of the interview" do expect(@job_post).to have_key(:title) end end describe "#users" do context "given no id" do before do VCR.use_cassette('client/users') do @users = @client.users end end it "returns a response" do expect(@users).to_not be_nil end it "returns an array of applications" do expect(@users).to be_an_instance_of(Array) end it "returns application details" do expect(@users.first).to have_key(:name) end end context "given an id" do before do VCR.use_cassette('client/user') do @job = @client.users(10327) end end it "returns a response" do expect(@job).to_not be_nil end it "returns an application hash" do expect(@job).to be_an_instance_of(Hash) end it "returns an application's details" do expect(@job).to have_key(:name) end end end describe "#sources" do context "given no id" do before do VCR.use_cassette('client/sources') do @sources = @client.sources end end it "returns a response" do expect(@sources).to_not be_nil end it "returns an array of applications" do expect(@sources).to be_an_instance_of(Array) end it "returns application details" do expect(@sources.first).to have_key(:name) end end context "given an id" do before do VCR.use_cassette('client/source') do @source = @client.sources(1) end end it "returns a response" do expect(@source).to_not be_nil end it "returns an application hash" do expect(@source).to be_an_instance_of(Hash) end it "returns an application's details" do expect(@source).to have_key(:name) end end end describe "#offers" do context "given no id" do before do VCR.use_cassette('client/offers') do @offers = @client.offers end end it "returns a response" do expect(@offers).to_not be nil end it "returns an array of offers" do expect(@offers).to be_an_instance_of(Array) expect(@offers.first[:id]).to be_a(Integer).and be > 0 expect(@offers.first[:created_at]).to be_a(String) expect(@offers.first[:version]).to be_a(Integer).and be > 0 expect(@offers.first[:status]).to be_a(String) end end context "given an id" do before do VCR.use_cassette('client/offer') do @offer = @client.offers(221598) end end it "returns a response" do expect(@offer).to_not be nil end it "returns an offer object" do expect(@offer).to be_an_instance_of(Hash) expect(@offer[:id]).to be_a(Integer).and be > 0 expect(@offer[:created_at]).to be_a(String) expect(@offer[:version]).to be_a(Integer).and be > 0 expect(@offer[:status]).to be_a(String) end end end end end Make it easier to set the API token in tests require 'spec_helper' describe GreenhouseIo::Client do FAKE_API_TOKEN = '123FakeToken' it "should have a base url for an API endpoint" do expect(GreenhouseIo::Client.base_uri).to eq("https://harvest.greenhouse.io/v1") end context "given an instance of GreenhouseIo::Client" do before do GreenhouseIo.configuration.symbolize_keys = true @client = GreenhouseIo::Client.new(FAKE_API_TOKEN) end describe "#initialize" do it "has an api_token" do expect(@client.api_token).to eq(FAKE_API_TOKEN) end it "uses the configuration value when token is not specified" do GreenhouseIo.configuration.api_token = '123FakeENV' default_client = GreenhouseIo::Client.new expect(default_client.api_token).to eq('123FakeENV') end end describe "#path_id" do context "given an id" do it "returns an id path" do output = @client.send(:path_id, 1) expect(output).to eq('/1') end end context "given no id" do it "returns nothing" do output = @client.send(:path_id) expect(output).to be_nil end end end describe "#set_rate_limits" do before do @headers = { 'x-ratelimit-limit' => '20', 'x-ratelimit-remaining' => '20' } end it "sets the rate limit" do @client.send(:set_rate_limits, @headers) expect(@client.rate_limit).to eq(20) end it "sets the remaining rate limit" do @client.send(:set_rate_limits, @headers) expect(@client.rate_limit_remaining).to eq(20) end end describe "#permitted_options" do let(:options) { GreenhouseIo::Client::PERMITTED_OPTIONS + [:where] } it "allows permitted options" do output = @client.send(:permitted_options, options) GreenhouseIo::Client::PERMITTED_OPTIONS.each do |option| expect(output).to include(option) end end it "discards non-permitted options" do output = @client.send(:permitted_options, options) expect(output).to_not include(:where) end end describe "#offices" do context "given no id" do before do VCR.use_cassette('client/offices') do @offices_response = @client.offices end end it "returns a response" do expect(@offices_response).to_not be_nil end it "returns an array of offices" do expect(@offices_response).to be_an_instance_of(Array) end it "returns office details" do expect(@offices_response.first).to have_key(:name) end end context "given an id" do before do VCR.use_cassette('client/office') do @office_response = @client.offices(220) end end it "returns a response" do expect(@office_response).to_not be_nil end it "returns an office hash" do expect(@office_response).to be_an_instance_of(Hash) end it "returns an office's details" do expect(@office_response).to have_key(:name) end end end describe "#departments" do context "given no id" do before do VCR.use_cassette('client/departments') do @departments_response = @client.departments end end it "returns a response" do expect(@departments_response).to_not be_nil end it "returns an array of departments" do expect(@departments_response).to be_an_instance_of(Array) end it "returns office details" do expect(@departments_response.first).to have_key(:name) end end context "given an id" do before do VCR.use_cassette('client/department') do @department_response = @client.departments(187) end end it "returns a response" do expect(@department_response).to_not be_nil end it "returns a department hash" do expect(@department_response).to be_an_instance_of(Hash) end it "returns a department's details" do expect(@department_response).to have_key(:name) end end end describe "#candidates" do context "given no id" do before do VCR.use_cassette('client/candidates') do @candidates_response = @client.candidates end end it "returns a response" do expect(@candidates_response).to_not be_nil end it "returns an array of candidates" do expect(@candidates_response).to be_an_instance_of(Array) end it "returns details of candidates" do expect(@candidates_response.first).to have_key(:first_name) end end context "given an id" do before do VCR.use_cassette('client/candidate') do @candidate_response = @client.candidates(1) end end it "returns a response" do expect(@candidate_response).to_not be_nil end it "returns a candidate hash" do expect(@candidate_response).to be_an_instance_of(Hash) end it "returns a candidate's details" do expect(@candidate_response).to have_key(:first_name) end end end describe "#activity_feed" do before do VCR.use_cassette('client/activity_feed') do @activity_feed = @client.activity_feed(1) end end it "returns a response" do expect(@activity_feed).to_not be_nil end it "returns an activity feed" do expect(@activity_feed).to be_an_instance_of(Hash) end it "returns details of the activity feed" do expect(@activity_feed).to have_key(:activities) end end describe "#applications" do context "given no id" do before do VCR.use_cassette('client/applications') do @applications = @client.applications end end it "returns a response" do expect(@applications).to_not be_nil end it "returns an array of applications" do expect(@applications).to be_an_instance_of(Array) end it "returns application details" do expect(@applications.first).to have_key(:person_id) end end context "given an id" do before do VCR.use_cassette('client/application') do @application = @client.applications(1) end end it "returns a response" do expect(@application).to_not be_nil end it "returns an application hash" do expect(@application).to be_an_instance_of(Hash) end it "returns an application's details" do expect(@application).to have_key(:person_id) end end context "given a job_id" do before do VCR.use_cassette('client/application_by_job_id') do @applications = @client.applications(nil, :job_id => 144371) end end it "returns a response" do expect(@applications).to_not be_nil end it "returns an array of applications" do expect(@applications).to be_an_instance_of(Array) expect(@applications.first).to be_an_instance_of(Hash) expect(@applications.first).to have_key(:prospect) end end end describe "#scorecards" do before do VCR.use_cassette('client/scorecards') do @scorecard = @client.scorecards(1) end end it "returns a response" do expect(@scorecard).to_not be_nil end it "returns an array of scorecards" do expect(@scorecard).to be_an_instance_of(Array) end it "returns details of the scorecards" do expect(@scorecard.first).to have_key(:interview) end end describe "#scheduled_interviews" do before do VCR.use_cassette('client/scheduled_interviews') do @scheduled_interviews = @client.scheduled_interviews(1) end end it "returns a response" do expect(@scheduled_interviews).to_not be_nil end it "returns an array of scheduled interviews" do expect(@scheduled_interviews).to be_an_instance_of(Array) end it "returns details of the interview" do expect(@scheduled_interviews.first).to have_key(:starts_at) end end describe "#jobs" do context "given no id" do before do VCR.use_cassette('client/jobs') do @jobs = @client.jobs end end it "returns a response" do expect(@jobs).to_not be_nil end it "returns an array of applications" do expect(@jobs).to be_an_instance_of(Array) end it "returns application details" do expect(@jobs.first).to have_key(:employment_type) end end context "given an id" do before do VCR.use_cassette('client/job') do @job = @client.jobs(4690) end end it "returns a response" do expect(@job).to_not be_nil end it "returns an application hash" do expect(@job).to be_an_instance_of(Hash) end it "returns an application's details" do expect(@job).to have_key(:employment_type) end end end describe "#stages" do before do VCR.use_cassette('client/stages') do @stages = @client.stages(4690) end end it "returns a response" do expect(@stages).to_not be_nil end it "returns an array of scheduled interviews" do expect(@stages).to be_an_instance_of(Array) end it "returns details of the interview" do expect(@stages.first).to have_key(:name) end end describe "#job_post" do before do VCR.use_cassette('client/job_post') do @job_post = @client.job_post(4690) end end it "returns a response" do expect(@job_post).to_not be_nil end it "returns an array of scheduled interviews" do expect(@job_post).to be_an_instance_of(Hash) end it "returns details of the interview" do expect(@job_post).to have_key(:title) end end describe "#users" do context "given no id" do before do VCR.use_cassette('client/users') do @users = @client.users end end it "returns a response" do expect(@users).to_not be_nil end it "returns an array of applications" do expect(@users).to be_an_instance_of(Array) end it "returns application details" do expect(@users.first).to have_key(:name) end end context "given an id" do before do VCR.use_cassette('client/user') do @job = @client.users(10327) end end it "returns a response" do expect(@job).to_not be_nil end it "returns an application hash" do expect(@job).to be_an_instance_of(Hash) end it "returns an application's details" do expect(@job).to have_key(:name) end end end describe "#sources" do context "given no id" do before do VCR.use_cassette('client/sources') do @sources = @client.sources end end it "returns a response" do expect(@sources).to_not be_nil end it "returns an array of applications" do expect(@sources).to be_an_instance_of(Array) end it "returns application details" do expect(@sources.first).to have_key(:name) end end context "given an id" do before do VCR.use_cassette('client/source') do @source = @client.sources(1) end end it "returns a response" do expect(@source).to_not be_nil end it "returns an application hash" do expect(@source).to be_an_instance_of(Hash) end it "returns an application's details" do expect(@source).to have_key(:name) end end end describe "#offers" do context "given no id" do before do VCR.use_cassette('client/offers') do @offers = @client.offers end end it "returns a response" do expect(@offers).to_not be nil end it "returns an array of offers" do expect(@offers).to be_an_instance_of(Array) expect(@offers.first[:id]).to be_a(Integer).and be > 0 expect(@offers.first[:created_at]).to be_a(String) expect(@offers.first[:version]).to be_a(Integer).and be > 0 expect(@offers.first[:status]).to be_a(String) end end context "given an id" do before do VCR.use_cassette('client/offer') do @offer = @client.offers(221598) end end it "returns a response" do expect(@offer).to_not be nil end it "returns an offer object" do expect(@offer).to be_an_instance_of(Hash) expect(@offer[:id]).to be_a(Integer).and be > 0 expect(@offer[:created_at]).to be_a(String) expect(@offer[:version]).to be_a(Integer).and be > 0 expect(@offer[:status]).to be_a(String) end end end end end
require 'spec_helper.rb' describe 'jira' do describe 'jira::config' do context 'supported operating systems' do on_supported_os.each do |os, facts| context "on #{os}" do let(:facts) do facts end context 'default params' do let(:params) do { javahome: '/opt/java' } end it { is_expected.to compile.with_all_deps } it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/bin/setenv.sh'). with_content(%r{#DISABLE_NOTIFICATIONS=}) end it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/bin/user.sh') } it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml') } # Also ensure that we actually omit elements by default it do is_expected.to contain_file('/home/jira/dbconfig.xml'). with_content(%r{jdbc:postgresql://localhost:5432/jira}). with_content(%r{<schema-name>public</schema-name>}). with_content(%r{<pool-max-size>20}). with_content(%r{<pool-min-size>20}). with_content(%r{<pool-max-wait>30000}). with_content(%r{<pool-max-idle>20}). with_content(%r{<pool-remove-abandoned>true}). with_content(%r{<pool-remove-abandoned-timeout>300}). with_content(%r{<min-evictable-idle-time-millis>60000}). with_content(%r{<time-between-eviction-runs-millis>300000}). with_content(%r{<pool-test-while-idle>true}). with_content(%r{<pool-test-on-borrow>false}). with_content(%r{<validation-query>select version\(\);}). with_content(%r{<connection-properties>tcpKeepAlive=true;socketTimeout=240}) end it { is_expected.not_to contain_file('/home/jira/cluster.properties') } it { is_expected.not_to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/bin/check-java.sh') } end context 'default params with java install' do let(:params) do { javahome: '/usr/lib/jvm/jre-11-openjdk', java_package: 'java-11-openjdk-headless', } end it { is_expected.to compile.with_all_deps } it { is_expected.to contain_package('java-11-openjdk-headless') } end context 'default params with java install and mysql' do let(:params) do { db: 'mysql', javahome: '/usr/lib/jvm/jre-11-openjdk', java_package: 'java-11-openjdk-headless', } end it { is_expected.to compile.with_all_deps } it { is_expected.to contain_package('java-11-openjdk-headless') } it do is_expected.to contain_file('/home/jira/dbconfig.xml'). with_content(%r{<validation-query>select 1</validation-query>}). with_content(%r{<validation-query-timeout>3</validation-query-timeout>}). without_content(%r{<connection-properties>}) end end context 'database settings' do let(:params) do { version: '8.13.5', javahome: '/opt/java', connection_settings: 'TEST-SETTING;', pool_max_size: 200, pool_min_size: 10, validation_query: 'SELECT myfunction();', } end it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/bin/setenv.sh') } it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/bin/user.sh') } it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml') } it do is_expected.to contain_file('/home/jira/dbconfig.xml'). with_content(%r{<connection-properties>TEST-SETTING;</connection-properties>}). with_content(%r{<pool-max-size>200</pool-max-size>}). with_content(%r{<pool-min-size>10</pool-min-size>}). with_content(%r{<validation-query>SELECT myfunction\(\);</validation-query>}) end end context 'mysql params' do let(:params) do { version: '8.13.5', javahome: '/opt/java', db: 'mysql' } end it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/bin/setenv.sh') } it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/bin/user.sh') } it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml') } it do is_expected.to contain_file('/home/jira/dbconfig.xml'). with_content(%r{jdbc:mysql://localhost:3306/jira}) end end context 'oracle params' do let(:params) do { version: '8.13.5', javahome: '/opt/java', db: 'oracle', dbname: 'mydatabase', } end it do is_expected.to contain_file('/home/jira/dbconfig.xml'). with_content(%r{jdbc:oracle:thin:@localhost:1521:mydatabase}). with_content(%r{<database-type>oracle10g}). with_content(%r{<driver-class>oracle.jdbc.OracleDriver}) end end context 'oracle servicename' do let(:params) do { version: '8.13.5', javahome: '/opt/java', db: 'oracle', dbport: 1522, dbserver: 'oracleserver', oracle_use_sid: false, dbname: 'mydatabase', } end it do is_expected.to contain_file('/home/jira/dbconfig.xml'). with_content(%r{jdbc:oracle:thin:@oracleserver:1522/mydatabase}) end end context 'sqlserver params' do let(:params) do { version: '8.13.5', javahome: '/opt/java', db: 'sqlserver', dbport: '1433', dbschema: 'public' } end it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/bin/setenv.sh') } it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/bin/user.sh') } it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml') } it do is_expected.to contain_file('/home/jira/dbconfig.xml'). with_content(%r{<schema-name>public</schema-name>}) end end context 'custom dburl' do let(:params) do { version: '8.13.5', javahome: '/opt/java', dburl: 'my custom dburl' } end it do is_expected.to contain_file('/home/jira/dbconfig.xml'). with_content(%r{<url>my custom dburl</url>}) end end context 'customise tomcat connector' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_port: 9229 } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{<Connector port=\"9229\"\s+relaxedPathChars=}m) end end context 'server.xml listeners' do context 'version greater than 8' do let(:params) do { version: '8.1.0', javahome: '/opt/java' } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.1.0-standalone/conf/server.xml'). with_content(%r{<Listener className=\"org.apache.catalina.core.JreMemoryLeakPreventionListener\"}) end end end context 'customise tomcat connector with a binding address' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_port: 9229, tomcat_address: '127.0.0.1' } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{<Connector port=\"9229\"\s+address=\"127\.0\.0\.1\"\s+relaxedPathChars=}m) end end context 'tomcat context path' do let(:params) do { version: '8.13.5', javahome: '/opt/java', contextpath: '/jira' } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{path="/jira"}) end end context 'tomcat port' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_port: 8888 } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{port="8888"}) end end context 'tomcat acceptCount' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_accept_count: 200 } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{acceptCount="200"}) end end context 'tomcat MaxHttpHeaderSize' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_max_http_header_size: 4096 } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{maxHttpHeaderSize="4096"}) end end context 'tomcat MinSpareThreads' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_min_spare_threads: 50 } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{minSpareThreads="50"}) end end context 'tomcat ConnectionTimeout' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_connection_timeout: 25_000 } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{connectionTimeout="25000"}) end end context 'tomcat EnableLookups' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_enable_lookups: true } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{enableLookups="true"}) end end context 'tomcat Protocol' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_protocol: 'HTTP/1.1' } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{protocol="HTTP/1.1"}) end end context 'tomcat UseBodyEncodingForURI' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_use_body_encoding_for_uri: false } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{useBodyEncodingForURI="false"}) end end context 'tomcat DisableUploadTimeout' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_disable_upload_timeout: false } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{disableUploadTimeout="false"}) end end context 'tomcat EnableLookups' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_enable_lookups: true } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{enableLookups="true"}) end end context 'tomcat maxThreads' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_max_threads: 300 } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{maxThreads="300"}) end end context 'tomcat proxy path' do let(:params) do { version: '8.13.5', javahome: '/opt/java', proxy: { 'scheme' => 'https', 'proxyName' => 'www.example.com', 'proxyPort' => '9999' } } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{proxyName = 'www\.example\.com'}). with_content(%r{scheme = 'https'}). with_content(%r{proxyPort = '9999'}) end end context 'ajp proxy' do context 'with valid config including protocol AJP/1.3' do let(:params) do { version: '8.13.5', javahome: '/opt/java', ajp: { 'port' => '8009', 'protocol' => 'AJP/1.3' } } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{<Connector enableLookups="false" URIEncoding="UTF-8"\s+port = "8009"\s+protocol = "AJP/1.3"\s+/>}) end end context 'with valid config including protocol org.apache.coyote.ajp.AjpNioProtocol' do let(:params) do { version: '8.13.5', javahome: '/opt/java', ajp: { 'port' => '8009', 'protocol' => 'org.apache.coyote.ajp.AjpNioProtocol' } } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{<Connector enableLookups="false" URIEncoding="UTF-8"\s+port = "8009"\s+protocol = "org.apache.coyote.ajp.AjpNioProtocol"\s+/>}) end end end context 'tomcat additional connectors, without default' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_default_connector: false, tomcat_additional_connectors: { 8081 => { 'URIEncoding' => 'UTF-8', 'connectionTimeout' => '20000', 'protocol' => 'HTTP/1.1', 'proxyName' => 'foo.example.com', 'proxyPort' => '8123', 'secure' => true, 'scheme' => 'https' }, 8082 => { 'URIEncoding' => 'UTF-8', 'connectionTimeout' => '20000', 'protocol' => 'HTTP/1.1', 'proxyName' => 'bar.example.com', 'proxyPort' => '8124', 'scheme' => 'http' } } } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). without_content(%r{<Connector port="8080"}). with_content(%r{<Connector port="8081"}). with_content(%r{connectionTimeout="20000"}). with_content(%r{protocol="HTTP/1\.1"}). with_content(%r{proxyName="foo\.example\.com"}). with_content(%r{proxyPort="8123"}). with_content(%r{scheme="https"}). with_content(%r{secure="true"}). with_content(%r{URIEncoding="UTF-8"}). with_content(%r{<Connector port="8082"}). with_content(%r{connectionTimeout="20000"}). with_content(%r{protocol="HTTP/1\.1"}). with_content(%r{proxyName="bar\.example\.com"}). with_content(%r{proxyPort="8124"}). with_content(%r{scheme="http"}). with_content(%r{URIEncoding="UTF-8"}) end end context 'tomcat access log format' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_accesslog_format: '%a %{jira.request.id}r %{jira.request.username}r %t %I' } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{pattern="%a %{jira.request.id}r %{jira.request.username}r %t %I"/>}) end end context 'tomcat access log format with x-forward-for handling' do let(:params) do { version: '8.16.0', javahome: '/opt/java', tomcat_accesslog_enable_xforwarded_for: true, } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.16.0-standalone/conf/server.xml'). with_content(%r{org.apache.catalina.valves.RemoteIpValve}). with_content(%r{requestAttributesEnabled="true"}) end end context 'with script_check_java_managed enabled' do let(:params) do { script_check_java_manage: true, version: '8.1.0', javahome: '/opt/java' } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.1.0-standalone/bin/check-java.sh'). with_content(%r{Wrong JVM version}) end end context 'context resources' do let(:params) do { version: '8.13.5', javahome: '/opt/java', resources: { 'testdb' => { 'auth' => 'Container' } } } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/context.xml'). with_content(%r{<Resource name = "testdb"\n auth = "Container"\n />}) end end context 'disable notifications' do let(:params) do { version: '8.13.5', javahome: '/opt/java', disable_notifications: true } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/bin/setenv.sh'). with_content(%r{^DISABLE_NOTIFICATIONS=}) end end context 'native ssl support default params' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_native_ssl: true } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{redirectPort="8443"}). with_content(%r{port="8443"}). with_content(%r{keyAlias="jira"}). with_content(%r{keystoreFile="/home/jira/jira.jks"}). with_content(%r{keystorePass="changeit"}). with_content(%r{keystoreType="JKS"}). with_content(%r{port="8443".*acceptCount="100"}m). with_content(%r{port="8443".*maxThreads="150"}m) end end context 'native ssl support custom params' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_native_ssl: true, tomcat_https_port: 9443, tomcat_address: '127.0.0.1', tomcat_max_threads: 600, tomcat_accept_count: 600, tomcat_key_alias: 'keystorealias', tomcat_keystore_file: '/tmp/keyfile.ks', tomcat_keystore_pass: 'keystorepass', tomcat_keystore_type: 'PKCS12' } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{redirectPort="9443"}). with_content(%r{port="9443"}). with_content(%r{keyAlias="keystorealias"}). with_content(%r{keystoreFile="/tmp/keyfile.ks"}). with_content(%r{keystorePass="keystorepass"}). with_content(%r{keystoreType="PKCS12"}). with_content(%r{port="9443".*acceptCount="600"}m). with_content(%r{port="9443".*maxThreads="600"}m). with_content(%r{port="9443".*address="127\.0\.0\.1"}m) end end context 'enable secure admin sessions' do let(:params) do { version: '8.13.5', javahome: '/opt/java', enable_secure_admin_sessions: true } end it do is_expected.to contain_file('/home/jira/jira-config.properties'). with_content(%r{jira.websudo.is.disabled = false}) end end context 'disable secure admin sessions' do let(:params) do { version: '8.13.5', javahome: '/opt/java', enable_secure_admin_sessions: false } end it do is_expected.to contain_file('/home/jira/jira-config.properties'). with_content(%r{jira.websudo.is.disabled = true}) end end context 'jira-config.properties' do let(:params) do { version: '8.13.5', javahome: '/opt/java', jira_config_properties: { 'ops.bar.group.size.opsbar-transitions' => '4' } } end it do is_expected.to contain_file('/home/jira/jira-config.properties'). with_content(%r{jira.websudo.is.disabled = false}). with_content(%r{ops.bar.group.size.opsbar-transitions = 4}) end end context 'enable clustering' do let(:params) do { version: '8.13.5', javahome: '/opt/java', datacenter: true, shared_homedir: '/mnt/jira_shared_home_dir' } end it do is_expected.to contain_file('/home/jira/cluster.properties'). with_content(%r{jira.node.id = \S+}). with_content(%r{jira.shared.home = /mnt/jira_shared_home_dir}) end end context 'enable clustering with ehcache options' do let(:params) do { version: '8.13.5', javahome: '/opt/java', datacenter: true, shared_homedir: '/mnt/jira_shared_home_dir', ehcache_listener_host: 'jira.foo.net', ehcache_listener_port: 42, ehcache_object_port: 401 } end it do is_expected.to contain_file('/home/jira/cluster.properties'). with_content(%r{jira.node.id = \S+}). with_content(%r{jira.shared.home = /mnt/jira_shared_home_dir}). with_content(%r{ehcache.listener.hostName = jira.foo.net}). with_content(%r{ehcache.listener.port = 42}). with_content(%r{ehcache.object.port = 401}) end end context 'jira-8.12 - OpenJDK jvm params' do let(:params) do { version: '8.16.0', javahome: '/opt/java', jvm_type: 'openjdk-11' } end it { is_expected.to compile.with_all_deps } it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.16.0-standalone/bin/setenv.sh'). with_content(%r{#DISABLE_NOTIFICATIONS=}). with_content(%r{JVM_SUPPORT_RECOMMENDED_ARGS=''}). with_content(%r{JVM_GC_ARGS='.+ \-XX:\+ExplicitGCInvokesConcurrent}). with_content(%r{JVM_CODE_CACHE_ARGS='\S+InitialCodeCacheSize=32m \S+ReservedCodeCacheSize=512m}). with_content(%r{JVM_REQUIRED_ARGS='.+InterningDocumentFactory}) end it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.16.0-standalone/bin/user.sh') } it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.16.0-standalone/conf/server.xml') } it do is_expected.to contain_file('/home/jira/dbconfig.xml'). with_content(%r{jdbc:postgresql://localhost:5432/jira}). with_content(%r{<schema-name>public</schema-name>}) end it { is_expected.not_to contain_file('/home/jira/cluster.properties') } it { is_expected.not_to contain_file('/opt/jira/atlassian-jira-software-8.16.0-standalone/bin/check-java.sh') } end context 'jira-8.12 - custom jvm params' do let(:params) do { version: '8.16.0', javahome: '/opt/java', java_opts: '-XX:-TEST_OPTIONAL', jvm_gc_args: '-XX:-TEST_GC_ARG', jvm_code_cache_args: '-XX:-TEST_CODECACHE', jvm_extra_args: '-XX:-TEST_EXTRA' } end it { is_expected.to compile.with_all_deps } it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.16.0-standalone/bin/setenv.sh'). with_content(%r{#DISABLE_NOTIFICATIONS=}). with_content(%r{JVM_SUPPORT_RECOMMENDED_ARGS=\S+TEST_OPTIONAL}). with_content(%r{JVM_GC_ARGS=\S+TEST_GC_ARG}). with_content(%r{JVM_CODE_CACHE_ARGS=\S+TEST_CODECACHE}). with_content(%r{JVM_EXTRA_ARGS=\S+TEST_EXTRA}) end it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.16.0-standalone/bin/user.sh') } it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.16.0-standalone/conf/server.xml') } it do is_expected.to contain_file('/home/jira/dbconfig.xml'). with_content(%r{jdbc:postgresql://localhost:5432/jira}). with_content(%r{<schema-name>public</schema-name>}) end it { is_expected.not_to contain_file('/home/jira/cluster.properties') } it { is_expected.not_to contain_file('/opt/jira/atlassian-jira-software-8.16.0-standalone/bin/check-java.sh') } end end end end end end add tests for proxy with native ssl require 'spec_helper.rb' describe 'jira' do describe 'jira::config' do context 'supported operating systems' do on_supported_os.each do |os, facts| context "on #{os}" do let(:facts) do facts end context 'default params' do let(:params) do { javahome: '/opt/java' } end it { is_expected.to compile.with_all_deps } it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/bin/setenv.sh'). with_content(%r{#DISABLE_NOTIFICATIONS=}) end it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/bin/user.sh') } it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml') } # Also ensure that we actually omit elements by default it do is_expected.to contain_file('/home/jira/dbconfig.xml'). with_content(%r{jdbc:postgresql://localhost:5432/jira}). with_content(%r{<schema-name>public</schema-name>}). with_content(%r{<pool-max-size>20}). with_content(%r{<pool-min-size>20}). with_content(%r{<pool-max-wait>30000}). with_content(%r{<pool-max-idle>20}). with_content(%r{<pool-remove-abandoned>true}). with_content(%r{<pool-remove-abandoned-timeout>300}). with_content(%r{<min-evictable-idle-time-millis>60000}). with_content(%r{<time-between-eviction-runs-millis>300000}). with_content(%r{<pool-test-while-idle>true}). with_content(%r{<pool-test-on-borrow>false}). with_content(%r{<validation-query>select version\(\);}). with_content(%r{<connection-properties>tcpKeepAlive=true;socketTimeout=240}) end it { is_expected.not_to contain_file('/home/jira/cluster.properties') } it { is_expected.not_to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/bin/check-java.sh') } end context 'default params with java install' do let(:params) do { javahome: '/usr/lib/jvm/jre-11-openjdk', java_package: 'java-11-openjdk-headless', } end it { is_expected.to compile.with_all_deps } it { is_expected.to contain_package('java-11-openjdk-headless') } end context 'default params with java install and mysql' do let(:params) do { db: 'mysql', javahome: '/usr/lib/jvm/jre-11-openjdk', java_package: 'java-11-openjdk-headless', } end it { is_expected.to compile.with_all_deps } it { is_expected.to contain_package('java-11-openjdk-headless') } it do is_expected.to contain_file('/home/jira/dbconfig.xml'). with_content(%r{<validation-query>select 1</validation-query>}). with_content(%r{<validation-query-timeout>3</validation-query-timeout>}). without_content(%r{<connection-properties>}) end end context 'database settings' do let(:params) do { version: '8.13.5', javahome: '/opt/java', connection_settings: 'TEST-SETTING;', pool_max_size: 200, pool_min_size: 10, validation_query: 'SELECT myfunction();', } end it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/bin/setenv.sh') } it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/bin/user.sh') } it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml') } it do is_expected.to contain_file('/home/jira/dbconfig.xml'). with_content(%r{<connection-properties>TEST-SETTING;</connection-properties>}). with_content(%r{<pool-max-size>200</pool-max-size>}). with_content(%r{<pool-min-size>10</pool-min-size>}). with_content(%r{<validation-query>SELECT myfunction\(\);</validation-query>}) end end context 'mysql params' do let(:params) do { version: '8.13.5', javahome: '/opt/java', db: 'mysql' } end it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/bin/setenv.sh') } it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/bin/user.sh') } it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml') } it do is_expected.to contain_file('/home/jira/dbconfig.xml'). with_content(%r{jdbc:mysql://localhost:3306/jira}) end end context 'oracle params' do let(:params) do { version: '8.13.5', javahome: '/opt/java', db: 'oracle', dbname: 'mydatabase', } end it do is_expected.to contain_file('/home/jira/dbconfig.xml'). with_content(%r{jdbc:oracle:thin:@localhost:1521:mydatabase}). with_content(%r{<database-type>oracle10g}). with_content(%r{<driver-class>oracle.jdbc.OracleDriver}) end end context 'oracle servicename' do let(:params) do { version: '8.13.5', javahome: '/opt/java', db: 'oracle', dbport: 1522, dbserver: 'oracleserver', oracle_use_sid: false, dbname: 'mydatabase', } end it do is_expected.to contain_file('/home/jira/dbconfig.xml'). with_content(%r{jdbc:oracle:thin:@oracleserver:1522/mydatabase}) end end context 'sqlserver params' do let(:params) do { version: '8.13.5', javahome: '/opt/java', db: 'sqlserver', dbport: '1433', dbschema: 'public' } end it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/bin/setenv.sh') } it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/bin/user.sh') } it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml') } it do is_expected.to contain_file('/home/jira/dbconfig.xml'). with_content(%r{<schema-name>public</schema-name>}) end end context 'custom dburl' do let(:params) do { version: '8.13.5', javahome: '/opt/java', dburl: 'my custom dburl' } end it do is_expected.to contain_file('/home/jira/dbconfig.xml'). with_content(%r{<url>my custom dburl</url>}) end end context 'customise tomcat connector' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_port: 9229 } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{<Connector port=\"9229\"\s+relaxedPathChars=}m) end end context 'server.xml listeners' do context 'version greater than 8' do let(:params) do { version: '8.1.0', javahome: '/opt/java' } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.1.0-standalone/conf/server.xml'). with_content(%r{<Listener className=\"org.apache.catalina.core.JreMemoryLeakPreventionListener\"}) end end end context 'customise tomcat connector with a binding address' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_port: 9229, tomcat_address: '127.0.0.1' } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{<Connector port=\"9229\"\s+address=\"127\.0\.0\.1\"\s+relaxedPathChars=}m) end end context 'tomcat context path' do let(:params) do { version: '8.13.5', javahome: '/opt/java', contextpath: '/jira' } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{path="/jira"}) end end context 'tomcat port' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_port: 8888 } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{port="8888"}) end end context 'tomcat acceptCount' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_accept_count: 200 } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{acceptCount="200"}) end end context 'tomcat MaxHttpHeaderSize' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_max_http_header_size: 4096 } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{maxHttpHeaderSize="4096"}) end end context 'tomcat MinSpareThreads' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_min_spare_threads: 50 } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{minSpareThreads="50"}) end end context 'tomcat ConnectionTimeout' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_connection_timeout: 25_000 } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{connectionTimeout="25000"}) end end context 'tomcat EnableLookups' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_enable_lookups: true } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{enableLookups="true"}) end end context 'tomcat Protocol' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_protocol: 'HTTP/1.1' } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{protocol="HTTP/1.1"}) end end context 'tomcat UseBodyEncodingForURI' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_use_body_encoding_for_uri: false } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{useBodyEncodingForURI="false"}) end end context 'tomcat DisableUploadTimeout' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_disable_upload_timeout: false } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{disableUploadTimeout="false"}) end end context 'tomcat EnableLookups' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_enable_lookups: true } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{enableLookups="true"}) end end context 'tomcat maxThreads' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_max_threads: 300 } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{maxThreads="300"}) end end context 'tomcat proxy path' do let(:params) do { version: '8.13.5', javahome: '/opt/java', proxy: { 'scheme' => 'https', 'proxyName' => 'www.example.com', 'proxyPort' => '9999' } } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{proxyName = 'www\.example\.com'}). with_content(%r{scheme = 'https'}). with_content(%r{proxyPort = '9999'}) end end context 'tomcat proxy path native ssl default params' do let(:params) do { version: '8.13.5', javahome: '/opt/java', proxy: { 'scheme' => 'https', 'proxyName' => 'www.example.com', 'proxyPort' => '9999' }, tomcat_native_ssl: true } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{proxyName = 'www\.example\.com'}). with_content(%r{scheme = 'https'}). with_content(%r{proxyPort = '9999'}). with_content(%r{redirectPort="8443"}). with_content(%r{port="8443"}). with_content(%r{keyAlias="jira"}). with_content(%r{keystoreFile="/home/jira/jira.jks"}). with_content(%r{keystorePass="changeit"}). with_content(%r{keystoreType="JKS"}). with_content(%r{port="8443".*acceptCount="100"}m). with_content(%r{port="8443".*maxThreads="150"}m) end end context 'ajp proxy' do context 'with valid config including protocol AJP/1.3' do let(:params) do { version: '8.13.5', javahome: '/opt/java', ajp: { 'port' => '8009', 'protocol' => 'AJP/1.3' } } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{<Connector enableLookups="false" URIEncoding="UTF-8"\s+port = "8009"\s+protocol = "AJP/1.3"\s+/>}) end end context 'with valid config including protocol org.apache.coyote.ajp.AjpNioProtocol' do let(:params) do { version: '8.13.5', javahome: '/opt/java', ajp: { 'port' => '8009', 'protocol' => 'org.apache.coyote.ajp.AjpNioProtocol' } } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{<Connector enableLookups="false" URIEncoding="UTF-8"\s+port = "8009"\s+protocol = "org.apache.coyote.ajp.AjpNioProtocol"\s+/>}) end end end context 'tomcat additional connectors, without default' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_default_connector: false, tomcat_additional_connectors: { 8081 => { 'URIEncoding' => 'UTF-8', 'connectionTimeout' => '20000', 'protocol' => 'HTTP/1.1', 'proxyName' => 'foo.example.com', 'proxyPort' => '8123', 'secure' => true, 'scheme' => 'https' }, 8082 => { 'URIEncoding' => 'UTF-8', 'connectionTimeout' => '20000', 'protocol' => 'HTTP/1.1', 'proxyName' => 'bar.example.com', 'proxyPort' => '8124', 'scheme' => 'http' } } } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). without_content(%r{<Connector port="8080"}). with_content(%r{<Connector port="8081"}). with_content(%r{connectionTimeout="20000"}). with_content(%r{protocol="HTTP/1\.1"}). with_content(%r{proxyName="foo\.example\.com"}). with_content(%r{proxyPort="8123"}). with_content(%r{scheme="https"}). with_content(%r{secure="true"}). with_content(%r{URIEncoding="UTF-8"}). with_content(%r{<Connector port="8082"}). with_content(%r{connectionTimeout="20000"}). with_content(%r{protocol="HTTP/1\.1"}). with_content(%r{proxyName="bar\.example\.com"}). with_content(%r{proxyPort="8124"}). with_content(%r{scheme="http"}). with_content(%r{URIEncoding="UTF-8"}) end end context 'tomcat access log format' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_accesslog_format: '%a %{jira.request.id}r %{jira.request.username}r %t %I' } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{pattern="%a %{jira.request.id}r %{jira.request.username}r %t %I"/>}) end end context 'tomcat access log format with x-forward-for handling' do let(:params) do { version: '8.16.0', javahome: '/opt/java', tomcat_accesslog_enable_xforwarded_for: true, } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.16.0-standalone/conf/server.xml'). with_content(%r{org.apache.catalina.valves.RemoteIpValve}). with_content(%r{requestAttributesEnabled="true"}) end end context 'with script_check_java_managed enabled' do let(:params) do { script_check_java_manage: true, version: '8.1.0', javahome: '/opt/java' } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.1.0-standalone/bin/check-java.sh'). with_content(%r{Wrong JVM version}) end end context 'context resources' do let(:params) do { version: '8.13.5', javahome: '/opt/java', resources: { 'testdb' => { 'auth' => 'Container' } } } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/context.xml'). with_content(%r{<Resource name = "testdb"\n auth = "Container"\n />}) end end context 'disable notifications' do let(:params) do { version: '8.13.5', javahome: '/opt/java', disable_notifications: true } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/bin/setenv.sh'). with_content(%r{^DISABLE_NOTIFICATIONS=}) end end context 'native ssl support default params' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_native_ssl: true } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{redirectPort="8443"}). with_content(%r{port="8443"}). with_content(%r{keyAlias="jira"}). with_content(%r{keystoreFile="/home/jira/jira.jks"}). with_content(%r{keystorePass="changeit"}). with_content(%r{keystoreType="JKS"}). with_content(%r{port="8443".*acceptCount="100"}m). with_content(%r{port="8443".*maxThreads="150"}m) end end context 'native ssl support custom params' do let(:params) do { version: '8.13.5', javahome: '/opt/java', tomcat_native_ssl: true, tomcat_https_port: 9443, tomcat_address: '127.0.0.1', tomcat_max_threads: 600, tomcat_accept_count: 600, tomcat_key_alias: 'keystorealias', tomcat_keystore_file: '/tmp/keyfile.ks', tomcat_keystore_pass: 'keystorepass', tomcat_keystore_type: 'PKCS12' } end it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.13.5-standalone/conf/server.xml'). with_content(%r{redirectPort="9443"}). with_content(%r{port="9443"}). with_content(%r{keyAlias="keystorealias"}). with_content(%r{keystoreFile="/tmp/keyfile.ks"}). with_content(%r{keystorePass="keystorepass"}). with_content(%r{keystoreType="PKCS12"}). with_content(%r{port="9443".*acceptCount="600"}m). with_content(%r{port="9443".*maxThreads="600"}m). with_content(%r{port="9443".*address="127\.0\.0\.1"}m) end end context 'enable secure admin sessions' do let(:params) do { version: '8.13.5', javahome: '/opt/java', enable_secure_admin_sessions: true } end it do is_expected.to contain_file('/home/jira/jira-config.properties'). with_content(%r{jira.websudo.is.disabled = false}) end end context 'disable secure admin sessions' do let(:params) do { version: '8.13.5', javahome: '/opt/java', enable_secure_admin_sessions: false } end it do is_expected.to contain_file('/home/jira/jira-config.properties'). with_content(%r{jira.websudo.is.disabled = true}) end end context 'jira-config.properties' do let(:params) do { version: '8.13.5', javahome: '/opt/java', jira_config_properties: { 'ops.bar.group.size.opsbar-transitions' => '4' } } end it do is_expected.to contain_file('/home/jira/jira-config.properties'). with_content(%r{jira.websudo.is.disabled = false}). with_content(%r{ops.bar.group.size.opsbar-transitions = 4}) end end context 'enable clustering' do let(:params) do { version: '8.13.5', javahome: '/opt/java', datacenter: true, shared_homedir: '/mnt/jira_shared_home_dir' } end it do is_expected.to contain_file('/home/jira/cluster.properties'). with_content(%r{jira.node.id = \S+}). with_content(%r{jira.shared.home = /mnt/jira_shared_home_dir}) end end context 'enable clustering with ehcache options' do let(:params) do { version: '8.13.5', javahome: '/opt/java', datacenter: true, shared_homedir: '/mnt/jira_shared_home_dir', ehcache_listener_host: 'jira.foo.net', ehcache_listener_port: 42, ehcache_object_port: 401 } end it do is_expected.to contain_file('/home/jira/cluster.properties'). with_content(%r{jira.node.id = \S+}). with_content(%r{jira.shared.home = /mnt/jira_shared_home_dir}). with_content(%r{ehcache.listener.hostName = jira.foo.net}). with_content(%r{ehcache.listener.port = 42}). with_content(%r{ehcache.object.port = 401}) end end context 'jira-8.12 - OpenJDK jvm params' do let(:params) do { version: '8.16.0', javahome: '/opt/java', jvm_type: 'openjdk-11' } end it { is_expected.to compile.with_all_deps } it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.16.0-standalone/bin/setenv.sh'). with_content(%r{#DISABLE_NOTIFICATIONS=}). with_content(%r{JVM_SUPPORT_RECOMMENDED_ARGS=''}). with_content(%r{JVM_GC_ARGS='.+ \-XX:\+ExplicitGCInvokesConcurrent}). with_content(%r{JVM_CODE_CACHE_ARGS='\S+InitialCodeCacheSize=32m \S+ReservedCodeCacheSize=512m}). with_content(%r{JVM_REQUIRED_ARGS='.+InterningDocumentFactory}) end it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.16.0-standalone/bin/user.sh') } it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.16.0-standalone/conf/server.xml') } it do is_expected.to contain_file('/home/jira/dbconfig.xml'). with_content(%r{jdbc:postgresql://localhost:5432/jira}). with_content(%r{<schema-name>public</schema-name>}) end it { is_expected.not_to contain_file('/home/jira/cluster.properties') } it { is_expected.not_to contain_file('/opt/jira/atlassian-jira-software-8.16.0-standalone/bin/check-java.sh') } end context 'jira-8.12 - custom jvm params' do let(:params) do { version: '8.16.0', javahome: '/opt/java', java_opts: '-XX:-TEST_OPTIONAL', jvm_gc_args: '-XX:-TEST_GC_ARG', jvm_code_cache_args: '-XX:-TEST_CODECACHE', jvm_extra_args: '-XX:-TEST_EXTRA' } end it { is_expected.to compile.with_all_deps } it do is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.16.0-standalone/bin/setenv.sh'). with_content(%r{#DISABLE_NOTIFICATIONS=}). with_content(%r{JVM_SUPPORT_RECOMMENDED_ARGS=\S+TEST_OPTIONAL}). with_content(%r{JVM_GC_ARGS=\S+TEST_GC_ARG}). with_content(%r{JVM_CODE_CACHE_ARGS=\S+TEST_CODECACHE}). with_content(%r{JVM_EXTRA_ARGS=\S+TEST_EXTRA}) end it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.16.0-standalone/bin/user.sh') } it { is_expected.to contain_file('/opt/jira/atlassian-jira-software-8.16.0-standalone/conf/server.xml') } it do is_expected.to contain_file('/home/jira/dbconfig.xml'). with_content(%r{jdbc:postgresql://localhost:5432/jira}). with_content(%r{<schema-name>public</schema-name>}) end it { is_expected.not_to contain_file('/home/jira/cluster.properties') } it { is_expected.not_to contain_file('/opt/jira/atlassian-jira-software-8.16.0-standalone/bin/check-java.sh') } end end end end end end
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "wisepdf" s.version = "1.1.2" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Igor Alexandrov"] s.date = "2012-04-27" s.description = "wisepdf uses the shell utility wkhtmltopdf to serve a PDF file to a user from HTML. In other words, rather than dealing with a PDF generation DSL of some sort, you simply write an HTML view as you would normally, and let pdf take care of the hard stuff." s.email = "igor.alexandrov@gmail.com" s.extra_rdoc_files = [ "README.md" ] s.files = [ ".travis.yml", "Gemfile", "Gemfile.lock", "MIT-LICENSE", "README.md", "Rakefile", "VERSION", "generators/wisepdf/templates/configure_wisepdf.rb", "generators/wisepdf/wisepdf_generator.rb", "lib/generators/wisepdf_generator.rb", "lib/wisepdf.rb", "lib/wisepdf/configuration.rb", "lib/wisepdf/errors.rb", "lib/wisepdf/helper.rb", "lib/wisepdf/rails.rb", "lib/wisepdf/rails/engine.rb", "lib/wisepdf/rails/legacy.rb", "lib/wisepdf/rails/railtie.rb", "lib/wisepdf/render.rb", "lib/wisepdf/tempfile.rb", "lib/wisepdf/writer.rb", "pdf.gemspec", "test/application_controller_test.rb", "test/dummy/README.rdoc", "test/dummy/Rakefile", "test/dummy/app/assets/javascripts/application.js", "test/dummy/app/assets/javascripts/wisepdf.js", "test/dummy/app/assets/stylesheets/application.css", "test/dummy/app/assets/stylesheets/wisepdf.css", "test/dummy/app/controllers/application_controller.rb", "test/dummy/app/helpers/application_helper.rb", "test/dummy/app/mailers/.gitkeep", "test/dummy/app/models/.gitkeep", "test/dummy/app/views/layouts/application.html.erb", "test/dummy/config.ru", "test/dummy/config/application.rb", "test/dummy/config/boot.rb", "test/dummy/config/database.yml", "test/dummy/config/environment.rb", "test/dummy/config/environments/development.rb", "test/dummy/config/environments/production.rb", "test/dummy/config/environments/test.rb", "test/dummy/config/initializers/backtrace_silencers.rb", "test/dummy/config/initializers/inflections.rb", "test/dummy/config/initializers/mime_types.rb", "test/dummy/config/initializers/secret_token.rb", "test/dummy/config/initializers/session_store.rb", "test/dummy/config/initializers/wrap_parameters.rb", "test/dummy/config/locales/en.yml", "test/dummy/config/routes.rb", "test/dummy/lib/assets/.gitkeep", "test/dummy/log/.gitkeep", "test/dummy/public/404.html", "test/dummy/public/422.html", "test/dummy/public/500.html", "test/dummy/public/favicon.ico", "test/dummy/public/javascripts/wisepdf.js", "test/dummy/public/stylesheets/wisepdf.css", "test/dummy/script/rails", "test/dummy/tmp/cache/assets/CA9/590/sprockets%2F260d19b0714b39b217abfe83309458b7", "test/dummy/tmp/cache/assets/D13/4A0/sprockets%2Fc857f4fea90e731182fa7000ea6833e9", "test/dummy/tmp/cache/assets/D1C/0F0/sprockets%2F13dc05c787589dd73a669e0ad23d54e8", "test/dummy/tmp/cache/assets/D6E/B20/sprockets%2F2669d77f5dd55e82ba092accac21871a", "test/dummy/tmp/cache/assets/D93/BA0/sprockets%2Fe162e2a148480db4edf41c7ca8a527cb", "test/dummy/tmp/cache/assets/E1B/1A0/sprockets%2Fbdc3a3ccd7d2f02dddd41712ed4c8e31", "test/helper.rb", "test/helper_assets_test.rb", "test/helper_legacy_test.rb", "test/writer_test.rb", "wisepdf.gemspec" ] s.homepage = "http://github.com/igor-alexandrov/wisepdf" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = "1.8.15" s.summary = "wkhtmltopdf for Rails done right" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<rails>, [">= 3.0.0"]) s.add_development_dependency(%q<sqlite3>, [">= 0"]) s.add_development_dependency(%q<wkhtmltopdf-binary>, [">= 0"]) s.add_development_dependency(%q<shoulda>, [">= 0"]) s.add_development_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.6.4"]) else s.add_dependency(%q<rails>, [">= 3.0.0"]) s.add_dependency(%q<sqlite3>, [">= 0"]) s.add_dependency(%q<wkhtmltopdf-binary>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.6.4"]) end else s.add_dependency(%q<rails>, [">= 3.0.0"]) s.add_dependency(%q<sqlite3>, [">= 0"]) s.add_dependency(%q<wkhtmltopdf-binary>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.6.4"]) end end Regenerate gemspec for version 1.1.3 # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "wisepdf" s.version = "1.1.3" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Igor Alexandrov"] s.date = "2012-04-27" s.description = "wisepdf uses the shell utility wkhtmltopdf to serve a PDF file to a user from HTML. In other words, rather than dealing with a PDF generation DSL of some sort, you simply write an HTML view as you would normally, and let pdf take care of the hard stuff." s.email = "igor.alexandrov@gmail.com" s.extra_rdoc_files = [ "README.md" ] s.files = [ ".travis.yml", "Gemfile", "Gemfile.lock", "MIT-LICENSE", "README.md", "Rakefile", "VERSION", "generators/wisepdf/templates/configure_wisepdf.rb", "generators/wisepdf/wisepdf_generator.rb", "lib/generators/wisepdf_generator.rb", "lib/wisepdf.rb", "lib/wisepdf/configuration.rb", "lib/wisepdf/errors.rb", "lib/wisepdf/helper.rb", "lib/wisepdf/rails.rb", "lib/wisepdf/rails/engine.rb", "lib/wisepdf/rails/legacy.rb", "lib/wisepdf/rails/railtie.rb", "lib/wisepdf/render.rb", "lib/wisepdf/tempfile.rb", "lib/wisepdf/writer.rb", "pdf.gemspec", "test/application_controller_test.rb", "test/dummy/README.rdoc", "test/dummy/Rakefile", "test/dummy/app/assets/javascripts/application.js", "test/dummy/app/assets/javascripts/wisepdf.js", "test/dummy/app/assets/stylesheets/application.css", "test/dummy/app/assets/stylesheets/wisepdf.css", "test/dummy/app/controllers/application_controller.rb", "test/dummy/app/helpers/application_helper.rb", "test/dummy/app/mailers/.gitkeep", "test/dummy/app/models/.gitkeep", "test/dummy/app/views/layouts/application.html.erb", "test/dummy/config.ru", "test/dummy/config/application.rb", "test/dummy/config/boot.rb", "test/dummy/config/database.yml", "test/dummy/config/environment.rb", "test/dummy/config/environments/development.rb", "test/dummy/config/environments/production.rb", "test/dummy/config/environments/test.rb", "test/dummy/config/initializers/backtrace_silencers.rb", "test/dummy/config/initializers/inflections.rb", "test/dummy/config/initializers/mime_types.rb", "test/dummy/config/initializers/secret_token.rb", "test/dummy/config/initializers/session_store.rb", "test/dummy/config/initializers/wrap_parameters.rb", "test/dummy/config/locales/en.yml", "test/dummy/config/routes.rb", "test/dummy/lib/assets/.gitkeep", "test/dummy/log/.gitkeep", "test/dummy/public/404.html", "test/dummy/public/422.html", "test/dummy/public/500.html", "test/dummy/public/favicon.ico", "test/dummy/public/javascripts/wisepdf.js", "test/dummy/public/stylesheets/wisepdf.css", "test/dummy/script/rails", "test/dummy/tmp/cache/assets/CA9/590/sprockets%2F260d19b0714b39b217abfe83309458b7", "test/dummy/tmp/cache/assets/D13/4A0/sprockets%2Fc857f4fea90e731182fa7000ea6833e9", "test/dummy/tmp/cache/assets/D1C/0F0/sprockets%2F13dc05c787589dd73a669e0ad23d54e8", "test/dummy/tmp/cache/assets/D6E/B20/sprockets%2F2669d77f5dd55e82ba092accac21871a", "test/dummy/tmp/cache/assets/D93/BA0/sprockets%2Fe162e2a148480db4edf41c7ca8a527cb", "test/dummy/tmp/cache/assets/E1B/1A0/sprockets%2Fbdc3a3ccd7d2f02dddd41712ed4c8e31", "test/helper.rb", "test/helper_assets_test.rb", "test/helper_legacy_test.rb", "test/writer_test.rb", "wisepdf.gemspec" ] s.homepage = "http://github.com/igor-alexandrov/wisepdf" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = "1.8.15" s.summary = "wkhtmltopdf for Rails done right" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<rails>, [">= 3.0.0"]) s.add_development_dependency(%q<sqlite3>, [">= 0"]) s.add_development_dependency(%q<wkhtmltopdf-binary>, [">= 0"]) s.add_development_dependency(%q<shoulda>, [">= 0"]) s.add_development_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.6.4"]) else s.add_dependency(%q<rails>, [">= 3.0.0"]) s.add_dependency(%q<sqlite3>, [">= 0"]) s.add_dependency(%q<wkhtmltopdf-binary>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.6.4"]) end else s.add_dependency(%q<rails>, [">= 3.0.0"]) s.add_dependency(%q<sqlite3>, [">= 0"]) s.add_dependency(%q<wkhtmltopdf-binary>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.6.4"]) end end
module MiqAeDatastore XML_VERSION = "1.0" XML_VERSION_MIN_SUPPORTED = "1.0" MANAGEIQ_DOMAIN = "ManageIQ" MANAGEIQ_PRIORITY = 0 DATASTORE_DIRECTORY = Rails.root.join('db/fixtures/ae_datastore') DEFAULT_OBJECT_NAMESPACE = "$" TEMP_DOMAIN_PREFIX = "TEMP_DOMAIN" ALL_DOMAINS = "*" # deprecated module module Import def self.load_xml(xml, domain = MiqAeDatastore.temp_domain) MiqAeDatastore.xml_deprecated_warning XmlImport.load_xml(xml, domain) end end TMP_DIR = File.expand_path(File.join(Rails.root, "tmp/miq_automate_engine")) def self.temp_domain "#{TEMP_DOMAIN_PREFIX}-#{MiqUUID.new_guid}" end def self.xml_deprecated_warning msg = "[DEPRECATION] xml export/import is deprecated. Please use the YAML format instead. At #{caller[1]}" $log.warn msg warn msg end def self.default_backup_filename "datastore_#{format_timezone(Time.now, Time.zone, "fname")}.zip" end def self.backup(options) options['zip_file'] ||= default_backup_filename export_options = options.slice('zip_file', 'overwrite') MiqAeExport.new(ALL_DOMAINS, export_options).export end def self.convert(filename, domain_name = temp_domain, export_options = {}) if export_options['zip_file'].blank? && export_options['export_dir'].blank? && export_options['yaml_file'].blank? export_options['export_dir'] = TMP_DIR end File.open(filename, 'r') do |handle| XmlYamlConverter.convert(handle, domain_name, export_options) end end def self.upload(fd, name = nil, domain_name = ALL_DOMAINS) name ||= fd.original_filename ext = File.extname(name) basename = File.basename(name, ext) name = "#{basename}.zip" block_size = 65_536 FileUtils.mkdir_p(TMP_DIR) unless File.directory?(TMP_DIR) filename = File.join(TMP_DIR, name) $log.info("MIQ(MiqAeDatastore) Uploading Datastore Import to file <#{filename}>") if $log outfd = File.open(filename, "wb") data = fd.read(block_size) until fd.eof outfd.write(data) data = fd.read(block_size) end outfd.write(data) if data fd.close outfd.close $log.info("MIQ(MiqAeDatastore) Upload complete (size=#{File.size(filename)})") if $log begin import_yaml_zip(filename, domain_name) ensure File.delete(filename) end end def self.import(fname, domain = temp_domain) _, t = Benchmark.realtime_block(:total_time) { XmlImport.load_file(fname, domain) } $log.info("MIQ(MiqAeDatastore.import) Import #{fname}...Complete - Benchmark: #{t.inspect}") end def self.restore(fname) $log.info("MIQ(MiqAeDatastore.restore) Restore from #{fname}...Starting") MiqAeDatastore.reset MiqAeImport.new(ALL_DOMAINS, 'zip_file' => fname, 'preview' => false, 'restore' => true).import $log.info("MIQ(MiqAeDatastore.restore) Restore from #{fname}...Complete") end def self.import_yaml_zip(fname, domain) t = Benchmark.realtime_block(:total_time) do import_options = {'zip_file' => fname, 'preview' => false, 'mode' => 'add'} MiqAeImport.new(domain, import_options).import end $log.info("MIQ(MiqAeDatastore.import) Import #{fname}...Complete - Benchmark: #{t.inspect}") end def self.import_yaml_dir(dirname, domain) t = Benchmark.realtime_block(:total_time) do import_options = {'import_dir' => dirname, 'preview' => false, 'mode' => 'add', 'restore' => true} MiqAeImport.new(domain, import_options).import end $log.info("MIQ(MiqAeDatastore.import) Import from #{dirname}...Complete - Benchmark: #{t.inspect}") end def self.export require 'tempfile' temp_export = Tempfile.new('ae_export') MiqAeDatastore.backup('zip_file' => temp_export.path, 'overwrite' => true) File.read(temp_export.path) ensure temp_export.close temp_export.unlink end def self.export_class(ns, class_name) XmlExport.class_to_xml(ns, class_name) end def self.export_namespace(ns) XmlExport.namespace_to_xml(ns) end def self.reset $log.info("MIQ(MiqAeDatastore) Clearing datastore") if $log [MiqAeClass, MiqAeField, MiqAeInstance, MiqAeNamespace, MiqAeMethod, MiqAeValue].each(&:delete_all) end def self.reset_default_namespace ns = MiqAeNamespace.find_by_fqname(DEFAULT_OBJECT_NAMESPACE) ns.destroy if ns seed_default_namespace end def self.reset_domain(datastore_dir, domain_name) $log.info("MIQ(MiqAeDatastore) Resetting domain #{domain_name} from #{datastore_dir}") if $log ns = MiqAeDomain.find_by_fqname(domain_name) ns.destroy if ns import_yaml_dir(datastore_dir, domain_name) if domain_name.downcase == MANAGEIQ_DOMAIN.downcase ns = MiqAeDomain.find_by_fqname(MANAGEIQ_DOMAIN) ns.update_attributes!(:system => true, :enabled => true, :priority => MANAGEIQ_PRIORITY) if ns end end def self.reset_manageiq_domain reset_domain(DATASTORE_DIRECTORY, MANAGEIQ_DOMAIN) end def self.seed_default_namespace default_ns = MiqAeNamespace.create!(:name => DEFAULT_OBJECT_NAMESPACE) object_class = default_ns.ae_classes.create!(:name => 'Object') default_method_options = {:language => 'ruby', :scope => 'instance', :location => 'builtin'} object_class.ae_methods.create!(default_method_options.merge(:name => 'log_object')) object_class.ae_methods.create!(default_method_options.merge(:name => 'log_workspace')) email_method = object_class.ae_methods.create!(default_method_options.merge(:name => 'send_email')) email_method.inputs.build([{:name => 'to', :priority => 1, :datatype => 'string'}, {:name => 'from', :priority => 2, :datatype => 'string'}, {:name => 'subject', :priority => 3, :datatype => 'string'}, {:name => 'body', :priority => 4, :datatype => 'string'}]) email_method.save! end def self.reset_to_defaults raise "Datastore directory [#{DATASTORE_DIRECTORY}] not found" unless Dir.exist?(DATASTORE_DIRECTORY) Dir.glob(DATASTORE_DIRECTORY.join("*", MiqAeDomain::DOMAIN_YAML_FILENAME)).each do |domain_file| domain_name = File.basename(File.dirname(domain_file)) reset_domain(DATASTORE_DIRECTORY, domain_name) end reset_default_namespace end def self.seed MiqRegion.my_region.lock(:shared, 1800) do log_prefix = 'MIQ(MiqAeDatastore.seed)' ns = MiqAeDomain.find_by_fqname(MANAGEIQ_DOMAIN) unless ns $log.info "#{log_prefix} Seeding ManageIQ domain..." if $log begin reset_to_defaults rescue => err $log.error "#{log_prefix} Seeding... Reset failed, #{err.message}" if $log else $log.info "#{log_prefix} Seeding... Complete" if $log end end end end def self.get_homonymic_across_domains(arclass, fqname, enabled = nil) return [] if fqname.blank? options = arclass == ::MiqAeClass ? {:has_instance_name => false} : {} _, ns, klass, name = ::MiqAeEngine::MiqAePath.get_domain_ns_klass_inst(fqname, options) name = klass if arclass == ::MiqAeClass MiqAeDatastore.get_sorted_matching_objects(arclass, ns, klass, name, enabled) end def self.get_sorted_matching_objects(arclass, ns, klass, name, enabled) options = arclass == ::MiqAeClass ? {:has_instance_name => false} : {} matches = arclass.where("lower(name) = ?", name.downcase).collect do |obj| get_domain_priority_object(obj, klass, ns, enabled, options) end.compact matches.sort { |a, b| b[:priority] <=> a[:priority] }.collect { |v| v[:obj] } end def self.get_domain_priority_object(obj, klass, ns, enabled, options) domain, nsd, klass_name, _ = ::MiqAeEngine::MiqAePath.get_domain_ns_klass_inst(obj.fqname, options) return if !klass_name.casecmp(klass).zero? || !nsd.casecmp(ns).zero? domain_obj = get_domain_object(domain, enabled) {:obj => obj, :priority => domain_obj.priority} if domain_obj end def self.get_domain_object(name, enabled) arel = MiqAeDomain.where("lower(name) = ?", name.downcase) arel = arel.where(:enabled => enabled) unless enabled.nil? arel.first end end # module MiqAeDatastore Preserve & set the priority,enabled,system of domains after db reset https://bugzilla.redhat.com/show_bug.cgi?id=1200925 module MiqAeDatastore XML_VERSION = "1.0" XML_VERSION_MIN_SUPPORTED = "1.0" MANAGEIQ_DOMAIN = "ManageIQ" MANAGEIQ_PRIORITY = 0 DATASTORE_DIRECTORY = Rails.root.join('db/fixtures/ae_datastore') DEFAULT_OBJECT_NAMESPACE = "$" TEMP_DOMAIN_PREFIX = "TEMP_DOMAIN" ALL_DOMAINS = "*" PRESERVED_ATTRS = [:priority, :enabled, :system] # deprecated module module Import def self.load_xml(xml, domain = MiqAeDatastore.temp_domain) MiqAeDatastore.xml_deprecated_warning XmlImport.load_xml(xml, domain) end end TMP_DIR = File.expand_path(File.join(Rails.root, "tmp/miq_automate_engine")) def self.temp_domain "#{TEMP_DOMAIN_PREFIX}-#{MiqUUID.new_guid}" end def self.xml_deprecated_warning msg = "[DEPRECATION] xml export/import is deprecated. Please use the YAML format instead. At #{caller[1]}" $log.warn msg warn msg end def self.default_backup_filename "datastore_#{format_timezone(Time.now, Time.zone, "fname")}.zip" end def self.backup(options) options['zip_file'] ||= default_backup_filename export_options = options.slice('zip_file', 'overwrite') MiqAeExport.new(ALL_DOMAINS, export_options).export end def self.convert(filename, domain_name = temp_domain, export_options = {}) if export_options['zip_file'].blank? && export_options['export_dir'].blank? && export_options['yaml_file'].blank? export_options['export_dir'] = TMP_DIR end File.open(filename, 'r') do |handle| XmlYamlConverter.convert(handle, domain_name, export_options) end end def self.upload(fd, name = nil, domain_name = ALL_DOMAINS) name ||= fd.original_filename ext = File.extname(name) basename = File.basename(name, ext) name = "#{basename}.zip" block_size = 65_536 FileUtils.mkdir_p(TMP_DIR) unless File.directory?(TMP_DIR) filename = File.join(TMP_DIR, name) $log.info("MIQ(MiqAeDatastore) Uploading Datastore Import to file <#{filename}>") if $log outfd = File.open(filename, "wb") data = fd.read(block_size) until fd.eof outfd.write(data) data = fd.read(block_size) end outfd.write(data) if data fd.close outfd.close $log.info("MIQ(MiqAeDatastore) Upload complete (size=#{File.size(filename)})") if $log begin import_yaml_zip(filename, domain_name) ensure File.delete(filename) end end def self.import(fname, domain = temp_domain) _, t = Benchmark.realtime_block(:total_time) { XmlImport.load_file(fname, domain) } $log.info("MIQ(MiqAeDatastore.import) Import #{fname}...Complete - Benchmark: #{t.inspect}") end def self.restore(fname) $log.info("MIQ(MiqAeDatastore.restore) Restore from #{fname}...Starting") MiqAeDatastore.reset MiqAeImport.new(ALL_DOMAINS, 'zip_file' => fname, 'preview' => false, 'restore' => true).import $log.info("MIQ(MiqAeDatastore.restore) Restore from #{fname}...Complete") end def self.import_yaml_zip(fname, domain) t = Benchmark.realtime_block(:total_time) do import_options = {'zip_file' => fname, 'preview' => false, 'mode' => 'add'} MiqAeImport.new(domain, import_options).import end $log.info("MIQ(MiqAeDatastore.import) Import #{fname}...Complete - Benchmark: #{t.inspect}") end def self.import_yaml_dir(dirname, domain) t = Benchmark.realtime_block(:total_time) do import_options = {'import_dir' => dirname, 'preview' => false, 'mode' => 'add', 'restore' => true} MiqAeImport.new(domain, import_options).import end $log.info("MIQ(MiqAeDatastore.import) Import from #{dirname}...Complete - Benchmark: #{t.inspect}") end def self.export require 'tempfile' temp_export = Tempfile.new('ae_export') MiqAeDatastore.backup('zip_file' => temp_export.path, 'overwrite' => true) File.read(temp_export.path) ensure temp_export.close temp_export.unlink end def self.export_class(ns, class_name) XmlExport.class_to_xml(ns, class_name) end def self.export_namespace(ns) XmlExport.namespace_to_xml(ns) end def self.reset $log.info("MIQ(MiqAeDatastore) Clearing datastore") if $log [MiqAeClass, MiqAeField, MiqAeInstance, MiqAeNamespace, MiqAeMethod, MiqAeValue].each(&:delete_all) end def self.reset_default_namespace ns = MiqAeNamespace.find_by_fqname(DEFAULT_OBJECT_NAMESPACE) ns.destroy if ns seed_default_namespace end def self.reset_domain(datastore_dir, domain_name) $log.info("MIQ(MiqAeDatastore) Resetting domain #{domain_name} from #{datastore_dir}") if $log ns = MiqAeDomain.find_by_fqname(domain_name) ns.destroy if ns import_yaml_dir(datastore_dir, domain_name) if domain_name.downcase == MANAGEIQ_DOMAIN.downcase ns = MiqAeDomain.find_by_fqname(MANAGEIQ_DOMAIN) ns.update_attributes!(:system => true, :enabled => true, :priority => MANAGEIQ_PRIORITY) if ns end end def self.reset_manageiq_domain reset_domain(DATASTORE_DIRECTORY, MANAGEIQ_DOMAIN) end def self.seed_default_namespace default_ns = MiqAeNamespace.create!(:name => DEFAULT_OBJECT_NAMESPACE) object_class = default_ns.ae_classes.create!(:name => 'Object') default_method_options = {:language => 'ruby', :scope => 'instance', :location => 'builtin'} object_class.ae_methods.create!(default_method_options.merge(:name => 'log_object')) object_class.ae_methods.create!(default_method_options.merge(:name => 'log_workspace')) email_method = object_class.ae_methods.create!(default_method_options.merge(:name => 'send_email')) email_method.inputs.build([{:name => 'to', :priority => 1, :datatype => 'string'}, {:name => 'from', :priority => 2, :datatype => 'string'}, {:name => 'subject', :priority => 3, :datatype => 'string'}, {:name => 'body', :priority => 4, :datatype => 'string'}]) email_method.save! end def self.reset_to_defaults raise "Datastore directory [#{DATASTORE_DIRECTORY}] not found" unless Dir.exist?(DATASTORE_DIRECTORY) saved_attrs = preserved_attrs_for_domains Dir.glob(DATASTORE_DIRECTORY.join("*", MiqAeDomain::DOMAIN_YAML_FILENAME)).each do |domain_file| domain_name = File.basename(File.dirname(domain_file)) reset_domain(DATASTORE_DIRECTORY, domain_name) end saved_attrs.each { |dom, attrs| MiqAeDomain.find_by_fqname(dom).update_attributes(attrs) } reset_default_namespace end def self.seed MiqRegion.my_region.lock(:shared, 1800) do log_prefix = 'MIQ(MiqAeDatastore.seed)' ns = MiqAeDomain.find_by_fqname(MANAGEIQ_DOMAIN) unless ns $log.info "#{log_prefix} Seeding ManageIQ domain..." if $log begin reset_to_defaults rescue => err $log.error "#{log_prefix} Seeding... Reset failed, #{err.message}" if $log else $log.info "#{log_prefix} Seeding... Complete" if $log end end end end def self.get_homonymic_across_domains(arclass, fqname, enabled = nil) return [] if fqname.blank? options = arclass == ::MiqAeClass ? {:has_instance_name => false} : {} _, ns, klass, name = ::MiqAeEngine::MiqAePath.get_domain_ns_klass_inst(fqname, options) name = klass if arclass == ::MiqAeClass MiqAeDatastore.get_sorted_matching_objects(arclass, ns, klass, name, enabled) end def self.get_sorted_matching_objects(arclass, ns, klass, name, enabled) options = arclass == ::MiqAeClass ? {:has_instance_name => false} : {} matches = arclass.where("lower(name) = ?", name.downcase).collect do |obj| get_domain_priority_object(obj, klass, ns, enabled, options) end.compact matches.sort { |a, b| b[:priority] <=> a[:priority] }.collect { |v| v[:obj] } end def self.get_domain_priority_object(obj, klass, ns, enabled, options) domain, nsd, klass_name, _ = ::MiqAeEngine::MiqAePath.get_domain_ns_klass_inst(obj.fqname, options) return if !klass_name.casecmp(klass).zero? || !nsd.casecmp(ns).zero? domain_obj = get_domain_object(domain, enabled) {:obj => obj, :priority => domain_obj.priority} if domain_obj end def self.get_domain_object(name, enabled) arel = MiqAeDomain.where("lower(name) = ?", name.downcase) arel = arel.where(:enabled => enabled) unless enabled.nil? arel.first end def self.preserved_attrs_for_domains MiqAeDomain.all.each_with_object({}) do |dom, h| next if dom.name.downcase == MANAGEIQ_DOMAIN.downcase h[dom.name] = PRESERVED_ATTRS.each_with_object({}) { |attr, ih| ih[attr] = dom[attr] } end end end # module MiqAeDatastore
require_relative '../../spec_helper' RSpec.describe Languages::Ruby::ClassRuby do before :all do @classRuby = Languages::Ruby::ClassRuby.new end context "When is class without inheritance" do it "Ordinary class declaration." do classNameCaptured = @classRuby.get_class("class Xpto").name expect(classNameCaptured).to eq("Xpto") end it "Class declaration with whitespace." do classNameCaptured = @classRuby.get_class(" class Xpto").name expect(classNameCaptured).to eq("Xpto") end it "Class declaration between whitespace." do classNameCaptured = @classRuby.get_class(" class Xpto ").name expect(classNameCaptured).to eq("Xpto") end it "Class declaration with whitespace in the beginning." do classNameCaptured = @classRuby.get_class(" class Xpto").name expect(classNameCaptured).to eq("Xpto") end it "Class declaration with whitespace in the end." do classNameCaptured = @classRuby.get_class("class Xpto ").name expect(classNameCaptured).to eq("Xpto") end it "Class declaration delimited by whitespace." do classNameCaptured = @classRuby.get_class(" class Xpto ").name expect(classNameCaptured).to eq("Xpto") end it "Class declaration with a few whitespace." do classNameCaptured = @classRuby.get_class(" class Xpto ").name expect(classNameCaptured).to eq("Xpto") end it "Class declaration with whitespace in the beginning." do classNameCaptured = @classRuby.get_class(" class Xpto").name expect(classNameCaptured).to eq("Xpto") end it "Class declaration ended with whitespace." do classNameCaptured = @classRuby.get_class("class Xpto ").name expect(classNameCaptured).to eq("Xpto") end it "Class declaration with many whitespace." do classNameCaptured = @classRuby.get_class(" class Xpto ").name expect(classNameCaptured).to eq("Xpto") end it "Class declaration with tab." do classNameCaptured = @classRuby.get_class(" class Xpto ").name expect(classNameCaptured).to eq("Xpto") end end context "When with inheritance" do it "Simple class name w/ inheritance." do classNameCaptured = @classRuby.get_class("class Xpto < Abc").name expect(classNameCaptured).to eq("Xpto") end it "Simple class inheritance." do classNameCaptured = @classRuby.get_class("class Xpto < Abc").inheritances expect(classNameCaptured).to eq([["Abc"]]) end it "Class name w/ inheritance with whitespace in the beginning." do classNameCaptured = @classRuby.get_class(" class Xpto < Abc").name expect(classNameCaptured).to eq("Xpto") end it "Class inheritance with whitespace in the beginning." do classNameCaptured = @classRuby.get_class(" class Xpto < Abc") .inheritances expect(classNameCaptured).to eq([["Abc"]]) end it "Class name w/ inheritance with whitespace between <." do classNameCaptured = @classRuby.get_class("class Xpto < Abc").name expect(classNameCaptured).to eq("Xpto") end it "Class inheritance with whitespace between <." do classNameCaptured = @classRuby.get_class("class Xpto < Abc") .inheritances expect(classNameCaptured).to eq([["Abc"]]) end it "Class name w/ inheritance with many whitespace." do classNameCaptured = @classRuby.get_class(" class Xpto < Abc ").name expect(classNameCaptured).to eq("Xpto") end it "Class inheritance with many whitespace." do classNameCaptured = @classRuby.get_class(" class Xpto < Abc ") .inheritances expect(classNameCaptured).to eq([["Abc"]]) end it "Class name w/ inheritance with many whitespace between <." do classNameCaptured = @classRuby.get_class("class Xpto < Abc").name expect(classNameCaptured).to eq("Xpto") end it "Class inheritance with many whitespace between <." do classNameCaptured = @classRuby.get_class("class Xpto < Abc") .inheritances expect(classNameCaptured).to eq([["Abc"]]) end it "Class name w/ inheritance with whitespace in the corners." do classNameCaptured = @classRuby.get_class(" class Xpto < Abc ").name expect(classNameCaptured).to eq("Xpto") end it "Class inheritance with whitespace in the corners." do classNameCaptured = @classRuby.get_class(" class Xpto < Abc ") .inheritances expect(classNameCaptured).to eq([["Abc"]]) end end context "Get inheritance" do it "Class inheritance normal case" do inheritance = @classRuby.get_class("class Xpto < Abc").inheritances[0] expect(inheritance).to eq(["Abc"]) end it "Inheritance with many spaces in the beginning" do inheritance = @classRuby.get_class("class Xpto < Abc").inheritances[0] expect(inheritance).to eq(["Abc"]) end it "Inheritance with many spaces in the end" do inheritance = @classRuby.get_class("class Xpto < Abc ").inheritances[0] expect(inheritance).to eq(["Abc"]) end it "Inheritance with many spaces in the beginning and in the end" do inheritance = @classRuby.get_class("class Xs < Abc ").inheritances[0] expect(inheritance).to eq(["Abc"]) end end after :all do @classRuby = nil end end Test to detected bug 163, and refactored test. require_relative '../../spec_helper' RSpec.describe Languages::Ruby::ClassRuby do before :all do @classRuby = Languages::Ruby::ClassRuby.new end context 'When is class without inheritance' do it 'Ordinary class declaration.' do classNameCaptured = @classRuby.get_class('class Xpto').name expect(classNameCaptured).to eq('Xpto') end it 'Class declaration with whitespace.' do classNameCaptured = @classRuby.get_class(' class Xpto').name expect(classNameCaptured).to eq('Xpto') end it 'Class declaration between whitespace.' do classNameCaptured = @classRuby.get_class(' class Xpto ').name expect(classNameCaptured).to eq('Xpto') end it 'Class declaration with whitespace in the beginning.' do classNameCaptured = @classRuby.get_class(' class Xpto').name expect(classNameCaptured).to eq('Xpto') end it 'Class declaration with whitespace in the end.' do classNameCaptured = @classRuby.get_class('class Xpto ').name expect(classNameCaptured).to eq('Xpto') end it 'Class declaration delimited by whitespace.' do classNameCaptured = @classRuby.get_class(' class Xpto ').name expect(classNameCaptured).to eq('Xpto') end it 'Class declaration with a few whitespace.' do classNameCaptured = @classRuby.get_class(' class Xpto ').name expect(classNameCaptured).to eq('Xpto') end it 'Class declaration with whitespace in the beginning.' do classNameCaptured = @classRuby.get_class(' class Xpto').name expect(classNameCaptured).to eq('Xpto') end it 'Class declaration ended with whitespace.' do classNameCaptured = @classRuby.get_class('class Xpto ').name expect(classNameCaptured).to eq('Xpto') end it 'Class declaration with many whitespace.' do classNameCaptured = @classRuby.get_class(' class Xpto ').name expect(classNameCaptured).to eq('Xpto') end it 'Class declaration with tab.' do classNameCaptured = @classRuby.get_class(' class Xpto ').name expect(classNameCaptured).to eq('Xpto') end end context 'When with inheritance' do it 'Simple class name w/ inheritance.' do classNameCaptured = @classRuby.get_class('class Xpto < Abc').name expect(classNameCaptured).to eq('Xpto') end it 'Simple class inheritance.' do classNameCaptured = @classRuby.get_class('class Xpto < Abc').inheritances expect(classNameCaptured).to eq([['Abc']]) end it 'Class name w/ inheritance with whitespace in the beginning.' do classNameCaptured = @classRuby.get_class(' class Xpto < Abc').name expect(classNameCaptured).to eq('Xpto') end it 'Class inheritance with whitespace in the beginning.' do classNameCaptured = @classRuby.get_class(' class Xpto < Abc') .inheritances expect(classNameCaptured).to eq([['Abc']]) end it 'Class name w/ inheritance with whitespace between <.' do classNameCaptured = @classRuby.get_class('class Xpto < Abc').name expect(classNameCaptured).to eq('Xpto') end it 'Class inheritance with whitespace between <.' do classNameCaptured = @classRuby.get_class('class Xpto < Abc') .inheritances expect(classNameCaptured).to eq([['Abc']]) end it 'Class name w/ inheritance with many whitespace.' do classNameCaptured = @classRuby.get_class(' class Xpto < Abc ').name expect(classNameCaptured).to eq('Xpto') end it 'Class inheritance with many whitespace.' do classNameCaptured = @classRuby.get_class(' class Xpto < Abc ') .inheritances expect(classNameCaptured).to eq([['Abc']]) end it 'Class name w/ inheritance with many whitespace between <.' do classNameCaptured = @classRuby.get_class('class Xpto < Abc').name expect(classNameCaptured).to eq('Xpto') end it 'Class inheritance with many whitespace between <.' do classNameCaptured = @classRuby.get_class('class Xpto < Abc') .inheritances expect(classNameCaptured).to eq([['Abc']]) end it 'Class name w/ inheritance with whitespace in the corners.' do classNameCaptured = @classRuby.get_class(' class Xpto < Abc ').name expect(classNameCaptured).to eq('Xpto') end it 'Class inheritance with whitespace in the corners.' do classNameCaptured = @classRuby.get_class(' class Xpto < Abc ') .inheritances expect(classNameCaptured).to eq([['Abc']]) end it 'Class inheritance with module namespace' do classNameCaptured = @classRuby.get_class('class Xpto < lalala::Abc') .inheritances expect(classNameCaptured).to eq([['Abc']]) end it 'Class inheritance with multiple module namespace' do classNameCaptured = @classRuby.get_class('class Xpto < lu::la::lo::Abc') .inheritances expect(classNameCaptured).to eq([['Abc']]) end it 'Class inheritance with module namespace and spaces' do classNameCaptured = @classRuby.get_class(' class Xpto < lalala::Abc ') .inheritances expect(classNameCaptured).to eq([['Abc']]) end it 'Class inheritance with module namespace and spaces before module' do classNameCaptured = @classRuby.get_class(' class Xpto < lalala::Abc ') .inheritances expect(classNameCaptured).to eq([['Abc']]) end end context 'Get inheritance' do it 'Class inheritance normal case' do inheritance = @classRuby.get_class('class Xpto < Abc').inheritances[0] expect(inheritance).to eq(['Abc']) end it 'Inheritance with many spaces in the beginning' do inheritance = @classRuby.get_class('class Xpto < Abc').inheritances[0] expect(inheritance).to eq(['Abc']) end it 'Inheritance with many spaces in the end' do inheritance = @classRuby.get_class('class Xpto < Abc ').inheritances[0] expect(inheritance).to eq(['Abc']) end it 'Inheritance with many spaces in the beginning and in the end' do inheritance = @classRuby.get_class('class Xs < Abc ').inheritances[0] expect(inheritance).to eq(['Abc']) end end after :all do @classRuby = nil end end
Add encryptor spec require 'spec_helper' describe AdminAuth::Encryptor do subject { AdminAuth::Encryptor.new } describe '#encrypt_password' do let(:password) { double } let(:encrypted_password) { double } before { expect(BCrypt::Password).to receive(:create).with(password, cost: 10).and_return(encrypted_password) } it { expect(subject.encrypt_password(password)).to eq encrypted_password } end describe '#compare_passwords?' do let(:password) { double } let(:encrypted_password) { double } let(:salt) { double } let(:bcrypt) { double(salt: salt) } let(:hashed_password) { double } before do expect(BCrypt::Password).to receive(:new).with(encrypted_password).and_return(bcrypt) expect(BCrypt::Engine).to receive(:hash_secret).with(password, salt).and_return(hashed_password) expect(Rack::Utils).to receive(:secure_compare).with(hashed_password, encrypted_password).and_return(true) end it { expect(subject.compare_passwords?(password, encrypted_password)).to eq true } end end
require 'spec_helper' describe Fasterer::MethodCall do let(:ripper) do Ripper.sexp(code) end let(:method_call) do Fasterer::MethodCall.new(call_element) end describe 'method call on a constant' do # let(:code) { 'method_call_on_constant.rb' } let(:code) { "User.hello()" } # This is where the :call token will be recognized. let(:call_element) { ripper.drop(1).first.first[1] } it 'should detect constant' do expect(method_call.method_name).to eq('hello') expect(method_call.arguments).to be_empty end end describe 'method call on a integer' do let(:code) { '1.hello()' } # This is where the :call token will be recognized. let(:call_element) { ripper.drop(1).first.first[1] } it 'should detect integer' do expect(method_call.method_name).to eq('hello') expect(method_call.arguments).to be_empty end end describe 'method call on a string' do let(:code) { "'hello'.hello()" } let(:call_element) { ripper.drop(1).first.first[1] } it 'should detect string' do expect(method_call.method_name).to eq('hello') expect(method_call.arguments).to be_empty end end describe 'method call on a variable' do let(:code) do "number_one = 1\n"\ "number_one.hello()" end let(:call_element) { ripper.drop(1).first.last[1] } it 'should detect variable' do expect(method_call.method_name).to eq('hello') expect(method_call.arguments).to be_empty expect(method_call.receiver).to be_a(Fasterer::VariableReference) end end describe 'method call on a method' do let(:code) { '1.hi(2).hello()' } let(:call_element) { ripper.drop(1).first.first[1] } it 'should detect method' do expect(method_call.method_name).to eq('hello') expect(method_call.receiver).to be_a(Fasterer::MethodCall) expect(method_call.receiver.name).to eq('hi') expect(method_call.arguments).to be_empty end end describe 'method call with equals operator' do let(:code) { 'method_call_with_equals.rb' } let(:call_element) { ripper.drop(1).first.first[1] } xit 'should recognize receiver' do # expect(method_call.method_name).to eq('hello') # expect(method_call.receiver).to be_a(Fasterer::MethodCall) # expect(method_call.receiver.name).to eq('hi') end end # Needed for Hash.fetch. Need to do more reconstruction, # before recognizing method calls arguments. describe 'method call with a block' do let(:code) do <<-code number_one = 1 number_one.fetch do |el| number_two = 2 number_three = 3 end code end let(:call_element) { ripper.drop(1).first.last } it 'should detect block' do expect(method_call.method_name).to eq('fetch') expect(method_call.arguments).to be_empty expect(method_call.has_block?).to be expect(method_call.receiver).to be_a(Fasterer::VariableReference) end end describe 'method call with an argument and a block' do let(:code) do <<-code number_one = 1 number_one.fetch(:writing) { [*1..100] } code end let(:call_element) { ripper.drop(1).first.last } it 'should detect argument and a block' do expect(method_call.method_name).to eq('fetch') expect(method_call.arguments.count).to eq(1) expect(method_call.arguments.first.type).to eq(:symbol_literal) expect(method_call.has_block?).to be expect(method_call.receiver).to be_a(Fasterer::VariableReference) end end # method_add_arg describe 'method call with an argument' do let(:code) { '{}.fetch(:writing)' } let(:call_element) { ripper.drop(1).first.first } it 'should detect argument' do expect(method_call.method_name).to eq('fetch') expect(method_call.arguments.count).to eq(1) expect(method_call.arguments.first.type).to eq(:symbol_literal) # expect(method_call.receiver).to be_a(Fasterer::MethodCall) # expect(method_call.receiver.name).to eq('hi') end end describe 'method call with an argument without brackets' do let(:code) { '{}.fetch :writing, :listening' } let(:call_element) { ripper.drop(1).first.first } it 'should detect argument' do expect(method_call.method_name).to eq('fetch') expect(method_call.arguments.count).to eq(2) expect(method_call.arguments[0].type).to eq(:symbol_literal) expect(method_call.arguments[1].type).to eq(:symbol_literal) # expect(method_call.receiver).to be_a(Fasterer::MethodCall) # expect(method_call.receiver.name).to eq('hi') end end describe 'method call without an explicit receiver' do let(:code) { 'fetch(:writing, :listening)' } let(:call_element) { ripper.drop(1).first.first } it 'should detect two arguments' do expect(method_call.method_name).to eq('fetch') expect(method_call.arguments.count).to eq(2) expect(method_call.arguments[0].type).to eq(:symbol_literal) expect(method_call.arguments[1].type).to eq(:symbol_literal) expect(method_call.receiver).to be_nil end end describe 'method call without an explicit receiver and without brackets' do let(:code) { 'fetch :writing, :listening' } let(:call_element) { ripper.drop(1).first.first } it 'should detect two arguments' do expect(method_call.method_name).to eq('fetch') expect(method_call.arguments.count).to eq(2) expect(method_call.arguments[0].type).to eq(:symbol_literal) expect(method_call.arguments[1].type).to eq(:symbol_literal) expect(method_call.receiver).to be_nil end end describe 'method call without an explicit receiver and without brackets and do end' do let(:code) do <<-code "fetch :writing do\n"\ "end" code end let(:call_element) { ripper.drop(1).first.first } it 'should detect argument and a block' do # expect(method_call.method_name).to eq('fetch') # expect(method_call.arguments.count).to eq(2) # expect(method_call.arguments[0].type).to eq(:symbol_literal) # expect(method_call.arguments[1].type).to eq(:symbol_literal) # expect(method_call.receiver).to be_nil end end describe 'method call with two arguments' do let(:code) do "number_one = 1\n"\ "number_one.fetch(:writing, :zumba)" end let(:call_element) { ripper.drop(1).first.last } it 'should detect arguments' do expect(method_call.method_name).to eq('fetch') expect(method_call.arguments.count).to eq(2) expect(method_call.arguments[0].type).to eq(:symbol_literal) expect(method_call.arguments[1].type).to eq(:symbol_literal) expect(method_call.receiver).to be_a(Fasterer::VariableReference) end end describe 'method call with a regex argument' do let(:code) { '{}.fetch(/.*/)' } let(:call_element) { ripper.drop(1).first.first } it 'should detect regex argument' do expect(method_call.method_name).to eq('fetch') expect(method_call.arguments.count).to eq(1) expect(method_call.arguments[0].type).to eq(:regexp_literal) end end describe 'method call with a integer argument' do let(:code) { '[].flatten(1)' } let(:call_element) { ripper.drop(1).first.first } it 'should detect regex argument' do expect(method_call.method_name).to eq('flatten') expect(method_call.arguments.count).to eq(1) expect(method_call.arguments[0].type).to eq(:@int) expect(method_call.arguments[0].value).to eq("1") end end end Reordered method_call spec. require 'spec_helper' describe Fasterer::MethodCall do let(:ripper) do Ripper.sexp(code) end let(:method_call) do Fasterer::MethodCall.new(call_element) end describe 'with explicit receiver' do describe 'without arguments, without block, called with parentheses' do describe 'method call on a constant' do let(:code) { "User.hello()" } # This is where the :call token will be recognized. let(:call_element) { ripper.drop(1).first.first[1] } it 'should detect constant' do expect(method_call.method_name).to eq('hello') expect(method_call.arguments).to be_empty end end describe 'method call on a integer' do let(:code) { '1.hello()' } # This is where the :call token will be recognized. let(:call_element) { ripper.drop(1).first.first[1] } it 'should detect integer' do expect(method_call.method_name).to eq('hello') expect(method_call.arguments).to be_empty end end describe 'method call on a string' do let(:code) { "'hello'.hello()" } let(:call_element) { ripper.drop(1).first.first[1] } it 'should detect string' do expect(method_call.method_name).to eq('hello') expect(method_call.arguments).to be_empty end end describe 'method call on a variable' do let(:code) do "number_one = 1\n"\ "number_one.hello()" end let(:call_element) { ripper.drop(1).first.last[1] } it 'should detect variable' do expect(method_call.method_name).to eq('hello') expect(method_call.arguments).to be_empty expect(method_call.receiver).to be_a(Fasterer::VariableReference) end end describe 'method call on a method' do let(:code) { '1.hi(2).hello()' } let(:call_element) { ripper.drop(1).first.first[1] } it 'should detect method' do expect(method_call.method_name).to eq('hello') expect(method_call.receiver).to be_a(Fasterer::MethodCall) expect(method_call.receiver.name).to eq('hi') expect(method_call.arguments).to be_empty end end end describe 'without arguments, without block, called without parentheses' do describe 'method call on a constant' do let(:code) { "User.hello" } # This is where the :call token will be recognized. let(:call_element) { ripper.drop(1).first.first } it 'should detect constant' do expect(method_call.method_name).to eq('hello') expect(method_call.arguments).to be_empty end end describe 'method call on a integer' do let(:code) { '1.hello' } # This is where the :call token will be recognized. let(:call_element) { ripper.drop(1).first.first } it 'should detect integer' do expect(method_call.method_name).to eq('hello') expect(method_call.arguments).to be_empty end end describe 'method call on a string' do let(:code) { "'hello'.hello" } let(:call_element) { ripper.drop(1).first.first } it 'should detect string' do expect(method_call.method_name).to eq('hello') expect(method_call.arguments).to be_empty end end describe 'method call on a variable' do let(:code) do "number_one = 1\n"\ "number_one.hello" end let(:call_element) { ripper.drop(1).first.last } it 'should detect variable' do expect(method_call.method_name).to eq('hello') expect(method_call.arguments).to be_empty expect(method_call.receiver).to be_a(Fasterer::VariableReference) end end describe 'method call on a method' do let(:code) { '1.hi(2).hello' } let(:call_element) { ripper.drop(1).first.first } it 'should detect method' do expect(method_call.method_name).to eq('hello') expect(method_call.receiver).to be_a(Fasterer::MethodCall) expect(method_call.receiver.name).to eq('hi') expect(method_call.arguments).to be_empty end end end describe 'with do end block' do describe 'and no arguments' do let(:code) do <<-code number_one = 1 number_one.fetch do |el| number_two = 2 number_three = 3 end code end let(:call_element) { ripper.drop(1).first.last } it 'should detect block' do expect(method_call.method_name).to eq('fetch') expect(method_call.arguments).to be_empty expect(method_call.has_block?).to be expect(method_call.receiver).to be_a(Fasterer::VariableReference) end end describe 'and one argument within parentheses' do let(:code) do <<-code number_one = 1 number_one.fetch(100) do |el| number_two = 2 number_three = 3 end code end let(:call_element) { ripper.drop(1).first.last } it 'should detect block' do expect(method_call.method_name).to eq('fetch') expect(method_call.arguments.count).to be(1) expect(method_call.has_block?).to be expect(method_call.receiver).to be_a(Fasterer::VariableReference) end end end describe 'with curly block' do describe 'in one line' do let(:code) do <<-code number_one = 1 number_one.fetch { |el| number_two = 2 } code end let(:call_element) { ripper.drop(1).first.last } it 'should detect block' do expect(method_call.method_name).to eq('fetch') expect(method_call.arguments).to be_empty expect(method_call.has_block?).to be expect(method_call.receiver).to be_a(Fasterer::VariableReference) end end describe 'multi lined' do let(:code) do <<-code number_one = 1 number_one.fetch { |el| number_two = 2 number_three = 3 } code end let(:call_element) { ripper.drop(1).first.last } it 'should detect block' do expect(method_call.method_name).to eq('fetch') expect(method_call.arguments).to be_empty expect(method_call.has_block?).to be expect(method_call.receiver).to be_a(Fasterer::VariableReference) end end end describe 'with arguments, without block, called with parentheses' do describe 'method call with an argument' do let(:code) { '{}.fetch(:writing)' } let(:call_element) { ripper.drop(1).first.first } it 'should detect argument' do expect(method_call.method_name).to eq('fetch') expect(method_call.arguments.count).to eq(1) expect(method_call.arguments.first.type).to eq(:symbol_literal) # expect(method_call.receiver).to be_a(Fasterer::MethodCall) # expect(method_call.receiver.name).to eq('hi') end end end describe 'arguments without parenthesis' do describe 'method call with an argument' do let(:code) { '{}.fetch :writing, :listening' } let(:call_element) { ripper.drop(1).first.first } it 'should detect argument' do expect(method_call.method_name).to eq('fetch') expect(method_call.arguments.count).to eq(2) expect(method_call.arguments[0].type).to eq(:symbol_literal) expect(method_call.arguments[1].type).to eq(:symbol_literal) # expect(method_call.receiver).to be_a(Fasterer::MethodCall) # expect(method_call.receiver.name).to eq('hi') end end end end describe 'with implicit receiver' do end describe 'method call with an argument and a block' do let(:code) do <<-code number_one = 1 number_one.fetch(:writing) { [*1..100] } code end let(:call_element) { ripper.drop(1).first.last } it 'should detect argument and a block' do expect(method_call.method_name).to eq('fetch') expect(method_call.arguments.count).to eq(1) expect(method_call.arguments.first.type).to eq(:symbol_literal) expect(method_call.has_block?).to be expect(method_call.receiver).to be_a(Fasterer::VariableReference) end end describe 'method call without an explicit receiver' do let(:code) { 'fetch(:writing, :listening)' } let(:call_element) { ripper.drop(1).first.first } it 'should detect two arguments' do expect(method_call.method_name).to eq('fetch') expect(method_call.arguments.count).to eq(2) expect(method_call.arguments[0].type).to eq(:symbol_literal) expect(method_call.arguments[1].type).to eq(:symbol_literal) expect(method_call.receiver).to be_nil end end describe 'method call without an explicit receiver and without brackets' do let(:code) { 'fetch :writing, :listening' } let(:call_element) { ripper.drop(1).first.first } it 'should detect two arguments' do expect(method_call.method_name).to eq('fetch') expect(method_call.arguments.count).to eq(2) expect(method_call.arguments[0].type).to eq(:symbol_literal) expect(method_call.arguments[1].type).to eq(:symbol_literal) expect(method_call.receiver).to be_nil end end describe 'method call without an explicit receiver and without brackets and do end' do let(:code) do <<-code "fetch :writing do\n"\ "end" code end let(:call_element) { ripper.drop(1).first.first } it 'should detect argument and a block' do # expect(method_call.method_name).to eq('fetch') # expect(method_call.arguments.count).to eq(2) # expect(method_call.arguments[0].type).to eq(:symbol_literal) # expect(method_call.arguments[1].type).to eq(:symbol_literal) # expect(method_call.receiver).to be_nil end end describe 'method call with two arguments' do let(:code) do "number_one = 1\n"\ "number_one.fetch(:writing, :zumba)" end let(:call_element) { ripper.drop(1).first.last } it 'should detect arguments' do expect(method_call.method_name).to eq('fetch') expect(method_call.arguments.count).to eq(2) expect(method_call.arguments[0].type).to eq(:symbol_literal) expect(method_call.arguments[1].type).to eq(:symbol_literal) expect(method_call.receiver).to be_a(Fasterer::VariableReference) end end describe 'method call with a regex argument' do let(:code) { '{}.fetch(/.*/)' } let(:call_element) { ripper.drop(1).first.first } it 'should detect regex argument' do expect(method_call.method_name).to eq('fetch') expect(method_call.arguments.count).to eq(1) expect(method_call.arguments[0].type).to eq(:regexp_literal) end end describe 'method call with a integer argument' do let(:code) { '[].flatten(1)' } let(:call_element) { ripper.drop(1).first.first } it 'should detect regex argument' do expect(method_call.method_name).to eq('flatten') expect(method_call.arguments.count).to eq(1) expect(method_call.arguments[0].type).to eq(:@int) expect(method_call.arguments[0].value).to eq("1") end end describe 'method call with equals operator' do let(:code) { 'method_call_with_equals.rb' } let(:call_element) { ripper.drop(1).first.first[1] } xit 'should recognize receiver' do # expect(method_call.method_name).to eq('hello') # expect(method_call.receiver).to be_a(Fasterer::MethodCall) # expect(method_call.receiver.name).to eq('hi') end end end
Add spec for Klarna::Configuration. require 'spec_helper' describe Klarna::Configuration do subject { Klarna::Configuration.new } it { should respond_to(:hostname) } it { should respond_to(:port) } it { should respond_to(:store_id) } it { should respond_to(:store_secret) } end
describe Pumper::Specification do subject { described_class.new } before do currrent_path = Dir.pwd Dir.stub(:pwd).and_return("#{ currrent_path }/spec/fixtures") end its(:name) { is_expected.to eq('simple_gem') } its(:version) { is_expected.to eq('1.2.3') } its(:for_gemfile) { is_expected.to eq("gem 'simple_gem', '~> 1.2.3'") } its(:gem_file_name) { is_expected.to eq('simple_gem-1.2.3.gem') } end fix deprecation warning describe Pumper::Specification do subject { described_class.new } before do currrent_path = Dir.pwd allow(Dir).to receive_messages(pwd: "#{ currrent_path }/spec/fixtures") end its(:name) { is_expected.to eq('simple_gem') } its(:version) { is_expected.to eq('1.2.3') } its(:for_gemfile) { is_expected.to eq("gem 'simple_gem', '~> 1.2.3'") } its(:gem_file_name) { is_expected.to eq('simple_gem-1.2.3.gem') } end
require_relative '../../spec_helper' require 'savon/mock/spec_helper' describe Messagemedia::SOAP::Client do include Savon::SpecHelper before(:all) { savon.mock! } after(:all) { savon.unmock! } describe '#send_message' do it 'sends a message' do expected_request_body = { :'api:authentication' => { :'api:userId' => 'username', :'api:password' => 'password' }, :'api:requestBody' => { :'api:messages' => { :@sendMode => 'normal', :'api:message' => [ { :'api:content' => 'Test', :'api:recipients' => { :'api:recipient' => ['0491570156'], :attributes! => { :'api:recipient' => { :uid => [0] } } }, :@format => 'SMS', :@sequenceNumber => 0, :'api:deliveryReport' => true, :'api:validityPeriod' => 1, :'api:origin' => '0491570110' } ] } } } packaged_response = { :code => 200, :headers => {}, :body => Gyoku.xml({ :'SOAP-ENV:Envelope' => { :'@xmlns:SOAP-ENV' => 'http://schemas.xmlsoap.org/soap/envelope/', :'@xmlns:xsd' => 'http://www.w3.org/2001/XMLSchema', :'@xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance', :'@xmlns:SOAP-ENC' => 'http://schemas.xmlsoap.org/soap/encoding/', :'SOAP-ENV:Body' => { :send_messages_response => { :@xmlns => 'http://xml.m4u.com.au/2009', :result => { :account_details => { :@type => 'daily', :@credit_limit => '500', :@credit_remaining => '497' }, :@sent => '1', :@scheduled => '0', :@failed => '0' } } } } }, { :key_converter => :none }) } savon.expects(:send_messages).with(message: expected_request_body).returns(packaged_response) client = described_class.new('username', 'password') result = client.send_message('0491570156', 'Test', 0, '0491570110') expect(result).to_not be_nil expect(result[:account_details]).to_not be_nil expect(result[:account_details][:@type]).to eq('daily') expect(result[:account_details][:@credit_limit]).to eq('500') expect(result[:account_details][:@credit_remaining]).to eq('497') expect(result[:@sent]).to eq('1') expect(result[:@scheduled]).to eq('0') expect(result[:@failed]).to eq('0') end end describe '#send_messages' do it 'sends multiple message' do expected_request_body = { :'api:authentication' => { :'api:userId' => 'username', :'api:password' => 'password' }, :'api:requestBody' => { :'api:messages' => { :@sendMode => 'normal', :'api:message' => [ { :'api:content' => 'Test 1', :'api:recipients' => { :'api:recipient' => ['0491570156'], :attributes! => { :'api:recipient' => { :uid => [0] } } }, :@format => 'SMS', :@sequenceNumber => 0, :'api:deliveryReport' => true, :'api:validityPeriod' => 1, :'api:origin' => '0491570110' }, { :'api:content' => 'Test 2', :'api:recipients' => { :'api:recipient' => ['0491570157'], :attributes! => { :'api:recipient' => { :uid => [1] } } }, :@format => 'SMS', :@sequenceNumber => 0, :'api:deliveryReport' => false, :'api:validityPeriod' => 2, :'api:origin' => '0491570109' } ] } } } packaged_response = { :code => 200, :headers => {}, :body => Gyoku.xml({ :'SOAP-ENV:Envelope' => { :'@xmlns:SOAP-ENV' => 'http://schemas.xmlsoap.org/soap/envelope/', :'@xmlns:xsd' => 'http://www.w3.org/2001/XMLSchema', :'@xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance', :'@xmlns:SOAP-ENC' => 'http://schemas.xmlsoap.org/soap/encoding/', :'SOAP-ENV:Body' => { :send_messages_response => { :@xmlns => 'http://xml.m4u.com.au/2009', :result => { :account_details => { :@type => 'daily', :@credit_limit => '500', :@credit_remaining => '497' }, :@sent => '2', :@scheduled => '0', :@failed => '0' } } } } }, { :key_converter => :none }) } savon.expects(:send_messages).with(message: expected_request_body).returns(packaged_response) client = described_class.new('username', 'password') message_1 = Messagemedia::SOAP::Message.new message_1.content = 'Test 1' message_1.add_recipient(0, '0491570156') message_1.origin = '0491570110' message_2 = Messagemedia::SOAP::Message.new message_2.content = 'Test 2' message_2.add_recipient(1, '0491570157') message_2.delivery_report = false message_2.validity_period = 2 message_2.origin = '0491570109' result = client.send_messages([message_1, message_2]) expect(result).to_not be_nil expect(result[:account_details]).to_not be_nil expect(result[:account_details][:@type]).to eq('daily') expect(result[:account_details][:@credit_limit]).to eq('500') expect(result[:account_details][:@credit_remaining]).to eq('497') expect(result[:@sent]).to eq('2') expect(result[:@scheduled]).to eq('0') expect(result[:@failed]).to eq('0') end end end Add test case for get_user_info method in Client class require_relative '../../spec_helper' require 'savon/mock/spec_helper' describe Messagemedia::SOAP::Client do include Savon::SpecHelper before(:all) { savon.mock! } after(:all) { savon.unmock! } describe '#send_message' do it 'sends a message' do expected_request_body = { :'api:authentication' => { :'api:userId' => 'username', :'api:password' => 'password' }, :'api:requestBody' => { :'api:messages' => { :@sendMode => 'normal', :'api:message' => [ { :'api:content' => 'Test', :'api:recipients' => { :'api:recipient' => ['0491570156'], :attributes! => { :'api:recipient' => { :uid => [0] } } }, :@format => 'SMS', :@sequenceNumber => 0, :'api:deliveryReport' => true, :'api:validityPeriod' => 1, :'api:origin' => '0491570110' } ] } } } packaged_response = { :code => 200, :headers => {}, :body => Gyoku.xml({ :'SOAP-ENV:Envelope' => { :'@xmlns:SOAP-ENV' => 'http://schemas.xmlsoap.org/soap/envelope/', :'@xmlns:xsd' => 'http://www.w3.org/2001/XMLSchema', :'@xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance', :'@xmlns:SOAP-ENC' => 'http://schemas.xmlsoap.org/soap/encoding/', :'SOAP-ENV:Body' => { :send_messages_response => { :@xmlns => 'http://xml.m4u.com.au/2009', :result => { :account_details => { :@type => 'daily', :@credit_limit => '500', :@credit_remaining => '497' }, :@sent => '1', :@scheduled => '0', :@failed => '0' } } } } }, { :key_converter => :none }) } savon.expects(:send_messages).with(message: expected_request_body).returns(packaged_response) client = described_class.new('username', 'password') result = client.send_message('0491570156', 'Test', 0, '0491570110') expect(result).to_not be_nil expect(result[:account_details]).to_not be_nil expect(result[:account_details][:@type]).to eq('daily') expect(result[:account_details][:@credit_limit]).to eq('500') expect(result[:account_details][:@credit_remaining]).to eq('497') expect(result[:@sent]).to eq('1') expect(result[:@scheduled]).to eq('0') expect(result[:@failed]).to eq('0') end end describe '#send_messages' do it 'sends multiple message' do expected_request_body = { :'api:authentication' => { :'api:userId' => 'username', :'api:password' => 'password' }, :'api:requestBody' => { :'api:messages' => { :@sendMode => 'normal', :'api:message' => [ { :'api:content' => 'Test 1', :'api:recipients' => { :'api:recipient' => ['0491570156'], :attributes! => { :'api:recipient' => { :uid => [0] } } }, :@format => 'SMS', :@sequenceNumber => 0, :'api:deliveryReport' => true, :'api:validityPeriod' => 1, :'api:origin' => '0491570110' }, { :'api:content' => 'Test 2', :'api:recipients' => { :'api:recipient' => ['0491570157'], :attributes! => { :'api:recipient' => { :uid => [1] } } }, :@format => 'SMS', :@sequenceNumber => 0, :'api:deliveryReport' => false, :'api:validityPeriod' => 2, :'api:origin' => '0491570109' } ] } } } packaged_response = { :code => 200, :headers => {}, :body => Gyoku.xml({ :'SOAP-ENV:Envelope' => { :'@xmlns:SOAP-ENV' => 'http://schemas.xmlsoap.org/soap/envelope/', :'@xmlns:xsd' => 'http://www.w3.org/2001/XMLSchema', :'@xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance', :'@xmlns:SOAP-ENC' => 'http://schemas.xmlsoap.org/soap/encoding/', :'SOAP-ENV:Body' => { :send_messages_response => { :@xmlns => 'http://xml.m4u.com.au/2009', :result => { :account_details => { :@type => 'daily', :@credit_limit => '500', :@credit_remaining => '497' }, :@sent => '2', :@scheduled => '0', :@failed => '0' } } } } }, { :key_converter => :none }) } savon.expects(:send_messages).with(message: expected_request_body).returns(packaged_response) client = described_class.new('username', 'password') message_1 = Messagemedia::SOAP::Message.new message_1.content = 'Test 1' message_1.add_recipient(0, '0491570156') message_1.origin = '0491570110' message_2 = Messagemedia::SOAP::Message.new message_2.content = 'Test 2' message_2.add_recipient(1, '0491570157') message_2.delivery_report = false message_2.validity_period = 2 message_2.origin = '0491570109' result = client.send_messages([message_1, message_2]) expect(result).to_not be_nil expect(result[:account_details]).to_not be_nil expect(result[:account_details][:@type]).to eq('daily') expect(result[:account_details][:@credit_limit]).to eq('500') expect(result[:account_details][:@credit_remaining]).to eq('497') expect(result[:@sent]).to eq('2') expect(result[:@scheduled]).to eq('0') expect(result[:@failed]).to eq('0') end end describe '#get_user_info' do it 'returns user info' do expected_request_body = { :'api:authentication' => { :'api:userId' => 'username', :'api:password' => 'password' } } packaged_response = { :code => 200, :headers => {}, :body => Gyoku.xml({ :'SOAP-ENV:Envelope' => { :'@xmlns:SOAP-ENV' => 'http://schemas.xmlsoap.org/soap/envelope/', :'@xmlns:xsd' => 'http://www.w3.org/2001/XMLSchema', :'@xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance', :'@xmlns:SOAP-ENC' => 'http://schemas.xmlsoap.org/soap/encoding/', :'SOAP-ENV:Body' => { :check_user_response => { :@xmlns => 'http://xml.m4u.com.au/2009', :result => { :account_details => { :@type => 'daily', :@credit_limit => '500', :@credit_remaining => '497' }, :@sent => '2', :@scheduled => '0', :@failed => '0' } } } } }, { :key_converter => :none }) } savon.expects(:check_user).with(message: expected_request_body).returns(packaged_response) client = described_class.new('username', 'password') result = client.get_user_info expect(result).to_not be_nil expect(result[:account_details]).to_not be_nil expect(result[:account_details][:@type]).to eq('daily') expect(result[:account_details][:@credit_limit]).to eq('500') expect(result[:account_details][:@credit_remaining]).to eq('497') expect(result[:@sent]).to eq('2') expect(result[:@scheduled]).to eq('0') expect(result[:@failed]).to eq('0') end end end
require 'rails_helper' describe BaseOrganisation, type: :model do describe '#has_been_updated_recently?' do subject { FactoryGirl.create(:organisation, updated_at: Time.now) } it { is_expected.to have_been_updated_recently } context "updated too long ago" do subject { FactoryGirl.create(:organisation, updated_at: 365.days.ago)} it { is_expected.not_to have_been_updated_recently } end context "when updated recently" do subject { FactoryGirl.create(:organisation, updated_at: 364.days.ago) } it { is_expected.to have_been_updated_recently } end end describe 'geocoding' do subject { FactoryGirl.create(:organisation, updated_at: 366.days.ago) } it 'should geocode when address changes' do new_address = '30 pinner road' is_expected.to receive(:geocode) subject.update_attributes :address => new_address end it 'should geocode when postcode changes' do new_postcode = 'HA1 4RZ' is_expected.to receive(:geocode) subject.update_attributes :postcode => new_postcode end it 'should geocode when new object is created' do address = '60 pinner road' postcode = 'HA1 4HZ' org = FactoryGirl.build(:organisation,:address => address, :postcode => postcode, :name => 'Happy and Nice', :gmaps => true) expect(org).to receive(:geocode) org.save end end end organisation should have a name require 'rails_helper' describe BaseOrganisation, type: :model do describe '#validation' do it 'should have a valid factory' do expect(FactoryGirl.build(:organisation)).to be_valid end it 'is should have name' do expect(FactoryGirl.build(:organisation, name: '')).not_to be_valid end end end describe '#has_been_updated_recently?' do subject { FactoryGirl.create(:organisation, updated_at: Time.now) } it { is_expected.to have_been_updated_recently } context "updated too long ago" do subject { FactoryGirl.create(:organisation, updated_at: 365.days.ago)} it { is_expected.not_to have_been_updated_recently } end context "when updated recently" do subject { FactoryGirl.create(:organisation, updated_at: 364.days.ago) } it { is_expected.to have_been_updated_recently } end end describe 'geocoding' do subject { FactoryGirl.create(:organisation, updated_at: 366.days.ago) } it 'should geocode when address changes' do new_address = '30 pinner road' is_expected.to receive(:geocode) subject.update_attributes :address => new_address end it 'should geocode when postcode changes' do new_postcode = 'HA1 4RZ' is_expected.to receive(:geocode) subject.update_attributes :postcode => new_postcode end it 'should geocode when new object is created' do address = '60 pinner road' postcode = 'HA1 4HZ' org = FactoryGirl.build(:organisation,:address => address, :postcode => postcode, :name => 'Happy and Nice', :gmaps => true) expect(org).to receive(:geocode) org.save end end end
# Encoding: UTF-8 require 'spec_helper' describe EuropeanaWrapper, :type => :model do describe ".search" do ew = EuropeanaWrapper.new("svend foyn") before { @result = ew.search(0) } subject { @result } it "should return array" do expect(@result).to be_an_instance_of(Array) end it "should return array of References" do @result.each do |r| expect(r).to be_an_instance_of(Reference) end end end describe ".new_reference_from" do url = "http://www.europeana.eu/portal/record/2022609/3701E9A913A319B8B3154E5A5340F31DECBA883A.html?utm_source=api&utm_medium=api&utm_campaign=U4YHdx6jK" before { @ref = EuropeanaWrapper::new_reference_from(url) } subject { @ref } it "should be a reference" do expect(@ref).to be_an_instance_of(Reference) end it "should have correct info" do expect(@ref.title).to eq("VardΓ₯s fort, et tysk kystfort pΓ₯ NΓΈtterΓΈy") expect(@ref.creator).to eq("Yngvar Halvorsen") expect(@ref.lang).to eq("no") expect(@ref.year).to eq(nil) expect(@ref.reference_type_id).to eq(14) expect(@ref.url).to eq(url) end end describe ".new_reference_from with inconsistent api" do url = "http://www.europeana.eu/portal/record/2021002/C_536_3A2.html?utm_source=api&utm_medium=api&utm_campaign=U4YHdx6jK" before { @ref = EuropeanaWrapper::new_reference_from(url) } subject { @ref } it "should be a reference" do expect(@ref).to be_an_instance_of(Reference) end it "should have correct info" do expect(@ref.title).to eq("Lucifer (PΓ€ivΓ€)") expect(@ref.creator).to eq("Volpato, Giovanni (taiteilija)") expect(@ref.lang).to eq("fi") expect(@ref.year).to eq(nil) expect(@ref.reference_type_id).to eq(14) expect(@ref.url).to eq(url) end end end fixed europeana wrapper spec # Encoding: UTF-8 require 'spec_helper' describe EuropeanaWrapper, :type => :model do describe ".search" do ew = EuropeanaWrapper.new("svend foyn") before { @result = ew.search(0) } subject { @result } it "should return array" do expect(@result).to be_an_instance_of(Array) end it "should return array of References" do @result.each do |r| expect(r).to be_an_instance_of(Reference) end end end describe ".new_reference_from" do url = "http://www.europeana.eu/portal/record/2022609/3701E9A913A319B8B3154E5A5340F31DECBA883A.html?utm_source=api&utm_medium=api&utm_campaign=U4YHdx6jK" before { @ref = EuropeanaWrapper::new_reference_from(url) } subject { @ref } it "should be a reference" do expect(@ref).to be_an_instance_of(Reference) end it "should have correct info" do expect(@ref.title).to eq("VardΓ₯s fort, et tysk kystfort pΓ₯ NΓΈtterΓΈy") expect(@ref.creator).to eq("Yngvar Halvorsen") expect(@ref.lang).to eq("no") expect(@ref.year).to eq(nil) expect(@ref.reference_type_id).to eq(15) expect(@ref.url).to eq(url) end end describe ".new_reference_from with inconsistent api" do url = "http://www.europeana.eu/portal/record/2021002/e_IsShownAt_3287D67D_6018_40F1_B5E6_09BBD5F331ED.html?start=1&query=title%3ALucifer+%28P%C3%A4iv%C3%A4%29&startPage=1&rows=24" before { @ref = EuropeanaWrapper::new_reference_from(url) } subject { @ref } it "should be a reference" do expect(@ref).to be_an_instance_of(Reference) end it "should have correct info" do expect(@ref.title).to eq("Lucifer (PΓ€ivΓ€)") expect(@ref.creator).to eq("Volpato, Giovanni (taiteilija)") expect(@ref.lang).to eq("fi") expect(@ref.year).to eq(nil) expect(@ref.reference_type_id).to eq(15) expect(@ref.url).to eq(url) end end end
require File.dirname(__FILE__) + '/../spec_helper.rb' describe ObservationField do elastic_models( Observation ) describe "creation" do it "should stip allowd values" do of = ObservationField.make!(:allowed_values => "foo |bar") expect( of.allowed_values).to eq "foo|bar" end end describe "validation" do it "should fail if allowd_values doesn't have pipes" do expect { ObservationField.make!(:allowed_values => "foo") }.to raise_error(ActiveRecord::RecordInvalid) end it "should not allow tags in the name" do of = ObservationField.make!(:name => "hey <script>") expect(of.name).to eq"hey" end it "should not allow tags in the description" do of = ObservationField.make!(:description => "hey <script>") expect(of.description).to eq "hey" end it "should not allow tags in the allowed_values" do of = ObservationField.make!(:allowed_values => "hey|now <script>") expect(of.allowed_values).to eq "hey|now" end end describe "editing" do it "should reindex observations if the name is changed" do o = Observation.make! of = ObservationField.make!(name: "oldname") ofv = ObservationFieldValue.make!(observation: o, observation_field: of) expect( Observation.page_of_results({ "field:oldname": nil }).total_entries ).to eq 1 without_delay{ of.update_attributes(name: "newname") } new_of_with_oldname = ObservationField.make!(name: "oldname") expect( Observation.page_of_results({ "field:oldname": nil }).total_entries ).to eq 0 expect( Observation.page_of_results({ "field:newname": nil }).total_entries ).to eq 1 end it "should reindex projects" do of = ObservationField.make!( datatype: "numeric" ) proj = Project.make! pof = ProjectObservationField.make!( project: proj, observation_field: of ) Project.elastic_index!( ids: [proj.id] ) expect( Project.elastic_search( id: proj.id ).results.results.first. project_observation_fields.first.observation_field.datatype ).to eq "numeric" without_delay{ of.update_attributes( datatype: "text" ) } expect( Project.elastic_search( id: proj.id ).results.results.first. project_observation_fields.first.observation_field.datatype ).to eq "text" end end describe "destruction" do it "should not be possible if assosiated projects exist" it "should not be possible if assosiated observations exist" end describe "merge" do let(:keeper) { ObservationField.make! } let(:reject) { ObservationField.make! } it "should delete the reject" do keeper.merge(reject) expect(ObservationField.find_by_id(reject.id)).to be_blank end it "should merge requested allowed values" do keeper.update_attributes(:allowed_values => "a|b") reject.update_attributes(:allowed_values => "c|d") keeper.merge(reject, :merge => [:allowed_values]) keeper.reload expect(keeper.allowed_values).to eq "a|b|c|d" end it "should keep requested allowed values" do keeper.update_attributes(:allowed_values => "a|b") reject.update_attributes(:allowed_values => "c|d") keeper.merge(reject, :keep => [:allowed_values]) keeper.reload expect(keeper.allowed_values).to eq "c|d" end it "should update observation field for the observation field values of the reject" do ofv = ObservationFieldValue.make!(:observation_field => reject) keeper.merge(reject) ofv.reload expect(ofv.observation_field).to eq keeper end it "should create a notification for all users of the reject" it "should not be possible for a reject in use by a project" do pof = ProjectObservationField.make!(:observation_field => reject) keeper.merge(reject) expect(ObservationField.find_by_id(reject.id)).not_to be_blank end end end attempt spec fix require File.dirname(__FILE__) + '/../spec_helper.rb' describe ObservationField do elastic_models( Observation, Project ) describe "creation" do it "should stip allowd values" do of = ObservationField.make!(:allowed_values => "foo |bar") expect( of.allowed_values).to eq "foo|bar" end end describe "validation" do it "should fail if allowd_values doesn't have pipes" do expect { ObservationField.make!(:allowed_values => "foo") }.to raise_error(ActiveRecord::RecordInvalid) end it "should not allow tags in the name" do of = ObservationField.make!(:name => "hey <script>") expect(of.name).to eq"hey" end it "should not allow tags in the description" do of = ObservationField.make!(:description => "hey <script>") expect(of.description).to eq "hey" end it "should not allow tags in the allowed_values" do of = ObservationField.make!(:allowed_values => "hey|now <script>") expect(of.allowed_values).to eq "hey|now" end end describe "editing" do it "should reindex observations if the name is changed" do o = Observation.make! of = ObservationField.make!(name: "oldname") ofv = ObservationFieldValue.make!(observation: o, observation_field: of) expect( Observation.page_of_results({ "field:oldname": nil }).total_entries ).to eq 1 without_delay{ of.update_attributes(name: "newname") } new_of_with_oldname = ObservationField.make!(name: "oldname") expect( Observation.page_of_results({ "field:oldname": nil }).total_entries ).to eq 0 expect( Observation.page_of_results({ "field:newname": nil }).total_entries ).to eq 1 end it "should reindex projects" do of = ObservationField.make!( datatype: "numeric" ) proj = Project.make! pof = ProjectObservationField.make!( project: proj, observation_field: of ) Project.elastic_index!( ids: [proj.id] ) expect( Project.elastic_search( id: proj.id ).results.results.first. project_observation_fields.first.observation_field.datatype ).to eq "numeric" without_delay{ of.update_attributes( datatype: "text" ) } expect( Project.elastic_search( id: proj.id ).results.results.first. project_observation_fields.first.observation_field.datatype ).to eq "text" end end describe "destruction" do it "should not be possible if assosiated projects exist" it "should not be possible if assosiated observations exist" end describe "merge" do let(:keeper) { ObservationField.make! } let(:reject) { ObservationField.make! } it "should delete the reject" do keeper.merge(reject) expect(ObservationField.find_by_id(reject.id)).to be_blank end it "should merge requested allowed values" do keeper.update_attributes(:allowed_values => "a|b") reject.update_attributes(:allowed_values => "c|d") keeper.merge(reject, :merge => [:allowed_values]) keeper.reload expect(keeper.allowed_values).to eq "a|b|c|d" end it "should keep requested allowed values" do keeper.update_attributes(:allowed_values => "a|b") reject.update_attributes(:allowed_values => "c|d") keeper.merge(reject, :keep => [:allowed_values]) keeper.reload expect(keeper.allowed_values).to eq "c|d" end it "should update observation field for the observation field values of the reject" do ofv = ObservationFieldValue.make!(:observation_field => reject) keeper.merge(reject) ofv.reload expect(ofv.observation_field).to eq keeper end it "should create a notification for all users of the reject" it "should not be possible for a reject in use by a project" do pof = ProjectObservationField.make!(:observation_field => reject) keeper.merge(reject) expect(ObservationField.find_by_id(reject.id)).not_to be_blank end end end
require 'rails_helper' describe OptionSetImport do let(:mission) { get_mission } before do configatron.preferred_locale = :en end it 'should be able to import a simple option set' do name = "Simple" import = OptionSetImport.new(mission_id: mission.id, name: name, file: option_set_fixture("simple.xlsx")) succeeded = import.create_option_set expect(succeeded).to be_truthy option_set = import.option_set expect_simple_option_set(option_set, name: name) end it 'should be able to import an option set in admin mode' do name = "Simple Standard" import = OptionSetImport.new(mission_id: nil, name: name, file: option_set_fixture("simple.xlsx")) succeeded = import.create_option_set expect(succeeded).to be_truthy option_set = import.option_set expect_simple_option_set(option_set, name: name, standard: true) end it 'should be able to import a multi-level geographic option set' do name = "Multilevel Geographic" import = OptionSetImport.new( mission_id: mission.id, name: name, file: option_set_fixture("multilevel_geographic.xlsx") ) succeeded = import.create_option_set expect(succeeded).to be_truthy option_set = import.option_set expect(option_set).to have_attributes( name: name, level_count: 3, geographic?: true, allow_coordinates?: true) expect(option_set.level_names).to start_with( {'en' => 'Province'}, {'en' => 'City/District'}, {'en' => 'Commune/Territory'}) # check the total and top-level option counts expect(option_set.total_options).to eq(321) expect(option_set.options).to have(26).items # make sure that the non-leaf options have no coordinates option_set.preordered_option_nodes.each do |node| if node.child_options.present? expect(node).to have_attributes(option: have_attributes(coordinates?: false)) end end # verify the latitude and longitude of one of the options expect(option_set.all_options).to include( have_attributes(canonical_name: 'Aketi', latitude: 2.739529, longitude: 23.780851)) end it 'should correctly report errors for invalid coordinate values' do name = "Invalid Geographic" import = OptionSetImport.new( mission_id: mission.id, name: name, file: option_set_fixture("invalid_geographic.xlsx") ) succeeded = import.create_option_set expect(succeeded).to be_falsy end it 'should successfully import csv option set' do name = "CSV Set" import = OptionSetImport.new(mission_id: mission.id, name: name, file: option_set_fixture("simple.csv")) succeeded = import.create_option_set expect(succeeded).to be_truthy option_set = import.option_set expect_simple_option_set(option_set, name: "CSV Set") end private def expect_simple_option_set(option_set, name: "Simple", standard: false) expect(option_set).to have_attributes( name: name, geographic?: false, is_standard: standard) expect(option_set.levels).to be_nil expect(option_set.level_names).to include('en' => 'Province') expect(option_set.total_options).to eq(26) expect(option_set.all_options).to include(have_attributes(canonical_name: "Kinshasa")) end end 9127: Fix option set import spec require 'rails_helper' describe OptionSetImport do let(:mission) { get_mission } before do configatron.preferred_locale = :en end it 'should be able to import a simple option set' do name = "Simple" import = OptionSetImport.new(mission_id: mission.id, name: name, file: option_set_fixture("simple.xlsx")) import.run expect(import).to be_succeeded option_set = import.option_set expect_simple_option_set(option_set, name: name) end it 'should be able to import an option set in admin mode' do name = "Simple Standard" import = OptionSetImport.new(mission_id: nil, name: name, file: option_set_fixture("simple.xlsx")) import.run expect(import).to be_succeeded option_set = import.option_set expect_simple_option_set(option_set, name: name, standard: true) end it 'should be able to import a multi-level geographic option set' do name = "Multilevel Geographic" import = OptionSetImport.new( mission_id: mission.id, name: name, file: option_set_fixture("multilevel_geographic.xlsx") ) import.run expect(import).to be_succeeded option_set = import.option_set expect(option_set).to have_attributes( name: name, level_count: 3, geographic?: true, allow_coordinates?: true) expect(option_set.level_names).to start_with( {'en' => 'Province'}, {'en' => 'City/District'}, {'en' => 'Commune/Territory'}) # check the total and top-level option counts expect(option_set.total_options).to eq(321) expect(option_set.options).to have(26).items # make sure that the non-leaf options have no coordinates option_set.preordered_option_nodes.each do |node| if node.child_options.present? expect(node).to have_attributes(option: have_attributes(coordinates?: false)) end end # verify the latitude and longitude of one of the options expect(option_set.all_options).to include( have_attributes(canonical_name: 'Aketi', latitude: 2.739529, longitude: 23.780851)) end it 'should correctly report errors for invalid coordinate values' do name = "Invalid Geographic" import = OptionSetImport.new( mission_id: mission.id, name: name, file: option_set_fixture("invalid_geographic.xlsx") ) import.run expect(import).not_to be_succeeded end it 'should successfully import csv option set' do name = "CSV Set" import = OptionSetImport.new(mission_id: mission.id, name: name, file: option_set_fixture("simple.csv")) import.run expect(import).to be_succeeded option_set = import.option_set expect_simple_option_set(option_set, name: "CSV Set") end private def expect_simple_option_set(option_set, name: "Simple", standard: false) expect(option_set).to have_attributes( name: name, geographic?: false, is_standard: standard) expect(option_set.levels).to be_nil expect(option_set.level_names).to include('en' => 'Province') expect(option_set.total_options).to eq(26) expect(option_set.all_options).to include(have_attributes(canonical_name: "Kinshasa")) end end
require 'spec_helper' describe Spree::CreditCard, type: :model do context "payment is of type Solidus::Gateway::BraintreeGateway" do let(:payment_method) do Solidus::Gateway::BraintreeGateway.create!( name: 'Braintree Gateway', environment: 'sandbox', active: true ) end let(:credit_card) do FactoryGirl.create(:credit_card, payment_method: payment_method, encrypted_data: nil, gateway_customer_profile_id: nil, gateway_payment_profile_id: nil ) end it "require_card_numbers? returns false" do expect(credit_card.require_card_numbers?).not_to be end end end add name validation spec require 'spec_helper' describe Spree::CreditCard, type: :model do context "payment is of type Solidus::Gateway::BraintreeGateway" do let(:payment_method) do Solidus::Gateway::BraintreeGateway.create!( name: 'Braintree Gateway', environment: 'sandbox', active: true ) end let(:credit_card) do FactoryGirl.create(:credit_card, payment_method: payment_method, encrypted_data: nil, gateway_customer_profile_id: nil, gateway_payment_profile_id: nil ) end it "require_card_numbers? returns false" do expect(credit_card.require_card_numbers?).not_to be end it "validate presence of name on create" do expect do credit_card = FactoryGirl.create(:credit_card, payment_method: payment_method, name: nil ) end.to raise_error(ActiveRecord::RecordInvalid, /Name can't be blank/) end end end
require 'spec_helper' RSpec.describe "Test cases for all Core 24 Json files" do def test(file) jsonfile = File.open(file).read json_response = Application.new(jsonfile, 'application/json') @json_response = JSON.parse(json_response.to_json) puts "The number of applicants in #{file} json file: #{@json_response['Applicants'].count}" return @json_response end shared_examples_for "Core 24 tests" do it "Compares FPL" do @json_response["Applicants"].each_with_index do |applicant, index| expect(applicant['Medicaid Household']['MAGI as Percentage of FPL']).to eq @person[index][:FPL] end end it "Compares Medicaid Eligibilty " do @json_response["Applicants"].each_with_index do |applicant, index| expect(applicant['Medicaid Eligible']).to eq @person[index][:MedicaidEligible] end end it "Compares MAGI" do @json_response["Applicants"].each_with_index do |applicant, index| expect(applicant['Medicaid Household']['MAGI']).to eq @person[index][:MAGI] end end it "Compares APTC Referal" do @json_response["Applicants"].each_with_index do |applicant, index| expect(applicant['Determinations']['APTC Referral']['Indicator']).to eq @person[index][:APTCReferal] end end end describe "QA-CORE-1-UA-012.json" do before(:all) do @json_response = test('spec/core24_json_files/QA-CORE-1-UA-012.json') @person = [] @person << { FPL: 84, MAGI: 10000, MedicaidEligible: 'N', APTCReferal: 'Y'} end it_behaves_like "Core 24 tests" end describe "test_QACORE8MAGIIAUA004_married_filing_separately_big_household" do before(:all) do @json_response = test('spec/core24_json_files/QA-CORE-8-MAGI_IA_UA-004.json') @person = [] @person << {FPL: 240, MAGI: 88348, MedicaidEligible: 'N', APTCReferal: 'Y'} @person << {FPL: 407, MAGI: 81939, MedicaidEligible: 'N', APTCReferal: 'Y'} @person << {FPL: 407, MAGI: 81939, MedicaidEligible: 'N', APTCReferal: 'Y'} @person << {FPL: 240, MAGI: 88348, MedicaidEligible: 'N', APTCReferal: 'Y'} @person << {FPL: 0, MAGI: 0, MedicaidEligible: 'Y', APTCReferal: 'N'} @person << {FPL: 0, MAGI: 0, MedicaidEligible: 'Y', APTCReferal: 'N'} @person << {FPL: 0, MAGI: 0, MedicaidEligible: 'N', APTCReferal: 'Y'} @person << {FPL: 0, MAGI: 0, MedicaidEligible: 'Y', APTCReferal: 'N'} end it_behaves_like "Core 24 tests" end end Add Rspec examples for 5 core Json files require 'spec_helper' RSpec.describe "Test cases for all Core 24 Json files" do def get_response(file) jsonfile = File.open(file).read json_response = Application.new(jsonfile, 'application/json') @json_response = JSON.parse(json_response.to_json) puts "The number of applicants in #{file} json file: #{@json_response['Applicants'].count}" return @json_response end shared_examples_for "Core 24 tests" do it "Compares FPL" do @json_response["Applicants"].each_with_index do |applicant, index| expect(applicant['Medicaid Household']['MAGI as Percentage of FPL']).to eq @person[index][:FPL] end end it "Compares Medicaid Eligibilty " do @json_response["Applicants"].each_with_index do |applicant, index| expect(applicant['Medicaid Eligible']).to eq @person[index][:MedicaidEligible] end end it "Compares MAGI" do @json_response["Applicants"].each_with_index do |applicant, index| expect(applicant['Medicaid Household']['MAGI']).to eq @person[index][:MAGI] end end it "Compares APTC Referal" do @json_response["Applicants"].each_with_index do |applicant, index| expect(applicant['Determinations']['APTC Referral']['Indicator']).to eq @person[index][:APTCReferal] end end end describe "test_QACORE1UA012" do before(:all) do @json_response = get_response('spec/core24_json_files/QA-CORE-1-UA-012.json') @person = [] @person << { FPL: 84, MAGI: 10000, MedicaidEligible: 'N', APTCReferal: 'Y'} end it_behaves_like "Core 24 tests" end describe "test_QACORE8MAGIIAUA004_married_filing_separately_big_household" do before(:all) do @json_response = get_response('spec/core24_json_files/QA-CORE-8-MAGI_IA_UA-004.json') @person = [] @person << {FPL: 240, MAGI: 88348, MedicaidEligible: 'N', APTCReferal: 'Y'} @person << {FPL: 407, MAGI: 81939, MedicaidEligible: 'N', APTCReferal: 'Y'} @person << {FPL: 407, MAGI: 81939, MedicaidEligible: 'N', APTCReferal: 'Y'} @person << {FPL: 240, MAGI: 88348, MedicaidEligible: 'N', APTCReferal: 'Y'} @person << {FPL: 0, MAGI: 0, MedicaidEligible: 'Y', APTCReferal: 'N'} @person << {FPL: 0, MAGI: 0, MedicaidEligible: 'Y', APTCReferal: 'N'} @person << {FPL: 0, MAGI: 0, MedicaidEligible: 'N', APTCReferal: 'Y'} @person << {FPL: 0, MAGI: 0, MedicaidEligible: 'Y', APTCReferal: 'N'} end it_behaves_like "Core 24 tests" end describe "test_QACORE6MAGINONMAGI008" do before(:all) do @json_response = get_response('spec/core24_json_files/QA-CORE-6-MAGI_NONMAGI-008.json') @person = [] @person << { FPL: 176, MAGI: 57546, MedicaidEligible: 'Y', APTCReferal: 'N'} @person << { FPL: 176, MAGI: 57546, MedicaidEligible: 'Y', APTCReferal: 'N'} @person << { FPL: 176, MAGI: 57546, MedicaidEligible: 'Y', APTCReferal: 'N'} @person << { FPL: 176, MAGI: 57546, MedicaidEligible: 'Y', APTCReferal: 'N'} @person << { FPL: 0, MAGI: 0, MedicaidEligible: 'Y', APTCReferal: 'N'} @person << { FPL: 51, MAGI: 6100, MedicaidEligible: 'Y', APTCReferal: 'N'} end it_behaves_like "Core 24 tests" end describe "test_APTC1IA50" do before(:all) do @json_response = get_response('spec/core24_json_files/APTC-1-IA-50.json') @person = [] @person << { FPL: 229, MAGI: 27000, MedicaidEligible: 'N', APTCReferal: 'Y'} end it_behaves_like "Core 24 tests" end describe "test_APTC2IAUA6067WEEKLY" do before(:all) do @json_response = get_response('spec/core24_json_files/APTC-2-IA-UA-60-67-WEEKLY.json') @person = [] @person << { FPL: 282, MAGI: 44979, MedicaidEligible: 'N', APTCReferal: 'Y'} @person << { FPL: 282, MAGI: 44979, MedicaidEligible: 'N', APTCReferal: 'Y'} end it_behaves_like "Core 24 tests" end end
require 'rails_helper' describe User::Notification do before(:all) { create(:user_notification) } it { should belong_to(:user) } it { should_not allow_value(nil).for(:user) } it { should validate_presence_of(:message) } it { should validate_length_of(:message).is_at_least(1) } it { should validate_length_of(:message).is_at_most(128) } it { should validate_presence_of(:link) } it { should validate_length_of(:link).is_at_least(1) } it { should validate_length_of(:link).is_at_most(128) } end Notification model specs require 'rails_helper' describe User::Notification do before(:all) { create(:user_notification) } it { should belong_to(:user) } it { should_not allow_value(nil).for(:user) } it { should validate_presence_of(:message) } it { should validate_presence_of(:link) } end
require 'spec_helper' require "naturalsorter" describe Versioncmp do it "smaler" do expect( Versioncmp.compare("1.1", "1.2")).to eql(-1) end it "smaler" do expect( Versioncmp.compare("1.1.5", "1.1.x-dev")).to eql(-1) end it "smaler" do expect( Versioncmp.compare("1.1.5", "1.1-dev")).to eql(-1) end it "smaler" do expect( Versioncmp.compare("0.3", "0.7-groovy-2.0")).to eql(-1) end it "bigger" do expect( Versioncmp.compare("1.1", "1.0")).to eql(1) end it "1.1.1 is bigger than 1.1" do expect( Versioncmp.compare("1.1.1", "1.1")).to eql(1) end it "dev-master is bigger than 10.10.999" do expect( Versioncmp.compare("dev-master", "10.10.999")).to eql(1) end it "2.2.x-dev is bigger than 2.2.1" do expect( Versioncmp.compare("2.2.x-dev", "2.2.1")).to eql(1) end it "3.5.5-1 is bigger than 3.5.5" do expect( Versioncmp.compare("3.5.5-1", "3.5.5")).to eql(1) end it "3.5.5 is smaller than 3.5.5-1 " do expect( Versioncmp.compare("3.5.5", "3.5.5-1")).to eql(-1) end it "2.3.1-b01 is bigger than 2.3.1" do expect( Versioncmp.compare("2.3.1-b01", "2.3.1")).to eql(1) end it "2.3.2-b01 is bigger than 2.3.1" do expect( Versioncmp.compare("2.3.2-b01", "2.3.1")).to eql(1) end it "2.3.d-b01 is smaller than 2.3.1" do expect( Versioncmp.compare("2.3.d-b01", "2.3.1")).to eql(-1) end it "2.18.1 is bigger than 2.18-20141019" do expect( Versioncmp.compare("2.18.1", "2.18-20141019")).to eql(1) end it "2.18-20141019 is smaller than 2.18.1" do expect( Versioncmp.compare("2.18-20141019", "2.18.1")).to eql(-1) end it "1.1 is smaller than 1.1.1" do expect( Versioncmp.compare("1.1", "1.1.1")).to eql(-1) end it "equal" do expect( Versioncmp.compare("1.1", "1.1")).to eql(0) end it "equal" do expect( Versioncmp.compare("1.0", "1.0.0")).to eql(0) end it "1.0.0 is smaller than 1.0.*" do expect( Versioncmp.compare("1.0.0", "1.0.*")).to eql(-1) end it "1.0 is smaller than 1.0.*" do expect( Versioncmp.compare("1.0.0", "1.0.*")).to eql(-1) end it "equal RC" do expect( Versioncmp.compare("1.1.RC1", "1.1.RC1")).to eql(0) end it "smaller RC" do expect( Versioncmp.compare("1.1.RC1", "1.1")).to eql(-1) end it "smaller RC" do expect( Versioncmp.compare("1.1.rc1", "1.1")).to eql(-1) end it "smaller RC" do expect( Versioncmp.compare("1.1.rc1", "2.0")).to eql(-1) end it "smaller RC" do expect( Versioncmp.compare("1.1-rc1", "1.1")).to eql(-1) end it "smaller alpha" do expect( Versioncmp.compare("1.1-alpha1", "1.1")).to eql(-1) end it "alpha is smaller than BETA" do expect( Versioncmp.compare("2.1.0alpha", "2.1.0-BETA1")).to eql(-1) end it "smaller alpha-1" do expect( Versioncmp.compare("1.1-alpha-1", "1.1")).to eql(-1) end it "smaller alpha" do expect( Versioncmp.compare("1.1", "1.1-alpha-1")).to eql(1) end it "smaller beta" do expect( Versioncmp.compare("3.1-beta1", "3.1")).to eql(-1) end it "smaller beta" do expect( Versioncmp.compare("3.1-beta-1", "3.1")).to eql(-1) end it "smaller 3.0-rc4-negotiate" do expect( Versioncmp.compare("3.0-rc4-negotiate", "3.0")).to eql(-1) end it "smaller 3.1-jbossorg-1" do expect( Versioncmp.compare("3.1-jbossorg-1", "3.1")).to eql(-1) end it "smaller 3.1-pre1" do expect( Versioncmp.compare("3.1-pre1", "3.1")).to eql(-1) end it "bigger RC" do expect( Versioncmp.compare("1.1.rc3", "1.1.rc2")).to eql(1) end it "bigger RC than 1.0" do expect( Versioncmp.compare("1.1.RC1", "1.0")).to eql(1) end it "bigger RC than 1.0" do expect( Versioncmp.compare("1.1.RC1", "1.1")).to eql(-1) end it "20040121.140929 is smaller than 1.1" do expect( Versioncmp.compare("20040121.140929", "1.1")).to eql(-1) end it "1.1 is bigger than 20040121.140929" do expect( Versioncmp.compare("1.1", "20040121.140929")).to eql(1) end it "1.7b2 is smaller than 1.7" do expect( Versioncmp.compare("1.7b2", "1.7")).to eql(-1) end it "1.7 is bigger than 1.7b2" do expect( Versioncmp.compare("1.7", "1.7b2")).to eql(1) end it "1.7 is bigger than 1.7rc2" do expect( Versioncmp.compare("1.7", "1.7rc2")).to eql(1) end it "1.7 is bigger than 1.7RC2" do expect( Versioncmp.compare("1.7", "1.7RC2")).to eql(1) end it "1.7 is bigger than 1.7a" do expect( Versioncmp.compare("1.7", "1.7a")).to eql(1) end it "1.7 is bigger than 1.7b" do expect( Versioncmp.compare("1.7", "1.7b")).to eql(1) end it "1.7b is bigger than 1.7a" do expect( Versioncmp.compare("1.7b", "1.7a")).to eql(1) end it "1.7.1rc1 is smaller than 1.7.2" do expect( Versioncmp.compare("1.7.1rc1", "1.7.2")).to eql(-1) end it "1.7.2 is bigger than 1.7.1rc1" do expect( Versioncmp.compare("1.7.2", "1.7.1rc1")).to eql(1) end it "99.0-does-not-exist is smaller than 1.7.1" do expect( Versioncmp.compare("99.0-does-not-exist", "1.7.1")).to eql(-1) end it "2.2.1-b03 is bigger then 2.2" do expect( Versioncmp.compare("2.2.1-b03", "2.2")).to eql(1) end it "3.0.0 is equal to 3.0" do expect( Versioncmp.compare("3.0.0", "3.0")).to eql(0) end it "3.0 is equal to 3.0.0" do expect( Versioncmp.compare("3.0", "3.0.0")).to eql(0) end it "3.1-SNAPSHOT is equal to 3.1-SNAPSHOT" do expect( Versioncmp.compare("3.1-SNAPSHOT", "3.1-SNAPSHOT")).to eql(0) end it "3.1-SNAPSHOT is smaller than 3.2-SNAPSHOT" do expect( Versioncmp.compare("3.1-SNAPSHOT", "3.2-SNAPSHOT")).to eql(-1) end it "3.1 is smaller than 3.2-SNAPSHOT" do expect( Versioncmp.compare("3.1", "3.2-SNAPSHOT")).to eql(-1) end it "1.5.2 is smaller than 1.5.2-patch1" do expect( Versioncmp.compare("1.5.2", "1.5.2-patch1")).to eql(-1) end it "dev-master is bigger than 1.0.0" do expect( Versioncmp.compare("dev-master", "1.0.0")).to eql(1) end it "dev-master is bigger than dev-support_old" do expect( Versioncmp.compare("dev-master", "dev-support_old")).to eql(1) end it "dev-develop is bigger than 1.0.0" do expect( Versioncmp.compare("dev-develop", "1.0.0")).to eql(1) end it "dev-something is bigger than 1.0.0" do expect( Versioncmp.compare("dev-something", "1.0.0")).to eql(1) end end Add more tests require 'spec_helper' require "naturalsorter" describe Versioncmp do it "smaler" do expect( Versioncmp.compare("1.1", "1.2")).to eql(-1) end it "smaler" do expect( Versioncmp.compare("1.1.5", "1.1.x-dev")).to eql(-1) end it "smaler" do expect( Versioncmp.compare("1.1.5", "1.1-dev")).to eql(-1) end it "smaler" do expect( Versioncmp.compare("0.3", "0.7-groovy-2.0")).to eql(-1) end it "bigger" do expect( Versioncmp.compare("1.1", "1.0")).to eql(1) end it "bigger" do expect( Versioncmp.compare("2.5", "2.0-beta-1")).to eql(1) end it "bigger" do expect( Versioncmp.compare("2.3", "2.0-beta-1")).to eql(1) end it "1.1.1 is bigger than 1.1" do expect( Versioncmp.compare("1.1.1", "1.1")).to eql(1) end it "dev-master is bigger than 10.10.999" do expect( Versioncmp.compare("dev-master", "10.10.999")).to eql(1) end it "2.2.x-dev is bigger than 2.2.1" do expect( Versioncmp.compare("2.2.x-dev", "2.2.1")).to eql(1) end it "3.5.5-1 is bigger than 3.5.5" do expect( Versioncmp.compare("3.5.5-1", "3.5.5")).to eql(1) end it "3.5.5 is smaller than 3.5.5-1 " do expect( Versioncmp.compare("3.5.5", "3.5.5-1")).to eql(-1) end it "2.3.1-b01 is bigger than 2.3.1" do expect( Versioncmp.compare("2.3.1-b01", "2.3.1")).to eql(1) end it "2.3.2-b01 is bigger than 2.3.1" do expect( Versioncmp.compare("2.3.2-b01", "2.3.1")).to eql(1) end it "2.3.d-b01 is smaller than 2.3.1" do expect( Versioncmp.compare("2.3.d-b01", "2.3.1")).to eql(-1) end it "2.18.1 is bigger than 2.18-20141019" do expect( Versioncmp.compare("2.18.1", "2.18-20141019")).to eql(1) end it "2.18-20141019 is smaller than 2.18.1" do expect( Versioncmp.compare("2.18-20141019", "2.18.1")).to eql(-1) end it "1.1 is smaller than 1.1.1" do expect( Versioncmp.compare("1.1", "1.1.1")).to eql(-1) end it "equal" do expect( Versioncmp.compare("1.1", "1.1")).to eql(0) end it "equal" do expect( Versioncmp.compare("1.0", "1.0.0")).to eql(0) end it "1.0.0 is smaller than 1.0.*" do expect( Versioncmp.compare("1.0.0", "1.0.*")).to eql(-1) end it "1.0 is smaller than 1.0.*" do expect( Versioncmp.compare("1.0.0", "1.0.*")).to eql(-1) end it "equal RC" do expect( Versioncmp.compare("1.1.RC1", "1.1.RC1")).to eql(0) end it "smaller RC" do expect( Versioncmp.compare("1.1.RC1", "1.1")).to eql(-1) end it "smaller RC" do expect( Versioncmp.compare("1.1.rc1", "1.1")).to eql(-1) end it "smaller RC" do expect( Versioncmp.compare("1.1.rc1", "2.0")).to eql(-1) end it "smaller RC" do expect( Versioncmp.compare("1.1-rc1", "1.1")).to eql(-1) end it "smaller alpha" do expect( Versioncmp.compare("1.1-alpha1", "1.1")).to eql(-1) end it "alpha is smaller than BETA" do expect( Versioncmp.compare("2.1.0alpha", "2.1.0-BETA1")).to eql(-1) end it "smaller alpha-1" do expect( Versioncmp.compare("1.1-alpha-1", "1.1")).to eql(-1) end it "smaller alpha" do expect( Versioncmp.compare("1.1", "1.1-alpha-1")).to eql(1) end it "smaller beta" do expect( Versioncmp.compare("3.1-beta1", "3.1")).to eql(-1) end it "smaller beta" do expect( Versioncmp.compare("3.1-beta-1", "3.1")).to eql(-1) end it "smaller 3.0-rc4-negotiate" do expect( Versioncmp.compare("3.0-rc4-negotiate", "3.0")).to eql(-1) end it "smaller 3.1-jbossorg-1" do expect( Versioncmp.compare("3.1-jbossorg-1", "3.1")).to eql(-1) end it "smaller 3.1-pre1" do expect( Versioncmp.compare("3.1-pre1", "3.1")).to eql(-1) end it "bigger RC" do expect( Versioncmp.compare("1.1.rc3", "1.1.rc2")).to eql(1) end it "bigger RC than 1.0" do expect( Versioncmp.compare("1.1.RC1", "1.0")).to eql(1) end it "bigger RC than 1.0" do expect( Versioncmp.compare("1.1.RC1", "1.1")).to eql(-1) end it "20040121.140929 is smaller than 1.1" do expect( Versioncmp.compare("20040121.140929", "1.1")).to eql(-1) end it "1.1 is bigger than 20040121.140929" do expect( Versioncmp.compare("1.1", "20040121.140929")).to eql(1) end it "1.7b2 is smaller than 1.7" do expect( Versioncmp.compare("1.7b2", "1.7")).to eql(-1) end it "1.7 is bigger than 1.7b2" do expect( Versioncmp.compare("1.7", "1.7b2")).to eql(1) end it "1.7 is bigger than 1.7rc2" do expect( Versioncmp.compare("1.7", "1.7rc2")).to eql(1) end it "1.7 is bigger than 1.7RC2" do expect( Versioncmp.compare("1.7", "1.7RC2")).to eql(1) end it "1.7 is bigger than 1.7a" do expect( Versioncmp.compare("1.7", "1.7a")).to eql(1) end it "1.7 is bigger than 1.7b" do expect( Versioncmp.compare("1.7", "1.7b")).to eql(1) end it "1.7b is bigger than 1.7a" do expect( Versioncmp.compare("1.7b", "1.7a")).to eql(1) end it "1.7.1rc1 is smaller than 1.7.2" do expect( Versioncmp.compare("1.7.1rc1", "1.7.2")).to eql(-1) end it "1.7.2 is bigger than 1.7.1rc1" do expect( Versioncmp.compare("1.7.2", "1.7.1rc1")).to eql(1) end it "99.0-does-not-exist is smaller than 1.7.1" do expect( Versioncmp.compare("99.0-does-not-exist", "1.7.1")).to eql(-1) end it "2.2.1-b03 is bigger then 2.2" do expect( Versioncmp.compare("2.2.1-b03", "2.2")).to eql(1) end it "3.0.0 is equal to 3.0" do expect( Versioncmp.compare("3.0.0", "3.0")).to eql(0) end it "3.0 is equal to 3.0.0" do expect( Versioncmp.compare("3.0", "3.0.0")).to eql(0) end it "3.1-SNAPSHOT is equal to 3.1-SNAPSHOT" do expect( Versioncmp.compare("3.1-SNAPSHOT", "3.1-SNAPSHOT")).to eql(0) end it "3.1-SNAPSHOT is smaller than 3.2-SNAPSHOT" do expect( Versioncmp.compare("3.1-SNAPSHOT", "3.2-SNAPSHOT")).to eql(-1) end it "3.1 is smaller than 3.2-SNAPSHOT" do expect( Versioncmp.compare("3.1", "3.2-SNAPSHOT")).to eql(-1) end it "1.5.2 is smaller than 1.5.2-patch1" do expect( Versioncmp.compare("1.5.2", "1.5.2-patch1")).to eql(-1) end it "dev-master is bigger than 1.0.0" do expect( Versioncmp.compare("dev-master", "1.0.0")).to eql(1) end it "dev-master is bigger than dev-support_old" do expect( Versioncmp.compare("dev-master", "dev-support_old")).to eql(1) end it "dev-develop is bigger than 1.0.0" do expect( Versioncmp.compare("dev-develop", "1.0.0")).to eql(1) end it "dev-something is bigger than 1.0.0" do expect( Versioncmp.compare("dev-something", "1.0.0")).to eql(1) end end
#module EnjuNii class Ability include CanCan::Ability def initialize(user, ip_address = '0.0.0.0') case user.try(:role).try(:name) when 'Administrator' can [:read, :update], NiiType can [:destroy, :delete], NiiType do |nii_type| true unless nii_type.manifestations.exists? end if LibraryGroup.site_config.network_access_allowed?(ip_address) else can :read, NiiType end end end #end remove dummy file
# encoding: utf-8 require 'spec_helper' require 'open_classes/string/uniq' describe String do context :uniq do cases = [ { case_no: 1, case_title: 'normal case', input: 'abcdac', expected: 'abcd', }, { case_no: 2, case_title: 'not exist duplication case', input: 'abc', expected: 'abc', }, { case_no: 3, case_title: 'empty case', input: '', expected: '', }, ] cases.each do |c| it "|case_no=#{c[:case_no]}|case_title=#{c[:case_title]}" do begin case_before c # -- given -- # nothing # -- when -- actual = c[:input].uniq # -- then -- expect(actual).to eq(c[:expected]) ensure case_after c end end def case_before(c) # implement each case before end def case_after(c) # implement each case after end end end end Fix rubocop warning 'TrailingComma' in uniq_spec # encoding: utf-8 require 'spec_helper' require 'open_classes/string/uniq' describe String do context :uniq do cases = [ { case_no: 1, case_title: 'normal case', input: 'abcdac', expected: 'abcd' }, { case_no: 2, case_title: 'not exist duplication case', input: 'abc', expected: 'abc' }, { case_no: 3, case_title: 'empty case', input: '', expected: '' } ] cases.each do |c| it "|case_no=#{c[:case_no]}|case_title=#{c[:case_title]}" do begin case_before c # -- given -- # nothing # -- when -- actual = c[:input].uniq # -- then -- expect(actual).to eq(c[:expected]) ensure case_after c end end def case_before(c) # implement each case before end def case_after(c) # implement each case after end end end end
require 'faker' FactoryGirl.define do factory :taxonomite_node, :class => 'Taxonomite::Node' do name { Faker::Lorem.word.capitalize } description { Faker::Lorem.paragraph } end factory :taxonomite_species, :class => 'Taxonomite::Species' do name { "#{Faker::Lorem.word.capitalize} #{Faker::Lorem.word}" } description { Faker::Lorem.paragraph } end factory :taxonomite_genus, :class => 'Taxonomite::Genus' do name { "#{Faker::Lorem.word.capitalize} #{Faker::Lorem.word}" } description { Faker::Lorem.paragraph } end factory :taxonomite_family, :class => 'Taxonomite::Family' do name { "#{Faker::Lorem.word.capitalize} #{Faker::Lorem.word}" } description { Faker::Lorem.paragraph } end factory :taxonomite_order, :class => 'Taxonomite::Order' do name { "#{Faker::Lorem.word.capitalize} #{Faker::Lorem.word}" } description { Faker::Lorem.paragraph } end factory :taxonomite_class, :class => 'Taxonomite::Class' do name { "#{Faker::Lorem.word.capitalize} #{Faker::Lorem.word}" } description { Faker::Lorem.paragraph } end factory :taxonomite_phylum, :class => 'Taxonomite::Phylum' do name { "#{Faker::Lorem.word.capitalize} #{Faker::Lorem.word}" } description { Faker::Lorem.paragraph } end factory :taxonomite_kingdom, :class => 'Taxonomite::Kingdom' do name { "#{Faker::Lorem.word.capitalize} #{Faker::Lorem.word}" } description { Faker::Lorem.paragraph } end end fix factories (drop description from Node) require 'faker' FactoryGirl.define do factory :taxonomite_node, :class => 'Taxonomite::Node' do name { Faker::Lorem.word.capitalize } end factory :taxonomite_species, :class => 'Taxonomite::Species' do name { "#{Faker::Lorem.word.capitalize} #{Faker::Lorem.word}" } end factory :taxonomite_genus, :class => 'Taxonomite::Genus' do name { "#{Faker::Lorem.word.capitalize} #{Faker::Lorem.word}" } end factory :taxonomite_family, :class => 'Taxonomite::Family' do name { "#{Faker::Lorem.word.capitalize} #{Faker::Lorem.word}" } end factory :taxonomite_order, :class => 'Taxonomite::Order' do name { "#{Faker::Lorem.word.capitalize} #{Faker::Lorem.word}" } end factory :taxonomite_class, :class => 'Taxonomite::Class' do name { "#{Faker::Lorem.word.capitalize} #{Faker::Lorem.word}" } end factory :taxonomite_phylum, :class => 'Taxonomite::Phylum' do name { "#{Faker::Lorem.word.capitalize} #{Faker::Lorem.word}" } end factory :taxonomite_kingdom, :class => 'Taxonomite::Kingdom' do name { "#{Faker::Lorem.word.capitalize} #{Faker::Lorem.word}" } end end
add date_spec test require 'date' require 'time' describe "DateTime" do it "should parse datetime" do str = "2010-07-08T12:14:20Z" date = Time.parse(str) date.year.should == 2010 date.hour.should == 12 str2 = date.strftime("%m/%d/%Y") str2.should == "07/08/2010" end end
require 'spec_helper' include Warden::Test::Helpers describe_options = { type: :feature } describe_options[:js] = true if ENV['JS'] describe 'end to end behavior', describe_options do before(:all) do @old_resque_inline_value = Resque.inline Resque.inline = true end after(:all) do Resque.inline = @old_resque_inline_value User.destroy_all Batch.destroy_all end let(:user) { FactoryGirl.find_or_create(:user) } let(:prefix) { Time.now.strftime("%Y-%m-%d-%H-%M-%S-%L") } let(:initial_title) { "#{prefix} Something Special" } let(:initial_file_path) { __FILE__ } let(:updated_title) { "#{prefix} Another Not Quite" } let(:updated_file_path) { Rails.root.join('app/controllers/application_controller.rb').to_s } describe 'upload a file' do let(:agreed_to_terms_of_service) { false } it "should show up on dashboard", js: true do login_js visit '/' click_link('Share Your Work') check("terms_of_service") test_file_path = Rails.root.join('spec/fixtures/world.png').to_s file_format = 'png (Portable Network Graphics)' page.execute_script(%Q{$("input[type=file]").css("opacity", "1").css("-moz-transform", "none");$("input[type=file]").attr('id',"fileselect");}) attach_file("fileselect", test_file_path) page.first('.start').click page.should have_content('Apply Metadata') fill_in('generic_file_title', with: 'MY Title for the World') fill_in('generic_file_tag', with: 'test') fill_in('generic_file_creator', with: 'me') click_link('License Descriptions') page.should have_content('ScholarSphere License Descriptions') click_on('Close') page.should have_css('#rightsModal', visible: false) click_link("What's this") page.should have_content('ScholarSphere Permissions') click_on('Close') page.should have_css('#myModal', visible: false) page.should have_content('Save') click_on('upload_submit') URI(current_url).path.should == Sufia::Engine.routes.url_helpers.dashboard_files_path page.should have_content('Browse By') page.should have_content('MY Title for the World') within('#facets') do # I call CSS/DOM shenanigans; I can't access 'Creator' link # directly and instead must find by CSS selector, validate it all('a.accordion-toggle').each do |elem| elem.click if elem.text == 'File Format' end within ('#collapse_File_Format_db') do click_on(file_format) end end page.should have_content('X png (Portable Network Graphics)') page.should have_no_content("Your files are being processed by ScholarSphere in the background.") page.should have_content(file_format) within('.alert-warning') do page.should have_content(file_format) end page.should have_content('MY Title for the World') within('#documents') do first('button.dropdown-toggle').click click_link('Edit File') end page.should have_content('Edit MY Title for the World') first('i.glyphicon-question-sign').click # TODO: more test for edit? go_to_dashboard_files count = 0 within('#documents') do count = all('button.dropdown-toggle').count end 1.upto(count) do within('#documents') do first('button.dropdown-toggle').click click_link('Delete File') end URI(current_url).path.should == Sufia::Engine.routes.url_helpers.dashboard_files_path end within('#documents') do all('button.dropdown-toggle').count.should == 0 end end end end Adding sleep to make test work on servers require 'spec_helper' include Warden::Test::Helpers describe_options = { type: :feature } describe_options[:js] = true if ENV['JS'] describe 'end to end behavior', describe_options do before(:all) do @old_resque_inline_value = Resque.inline Resque.inline = true end after(:all) do Resque.inline = @old_resque_inline_value User.destroy_all Batch.destroy_all end let(:user) { FactoryGirl.find_or_create(:user) } let(:prefix) { Time.now.strftime("%Y-%m-%d-%H-%M-%S-%L") } let(:initial_title) { "#{prefix} Something Special" } let(:initial_file_path) { __FILE__ } let(:updated_title) { "#{prefix} Another Not Quite" } let(:updated_file_path) { Rails.root.join('app/controllers/application_controller.rb').to_s } describe 'upload a file' do let(:agreed_to_terms_of_service) { false } it "should show up on dashboard", js: true do login_js visit '/' click_link('Share Your Work') check("terms_of_service") test_file_path = Rails.root.join('spec/fixtures/world.png').to_s file_format = 'png (Portable Network Graphics)' page.execute_script(%Q{$("input[type=file]").css("opacity", "1").css("-moz-transform", "none");$("input[type=file]").attr('id',"fileselect");}) attach_file("fileselect", test_file_path) page.first('.start').click page.should have_content('Apply Metadata') fill_in('generic_file_title', with: 'MY Title for the World') fill_in('generic_file_tag', with: 'test') fill_in('generic_file_creator', with: 'me') page.should have_css('#rightsModal.modal[aria-hidden*="true"]', visible: false) click_link('License Descriptions') sleep(1) page.should have_content('ScholarSphere License Descriptions') click_on('Close') sleep(1) page.should_not have_content('ScholarSph7ere License Descriptions') page.should have_css('#rightsModal', visible: false) click_link("What's this") sleep(1) page.should have_content('ScholarSphere Permissions') click_on('Close') sleep(1) page.should_not have_content('ScholarSphere Permissions') page.should have_css('#myModal', visible: false) page.should have_css('#myModal.modal[aria-hidden*="true"]', visible: false) page.should have_content('Save') click_on('upload_submit') URI(current_url).path.should == Sufia::Engine.routes.url_helpers.dashboard_files_path page.should have_content('Browse By') page.should have_content('MY Title for the World') within('#facets') do # I call CSS/DOM shenanigans; I can't access 'Creator' link # directly and instead must find by CSS selector, validate it all('a.accordion-toggle').each do |elem| elem.click if elem.text == 'File Format' end within ('#collapse_File_Format_db') do click_on(file_format) end end page.should have_content('X png (Portable Network Graphics)') page.should have_no_content("Your files are being processed by ScholarSphere in the background.") page.should have_content(file_format) within('.alert-warning') do page.should have_content(file_format) end page.should have_content('MY Title for the World') within('#documents') do first('button.dropdown-toggle').click click_link('Edit File') end page.should have_content('Edit MY Title for the World') first('i.glyphicon-question-sign').click # TODO: more test for edit? go_to_dashboard_files count = 0 within('#documents') do count = all('button.dropdown-toggle').count end 1.upto(count) do within('#documents') do first('button.dropdown-toggle').click click_link('Delete File') end URI(current_url).path.should == Sufia::Engine.routes.url_helpers.dashboard_files_path end within('#documents') do all('button.dropdown-toggle').count.should == 0 end end end end
require 'spec_helper' describe Resque::Plugins::ConcurrentRestriction::Worker do include PerformJob before(:each) do Resque.redis.flushall end after(:each) do Resque.redis.lrange("failed", 0, -1).size.should == 0 Resque.redis.get("stat:failed").to_i.should == 0 end it "should do nothing for no jobs" do run_resque_queue('*') Resque.redis.keys("restriction:*").should == [] end it "should run normal job without restriction" do run_resque_job(NoRestrictionJob, :queue => :normal, :inline => true) Resque.size(:normal).should == 0 NoRestrictionJob.run_count.should == 1 Resque.redis.keys("restriction:*").should == [] end it "should run a restricted job that is not currently restricted" do run_resque_job(RestrictionJob, :queue => :normal) Resque.size(:normal).should == 0 RestrictionJob.run_count.should == 1 RestrictionJob.running_count(RestrictionJob.tracking_key).should == 0 end it "should stash a restricted job that is currently restricted" do RestrictionJob.set_running_count(RestrictionJob.tracking_key, 99) run_resque_job(RestrictionJob, :queue => :normal) Resque.size(:normal).should == 0 RestrictionJob.run_count.should == 0 RestrictionJob.next_runnable_job(:normal).should be_nil RestrictionJob.set_running_count(RestrictionJob.tracking_key, 0) RestrictionJob.next_runnable_job(:normal).should == Resque::Job.new('normal', {'class' => 'RestrictionJob', 'args' => []}) end it "should pull job from restricted queue if nothing to run" do RestrictionJob.set_running_count(RestrictionJob.tracking_key, 99) run_resque_job(RestrictionJob, :queue => :normal) RestrictionJob.run_count.should == 0 RestrictionJob.set_running_count(RestrictionJob.tracking_key, 0) RestrictionJob.restriction_queue(RestrictionJob.tracking_key, :normal).should_not == [] run_resque_queue(:normal) RestrictionJob.next_runnable_job(:normal).should be_nil RestrictionJob.run_count.should == 1 end it "should prefer running a normal job over one on restriction queue" do Resque::Plugins::ConcurrentRestriction.restricted_before_queued.should == false RestrictionJob.set_running_count(RestrictionJob.tracking_key, 99) run_resque_job(RestrictionJob, :queue => :normal) RestrictionJob.run_count.should == 0 RestrictionJob.set_running_count(RestrictionJob.tracking_key, 0) run_resque_job(NoRestrictionJob, :queue => :normal) RestrictionJob.restriction_queue(RestrictionJob.tracking_key, :normal).should_not == [] NoRestrictionJob.run_count.should == 1 RestrictionJob.run_count.should == 0 run_resque_queue(:normal) RestrictionJob.restriction_queue(RestrictionJob.tracking_key, :normal).should == [] NoRestrictionJob.run_count.should == 1 RestrictionJob.run_count.should == 1 end it "should prefer running a restricted job over normal one when option given" do begin Resque::Plugins::ConcurrentRestriction.restricted_before_queued = true RestrictionJob.set_running_count(RestrictionJob.tracking_key, 99) run_resque_job(RestrictionJob, :queue => :normal) RestrictionJob.run_count.should == 0 RestrictionJob.set_running_count(RestrictionJob.tracking_key, 0) run_resque_job(NoRestrictionJob, :queue => :normal) RestrictionJob.restriction_queue(RestrictionJob.tracking_key, :normal).should == [] NoRestrictionJob.run_count.should == 0 RestrictionJob.run_count.should == 1 run_resque_queue(:normal) RestrictionJob.restriction_queue(RestrictionJob.tracking_key, :normal).should == [] NoRestrictionJob.run_count.should == 1 RestrictionJob.run_count.should == 1 ensure Resque::Plugins::ConcurrentRestriction.restricted_before_queued = false end end it "should be able to run multiple restricted jobs in a row without exceeding restriction" do run_resque_job(RestrictionJob, :queue => :normal) run_resque_job(RestrictionJob, :queue => :normal) RestrictionJob.run_count.should == 2 end it "should be able to run more restricted jobs than limit in a row" do 7.times {|i| Resque.enqueue(RestrictionJob, i) } 7.times {|i| run_resque_queue(:normal) } RestrictionJob.total_run_count.should == 7 end it "should preserve queue in restricted job on restriction queue" do RestrictionJob.set_running_count(RestrictionJob.tracking_key, 99) run_resque_job(RestrictionJob, :queue => :some_queue) RestrictionJob.set_running_count(RestrictionJob.tracking_key, 0) run_resque_queue(:normal) RestrictionJob.run_count.should == 0 run_resque_queue('some_queue') RestrictionJob.run_count.should == 1 end it "should track how many jobs are currently running" do t = Thread.new do run_resque_job(ConcurrentRestrictionJob) end sleep 0.1 ConcurrentRestrictionJob.running_count(ConcurrentRestrictionJob.tracking_key).should == 1 t.join ConcurrentRestrictionJob.running_count(ConcurrentRestrictionJob.tracking_key).should == 0 end it "should run multiple jobs concurrently" do 7.times {|i| Resque.enqueue(MultipleConcurrentRestrictionJob, i) } 7.times do unless child = fork Resque.redis.client.connect run_resque_queue('*') exit! end end sleep 0.25 MultipleConcurrentRestrictionJob.total_run_count.should == 4 MultipleConcurrentRestrictionJob.running_count(MultipleConcurrentRestrictionJob.tracking_key).should == 4 MultipleConcurrentRestrictionJob.restriction_queue(MultipleConcurrentRestrictionJob.tracking_key, :normal).size.should == 3 Process.waitall 3.times do unless child = fork Resque.redis.client.connect run_resque_queue('*') exit! end end sleep 0.25 MultipleConcurrentRestrictionJob.total_run_count.should == 7 MultipleConcurrentRestrictionJob.running_count(MultipleConcurrentRestrictionJob.tracking_key).should == 3 MultipleConcurrentRestrictionJob.restriction_queue(MultipleConcurrentRestrictionJob.tracking_key, :normal).size.should == 0 Process.waitall MultipleConcurrentRestrictionJob.running_count(MultipleConcurrentRestrictionJob.tracking_key).should == 0 MultipleConcurrentRestrictionJob.total_run_count.should == 7 end it "should run only one concurrent job" do 5.times {|i| Resque.enqueue(OneConcurrentRestrictionJob, i) } 5.times do unless child = fork Resque.redis.client.connect run_resque_queue('*') exit! end end sleep 0.25 OneConcurrentRestrictionJob.total_run_count.should == 1 OneConcurrentRestrictionJob.running_count(OneConcurrentRestrictionJob.tracking_key).should == 1 OneConcurrentRestrictionJob.restriction_queue(OneConcurrentRestrictionJob.tracking_key, :normal).size.should == 4 Process.waitall 2.times do unless child = fork Resque.redis.client.connect run_resque_queue('*') exit! end end sleep 0.25 OneConcurrentRestrictionJob.total_run_count.should == 2 OneConcurrentRestrictionJob.running_count(OneConcurrentRestrictionJob.tracking_key).should == 1 OneConcurrentRestrictionJob.restriction_queue(OneConcurrentRestrictionJob.tracking_key, :normal).size.should == 3 Process.waitall OneConcurrentRestrictionJob.running_count(OneConcurrentRestrictionJob.tracking_key).should == 0 OneConcurrentRestrictionJob.total_run_count.should == 2 end it "should decrement execution number when concurrent job fails" do run_resque_job(ConcurrentRestrictionJob, "bad") Resque.redis.lrange("failed", 0, -1).size.should == 1 ConcurrentRestrictionJob.running_count(ConcurrentRestrictionJob.tracking_key).should == 0 Resque.redis.del("failed") Resque.redis.del("stat:failed") end it "should handle jobs with custom restriction identifier" do IdentifiedRestrictionJob.set_running_count(IdentifiedRestrictionJob.tracking_key(1), 99) run_resque_job(IdentifiedRestrictionJob, 1, :queue => :normal) run_resque_job(IdentifiedRestrictionJob, 2, :queue => :normal) IdentifiedRestrictionJob.run_count(1).should == 0 IdentifiedRestrictionJob.run_count(2).should == 1 IdentifiedRestrictionJob.set_running_count(IdentifiedRestrictionJob.tracking_key(1), 0) run_resque_queue(:normal) IdentifiedRestrictionJob.restriction_queue(IdentifiedRestrictionJob.tracking_key(1), :normal).should == [] IdentifiedRestrictionJob.run_count(1).should == 1 IdentifiedRestrictionJob.run_count(2).should == 1 end it "should track queue" do RestrictionJob.set_running_count(RestrictionJob.tracking_key, 99) run_resque_job(RestrictionJob, 1, :queue => :normal1) run_resque_job(RestrictionJob, 2, :queue => :normal1) run_resque_job(RestrictionJob, 3, :queue => :normal2) RestrictionJob.run_count.should == 0 RestrictionJob.set_running_count(RestrictionJob.tracking_key, 0) run_resque_queue(:normal1) RestrictionJob.total_run_count.should == 1 run_resque_queue(:normal1) RestrictionJob.total_run_count.should == 2 run_resque_queue(:normal2) RestrictionJob.total_run_count.should == 3 end it "should override number of retries with environment variable" do # Something.get_queued_job_retries.should == Resque::Plugins::ConcurrentRestriction::Job::DEFAULT_GET_QUEUED_JOB_RETRIES # ENV['GET_QUEUED_JOB_RETRIES'] = 3 # Something.get_queued_job_retries.should == ENV['GET_QUEUED_JOB_RETRIES'].to_i end it "should move multiple items to the restricted queue each iteration" do # TODO: implement me! end end Add tests to cover new functionality require 'spec_helper' describe Resque::Plugins::ConcurrentRestriction::Worker do include PerformJob before(:each) do Resque.redis.flushall end after(:each) do Resque.redis.lrange("failed", 0, -1).size.should == 0 Resque.redis.get("stat:failed").to_i.should == 0 end it "should do nothing for no jobs" do run_resque_queue('*') Resque.redis.keys("restriction:*").should == [] end it "should run normal job without restriction" do run_resque_job(NoRestrictionJob, :queue => :normal, :inline => true) Resque.size(:normal).should == 0 NoRestrictionJob.run_count.should == 1 Resque.redis.keys("restriction:*").should == [] end it "should run a restricted job that is not currently restricted" do run_resque_job(RestrictionJob, :queue => :normal) Resque.size(:normal).should == 0 RestrictionJob.run_count.should == 1 RestrictionJob.running_count(RestrictionJob.tracking_key).should == 0 end it "should stash a restricted job that is currently restricted" do RestrictionJob.set_running_count(RestrictionJob.tracking_key, 99) run_resque_job(RestrictionJob, :queue => :normal) Resque.size(:normal).should == 0 RestrictionJob.run_count.should == 0 RestrictionJob.next_runnable_job(:normal).should be_nil RestrictionJob.set_running_count(RestrictionJob.tracking_key, 0) RestrictionJob.next_runnable_job(:normal).should == Resque::Job.new('normal', {'class' => 'RestrictionJob', 'args' => []}) end it "should pull job from restricted queue if nothing to run" do RestrictionJob.set_running_count(RestrictionJob.tracking_key, 99) run_resque_job(RestrictionJob, :queue => :normal) RestrictionJob.run_count.should == 0 RestrictionJob.set_running_count(RestrictionJob.tracking_key, 0) RestrictionJob.restriction_queue(RestrictionJob.tracking_key, :normal).should_not == [] run_resque_queue(:normal) RestrictionJob.next_runnable_job(:normal).should be_nil RestrictionJob.run_count.should == 1 end it "should prefer running a normal job over one on restriction queue" do Resque::Plugins::ConcurrentRestriction.restricted_before_queued.should == false RestrictionJob.set_running_count(RestrictionJob.tracking_key, 99) run_resque_job(RestrictionJob, :queue => :normal) RestrictionJob.run_count.should == 0 RestrictionJob.set_running_count(RestrictionJob.tracking_key, 0) run_resque_job(NoRestrictionJob, :queue => :normal) RestrictionJob.restriction_queue(RestrictionJob.tracking_key, :normal).should_not == [] NoRestrictionJob.run_count.should == 1 RestrictionJob.run_count.should == 0 run_resque_queue(:normal) RestrictionJob.restriction_queue(RestrictionJob.tracking_key, :normal).should == [] NoRestrictionJob.run_count.should == 1 RestrictionJob.run_count.should == 1 end it "should prefer running a restricted job over normal one when option given" do begin Resque::Plugins::ConcurrentRestriction.restricted_before_queued = true RestrictionJob.set_running_count(RestrictionJob.tracking_key, 99) run_resque_job(RestrictionJob, :queue => :normal) RestrictionJob.run_count.should == 0 RestrictionJob.set_running_count(RestrictionJob.tracking_key, 0) run_resque_job(NoRestrictionJob, :queue => :normal) RestrictionJob.restriction_queue(RestrictionJob.tracking_key, :normal).should == [] NoRestrictionJob.run_count.should == 0 RestrictionJob.run_count.should == 1 run_resque_queue(:normal) RestrictionJob.restriction_queue(RestrictionJob.tracking_key, :normal).should == [] NoRestrictionJob.run_count.should == 1 RestrictionJob.run_count.should == 1 ensure Resque::Plugins::ConcurrentRestriction.restricted_before_queued = false end end it "should be able to run multiple restricted jobs in a row without exceeding restriction" do run_resque_job(RestrictionJob, :queue => :normal) run_resque_job(RestrictionJob, :queue => :normal) RestrictionJob.run_count.should == 2 end it "should be able to run more restricted jobs than limit in a row" do 7.times {|i| Resque.enqueue(RestrictionJob, i) } 7.times {|i| run_resque_queue(:normal) } RestrictionJob.total_run_count.should == 7 end it "should preserve queue in restricted job on restriction queue" do RestrictionJob.set_running_count(RestrictionJob.tracking_key, 99) run_resque_job(RestrictionJob, :queue => :some_queue) RestrictionJob.set_running_count(RestrictionJob.tracking_key, 0) run_resque_queue(:normal) RestrictionJob.run_count.should == 0 run_resque_queue('some_queue') RestrictionJob.run_count.should == 1 end it "should track how many jobs are currently running" do t = Thread.new do run_resque_job(ConcurrentRestrictionJob) end sleep 0.1 ConcurrentRestrictionJob.running_count(ConcurrentRestrictionJob.tracking_key).should == 1 t.join ConcurrentRestrictionJob.running_count(ConcurrentRestrictionJob.tracking_key).should == 0 end it "should run multiple jobs concurrently" do 7.times {|i| Resque.enqueue(MultipleConcurrentRestrictionJob, i) } 7.times do unless child = fork Resque.redis.client.connect run_resque_queue('*') exit! end end sleep 0.25 MultipleConcurrentRestrictionJob.total_run_count.should == 4 MultipleConcurrentRestrictionJob.running_count(MultipleConcurrentRestrictionJob.tracking_key).should == 4 MultipleConcurrentRestrictionJob.restriction_queue(MultipleConcurrentRestrictionJob.tracking_key, :normal).size.should == 3 Process.waitall 3.times do unless child = fork Resque.redis.client.connect run_resque_queue('*') exit! end end sleep 0.25 MultipleConcurrentRestrictionJob.total_run_count.should == 7 MultipleConcurrentRestrictionJob.running_count(MultipleConcurrentRestrictionJob.tracking_key).should == 3 MultipleConcurrentRestrictionJob.restriction_queue(MultipleConcurrentRestrictionJob.tracking_key, :normal).size.should == 0 Process.waitall MultipleConcurrentRestrictionJob.running_count(MultipleConcurrentRestrictionJob.tracking_key).should == 0 MultipleConcurrentRestrictionJob.total_run_count.should == 7 end it "should run only one concurrent job" do 5.times {|i| Resque.enqueue(OneConcurrentRestrictionJob, i) } 5.times do unless child = fork Resque.redis.client.connect run_resque_queue('*') exit! end end sleep 0.25 OneConcurrentRestrictionJob.total_run_count.should == 1 OneConcurrentRestrictionJob.running_count(OneConcurrentRestrictionJob.tracking_key).should == 1 OneConcurrentRestrictionJob.restriction_queue(OneConcurrentRestrictionJob.tracking_key, :normal).size.should == 4 Process.waitall 2.times do unless child = fork Resque.redis.client.connect run_resque_queue('*') exit! end end sleep 0.25 OneConcurrentRestrictionJob.total_run_count.should == 2 OneConcurrentRestrictionJob.running_count(OneConcurrentRestrictionJob.tracking_key).should == 1 OneConcurrentRestrictionJob.restriction_queue(OneConcurrentRestrictionJob.tracking_key, :normal).size.should == 3 Process.waitall OneConcurrentRestrictionJob.running_count(OneConcurrentRestrictionJob.tracking_key).should == 0 OneConcurrentRestrictionJob.total_run_count.should == 2 end it "should decrement execution number when concurrent job fails" do run_resque_job(ConcurrentRestrictionJob, "bad") Resque.redis.lrange("failed", 0, -1).size.should == 1 ConcurrentRestrictionJob.running_count(ConcurrentRestrictionJob.tracking_key).should == 0 Resque.redis.del("failed") Resque.redis.del("stat:failed") end it "should handle jobs with custom restriction identifier" do IdentifiedRestrictionJob.set_running_count(IdentifiedRestrictionJob.tracking_key(1), 99) run_resque_job(IdentifiedRestrictionJob, 1, :queue => :normal) run_resque_job(IdentifiedRestrictionJob, 2, :queue => :normal) IdentifiedRestrictionJob.run_count(1).should == 0 IdentifiedRestrictionJob.run_count(2).should == 1 IdentifiedRestrictionJob.set_running_count(IdentifiedRestrictionJob.tracking_key(1), 0) run_resque_queue(:normal) IdentifiedRestrictionJob.restriction_queue(IdentifiedRestrictionJob.tracking_key(1), :normal).should == [] IdentifiedRestrictionJob.run_count(1).should == 1 IdentifiedRestrictionJob.run_count(2).should == 1 end it "should track queue" do RestrictionJob.set_running_count(RestrictionJob.tracking_key, 99) run_resque_job(RestrictionJob, 1, :queue => :normal1) run_resque_job(RestrictionJob, 2, :queue => :normal1) run_resque_job(RestrictionJob, 3, :queue => :normal2) RestrictionJob.run_count.should == 0 RestrictionJob.set_running_count(RestrictionJob.tracking_key, 0) run_resque_queue(:normal1) RestrictionJob.total_run_count.should == 1 run_resque_queue(:normal1) RestrictionJob.total_run_count.should == 2 run_resque_queue(:normal2) RestrictionJob.total_run_count.should == 3 end it "should move multiple items to the restricted queue each iteration" do RestrictionJob.set_running_count(RestrictionJob.tracking_key, 99) 5.times {|i| Resque.enqueue(RestrictionJob, :queue => :normal)} Resque.size(:normal).should == 5 RestrictionJob.restriction_queue(RestrictionJob.tracking_key, :normal).size.should == 0 Resque::Plugins::ConcurrentRestriction.get_queued_job_attempts = 3 run_resque_queue(:normal) RestrictionJob.run_count.should == 0 Resque.size(:normal).should == 2 RestrictionJob.restriction_queue(RestrictionJob.tracking_key, :normal).size.should == 3 end end
require 'spec_helper' describe Geometry::Comparison do describe '#compare_points' do # it 'should be true when both abscissas and ordinates are equal' do # compare = Geometry::Comparison.new(1, 1 ,1 ,1) # expect(compare.compare_points).to eq(true) # end it 'should be true when both abscissas and ordinates equal' do point1 = Geometry::Comparison.new(1, 2) point2 = Geometry::Comparison.new(1, 2) expect(point1 == point2).to eq(true) end it 'should be false when both abscissas and ordinates are not equal' do point1 = Geometry::Comparison.new(1, 2) point2 = Geometry::Comparison.new(1, 3) expect(point1 == point2).to eq(false) end it 'should return true for (Reflexive property) given one point'do point1 = Geometry::Comparison.new(1, 1) expect(point1 == point1).to eq(true) end it 'should return true for symmetric property for given two points 'do point1 = Geometry::Comparison.new(1, 1) point2 = Geometry::Comparison.new(1, 1) expect(point1 == point2 && point2 == point1).to eq(true) end it 'should return false when given a NIL point ' do point1 = Geometry::Comparison.new(1, 1) point2 = Geometry::Comparison.new(nil,nil) expect{ point1 == point2 }.to raise_error(NoMethodError) end end end Corrected the nil check test spec for given two points require 'spec_helper' describe Geometry::Comparison do describe '#compare_points' do # it 'should be true when both abscissas and ordinates are equal' do # compare = Geometry::Comparison.new(1, 1 ,1 ,1) # expect(compare.compare_points).to eq(true) # end it 'should be true when both abscissas and ordinates equal' do point1 = Geometry::Comparison.new(1, 2) point2 = Geometry::Comparison.new(1, 2) expect(point1 == point2).to eq(true) end it 'should be false when both abscissas and ordinates are not equal' do point1 = Geometry::Comparison.new(1, 2) point2 = Geometry::Comparison.new(1, 3) expect(point1 == point2).to eq(false) end it 'should return true for (Reflexive property) given one point'do point1 = Geometry::Comparison.new(1, 1) expect(point1 == point1).to eq(true) end it 'should return true for symmetric property for given two points 'do point1 = Geometry::Comparison.new(1, 1) point2 = Geometry::Comparison.new(1, 1) expect(point1 == point2 && point2 == point1).to eq(true) end it 'should return false when given a NIL point ' do point1 = Geometry::Comparison.new(1, 1) point2 = Geometry::Comparison.new(nil,nil) expect(point1 ==point2).to eq(false) end end end
ENV["RAILS_ENV"] = "test" require "webmock" require "pact/provider/rspec" require "rails_helper" WebMock.disable! Pact.configure do |config| config.reports_dir = "spec/reports/pacts" config.include WebMock::API config.include WebMock::Matchers end def url_encode(str) ERB::Util.url_encode(str) end Pact.service_provider "Content Store" do honours_pact_with "Publishing API" do if ENV['USE_LOCAL_PACT'] pact_uri ENV.fetch('PUBLISHING_API_PACT_PATH', '../publishing-api/spec/pacts/publishing_api-content_store.json') else base_url = ENV.fetch("PACT_BROKER_BASE_URL", "https://pact-broker.cloudapps.digital") url = "#{base_url}/pacts/provider/#{url_encode(name)}/consumer/#{url_encode(consumer_name)}" version_part = ENV['PUBLISHING_API_PACT_VERSION'] ? "versions/#{url_encode(ENV['PUBLISHING_API_PACT_VERSION'])}" : 'latest' pact_uri "#{url}/#{version_part}" end end end Pact.provider_states_for "Publishing API" do set_up do WebMock.enable! WebMock.reset! DatabaseCleaner.clean_with :truncation end tear_down do WebMock.disable! end provider_state "no content item exists with base_path /vat-rates" do set_up do # no-op end end provider_state "a content item exists with base_path /vat-rates" do set_up do FactoryGirl.create(:content_item, base_path: "/vat-rates") end end provider_state "a content item exists with base_path /vat-rates and payload_version 0" do set_up do FactoryGirl.create(:content_item, base_path: "/vat-rates", payload_version: 0) end end provider_state "a content item exists with base_path /vat-rates and payload_version 10" do set_up do FactoryGirl.create(:content_item, base_path: "/vat-rates", payload_version: 10) end end end Stub some router-api requests in the pact tests Changing the Content Store to delete routes upon the deletion of the content means that in the pact tests with the Publishing API, requests are made to the router-api. This commit puts in some basic stubs for these requests. ENV["RAILS_ENV"] = "test" require "webmock" require "pact/provider/rspec" require "rails_helper" WebMock.disable! Pact.configure do |config| config.reports_dir = "spec/reports/pacts" config.include WebMock::API config.include WebMock::Matchers end def url_encode(str) ERB::Util.url_encode(str) end Pact.service_provider "Content Store" do honours_pact_with "Publishing API" do if ENV['USE_LOCAL_PACT'] pact_uri ENV.fetch('PUBLISHING_API_PACT_PATH', '../publishing-api/spec/pacts/publishing_api-content_store.json') else base_url = ENV.fetch("PACT_BROKER_BASE_URL", "https://pact-broker.cloudapps.digital") url = "#{base_url}/pacts/provider/#{url_encode(name)}/consumer/#{url_encode(consumer_name)}" version_part = ENV['PUBLISHING_API_PACT_VERSION'] ? "versions/#{url_encode(ENV['PUBLISHING_API_PACT_VERSION'])}" : 'latest' pact_uri "#{url}/#{version_part}" end end end Pact.provider_states_for "Publishing API" do set_up do WebMock.enable! WebMock.reset! DatabaseCleaner.clean_with :truncation escaped_router_api_prefix = Regexp.escape(Plek.find('router-api')) stub_request( :delete, %r(\A#{escaped_router_api_prefix}/routes) ).to_return( status: 404, body: "{}", headers: { "Content-Type" => "application/json" } ) stub_request( :post, %r(\A#{escaped_router_api_prefix}/routes/commit) ).to_return( status: 200, body: "{}", headers: { "Content-Type" => "application/json" } ) end tear_down do WebMock.disable! end provider_state "no content item exists with base_path /vat-rates" do set_up do # no-op end end provider_state "a content item exists with base_path /vat-rates" do set_up do FactoryGirl.create(:content_item, base_path: "/vat-rates") end end provider_state "a content item exists with base_path /vat-rates and payload_version 0" do set_up do FactoryGirl.create(:content_item, base_path: "/vat-rates", payload_version: 0) end end provider_state "a content item exists with base_path /vat-rates and payload_version 10" do set_up do FactoryGirl.create(:content_item, base_path: "/vat-rates", payload_version: 10) end end end
require "spec_helper" require "heroku/command/logs" module Heroku::Command describe Logs do before do @cli = prepare_command(Logs) end it "shows the app logs" do @cli.heroku.should_receive(:read_logs).with('myapp', []) @cli.index end it "shows the app cron logs" do @cli.heroku.should_receive(:cron_logs).with('myapp').and_return('cron logs') @cli.should_receive(:display).with('cron logs') @cli.cron end end end specs for logs require "spec_helper" require "heroku/command/logs" describe Heroku::Command::Logs do describe "logs" do it "runs with no options" do stub_core.read_logs("myapp", []) execute "logs" end it "runs with options" do stub_core.read_logs("myapp", [ "tail=1", "num=2", "ps=ps.3", "source=source.4" ]) execute "logs --tail --num 2 --ps ps.3 --source source.4" end describe "with log output" do before(:each) do stub_core.read_logs("myapp", []).yields("2011-01-01T00:00:00+00:00 app[web.1]: test") end it "prettifies output" do execute "logs" output.should == "\e[36m2011-01-01T00:00:00+00:00 app[web.1]:\e[0m test" end it "does not use ansi if stdout is not a tty" do extend RR::Adapters::RRMethods stub(STDOUT).isatty.returns(false) execute "logs" output.should == "2011-01-01T00:00:00+00:00 app[web.1]: test" stub(STDOUT).isatty.returns(true) end end end describe "deprecated logs:cron" do it "can view cron logs" do stub_core.cron_logs("myapp").returns("the_cron_logs") execute "logs:cron" output.should =~ /the_cron_logs/ end end describe "drains" do it "can list drains" do stub_core.list_drains("myapp").returns("drains") execute "logs:drains" output.should == "drains" end it "can add drains" do stub_core.add_drain("myapp", "syslog://localhost/add").returns("added") execute "logs:drains add syslog://localhost/add" output.should == "added" end it "can remove drains" do stub_core.remove_drain("myapp", "syslog://localhost/remove").returns("removed") execute "logs:drains remove syslog://localhost/remove" output.should == "removed" end it "can clear drains" do stub_core.clear_drains("myapp").returns("cleared") execute "logs:drains clear" output.should == "cleared" end it "errors on unknown subcommand" do lambda { execute "logs:drains foo" }.should fail_command("usage: heroku logs:drains <add | remove | clear>") end end end
ENV["RAILS_ENV"] = "test" require "webmock" require "pact/provider/rspec" require "rails_helper" WebMock.disable! Pact.configure do |config| config.reports_dir = "spec/reports/pacts" config.include WebMock::API config.include WebMock::Matchers end Pact.service_provider "Content Store" do honours_pact_with "Publishing API" do if ENV['USE_LOCAL_PACT'] pact_uri ENV.fetch('PUBLISHING_API_PACT_PATH', '../publishing-api/spec/pacts/publishing_api-content_store.json') else base_url = ENV.fetch("PACT_BROKER_BASE_URL", "https://pact-broker.cloudapps.digital") url = "#{base_url}/pacts/provider/#{URI.escape(name)}/consumer/#{URI.escape(consumer_name)}" version_part = ENV['PUBLISHING_API_PACT_VERSION'] ? "versions/#{ENV['PUBLISHING_API_PACT_VERSION']}" : 'latest' pact_uri "#{url}/#{version_part}" end end end Pact.provider_states_for "Publishing API" do set_up do WebMock.enable! WebMock.reset! DatabaseCleaner.clean_with :truncation end tear_down do WebMock.disable! end provider_state "a content item exists with base_path /vat-rates and transmitted_at 1000000000000000000" do set_up do stub_request(:any, Regexp.new(Plek.find("router-api"))) FactoryGirl.create( :content_item, base_path: "/vat-rates", transmitted_at: "1000000000000000000", ) end end provider_state "a content item exists with base_path /vat-rates and transmitted_at 3000000000000000000" do set_up do stub_request(:any, Regexp.new(Plek.find("router-api"))) FactoryGirl.create( :content_item, base_path: "/vat-rates", transmitted_at: "3000000000000000000", ) end end provider_state "no content item exists with base_path /vat-rates" do set_up do # no-op end end provider_state "a content item exists with base_path /vat-rates" do set_up do FactoryGirl.create(:content_item, base_path: "/vat-rates") end end provider_state "a content item exists with base_path /vat-rates and payload_version 0" do set_up do FactoryGirl.create(:content_item, base_path: "/vat-rates", payload_version: 0) end end provider_state "a content item exists with base_path /vat-rates and payload_version 10" do set_up do FactoryGirl.create(:content_item, base_path: "/vat-rates", payload_version: 10) end end end Escape segments of Pact URL Previously if the value ENV['PUBLISHING_API_PACT_VERSION'] contained a slash the Pact URL would 404, usage of CGI.escape will percent encode non URI characters. The usage of URI.escape has been updated in the url variable also as I think the original author meant the effects of CGI.escape all along. ENV["RAILS_ENV"] = "test" require "webmock" require "pact/provider/rspec" require "rails_helper" WebMock.disable! Pact.configure do |config| config.reports_dir = "spec/reports/pacts" config.include WebMock::API config.include WebMock::Matchers end Pact.service_provider "Content Store" do honours_pact_with "Publishing API" do if ENV['USE_LOCAL_PACT'] pact_uri ENV.fetch('PUBLISHING_API_PACT_PATH', '../publishing-api/spec/pacts/publishing_api-content_store.json') else base_url = ENV.fetch("PACT_BROKER_BASE_URL", "https://pact-broker.cloudapps.digital") url = "#{base_url}/pacts/provider/#{CGI.escape(name)}/consumer/#{CGI.escape(consumer_name)}" version_part = ENV['PUBLISHING_API_PACT_VERSION'] ? "versions/#{CGI.escape(ENV['PUBLISHING_API_PACT_VERSION'])}" : 'latest' pact_uri "#{url}/#{version_part}" end end end Pact.provider_states_for "Publishing API" do set_up do WebMock.enable! WebMock.reset! DatabaseCleaner.clean_with :truncation end tear_down do WebMock.disable! end provider_state "a content item exists with base_path /vat-rates and transmitted_at 1000000000000000000" do set_up do stub_request(:any, Regexp.new(Plek.find("router-api"))) FactoryGirl.create( :content_item, base_path: "/vat-rates", transmitted_at: "1000000000000000000", ) end end provider_state "a content item exists with base_path /vat-rates and transmitted_at 3000000000000000000" do set_up do stub_request(:any, Regexp.new(Plek.find("router-api"))) FactoryGirl.create( :content_item, base_path: "/vat-rates", transmitted_at: "3000000000000000000", ) end end provider_state "no content item exists with base_path /vat-rates" do set_up do # no-op end end provider_state "a content item exists with base_path /vat-rates" do set_up do FactoryGirl.create(:content_item, base_path: "/vat-rates") end end provider_state "a content item exists with base_path /vat-rates and payload_version 0" do set_up do FactoryGirl.create(:content_item, base_path: "/vat-rates", payload_version: 0) end end provider_state "a content item exists with base_path /vat-rates and payload_version 10" do set_up do FactoryGirl.create(:content_item, base_path: "/vat-rates", payload_version: 10) end end end
Add basic HookSpecificCheck coverage Not testing the git-specific (e.g. staged files) stuff yet, but sanity checking commit messages. Change-Id: I07298d2615365796906c37b8f6d469a78840f0ec Reviewed-on: https://gerrit.causes.com/22959 Tested-by: jenkins <d95b56ce41a2e1ac4cecdd398defd7414407cc08@causes.com> Reviewed-by: Joe Lencioni <1dd72cf724deaab5db236f616560fc7067b734e1@causes.com> require 'spec_helper' require 'tempfile' describe Overcommit::GitHook::HookSpecificCheck do class SpeccedCheck < described_class end let(:arguments) { [] } subject { SpeccedCheck.new(*arguments) } describe '#name' do it 'underscorizes' do subject.name.should == 'specced_check' end end describe '#stealth?' do before do @old_stealth = subject.stealth? end after do subject.class.stealth = @old_stealth end it 'is not stealth by default' do subject.stealth?.should be_false end context 'when marked `stealth!`' do it 'returns true' do subject.class.stealth! subject.should be_stealth end end end describe '#commit_message' do context 'when passed no arguments' do it 'fails' do expect { subject.send(:commit_message) }. to raise_error end end context 'when passed a filename from the command line' do let(:tempfile) { Tempfile.new('commit-msg-spec') } let(:arguments) { [tempfile.path] } let(:message) { 'Hello, World!' } before do tempfile.write message tempfile.rewind end after do tempfile.close tempfile.unlink end it 'reads the file' do subject.send(:commit_message).join.should include message end end end end
require "spec_helper_lite" require 'undo/storage/rails_cache' describe Undo::Storage::RailsCache do let(:adapter) { described_class.new cache } let(:cache) { double :cache } it "writes hash to cache as json" do expect(cache).to receive(:write).with("123", '{"hello":"world"}', anything) adapter.put "123", "hello" => "world" end it "reads hash from cache" do expect(cache).to receive(:read).with("123", anything) { '{"hello":"world"}' } expect(adapter.fetch "123").to eq "hello" => "world" end it "does not raise when created without arguments" do expect { described_class.new }.not_to raise_error end describe "options" do let(:adapter) { described_class.new cache, options } let(:options) { Hash.new } it "sends provided options to cache.read" do expect(cache).to receive(:read).with any_args, options adapter.fetch "foo" end it "sends provided options to cache.write" do expect(cache).to receive(:write).with any_args, options adapter.put "foo", "bar" end end end Fix test for ruby-1.9 require "spec_helper_lite" require 'undo/storage/rails_cache' describe Undo::Storage::RailsCache do let(:adapter) { described_class.new cache } let(:cache) { double :cache } it "writes hash to cache as json" do expect(cache).to receive(:write).with("123", '{"hello":"world"}', anything) adapter.put "123", "hello" => "world" end it "reads hash from cache" do expect(cache).to receive(:read).with("123", anything) { '{"hello":"world"}' } expect(adapter.fetch "123").to eq "hello" => "world" end it "does not raise when created without arguments" do expect { described_class.new }.not_to raise_error end describe "options" do let(:adapter) { described_class.new cache, options } let(:options) { Hash.new } it "sends provided options to cache.read" do expect(cache).to receive(:read).with any_args, options adapter.fetch "foo" end it "sends provided options to cache.write" do expect(cache).to receive(:write).with any_args, options adapter.put "foo", "bar" end before do # JSON.load behaves differently in 1.9 allow(cache).to receive(:read).with(any_args) { { :foo => :bar }.to_json } end if RUBY_VERSION < "2.0" end end
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') require "benchmark" describe Officer do before do @server_thread = Thread.new do Officer::Server.new.run end end after do @server_thread.terminate end describe "COMMAND: with_lock" do before do @client = Officer::Client.new end after do @client.send("disconnect") @client = nil end it "should allow a client to request and release a lock using block syntax" do @client.with_lock("testlock") do @client.my_locks.should eq({"value"=>["testlock"], "result"=>"my_locks"}) end end end describe "COMMAND: reset" do before do @client = Officer::Client.new end after do @client.send("disconnect") @client = nil end it "should allow a client to reset all of its locks (release them all)" do @client.lock("testlock1") @client.lock("testlock2") @client.my_locks.should eq({"value"=>["testlock1", "testlock2"], "result"=>"my_locks"}) @client.reset @client.my_locks.should eq({"value"=>[], "result"=>"my_locks"}) end end describe "COMMAND: reconnect" do before do @client = Officer::Client.new end after do @client.send("disconnect") @client = nil end it "should allow a client to force a reconnect in order to get a new socket" do original_socket = @client.instance_variable_get("@socket") @client.reconnect @client.instance_variable_get("@socket").should_not eq(original_socket) @client.my_locks.should eq({"value"=>[], "result"=>"my_locks"}) end end describe "COMMAND: connections" do before do @client1 = Officer::Client.new @client2 = Officer::Client.new @client1_src_port = @client1.instance_variable_get('@socket').addr[1] @client2_src_port = @client2.instance_variable_get('@socket').addr[1] @client1.lock("client1_testlock1") @client1.lock("client1_testlock2") @client2.lock("client2_testlock1") @client2.lock("client2_testlock2") end after do @client1.send("disconnect") @client1 = nil @client2.send("disconnect") @client2 = nil end it "should allow a client to see all the connections to a server" do connections = @client2.connections connections["value"]["127.0.0.1:#{@client1_src_port}"].should eq(["client1_testlock1", "client1_testlock2"]) connections["value"]["127.0.0.1:#{@client2_src_port}"].should eq(["client2_testlock1", "client2_testlock2"]) connections["value"].keys.length.should eq(2) connections["result"].should eq("connections") end end describe "COMMAND: locks" do before do @client1 = Officer::Client.new @client2 = Officer::Client.new @client1_src_port = @client1.instance_variable_get('@socket').addr[1] @client2_src_port = @client2.instance_variable_get('@socket').addr[1] @client1.lock("client1_testlock1") @client1.lock("client1_testlock2") @client2.lock("client2_testlock1") @client2.lock("client2_testlock2") end after do @client1.send("disconnect") @client1 = nil @client2.send("disconnect") @client2 = nil end it "should allow a client to see all the locks on a server (including those owned by other clients)" do locks = @client2.locks locks["value"]["client1_testlock1"].should eq(["127.0.0.1:#{@client1_src_port}"]) locks["value"]["client1_testlock2"].should eq(["127.0.0.1:#{@client1_src_port}"]) locks["value"]["client2_testlock1"].should eq(["127.0.0.1:#{@client2_src_port}"]) locks["value"]["client2_testlock2"].should eq(["127.0.0.1:#{@client2_src_port}"]) locks["value"].length.should eq(4) locks["result"].should eq("locks") end end describe "COMMAND: my_locks" do before do @client = Officer::Client.new end after do @client.send("disconnect") @client = nil end it "should allow a client to request its locks" do @client.lock("testlock") @client.my_locks.should eq({"value"=>["testlock"], "result"=>"my_locks"}) end end describe "COMMAND: lock & unlock" do describe "basic functionality" do before do @client = Officer::Client.new end after do @client.send("disconnect") @client = nil end it "should allow a client to request and release a lock" do @client.lock("testlock").should eq({"result" => "acquired", "name" => "testlock"}) @client.my_locks.should eq({"value"=>["testlock"], "result"=>"my_locks"}) @client.unlock("testlock") @client.my_locks.should eq({"value"=>[], "result"=>"my_locks"}) end end describe "locking options" do describe "OPTION: timeout" do before do @client1 = Officer::Client.new @client2 = Officer::Client.new @client1_src_port = @client1.instance_variable_get('@socket').addr[1] @client2_src_port = @client2.instance_variable_get('@socket').addr[1] @client1.lock("testlock") end after do @client1.send("disconnect") @client1 = nil @client2.send("disconnect") @client2 = nil end it "should allow a client to set an instant timeout when obtaining a lock" do @client2.lock("testlock", :timeout => 0).should eq( {"result"=>"timed_out", "name"=>"testlock", "queue"=>["127.0.0.1:#{@client1_src_port}"]} ) end it "should allow a client to set an instant timeout when obtaining a lock using the block syntax" do lambda { @client2.with_lock("testlock", :timeout => 0){} }.should raise_error(Officer::LockTimeoutError, "queue=127.0.0.1:#{@client1_src_port}") end it "should allow a client to set a positive integer timeout when obtaining a lock" do time = Benchmark.realtime do @client2.lock("testlock", :timeout => 1).should eq( {"result"=>"timed_out", "name"=>"testlock", "queue"=>["127.0.0.1:#{@client1_src_port}"]} ) end time.should > 1 time.should < 1.5 end end describe "OPTION: queue_max" do before do @client1 = Officer::Client.new @client1.lock("testlock") @thread1 = Thread.new { @client2 = Officer::Client.new @client2.lock("testlock") raise "This should never execute since the lock request should block" } @thread2 = Thread.new { @client3 = Officer::Client.new @client3.lock("testlock") raise "This should never execute since the lock request should block" } sleep(0.25) # Allow thread 1 & 2 time to run. @thread1.status.should eq("sleep") @thread2.status.should eq("sleep") @client1_src_port = @client1.instance_variable_get('@socket').addr[1] @client2_src_port = @client2.instance_variable_get('@socket').addr[1] @client3_src_port = @client3.instance_variable_get('@socket').addr[1] @client4 = Officer::Client.new end after do @thread1.terminate @thread2.terminate end it "should allow a client to abort lock acquisition if the wait queue is too long" do @client4.lock("testlock", :queue_max => 3).should eq( {"result" => "queue_maxed", "name" => "testlock", "queue" => ["127.0.0.1:#{@client1_src_port}", "127.0.0.1:#{@client2_src_port}", "127.0.0.1:#{@client3_src_port}"]} ) end it "should allow a client to abort lock acquisition if the wait queue is too long (block syntax)" do lambda { @client4.with_lock("testlock", :queue_max => 3) {} }.should raise_error(Officer::LockQueuedMaxError) end end describe "OPTION: namespace" do before do @client = Officer::Client.new(:namespace => "myapp") end after do @client.send("disconnect") @client = nil end it "should allow a client to set a namespace when obtaining a lock" do @client.with_lock("testlock") do @client.locks["value"]["myapp:testlock"].should_not eq(nil) end end end end end end Cleanup test name require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') require "benchmark" describe Officer do before do @server_thread = Thread.new do Officer::Server.new.run end end after do @server_thread.terminate end describe "COMMAND: with_lock" do before do @client = Officer::Client.new end after do @client.send("disconnect") @client = nil end it "should allow a client to request and release a lock using block syntax" do @client.with_lock("testlock") do @client.my_locks.should eq({"value"=>["testlock"], "result"=>"my_locks"}) end end end describe "COMMAND: reset" do before do @client = Officer::Client.new end after do @client.send("disconnect") @client = nil end it "should allow a client to reset all of its locks (release them all)" do @client.lock("testlock1") @client.lock("testlock2") @client.my_locks.should eq({"value"=>["testlock1", "testlock2"], "result"=>"my_locks"}) @client.reset @client.my_locks.should eq({"value"=>[], "result"=>"my_locks"}) end end describe "COMMAND: reconnect" do before do @client = Officer::Client.new end after do @client.send("disconnect") @client = nil end it "should allow a client to force a reconnect in order to get a new socket" do original_socket = @client.instance_variable_get("@socket") @client.reconnect @client.instance_variable_get("@socket").should_not eq(original_socket) @client.my_locks.should eq({"value"=>[], "result"=>"my_locks"}) end end describe "COMMAND: connections" do before do @client1 = Officer::Client.new @client2 = Officer::Client.new @client1_src_port = @client1.instance_variable_get('@socket').addr[1] @client2_src_port = @client2.instance_variable_get('@socket').addr[1] @client1.lock("client1_testlock1") @client1.lock("client1_testlock2") @client2.lock("client2_testlock1") @client2.lock("client2_testlock2") end after do @client1.send("disconnect") @client1 = nil @client2.send("disconnect") @client2 = nil end it "should allow a client to see all the connections to a server" do connections = @client2.connections connections["value"]["127.0.0.1:#{@client1_src_port}"].should eq(["client1_testlock1", "client1_testlock2"]) connections["value"]["127.0.0.1:#{@client2_src_port}"].should eq(["client2_testlock1", "client2_testlock2"]) connections["value"].keys.length.should eq(2) connections["result"].should eq("connections") end end describe "COMMAND: locks" do before do @client1 = Officer::Client.new @client2 = Officer::Client.new @client1_src_port = @client1.instance_variable_get('@socket').addr[1] @client2_src_port = @client2.instance_variable_get('@socket').addr[1] @client1.lock("client1_testlock1") @client1.lock("client1_testlock2") @client2.lock("client2_testlock1") @client2.lock("client2_testlock2") end after do @client1.send("disconnect") @client1 = nil @client2.send("disconnect") @client2 = nil end it "should allow a client to see all the locks on a server (including those owned by other clients)" do locks = @client2.locks locks["value"]["client1_testlock1"].should eq(["127.0.0.1:#{@client1_src_port}"]) locks["value"]["client1_testlock2"].should eq(["127.0.0.1:#{@client1_src_port}"]) locks["value"]["client2_testlock1"].should eq(["127.0.0.1:#{@client2_src_port}"]) locks["value"]["client2_testlock2"].should eq(["127.0.0.1:#{@client2_src_port}"]) locks["value"].length.should eq(4) locks["result"].should eq("locks") end end describe "COMMAND: my_locks" do before do @client = Officer::Client.new end after do @client.send("disconnect") @client = nil end it "should allow a client to request its locks" do @client.lock("testlock") @client.my_locks.should eq({"value"=>["testlock"], "result"=>"my_locks"}) end end describe "COMMAND: lock & unlock" do describe "basic functionality" do before do @client = Officer::Client.new end after do @client.send("disconnect") @client = nil end it "should allow a client to request and release a lock" do @client.lock("testlock").should eq({"result" => "acquired", "name" => "testlock"}) @client.my_locks.should eq({"value"=>["testlock"], "result"=>"my_locks"}) @client.unlock("testlock") @client.my_locks.should eq({"value"=>[], "result"=>"my_locks"}) end end describe "locking options" do describe "OPTION: timeout" do before do @client1 = Officer::Client.new @client2 = Officer::Client.new @client1_src_port = @client1.instance_variable_get('@socket').addr[1] @client2_src_port = @client2.instance_variable_get('@socket').addr[1] @client1.lock("testlock") end after do @client1.send("disconnect") @client1 = nil @client2.send("disconnect") @client2 = nil end it "should allow a client to set an instant timeout when obtaining a lock" do @client2.lock("testlock", :timeout => 0).should eq( {"result"=>"timed_out", "name"=>"testlock", "queue"=>["127.0.0.1:#{@client1_src_port}"]} ) end it "should allow a client to set an instant timeout when obtaining a lock (block syntax)" do lambda { @client2.with_lock("testlock", :timeout => 0){} }.should raise_error(Officer::LockTimeoutError, "queue=127.0.0.1:#{@client1_src_port}") end it "should allow a client to set a positive integer timeout when obtaining a lock" do time = Benchmark.realtime do @client2.lock("testlock", :timeout => 1).should eq( {"result"=>"timed_out", "name"=>"testlock", "queue"=>["127.0.0.1:#{@client1_src_port}"]} ) end time.should > 1 time.should < 1.5 end end describe "OPTION: queue_max" do before do @client1 = Officer::Client.new @client1.lock("testlock") @thread1 = Thread.new { @client2 = Officer::Client.new @client2.lock("testlock") raise "This should never execute since the lock request should block" } @thread2 = Thread.new { @client3 = Officer::Client.new @client3.lock("testlock") raise "This should never execute since the lock request should block" } sleep(0.25) # Allow thread 1 & 2 time to run. @thread1.status.should eq("sleep") @thread2.status.should eq("sleep") @client1_src_port = @client1.instance_variable_get('@socket').addr[1] @client2_src_port = @client2.instance_variable_get('@socket').addr[1] @client3_src_port = @client3.instance_variable_get('@socket').addr[1] @client4 = Officer::Client.new end after do @thread1.terminate @thread2.terminate end it "should allow a client to abort lock acquisition if the wait queue is too long" do @client4.lock("testlock", :queue_max => 3).should eq( {"result" => "queue_maxed", "name" => "testlock", "queue" => ["127.0.0.1:#{@client1_src_port}", "127.0.0.1:#{@client2_src_port}", "127.0.0.1:#{@client3_src_port}"]} ) end it "should allow a client to abort lock acquisition if the wait queue is too long (block syntax)" do lambda { @client4.with_lock("testlock", :queue_max => 3) {} }.should raise_error(Officer::LockQueuedMaxError) end end describe "OPTION: namespace" do before do @client = Officer::Client.new(:namespace => "myapp") end after do @client.send("disconnect") @client = nil end it "should allow a client to set a namespace when obtaining a lock" do @client.with_lock("testlock") do @client.locks["value"]["myapp:testlock"].should_not eq(nil) end end end end end end
require_relative '../../../../../spec/spec_helper' require_relative '../../../../../spec/helpers/graphql_type_tester' describe Types::UserType do let_once(:user) { student_in_course(active_all: true).user } let(:student_type) { GraphQLTypeTester.new(Types::UserType, user) } before { Account.default.enable_service(:analytics) Account.default.save! } context "summaryAnalytics" do it "works" do expect( student_type.summaryAnalytics( args: {courseId: @course.id.to_s}, current_user: @teacher ) ).to be_a Analytics::StudentSummary end it "is nil when analytics is not enabled" do Account.default.disable_service(:analytics) Account.default.save! expect( student_type.summaryAnalytics( args: {courseId: @course.id.to_s}, current_user: @teacher ) ).to be_nil end it "is nil for teachers without permission" do RoleOverride.manage_role_override( Account.default, teacher_role, 'view_analytics', override: false ) expect( student_type.summaryAnalytics( args: {courseId: @course.id.to_s}, current_user: @teacher ) ).to be_nil end it "is nil for students" do expect( student_type.summaryAnalytics( args: {courseId: @course.id.to_s}, current_user: @student ) ).to be_nil end end end update specs for new graphql version Change-Id: Ic781162a4be83560543e084d66ae39cf0bd0a2e1 Reviewed-on: https://gerrit.instructure.com/152111 Tested-by: Jenkins Reviewed-by: Jonathan Featherstone <c99460343437e667b0585ea68fd7caf7bd0a02ab@instructure.com> Product-Review: Cameron Matheson <1d572acbfa68c7c6e541c7b840d6b622e5c0dc91@instructure.com> QA-Review: Cameron Matheson <1d572acbfa68c7c6e541c7b840d6b622e5c0dc91@instructure.com> require_relative '../../../../../spec/spec_helper' require_relative '../../../../../spec/helpers/graphql_type_tester' describe Types::UserType do let_once(:user) { student_in_course(active_all: true).user } let(:student_type) { GraphQLTypeTester.new(Types::UserType, user) } before { Account.default.enable_service(:analytics) Account.default.save! } context "summaryAnalytics" do it "works" do expect( student_type.summaryAnalytics( args: {course_id: @course.id.to_s}, current_user: @teacher ) ).to be_a Analytics::StudentSummary end it "is nil when analytics is not enabled" do Account.default.disable_service(:analytics) Account.default.save! expect( student_type.summaryAnalytics( args: {course_id: @course.id.to_s}, current_user: @teacher ) ).to be_nil end it "is nil for teachers without permission" do RoleOverride.manage_role_override( Account.default, teacher_role, 'view_analytics', override: false ) expect( student_type.summaryAnalytics( args: {course_id: @course.id.to_s}, current_user: @teacher ) ).to be_nil end it "is nil for students" do expect( student_type.summaryAnalytics( args: {course_id: @course.id.to_s}, current_user: @student ) ).to be_nil end end end
# frozen_string_literal: true describe "Tests Sampling" do context "RSpec integration" do specify "SAMPLE=2" do output = run_rspec("sample", env: {"SAMPLE" => "2"}) expect(output).to include("2 examples, 0 failures") end specify "SAMPLE=1" do output = run_rspec("sample", env: {"SAMPLE" => "1"}) expect(output).to include("1 example, 0 failures") end specify "SAMPLE=1 with tag filter" do output = run_rspec("sample", env: {"SAMPLE" => "1"}, options: "-fd --tag sometag") expect(output).to include("always passes with tag") expect(output).to include("1 example, 0 failures") end specify "SAMPLE=1 with description filter" do output = run_rspec("sample", env: {"SAMPLE" => "1"}, options: "-fd -e flickers") expect(output).to include("flickers") expect(output).to include("1 example, 0 failures") end specify "SAMPLE=2 with seed" do outputs = Array .new(10) { run_rspec("sample", env: {"SAMPLE" => "2"}, options: "--format=documentation --seed 42") } .map { |output| output.gsub(/Finished in.*/, "") } expect(outputs.uniq.size).to eq 1 end specify "SAMPLE_GROUPS=1" do output = run_rspec("sample", env: {"SAMPLE_GROUPS" => "1"}) expect(output).to include("1 example, 0 failures") end specify "SAMPLE_GROUPS=2" do output = run_rspec("sample", env: {"SAMPLE_GROUPS" => "2"}) expect(output).to include("2 examples, 0 failures") end specify "SAMPLE_GROUPS=2 with seed" do outputs = Array .new(10) { run_rspec("sample", env: {"SAMPLE_GROUPS" => "2"}, options: "--format=documentation --seed 42") } .map { |output| output.gsub(/Finished in.*/, "").gsub(/\s/m, "") } expect(outputs.uniq.size).to eq(1), "Outputs must be equal:\n#{outputs.uniq.join("\n")}" end end context "Minitest integration" do specify "SAMPLE=2" do output = run_minitest("sample", env: {"SAMPLE" => "2"}) expect(output).to include("2 runs, 2 assertions, 0 failures, 0 errors, 0 skips") end specify "SAMPLE=1" do output = run_minitest("sample", env: {"SAMPLE" => "1"}) expect(output).to include("1 runs, 1 assertions, 0 failures, 0 errors, 0 skips") end specify "SAMPLE=2 with seed" do outputs = Array .new(10) { run_minitest("sample", env: {"SAMPLE" => "2", "TESTOPTS" => "-v --seed 42"}) } .map { |output| output.gsub(/Finished in.*/, "") } expect(outputs.uniq.size).to eq 1 end specify "SAMPLE_GROUPS=1" do output = run_minitest("sample", env: {"SAMPLE_GROUPS" => "1"}) expect(output).to include("2 runs, 2 assertions, 0 failures, 0 errors, 0 skips") end specify "SAMPLE_GROUPS=2" do output = run_minitest("sample", env: {"SAMPLE_GROUPS" => "2"}) expect(output).to include("4 runs, 4 assertions, 0 failures, 0 errors, 0 skips") end specify "SAMPLE_GROUPS=2 with seed" do outputs = Array .new(10) { run_minitest("sample", env: {"SAMPLE_GROUPS" => "2", "TESTOPTS" => "-v --seed 42"}) } .map { |output| output.gsub(/Finished in.*/, "").gsub(/\s/, "") } expect(outputs.uniq.size).to eq(1), "Outputs must be equal:\n#{outputs.uniq.join("\n")}" end end end Fix sampling spec for JRuby # frozen_string_literal: true describe "Tests Sampling" do context "RSpec integration" do specify "SAMPLE=2" do output = run_rspec("sample", env: {"SAMPLE" => "2"}) expect(output).to include("2 examples, 0 failures") end specify "SAMPLE=1" do output = run_rspec("sample", env: {"SAMPLE" => "1"}) expect(output).to include("1 example, 0 failures") end specify "SAMPLE=1 with tag filter" do output = run_rspec("sample", env: {"SAMPLE" => "1"}, options: "-fd --tag sometag") expect(output).to include("always passes with tag") expect(output).to include("1 example, 0 failures") end specify "SAMPLE=1 with description filter" do output = run_rspec("sample", env: {"SAMPLE" => "1"}, options: "-fd -e flickers") expect(output).to include("flickers") expect(output).to include("1 example, 0 failures") end specify "SAMPLE=2 with seed" do outputs = Array .new(10) { run_rspec("sample", env: {"SAMPLE" => "2"}, options: "--format=documentation --seed 42") } .map(&method(:filter_output)) expect(outputs.uniq.size).to eq(1), "Outputs must be equal:\n#{outputs.uniq.join("\n")}" end specify "SAMPLE_GROUPS=1" do output = run_rspec("sample", env: {"SAMPLE_GROUPS" => "1"}) expect(output).to include("1 example, 0 failures") end specify "SAMPLE_GROUPS=2" do output = run_rspec("sample", env: {"SAMPLE_GROUPS" => "2"}) expect(output).to include("2 examples, 0 failures") end specify "SAMPLE_GROUPS=2 with seed" do outputs = Array .new(10) { run_rspec("sample", env: {"SAMPLE_GROUPS" => "2"}, options: "--format=documentation --seed 42") } .map(&method(:filter_output)) expect(outputs.uniq.size).to eq(1), "Outputs must be equal:\n#{outputs.uniq.join("\n")}" end end context "Minitest integration" do specify "SAMPLE=2" do output = run_minitest("sample", env: {"SAMPLE" => "2"}) expect(output).to include("2 runs, 2 assertions, 0 failures, 0 errors, 0 skips") end specify "SAMPLE=1" do output = run_minitest("sample", env: {"SAMPLE" => "1"}) expect(output).to include("1 runs, 1 assertions, 0 failures, 0 errors, 0 skips") end specify "SAMPLE=2 with seed" do outputs = Array .new(10) { run_minitest("sample", env: {"SAMPLE" => "2", "TESTOPTS" => "-v --seed 42"}) } .map(&method(:filter_output)) expect(outputs.uniq.size).to eq(1), "Outputs must be equal:\n#{outputs.uniq.join("\n")}" end specify "SAMPLE_GROUPS=1" do output = run_minitest("sample", env: {"SAMPLE_GROUPS" => "1"}) expect(output).to include("2 runs, 2 assertions, 0 failures, 0 errors, 0 skips") end specify "SAMPLE_GROUPS=2" do output = run_minitest("sample", env: {"SAMPLE_GROUPS" => "2"}) expect(output).to include("4 runs, 4 assertions, 0 failures, 0 errors, 0 skips") end specify "SAMPLE_GROUPS=2 with seed" do outputs = Array .new(10) { run_minitest("sample", env: {"SAMPLE_GROUPS" => "2", "TESTOPTS" => "-v --seed 42"}) } .map(&method(:filter_output)) expect(outputs.uniq.size).to eq(1), "Outputs must be equal:\n#{outputs.uniq.join("\n")}" end end def filter_output(output) output.gsub(/Finished in.*/, "").tap do |str| str.gsub!(/\s/, "") str.gsub!(%r{#test_pass=\d+.\d+s=}, "") # for JRuby end end end
# frozen_string_literal: true RSpec.describe JWT do describe '.decode for JWK usecase' do let(:keypair) { OpenSSL::PKey::RSA.new(2048) } let(:jwk) { JWT::JWK.new(keypair) } let(:public_jwks) { { keys: [jwk.export, { kid: 'not_the_correct_one' }] } } let(:token_payload) { {'data' => 'something'} } let(:token_headers) { { kid: jwk.kid } } let(:signed_token) { described_class.encode(token_payload, jwk.keypair, 'RS512', token_headers) } context 'when JWK features are used manually' do it 'is able to decode the token' do payload, _header = described_class.decode(signed_token, nil, true, { algorithms: ['RS512'] }) do |header, _payload| JWT::JWK.import(public_jwks[:keys].find { |key| key[:kid] == header['kid'] }).keypair end expect(payload).to eq(token_payload) end end context 'when jwk keys are given as an array' do context 'and kid is in the set' do it 'is able to decode the token' do payload, _header = described_class.decode(signed_token, nil, true, { algorithms: ['RS512'], jwks: public_jwks}) expect(payload).to eq(token_payload) end end context 'and kid is not in the set' do before do public_jwks[:keys].first[:kid] = 'NOT_A_MATCH' end it 'raises an exception' do expect { described_class.decode(signed_token, nil, true, { algorithms: ['RS512'], jwks: public_jwks}) }.to raise_error( JWT::DecodeError, /Could not find public key for kid .*/ ) end end context 'no keys are found in the set' do let(:public_jwks) { {keys: []} } it 'raises an exception' do expect { described_class.decode(signed_token, nil, true, { algorithms: ['RS512'], jwks: public_jwks}) }.to raise_error( JWT::DecodeError, /No keys found in jwks/ ) end end context 'token does not know the kid' do let(:token_headers) { {} } it 'raises an exception' do expect { described_class.decode(signed_token, nil, true, { algorithms: ['RS512'], jwks: public_jwks}) }.to raise_error( JWT::DecodeError, 'No key id (kid) found from token headers' ) end end end context 'when jwk keys are loaded using a proc/lambda' do it 'decodes the token' do payload, _header = described_class.decode(signed_token, nil, true, { algorithms: ['RS512'], jwks: lambda { |_opts| public_jwks }}) expect(payload).to eq(token_payload) end end context 'when jwk keys are rotated' do it 'decodes the token' do key_loader = ->(options) { options[:invalidate] ? public_jwks : { keys: [] } } payload, _header = described_class.decode(signed_token, nil, true, { algorithms: ['RS512'], jwks: key_loader}) expect(payload).to eq(token_payload) end end context 'when jwk keys are loaded from JSON with string keys' do it 'decodes the token' do key_loader = ->(options) { JSON.parse(JSON.generate(public_jwks)) } payload, _header = described_class.decode(signed_token, nil, true, { algorithms: ['RS512'], jwks: key_loader}) expect(payload).to eq(token_payload) end end end end Tests for mixing JWK keys with mismatching algorithms # frozen_string_literal: true RSpec.describe JWT do describe '.decode for JWK usecase' do let(:keypair) { OpenSSL::PKey::RSA.new(2048) } let(:jwk) { JWT::JWK.new(keypair) } let(:public_jwks) { { keys: [jwk.export, { kid: 'not_the_correct_one' }] } } let(:token_payload) { {'data' => 'something'} } let(:token_headers) { { kid: jwk.kid } } let(:signed_token) { described_class.encode(token_payload, jwk.keypair, 'RS512', token_headers) } context 'when JWK features are used manually' do it 'is able to decode the token' do payload, _header = described_class.decode(signed_token, nil, true, { algorithms: ['RS512'] }) do |header, _payload| JWT::JWK.import(public_jwks[:keys].find { |key| key[:kid] == header['kid'] }).keypair end expect(payload).to eq(token_payload) end end context 'when jwk keys are given as an array' do context 'and kid is in the set' do it 'is able to decode the token' do payload, _header = described_class.decode(signed_token, nil, true, { algorithms: ['RS512'], jwks: public_jwks}) expect(payload).to eq(token_payload) end end context 'and kid is not in the set' do before do public_jwks[:keys].first[:kid] = 'NOT_A_MATCH' end it 'raises an exception' do expect { described_class.decode(signed_token, nil, true, { algorithms: ['RS512'], jwks: public_jwks}) }.to raise_error( JWT::DecodeError, /Could not find public key for kid .*/ ) end end context 'no keys are found in the set' do let(:public_jwks) { {keys: []} } it 'raises an exception' do expect { described_class.decode(signed_token, nil, true, { algorithms: ['RS512'], jwks: public_jwks}) }.to raise_error( JWT::DecodeError, /No keys found in jwks/ ) end end context 'token does not know the kid' do let(:token_headers) { {} } it 'raises an exception' do expect { described_class.decode(signed_token, nil, true, { algorithms: ['RS512'], jwks: public_jwks}) }.to raise_error( JWT::DecodeError, 'No key id (kid) found from token headers' ) end end end context 'when jwk keys are loaded using a proc/lambda' do it 'decodes the token' do payload, _header = described_class.decode(signed_token, nil, true, { algorithms: ['RS512'], jwks: lambda { |_opts| public_jwks }}) expect(payload).to eq(token_payload) end end context 'when jwk keys are rotated' do it 'decodes the token' do key_loader = ->(options) { options[:invalidate] ? public_jwks : { keys: [] } } payload, _header = described_class.decode(signed_token, nil, true, { algorithms: ['RS512'], jwks: key_loader}) expect(payload).to eq(token_payload) end end context 'when jwk keys are loaded from JSON with string keys' do it 'decodes the token' do key_loader = ->(options) { JSON.parse(JSON.generate(public_jwks)) } payload, _header = described_class.decode(signed_token, nil, true, { algorithms: ['RS512'], jwks: key_loader}) expect(payload).to eq(token_payload) end end context 'mixing algorithms using kid header' do let(:hmac_jwk) { JWT::JWK.new('secret') } let(:rsa_jwk) { JWT::JWK.new(OpenSSL::PKey::RSA.new(2048)) } let(:ec_jwk_secp384r1) { JWT::JWK.new(OpenSSL::PKey::EC.new('secp384r1').generate_key) } let(:ec_jwk_secp521r1) { JWT::JWK.new(OpenSSL::PKey::EC.new('secp521r1').generate_key) } let(:jwks) { { keys: [hmac_jwk.export(include_private: true), rsa_jwk.export, ec_jwk_secp384r1.export, ec_jwk_secp521r1.export] } } context 'when RSA key is pointed to as HMAC secret' do let(:signed_token) { described_class.encode({'foo' => 'bar'}, 'is not really relevant in the scenario', 'HS256', { kid: rsa_jwk.kid }) } it 'fails in some way' do expect { described_class.decode(signed_token, nil, true, algorithms: ['HS256'], jwks: jwks) }.to( raise_error do |e| if defined?(RbNaCl) expect(e).to be_a(NoMethodError) expect(e.message).to match(/undefined method `bytesize'/) else expect(e).to be_a(TypeError) expect(e.message).to eq('no implicit conversion of OpenSSL::PKey::RSA into String') end end ) end end context 'when EC key is pointed to as HMAC secret' do let(:signed_token) { described_class.encode({'foo' => 'bar'}, 'is not really relevant in the scenario', 'HS256', { kid: ec_jwk_secp384r1.kid }) } it 'fails in some way' do expect { described_class.decode(signed_token, nil, true, algorithms: ['HS256'], jwks: jwks) }.to( raise_error do |e| if defined?(RbNaCl) expect(e).to be_a(NoMethodError) expect(e.message).to match(/undefined method `bytesize'/) else expect(e).to be_a(TypeError) expect(e.message).to eq('no implicit conversion of OpenSSL::PKey::EC into String') end end ) end end context 'when EC key is pointed to as RSA public key' do let(:signed_token) { described_class.encode({'foo' => 'bar'}, rsa_jwk.keypair, 'RS512', { kid: ec_jwk_secp384r1.kid }) } it 'fails in some way' do expect { described_class.decode(signed_token, nil, true, algorithms: ['RS512'], jwks: jwks) }.to( raise_error(JWT::VerificationError, 'Signature verification raised') ) end end context 'when HMAC secret is pointed to as RSA public key' do let(:signed_token) { described_class.encode({'foo' => 'bar'}, rsa_jwk.keypair, 'RS512', { kid: hmac_jwk.kid }) } it 'fails in some way' do expect { described_class.decode(signed_token, nil, true, algorithms: ['RS512'], jwks: jwks) }.to( raise_error(NoMethodError, /undefined method `verify' for \"secret\":String/) ) end end context 'when HMAC secret is pointed to as EC public key' do let(:signed_token) { described_class.encode({'foo' => 'bar'}, ec_jwk_secp384r1.keypair, 'ES384', { kid: hmac_jwk.kid }) } it 'fails in some way' do expect { described_class.decode(signed_token, nil, true, algorithms: ['ES384'], jwks: jwks) }.to( raise_error(NoMethodError, /undefined method `group' for \"secret\":String/) ) end end context 'when ES384 key is pointed to as ES512 key' do let(:signed_token) { described_class.encode({'foo' => 'bar'}, ec_jwk_secp384r1.keypair, 'ES512', { kid: ec_jwk_secp521r1.kid }) } it 'fails in some way' do expect { described_class.decode(signed_token, nil, true, algorithms: ['ES512'], jwks: jwks) }.to( raise_error(JWT::IncorrectAlgorithm, 'payload algorithm is ES512 but ES384 signing key was provided') ) end end end end end
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe AllControllers do describe 'names class method' do # NOTE: The names should be generated dynamically # For now, I'm just testing that the correct list of names are returned, # combined with the knowledge that the code is written to behave dynamically. # If you want to change this test to prove that the code is dynamic, be my guest... it 'should list all controller names' do # For now I'm testing this is strictly equal. # Once we trust it, we could use subset? instead to keep it from breaking ALL the time... AllControllers.names.should == %w{ checklist_builder/answers checklist_builder/checklists checklist_builder/elements checklist_builder/questions checklists countries custom_flags custom_probes district/schools district/users districts enrollments frequencies groups ignore_flags intervention_builder/categories intervention_builder/goals intervention_builder/interventions intervention_builder/objectives intervention_builder/probes intervention_builder/recommended_monitors interventions/categories interventions/comments interventions/definitions interventions/goals interventions/objectives interventions/participants interventions/probe_assignments interventions/probes interventions login main news_items principal_overrides probe_questions recommendations reports roles schools states student_comments students tiers users } end end end forgot to remove users controller reference require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe AllControllers do describe 'names class method' do # NOTE: The names should be generated dynamically # For now, I'm just testing that the correct list of names are returned, # combined with the knowledge that the code is written to behave dynamically. # If you want to change this test to prove that the code is dynamic, be my guest... it 'should list all controller names' do # For now I'm testing this is strictly equal. # Once we trust it, we could use subset? instead to keep it from breaking ALL the time... static_list = %w{ checklist_builder/answers checklist_builder/checklists checklist_builder/elements checklist_builder/questions checklists countries custom_flags custom_probes district/schools district/users districts enrollments frequencies groups ignore_flags intervention_builder/categories intervention_builder/goals intervention_builder/interventions intervention_builder/objectives intervention_builder/probes intervention_builder/recommended_monitors interventions/categories interventions/comments interventions/definitions interventions/goals interventions/objectives interventions/participants interventions/probe_assignments interventions/probes interventions login main news_items principal_overrides probe_questions recommendations reports roles schools states student_comments students tiers } AllControllers.names.should == static_list end end end
require 'spec_helper' describe Danica::Function do class Danica::Function class Spatial < Danica::Function variables :time, :acceleration, :initial_space, :initial_velocity delegate :to_tex, :to_gnu, to: :sum private def sum @sum ||= Sum.new(variables: parcels) end def parcels [ initial_space, spatial_velocity, spatial_acceleration ] end def spatial_velocity Product.new(variables: [ initial_velocity, time ]) end def spatial_acceleration Division.new(numerator: Product.new(variables: [ acceleration, time_squared ]), denominator: 2) end def time_squared Power.new(base: time, exponent: 2) end end end let(:variables) do { time: :t, acceleration: 'a', initial_space: { name: :S0, latex: 'S_0' }, initial_velocity: { name: :V0, latex: 'V_0' } } end let(:subject) { described_class::Spatial.new(variables) } describe '#to_tex' do context 'when creating the spatial function for constantly accelerated movement' do let(:expected) { 'S_0 + V_0 \cdot t + \frac{a \cdot t^{2}}{2}' } it 'return the latex format CAM' do expect(subject.to_tex).to eq(expected) end end end describe '#to_gnu' do context 'when creating the spatial function for constantly accelerated movement' do let(:expected) { 'S0 + V0 * t + a * t**2/2' } it 'return the latex format CAM' do expect(subject.to_gnu).to eq(expected) end end end describe '#variables_hash' do let(:expected) do { time: Danica::Variable.new(name: :t), acceleration: Danica::Variable.new(name: 'a'), initial_space: Danica::Variable.new( name: :S0, latex: 'S_0' ), initial_velocity: Danica::Variable.new( name: :V0, latex: 'V_0' ) } end context 'when variables are already wrapped with DanicaVariable' do let(:variables) { expected } it 'returns a hash with the variabels' do expect(subject.variables_hash).to eq(expected) end end context 'when variables are not wrapped yet' do it 'returns a hash with the variabels' do expect(subject.variables_hash).to eq(expected) end end end describe '#variables' do let(:subject) { described_class::Spatial.new } let(:time) { Danica::Variable.new(name: :t) } context 'when initialized with an empty variable set' do it do expect(subject.variables.compact).to be_empty end end context 'when changing a variable' do before do subject.time = time end it 'returns the list of variables' do expect(subject.variables.compact).to eq([ time ]) end end end end Add spec when initializing with string keyed map require 'spec_helper' describe Danica::Function do class Danica::Function class Spatial < Danica::Function variables :time, :acceleration, :initial_space, :initial_velocity delegate :to_tex, :to_gnu, to: :sum private def sum @sum ||= Sum.new(variables: parcels) end def parcels [ initial_space, spatial_velocity, spatial_acceleration ] end def spatial_velocity Product.new(variables: [ initial_velocity, time ]) end def spatial_acceleration Division.new(numerator: Product.new(variables: [ acceleration, time_squared ]), denominator: 2) end def time_squared Power.new(base: time, exponent: 2) end end end let(:variables) do { time: :t, acceleration: 'a', initial_space: { name: :S0, latex: 'S_0' }, initial_velocity: { name: :V0, latex: 'V_0' } } end let(:subject) { described_class::Spatial.new(variables) } describe '#to_tex' do context 'when creating the spatial function for constantly accelerated movement' do let(:expected) { 'S_0 + V_0 \cdot t + \frac{a \cdot t^{2}}{2}' } it 'return the latex format CAM' do expect(subject.to_tex).to eq(expected) end end end describe '#to_gnu' do context 'when creating the spatial function for constantly accelerated movement' do let(:expected) { 'S0 + V0 * t + a * t**2/2' } it 'return the latex format CAM' do expect(subject.to_gnu).to eq(expected) end end end describe '#variables_hash' do let(:expected) do { time: Danica::Variable.new(name: :t), acceleration: Danica::Variable.new(name: 'a'), initial_space: Danica::Variable.new( name: :S0, latex: 'S_0' ), initial_velocity: Danica::Variable.new( name: :V0, latex: 'V_0' ) } end context 'when variables are already wrapped with DanicaVariable' do let(:variables) { expected } it 'returns a hash with the variabels' do expect(subject.variables_hash).to eq(expected) end end context 'when variables have been defined with string name' do before do variables.change_keys!(&:to_s) end it 'returns a hash with the variabels' do expect(subject.variables_hash).to eq(expected) end end context 'when variables are not wrapped yet' do it 'returns a hash with the variabels' do expect(subject.variables_hash).to eq(expected) end end end describe '#variables' do let(:subject) { described_class::Spatial.new } let(:time) { Danica::Variable.new(name: :t) } context 'when initialized with an empty variable set' do it do expect(subject.variables.compact).to be_empty end end context 'when changing a variable' do before do subject.time = time end it 'returns the list of variables' do expect(subject.variables.compact).to eq([ time ]) end end end end
require 'spec_helper' describe Daylight::Errors do class BaseErrorTest < StandardError def initialize resposne, message=nill @message = 'base' end def to_s @message.dup end end class ErrorTest < BaseErrorTest include Daylight::Errors end def mock_response headers, body double(header: headers, body: body) end it 'ignores parsing with no body and content-type' do error = ErrorTest.new(mock_response({}, nil)) error.messages.should == [] error.to_s.should == 'base' end it 'sets no message for unknown content-type' do error = ErrorTest.new(mock_response({'content-type' => 'application/foo'}, 'bar error, no drink')) error.messages.should == [] error.to_s.should == 'base' end describe :xml do let(:xml_error) { '<errors><error>message</error></errors>' } let(:xml_errors) { '<errors><error>problem 1</error><error>problem 2</error></errors>' } def xml_response body=nil mock_response({'content-type' => 'application/xml; charset=utf-8'}, body) end it 'parses no error' do error = ErrorTest.new(xml_response) error.messages.should == [] error.to_s.should == 'base' end it 'parses one error' do error = ErrorTest.new(xml_response(xml_error)) error.messages.should == ['message'] error.to_s.should == 'base Root Cause = message' end it 'parses multiple errors' do error = ErrorTest.new(xml_response(xml_errors)) error.messages.should == ['problem 1', 'problem 2'] error.to_s.should == 'base Root Cause = problem 1, problem 2' end it 'handles decode errors and sets no messages' do error = ErrorTest.new(xml_response('bad data')) error.messages.should == [] error.to_s.should == 'base' end end describe :json do let(:json_error) { { errors: 'message'}.to_json } let(:json_errors) { { errors: ['problem 1', 'problem 2'] }.to_json } def json_response body=nil mock_response({'content-type' => 'application/json; charset=utf-8'}, body) end it 'parses no error' do error = ErrorTest.new(json_response) error.messages.should == [] error.to_s.should == 'base' end it 'parses one error' do error = ErrorTest.new(json_response(json_error)) error.messages.should == ['message'] error.to_s.should == 'base Root Cause = message' end it 'parses multiple errors' do error = ErrorTest.new(json_response(json_errors)) error.messages.should == ['problem 1', 'problem 2'] error.to_s.should == 'base Root Cause = problem 1, problem 2' end it 'handles decode errors and sets no messages' do error = ErrorTest.new(json_response('<bad data>')) error.messages.should == [] error.to_s.should == 'base' end end end tests for displaying Request-Ids in client errors require 'spec_helper' describe Daylight::Errors do class BaseErrorTest < StandardError def initialize resposne, message=nill @message = 'base' end def to_s @message.dup end end class ErrorTest < BaseErrorTest include Daylight::Errors end def mock_response headers, body double(header: headers, body: body) end it 'ignores parsing with no body and content-type' do error = ErrorTest.new(mock_response({}, nil)) error.messages.should == [] error.to_s.should == 'base' end it 'sets no message for unknown content-type' do error = ErrorTest.new(mock_response({'content-type' => 'application/foo'}, 'bar error, no drink')) error.messages.should == [] error.to_s.should == 'base' end describe :xml do let(:xml_error) { '<errors><error>message</error></errors>' } let(:xml_errors) { '<errors><error>problem 1</error><error>problem 2</error></errors>' } def xml_response body=nil, headers={} mock_response({'content-type' => 'application/xml; charset=utf-8'}.merge!(headers), body) end it 'parses no error' do error = ErrorTest.new(xml_response) error.messages.should == [] error.to_s.should == 'base' end it 'parses one error' do error = ErrorTest.new(xml_response(xml_error)) error.messages.should == ['message'] error.to_s.should == 'base Root Cause = message.' end it 'parses multiple errors' do error = ErrorTest.new(xml_response(xml_errors)) error.messages.should == ['problem 1', 'problem 2'] error.to_s.should == 'base Root Cause = problem 1, problem 2.' end it 'parses no error with x-request-id header' do error = ErrorTest.new(xml_response(nil, 'x-request-id' => 'uuid')) error.messages.should == [] error.to_s.should == 'base Request-Id = uuid.' end it 'parses one error with x-request-id header' do error = ErrorTest.new(xml_response(xml_error, 'x-request-id' => 'uuid')) error.messages.should == ['message'] error.to_s.should == 'base Root Cause = message. Request-Id = uuid.' end it 'parses multiple errors with x-request-id header' do error = ErrorTest.new(xml_response(xml_errors, 'x-request-id' => 'uuid')) error.messages.should == ['problem 1', 'problem 2'] error.to_s.should == 'base Root Cause = problem 1, problem 2. Request-Id = uuid.' end it 'handles decode errors and sets no messages' do error = ErrorTest.new(xml_response('bad data')) error.messages.should == [] error.to_s.should == 'base' end end describe :json do let(:json_error) { { errors: 'message'}.to_json } let(:json_errors) { { errors: ['problem 1', 'problem 2'] }.to_json } def json_response body=nil, headers={} mock_response({'content-type' => 'application/json; charset=utf-8'}.merge!(headers), body) end it 'parses no error' do error = ErrorTest.new(json_response) error.messages.should == [] error.to_s.should == 'base' end it 'parses one error' do error = ErrorTest.new(json_response(json_error)) error.messages.should == ['message'] error.to_s.should == 'base Root Cause = message.' end it 'parses multiple errors' do error = ErrorTest.new(json_response(json_errors)) error.messages.should == ['problem 1', 'problem 2'] error.to_s.should == 'base Root Cause = problem 1, problem 2.' end it 'parses one error with x-request-id header' do error = ErrorTest.new(json_response(json_error, 'x-request-id' => 'uuid')) error.messages.should == ['message'] error.to_s.should == 'base Root Cause = message. Request-Id = uuid.' end it 'parses multiple errors with x-request-id header' do error = ErrorTest.new(json_response(json_errors, 'x-request-id' => 'uuid')) error.messages.should == ['problem 1', 'problem 2'] error.to_s.should == 'base Root Cause = problem 1, problem 2. Request-Id = uuid.' end it 'handles decode errors and sets no messages' do error = ErrorTest.new(json_response('<bad data>')) error.messages.should == [] error.to_s.should == 'base' end end end
describe Rambo::RSpec::SpecFile do let(:raw_raml) { Raml::Parser.parse(File.read(raml_file)) } let(:raml) { Rambo::RamlModels::Api.new(raw_raml) } let(:spec_file) { Rambo::RSpec::SpecFile.new(raw_raml) } context "file with examples" do let(:raml_file) { File.expand_path("../../../support/foobar.raml", __FILE__) } describe "#initialize" do it "assigns @raml" do expect(spec_file.raml).to be_a Rambo::RamlModels::Api end it "uses the correct schema" do puts spec_file.raml.schema expect(spec_file.raml.schema).to eq raw_raml end end describe "#template" do it "is a string" do expect(spec_file.template.is_a?(String)).to be true end end describe "#render" do it "interpolates the correct values" do expect(spec_file.render).to include("e-BookMobile API") end end end context "file with schema" do let(:raml_file) do File.expand_path("features/support/examples/raml/basic_raml_with_schema.raml") end describe "#initialize" do it "assigns @raml" do expect(spec_file.raml).to be_a(Rambo::RamlModels::Api) end end describe "#template" do it "is a string" do expect(spec_file.template.is_a?(String)).to be true end end describe "#render" do let(:test_data) { '"data" => 1' } it "interpolates the correct values" do expect(spec_file.render).to include(test_data) end end end end Stub JsonTestData so we know data value describe Rambo::RSpec::SpecFile do let(:raw_raml) { Raml::Parser.parse(File.read(raml_file)) } let(:raml) { Rambo::RamlModels::Api.new(raw_raml) } let(:spec_file) { Rambo::RSpec::SpecFile.new(raw_raml) } context "file with examples" do let(:raml_file) { File.expand_path("../../../support/foobar.raml", __FILE__) } describe "#initialize" do it "assigns @raml" do expect(spec_file.raml).to be_a Rambo::RamlModels::Api end it "uses the correct schema" do puts spec_file.raml.schema expect(spec_file.raml.schema).to eq raw_raml end end describe "#template" do it "is a string" do expect(spec_file.template.is_a?(String)).to be true end end describe "#render" do it "interpolates the correct values" do expect(spec_file.render).to include("e-BookMobile API") end end end context "file with schema" do let(:raml_file) do File.expand_path("features/support/examples/raml/basic_raml_with_schema.raml") end describe "#initialize" do it "assigns @raml" do expect(spec_file.raml).to be_a(Rambo::RamlModels::Api) end end describe "#template" do it "is a string" do expect(spec_file.template.is_a?(String)).to be true end end describe "#render" do let(:test_data) { '"data" => 1' } it "interpolates the correct values" do allow(JsonTestData).to receive(:generate).and_return({ :data => 1 }) expect(spec_file.render).to include(test_data) end end end end
require 'rspec' require 'spec_helper' require 'databasedotcom' describe Databasedotcom::Sobject::Sobject do class TestClass < Databasedotcom::Sobject::Sobject end before do @client = Databasedotcom::Client.new(File.join(File.dirname(__FILE__), "../../fixtures/databasedotcom.yml")) @client.authenticate(:token => "foo", :instance_url => "https://na9.salesforce.com") TestClass.client = @client end describe "materialization" do context "with a valid Sobject name" do response = JSON.parse(File.read(File.join(File.dirname(__FILE__), "../../fixtures/sobject/sobject_describe_success_response.json"))) it "requests a description of the class" do @client.should_receive(:describe_sobject).with("TestClass").and_return(response) TestClass.materialize("TestClass") end context "with a response" do before do @client.stub(:describe_sobject).and_return(response) TestClass.materialize("TestClass") @sobject = TestClass.new end describe ".attributes" do it "returns the attributes for this Sobject" do TestClass.attributes.should_not be_nil TestClass.attributes.should =~ response["fields"].collect { |f| [f["name"], f["relationshipName"]] }.flatten.compact end end describe "getters and setters" do response["fields"].collect { |f| f["name"] }.each do |name| it "creates a getter and setter for the #{name} attribute" do @sobject.should respond_to(name.to_sym) @sobject.should respond_to("#{name}=".to_sym) end end end describe "default values" do response["fields"].each do |f| it "sets #{f['name']} to #{f['defaultValueFormula'] ? f['defaultValueFormula'] : 'nil'}" do @sobject.send(f["name"].to_sym).should == f["defaultValueFormula"] end end end end end context "with an invalid Sobject name" do it "propagates exceptions" do @client.should_receive(:describe_sobject).with("TestClass").and_raise(Databasedotcom::SalesForceError.new(double("result", :body => "{}"))) lambda { TestClass.materialize("TestClass") }.should raise_error(Databasedotcom::SalesForceError) end end end context "with a materialized class" do before do response = JSON.parse(File.read(File.join(File.dirname(__FILE__), "../../fixtures/sobject/sobject_describe_success_response.json"))) @client.should_receive(:describe_sobject).with("TestClass").and_return(response) TestClass.materialize("TestClass") @field_names = TestClass.description["fields"].collect { |f| f["name"] } end describe "#==" do before do @first = TestClass.new("Id" => "foo") end context "when the objects are the same class" do context "when the ids match" do before do @second = TestClass.new("Id" => "foo") end it "returns true" do @first.should == @second end end context "when the ids do not match" do before do @second = TestClass.new("Id" => "bar") end it "returns false" do @first.should_not == @second end end end context "when the objects are different classes" do before do @second = stub(:is_a? => false) end it "returns false" do @first.should_not == @second end end end describe ".new" do it "creates a new in-memory instance with the specified attributes" do obj = TestClass.new("Name" => "foo") obj.Name.should == "foo" obj.should be_new_record end end describe ".create" do it "returns a new instance with the specified attributes" do @client.should_receive(:create).with(TestClass, "moo").and_return("gar") TestClass.create("moo").should == "gar" end end describe ".find" do context "with a valid id" do it "returns the found instance" do @client.should_receive(:find).with(TestClass, "abc").and_return("bar") TestClass.find("abc").should == "bar" end end context "with an invalid id" do it "propagates exceptions" do @client.should_receive(:find).with(TestClass, "abc").and_raise(Databasedotcom::SalesForceError.new(double("result", :body => "{}"))) lambda { TestClass.find("abc") }.should raise_error(Databasedotcom::SalesForceError) end end end describe ".all" do it "returns a paginated enumerable containing all instances" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass").and_return("foo") TestClass.all.should == "foo" end end describe ".query" do it "constructs and submits a SOQL query" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'foo'").and_return("bar") TestClass.query("Name = 'foo'").should == "bar" end end describe ".delete" do it "deletes a record specified by id" do @client.should_receive(:delete).with("TestClass", "recordId").and_return("deleteResponse") TestClass.delete("recordId").should == "deleteResponse" end end describe ".first" do it "loads the first record" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass ORDER BY Id ASC LIMIT 1").and_return(["foo"]) TestClass.first.should == "foo" end it "optionally includes SOQL conditions" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE conditions ORDER BY Id ASC LIMIT 1").and_return(["foo"]) TestClass.first("conditions").should == "foo" end end describe ".last" do it "loads the last record" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass ORDER BY Id DESC LIMIT 1").and_return(["bar"]) TestClass.last.should == "bar" end it "optionally includes SOQL conditions" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE conditions ORDER BY Id DESC LIMIT 1").and_return(["bar"]) TestClass.last("conditions").should == "bar" end end describe ".count" do it "gets the record count" do @client.should_receive(:query).with("SELECT COUNT() FROM TestClass").and_return(double("collection", :total_size => 42)) TestClass.count.should == 42 end end describe ".coerce_params" do it "coerces boolean attributes" do TestClass.coerce_params("Checkbox_Field" => "1")["Checkbox_Field"].should be_true TestClass.coerce_params("Checkbox_Field" => "0")["Checkbox_Field"].should be_false TestClass.coerce_params("Checkbox_Field" => true)["Checkbox_Field"].should be_true TestClass.coerce_params("Checkbox_Field" => false)["Checkbox_Field"].should be_false end it "coerces currency attributes" do TestClass.coerce_params("Currency_Field" => "123.4")["Currency_Field"].should == 123.4 TestClass.coerce_params("Currency_Field" => 123.4)["Currency_Field"].should == 123.4 end it "coerces percent attributes" do TestClass.coerce_params("Percent_Field" => "123.4")["Percent_Field"].should == 123.4 TestClass.coerce_params("Percent_Field" => 123.4)["Percent_Field"].should == 123.4 end it "coerces date fields" do today = Date.today Date.stub(:today).and_return(today) TestClass.coerce_params("Date_Field" => "2010-04-01")["Date_Field"].should == Date.civil(2010, 4, 1) TestClass.coerce_params("Date_Field" => "bogus")["Date_Field"].should == Date.today end it "coerces datetime fields" do now = DateTime.now DateTime.stub(:now).and_return(now) TestClass.coerce_params("DateTime_Field" => "2010-04-01T12:05:10Z")["DateTime_Field"].to_s.should == DateTime.civil(2010, 4, 1, 12, 5, 10).to_s TestClass.coerce_params("DateTime_Field" => "bogus")["DateTime_Field"].to_s.should == now.to_s end end describe "dynamic finders" do describe "find_by_xxx" do context "with a single attribute" do it "constructs and executes a query matching the dynamic attributes" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'Richard' LIMIT 1").and_return(["bar"]) TestClass.find_by_Name('Richard').should == "bar" end it "handles boolean values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE IsDeleted = false LIMIT 1").and_return(["bar"]) TestClass.find_by_IsDeleted(false).should == "bar" end it "handles numeric values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Number_Field = 23.4 LIMIT 1").and_return(["bar"]) TestClass.find_by_Number_Field(23.4).should == "bar" end it "handles date values" do today = Date.today @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Date_FIeld = #{today.to_s} LIMIT 1").and_return(["bar"]) TestClass.find_by_Date_FIeld(today).should == "bar" end it "handles datetime values" do now = Time.now @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE DateTime_Field = #{now.strftime("%Y-%m-%dT%H:%M:%S.%L%z").insert(-3, ":")} LIMIT 1").and_return(["bar"]) TestClass.find_by_DateTime_Field(now).should == "bar" end it "escapes special characters" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'o\\'reilly' LIMIT 1").and_return(["bar"]) TestClass.find_by_Name("o'reilly").should == "bar" end end context "with multiple attributes" do it "constructs and executes a query matching the dynamic attributes" do @client.should_receive(:query) do |query| query.should include("Name = 'Richard'") query.should include("City = 'San Francisco'") query.should include(" LIMIT 1") ["bar"] end TestClass.find_by_Name_and_City('Richard', 'San Francisco').should == "bar" end end end describe "find_all_by_xxx" do context "with a single attribute" do it "constructs and executes a query matching the dynamic attributes" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'Richard'").and_return(["bar"]) TestClass.find_all_by_Name('Richard').should == ["bar"] end it "handles boolean values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE IsDeleted = false").and_return(["bar"]) TestClass.find_all_by_IsDeleted(false).should == ["bar"] end it "handles numeric values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Number_Field = 23.4").and_return(["bar"]) TestClass.find_all_by_Number_Field(23.4).should == ["bar"] end it "handles date values" do today = Date.today @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Date_FIeld = #{today.to_s}").and_return(["bar"]) TestClass.find_all_by_Date_FIeld(today).should == ["bar"] end it "handles datetime values" do now = Time.now @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE DateTime_Field = #{now.strftime("%Y-%m-%dT%H:%M:%S.%L%z").insert(-3, ":")}").and_return(["bar"]) TestClass.find_all_by_DateTime_Field(now).should == ["bar"] end it "escapes special characters" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'o\\'reilly'").and_return(["bar"]) TestClass.find_all_by_Name("o'reilly").should == ["bar"] end end context "with multiple attributes" do it "constructs and executes a query matching the dynamic attributes" do @client.should_receive(:query) do |query| query.should include("Name = 'Richard'") query.should include("City = 'San Francisco'") ["bar"] end TestClass.find_all_by_Name_and_City('Richard', 'San Francisco').should == ["bar"] end end end end describe "dynamic creators" do describe "find_or_create_by_xxx" do context "with a single attribute" do it "searches for a record with the specified attribute and creates it if it doesn't exist" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'Richard' LIMIT 1").and_return(nil) @client.should_receive(:create).with(TestClass, "Name" => "Richard").and_return("gar") TestClass.find_or_create_by_Name('Richard').should == "gar" end it "handles boolean values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE IsDeleted = false LIMIT 1").and_return(nil) @client.should_receive(:create).with(TestClass, "IsDeleted" => false).and_return("gar") TestClass.find_or_create_by_IsDeleted(false).should == "gar" end it "handles numeric values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Number_Field = 23.4 LIMIT 1").and_return(nil) @client.should_receive(:create).with(TestClass, "Number_Field" => 23.4).and_return("gar") TestClass.find_or_create_by_Number_Field(23.4).should == "gar" end it "handles date values" do today = Date.today @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Date_FIeld = #{today.to_s} LIMIT 1").and_return(nil) @client.should_receive(:create).with(TestClass, "Date_FIeld" => today).and_return("gar") TestClass.find_or_create_by_Date_FIeld(today).should == "gar" end it "handles datetime values" do now = Time.now @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE DateTime_Field = #{now.strftime("%Y-%m-%dT%H:%M:%S.%L%z").insert(-3, ":")} LIMIT 1").and_return(nil) @client.should_receive(:create).with(TestClass, "DateTime_Field" => now).and_return("gar") TestClass.find_or_create_by_DateTime_Field(now).should == "gar" end it "escapes special characters" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'o\\'reilly' LIMIT 1").and_return(nil) @client.should_receive(:create).with(TestClass, "Name" => "o'reilly").and_return("gar") TestClass.find_or_create_by_Name("o'reilly").should == "gar" end end context "with multiple attributes" do it "searches for a record with the specified attributes and creates it if it doesn't exist" do @client.should_receive(:query) do |query| query.should include("Name = 'Richard'") query.should include("City = 'San Francisco'") query.should include(" LIMIT 1") nil end @client.should_receive(:create).with(TestClass, {"Name" => "Richard", "City" => "San Francisco"}).and_return("bar") TestClass.find_or_create_by_Name_and_City('Richard', 'San Francisco').should == "bar" end end context "with a hash argument containing additional attributes" do it "finds by the named arguments, but creates by all values in the hash" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'Richard' LIMIT 1").and_return(nil) @client.should_receive(:create).with(TestClass, "Name" => "Richard", "Email_Field" => "foo@bar.com", "IsDeleted" => false).and_return("gar") TestClass.find_or_create_by_Name("Name" => 'Richard', "Email_Field" => "foo@bar.com", "IsDeleted" => false).should == "gar" end end end end describe "dynamic initializers" do describe "find_or_initialize_by_xxx" do context "with a single attribute" do it "searches for a record with the specified attribute and initializes it if it doesn't exist" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'Richard' LIMIT 1").and_return(nil) TestClass.find_or_initialize_by_Name('Richard').Name.should == "Richard" end it "handles boolean values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE IsDeleted = false LIMIT 1").and_return(nil) TestClass.find_or_initialize_by_IsDeleted(false).IsDeleted.should be_false end it "handles numeric values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Number_Field = 23.4 LIMIT 1").and_return(nil) TestClass.find_or_initialize_by_Number_Field(23.4).Number_Field.should == 23.4 end it "handles date values" do today = Date.today @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Date_Field = #{today.to_s} LIMIT 1").and_return(nil) TestClass.find_or_initialize_by_Date_Field(today).Date_Field.should == today end it "handles datetime values" do now = Time.now @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE DateTime_Field = #{now.strftime("%Y-%m-%dT%H:%M:%S.%L%z").insert(-3, ":")} LIMIT 1").and_return(nil) TestClass.find_or_initialize_by_DateTime_Field(now).DateTime_Field.should == now end it "escapes special characters" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'o\\'reilly' LIMIT 1").and_return(nil) TestClass.find_or_initialize_by_Name("o'reilly").Name.should == "o'reilly" end end context "with multiple attributes" do it "searches for a record with the specified attributes and initializes it if it doesn't exist" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'Richard' AND Email_Field = 'fake@email.com' LIMIT 1").and_return(nil) result = TestClass.find_or_initialize_by_Name_and_Email_Field('Richard', 'fake@email.com') result.Name.should == "Richard" result.Email_Field.should == "fake@email.com" end end context "with a hash argument containing additional attributes" do it "finds by the named arguments, but initializes by all values in the hash" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'Richard' LIMIT 1").and_return(nil) result = TestClass.find_or_initialize_by_Name("Name" => 'Richard', "Email_Field" => "foo@bar.com", "IsDeleted" => false) result.Name.should == "Richard" result.Email_Field.should == "foo@bar.com" result.IsDeleted.should be_false end end end end describe "#attributes=" do it "updates the object with the provided attributes" do obj = TestClass.new obj.Name.should be_nil obj.attributes = { "Name" => "foo" } obj.Name.should == "foo" end end describe "#save" do context "with a new object" do before do @obj = TestClass.new @obj.client = @client @obj.Name = "testname" @obj_double = double("object", "Id" => "foo") end it "creates the record remotely with the set attributes" do @client.should_receive(:create).and_return(@obj_double) @obj.save end it "includes only the createable attributes" do @client.should_receive(:create) do |clazz, attrs| attrs.all? {|attr, value| TestClass.createable?(attr).should be_true} @obj_double end @obj.save end it "sets the Id of the newly-persisted object" do @obj.Id.should be_nil @client.should_receive(:create).and_return(@obj_double) @obj.save @obj.Id.should == @obj_double.Id end end context "with an previously-persisted object" do before do @obj = TestClass.new @obj.client = @client @obj.Id = "rid" end it "updates the record with the attributes of the object" do @client.should_receive(:update).and_return("saved updates") @obj.save.should == "saved updates" end it "includes only the updateable attributes" do @client.should_receive(:update) do |clazz, id, attrs| attrs.all? {|attr, value| TestClass.updateable?(attr).should be_true} end @obj.save end end end describe "#update" do it "returns itself with the updated attributes" do obj = TestClass.new obj.Id = "rid" obj.client = @client @client.should_receive(:update).with(TestClass, "rid", {"Name" => "newName"}).and_return(true) obj.update_attributes({"Name" => "newName"}).Name.should == "newName" end end describe "#delete" do it "deletes itself from the database and returns itself" do obj = TestClass.new obj.Id = "rid" obj.client = @client @client.should_receive(:delete).with(TestClass, "rid").and_return("destroyResponse") obj.delete.should == obj end end describe ".search" do it "submits a SOSL query" do @client.should_receive(:search).with("foo").and_return("bar") TestClass.search("foo").should == "bar" end end describe ".upsert" do it "submits an upsert request" do @client.should_receive(:upsert).with("TestClass", "externalField", "foo", "Name" => "Richard").and_return("gar") TestClass.upsert("externalField", "foo", "Name" => "Richard").should == "gar" end end describe ".label_for" do it "returns the label for a named attribute" do TestClass.label_for("Picklist_Field").should == "Picklist Label" end it "raises ArgumentError for unknown attributes" do lambda { TestClass.label_for("Foobar") }.should raise_error(ArgumentError) end end describe ".picklist_values" do it "returns an array of picklist values for an attribute" do TestClass.picklist_values("Picklist_Field").length.should == 3 end it "raises ArgumentError for unknown attributes" do lambda { TestClass.picklist_values("Foobar") }.should raise_error(ArgumentError) end end describe ".field_type" do it "returns the field type for an attribute" do TestClass.field_type("Picklist_Field").should == "picklist" end it "raises ArgumentError for unknown attributes" do lambda { TestClass.field_type("Foobar") }.should raise_error(ArgumentError) end end describe ".updateable?" do it "returns the updateable flag for an attribute" do TestClass.updateable?("Picklist_Field").should be_true TestClass.updateable?("Id").should be_false end it "raises ArgumentError for unknown attributes" do lambda { TestClass.updateable?("Foobar") }.should raise_error(ArgumentError) end end describe ".createable?" do it "returns the createable flag for an attribute" do TestClass.createable?("IsDeleted").should be_false TestClass.createable?("Picklist_Field").should be_true end it "raises ArgumentError for unknown attributes" do lambda { TestClass.createable?("Foobar") }.should raise_error(ArgumentError) end end describe "#[]" do before do @obj = TestClass.new @obj.Id = "rid" @obj.client = @client end it "allows enumerable-like access to attributes" do @obj.Checkbox_Field = "foo" @obj["Checkbox_Field"].should == "foo" end it "returns nil if the attribute does not exist" do @obj["Foobar"].should == nil end end describe "#[]=" do before do @obj = TestClass.new @obj.Id = "rid" @obj.client = @client end it "allows enumerable-like setting of attributes" do @obj["Checkbox_Field"] = "foo" @obj.Checkbox_Field.should == "foo" end it "raises Argument error if attribute does not exist" do lambda { @obj["Foobar"] = "yes" }.should raise_error(ArgumentError) end end describe "form_for compatibility methods" do describe "#persisted?" do it "returns true if the object has an Id" do obj = TestClass.new obj.should_not be_persisted obj.Id = "foo" obj.should be_persisted end end describe "#new_record?" do it "returns true unless the object has an Id" do obj = TestClass.new obj.should be_new_record obj.Id = "foo" obj.should_not be_new_record end end describe "#to_key" do it "returns a unique object key" do TestClass.new.to_key.should_not == TestClass.new.to_key end end describe "#to_param" do it "returns the object Id" do obj = TestClass.new obj.Id = "foo" obj.to_param.should == "foo" end end end describe "#reload" do before do Databasedotcom::Sobject::Sobject.should_receive(:find).with("foo").and_return(double("sobject", :attributes => { "Id" => "foo", "Name" => "James"})) end it "reloads the object" do obj = TestClass.new obj.Id = "foo" obj.reload end it "resets the object attributes" do obj = TestClass.new obj.Id = "foo" obj.Name = "Jerry" obj.reload obj.Id.should == "foo" obj.Name.should == "James" end it "returns self" do obj = TestClass.new obj.Id = "foo" obj.Name = "Jerry" reloaded_obj = obj.reload reloaded_obj.should == obj end end end end Add test to verify when using exclusions on save that fields are removed require 'rspec' require 'spec_helper' require 'databasedotcom' describe Databasedotcom::Sobject::Sobject do class TestClass < Databasedotcom::Sobject::Sobject end before do @client = Databasedotcom::Client.new(File.join(File.dirname(__FILE__), "../../fixtures/databasedotcom.yml")) @client.authenticate(:token => "foo", :instance_url => "https://na9.salesforce.com") TestClass.client = @client end describe "materialization" do context "with a valid Sobject name" do response = JSON.parse(File.read(File.join(File.dirname(__FILE__), "../../fixtures/sobject/sobject_describe_success_response.json"))) it "requests a description of the class" do @client.should_receive(:describe_sobject).with("TestClass").and_return(response) TestClass.materialize("TestClass") end context "with a response" do before do @client.stub(:describe_sobject).and_return(response) TestClass.materialize("TestClass") @sobject = TestClass.new end describe ".attributes" do it "returns the attributes for this Sobject" do TestClass.attributes.should_not be_nil TestClass.attributes.should =~ response["fields"].collect { |f| [f["name"], f["relationshipName"]] }.flatten.compact end end describe "getters and setters" do response["fields"].collect { |f| f["name"] }.each do |name| it "creates a getter and setter for the #{name} attribute" do @sobject.should respond_to(name.to_sym) @sobject.should respond_to("#{name}=".to_sym) end end end describe "default values" do response["fields"].each do |f| it "sets #{f['name']} to #{f['defaultValueFormula'] ? f['defaultValueFormula'] : 'nil'}" do @sobject.send(f["name"].to_sym).should == f["defaultValueFormula"] end end end end end context "with an invalid Sobject name" do it "propagates exceptions" do @client.should_receive(:describe_sobject).with("TestClass").and_raise(Databasedotcom::SalesForceError.new(double("result", :body => "{}"))) lambda { TestClass.materialize("TestClass") }.should raise_error(Databasedotcom::SalesForceError) end end end context "with a materialized class" do before do response = JSON.parse(File.read(File.join(File.dirname(__FILE__), "../../fixtures/sobject/sobject_describe_success_response.json"))) @client.should_receive(:describe_sobject).with("TestClass").and_return(response) TestClass.materialize("TestClass") @field_names = TestClass.description["fields"].collect { |f| f["name"] } end describe "#==" do before do @first = TestClass.new("Id" => "foo") end context "when the objects are the same class" do context "when the ids match" do before do @second = TestClass.new("Id" => "foo") end it "returns true" do @first.should == @second end end context "when the ids do not match" do before do @second = TestClass.new("Id" => "bar") end it "returns false" do @first.should_not == @second end end end context "when the objects are different classes" do before do @second = stub(:is_a? => false) end it "returns false" do @first.should_not == @second end end end describe ".new" do it "creates a new in-memory instance with the specified attributes" do obj = TestClass.new("Name" => "foo") obj.Name.should == "foo" obj.should be_new_record end end describe ".create" do it "returns a new instance with the specified attributes" do @client.should_receive(:create).with(TestClass, "moo").and_return("gar") TestClass.create("moo").should == "gar" end end describe ".find" do context "with a valid id" do it "returns the found instance" do @client.should_receive(:find).with(TestClass, "abc").and_return("bar") TestClass.find("abc").should == "bar" end end context "with an invalid id" do it "propagates exceptions" do @client.should_receive(:find).with(TestClass, "abc").and_raise(Databasedotcom::SalesForceError.new(double("result", :body => "{}"))) lambda { TestClass.find("abc") }.should raise_error(Databasedotcom::SalesForceError) end end end describe ".all" do it "returns a paginated enumerable containing all instances" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass").and_return("foo") TestClass.all.should == "foo" end end describe ".query" do it "constructs and submits a SOQL query" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'foo'").and_return("bar") TestClass.query("Name = 'foo'").should == "bar" end end describe ".delete" do it "deletes a record specified by id" do @client.should_receive(:delete).with("TestClass", "recordId").and_return("deleteResponse") TestClass.delete("recordId").should == "deleteResponse" end end describe ".first" do it "loads the first record" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass ORDER BY Id ASC LIMIT 1").and_return(["foo"]) TestClass.first.should == "foo" end it "optionally includes SOQL conditions" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE conditions ORDER BY Id ASC LIMIT 1").and_return(["foo"]) TestClass.first("conditions").should == "foo" end end describe ".last" do it "loads the last record" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass ORDER BY Id DESC LIMIT 1").and_return(["bar"]) TestClass.last.should == "bar" end it "optionally includes SOQL conditions" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE conditions ORDER BY Id DESC LIMIT 1").and_return(["bar"]) TestClass.last("conditions").should == "bar" end end describe ".count" do it "gets the record count" do @client.should_receive(:query).with("SELECT COUNT() FROM TestClass").and_return(double("collection", :total_size => 42)) TestClass.count.should == 42 end end describe ".coerce_params" do it "coerces boolean attributes" do TestClass.coerce_params("Checkbox_Field" => "1")["Checkbox_Field"].should be_true TestClass.coerce_params("Checkbox_Field" => "0")["Checkbox_Field"].should be_false TestClass.coerce_params("Checkbox_Field" => true)["Checkbox_Field"].should be_true TestClass.coerce_params("Checkbox_Field" => false)["Checkbox_Field"].should be_false end it "coerces currency attributes" do TestClass.coerce_params("Currency_Field" => "123.4")["Currency_Field"].should == 123.4 TestClass.coerce_params("Currency_Field" => 123.4)["Currency_Field"].should == 123.4 end it "coerces percent attributes" do TestClass.coerce_params("Percent_Field" => "123.4")["Percent_Field"].should == 123.4 TestClass.coerce_params("Percent_Field" => 123.4)["Percent_Field"].should == 123.4 end it "coerces date fields" do today = Date.today Date.stub(:today).and_return(today) TestClass.coerce_params("Date_Field" => "2010-04-01")["Date_Field"].should == Date.civil(2010, 4, 1) TestClass.coerce_params("Date_Field" => "bogus")["Date_Field"].should == Date.today end it "coerces datetime fields" do now = DateTime.now DateTime.stub(:now).and_return(now) TestClass.coerce_params("DateTime_Field" => "2010-04-01T12:05:10Z")["DateTime_Field"].to_s.should == DateTime.civil(2010, 4, 1, 12, 5, 10).to_s TestClass.coerce_params("DateTime_Field" => "bogus")["DateTime_Field"].to_s.should == now.to_s end end describe "dynamic finders" do describe "find_by_xxx" do context "with a single attribute" do it "constructs and executes a query matching the dynamic attributes" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'Richard' LIMIT 1").and_return(["bar"]) TestClass.find_by_Name('Richard').should == "bar" end it "handles boolean values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE IsDeleted = false LIMIT 1").and_return(["bar"]) TestClass.find_by_IsDeleted(false).should == "bar" end it "handles numeric values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Number_Field = 23.4 LIMIT 1").and_return(["bar"]) TestClass.find_by_Number_Field(23.4).should == "bar" end it "handles date values" do today = Date.today @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Date_FIeld = #{today.to_s} LIMIT 1").and_return(["bar"]) TestClass.find_by_Date_FIeld(today).should == "bar" end it "handles datetime values" do now = Time.now @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE DateTime_Field = #{now.strftime("%Y-%m-%dT%H:%M:%S.%L%z").insert(-3, ":")} LIMIT 1").and_return(["bar"]) TestClass.find_by_DateTime_Field(now).should == "bar" end it "escapes special characters" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'o\\'reilly' LIMIT 1").and_return(["bar"]) TestClass.find_by_Name("o'reilly").should == "bar" end end context "with multiple attributes" do it "constructs and executes a query matching the dynamic attributes" do @client.should_receive(:query) do |query| query.should include("Name = 'Richard'") query.should include("City = 'San Francisco'") query.should include(" LIMIT 1") ["bar"] end TestClass.find_by_Name_and_City('Richard', 'San Francisco').should == "bar" end end end describe "find_all_by_xxx" do context "with a single attribute" do it "constructs and executes a query matching the dynamic attributes" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'Richard'").and_return(["bar"]) TestClass.find_all_by_Name('Richard').should == ["bar"] end it "handles boolean values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE IsDeleted = false").and_return(["bar"]) TestClass.find_all_by_IsDeleted(false).should == ["bar"] end it "handles numeric values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Number_Field = 23.4").and_return(["bar"]) TestClass.find_all_by_Number_Field(23.4).should == ["bar"] end it "handles date values" do today = Date.today @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Date_FIeld = #{today.to_s}").and_return(["bar"]) TestClass.find_all_by_Date_FIeld(today).should == ["bar"] end it "handles datetime values" do now = Time.now @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE DateTime_Field = #{now.strftime("%Y-%m-%dT%H:%M:%S.%L%z").insert(-3, ":")}").and_return(["bar"]) TestClass.find_all_by_DateTime_Field(now).should == ["bar"] end it "escapes special characters" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'o\\'reilly'").and_return(["bar"]) TestClass.find_all_by_Name("o'reilly").should == ["bar"] end end context "with multiple attributes" do it "constructs and executes a query matching the dynamic attributes" do @client.should_receive(:query) do |query| query.should include("Name = 'Richard'") query.should include("City = 'San Francisco'") ["bar"] end TestClass.find_all_by_Name_and_City('Richard', 'San Francisco').should == ["bar"] end end end end describe "dynamic creators" do describe "find_or_create_by_xxx" do context "with a single attribute" do it "searches for a record with the specified attribute and creates it if it doesn't exist" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'Richard' LIMIT 1").and_return(nil) @client.should_receive(:create).with(TestClass, "Name" => "Richard").and_return("gar") TestClass.find_or_create_by_Name('Richard').should == "gar" end it "handles boolean values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE IsDeleted = false LIMIT 1").and_return(nil) @client.should_receive(:create).with(TestClass, "IsDeleted" => false).and_return("gar") TestClass.find_or_create_by_IsDeleted(false).should == "gar" end it "handles numeric values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Number_Field = 23.4 LIMIT 1").and_return(nil) @client.should_receive(:create).with(TestClass, "Number_Field" => 23.4).and_return("gar") TestClass.find_or_create_by_Number_Field(23.4).should == "gar" end it "handles date values" do today = Date.today @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Date_FIeld = #{today.to_s} LIMIT 1").and_return(nil) @client.should_receive(:create).with(TestClass, "Date_FIeld" => today).and_return("gar") TestClass.find_or_create_by_Date_FIeld(today).should == "gar" end it "handles datetime values" do now = Time.now @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE DateTime_Field = #{now.strftime("%Y-%m-%dT%H:%M:%S.%L%z").insert(-3, ":")} LIMIT 1").and_return(nil) @client.should_receive(:create).with(TestClass, "DateTime_Field" => now).and_return("gar") TestClass.find_or_create_by_DateTime_Field(now).should == "gar" end it "escapes special characters" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'o\\'reilly' LIMIT 1").and_return(nil) @client.should_receive(:create).with(TestClass, "Name" => "o'reilly").and_return("gar") TestClass.find_or_create_by_Name("o'reilly").should == "gar" end end context "with multiple attributes" do it "searches for a record with the specified attributes and creates it if it doesn't exist" do @client.should_receive(:query) do |query| query.should include("Name = 'Richard'") query.should include("City = 'San Francisco'") query.should include(" LIMIT 1") nil end @client.should_receive(:create).with(TestClass, {"Name" => "Richard", "City" => "San Francisco"}).and_return("bar") TestClass.find_or_create_by_Name_and_City('Richard', 'San Francisco').should == "bar" end end context "with a hash argument containing additional attributes" do it "finds by the named arguments, but creates by all values in the hash" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'Richard' LIMIT 1").and_return(nil) @client.should_receive(:create).with(TestClass, "Name" => "Richard", "Email_Field" => "foo@bar.com", "IsDeleted" => false).and_return("gar") TestClass.find_or_create_by_Name("Name" => 'Richard', "Email_Field" => "foo@bar.com", "IsDeleted" => false).should == "gar" end end end end describe "dynamic initializers" do describe "find_or_initialize_by_xxx" do context "with a single attribute" do it "searches for a record with the specified attribute and initializes it if it doesn't exist" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'Richard' LIMIT 1").and_return(nil) TestClass.find_or_initialize_by_Name('Richard').Name.should == "Richard" end it "handles boolean values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE IsDeleted = false LIMIT 1").and_return(nil) TestClass.find_or_initialize_by_IsDeleted(false).IsDeleted.should be_false end it "handles numeric values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Number_Field = 23.4 LIMIT 1").and_return(nil) TestClass.find_or_initialize_by_Number_Field(23.4).Number_Field.should == 23.4 end it "handles date values" do today = Date.today @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Date_Field = #{today.to_s} LIMIT 1").and_return(nil) TestClass.find_or_initialize_by_Date_Field(today).Date_Field.should == today end it "handles datetime values" do now = Time.now @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE DateTime_Field = #{now.strftime("%Y-%m-%dT%H:%M:%S.%L%z").insert(-3, ":")} LIMIT 1").and_return(nil) TestClass.find_or_initialize_by_DateTime_Field(now).DateTime_Field.should == now end it "escapes special characters" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'o\\'reilly' LIMIT 1").and_return(nil) TestClass.find_or_initialize_by_Name("o'reilly").Name.should == "o'reilly" end end context "with multiple attributes" do it "searches for a record with the specified attributes and initializes it if it doesn't exist" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'Richard' AND Email_Field = 'fake@email.com' LIMIT 1").and_return(nil) result = TestClass.find_or_initialize_by_Name_and_Email_Field('Richard', 'fake@email.com') result.Name.should == "Richard" result.Email_Field.should == "fake@email.com" end end context "with a hash argument containing additional attributes" do it "finds by the named arguments, but initializes by all values in the hash" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'Richard' LIMIT 1").and_return(nil) result = TestClass.find_or_initialize_by_Name("Name" => 'Richard', "Email_Field" => "foo@bar.com", "IsDeleted" => false) result.Name.should == "Richard" result.Email_Field.should == "foo@bar.com" result.IsDeleted.should be_false end end end end describe "#attributes=" do it "updates the object with the provided attributes" do obj = TestClass.new obj.Name.should be_nil obj.attributes = { "Name" => "foo" } obj.Name.should == "foo" end end describe "#save" do context "with a new object" do before do @obj = TestClass.new @obj.client = @client @obj.Name = "testname" @obj_double = double("object", "Id" => "foo") end it "creates the record remotely with the set attributes" do @client.should_receive(:create).and_return(@obj_double) @obj.save end it "includes only the createable attributes" do @client.should_receive(:create) do |clazz, attrs| attrs.all? {|attr, value| TestClass.createable?(attr).should be_true} @obj_double end @obj.save end it "sets the Id of the newly-persisted object" do @obj.Id.should be_nil @client.should_receive(:create).and_return(@obj_double) @obj.save @obj.Id.should == @obj_double.Id end end context "with an previously-persisted object" do before do @obj = TestClass.new @obj.client = @client @obj.Id = "rid" end it "updates the record with the attributes of the object" do @client.should_receive(:update).and_return("saved updates") @obj.save.should == "saved updates" end it "includes only the updateable attributes" do @client.should_receive(:update) do |clazz, id, attrs| attrs.all? {|attr, value| TestClass.updateable?(attr).should be_true} end @obj.save end end context "with exclusions argument" do before do @obj = TestClass.new @obj.Name = "testname" @obj.OwnerId = "someownerid" @obj_double = double("object", "Id" => "foo") end it "remove any listed fields from the attributes on create" do @client.should_receive(:create) do |clazz, attrs| attrs.include?("Name").should be_false attrs.include?("OwnerId").should be_true @obj_double end @obj.save(:exclusions => ["Name"]) end it "remove any listed fields from the attributes on update" do @obj.Id = "foo" @client.should_receive(:update) do |clazz, id, attrs| attrs.include?("Name").should be_false attrs.include?("OwnerId").should be_true end result = @obj.save(:exclusions => ["Name"]) end end end describe "#update" do it "returns itself with the updated attributes" do obj = TestClass.new obj.Id = "rid" obj.client = @client @client.should_receive(:update).with(TestClass, "rid", {"Name" => "newName"}).and_return(true) obj.update_attributes({"Name" => "newName"}).Name.should == "newName" end end describe "#delete" do it "deletes itself from the database and returns itself" do obj = TestClass.new obj.Id = "rid" obj.client = @client @client.should_receive(:delete).with(TestClass, "rid").and_return("destroyResponse") obj.delete.should == obj end end describe ".search" do it "submits a SOSL query" do @client.should_receive(:search).with("foo").and_return("bar") TestClass.search("foo").should == "bar" end end describe ".upsert" do it "submits an upsert request" do @client.should_receive(:upsert).with("TestClass", "externalField", "foo", "Name" => "Richard").and_return("gar") TestClass.upsert("externalField", "foo", "Name" => "Richard").should == "gar" end end describe ".label_for" do it "returns the label for a named attribute" do TestClass.label_for("Picklist_Field").should == "Picklist Label" end it "raises ArgumentError for unknown attributes" do lambda { TestClass.label_for("Foobar") }.should raise_error(ArgumentError) end end describe ".picklist_values" do it "returns an array of picklist values for an attribute" do TestClass.picklist_values("Picklist_Field").length.should == 3 end it "raises ArgumentError for unknown attributes" do lambda { TestClass.picklist_values("Foobar") }.should raise_error(ArgumentError) end end describe ".field_type" do it "returns the field type for an attribute" do TestClass.field_type("Picklist_Field").should == "picklist" end it "raises ArgumentError for unknown attributes" do lambda { TestClass.field_type("Foobar") }.should raise_error(ArgumentError) end end describe ".updateable?" do it "returns the updateable flag for an attribute" do TestClass.updateable?("Picklist_Field").should be_true TestClass.updateable?("Id").should be_false end it "raises ArgumentError for unknown attributes" do lambda { TestClass.updateable?("Foobar") }.should raise_error(ArgumentError) end end describe ".createable?" do it "returns the createable flag for an attribute" do TestClass.createable?("IsDeleted").should be_false TestClass.createable?("Picklist_Field").should be_true end it "raises ArgumentError for unknown attributes" do lambda { TestClass.createable?("Foobar") }.should raise_error(ArgumentError) end end describe "#[]" do before do @obj = TestClass.new @obj.Id = "rid" @obj.client = @client end it "allows enumerable-like access to attributes" do @obj.Checkbox_Field = "foo" @obj["Checkbox_Field"].should == "foo" end it "returns nil if the attribute does not exist" do @obj["Foobar"].should == nil end end describe "#[]=" do before do @obj = TestClass.new @obj.Id = "rid" @obj.client = @client end it "allows enumerable-like setting of attributes" do @obj["Checkbox_Field"] = "foo" @obj.Checkbox_Field.should == "foo" end it "raises Argument error if attribute does not exist" do lambda { @obj["Foobar"] = "yes" }.should raise_error(ArgumentError) end end describe "form_for compatibility methods" do describe "#persisted?" do it "returns true if the object has an Id" do obj = TestClass.new obj.should_not be_persisted obj.Id = "foo" obj.should be_persisted end end describe "#new_record?" do it "returns true unless the object has an Id" do obj = TestClass.new obj.should be_new_record obj.Id = "foo" obj.should_not be_new_record end end describe "#to_key" do it "returns a unique object key" do TestClass.new.to_key.should_not == TestClass.new.to_key end end describe "#to_param" do it "returns the object Id" do obj = TestClass.new obj.Id = "foo" obj.to_param.should == "foo" end end end describe "#reload" do before do Databasedotcom::Sobject::Sobject.should_receive(:find).with("foo").and_return(double("sobject", :attributes => { "Id" => "foo", "Name" => "James"})) end it "reloads the object" do obj = TestClass.new obj.Id = "foo" obj.reload end it "resets the object attributes" do obj = TestClass.new obj.Id = "foo" obj.Name = "Jerry" obj.reload obj.Id.should == "foo" obj.Name.should == "James" end it "returns self" do obj = TestClass.new obj.Id = "foo" obj.Name = "Jerry" reloaded_obj = obj.reload reloaded_obj.should == obj end end end end
require 'spec_helper' describe Lobbyist::V2::Company, customer_call: true do describe "#disconnect_direct_connect" do it 'disconnect from the company and return the company' do VCR.use_cassette('v2/company_disconnect_direct_connect') do results = Lobbyist::V2::Company.disconnect_direct_connect(5565) expect(results).to be_a(Lobbyist::V2::Company) expect(results.workflow_system_id).to be(nil) end end it 'direct_connect_settings for company' do VCR.use_cassette('v2/direct_connect_setting') do results = Lobbyist::V2::Company.direct_connect_settings(5565) expect(results).to be_a(Lobbyist::V2::DirectConnectSetting) expect(results.company_id).to be(5565) end end end end CA-7071 #comment Fixed formatting issue for company spec. require 'spec_helper' describe Lobbyist::V2::Company, customer_call: true do describe "#disconnect_direct_connect" do it 'disconnect from the company and return the company' do VCR.use_cassette('v2/company_disconnect_direct_connect') do results = Lobbyist::V2::Company.disconnect_direct_connect(5565) expect(results).to be_a(Lobbyist::V2::Company) expect(results.workflow_system_id).to be(nil) end end end describe "#direct_connect_settings" do it 'direct_connect_settings for company' do VCR.use_cassette('v2/direct_connect_setting') do results = Lobbyist::V2::Company.direct_connect_settings(5565) expect(results).to be_a(Lobbyist::V2::DirectConnectSetting) expect(results.company_id).to be(5565) end end end end
Added user mailer spec. require "spec_helper" describe UserMailer do let(:user) { Fabricate(:user) } describe 'activation_needed_email' do let(:mail) { UserMailer.activation_needed_email(user) } it 'should be valid' do mail.should have_subject('Welcome to Courseware') mail.should deliver_to(user.email) mail.should deliver_from(Courseware.config.default_email_address) mail.should have_body_text(activate_user_url(user.activation_token)) end end describe 'activation_success_email' do let(:mail) { UserMailer.activation_success_email(user) } it 'should be valid' do mail.should have_subject('Your Courseware account was activated') mail.should deliver_to(user.email) mail.should deliver_from(Courseware.config.default_email_address) mail.should have_body_text(login_url) end end describe 'reset_password_email' do before do # Set a reset token token = Faker::HipsterIpsum.word user.update_attribute :reset_password_token, token user.update_attribute :reset_password_token_expires_at, Date.tomorrow end let(:mail) { UserMailer.reset_password_email(user) } it 'should be valid' do mail.should have_subject('Your Courseware password has been reset') mail.should deliver_to(user.email) mail.should deliver_from(Courseware.config.default_email_address) mail.should have_body_text(edit_password_url(user.reset_password_token)) end end end
require 'spec_helper' describe Conversation do before(:each) do @grasshopper = User.create(first_name: 'Grass', last_name: 'Hopper', email: 'gh@ga.co', password: '123', password_confirmation: '123', role: 'apprentice') @master = User.create(first_name: 'Master', last_name: 'Hopper', email: 'gm@ga.co', password: '123', password_confirmation: '123', role: 'master') @conversation = Conversation.create(created_by: @grasshopper.id, created_for: @master.id) end it "should not valid without created_for" do @conversation.created_for = nil expect(@conversation).to_not be_valid end it "should not valid without created_by" do @conversation.created_by = nil expect(@conversation).to_not be_valid end it "should update updated_at when new message is created" do previous_updated_at_time = @conversation.updated_at @conversation.messages.create(from_user: @grasshopper.id, to_user: @master.id) expect(Conversation.find(@conversation.id).updated_at).to_not eq previous_updated_at_time end describe "when created_by initiater" do describe "recipient" do it "should not be the same as initiater" do conversation = Conversation.new(created_by: @grasshopper.id, created_for: @grasshopper.id) conversation.save expect(conversation).to_not be_valid end it "should not have existing conversation with the initiater" do new_conversation_same_initiater = Conversation.create(created_by: @grasshopper.id, created_for: @master.id) new_conversation_different_initiater = Conversation.create(created_by: @master.id, created_for: @grasshopper.id) expect(new_conversation_same_initiater).to_not be_valid expect(new_conversation_different_initiater).to_not be_valid end end end describe "updated_at" do it "should be updated when a new message is created in this conversation" end end REMOVED redundant test require 'spec_helper' describe Conversation do before(:each) do @grasshopper = User.create(first_name: 'Grass', last_name: 'Hopper', email: 'gh@ga.co', password: '123', password_confirmation: '123', role: 'apprentice') @master = User.create(first_name: 'Master', last_name: 'Hopper', email: 'gm@ga.co', password: '123', password_confirmation: '123', role: 'master') @conversation = Conversation.create(created_by: @grasshopper.id, created_for: @master.id) end it "should not valid without created_for" do @conversation.created_for = nil expect(@conversation).to_not be_valid end it "should not valid without created_by" do @conversation.created_by = nil expect(@conversation).to_not be_valid end it "should update updated_at when new message is created" do previous_updated_at_time = @conversation.updated_at @conversation.messages.create(from_user: @grasshopper.id, to_user: @master.id) expect(Conversation.find(@conversation.id).updated_at).to_not eq previous_updated_at_time end describe "when created_by initiater" do describe "recipient" do it "should not be the same as initiater" do conversation = Conversation.new(created_by: @grasshopper.id, created_for: @grasshopper.id) conversation.save expect(conversation).to_not be_valid end it "should not have existing conversation with the initiater" do new_conversation_same_initiater = Conversation.create(created_by: @grasshopper.id, created_for: @master.id) new_conversation_different_initiater = Conversation.create(created_by: @master.id, created_for: @grasshopper.id) expect(new_conversation_same_initiater).to_not be_valid expect(new_conversation_different_initiater).to_not be_valid end end end end
require 'rails_helper' RSpec.describe DomainBlock, type: :model do describe 'validations' do it 'has a valid fabricator' do domain_block = Fabricate.build(:domain_block) expect(domain_block).to be_valid end it 'is invalid without a domain' do domain_block = Fabricate.build(:domain_block, domain: nil) domain_block.valid? expect(domain_block).to model_have_error_on_field(:domain) end it 'is invalid if the domain already exists' do domain_block_1 = Fabricate(:domain_block, domain: 'dalek.com') domain_block_2 = Fabricate.build(:domain_block, domain: 'dalek.com') domain_block_2.valid? expect(domain_block_2).to model_have_error_on_field(:domain) end end end Cover DomainBlock more (#3838) require 'rails_helper' RSpec.describe DomainBlock, type: :model do describe 'validations' do it 'has a valid fabricator' do domain_block = Fabricate.build(:domain_block) expect(domain_block).to be_valid end it 'is invalid without a domain' do domain_block = Fabricate.build(:domain_block, domain: nil) domain_block.valid? expect(domain_block).to model_have_error_on_field(:domain) end it 'is invalid if the same normalized domain already exists' do domain_block_1 = Fabricate(:domain_block, domain: 'にゃん') domain_block_2 = Fabricate.build(:domain_block, domain: 'xn--r9j5b5b') domain_block_2.valid? expect(domain_block_2).to model_have_error_on_field(:domain) end end describe 'blocked?' do it 'returns true if the domain is suspended' do Fabricate(:domain_block, domain: 'domain', severity: :suspend) expect(DomainBlock.blocked?('domain')).to eq true end it 'returns false even if the domain is silenced' do Fabricate(:domain_block, domain: 'domain', severity: :silence) expect(DomainBlock.blocked?('domain')).to eq false end it 'returns false if the domain is not suspended nor silenced' do expect(DomainBlock.blocked?('domain')).to eq false end end end
require 'rails_helper' RSpec.describe HangmanGame do let(:initial_lives) { 1 } let(:mystery_word) { 'abc' } subject(:game) { HangmanGame.create(mystery_word: mystery_word, initial_lives: initial_lives) } describe 'testing new game validation' do context 'with an empty word' do let(:mystery_word) { '' } it 'should not save' do expect(game).to be_invalid end end context "with a word that has symbols" do let(:mystery_word) { '\@dabomb' } it 'should not save' do expect(game).to be_invalid end end context "with a word that has numbers" do let(:mystery_word) { 'l33t' } it 'should not save' do expect(game).to be_invalid end end context "with a word that has blank space" do let(:mystery_word) { 'hello darkness' } it 'should not save' do expect(game).to be_invalid end end context "with a singular character word" do let(:mystery_word) { 'h' } it 'should not save' do expect(game).to be_invalid end end context "with an alphabetical mystery word with more than 1 character" do let(:mystery_word) { 'hh' } it 'should save' do expect(game).to be_valid end end context "with 0 or less initial lives" do let(:initial_lives) { 0 } it 'should not save with 0 lives' do expect(game).to be_invalid end let(:initial_lives) { -1 } it 'should not save with -1 lives' do expect(game).to be_invalid end end end describe 'testing valid input' do let(:mystery_word) { 'abc' } context 'given input occuring in the mystery word' do let(:correct_input) { mystery_word.chars.first } it 'should reveal the letter in masked word' do game.guess(correct_input) expect(game.masked_word).to eql([ 'a', nil, nil ]) end it 'should not decrement life' do initial_lives = game.lives game.guess(correct_input) expect(game.lives).to eql(initial_lives) end end context 'given input not appearing in the mystery word' do let(:incorrect_input) { 'z' } it 'should not reveal any letters in masked word' do game.guess(incorrect_input) expect(game.masked_word).to eql([ nil, nil, nil]) end it 'should decrement the players life' do initial_lives = game.lives game.guess(incorrect_input) expect(game.lives).to eql(initial_lives - 1) end end context 'given uppercase input appearing in the word' do let(:uppercase_input) { 'A' } it 'should reveal the letter in the masked word' do game.guess(uppercase_input) expect(game.masked_word).to eql([ 'a', nil, nil ]) end end end describe 'a game with uppercase letters in mystery word' do let(:mystery_word) { 'AbCc' } context 'given lowercase input' do it 'should reveal the uppercase letter in the masked word' do game.guess('a') expect(game.masked_word).to eql([ 'A', nil, nil, nil ]) end it 'should reveal all occurences of letter regardless of case' do game.guess('c') expect(game.masked_word).to eql([ nil, nil, 'C', 'c' ]) end end end describe 'testing all letters are guessed' do let(:mystery_word) { 'abc' } it 'should win the game' do game.guess(mystery_word.chars.first) game.guess(mystery_word.chars.second) game.guess(mystery_word.chars.third) expect(game).to be_won expect(game).not_to be_running end end describe 'testing player runs out of lives' do let(:mystery_word) { 'abc' } let(:initial_lives) { 1 } it 'should lose the game' do game.guess('y') expect(game).not_to be_won expect(game).not_to be_running end end describe 'testing input validator' do let(:mystery_word) { 'abc' } context 'with invalid inputs' do let(:symbols) { [ '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '[', ']', '{', '}' ] } it 'should reject symbols' do random_symbols = symbols.sample(3) expect(game.valid_input?(random_symbols.first)).to be_falsey expect(game.valid_input?(random_symbols.second)).to be_falsey expect(game.valid_input?(random_symbols.third)).to be_falsey end it 'should reject numbers' do expect(game.valid_input?('1')).to be_falsey expect(game.valid_input?('9')).to be_falsey end it 'should reject multiple characters' do expect(game.valid_input?('ab')).to be_falsey end it 'should reject empty inputs' do expect(game.valid_input?('')).to be_falsey end it 'should reject letters already guessed' do game.guess('a') expect(game.valid_input?('a')).to be_falsey end end context 'with valid inputs' do it 'should accept lowercase alphabetic inputs' do expect(game.valid_input?('b')).to be_truthy end it 'should accept uppercase alphabetic inputs' do expect(game.valid_input?('A')).to be_truthy end end end end added errors check require 'rails_helper' RSpec.describe HangmanGame do let(:initial_lives) { 1 } let(:mystery_word) { 'abc' } subject(:game) { HangmanGame.create(mystery_word: mystery_word, initial_lives: initial_lives) } describe 'testing new game validation' do context 'with an empty word' do let(:mystery_word) { '' } it 'should not save' do expect(game).to be_invalid end it 'should contain a mystery word error' do expect(game.errors[:mystery_word]) end end context "with a word that has symbols" do let(:mystery_word) { '\@dabomb' } it 'should not save' do expect(game).to be_invalid end end context "with a word that has numbers" do let(:mystery_word) { 'l33t' } it 'should not save' do expect(game).to be_invalid end end context "with a word that has blank space" do let(:mystery_word) { 'hello darkness' } it 'should not save' do expect(game).to be_invalid end end context "with a singular character word" do let(:mystery_word) { 'h' } it 'should not save' do expect(game).to be_invalid end end context "with an alphabetical mystery word with more than 1 character" do let(:mystery_word) { 'hh' } it 'should save' do expect(game).to be_valid end end context "with 0 or less initial lives" do let(:initial_lives) { 0 } it 'should not save with 0 lives' do expect(game).to be_invalid end let(:initial_lives) { -1 } it 'should not save with -1 lives' do expect(game).to be_invalid end end end describe 'testing valid input' do let(:mystery_word) { 'abc' } context 'given input occuring in the mystery word' do let(:correct_input) { mystery_word.chars.first } it 'should reveal the letter in masked word' do game.guess(correct_input) expect(game.masked_word).to eql([ 'a', nil, nil ]) end it 'should not decrement life' do initial_lives = game.lives game.guess(correct_input) expect(game.lives).to eql(initial_lives) end end context 'given input not appearing in the mystery word' do let(:incorrect_input) { 'z' } it 'should not reveal any letters in masked word' do game.guess(incorrect_input) expect(game.masked_word).to eql([ nil, nil, nil]) end it 'should decrement the players life' do initial_lives = game.lives game.guess(incorrect_input) expect(game.lives).to eql(initial_lives - 1) end end context 'given uppercase input appearing in the word' do let(:uppercase_input) { 'A' } it 'should reveal the letter in the masked word' do game.guess(uppercase_input) expect(game.masked_word).to eql([ 'a', nil, nil ]) end end end describe 'a game with uppercase letters in mystery word' do let(:mystery_word) { 'AbCc' } context 'given lowercase input' do it 'should reveal the uppercase letter in the masked word' do game.guess('a') expect(game.masked_word).to eql([ 'A', nil, nil, nil ]) end it 'should reveal all occurences of letter regardless of case' do game.guess('c') expect(game.masked_word).to eql([ nil, nil, 'C', 'c' ]) end end end describe 'testing all letters are guessed' do let(:mystery_word) { 'abc' } it 'should win the game' do game.guess(mystery_word.chars.first) game.guess(mystery_word.chars.second) game.guess(mystery_word.chars.third) expect(game).to be_won expect(game).not_to be_running end end describe 'testing player runs out of lives' do let(:mystery_word) { 'abc' } let(:initial_lives) { 1 } it 'should lose the game' do game.guess('y') expect(game).not_to be_won expect(game).not_to be_running end end describe 'testing input validator' do let(:mystery_word) { 'abc' } context 'with invalid inputs' do let(:symbols) { [ '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '[', ']', '{', '}' ] } it 'should reject symbols' do random_symbols = symbols.sample(3) expect(game.valid_input?(random_symbols.first)).to be_falsey expect(game.valid_input?(random_symbols.second)).to be_falsey expect(game.valid_input?(random_symbols.third)).to be_falsey end it 'should reject numbers' do expect(game.valid_input?('1')).to be_falsey expect(game.valid_input?('9')).to be_falsey end it 'should reject multiple characters' do expect(game.valid_input?('ab')).to be_falsey end it 'should reject empty inputs' do expect(game.valid_input?('')).to be_falsey end it 'should reject letters already guessed' do game.guess('a') expect(game.valid_input?('a')).to be_falsey end end context 'with valid inputs' do it 'should accept lowercase alphabetic inputs' do expect(game.valid_input?('b')).to be_truthy end it 'should accept uppercase alphabetic inputs' do expect(game.valid_input?('A')).to be_truthy end end end end
require 'spec_helper' module Newsie describe Event do let(:event) do mock_model Event, :name => "test_event", :start_date => Time.now(), :end_date => Time.now() + (60*60*24), # next day :content => "Random content", end let(:event) do mock_model Event, :name => "test_event2", :start_date => Time.now() - (60*60*24), #yesterday :end_date => Time.now() - 1, # one second ago :content => "Random content 2", end it { event.should be_valid } context "methods" do context "extra_extra" do it { extra_extra.should eq("Random content") } end end end end Updated the specs for event model require 'spec_helper' require File.join(File.dirname(__FILE__), '..', '..', '..', 'app', 'models', 'newsie', 'event') module Newsie describe Event do before :all do 5.times do |i| Newsie::Event.create!( { :name => "Event #{i}", :start_date => Time.now() + (60*60*24*(i-1)), #Start with day before :end_dated => Time.now() + (60*60*24*i), #Start with current current day :content => "Content #{i}" } ) end end let(:event) do mock_model Event, :name => "test_event", :start_date => Time.now(), :end_date => Time.now() + (60*60*24), # next day :content => "Random content", end it { event.should be_valid } context "methods" do context "extra_extra" do it { Event.extra_extra.should eq("Content 0") } end end end end
require 'spec_helper' require 'controller_spec_helper' require 'stringio' require 'csv_helper' include CSVHelper CSV_HEADERS = ["Netid / Email", "Chart String" , "Product Name" , "Quantity" , "Order Date" , "Fulfillment Date"] DEFAULT_ORDER_DATE = 4.days.ago.to_date DEFAULT_FULLFILLED_DATE = 3.days.ago.to_date def errors_for_import_with_row(opts={}) row = CSV::Row.new(CSV_HEADERS, [ opts[:username] || @guest.username, opts[:account_number] || "111-2222222-33333333-01", opts[:product_name] || "Example Item", opts[:quantity] || 1, opts[:order_date] || DEFAULT_ORDER_DATE.strftime("%m/%d/%Y"), opts[:fullfillment_date] || DEFAULT_FULLFILLED_DATE.strftime("%m/%d/%Y") ]) errs = @order_import.errors_for(row) end describe OrderImport do before(:all) { create_users } before :each do # clear Timecop's altering of time if active Timecop.return before_import = 10.days.ago Timecop.travel(before_import) do @authable = Factory.create(:facility) @facility_account = @authable.facility_accounts.create!(Factory.attributes_for(:facility_account)) grant_role(@director, @authable) @item = @authable.items.create!(Factory.attributes_for(:item, :facility_account_id => @facility_account.id, :name => "Example Item" )) # price stuff @price_group = @authable.price_groups.create!(Factory.attributes_for(:price_group)) @pg_member = Factory.create(:user_price_group_member, :user => @guest, :price_group => @price_group) @item_pp=@item.item_price_policies.create!(Factory.attributes_for(:item_price_policy, :price_group_id => @price_group.id, )) @guest2 = Factory.create :user, :username => 'guest2' @pg_member = Factory.create(:user_price_group_member, :user => @guest2, :price_group => @price_group) @account = Factory.create(:nufs_account, :description => "dummy account", :account_number => '111-2222222-33333333-01', :account_users_attributes => [ Hash[:user => @guest, :created_by => @guest, :user_role => 'Owner'], Hash[:user => @guest2, :created_by => @guest, :user_role => 'Purchaser'] ] ) end stored_file = StoredFile.create!( :file => StringIO.new("c,s,v"), :file_type => 'import_upload', :name => "clean_import.csv", :created_by => @director.id ) @order_import=OrderImport.create!( :created_by => @director.id, :upload_file => stored_file, :facility => @authable ) end # validation testing it { should belong_to :creator } it { should belong_to :upload_file } it { should belong_to :error_file } it { should validate_presence_of :upload_file_id } it { should validate_presence_of :created_by } describe "errors_for(row) (low-level) behavior" do describe "error detection" do it "shouldn't have errors for a valid row" do errors_for_import_with_row.should == [] end it "should have error when user isn't found" do errors_for_import_with_row(:username => "username_that_wont_be_there").first.should match /user/ end it "should have error when account isn't found" do errors_for_import_with_row(:account_number => "not_an_account_number").first.should match /find account/ end it "should have error when product isn't found" do errors_for_import_with_row(:product_name => "not_a_product_name").first.should match /find product/ end end describe "created order" do before :each do # run the import of row errors_for_import_with_row.should == [] @created_order = Order.last end it "should have ordered_at set appropriately" do @created_order.ordered_at.to_date.should == DEFAULT_ORDER_DATE end it "should have created_by_user set to creator of import" do @created_order.created_by_user.should == @director end it "should have user set to user in line of import" do @created_order.user.should == @guest end it { @created_order.should be_purchased } context "created order_details" do it "should exist" do assert @created_order.has_details? end it "should have the right product" do @created_order.order_details.first.product.should == @item end it "should have status complete" do @created_order.order_details.each do |od| od.state.should == "complete" end end it "should have price policies" do @created_order.order_details.each do |od| od.price_policy.should_not be nil end end it "should not be problem orders" do @created_order.order_details.each do |od| od.should_not be_problem_order end end it "should have right fullfilled_at" do @created_order.order_details.each do |od| od.fulfilled_at.to_date.should == DEFAULT_FULLFILLED_DATE end end end end describe "multiple calls (same order_key)" do before :each do @old_count = Order.count errors_for_import_with_row( :fullfillment_date => 2.days.ago, :quantity => 2 ).should == [] @first_od = OrderDetail.last errors_for_import_with_row( :fullfillment_date => 3.days.ago, :quantity => 3 ).should == [] end it "should merge orders when possible" do (Order.count - @old_count).should == 1 end it "should not have problem orders" do Order.last.order_details.each do |od| od.should_not be_problem_order end end it "should not change already attached details" do @after_od = OrderDetail.find(@first_od.id) @after_od.reload @after_od.should == @first_od end end describe "multiple calls (diff order_key)" do before :each do @old_count = Order.count errors_for_import_with_row( :fullfillment_date => 2.days.ago, :quantity => 2, :username => 'guest' ).should == [] @first_od = OrderDetail.last errors_for_import_with_row( :fullfillment_date => 3.days.ago, :quantity => 3, :username => 'guest2' ).should == [] end it "should not merge when users are different" do (Order.count - @old_count).should > 1 end it "should not have problem orders" do Order.last.order_details.each do |od| od.should_not be_problem_order end end it "should not change already attached details" do @after_od = OrderDetail.find(@first_od.id) @after_od.reload @after_od.should == @first_od end end end def generate_import_file(*args) args = [{}] if args.length == 0 # default to at least one valid row whole_csv = CSV.generate :headers => true do |csv| csv << CSV_HEADERS args.each do |opts| row = CSV::Row.new(CSV_HEADERS, [ opts[:username] || 'guest', opts[:account_number] || "111-2222222-33333333-01", opts[:product_name] || "Example Item", opts[:quantity] || 1, opts[:order_date] || DEFAULT_ORDER_DATE.strftime("%m/%d/%Y"), opts[:fullfillment_date] || DEFAULT_FULLFILLED_DATE.strftime("%m/%d/%Y") ]) csv << row end end return StringIO.new whole_csv end describe "high-level calls" do it "should send notifications (save clean orders mode)" do import_file = generate_import_file( {:order_date => DEFAULT_ORDER_DATE}, # valid rows {:order_date => DEFAULT_ORDER_DATE}, # diff order date (so will be diff order) { :order_date => DEFAULT_ORDER_DATE + 1.day, :product_name => "Invalid Item Name" } ) @order_import.send_receipts = true @order_import.fail_on_error = false @order_import.upload_file.file = import_file @order_import.upload_file.save! @order_import.save! # expectations Notifier.expects(:order_receipt).once.returns( stub({:deliver => nil }) ) # run the import @order_import.process! end it "should send notifications (save nothing on error mode)" do import_file = generate_import_file( {}, {} ) @order_import.send_receipts = true @order_import.fail_on_error = true @order_import.upload_file.file = import_file @order_import.upload_file.save! @order_import.save! # expectations Notifier.expects(:order_receipt).once.returns( stub({:deliver => nil }) ) # run the import @order_import.process! end end end add tests require 'spec_helper' require 'controller_spec_helper' require 'stringio' require 'csv_helper' include CSVHelper CSV_HEADERS = ["Netid / Email", "Chart String" , "Product Name" , "Quantity" , "Order Date" , "Fulfillment Date"] DEFAULT_ORDER_DATE = 4.days.ago.to_date DEFAULT_FULLFILLED_DATE = 3.days.ago.to_date def errors_for_import_with_row(opts={}) row = CSV::Row.new(CSV_HEADERS, [ opts[:username] || @guest.username, opts[:account_number] || "111-2222222-33333333-01", opts[:product_name] || "Example Item", opts[:quantity] || 1, opts[:order_date] || DEFAULT_ORDER_DATE.strftime("%m/%d/%Y"), opts[:fullfillment_date] || DEFAULT_FULLFILLED_DATE.strftime("%m/%d/%Y") ]) errs = @order_import.errors_for(row) end describe OrderImport do before(:all) { create_users } before :each do # clear Timecop's altering of time if active Timecop.return before_import = 10.days.ago Timecop.travel(before_import) do @authable = Factory.create(:facility) @facility_account = @authable.facility_accounts.create!(Factory.attributes_for(:facility_account)) grant_role(@director, @authable) @item = @authable.items.create!(Factory.attributes_for(:item, :facility_account_id => @facility_account.id, :name => "Example Item" )) # price stuff @price_group = @authable.price_groups.create!(Factory.attributes_for(:price_group)) @pg_member = Factory.create(:user_price_group_member, :user => @guest, :price_group => @price_group) @item_pp=@item.item_price_policies.create!(Factory.attributes_for(:item_price_policy, :price_group_id => @price_group.id, )) @guest2 = Factory.create :user, :username => 'guest2' @pg_member = Factory.create(:user_price_group_member, :user => @guest2, :price_group => @price_group) @account = Factory.create(:nufs_account, :description => "dummy account", :account_number => '111-2222222-33333333-01', :account_users_attributes => [ Hash[:user => @guest, :created_by => @guest, :user_role => 'Owner'], Hash[:user => @guest2, :created_by => @guest, :user_role => 'Purchaser'] ] ) end stored_file = StoredFile.create!( :file => StringIO.new("c,s,v"), :file_type => 'import_upload', :name => "clean_import.csv", :created_by => @director.id ) @order_import=OrderImport.create!( :created_by => @director.id, :upload_file => stored_file, :facility => @authable ) end # validation testing it { should belong_to :creator } it { should belong_to :upload_file } it { should belong_to :error_file } it { should validate_presence_of :upload_file_id } it { should validate_presence_of :created_by } describe "errors_for(row) (low-level) behavior" do describe "error detection" do it "shouldn't have errors for a valid row" do errors_for_import_with_row.should == [] end it "should have error when user isn't found" do errors_for_import_with_row(:username => "username_that_wont_be_there").first.should match /user/ end it "should have error when account isn't found" do errors_for_import_with_row(:account_number => "not_an_account_number").first.should match /find account/ end it "should have error when product isn't found" do errors_for_import_with_row(:product_name => "not_a_product_name").first.should match /find product/ end end describe "created order" do before :each do # run the import of row errors_for_import_with_row.should == [] @created_order = Order.last end it "should have ordered_at set appropriately" do @created_order.ordered_at.to_date.should == DEFAULT_ORDER_DATE end it "should have created_by_user set to creator of import" do @created_order.created_by_user.should == @director end it "should have user set to user in line of import" do @created_order.user.should == @guest end it { @created_order.should be_purchased } context "created order_details" do it "should exist" do assert @created_order.has_details? end it "should have the right product" do @created_order.order_details.first.product.should == @item end it "should have status complete" do @created_order.order_details.each do |od| od.state.should == "complete" end end it "should have price policies" do @created_order.order_details.each do |od| od.price_policy.should_not be nil end end it "should not be problem orders" do @created_order.order_details.each do |od| od.should_not be_problem_order end end it "should have right fullfilled_at" do @created_order.order_details.each do |od| od.fulfilled_at.to_date.should == DEFAULT_FULLFILLED_DATE end end end end describe "multiple calls (same order_key)" do before :each do @old_count = Order.count errors_for_import_with_row( :fullfillment_date => 2.days.ago, :quantity => 2 ).should == [] @first_od = OrderDetail.last errors_for_import_with_row( :fullfillment_date => 3.days.ago, :quantity => 3 ).should == [] end it "should merge orders when possible" do (Order.count - @old_count).should == 1 end it "should not have problem orders" do Order.last.order_details.each do |od| od.should_not be_problem_order end end it "should not change already attached details" do @after_od = OrderDetail.find(@first_od.id) @after_od.reload @after_od.should == @first_od end end describe "multiple calls (diff order_key)" do before :each do @old_count = Order.count errors_for_import_with_row( :fullfillment_date => 2.days.ago, :quantity => 2, :username => 'guest' ).should == [] @first_od = OrderDetail.last errors_for_import_with_row( :fullfillment_date => 3.days.ago, :quantity => 3, :username => 'guest2' ).should == [] end it "should not merge when users are different" do (Order.count - @old_count).should > 1 end it "should not have problem orders" do Order.last.order_details.each do |od| od.should_not be_problem_order end end it "should not change already attached details" do @after_od = OrderDetail.find(@first_od.id) @after_od.reload @after_od.should == @first_od end end end def generate_import_file(*args) args = [{}] if args.length == 0 # default to at least one valid row whole_csv = CSV.generate :headers => true do |csv| csv << CSV_HEADERS args.each do |opts| row = CSV::Row.new(CSV_HEADERS, [ opts[:username] || 'guest', opts[:account_number] || "111-2222222-33333333-01", opts[:product_name] || "Example Item", opts[:quantity] || 1, opts[:order_date] || DEFAULT_ORDER_DATE.strftime("%m/%d/%Y"), opts[:fullfillment_date] || DEFAULT_FULLFILLED_DATE.strftime("%m/%d/%Y") ]) csv << row end end return StringIO.new whole_csv end describe "high-level calls" do it "should send notifications (save clean orders mode)" do import_file = generate_import_file( {:order_date => DEFAULT_ORDER_DATE}, # valid rows {:order_date => DEFAULT_ORDER_DATE}, # diff order date (so will be diff order) { :order_date => DEFAULT_ORDER_DATE + 1.day, :product_name => "Invalid Item Name" } ) @order_import.send_receipts = true @order_import.fail_on_error = false @order_import.upload_file.file = import_file @order_import.upload_file.save! @order_import.save! # expectations Notifier.expects(:order_receipt).once.returns( stub({:deliver => nil }) ) # run the import @order_import.process! end it "should not send notifications if error occured (save nothing on error mode)" do import_file = generate_import_file( {}, {:product_name => "Invalid Item Name"} ) @order_import.send_receipts = true @order_import.fail_on_error = true @order_import.upload_file.file = import_file @order_import.upload_file.save! @order_import.save! # expectations Notifier.expects(:order_receipt).never # run the import @order_import.process! end it "should send notifications if no errors occured (save nothing on error mode)" do import_file = generate_import_file( {}, {:product_name => "Invalid Item Name"} ) @order_import.send_receipts = true @order_import.fail_on_error = true @order_import.upload_file.file = import_file @order_import.upload_file.save! @order_import.save! # expectations Notifier.expects(:order_receipt).once.returns( stub({:deliver => nil }) ) # run the import @order_import.process! end end end
require_relative '../spec_helper' require_relative '../../app/models/visualization/collection' require_relative '../../app/models/organization.rb' require_relative 'organization_shared_examples' require_relative '../factories/visualization_creation_helpers' require 'helpers/account_types_helper' require 'helpers/unique_names_helper' require 'helpers/storage_helper' require 'factories/organizations_contexts' include CartoDB, StorageHelper, UniqueNamesHelper describe 'refactored behaviour' do it_behaves_like 'organization models' do before(:each) do @the_organization = ::Organization.where(id: @organization.id).first end def get_twitter_imports_count_by_organization_id(organization_id) raise "id doesn't match" unless organization_id == @the_organization.id @the_organization.get_twitter_imports_count end def get_geocoding_calls_by_organization_id(organization_id) raise "id doesn't match" unless organization_id == @the_organization.id @the_organization.get_geocoding_calls end def get_organization @the_organization end end end describe Organization do before(:all) do @user = create_user(:quota_in_bytes => 524288000, :table_quota => 500) end after(:all) do bypass_named_maps begin @user.destroy rescue # Silence error, can't do much more end end before(:each) do create_account_type_fg('ORGANIZATION USER') end describe '#destroy_cascade' do include TableSharing before(:each) do @organization = FactoryGirl.create(:organization) ::User.any_instance.stubs(:create_in_central).returns(true) ::User.any_instance.stubs(:update_in_central).returns(true) end after(:each) do @organization.delete if @organization.try(:persisted?) end it 'Destroys users and owner as well' do organization = Organization.new(quota_in_bytes: 1234567890, name: 'wadus', seats: 5).save owner = create_user(:quota_in_bytes => 524288000, :table_quota => 500) owner_org = CartoDB::UserOrganization.new(organization.id, owner.id) owner_org.promote_user_to_admin owner.reload organization.reload user = create_user(quota_in_bytes: 524288000, table_quota: 500, organization_id: organization.id) user.save user.reload organization.reload organization.users.count.should eq 2 organization.destroy_cascade Organization.where(id: organization.id).first.should be nil ::User.where(id: user.id).first.should be nil ::User.where(id: owner.id).first.should be nil end it 'Destroys viewer users with shared visualizations' do organization = Organization.new(quota_in_bytes: 1234567890, name: 'wadus', seats: 2, viewer_seats: 2).save owner = create_user(quota_in_bytes: 524288000, table_quota: 500) owner_org = CartoDB::UserOrganization.new(organization.id, owner.id) owner_org.promote_user_to_admin user1 = create_user(organization_id: organization.id) user2 = create_user(organization_id: organization.id) table1 = create_table(user_id: user1.id) table2 = create_table(user_id: user2.id) share_table_with_user(table1, user2) share_table_with_user(table2, user1) user1.viewer = true user1.save user2.viewer = true user2.save organization.destroy_cascade Organization.where(id: organization.id).first.should be nil ::User.where(id: user1.id).first.should be nil ::User.where(id: user2.id).first.should be nil ::User.where(id: owner.id).first.should be nil Carto::UserTable.exists?(table1.id).should be_false Carto::UserTable.exists?(table2.id).should be_false end it 'destroys users with unregistered tables' do organization = Organization.new(quota_in_bytes: 1234567890, name: 'wadus', seats: 5).save owner = create_user(quota_in_bytes: 524288000, table_quota: 500) owner_org = CartoDB::UserOrganization.new(organization.id, owner.id) owner_org.promote_user_to_admin owner.reload organization.reload user = create_user(quota_in_bytes: 524288000, table_quota: 500, organization_id: organization.id) user.save user.reload organization.reload user.in_database.run('CREATE TABLE foobarbaz (id serial)') organization.users.count.should eq 2 organization.destroy_cascade Organization.where(id: organization.id).first.should be nil ::User.where(id: user.id).first.should be nil ::User.where(id: owner.id).first.should be nil end it 'destroys its groups through the extension' do Carto::Group.any_instance.expects(:destroy_group_with_extension).once FactoryGirl.create(:carto_group, organization: Carto::Organization.find(@organization.id)) @organization.destroy end it 'destroys assets' do bypass_storage asset = FactoryGirl.create(:organization_asset, organization_id: @organization.id) @organization.destroy Carto::Asset.exists?(asset.id).should be_false end it 'calls :delete_in_central if delete_in_central parameter is true' do pending "Don't implemented. See Organization#destroy_cascade" @organization.expects(:delete_in_central).once @organization.destroy_cascade(delete_in_central: true) end end describe '#add_user_to_org' do it 'Tests adding a user to an organization (but no owner)' do org_quota = 1234567890 org_name = unique_name('org') org_seats = 5 username = @user.username organization = Organization.new organization.name = org_name organization.quota_in_bytes = org_quota organization.seats = org_seats organization.save organization.valid?.should eq true organization.errors.should eq Hash.new @user.organization = organization @user.save user = ::User.where(username: username).first user.should_not be nil user.organization_id.should_not eq nil user.organization_id.should eq organization.id user.organization.should_not eq nil user.organization.id.should eq organization.id user.organization.name.should eq org_name user.organization.quota_in_bytes.should eq org_quota user.organization.seats.should eq org_seats @user.organization = nil @user.save organization.destroy end it 'validates viewer and builder quotas' do quota = 1234567890 name = unique_name('org') seats = 1 viewer_seats = 1 organization = Organization.new(name: name, quota_in_bytes: quota, seats: seats, viewer_seats: viewer_seats).save user = create_validated_user CartoDB::UserOrganization.new(organization.id, user.id).promote_user_to_admin organization.reload user.reload organization.remaining_seats.should eq 0 organization.remaining_viewer_seats.should eq 1 organization.users.should include(user) viewer = create_validated_user(organization: organization, viewer: true) viewer.valid? should be_true viewer.reload organization.reload organization.remaining_seats.should eq 0 organization.remaining_viewer_seats.should eq 0 organization.users.should include(viewer) builder = create_validated_user(organization: organization, viewer: false) organization.reload organization.remaining_seats.should eq 0 organization.remaining_viewer_seats.should eq 0 organization.users.should_not include(builder) viewer2 = create_validated_user(organization: organization, viewer: true) organization.reload organization.remaining_seats.should eq 0 organization.remaining_viewer_seats.should eq 0 organization.users.should_not include(viewer2) organization.seats = 0 organization.viewer_seats = 0 organization.valid?.should be_false organization.errors.should include :seats, :viewer_seats organization.destroy_cascade end it 'allows saving user if organization has no seats left' do organization = FactoryGirl.create(:organization, seats: 2, viewer_seats: 0, quota_in_bytes: 10) user = create_validated_user(quota_in_bytes: 1) CartoDB::UserOrganization.new(organization.id, user.id).promote_user_to_admin organization.reload user.reload builder = create_validated_user(organization: organization, viewer: false, quota_in_bytes: 2) builder.organization.reload builder.set_fields({ quota_in_bytes: 1 }, [:quota_in_bytes]) builder.save(raise_on_failure: true) builder.reload builder.quota_in_bytes.should eq 1 organization.destroy_cascade end it 'Tests setting a user as the organization owner' do org_name = unique_name('org') organization = Organization.new(quota_in_bytes: 1234567890, name: org_name, seats: 5).save user = create_user(:quota_in_bytes => 524288000, :table_quota => 500) user_org = CartoDB::UserOrganization.new(organization.id, user.id) # This also covers the usecase of an user being moved to its own schema (without org) user_org.promote_user_to_admin organization.reload user.reload user.organization.id.should eq organization.id user.organization.owner.id.should eq user.id user.database_schema.should eq user.username user_org = CartoDB::UserOrganization.new(organization.id, user.id) expect { user_org.promote_user_to_admin }.to raise_error user.destroy end end describe '#org_members_and_owner_removal' do it 'Tests removing a normal member from the organization' do ::User.any_instance.stubs(:create_in_central).returns(true) ::User.any_instance.stubs(:update_in_central).returns(true) org_name = unique_name('org') organization = Organization.new(quota_in_bytes: 1234567890, name: org_name, seats: 5).save owner = create_user(:quota_in_bytes => 524288000, :table_quota => 500) user_org = CartoDB::UserOrganization.new(organization.id, owner.id) user_org.promote_user_to_admin organization.reload owner.reload member1 = create_user(:quota_in_bytes => 524288000, :table_quota => 500, organization_id: organization.id) member1.reload organization.reload member2 = create_user(:quota_in_bytes => 524288000, :table_quota => 500, organization_id: organization.id) member2.reload organization.users.count.should eq 3 results = member1.in_database(as: :public_user).fetch(%Q{ SELECT has_function_privilege('#{member1.database_public_username}', 'CDB_QueryTablesText(text)', 'execute') }).first results.nil?.should eq false results[:has_function_privilege].should eq true member1.destroy organization.reload organization.users.count.should eq 2 results = member2.in_database(as: :public_user).fetch(%Q{ SELECT has_function_privilege('#{member2.database_public_username}', 'CDB_QueryTablesText(text)', 'execute') }).first results.nil?.should eq false results[:has_function_privilege].should eq true # Can't remove owner if other members exist expect { owner.destroy }.to raise_error CartoDB::BaseCartoDBError member2.destroy organization.reload organization.users.count.should eq 1 results = owner.in_database(as: :public_user).fetch(%Q{ SELECT has_function_privilege('#{owner.database_public_username}', 'CDB_QueryTablesText(text)', 'execute') }).first results.nil?.should eq false results[:has_function_privilege].should eq true owner.destroy expect { organization.reload }.to raise_error Sequel::Error end it 'Tests removing a normal member with analysis tables' do ::User.any_instance.stubs(:create_in_central).returns(true) ::User.any_instance.stubs(:update_in_central).returns(true) org_name = unique_name('org') organization = Organization.new(quota_in_bytes: 1234567890, name: org_name, seats: 5).save owner = create_test_user('orgowner') user_org = CartoDB::UserOrganization.new(organization.id, owner.id) user_org.promote_user_to_admin organization.reload owner.reload member1 = create_test_user('member1', organization) create_random_table(member1, 'analysis_user_table') create_random_table(member1, 'users_table') member1.in_database.run(%{CREATE TABLE #{member1.database_schema}.analysis_4bd65e58e4_246c4acb2c67e4f3330d76c4be7c6deb8e07f344 (id serial)}) member1.reload organization.reload organization.users.count.should eq 2 results = member1.in_database(as: :public_user).fetch(%{ SELECT has_function_privilege('#{member1.database_public_username}', 'CDB_QueryTablesText(text)', 'execute') }).first results.nil?.should eq false results[:has_function_privilege].should eq true member1.destroy organization.reload organization.users.count.should eq 1 end end describe '#non_org_user_removal' do it 'Tests removing a normal user' do initial_count = ::User.all.count user = create_user(:quota_in_bytes => 524288000, :table_quota => 50) ::User.all.count.should eq (initial_count + 1) user.destroy ::User.all.count.should eq initial_count ::User.all.collect(&:id).should_not include(user.id) end end describe '#users_in_same_db_removal_error' do it "Tests that if 2+ users somehow have same database name, can't be deleted" do user2 = create_user(:quota_in_bytes => 524288000, :table_quota => 50, :database_name => @user.database_name) user2.database_name = @user.database_name user2.save expect { user2.destroy }.to raise_error CartoDB::BaseCartoDBError end end describe '#unique_name' do it 'Tests uniqueness of name' do org_name = unique_name('org') organization = Organization.new organization.name = org_name organization.quota_in_bytes = 123 organization.seats = 1 organization.errors organization.valid?.should eq true # Repeated username organization.name = @user.username organization.valid?.should eq false organization.name = org_name organization.save organization2 = Organization.new # Repeated name organization2.name = org_name organization2.quota_in_bytes = 123 organization2.seats = 1 organization2.valid?.should eq false organization.destroy end end describe '#org_shared_vis' do it "checks fetching all shared visualizations of an organization's members " do bypass_named_maps # Don't check/handle DB permissions Permission.any_instance.stubs(:revoke_previous_permissions).returns(nil) Permission.any_instance.stubs(:grant_db_permission).returns(nil) vis_1_name = 'viz_1' vis_2_name = 'viz_2' vis_3_name = 'viz_3' user1 = create_user(:quota_in_bytes => 1234567890, :table_quota => 5) user2 = create_user(:quota_in_bytes => 1234567890, :table_quota => 5) user3 = create_user(:quota_in_bytes => 1234567890, :table_quota => 5) organization = Organization.new organization.name = 'qwerty' organization.seats = 5 organization.quota_in_bytes = 1234567890 organization.save.reload user1.organization_id = organization.id user1.save.reload organization.owner_id = user1.id organization.save.reload user2.organization_id = organization.id user2.save.reload user3.organization_id = organization.id user3.save.reload vis1 = Visualization::Member.new(random_attributes(name: vis_1_name, user_id: user1.id)).store vis2 = Visualization::Member.new(random_attributes(name: vis_2_name, user_id: user2.id)).store vis3 = Visualization::Member.new(random_attributes(name: vis_3_name, user_id: user3.id)).store perm = vis1.permission perm.acl = [ { type: Permission::TYPE_ORGANIZATION, entity: { id: organization.id, username: organization.name }, access: Permission::ACCESS_READONLY } ] perm.save perm = vis2.permission perm.acl = [ { type: Permission::TYPE_ORGANIZATION, entity: { id: organization.id, username: organization.name }, access: Permission::ACCESS_READONLY } ] perm.save perm = vis3.permission perm.acl = [ { type: Permission::TYPE_ORGANIZATION, entity: { id: organization.id, username: organization.name }, access: Permission::ACCESS_READONLY } ] perm.save # Setup done, now to the proper test org_vis_array = organization.public_visualizations.map { |vis| vis.id } # Order is newest to oldest org_vis_array.should eq [vis3.id, vis2.id, vis1.id] # Clear first shared entities to be able to destroy vis1.permission.acl = [] vis1.permission.save vis2.permission.acl = [] vis2.permission.save vis3.permission.acl = [] vis3.permission.save begin user3.destroy user2.destroy user1.destroy rescue # TODO: Finish deletion of organization users and remove this so users are properly deleted or test fails end end end describe "#get_api_calls and #get_geocodings" do before(:each) do @organization = create_organization_with_users(name: 'overquota-org') end after(:each) do @organization.destroy end it "should return the sum of the api_calls for all organization users" do ::User.any_instance.stubs(:get_api_calls).returns (0..30).to_a @organization.get_api_calls.should == (0..30).to_a.sum * @organization.users.size end end describe '.overquota', focus: true do before(:all) do @organization = create_organization_with_users(name: 'overquota-org') @owner = User.where(id: @organization.owner_id).first end after(:all) do @organization.destroy end it "should return organizations over their geocoding quota" do Organization.any_instance.stubs(:owner).returns(@owner) Organization.overquota.should be_empty Organization.any_instance.stubs(:get_api_calls).returns(0) Organization.any_instance.stubs(:map_view_quota).returns(10) Organization.any_instance.stubs(:get_geocoding_calls).returns 30 Organization.any_instance.stubs(:geocoding_quota).returns 10 Organization.overquota.map(&:id).should include(@organization.id) Organization.overquota.size.should == Organization.count end it "should return organizations over their here isolines quota" do Organization.any_instance.stubs(:owner).returns(@owner) Organization.overquota.should be_empty Organization.any_instance.stubs(:get_api_calls).returns(0) Organization.any_instance.stubs(:map_view_quota).returns(10) Organization.any_instance.stubs(:get_geocoding_calls).returns 0 Organization.any_instance.stubs(:geocoding_quota).returns 10 Organization.any_instance.stubs(:get_here_isolines_calls).returns 30 Organization.any_instance.stubs(:here_isolines_quota).returns 10 Organization.overquota.map(&:id).should include(@organization.id) Organization.overquota.size.should == Organization.count end it "should return organizations over their data observatory snapshot quota" do Organization.any_instance.stubs(:owner).returns(@owner) Organization.overquota.should be_empty Organization.any_instance.stubs(:get_api_calls).returns(0) Organization.any_instance.stubs(:map_view_quota).returns(10) Organization.any_instance.stubs(:get_geocoding_calls).returns 0 Organization.any_instance.stubs(:geocoding_quota).returns 10 Organization.any_instance.stubs(:get_obs_snapshot_calls).returns 30 Organization.any_instance.stubs(:obs_snapshot_quota).returns 10 Organization.overquota.map(&:id).should include(@organization.id) Organization.overquota.size.should == Organization.count end it "should return organizations over their data observatory general quota" do Organization.any_instance.stubs(:owner).returns(@owner) Organization.overquota.should be_empty Organization.any_instance.stubs(:get_api_calls).returns(0) Organization.any_instance.stubs(:map_view_quota).returns(10) Organization.any_instance.stubs(:get_geocoding_calls).returns 0 Organization.any_instance.stubs(:geocoding_quota).returns 10 Organization.any_instance.stubs(:get_obs_snapshot_calls).returns 0 Organization.any_instance.stubs(:obs_snapshot_quota).returns 10 Organization.any_instance.stubs(:get_obs_general_calls).returns 30 Organization.any_instance.stubs(:obs_general_quota).returns 10 Organization.overquota.map(&:id).should include(@organization.id) Organization.overquota.size.should == Organization.count end it "should return organizations near their geocoding quota" do Organization.any_instance.stubs(:owner).returns(@owner) Organization.any_instance.stubs(:get_api_calls).returns(0) Organization.any_instance.stubs(:map_view_quota).returns(120) Organization.any_instance.stubs(:get_geocoding_calls).returns(81) Organization.any_instance.stubs(:geocoding_quota).returns(100) Organization.overquota.should be_empty Organization.overquota(0.20).map(&:id).should include(@organization.id) Organization.overquota(0.20).size.should == Organization.count Organization.overquota(0.10).should be_empty end it "should return organizations near their here isolines quota" do Organization.any_instance.stubs(:owner).returns(@owner) Organization.any_instance.stubs(:get_api_calls).returns(0) Organization.any_instance.stubs(:map_view_quota).returns(120) Organization.any_instance.stubs(:get_geocoding_calls).returns(0) Organization.any_instance.stubs(:geocoding_quota).returns(100) Organization.any_instance.stubs(:get_here_isolines_calls).returns(81) Organization.any_instance.stubs(:here_isolines_quota).returns(100) Organization.any_instance.stubs(:get_obs_snapshot_calls).returns(0) Organization.any_instance.stubs(:obs_snapshot_quota).returns(100) Organization.any_instance.stubs(:get_obs_general_calls).returns(0) Organization.any_instance.stubs(:obs_general_quota).returns(100) Organization.any_instance.stubs(:get_mapzen_routing_calls).returns(81) Organization.any_instance.stubs(:mapzen_routing_quota).returns(100) Organization.overquota.should be_empty Organization.overquota(0.20).map(&:id).should include(@organization.id) Organization.overquota(0.20).size.should == Organization.count Organization.overquota(0.10).should be_empty end it "should return organizations near their data observatory snapshot quota" do Organization.any_instance.stubs(:owner).returns(@owner) Organization.any_instance.stubs(:get_api_calls).returns(0) Organization.any_instance.stubs(:map_view_quota).returns(120) Organization.any_instance.stubs(:get_geocoding_calls).returns(0) Organization.any_instance.stubs(:geocoding_quota).returns(100) Organization.any_instance.stubs(:get_here_isolines_calls).returns(0) Organization.any_instance.stubs(:here_isolines_quota).returns(100) Organization.any_instance.stubs(:get_obs_general_calls).returns(0) Organization.any_instance.stubs(:obs_general_quota).returns(100) Organization.any_instance.stubs(:get_obs_snapshot_calls).returns(81) Organization.any_instance.stubs(:obs_snapshot_quota).returns(100) Organization.any_instance.stubs(:get_mapzen_routing_calls).returns(0) Organization.any_instance.stubs(:mapzen_routing_quota).returns(100) Organization.overquota.should be_empty Organization.overquota(0.20).map(&:id).should include(@organization.id) Organization.overquota(0.20).size.should == Organization.count Organization.overquota(0.10).should be_empty end it "should return organizations near their data observatory general quota" do Organization.any_instance.stubs(:owner).returns(@owner) Organization.any_instance.stubs(:get_api_calls).returns(0) Organization.any_instance.stubs(:map_view_quota).returns(120) Organization.any_instance.stubs(:get_geocoding_calls).returns(0) Organization.any_instance.stubs(:geocoding_quota).returns(100) Organization.any_instance.stubs(:get_here_isolines_calls).returns(0) Organization.any_instance.stubs(:here_isolines_quota).returns(100) Organization.any_instance.stubs(:get_obs_snapshot_calls).returns(0) Organization.any_instance.stubs(:obs_snapshot_quota).returns(100) Organization.any_instance.stubs(:get_obs_general_calls).returns(81) Organization.any_instance.stubs(:obs_general_quota).returns(100) Organization.any_instance.stubs(:get_mapzen_routing_calls).returns(0) Organization.any_instance.stubs(:mapzen_routing_quota).returns(100) Organization.overquota.should be_empty Organization.overquota(0.20).map(&:id).should include(@organization.id) Organization.overquota(0.20).size.should == Organization.count Organization.overquota(0.10).should be_empty end it "should return organizations over their mapzen routing quota" do Organization.any_instance.stubs(:owner).returns(@owner) Organization.overquota.should be_empty Organization.any_instance.stubs(:get_api_calls).returns(0) Organization.any_instance.stubs(:map_view_quota).returns(10) Organization.any_instance.stubs(:get_geocoding_calls).returns 0 Organization.any_instance.stubs(:geocoding_quota).returns 10 Organization.any_instance.stubs(:get_here_isolines_calls).returns(0) Organization.any_instance.stubs(:here_isolines_quota).returns(100) Organization.any_instance.stubs(:get_mapzen_routing_calls).returns 30 Organization.any_instance.stubs(:mapzen_routing_quota).returns 10 Organization.overquota.map(&:id).should include(@organization.id) Organization.overquota.size.should == Organization.count end end it 'should validate password_expiration_in_d' do organization = FactoryGirl.create(:organization) organization.valid?.should be_true organization.password_expiration_in_d.should_not be # minimum 1 day organization = FactoryGirl.create(:organization, password_expiration_in_d: 1) organization.valid?.should be_true organization.password_expiration_in_d.should eq 1 expect { organization = FactoryGirl.create(:organization, password_expiration_in_d: 0) }.to raise_error(Sequel::ValidationFailed, /password_expiration_in_d must be greater than 0 and lower than 366/) # maximum 1 year organization = FactoryGirl.create(:organization, password_expiration_in_d: 365) organization.valid?.should be_true organization.password_expiration_in_d.should eq 365 expect { organization = FactoryGirl.create(:organization, password_expiration_in_d: 366) }.to raise_error(Sequel::ValidationFailed, /password_expiration_in_d must be greater than 0 and lower than 366/) # nil or blank means unlimited organization = FactoryGirl.create(:organization, password_expiration_in_d: nil) organization.valid?.should be_true organization.password_expiration_in_d.should_not be organization = FactoryGirl.create(:organization, password_expiration_in_d: '') organization.valid?.should be_true organization.password_expiration_in_d.should_not be Cartodb.with_config(passwords: { 'expiration_in_d' => 1 }) do # defaults to global config if no value organization = FactoryGirl.build(:organization) organization.valid?.should be_true organization.save organization.password_expiration_in_d.should eq 1 organization = Carto::Organization.find(organization.id) organization.valid?.should be_true organization.password_expiration_in_d.should eq 1 organization.password_expiration_in_d = nil organization.valid?.should be_true organization.save organization = Carto::Organization.find(organization.id) organization.password_expiration_in_d.should_not be # override default config if a value is set organization = FactoryGirl.create(:organization, password_expiration_in_d: 10) organization.valid?.should be_true organization.password_expiration_in_d.should eq 10 # keep values configured organization = Carto::Organization.find(organization.id) organization.valid?.should be_true organization.password_expiration_in_d.should eq 10 end end def random_attributes(attributes = {}) random = unique_name('viz') { name: attributes.fetch(:name, random), description: attributes.fetch(:description, "description #{random}"), privacy: attributes.fetch(:privacy, Visualization::Member::PRIVACY_PUBLIC), tags: attributes.fetch(:tags, ['tag 1']), type: attributes.fetch(:type, Visualization::Member::TYPE_DERIVED), user_id: attributes.fetch(:user_id, UUIDTools::UUID.timestamp_create.to_s) } end # random_attributes end Fix corresponding test require_relative '../spec_helper' require_relative '../../app/models/visualization/collection' require_relative '../../app/models/organization.rb' require_relative 'organization_shared_examples' require_relative '../factories/visualization_creation_helpers' require 'helpers/account_types_helper' require 'helpers/unique_names_helper' require 'helpers/storage_helper' require 'factories/organizations_contexts' include CartoDB, StorageHelper, UniqueNamesHelper describe 'refactored behaviour' do it_behaves_like 'organization models' do before(:each) do @the_organization = ::Organization.where(id: @organization.id).first end def get_twitter_imports_count_by_organization_id(organization_id) raise "id doesn't match" unless organization_id == @the_organization.id @the_organization.get_twitter_imports_count end def get_geocoding_calls_by_organization_id(organization_id) raise "id doesn't match" unless organization_id == @the_organization.id @the_organization.get_geocoding_calls end def get_organization @the_organization end end end describe Organization do before(:all) do @user = create_user(:quota_in_bytes => 524288000, :table_quota => 500) end after(:all) do bypass_named_maps begin @user.destroy rescue # Silence error, can't do much more end end before(:each) do create_account_type_fg('ORGANIZATION USER') end describe '#destroy_cascade' do include TableSharing before(:each) do @organization = FactoryGirl.create(:organization) ::User.any_instance.stubs(:create_in_central).returns(true) ::User.any_instance.stubs(:update_in_central).returns(true) end after(:each) do @organization.delete if @organization.try(:persisted?) end it 'Destroys users and owner as well' do organization = Organization.new(quota_in_bytes: 1234567890, name: 'wadus', seats: 5).save owner = create_user(:quota_in_bytes => 524288000, :table_quota => 500) owner_org = CartoDB::UserOrganization.new(organization.id, owner.id) owner_org.promote_user_to_admin owner.reload organization.reload user = create_user(quota_in_bytes: 524288000, table_quota: 500, organization_id: organization.id) user.save user.reload organization.reload organization.users.count.should eq 2 organization.destroy_cascade Organization.where(id: organization.id).first.should be nil ::User.where(id: user.id).first.should be nil ::User.where(id: owner.id).first.should be nil end it 'Destroys viewer users with shared visualizations' do organization = Organization.new(quota_in_bytes: 1234567890, name: 'wadus', seats: 2, viewer_seats: 2).save owner = create_user(quota_in_bytes: 524288000, table_quota: 500) owner_org = CartoDB::UserOrganization.new(organization.id, owner.id) owner_org.promote_user_to_admin user1 = create_user(organization_id: organization.id) user2 = create_user(organization_id: organization.id) table1 = create_table(user_id: user1.id) table2 = create_table(user_id: user2.id) share_table_with_user(table1, user2) share_table_with_user(table2, user1) user1.viewer = true user1.save user2.viewer = true user2.save organization.destroy_cascade Organization.where(id: organization.id).first.should be nil ::User.where(id: user1.id).first.should be nil ::User.where(id: user2.id).first.should be nil ::User.where(id: owner.id).first.should be nil Carto::UserTable.exists?(table1.id).should be_false Carto::UserTable.exists?(table2.id).should be_false end it 'destroys users with unregistered tables' do organization = Organization.new(quota_in_bytes: 1234567890, name: 'wadus', seats: 5).save owner = create_user(quota_in_bytes: 524288000, table_quota: 500) owner_org = CartoDB::UserOrganization.new(organization.id, owner.id) owner_org.promote_user_to_admin owner.reload organization.reload user = create_user(quota_in_bytes: 524288000, table_quota: 500, organization_id: organization.id) user.save user.reload organization.reload user.in_database.run('CREATE TABLE foobarbaz (id serial)') organization.users.count.should eq 2 organization.destroy_cascade Organization.where(id: organization.id).first.should be nil ::User.where(id: user.id).first.should be nil ::User.where(id: owner.id).first.should be nil end it 'destroys its groups through the extension' do Carto::Group.any_instance.expects(:destroy_group_with_extension).once FactoryGirl.create(:carto_group, organization: Carto::Organization.find(@organization.id)) @organization.destroy end it 'destroys assets' do bypass_storage asset = FactoryGirl.create(:organization_asset, organization_id: @organization.id) @organization.destroy Carto::Asset.exists?(asset.id).should be_false end it 'calls :delete_in_central if delete_in_central parameter is true' do pending "Don't implemented. See Organization#destroy_cascade" @organization.expects(:delete_in_central).once @organization.destroy_cascade(delete_in_central: true) end end describe '#add_user_to_org' do it 'Tests adding a user to an organization (but no owner)' do org_quota = 1234567890 org_name = unique_name('org') org_seats = 5 username = @user.username organization = Organization.new organization.name = org_name organization.quota_in_bytes = org_quota organization.seats = org_seats organization.save organization.valid?.should eq true organization.errors.should eq Hash.new @user.organization = organization @user.save user = ::User.where(username: username).first user.should_not be nil user.organization_id.should_not eq nil user.organization_id.should eq organization.id user.organization.should_not eq nil user.organization.id.should eq organization.id user.organization.name.should eq org_name user.organization.quota_in_bytes.should eq org_quota user.organization.seats.should eq org_seats @user.organization = nil @user.save organization.destroy end it 'validates viewer and builder quotas' do quota = 1234567890 name = unique_name('org') seats = 1 viewer_seats = 1 organization = Organization.new(name: name, quota_in_bytes: quota, seats: seats, viewer_seats: viewer_seats).save user = create_validated_user CartoDB::UserOrganization.new(organization.id, user.id).promote_user_to_admin organization.reload user.reload organization.remaining_seats.should eq 0 organization.remaining_viewer_seats.should eq 1 organization.users.should include(user) viewer = create_validated_user(organization: organization, viewer: true) viewer.valid? should be_true viewer.reload organization.reload organization.remaining_seats.should eq 0 organization.remaining_viewer_seats.should eq 0 organization.users.should include(viewer) builder = create_validated_user(organization: organization, viewer: false) organization.reload organization.remaining_seats.should eq 0 organization.remaining_viewer_seats.should eq 0 organization.users.should_not include(builder) viewer2 = create_validated_user(organization: organization, viewer: true) organization.reload organization.remaining_seats.should eq 0 organization.remaining_viewer_seats.should eq 0 organization.users.should_not include(viewer2) organization.seats = 0 organization.viewer_seats = 0 organization.valid?.should be_false organization.errors.should include :seats, :viewer_seats organization.destroy_cascade end it 'allows saving user if organization has no seats left' do organization = FactoryGirl.create(:organization, seats: 2, viewer_seats: 0, quota_in_bytes: 10) user = create_validated_user(quota_in_bytes: 1) CartoDB::UserOrganization.new(organization.id, user.id).promote_user_to_admin organization.reload user.reload builder = create_validated_user(organization: organization, viewer: false, quota_in_bytes: 2) builder.organization.reload builder.set_fields({ quota_in_bytes: 1 }, [:quota_in_bytes]) builder.save(raise_on_failure: true) builder.reload builder.quota_in_bytes.should eq 1 organization.destroy_cascade end it 'Tests setting a user as the organization owner' do org_name = unique_name('org') organization = Organization.new(quota_in_bytes: 1234567890, name: org_name, seats: 5).save user = create_user(:quota_in_bytes => 524288000, :table_quota => 500) user_org = CartoDB::UserOrganization.new(organization.id, user.id) # This also covers the usecase of an user being moved to its own schema (without org) user_org.promote_user_to_admin organization.reload user.reload user.organization.id.should eq organization.id user.organization.owner.id.should eq user.id user.database_schema.should eq user.username user_org = CartoDB::UserOrganization.new(organization.id, user.id) expect { user_org.promote_user_to_admin }.to raise_error user.destroy end end describe '#org_members_and_owner_removal' do it 'Tests removing a normal member from the organization' do ::User.any_instance.stubs(:create_in_central).returns(true) ::User.any_instance.stubs(:update_in_central).returns(true) org_name = unique_name('org') organization = Organization.new(quota_in_bytes: 1234567890, name: org_name, seats: 5).save owner = create_user(:quota_in_bytes => 524288000, :table_quota => 500) user_org = CartoDB::UserOrganization.new(organization.id, owner.id) user_org.promote_user_to_admin organization.reload owner.reload member1 = create_user(:quota_in_bytes => 524288000, :table_quota => 500, organization_id: organization.id) member1.reload organization.reload member2 = create_user(:quota_in_bytes => 524288000, :table_quota => 500, organization_id: organization.id) member2.reload organization.users.count.should eq 3 results = member1.in_database(as: :public_user).fetch(%Q{ SELECT has_function_privilege('#{member1.database_public_username}', 'CDB_QueryTablesText(text)', 'execute') }).first results.nil?.should eq false results[:has_function_privilege].should eq true member1.destroy organization.reload organization.users.count.should eq 2 results = member2.in_database(as: :public_user).fetch(%Q{ SELECT has_function_privilege('#{member2.database_public_username}', 'CDB_QueryTablesText(text)', 'execute') }).first results.nil?.should eq false results[:has_function_privilege].should eq true # Can't remove owner if other members exist expect { owner.destroy }.to raise_error CartoDB::BaseCartoDBError member2.destroy organization.reload organization.users.count.should eq 1 results = owner.in_database(as: :public_user).fetch(%Q{ SELECT has_function_privilege('#{owner.database_public_username}', 'CDB_QueryTablesText(text)', 'execute') }).first results.nil?.should eq false results[:has_function_privilege].should eq true owner.destroy expect { organization.reload }.to raise_error Sequel::Error end it 'Tests removing a normal member with analysis tables' do ::User.any_instance.stubs(:create_in_central).returns(true) ::User.any_instance.stubs(:update_in_central).returns(true) org_name = unique_name('org') organization = Organization.new(quota_in_bytes: 1234567890, name: org_name, seats: 5).save owner = create_test_user('orgowner') user_org = CartoDB::UserOrganization.new(organization.id, owner.id) user_org.promote_user_to_admin organization.reload owner.reload member1 = create_test_user('member1', organization) create_random_table(member1, 'analysis_user_table') create_random_table(member1, 'users_table') member1.in_database.run(%{CREATE TABLE #{member1.database_schema}.analysis_4bd65e58e4_246c4acb2c67e4f3330d76c4be7c6deb8e07f344 (id serial)}) member1.reload organization.reload organization.users.count.should eq 2 results = member1.in_database(as: :public_user).fetch(%{ SELECT has_function_privilege('#{member1.database_public_username}', 'CDB_QueryTablesText(text)', 'execute') }).first results.nil?.should eq false results[:has_function_privilege].should eq true member1.destroy organization.reload organization.users.count.should eq 1 end end describe '#non_org_user_removal' do it 'Tests removing a normal user' do initial_count = ::User.all.count user = create_user(:quota_in_bytes => 524288000, :table_quota => 50) ::User.all.count.should eq (initial_count + 1) user.destroy ::User.all.count.should eq initial_count ::User.all.collect(&:id).should_not include(user.id) end end describe '#users_in_same_db_removal_error' do it "Tests that if 2+ users somehow have same database name, can't be deleted" do user2 = create_user(:quota_in_bytes => 524288000, :table_quota => 50, :database_name => @user.database_name) user2.database_name = @user.database_name user2.save expect { user2.destroy }.to raise_error CartoDB::BaseCartoDBError end end describe '#unique_name' do it 'Tests uniqueness of name' do org_name = unique_name('org') organization = Organization.new organization.name = org_name organization.quota_in_bytes = 123 organization.seats = 1 organization.errors organization.valid?.should eq true # Repeated username organization.name = @user.username organization.valid?.should eq false organization.name = org_name organization.save organization2 = Organization.new # Repeated name organization2.name = org_name organization2.quota_in_bytes = 123 organization2.seats = 1 organization2.valid?.should eq false organization.destroy end end describe '#org_shared_vis' do it "checks fetching all shared visualizations of an organization's members " do bypass_named_maps # Don't check/handle DB permissions Permission.any_instance.stubs(:revoke_previous_permissions).returns(nil) Permission.any_instance.stubs(:grant_db_permission).returns(nil) vis_1_name = 'viz_1' vis_2_name = 'viz_2' vis_3_name = 'viz_3' user1 = create_user(:quota_in_bytes => 1234567890, :table_quota => 5) user2 = create_user(:quota_in_bytes => 1234567890, :table_quota => 5) user3 = create_user(:quota_in_bytes => 1234567890, :table_quota => 5) organization = Organization.new organization.name = 'qwerty' organization.seats = 5 organization.quota_in_bytes = 1234567890 organization.save.reload user1.organization_id = organization.id user1.save.reload organization.owner_id = user1.id organization.save.reload user2.organization_id = organization.id user2.save.reload user3.organization_id = organization.id user3.save.reload vis1 = Visualization::Member.new(random_attributes(name: vis_1_name, user_id: user1.id)).store vis2 = Visualization::Member.new(random_attributes(name: vis_2_name, user_id: user2.id)).store vis3 = Visualization::Member.new(random_attributes(name: vis_3_name, user_id: user3.id)).store perm = vis1.permission perm.acl = [ { type: Permission::TYPE_ORGANIZATION, entity: { id: organization.id, username: organization.name }, access: Permission::ACCESS_READONLY } ] perm.save perm = vis2.permission perm.acl = [ { type: Permission::TYPE_ORGANIZATION, entity: { id: organization.id, username: organization.name }, access: Permission::ACCESS_READONLY } ] perm.save perm = vis3.permission perm.acl = [ { type: Permission::TYPE_ORGANIZATION, entity: { id: organization.id, username: organization.name }, access: Permission::ACCESS_READONLY } ] perm.save # Setup done, now to the proper test org_vis_array = organization.public_visualizations.map { |vis| vis.id } # Order is newest to oldest org_vis_array.should eq [vis3.id, vis2.id, vis1.id] # Clear first shared entities to be able to destroy vis1.permission.acl = [] vis1.permission.save vis2.permission.acl = [] vis2.permission.save vis3.permission.acl = [] vis3.permission.save begin user3.destroy user2.destroy user1.destroy rescue # TODO: Finish deletion of organization users and remove this so users are properly deleted or test fails end end end describe "#get_api_calls and #get_geocodings" do before(:each) do @organization = create_organization_with_users(name: 'overquota-org') end after(:each) do @organization.destroy end it "should return the sum of the api_calls for all organization users" do ::User.any_instance.stubs(:get_api_calls).returns (0..30).to_a @organization.get_api_calls.should == (0..30).to_a.sum * @organization.users.size end end describe '.overquota', focus: true do before(:all) do @organization = create_organization_with_users(name: 'overquota-org') @owner = User.where(id: @organization.owner_id).first end after(:all) do @organization.destroy end it "should return organizations over their geocoding quota" do Organization.any_instance.stubs(:owner).returns(@owner) Organization.overquota.should be_empty Organization.any_instance.stubs(:get_api_calls).returns(0) Organization.any_instance.stubs(:map_view_quota).returns(10) Organization.any_instance.stubs(:get_geocoding_calls).returns 30 Organization.any_instance.stubs(:geocoding_quota).returns 10 Organization.overquota.map(&:id).should include(@organization.id) Organization.overquota.size.should == Organization.count end it "should return organizations over their here isolines quota" do Organization.any_instance.stubs(:owner).returns(@owner) Organization.overquota.should be_empty Organization.any_instance.stubs(:get_api_calls).returns(0) Organization.any_instance.stubs(:map_view_quota).returns(10) Organization.any_instance.stubs(:get_geocoding_calls).returns 0 Organization.any_instance.stubs(:geocoding_quota).returns 10 Organization.any_instance.stubs(:get_here_isolines_calls).returns 30 Organization.any_instance.stubs(:here_isolines_quota).returns 10 Organization.overquota.map(&:id).should include(@organization.id) Organization.overquota.size.should == Organization.count end it "should return organizations over their data observatory snapshot quota" do Organization.any_instance.stubs(:owner).returns(@owner) Organization.overquota.should be_empty Organization.any_instance.stubs(:get_api_calls).returns(0) Organization.any_instance.stubs(:map_view_quota).returns(10) Organization.any_instance.stubs(:get_geocoding_calls).returns 0 Organization.any_instance.stubs(:geocoding_quota).returns 10 Organization.any_instance.stubs(:get_obs_snapshot_calls).returns 30 Organization.any_instance.stubs(:obs_snapshot_quota).returns 10 Organization.overquota.map(&:id).should include(@organization.id) Organization.overquota.size.should == Organization.count end it "should return organizations over their data observatory general quota" do Organization.any_instance.stubs(:owner).returns(@owner) Organization.overquota.should be_empty Organization.any_instance.stubs(:get_api_calls).returns(0) Organization.any_instance.stubs(:map_view_quota).returns(10) Organization.any_instance.stubs(:get_geocoding_calls).returns 0 Organization.any_instance.stubs(:geocoding_quota).returns 10 Organization.any_instance.stubs(:get_obs_snapshot_calls).returns 0 Organization.any_instance.stubs(:obs_snapshot_quota).returns 10 Organization.any_instance.stubs(:get_obs_general_calls).returns 30 Organization.any_instance.stubs(:obs_general_quota).returns 10 Organization.overquota.map(&:id).should include(@organization.id) Organization.overquota.size.should == Organization.count end it "should return organizations near their geocoding quota" do Organization.any_instance.stubs(:owner).returns(@owner) Organization.any_instance.stubs(:get_api_calls).returns(0) Organization.any_instance.stubs(:map_view_quota).returns(120) Organization.any_instance.stubs(:get_geocoding_calls).returns(81) Organization.any_instance.stubs(:geocoding_quota).returns(100) Organization.overquota.should be_empty Organization.overquota(0.20).map(&:id).should include(@organization.id) Organization.overquota(0.20).size.should == Organization.count Organization.overquota(0.10).should be_empty end it "should return organizations near their here isolines quota" do Organization.any_instance.stubs(:owner).returns(@owner) Organization.any_instance.stubs(:get_api_calls).returns(0) Organization.any_instance.stubs(:map_view_quota).returns(120) Organization.any_instance.stubs(:get_geocoding_calls).returns(0) Organization.any_instance.stubs(:geocoding_quota).returns(100) Organization.any_instance.stubs(:get_here_isolines_calls).returns(81) Organization.any_instance.stubs(:here_isolines_quota).returns(100) Organization.any_instance.stubs(:get_obs_snapshot_calls).returns(0) Organization.any_instance.stubs(:obs_snapshot_quota).returns(100) Organization.any_instance.stubs(:get_obs_general_calls).returns(0) Organization.any_instance.stubs(:obs_general_quota).returns(100) Organization.any_instance.stubs(:get_mapzen_routing_calls).returns(81) Organization.any_instance.stubs(:mapzen_routing_quota).returns(100) Organization.overquota.should be_empty Organization.overquota(0.20).map(&:id).should include(@organization.id) Organization.overquota(0.20).size.should == Organization.count Organization.overquota(0.10).should be_empty end it "should return organizations near their data observatory snapshot quota" do Organization.any_instance.stubs(:owner).returns(@owner) Organization.any_instance.stubs(:get_api_calls).returns(0) Organization.any_instance.stubs(:map_view_quota).returns(120) Organization.any_instance.stubs(:get_geocoding_calls).returns(0) Organization.any_instance.stubs(:geocoding_quota).returns(100) Organization.any_instance.stubs(:get_here_isolines_calls).returns(0) Organization.any_instance.stubs(:here_isolines_quota).returns(100) Organization.any_instance.stubs(:get_obs_general_calls).returns(0) Organization.any_instance.stubs(:obs_general_quota).returns(100) Organization.any_instance.stubs(:get_obs_snapshot_calls).returns(81) Organization.any_instance.stubs(:obs_snapshot_quota).returns(100) Organization.any_instance.stubs(:get_mapzen_routing_calls).returns(0) Organization.any_instance.stubs(:mapzen_routing_quota).returns(100) Organization.overquota.should be_empty Organization.overquota(0.20).map(&:id).should include(@organization.id) Organization.overquota(0.20).size.should == Organization.count Organization.overquota(0.10).should be_empty end it "should return organizations near their data observatory general quota" do Organization.any_instance.stubs(:owner).returns(@owner) Organization.any_instance.stubs(:get_api_calls).returns(0) Organization.any_instance.stubs(:map_view_quota).returns(120) Organization.any_instance.stubs(:get_geocoding_calls).returns(0) Organization.any_instance.stubs(:geocoding_quota).returns(100) Organization.any_instance.stubs(:get_here_isolines_calls).returns(0) Organization.any_instance.stubs(:here_isolines_quota).returns(100) Organization.any_instance.stubs(:get_obs_snapshot_calls).returns(0) Organization.any_instance.stubs(:obs_snapshot_quota).returns(100) Organization.any_instance.stubs(:get_obs_general_calls).returns(81) Organization.any_instance.stubs(:obs_general_quota).returns(100) Organization.any_instance.stubs(:get_mapzen_routing_calls).returns(0) Organization.any_instance.stubs(:mapzen_routing_quota).returns(100) Organization.overquota.should be_empty Organization.overquota(0.20).map(&:id).should include(@organization.id) Organization.overquota(0.20).size.should == Organization.count Organization.overquota(0.10).should be_empty end it "should return organizations over their mapzen routing quota" do Organization.any_instance.stubs(:owner).returns(@owner) Organization.overquota.should be_empty Organization.any_instance.stubs(:get_api_calls).returns(0) Organization.any_instance.stubs(:map_view_quota).returns(10) Organization.any_instance.stubs(:get_geocoding_calls).returns 0 Organization.any_instance.stubs(:geocoding_quota).returns 10 Organization.any_instance.stubs(:get_here_isolines_calls).returns(0) Organization.any_instance.stubs(:here_isolines_quota).returns(100) Organization.any_instance.stubs(:get_mapzen_routing_calls).returns 30 Organization.any_instance.stubs(:mapzen_routing_quota).returns 10 Organization.overquota.map(&:id).should include(@organization.id) Organization.overquota.size.should == Organization.count end end it 'should validate password_expiration_in_d' do organization = FactoryGirl.create(:organization) organization.valid?.should be_true organization.password_expiration_in_d.should_not be # minimum 1 day organization = FactoryGirl.create(:organization, password_expiration_in_d: 1) organization.valid?.should be_true organization.password_expiration_in_d.should eq 1 expect { organization = FactoryGirl.create(:organization, password_expiration_in_d: 0) }.to raise_error(Sequel::ValidationFailed, /password_expiration_in_d must be greater than 0 and lower than 366/) # maximum 1 year organization = FactoryGirl.create(:organization, password_expiration_in_d: 365) organization.valid?.should be_true organization.password_expiration_in_d.should eq 365 expect { organization = FactoryGirl.create(:organization, password_expiration_in_d: 366) }.to raise_error(Sequel::ValidationFailed, /password_expiration_in_d must be greater than 0 and lower than 366/) # nil or blank means unlimited organization = FactoryGirl.create(:organization, password_expiration_in_d: nil) organization.valid?.should be_true organization.password_expiration_in_d.should_not be organization = FactoryGirl.create(:organization, password_expiration_in_d: '') organization.valid?.should be_true organization.password_expiration_in_d.should_not be # defaults to global config if no value organization = FactoryGirl.build(:organization, password_expiration_in_d: 1) organization.valid?.should be_true organization.save organization = Carto::Organization.find(organization.id) organization.valid?.should be_true organization.password_expiration_in_d.should eq 1 organization.password_expiration_in_d = nil organization.valid?.should be_true organization.save organization = Carto::Organization.find(organization.id) organization.password_expiration_in_d.should_not be # override default config if a value is set organization = FactoryGirl.create(:organization, password_expiration_in_d: 10) organization.valid?.should be_true organization.password_expiration_in_d.should eq 10 # keep values configured organization = Carto::Organization.find(organization.id) organization.valid?.should be_true organization.password_expiration_in_d.should eq 10 end def random_attributes(attributes = {}) random = unique_name('viz') { name: attributes.fetch(:name, random), description: attributes.fetch(:description, "description #{random}"), privacy: attributes.fetch(:privacy, Visualization::Member::PRIVACY_PUBLIC), tags: attributes.fetch(:tags, ['tag 1']), type: attributes.fetch(:type, Visualization::Member::TYPE_DERIVED), user_id: attributes.fetch(:user_id, UUIDTools::UUID.timestamp_create.to_s) } end # random_attributes end
require 'rails_helper' RSpec.describe VoteCounter do before :each do @voter1 = create :user, contributor: true @voter2 = create :user, contributor: true end it "should only count latest vote per person" do pr = create :proposal comments = [ OpenStruct.new( body: ":-1:", created_at: 2.hours.ago, user: OpenStruct.new( login: @voter1.login ) ), OpenStruct.new( body: ":+1:", created_at: 1.hour.ago, user: OpenStruct.new( login: @voter1.login ) ) ] expect(pr).to receive(:time_of_last_commit).and_return(1.day.ago).at_least(:once) pr.send(:count_votes_in_comments, comments) expect(pr.score).to eq 1 expect(pr.yes.first.user).to eq @voter1 end [":+1:", ":thumbsup:", "πŸ‘", ":white_check_mark:", "βœ…"].each do |symbol| it "should treat #{symbol} as a yes vote" do pr = create :proposal comments = [ OpenStruct.new( body: "here is a vote! #{symbol}", created_at: 2.hours.ago, user: OpenStruct.new( login: @voter1.login ) ) ] expect(pr).to receive(:time_of_last_commit).and_return(1.day.ago) pr.send(:count_votes_in_comments, comments) expect(pr.score).to eq 1 end end it "should ignore votes from proposer" do pr = create :proposal comments = [ OpenStruct.new( body: ":+1:", created_at: 2.hours.ago, user: OpenStruct.new( login: pr.proposer.login ) ) ] expect(pr).to receive(:time_of_last_commit).and_return(1.day.ago) pr.send(:count_votes_in_comments, comments) expect(pr.score).to eq 0 end it "should ignore votes before last commit" do pr = create :proposal comments = [ OpenStruct.new( body: ":+1:", created_at: 2.hours.ago, user: OpenStruct.new( login: pr.proposer.login ) ) ] expect(pr).to receive(:time_of_last_commit).and_return(1.hour.ago) pr.send(:count_votes_in_comments, comments) expect(pr.score).to eq 0 end end test all vote symbols and longcodes require 'rails_helper' RSpec.describe VoteCounter do before :each do @voter1 = create :user, contributor: true @voter2 = create :user, contributor: true end it "should only count latest vote per person" do pr = create :proposal comments = [ OpenStruct.new( body: "βœ…", created_at: 2.hours.ago, user: OpenStruct.new( login: @voter1.login ) ), OpenStruct.new( body: "βœ…", created_at: 1.hour.ago, user: OpenStruct.new( login: @voter1.login ) ) ] expect(pr).to receive(:time_of_last_commit).and_return(1.day.ago).at_least(:once) pr.send(:count_votes_in_comments, comments) expect(pr.score).to eq 1 expect(pr.yes.first.user).to eq @voter1 end context "casting votes in comments" do [ { vote: "yes", symbols: [":+1:", ":thumbsup:", "πŸ‘", ":white_check_mark:", "βœ…"], score: 1 }, { vote: "no", symbols: [":hand:", "βœ‹", ":negative_squared_cross_mark:", "❎"], score: -1 }, { vote: "block", symbols: [":-1:", ":thumbsdown:", "πŸ‘Ž", ":no_entry_sign:", "🚫"], score: -1000 }, ].each do |set| set[:symbols].each do |symbol| it "should treat #{symbol} as a #{set[:vote]} vote" do pr = create :proposal comments = [ OpenStruct.new( body: "here is a vote! #{symbol}", created_at: 2.hours.ago, user: OpenStruct.new( login: @voter1.login ) ) ] expect(pr).to receive(:time_of_last_commit).and_return(1.day.ago) pr.send(:count_votes_in_comments, comments) expect(pr.score).to eq set[:score] end end end end it "should ignore votes from proposer" do pr = create :proposal comments = [ OpenStruct.new( body: "βœ…", created_at: 2.hours.ago, user: OpenStruct.new( login: pr.proposer.login ) ) ] expect(pr).to receive(:time_of_last_commit).and_return(1.day.ago) pr.send(:count_votes_in_comments, comments) expect(pr.score).to eq 0 end it "should ignore votes before last commit" do pr = create :proposal comments = [ OpenStruct.new( body: "βœ…", created_at: 2.hours.ago, user: OpenStruct.new( login: pr.proposer.login ) ) ] expect(pr).to receive(:time_of_last_commit).and_return(1.hour.ago) pr.send(:count_votes_in_comments, comments) expect(pr.score).to eq 0 end end
require 'spec_helper' class User include Mongoid::Document include Mongoid::Document::Taggable field :name belongs_to :organization end class Organization include Mongoid::Document field :name has_many :users end describe "A Taggable model" do let(:user) { User.new(name: 'Tuquito') } it "should have a tag_list method" do user.should respond_to(:tag_list) end it "should have a tag_list class method" do User.should respond_to(:tag_list) end it "should be able to update a tag list" do tag_list = "linux, tucuman, free software" tags = tag_list.split(',').map{ |tag| tag.strip}.flatten user.tag_list = tag_list user.tags.should == tags end it "returns an empty array if there are no tags" do user.tags = nil user.tags.should_not be_nil user.tags.should eql([]) end it "returns an empty array even if tag_list is equal to nil" do user.tag_list = nil user.tags.should_not be_nil user.tags.should eql([]) end end describe "A Taggable model with tags assigned" do before(:each) do @user = User.create!(name: 'Tuquito', tag_list: "linux, tucuman, free software") end it "should be able to find tagged_with objects" do User.tagged_with('linux').first.should == @user User.tagged_with(['tucuman', 'free software']).first.should == @user end it "should be able to find tagged_with objects if more than one object is present" do user_2 = User.create!(name: 'ubuntu', tag_list: 'linux') tagged_with_list = User.tagged_with('linux') tagged_with_list.include?(@user).should be_true tagged_with_list.include?(user_2).should be_true end it "should return all_tags per Model class" do User.create(name: 'ubuntu', tag_list: 'linux') expected_tag_list = [ {:name => "free software", :count => 1}, {:name => "linux", :count => 2}, {:name => "tucuman", :count => 1} ] User.all_tags.should == expected_tag_list end it "returns an array of all tags used on all instances of a model" do User.create(name: 'ubuntu', tag_list: 'linux') User.tag_list.sort.should == ["linux", "tucuman", "free software"].sort end it 'should be able to find tagged_with_all objects' do user_2 = User.create! name: 'Jane Doe', tag_list: 'linux, foo, bar' User.tagged_with_all(%w[foo linux]).should == [user_2] User.tagged_with_all('linux').to_a.should =~ ([@user, user_2]) User.tagged_with_all(%w[linux]).to_a.should =~ [@user, user_2] User.tagged_with_all([]).should == [] User.tagged_with_all(%w[foo tucuman]).should == [] end end describe "A Taggable model with scope" do before(:each) do @organization_1 = Organization.create(name: 'Qualica') @user_1 = @organization_1.users.create(name: 'User1', tag_list: "ubuntu, linux, tucuman") @user_2 = @organization_1.users.create(name: 'User2', tag_list: "ubuntu, linux, tucuman") @organization_2 = Organization.create(name: 'Microsoft') @user_3 = @organization_2.users.create(name: 'User3', tag_list: 'microsoft, windows, tucuman') @user_4 = @organization_2.users.create(name: 'User4', tag_list: 'ubuntu, linux, tucuman') end it "should return scoped tags when passing one option" do results = User.all_tags(organization_id: @organization_1.id) results.empty?.should be_false results.include?( {:name => "linux", :count => 2 } ).should be_true results.include?( {:name => "ubuntu", :count => 2 } ).should be_true results.include?( {:name => "tucuman", :count => 2 } ).should be_true results = User.all_tags(organization_id: @organization_2.id) results.empty?.should be_false results.include?( {:name =>"linux", :count => 1 } ).should be_true results.include?( {:name => "microsoft", :count => 1 } ).should be_true results.include?( {:name => "windows", :count => 1 } ).should be_true results.include?( {:name => "tucuman", :count => 2 } ).should be_true end it "should return scoped tags when passing more than one option" do results = User.all_tags(organization_id: @organization_1.id, name: @user_1.name) results.empty?.should be_false results.include?( {:name => "linux", :count => 1 } ).should be_true results.include?( {:name => "ubuntu", :count => 1 } ).should be_true results.include?( {:name => "tucuman", :count => 1 } ).should be_true end it "should return scoped tags when calling deprecated scoped_tags method" do results = User.all_tags(organization_id: @organization_1.id) results.empty?.should be_false results.include?( {:name => "linux", :count => 2 } ).should be_true results.include?( {:name => "ubuntu", :count => 2 } ).should be_true results.include?( {:name => "tucuman", :count => 2 } ).should be_true end end specs fixed require 'spec_helper' class User include Mongoid::Document include Mongoid::Document::Taggable field :name belongs_to :organization end class Organization include Mongoid::Document field :name has_many :users end describe "A Taggable model" do let(:user) { User.new(name: 'Tuquito') } it "should have a tag_list method" do user.should respond_to(:tag_list) end it "should have a tag_list class method" do User.should respond_to(:tag_list) end it "should be able to update a tag list" do tag_list = "linux, tucuman, free software" tags = tag_list.split(',').map{ |tag| tag.strip}.flatten user.tag_list = tag_list user.tags.should == tags end it "returns an empty array if there are no tags" do user.tags = nil user.tags.should_not be_nil user.tags.should eql([]) end it "returns an empty array even if tag_list is equal to nil" do user.tag_list = nil user.tags.should_not be_nil user.tags.should eql([]) end end describe "A Taggable model with tags assigned" do before(:each) do @user = User.create!(name: 'Tuquito', tag_list: "linux, tucuman, free software") end it "should be able to find tagged_with objects" do User.tagged_with('linux').first.should == @user User.tagged_with(['tucuman', 'free software']).first.should == @user end it "should be able to find tagged_with objects if more than one object is present" do user_2 = User.create!(name: 'ubuntu', tag_list: 'linux') tagged_with_list = User.tagged_with('linux') tagged_with_list.include?(@user).should be_true tagged_with_list.include?(user_2).should be_true end it "should return all_tags per Model class" do User.create(name: 'ubuntu', tag_list: 'linux') expected_tag_list = [ {:name => "free software", :count => 1}, {:name => "linux", :count => 2}, {:name => "tucuman", :count => 1} ] User.all_tags.should == expected_tag_list end it "returns an array of all tags used on all instances of a model" do User.create(name: 'ubuntu', tag_list: 'linux') User.tag_list.sort.should == ["linux", "tucuman", "free software"].sort end it 'should be able to find tagged_with_all objects' do user_2 = User.create! name: 'Jane Doe', tag_list: 'linux, foo, bar' User.tagged_with_all(%w[foo linux]).should == [user_2] User.tagged_with_all('linux').to_a.should =~ ([@user, user_2]) User.tagged_with_all(%w[linux]).to_a.should =~ [@user, user_2] User.tagged_with_all([]).should == [] User.tagged_with_all(%w[foo tucuman]).should == [] end end describe "A Taggable model with scope" do before(:each) do @organization_1 = Organization.create(name: 'Qualica') @user_1 = @organization_1.users.create(name: 'User1', tag_list: "ubuntu, linux, tucuman") @user_2 = @organization_1.users.create(name: 'User2', tag_list: "ubuntu, linux, tucuman") @organization_2 = Organization.create(name: 'Microsoft') @user_3 = @organization_2.users.create(name: 'User3', tag_list: 'microsoft, windows, tucuman') @user_4 = @organization_2.users.create(name: 'User4', tag_list: 'ubuntu, linux, tucuman') end it "should return scoped tags when passing one option" do results = User.all_tags(:en, organization_id: @organization_1.id) results.empty?.should be_false results.include?( {:name => "linux", :count => 2 } ).should be_true results.include?( {:name => "ubuntu", :count => 2 } ).should be_true results.include?( {:name => "tucuman", :count => 2 } ).should be_true results = User.all_tags(:en, organization_id: @organization_2.id) results.empty?.should be_false results.include?( {:name =>"linux", :count => 1 } ).should be_true results.include?( {:name => "microsoft", :count => 1 } ).should be_true results.include?( {:name => "windows", :count => 1 } ).should be_true results.include?( {:name => "tucuman", :count => 2 } ).should be_true end it "should return scoped tags when passing more than one option" do results = User.all_tags(:en, organization_id: @organization_1.id, name: @user_1.name) results.empty?.should be_false results.include?( {:name => "linux", :count => 1 } ).should be_true results.include?( {:name => "ubuntu", :count => 1 } ).should be_true results.include?( {:name => "tucuman", :count => 1 } ).should be_true end it "should return scoped tags when calling deprecated scoped_tags method" do results = User.all_tags(:en, organization_id: @organization_1.id) results.empty?.should be_false results.include?( {:name => "linux", :count => 2 } ).should be_true results.include?( {:name => "ubuntu", :count => 2 } ).should be_true results.include?( {:name => "tucuman", :count => 2 } ).should be_true end end
Terrible PhotosetDownloader spec require 'spec_helper' module FlickrOfflineGallery describe PhotosetDownloader do subject(:photoset_downloader) do described_class.new(photoset, selected_size) end let(:selected_size) { :thumbnail } let(:photoset) do VCR.use_cassette('photoset') do Photoset.new("72157639475533743") end end it 'should download' do photoset_downloader.download File.exist?(photoset.photos[0].local_jpg_path).should be_true end end end
require "read_time_estimator" require 'rspec' describe "ReadTimeEstimator" do describe "read_time" do it "returns the reading time in phrase form" do text = "word " * 250 expect(text.read_time).to eql "1.0 minutes to read" end end describe "time_per_word" do it "should output an amount of time given the length of a word" do expect("supercalifragilisticexpialidocious".time_per_word).to eql "02:10" end end end Replace time_per_word spec with minutes_to_read spec. PA-2182 require "read_time_estimator" require 'rspec' describe "ReadTimeEstimator" do describe "read_time" do it "returns the reading time in phrase form" do text = "word " * 250 expect(text.read_time).to eql "1.0 minutes to read" end end describe "minutes_to_read" do it "should output an amount of time given the length of a word" do text = "word " * 250 expect(text.minutes_to_read.to eql 1.0 end end end
require "spec_helper" describe "real world edgecases", :realworld => true, :sometimes => true do # there is no rbx-relative-require gem that will install on 1.9 it "ignores extra gems with bad platforms", :ruby => "~> 1.8.7" do gemfile <<-G source "https://rubygems.org" gem "linecache", "0.46" G bundle :lock expect(err).to eq("") expect(exitstatus).to eq(0) if exitstatus end # https://github.com/bundler/bundler/issues/1202 it "bundle cache works with rubygems 1.3.7 and pre gems", :ruby => "~> 1.8.7", "https://rubygems.org" => "~> 1.3.7" do install_gemfile <<-G source "https://rubygems.org" gem "rack", "1.3.0.beta2" gem "will_paginate", "3.0.pre2" G bundle :cache expect(out).not_to include("Removing outdated .gem files from vendor/cache") end # https://github.com/bundler/bundler/issues/1486 # this is a hash collision that only manifests on 1.8.7 it "finds the correct child versions", :ruby => "~> 1.8.7" do gemfile <<-G source "https://rubygems.org" gem 'i18n', '~> 0.6.0' gem 'activesupport', '~> 3.0' gem 'activerecord', '~> 3.0' gem 'builder', '~> 2.1.2' G bundle :lock expect(lockfile).to include("activemodel (3.0.5)") end it "resolves dependencies correctly", :ruby => "1.9.3" do gemfile <<-G source "https://rubygems.org" gem 'rails', '~> 3.0' gem 'capybara', '~> 2.2.0' gem 'rack-cache', '1.2.0' # last version that works on Ruby 1.9 G bundle :lock expect(lockfile).to include("rails (3.2.22)") expect(lockfile).to include("capybara (2.2.1)") end it "installs the latest version of gxapi_rails", :ruby => "1.9.3" do install_gemfile <<-G source "https://rubygems.org" gem "sass-rails" gem "rails", "~> 3" gem "gxapi_rails" gem 'rack-cache', '1.2.0' # last version that works on Ruby 1.9 G expect(out).to include("gxapi_rails 0.0.6") end it "installs the latest version of i18n" do gemfile <<-G source "https://rubygems.org" gem "i18n", "~> 0.6.0" gem "activesupport", "~> 3.0" gem "activerecord", "~> 3.0" gem "builder", "~> 2.1.2" G bundle :lock expect(lockfile).to include("i18n (0.6.11)") expect(lockfile).to include("activesupport (3.0.5)") end # https://github.com/bundler/bundler/issues/1500 it "does not fail install because of gem plugins" do realworld_system_gems("open_gem --version 1.4.2", "rake --version 0.9.2") gemfile <<-G source "https://rubygems.org" gem 'rack', '1.0.1' G bundle "install --path vendor/bundle", :expect_err => true expect(err).not_to include("Could not find rake") expect(err).to be_empty end it "checks out git repos when the lockfile is corrupted" do gemfile <<-G source "https://rubygems.org" gem 'activerecord', :github => 'carlhuda/rails-bundler-test', :branch => 'master' gem 'activesupport', :github => 'carlhuda/rails-bundler-test', :branch => 'master' gem 'actionpack', :github => 'carlhuda/rails-bundler-test', :branch => 'master' G lockfile <<-L GIT remote: git://github.com/carlhuda/rails-bundler-test.git revision: 369e28a87419565f1940815219ea9200474589d4 branch: master specs: actionpack (3.2.2) activemodel (= 3.2.2) activesupport (= 3.2.2) builder (~> 3.0.0) erubis (~> 2.7.0) journey (~> 1.0.1) rack (~> 1.4.0) rack-cache (~> 1.2) rack-test (~> 0.6.1) sprockets (~> 2.1.2) activemodel (3.2.2) activesupport (= 3.2.2) builder (~> 3.0.0) activerecord (3.2.2) activemodel (= 3.2.2) activesupport (= 3.2.2) arel (~> 3.0.2) tzinfo (~> 0.3.29) activesupport (3.2.2) i18n (~> 0.6) multi_json (~> 1.0) GIT remote: git://github.com/carlhuda/rails-bundler-test.git revision: 369e28a87419565f1940815219ea9200474589d4 branch: master specs: actionpack (3.2.2) activemodel (= 3.2.2) activesupport (= 3.2.2) builder (~> 3.0.0) erubis (~> 2.7.0) journey (~> 1.0.1) rack (~> 1.4.0) rack-cache (~> 1.2) rack-test (~> 0.6.1) sprockets (~> 2.1.2) activemodel (3.2.2) activesupport (= 3.2.2) builder (~> 3.0.0) activerecord (3.2.2) activemodel (= 3.2.2) activesupport (= 3.2.2) arel (~> 3.0.2) tzinfo (~> 0.3.29) activesupport (3.2.2) i18n (~> 0.6) multi_json (~> 1.0) GIT remote: git://github.com/carlhuda/rails-bundler-test.git revision: 369e28a87419565f1940815219ea9200474589d4 branch: master specs: actionpack (3.2.2) activemodel (= 3.2.2) activesupport (= 3.2.2) builder (~> 3.0.0) erubis (~> 2.7.0) journey (~> 1.0.1) rack (~> 1.4.0) rack-cache (~> 1.2) rack-test (~> 0.6.1) sprockets (~> 2.1.2) activemodel (3.2.2) activesupport (= 3.2.2) builder (~> 3.0.0) activerecord (3.2.2) activemodel (= 3.2.2) activesupport (= 3.2.2) arel (~> 3.0.2) tzinfo (~> 0.3.29) activesupport (3.2.2) i18n (~> 0.6) multi_json (~> 1.0) GEM remote: https://rubygems.org/ specs: arel (3.0.2) builder (3.0.0) erubis (2.7.0) hike (1.2.1) i18n (0.6.0) journey (1.0.3) multi_json (1.1.0) rack (1.4.1) rack-cache (1.2) rack (>= 0.4) rack-test (0.6.1) rack (>= 1.0) sprockets (2.1.2) hike (~> 1.2) rack (~> 1.0) tilt (~> 1.1, != 1.3.0) tilt (1.3.3) tzinfo (0.3.32) PLATFORMS ruby DEPENDENCIES actionpack! activerecord! activesupport! L bundle :lock expect(err).to eq("") expect(exitstatus).to eq(0) if exitstatus end end Auto merge of #4123 - bundler:seg-fix-realworld-specs, r=segiddins Fix edgecases spec for new gxapi_rails version \c @indirect require "spec_helper" describe "real world edgecases", :realworld => true, :sometimes => true do # there is no rbx-relative-require gem that will install on 1.9 it "ignores extra gems with bad platforms", :ruby => "~> 1.8.7" do gemfile <<-G source "https://rubygems.org" gem "linecache", "0.46" G bundle :lock expect(err).to eq("") expect(exitstatus).to eq(0) if exitstatus end # https://github.com/bundler/bundler/issues/1202 it "bundle cache works with rubygems 1.3.7 and pre gems", :ruby => "~> 1.8.7", "https://rubygems.org" => "~> 1.3.7" do install_gemfile <<-G source "https://rubygems.org" gem "rack", "1.3.0.beta2" gem "will_paginate", "3.0.pre2" G bundle :cache expect(out).not_to include("Removing outdated .gem files from vendor/cache") end # https://github.com/bundler/bundler/issues/1486 # this is a hash collision that only manifests on 1.8.7 it "finds the correct child versions", :ruby => "~> 1.8.7" do gemfile <<-G source "https://rubygems.org" gem 'i18n', '~> 0.6.0' gem 'activesupport', '~> 3.0' gem 'activerecord', '~> 3.0' gem 'builder', '~> 2.1.2' G bundle :lock expect(lockfile).to include("activemodel (3.0.5)") end it "resolves dependencies correctly", :ruby => "1.9.3" do gemfile <<-G source "https://rubygems.org" gem 'rails', '~> 3.0' gem 'capybara', '~> 2.2.0' gem 'rack-cache', '1.2.0' # last version that works on Ruby 1.9 G bundle :lock expect(lockfile).to include("rails (3.2.22)") expect(lockfile).to include("capybara (2.2.1)") end it "installs the latest version of gxapi_rails", :ruby => "1.9.3" do gemfile <<-G source "https://rubygems.org" gem "sass-rails" gem "rails", "~> 3" gem "gxapi_rails", "< 0.1.0" # 0.1.0 was released way after the test was written gem 'rack-cache', '1.2.0' # last version that works on Ruby 1.9 G bundle :lock expect(lockfile).to include("gxapi_rails (0.0.6)") end it "installs the latest version of i18n" do gemfile <<-G source "https://rubygems.org" gem "i18n", "~> 0.6.0" gem "activesupport", "~> 3.0" gem "activerecord", "~> 3.0" gem "builder", "~> 2.1.2" G bundle :lock expect(lockfile).to include("i18n (0.6.11)") expect(lockfile).to include("activesupport (3.0.5)") end # https://github.com/bundler/bundler/issues/1500 it "does not fail install because of gem plugins" do realworld_system_gems("open_gem --version 1.4.2", "rake --version 0.9.2") gemfile <<-G source "https://rubygems.org" gem 'rack', '1.0.1' G bundle "install --path vendor/bundle", :expect_err => true expect(err).not_to include("Could not find rake") expect(err).to be_empty end it "checks out git repos when the lockfile is corrupted" do gemfile <<-G source "https://rubygems.org" gem 'activerecord', :github => 'carlhuda/rails-bundler-test', :branch => 'master' gem 'activesupport', :github => 'carlhuda/rails-bundler-test', :branch => 'master' gem 'actionpack', :github => 'carlhuda/rails-bundler-test', :branch => 'master' G lockfile <<-L GIT remote: git://github.com/carlhuda/rails-bundler-test.git revision: 369e28a87419565f1940815219ea9200474589d4 branch: master specs: actionpack (3.2.2) activemodel (= 3.2.2) activesupport (= 3.2.2) builder (~> 3.0.0) erubis (~> 2.7.0) journey (~> 1.0.1) rack (~> 1.4.0) rack-cache (~> 1.2) rack-test (~> 0.6.1) sprockets (~> 2.1.2) activemodel (3.2.2) activesupport (= 3.2.2) builder (~> 3.0.0) activerecord (3.2.2) activemodel (= 3.2.2) activesupport (= 3.2.2) arel (~> 3.0.2) tzinfo (~> 0.3.29) activesupport (3.2.2) i18n (~> 0.6) multi_json (~> 1.0) GIT remote: git://github.com/carlhuda/rails-bundler-test.git revision: 369e28a87419565f1940815219ea9200474589d4 branch: master specs: actionpack (3.2.2) activemodel (= 3.2.2) activesupport (= 3.2.2) builder (~> 3.0.0) erubis (~> 2.7.0) journey (~> 1.0.1) rack (~> 1.4.0) rack-cache (~> 1.2) rack-test (~> 0.6.1) sprockets (~> 2.1.2) activemodel (3.2.2) activesupport (= 3.2.2) builder (~> 3.0.0) activerecord (3.2.2) activemodel (= 3.2.2) activesupport (= 3.2.2) arel (~> 3.0.2) tzinfo (~> 0.3.29) activesupport (3.2.2) i18n (~> 0.6) multi_json (~> 1.0) GIT remote: git://github.com/carlhuda/rails-bundler-test.git revision: 369e28a87419565f1940815219ea9200474589d4 branch: master specs: actionpack (3.2.2) activemodel (= 3.2.2) activesupport (= 3.2.2) builder (~> 3.0.0) erubis (~> 2.7.0) journey (~> 1.0.1) rack (~> 1.4.0) rack-cache (~> 1.2) rack-test (~> 0.6.1) sprockets (~> 2.1.2) activemodel (3.2.2) activesupport (= 3.2.2) builder (~> 3.0.0) activerecord (3.2.2) activemodel (= 3.2.2) activesupport (= 3.2.2) arel (~> 3.0.2) tzinfo (~> 0.3.29) activesupport (3.2.2) i18n (~> 0.6) multi_json (~> 1.0) GEM remote: https://rubygems.org/ specs: arel (3.0.2) builder (3.0.0) erubis (2.7.0) hike (1.2.1) i18n (0.6.0) journey (1.0.3) multi_json (1.1.0) rack (1.4.1) rack-cache (1.2) rack (>= 0.4) rack-test (0.6.1) rack (>= 1.0) sprockets (2.1.2) hike (~> 1.2) rack (~> 1.0) tilt (~> 1.1, != 1.3.0) tilt (1.3.3) tzinfo (0.3.32) PLATFORMS ruby DEPENDENCIES actionpack! activerecord! activesupport! L bundle :lock expect(err).to eq("") expect(exitstatus).to eq(0) if exitstatus end end