repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/validatable-1.6.7/lib/requireable.rb | provider/vendor/gems/validatable-1.6.7/lib/requireable.rb | module Validatable
module Requireable #:nodoc:
module ClassMethods #:nodoc:
def requires(*args)
required_options.concat args
end
def required_options
@required_options ||= []
end
end
def self.included(klass)
klass.extend ClassMethods
end
def requires(options)
required_options = self.class.required_options.inject([]) do |errors, attribute|
errors << attribute.to_s unless options.has_key?(attribute)
errors
end
raise ArgumentError.new("#{self.class} requires options: #{required_options.join(', ')}") if required_options.any?
true
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/validatable-1.6.7/lib/child_validation.rb | provider/vendor/gems/validatable-1.6.7/lib/child_validation.rb | module Validatable
class ChildValidation #:nodoc:
attr_accessor :attribute, :map, :should_validate_proc
def initialize(attribute, map, should_validate_proc)
@attribute = attribute
@map = map
@should_validate_proc = should_validate_proc
end
def should_validate?(instance)
instance.instance_eval &should_validate_proc
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/validatable-1.6.7/lib/validatable_class_methods.rb | provider/vendor/gems/validatable-1.6.7/lib/validatable_class_methods.rb | module Validatable
module ClassMethods #:nodoc:
def validate_children(instance, group)
self.children_to_validate.each do |child_validation|
next unless child_validation.should_validate?(instance)
child = instance.send child_validation.attribute
if (child.respond_to?(:valid_for_group?))
child.valid_for_group?(group)
else
child.valid?
end
child.errors.each do |attribute, messages|
if messages.is_a?(String)
add_error(instance, child_validation.map[attribute.to_sym] || attribute, messages)
else
messages.each do |message|
add_error(instance, child_validation.map[attribute.to_sym] || attribute, message)
end
end
end
end
end
def all_before_validations
if self.superclass.respond_to? :all_before_validations
return before_validations + self.superclass.all_before_validations
end
before_validations
end
def before_validations
@before_validations ||= []
end
def all_validations
if self.respond_to?(:superclass) && self.superclass.respond_to?(:all_validations)
return validations + self.superclass.all_validations
end
validations
end
def validations
@validations ||= []
end
def add_error(instance, attribute, msg)
instance.errors.add(attribute, msg)
end
def validation_keys_include?(key)
validations.map { |validation| validation.key }.include?(key)
end
def validations_to_include
@validations_to_include ||= []
end
protected
def add_validations(args, klass)
options = args.last.is_a?(Hash) ? args.pop : {}
args.each do |attribute|
new_validation = klass.new self, attribute, options
self.validations << new_validation
self.create_valid_method_for_groups new_validation.groups
end
end
def create_valid_method_for_groups(groups)
groups.each do |group|
self.class_eval do
define_method "valid_for_#{group}?".to_sym do
valid_for_group?(group)
end
end
end
end
def children_to_validate
@children_to_validate ||= []
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/validatable-1.6.7/lib/validations/validates_numericality_of.rb | provider/vendor/gems/validatable-1.6.7/lib/validations/validates_numericality_of.rb | module Validatable
class ValidatesNumericalityOf < ValidationBase #:nodoc:
option :only_integer
def valid?(instance)
value = instance.send(self.attribute).to_s
regex = self.only_integer ? /\A[+-]?\d+\Z/ : /^\d*\.{0,1}\d+$/
not (value =~ regex).nil?
end
def message(instance)
super || "must be a number"
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/validatable-1.6.7/lib/validations/validates_format_of.rb | provider/vendor/gems/validatable-1.6.7/lib/validations/validates_format_of.rb | module Validatable
class ValidatesFormatOf < ValidationBase #:nodoc:
required_option :with
def valid?(instance)
not (instance.send(self.attribute).to_s =~ self.with).nil?
end
def message(instance)
super || "is invalid"
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/validatable-1.6.7/lib/validations/validation_base.rb | provider/vendor/gems/validatable-1.6.7/lib/validations/validation_base.rb | module Validatable
class ValidationBase #:nodoc:
class << self
def required_option(*args)
option(*args)
requires(*args)
end
def option(*args)
attr_accessor(*args)
understands(*args)
end
def default(hash)
defaults.merge! hash
end
def defaults
@defaults ||= {}
end
def all_defaults
return defaults.merge(self.superclass.all_defaults) if self.superclass.respond_to? :all_defaults
defaults
end
def after_validate(&block)
after_validations << block
end
def after_validations
@after_validations ||= []
end
def all_after_validations
return after_validations + self.superclass.all_after_validations if self.superclass.respond_to? :all_after_validations
after_validations
end
end
include Understandable
include Requireable
option :message, :if, :times, :level, :groups, :key, :after_validate
default :level => 1, :groups => []
attr_accessor :attribute
def initialize(klass, attribute, options={})
must_understand options
requires options
self.class.all_understandings.each do |understanding|
options[understanding] = self.class.all_defaults[understanding] unless options.has_key? understanding
self.instance_variable_set("@#{understanding}", options[understanding])
end
self.attribute = attribute
self.groups = [self.groups] unless self.groups.is_a?(Array)
self.key = "#{klass.name}/#{self.class.name}/#{self.key || self.attribute}"
raise_error_if_key_is_dup(klass)
end
def raise_error_if_key_is_dup(klass)
message = "key #{self.key} must be unique, provide the :key option to specify a unique key"
raise ArgumentError.new(message) if klass.validation_keys_include? self.key
end
def should_validate?(instance)
result = validate_this_time?(instance)
result &&= instance.instance_eval(&self.if) unless self.if.nil?
result
end
def message(instance)
@message.respond_to?(:call) ? instance.instance_eval(&@message) : @message
end
def validate_this_time?(instance)
return true if @times.nil?
self.times > instance.times_validated(self.key)
end
def run_after_validate(result, instance, attribute)
self.class.all_after_validations.each do |block|
block.call result, instance, attribute
end
instance.instance_eval_with_params result, attribute, &self.after_validate unless self.after_validate.nil?
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/validatable-1.6.7/lib/validations/validates_true_for.rb | provider/vendor/gems/validatable-1.6.7/lib/validations/validates_true_for.rb | module Validatable
class ValidatesTrueFor < ValidationBase #:nodoc:
required_option :logic
def valid?(instance)
instance.instance_eval(&logic) == true
end
def message(instance)
super || "is invalid"
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/validatable-1.6.7/lib/validations/validates_length_of.rb | provider/vendor/gems/validatable-1.6.7/lib/validations/validates_length_of.rb | module Validatable
class ValidatesLengthOf < ValidationBase #:nodoc:
option :minimum, :maximum, :is, :within, :allow_nil
def message(instance)
super || "is invalid"
end
def valid?(instance)
valid = true
value = instance.send(self.attribute)
if value.nil?
return true if allow_nil
value = ""
end
valid &&= value.length <= maximum unless maximum.nil?
valid &&= value.length >= minimum unless minimum.nil?
valid &&= value.length == is unless is.nil?
valid &&= within.include?(value.length) unless within.nil?
valid
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/validatable-1.6.7/lib/validations/validates_confirmation_of.rb | provider/vendor/gems/validatable-1.6.7/lib/validations/validates_confirmation_of.rb | module Validatable
class ValidatesConfirmationOf < ValidationBase #:nodoc:
option :case_sensitive
default :case_sensitive => true
def valid?(instance)
return instance.send(self.attribute) == instance.send("#{self.attribute}_confirmation".to_sym) if case_sensitive
instance.send(self.attribute).to_s.casecmp(instance.send("#{self.attribute}_confirmation".to_sym).to_s) == 0
end
def message(instance)
super || "doesn't match confirmation"
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/validatable-1.6.7/lib/validations/validates_presence_of.rb | provider/vendor/gems/validatable-1.6.7/lib/validations/validates_presence_of.rb | module Validatable
class ValidatesPresenceOf < ValidationBase #:nodoc:
def valid?(instance)
return false if instance.send(self.attribute).nil?
instance.send(self.attribute).respond_to?(:strip) ? instance.send(self.attribute).strip.length != 0 : true
end
def message(instance)
super || "can't be empty"
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/validatable-1.6.7/lib/validations/validates_each.rb | provider/vendor/gems/validatable-1.6.7/lib/validations/validates_each.rb | module Validatable
class ValidatesEach < ValidationBase #:nodoc:
required_option :logic
def valid?(instance)
instance.instance_eval(&logic)
true # return true so no error is added. should look in the future at doing this different.
end
def message(instance)
super || "is invalid"
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/validatable-1.6.7/lib/validations/validates_acceptance_of.rb | provider/vendor/gems/validatable-1.6.7/lib/validations/validates_acceptance_of.rb | module Validatable
class ValidatesAcceptanceOf < ValidationBase #:nodoc:
def valid?(instance)
instance.send(self.attribute) == "true"
end
def message(instance)
super || "must be accepted"
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/builder-2.1.2/scripts/publish.rb | provider/vendor/gems/builder-2.1.2/scripts/publish.rb | # Optional publish task for Rake
require 'rake/contrib/sshpublisher'
require 'rake/contrib/rubyforgepublisher'
publisher = Rake::CompositePublisher.new
publisher.add Rake::RubyForgePublisher.new('builder', 'jimweirich')
publisher.add Rake::SshFilePublisher.new(
'umlcoop',
'htdocs/software/builder',
'.',
'builder.blurb')
desc "Publish the Documentation to RubyForge."
task :publish => [:rdoc] do
publisher.upload
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/builder-2.1.2/test/testblankslate.rb | provider/vendor/gems/builder-2.1.2/test/testblankslate.rb | #!/usr/bin/env ruby
require 'test/unit'
require 'test/preload'
require 'builder/blankslate'
require 'stringio'
# Methods to be introduced into the Object class late.
module LateObject
def late_object
33
end
def LateObject.included(mod)
# Modules defining an included method should not prevent blank
# slate erasure!
end
end
# Methods to be introduced into the Kernel module late.
module LateKernel
def late_kernel
44
end
def LateKernel.included(mod)
# Modules defining an included method should not prevent blank
# slate erasure!
end
end
# Introduce some late methods (both module and direct) into the Kernel
# module.
module Kernel
include LateKernel
def late_addition
1234
end
def double_late_addition
11
end
def double_late_addition
22
end
end
# Introduce some late methods (both module and direct) into the Object
# class.
class Object
include LateObject
def another_late_addition
4321
end
end
# Introduce some late methods by inclusion.
module GlobalModule
def global_inclusion
42
end
end
include GlobalModule
def direct_global
43
end
######################################################################
# Test case for blank slate.
#
class TestBlankSlate < Test::Unit::TestCase
def setup
@bs = BlankSlate.new
end
def test_undefined_methods_remain_undefined
assert_raise(NoMethodError) { @bs.no_such_method }
assert_raise(NoMethodError) { @bs.nil? }
end
# NOTE: NameError is acceptable because the lack of a '.' means that
# Ruby can't tell if it is a method or a local variable.
def test_undefined_methods_remain_undefined_during_instance_eval
assert_raise(NoMethodError, NameError) do
@bs.instance_eval do nil? end
end
assert_raise(NoMethodError, NameError) do
@bs.instance_eval do no_such_method end
end
end
def test_private_methods_are_undefined
assert_raise(NoMethodError) do
@bs.puts "HI"
end
end
def test_targetted_private_methods_are_undefined_during_instance_eval
assert_raise(NoMethodError, NameError) do
@bs.instance_eval do self.puts "HI" end
end
end
def test_untargetted_private_methods_are_defined_during_instance_eval
oldstdout = $stdout
$stdout = StringIO.new
@bs.instance_eval do
puts "HI"
end
ensure
$stdout = oldstdout
end
def test_methods_added_late_to_kernel_remain_undefined
assert_equal 1234, nil.late_addition
assert_raise(NoMethodError) { @bs.late_addition }
end
def test_methods_added_late_to_object_remain_undefined
assert_equal 4321, nil.another_late_addition
assert_raise(NoMethodError) { @bs.another_late_addition }
end
def test_methods_added_late_to_global_remain_undefined
assert_equal 42, global_inclusion
assert_raise(NoMethodError) { @bs.global_inclusion }
end
def test_preload_method_added
assert Kernel.k_added_names.include?(:late_addition)
assert Object.o_added_names.include?(:another_late_addition)
end
def test_method_defined_late_multiple_times_remain_undefined
assert_equal 22, nil.double_late_addition
assert_raise(NoMethodError) { @bs.double_late_addition }
end
def test_late_included_module_in_object_is_ok
assert_equal 33, 1.late_object
assert_raise(NoMethodError) { @bs.late_object }
end
def test_late_included_module_in_kernel_is_ok
assert_raise(NoMethodError) { @bs.late_kernel }
end
def test_revealing_previously_hidden_methods_are_callable
with_to_s = Class.new(BlankSlate) do
reveal :to_s
end
assert_match /^#<.*>$/, with_to_s.new.to_s
end
def test_revealing_a_hidden_method_twice_is_ok
with_to_s = Class.new(BlankSlate) do
reveal :to_s
reveal :to_s
end
assert_match /^#<.*>$/, with_to_s.new.to_s
end
def test_revealing_unknown_hidden_method_is_an_error
assert_raises(RuntimeError) do
Class.new(BlankSlate) do
reveal :xyz
end
end
end
def test_global_includes_still_work
assert_nothing_raised do
assert_equal 42, global_inclusion
assert_equal 42, Object.new.global_inclusion
assert_equal 42, "magic number".global_inclusion
assert_equal 43, direct_global
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/builder-2.1.2/test/test_xchar.rb | provider/vendor/gems/builder-2.1.2/test/test_xchar.rb | #!/usr/bin/env ruby
require 'test/unit'
require 'builder/xchar'
class TestXmlEscaping < Test::Unit::TestCase
def test_ascii
assert_equal 'abc', 'abc'.to_xs
end
def test_predefined
assert_equal '&', '&'.to_xs # ampersand
assert_equal '<', '<'.to_xs # left angle bracket
assert_equal '>', '>'.to_xs # right angle bracket
end
def test_invalid
assert_equal '*', "\x00".to_xs # null
assert_equal '*', "\x0C".to_xs # form feed
assert_equal '*', "\xEF\xBF\xBF".to_xs # U+FFFF
end
def test_iso_8859_1
assert_equal 'ç', "\xE7".to_xs # small c cedilla
assert_equal '©', "\xA9".to_xs # copyright symbol
end
def test_win_1252
assert_equal '’', "\x92".to_xs # smart quote
assert_equal '€', "\x80".to_xs # euro
end
def test_utf8
assert_equal '’', "\xE2\x80\x99".to_xs # right single quote
assert_equal '©', "\xC2\xA9".to_xs # copy
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/builder-2.1.2/test/preload.rb | provider/vendor/gems/builder-2.1.2/test/preload.rb | #!/usr/bin/env ruby
# We are defining method_added in Kernel and Object so that when
# BlankSlate overrides them later, we can verify that it correctly
# calls the older hooks.
module Kernel
class << self
attr_reader :k_added_names
alias_method :preload_method_added, :method_added
def method_added(name)
preload_method_added(name)
@k_added_names ||= []
@k_added_names << name
end
end
end
class Object
class << self
attr_reader :o_added_names
alias_method :preload_method_added, :method_added
def method_added(name)
preload_method_added(name)
@o_added_names ||= []
@o_added_names << name
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/builder-2.1.2/test/testmarkupbuilder.rb | provider/vendor/gems/builder-2.1.2/test/testmarkupbuilder.rb | #!/usr/bin/env ruby
#--
# Portions copyright 2004 by Jim Weirich (jim@weirichhouse.org).
# Portions copyright 2005 by Sam Ruby (rubys@intertwingly.net).
# All rights reserved.
# Permission is granted for use, copying, modification, distribution,
# and distribution of modified versions of this work as long as the
# above copyright notice is included.
#++
require 'test/unit'
require 'test/preload'
require 'builder'
require 'builder/xmlmarkup'
class TestMarkup < Test::Unit::TestCase
def setup
@xml = Builder::XmlMarkup.new
end
def test_create
assert_not_nil @xml
end
def test_simple
@xml.simple
assert_equal "<simple/>", @xml.target!
end
def test_value
@xml.value("hi")
assert_equal "<value>hi</value>", @xml.target!
end
def test_nested
@xml.outer { |x| x.inner("x") }
assert_equal "<outer><inner>x</inner></outer>", @xml.target!
end
def test_attributes
@xml.ref(:id => 12)
assert_equal %{<ref id="12"/>}, @xml.target!
end
def test_string_attributes_are_quoted_by_default
@xml.ref(:id => "H&R")
assert_equal %{<ref id="H&R"/>}, @xml.target!
end
def test_symbol_attributes_are_unquoted_by_default
@xml.ref(:id => :"H&R")
assert_equal %{<ref id="H&R"/>}, @xml.target!
end
def test_attributes_quoted_can_be_turned_on
@xml = Builder::XmlMarkup.new
@xml.ref(:id => "<H&R \"block\">")
assert_equal %{<ref id="<H&R "block">"/>}, @xml.target!
end
def test_mixed_attribute_quoting_with_nested_builders
x = Builder::XmlMarkup.new(:target=>@xml)
@xml.ref(:id=>:"H&R") {
x.element(:tag=>"Long&Short")
}
assert_equal "<ref id=\"H&R\"><element tag=\"Long&Short\"/></ref>",
@xml.target!
end
def test_multiple_attributes
@xml.ref(:id => 12, :name => "bill")
assert_match %r{^<ref( id="12"| name="bill"){2}/>$}, @xml.target!
end
def test_attributes_with_text
@xml.a("link", :href=>"http://onestepback.org")
assert_equal %{<a href="http://onestepback.org">link</a>}, @xml.target!
end
def test_complex
@xml.body(:bg=>"#ffffff") { |x|
x.title("T", :style=>"red")
}
assert_equal %{<body bg="#ffffff"><title style="red">T</title></body>}, @xml.target!
end
def test_funky_symbol
@xml.tag!("non-ruby-token", :id=>1) { |x| x.ok }
assert_equal %{<non-ruby-token id="1"><ok/></non-ruby-token>}, @xml.target!
end
def test_tag_can_handle_private_method
@xml.tag!("loop", :id=>1) { |x| x.ok }
assert_equal %{<loop id="1"><ok/></loop>}, @xml.target!
end
def test_no_explicit_marker
@xml.p { |x| x.b("HI") }
assert_equal "<p><b>HI</b></p>", @xml.target!
end
def test_reference_local_vars
n = 3
@xml.ol { |x| n.times { x.li(n) } }
assert_equal "<ol><li>3</li><li>3</li><li>3</li></ol>", @xml.target!
end
def test_reference_methods
@xml.title { |x| x.a { x.b(name) } }
assert_equal "<title><a><b>bob</b></a></title>", @xml.target!
end
def test_append_text
@xml.p { |x| x.br; x.text! "HI" }
assert_equal "<p><br/>HI</p>", @xml.target!
end
def test_ambiguous_markup
ex = assert_raises(ArgumentError) {
@xml.h1("data1") { b }
}
assert_match /\btext\b/, ex.message
assert_match /\bblock\b/, ex.message
end
def test_capitalized_method
@xml.P { |x| x.B("hi"); x.BR(); x.EM { x.text! "world" } }
assert_equal "<P><B>hi</B><BR/><EM>world</EM></P>", @xml.target!
end
def test_escaping
@xml.div { |x| x.text! "<hi>"; x.em("H&R Block") }
assert_equal %{<div><hi><em>H&R Block</em></div>}, @xml.target!
end
def test_non_escaping
@xml.div("ns:xml"=>:"&xml;") { |x| x << "<h&i>"; x.em("H&R Block") }
assert_equal %{<div ns:xml="&xml;"><h&i><em>H&R Block</em></div>}, @xml.target!
end
def test_return_value
str = @xml.x("men")
assert_equal @xml.target!, str
end
def test_stacked_builders
b = Builder::XmlMarkup.new( :target => @xml )
b.div { @xml.span { @xml.a("text", :href=>"ref") } }
assert_equal "<div><span><a href=\"ref\">text</a></span></div>", @xml.target!
end
def name
"bob"
end
end
class TestAttributeEscaping < Test::Unit::TestCase
def setup
@xml = Builder::XmlMarkup.new
end
def test_element_gt
@xml.title('1<2')
assert_equal '<title>1<2</title>', @xml.target!
end
def test_element_amp
@xml.title('AT&T')
assert_equal '<title>AT&T</title>', @xml.target!
end
def test_element_amp2
@xml.title('&')
assert_equal '<title>&amp;</title>', @xml.target!
end
def test_attr_less
@xml.a(:title => '2>1')
assert_equal '<a title="2>1"/>', @xml.target!
end
def test_attr_amp
@xml.a(:title => 'AT&T')
assert_equal '<a title="AT&T"/>', @xml.target!
end
def test_attr_quot
@xml.a(:title => '"x"')
assert_equal '<a title=""x""/>', @xml.target!
end
end
class TestNameSpaces < Test::Unit::TestCase
def setup
@xml = Builder::XmlMarkup.new(:indent=>2)
end
def test_simple_name_spaces
@xml.rdf :RDF
assert_equal "<rdf:RDF/>\n", @xml.target!
end
def test_long
xml = Builder::XmlMarkup.new(:indent=>2)
xml.instruct!
xml.rdf :RDF,
"xmlns:rdf" => :"&rdf;",
"xmlns:rdfs" => :"&rdfs;",
"xmlns:xsd" => :"&xsd;",
"xmlns:owl" => :"&owl;" do
xml.owl :Class, :'rdf:ID'=>'Bird' do
xml.rdfs :label, 'bird'
xml.rdfs :subClassOf do
xml.owl :Restriction do
xml.owl :onProperty, 'rdf:resource'=>'#wingspan'
xml.owl :maxCardinality,1,'rdf:datatype'=>'&xsd;nonNegativeInteger'
end
end
end
end
assert_match /^<\?xml/, xml.target!
assert_match /\n<rdf:RDF/m, xml.target!
assert_match /xmlns:rdf="&rdf;"/m, xml.target!
assert_match /<owl:Restriction>/m, xml.target!
end
end
class TestDeclarations < Test::Unit::TestCase
def setup
@xml = Builder::XmlMarkup.new(:indent=>2)
end
def test_declare
@xml.declare! :element
assert_equal "<!element>\n", @xml.target!
end
def test_bare_arg
@xml.declare! :element, :arg
assert_equal"<!element arg>\n", @xml.target!
end
def test_string_arg
@xml.declare! :element, "string"
assert_equal"<!element \"string\">\n", @xml.target!
end
def test_mixed_args
@xml.declare! :element, :x, "y", :z, "-//OASIS//DTD DocBook XML//EN"
assert_equal "<!element x \"y\" z \"-//OASIS//DTD DocBook XML//EN\">\n", @xml.target!
end
def test_nested_declarations
@xml = Builder::XmlMarkup.new
@xml.declare! :DOCTYPE, :chapter do |x|
x.declare! :ELEMENT, :chapter, "(title,para+)".intern
end
assert_equal "<!DOCTYPE chapter [<!ELEMENT chapter (title,para+)>]>", @xml.target!
end
def test_nested_indented_declarations
@xml.declare! :DOCTYPE, :chapter do |x|
x.declare! :ELEMENT, :chapter, "(title,para+)".intern
end
assert_equal "<!DOCTYPE chapter [\n <!ELEMENT chapter (title,para+)>\n]>\n", @xml.target!
end
def test_complex_declaration
@xml.declare! :DOCTYPE, :chapter do |x|
x.declare! :ELEMENT, :chapter, "(title,para+)".intern
x.declare! :ELEMENT, :title, "(#PCDATA)".intern
x.declare! :ELEMENT, :para, "(#PCDATA)".intern
end
expected = %{<!DOCTYPE chapter [
<!ELEMENT chapter (title,para+)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT para (#PCDATA)>
]>
}
assert_equal expected, @xml.target!
end
end
class TestSpecialMarkup < Test::Unit::TestCase
def setup
@xml = Builder::XmlMarkup.new(:indent=>2)
end
def test_comment
@xml.comment!("COMMENT")
assert_equal "<!-- COMMENT -->\n", @xml.target!
end
def test_indented_comment
@xml.p { @xml.comment! "OK" }
assert_equal "<p>\n <!-- OK -->\n</p>\n", @xml.target!
end
def test_instruct
@xml.instruct! :abc, :version=>"0.9"
assert_equal "<?abc version=\"0.9\"?>\n", @xml.target!
end
def test_indented_instruct
@xml.p { @xml.instruct! :xml }
assert_match %r{<p>\n <\?xml version="1.0" encoding="UTF-8"\?>\n</p>\n},
@xml.target!
end
def test_instruct_without_attributes
@xml.instruct! :zz
assert_equal "<?zz?>\n", @xml.target!
end
def test_xml_instruct
@xml.instruct!
assert_match /^<\?xml version="1.0" encoding="UTF-8"\?>$/, @xml.target!
end
def test_xml_instruct_with_overrides
@xml.instruct! :xml, :encoding=>"UCS-2"
assert_match /^<\?xml version="1.0" encoding="UCS-2"\?>$/, @xml.target!
end
def test_xml_instruct_with_standalong
@xml.instruct! :xml, :encoding=>"UCS-2", :standalone=>"yes"
assert_match /^<\?xml version="1.0" encoding="UCS-2" standalone="yes"\?>$/, @xml.target!
end
def test_no_blocks
assert_raises(Builder::IllegalBlockError) do
@xml.instruct! { |x| x.hi }
end
assert_raises(Builder::IllegalBlockError) do
@xml.comment!(:element) { |x| x.hi }
end
end
def test_cdata
@xml.cdata!("TEST")
assert_equal "<![CDATA[TEST]]>\n", @xml.target!
end
def test_cdata_with_ampersand
@xml.cdata!("TEST&CHECK")
assert_equal "<![CDATA[TEST&CHECK]]>\n", @xml.target!
end
end
class TestIndentedXmlMarkup < Test::Unit::TestCase
def setup
@xml = Builder::XmlMarkup.new(:indent=>2)
end
def test_one_level
@xml.ol { |x| x.li "text" }
assert_equal "<ol>\n <li>text</li>\n</ol>\n", @xml.target!
end
def test_two_levels
@xml.p { |x|
x.ol { x.li "text" }
x.br
}
assert_equal "<p>\n <ol>\n <li>text</li>\n </ol>\n <br/>\n</p>\n", @xml.target!
end
def test_initial_level
@xml = Builder::XmlMarkup.new(:indent=>2, :margin=>4)
@xml.name { |x| x.first("Jim") }
assert_equal " <name>\n <first>Jim</first>\n </name>\n", @xml.target!
end
class TestXmlEvents < Test::Unit::TestCase
def setup
@handler = EventHandler.new
@xe = Builder::XmlEvents.new(:target=>@handler)
end
def test_simple
@xe.p
assert_equal [:start, :p, nil], @handler.events.shift
assert_equal [:end, :p], @handler.events.shift
end
def test_text
@xe.p("HI")
assert_equal [:start, :p, nil], @handler.events.shift
assert_equal [:text, "HI"], @handler.events.shift
assert_equal [:end, :p], @handler.events.shift
end
def test_attributes
@xe.p("id"=>"2")
ev = @handler.events.shift
assert_equal [:start, :p], ev[0,2]
assert_equal "2", ev[2]['id']
assert_equal [:end, :p], @handler.events.shift
end
def test_indented
@xml = Builder::XmlEvents.new(:indent=>2, :target=>@handler)
@xml.p { |x| x.b("HI") }
assert_equal [:start, :p, nil], @handler.events.shift
assert_equal "\n ", pop_text
assert_equal [:start, :b, nil], @handler.events.shift
assert_equal "HI", pop_text
assert_equal [:end, :b], @handler.events.shift
assert_equal "\n", pop_text
assert_equal [:end, :p], @handler.events.shift
end
def pop_text
result = ''
while ! @handler.events.empty? && @handler.events[0][0] == :text
result << @handler.events[0][1]
@handler.events.shift
end
result
end
class EventHandler
attr_reader :events
def initialize
@events = []
end
def start_tag(sym, attrs)
@events << [:start, sym, attrs]
end
def end_tag(sym)
@events << [:end, sym]
end
def text(txt)
@events << [:text, txt]
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/builder-2.1.2/test/testeventbuilder.rb | provider/vendor/gems/builder-2.1.2/test/testeventbuilder.rb | class TestEvents < Test::Unit::TestCase
class Target
attr_reader :events
def initialize
@events = []
end
def start_tag(tag, attrs)
@events << [:start_tag, tag, attrs]
end
def end_tag(tag)
@events << [:end_tag, tag]
end
def text(string)
@events << [:text, string]
end
end
def setup
@target = Target.new
@xml = Builder::XmlEvents.new(:target=>@target)
end
def test_simple
@xml.one
expect [:start_tag, :one, nil]
expect [:end_tag, :one]
expect_done
end
def test_nested
@xml.one { @xml.two }
expect [:start_tag, :one, nil]
expect [:start_tag, :two, nil]
expect [:end_tag, :two]
expect [:end_tag, :one]
expect_done
end
def test_text
@xml.one("a")
expect [:start_tag, :one, nil]
expect [:text, "a"]
expect [:end_tag, :one]
expect_done
end
def test_special_text
@xml.one("H&R")
expect [:start_tag, :one, nil]
expect [:text, "H&R"]
expect [:end_tag, :one]
expect_done
end
def test_text_with_entity
@xml.one("H&R")
expect [:start_tag, :one, nil]
expect [:text, "H&R"]
expect [:end_tag, :one]
expect_done
end
def test_attributes
@xml.a(:b=>"c", :x=>"y")
expect [:start_tag, :a, {:x => "y", :b => "c"}]
expect [:end_tag, :a]
expect_done
end
def test_moderately_complex
@xml.tag! "address-book" do |x|
x.entry :id=>"1" do
x.name {
x.first "Bill"
x.last "Smith"
}
x.address "Cincinnati"
end
x.entry :id=>"2" do
x.name {
x.first "John"
x.last "Doe"
}
x.address "Columbus"
end
end
expect [:start_tag, "address-book".intern, nil]
expect [:start_tag, :entry, {:id => "1"}]
expect [:start_tag, :name, nil]
expect [:start_tag, :first, nil]
expect [:text, "Bill"]
expect [:end_tag, :first]
expect [:start_tag, :last, nil]
expect [:text, "Smith"]
expect [:end_tag, :last]
expect [:end_tag, :name]
expect [:start_tag, :address, nil]
expect [:text, "Cincinnati"]
expect [:end_tag, :address]
expect [:end_tag, :entry]
expect [:start_tag, :entry, {:id => "2"}]
expect [:start_tag, :name, nil]
expect [:start_tag, :first, nil]
expect [:text, "John"]
expect [:end_tag, :first]
expect [:start_tag, :last, nil]
expect [:text, "Doe"]
expect [:end_tag, :last]
expect [:end_tag, :name]
expect [:start_tag, :address, nil]
expect [:text, "Columbus"]
expect [:end_tag, :address]
expect [:end_tag, :entry]
expect [:end_tag, "address-book".intern]
expect_done
end
def expect(value)
assert_equal value, @target.events.shift
end
def expect_done
assert_nil @target.events.shift
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/builder-2.1.2/lib/builder.rb | provider/vendor/gems/builder-2.1.2/lib/builder.rb | #!/usr/bin/env ruby
#--
# Copyright 2004 by Jim Weirich (jim@weirichhouse.org).
# All rights reserved.
# Permission is granted for use, copying, modification, distribution,
# and distribution of modified versions of this work as long as the
# above copyright notice is included.
#++
require 'builder/xmlmarkup'
require 'builder/xmlevents'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/builder-2.1.2/lib/blankslate.rb | provider/vendor/gems/builder-2.1.2/lib/blankslate.rb | #!/usr/bin/env ruby
#--
# Copyright 2004, 2006 by Jim Weirich (jim@weirichhouse.org).
# All rights reserved.
# Permission is granted for use, copying, modification, distribution,
# and distribution of modified versions of this work as long as the
# above copyright notice is included.
#++
######################################################################
# BlankSlate provides an abstract base class with no predefined
# methods (except for <tt>\_\_send__</tt> and <tt>\_\_id__</tt>).
# BlankSlate is useful as a base class when writing classes that
# depend upon <tt>method_missing</tt> (e.g. dynamic proxies).
#
class BlankSlate
class << self
# Hide the method named +name+ in the BlankSlate class. Don't
# hide +instance_eval+ or any method beginning with "__".
def hide(name)
if instance_methods.include?(name.to_s) and
name !~ /^(__|instance_eval)/
@hidden_methods ||= {}
@hidden_methods[name.to_sym] = instance_method(name)
undef_method name
end
end
def find_hidden_method(name)
@hidden_methods ||= {}
@hidden_methods[name] || superclass.find_hidden_method(name)
end
# Redefine a previously hidden method so that it may be called on a blank
# slate object.
def reveal(name)
bound_method = nil
unbound_method = find_hidden_method(name)
fail "Don't know how to reveal method '#{name}'" unless unbound_method
define_method(name) do |*args|
bound_method ||= unbound_method.bind(self)
bound_method.call(*args)
end
end
end
instance_methods.each { |m| hide(m) }
end
######################################################################
# Since Ruby is very dynamic, methods added to the ancestors of
# BlankSlate <em>after BlankSlate is defined</em> will show up in the
# list of available BlankSlate methods. We handle this by defining a
# hook in the Object and Kernel classes that will hide any method
# defined after BlankSlate has been loaded.
#
module Kernel
class << self
alias_method :blank_slate_method_added, :method_added
# Detect method additions to Kernel and remove them in the
# BlankSlate class.
def method_added(name)
result = blank_slate_method_added(name)
return result if self != Kernel
BlankSlate.hide(name)
result
end
end
end
######################################################################
# Same as above, except in Object.
#
class Object
class << self
alias_method :blank_slate_method_added, :method_added
# Detect method additions to Object and remove them in the
# BlankSlate class.
def method_added(name)
result = blank_slate_method_added(name)
return result if self != Object
BlankSlate.hide(name)
result
end
def find_hidden_method(name)
nil
end
end
end
######################################################################
# Also, modules included into Object need to be scanned and have their
# instance methods removed from blank slate. In theory, modules
# included into Kernel would have to be removed as well, but a
# "feature" of Ruby prevents late includes into modules from being
# exposed in the first place.
#
class Module
alias blankslate_original_append_features append_features
def append_features(mod)
result = blankslate_original_append_features(mod)
return result if mod != Object
instance_methods.each do |name|
BlankSlate.hide(name)
end
result
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/builder-2.1.2/lib/builder/xmlevents.rb | provider/vendor/gems/builder-2.1.2/lib/builder/xmlevents.rb | #!/usr/bin/env ruby
#--
# Copyright 2004 by Jim Weirich (jim@weirichhouse.org).
# All rights reserved.
# Permission is granted for use, copying, modification, distribution,
# and distribution of modified versions of this work as long as the
# above copyright notice is included.
#++
require 'builder/xmlmarkup'
module Builder
# Create a series of SAX-like XML events (e.g. start_tag, end_tag)
# from the markup code. XmlEvent objects are used in a way similar
# to XmlMarkup objects, except that a series of events are generated
# and passed to a handler rather than generating character-based
# markup.
#
# Usage:
# xe = Builder::XmlEvents.new(hander)
# xe.title("HI") # Sends start_tag/end_tag/text messages to the handler.
#
# Indentation may also be selected by providing value for the
# indentation size and initial indentation level.
#
# xe = Builder::XmlEvents.new(handler, indent_size, initial_indent_level)
#
# == XML Event Handler
#
# The handler object must expect the following events.
#
# [<tt>start_tag(tag, attrs)</tt>]
# Announces that a new tag has been found. +tag+ is the name of
# the tag and +attrs+ is a hash of attributes for the tag.
#
# [<tt>end_tag(tag)</tt>]
# Announces that an end tag for +tag+ has been found.
#
# [<tt>text(text)</tt>]
# Announces that a string of characters (+text+) has been found.
# A series of characters may be broken up into more than one
# +text+ call, so the client cannot assume that a single
# callback contains all the text data.
#
class XmlEvents < XmlMarkup
def text!(text)
@target.text(text)
end
def _start_tag(sym, attrs, end_too=false)
@target.start_tag(sym, attrs)
_end_tag(sym) if end_too
end
def _end_tag(sym)
@target.end_tag(sym)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/builder-2.1.2/lib/builder/xmlmarkup.rb | provider/vendor/gems/builder-2.1.2/lib/builder/xmlmarkup.rb | #!/usr/bin/env ruby
#--
# Copyright 2004, 2005 by Jim Weirich (jim@weirichhouse.org).
# All rights reserved.
# Permission is granted for use, copying, modification, distribution,
# and distribution of modified versions of this work as long as the
# above copyright notice is included.
#++
# Provide a flexible and easy to use Builder for creating XML markup.
# See XmlBuilder for usage details.
require 'builder/xmlbase'
module Builder
# Create XML markup easily. All (well, almost all) methods sent to
# an XmlMarkup object will be translated to the equivalent XML
# markup. Any method with a block will be treated as an XML markup
# tag with nested markup in the block.
#
# Examples will demonstrate this easier than words. In the
# following, +xm+ is an +XmlMarkup+ object.
#
# xm.em("emphasized") # => <em>emphasized</em>
# xm.em { xmm.b("emp & bold") } # => <em><b>emph & bold</b></em>
# xm.a("A Link", "href"=>"http://onestepback.org")
# # => <a href="http://onestepback.org">A Link</a>
# xm.div { br } # => <div><br/></div>
# xm.target("name"=>"compile", "option"=>"fast")
# # => <target option="fast" name="compile"\>
# # NOTE: order of attributes is not specified.
#
# xm.instruct! # <?xml version="1.0" encoding="UTF-8"?>
# xm.html { # <html>
# xm.head { # <head>
# xm.title("History") # <title>History</title>
# } # </head>
# xm.body { # <body>
# xm.comment! "HI" # <!-- HI -->
# xm.h1("Header") # <h1>Header</h1>
# xm.p("paragraph") # <p>paragraph</p>
# } # </body>
# } # </html>
#
# == Notes:
#
# * The order that attributes are inserted in markup tags is
# undefined.
#
# * Sometimes you wish to insert text without enclosing tags. Use
# the <tt>text!</tt> method to accomplish this.
#
# Example:
#
# xm.div { # <div>
# xm.text! "line"; xm.br # line<br/>
# xm.text! "another line"; xmbr # another line<br/>
# } # </div>
#
# * The special XML characters <, >, and & are converted to <,
# > and & automatically. Use the <tt><<</tt> operation to
# insert text without modification.
#
# * Sometimes tags use special characters not allowed in ruby
# identifiers. Use the <tt>tag!</tt> method to handle these
# cases.
#
# Example:
#
# xml.tag!("SOAP:Envelope") { ... }
#
# will produce ...
#
# <SOAP:Envelope> ... </SOAP:Envelope>"
#
# <tt>tag!</tt> will also take text and attribute arguments (after
# the tag name) like normal markup methods. (But see the next
# bullet item for a better way to handle XML namespaces).
#
# * Direct support for XML namespaces is now available. If the
# first argument to a tag call is a symbol, it will be joined to
# the tag to produce a namespace:tag combination. It is easier to
# show this than describe it.
#
# xml.SOAP :Envelope do ... end
#
# Just put a space before the colon in a namespace to produce the
# right form for builder (e.g. "<tt>SOAP:Envelope</tt>" =>
# "<tt>xml.SOAP :Envelope</tt>")
#
# * XmlMarkup builds the markup in any object (called a _target_)
# that accepts the <tt><<</tt> method. If no target is given,
# then XmlMarkup defaults to a string target.
#
# Examples:
#
# xm = Builder::XmlMarkup.new
# result = xm.title("yada")
# # result is a string containing the markup.
#
# buffer = ""
# xm = Builder::XmlMarkup.new(buffer)
# # The markup is appended to buffer (using <<)
#
# xm = Builder::XmlMarkup.new(STDOUT)
# # The markup is written to STDOUT (using <<)
#
# xm = Builder::XmlMarkup.new
# x2 = Builder::XmlMarkup.new(:target=>xm)
# # Markup written to +x2+ will be send to +xm+.
#
# * Indentation is enabled by providing the number of spaces to
# indent for each level as a second argument to XmlBuilder.new.
# Initial indentation may be specified using a third parameter.
#
# Example:
#
# xm = Builder.new(:indent=>2)
# # xm will produce nicely formatted and indented XML.
#
# xm = Builder.new(:indent=>2, :margin=>4)
# # xm will produce nicely formatted and indented XML with 2
# # spaces per indent and an over all indentation level of 4.
#
# builder = Builder::XmlMarkup.new(:target=>$stdout, :indent=>2)
# builder.name { |b| b.first("Jim"); b.last("Weirich) }
# # prints:
# # <name>
# # <first>Jim</first>
# # <last>Weirich</last>
# # </name>
#
# * The instance_eval implementation which forces self to refer to
# the message receiver as self is now obsolete. We now use normal
# block calls to execute the markup block. This means that all
# markup methods must now be explicitly send to the xml builder.
# For instance, instead of
#
# xml.div { strong("text") }
#
# you need to write:
#
# xml.div { xml.strong("text") }
#
# Although more verbose, the subtle change in semantics within the
# block was found to be prone to error. To make this change a
# little less cumbersome, the markup block now gets the markup
# object sent as an argument, allowing you to use a shorter alias
# within the block.
#
# For example:
#
# xml_builder = Builder::XmlMarkup.new
# xml_builder.div { |xml|
# xml.stong("text")
# }
#
class XmlMarkup < XmlBase
# Create an XML markup builder. Parameters are specified by an
# option hash.
#
# :target=><em>target_object</em>::
# Object receiving the markup. +out+ must respond to the
# <tt><<</tt> operator. The default is a plain string target.
#
# :indent=><em>indentation</em>::
# Number of spaces used for indentation. The default is no
# indentation and no line breaks.
#
# :margin=><em>initial_indentation_level</em>::
# Amount of initial indentation (specified in levels, not
# spaces).
#
# :escape_attrs=><b>OBSOLETE</em>::
# The :escape_attrs option is no longer supported by builder
# (and will be quietly ignored). String attribute values are
# now automatically escaped. If you need unescaped attribute
# values (perhaps you are using entities in the attribute
# values), then give the value as a Symbol. This allows much
# finer control over escaping attribute values.
#
def initialize(options={})
indent = options[:indent] || 0
margin = options[:margin] || 0
super(indent, margin)
@target = options[:target] || ""
end
# Return the target of the builder.
def target!
@target
end
def comment!(comment_text)
_ensure_no_block block_given?
_special("<!-- ", " -->", comment_text, nil)
end
# Insert an XML declaration into the XML markup.
#
# For example:
#
# xml.declare! :ELEMENT, :blah, "yada"
# # => <!ELEMENT blah "yada">
def declare!(inst, *args, &block)
_indent
@target << "<!#{inst}"
args.each do |arg|
case arg
when String
@target << %{ "#{arg}"} # " WART
when Symbol
@target << " #{arg}"
end
end
if block_given?
@target << " ["
_newline
_nested_structures(block)
@target << "]"
end
@target << ">"
_newline
end
# Insert a processing instruction into the XML markup. E.g.
#
# For example:
#
# xml.instruct!
# #=> <?xml version="1.0" encoding="UTF-8"?>
# xml.instruct! :aaa, :bbb=>"ccc"
# #=> <?aaa bbb="ccc"?>
#
def instruct!(directive_tag=:xml, attrs={})
_ensure_no_block block_given?
if directive_tag == :xml
a = { :version=>"1.0", :encoding=>"UTF-8" }
attrs = a.merge attrs
end
_special(
"<?#{directive_tag}",
"?>",
nil,
attrs,
[:version, :encoding, :standalone])
end
# Insert a CDATA section into the XML markup.
#
# For example:
#
# xml.cdata!("text to be included in cdata")
# #=> <![CDATA[text to be included in cdata]]>
#
def cdata!(text)
_ensure_no_block block_given?
_special("<![CDATA[", "]]>", text, nil)
end
private
# NOTE: All private methods of a builder object are prefixed when
# a "_" character to avoid possible conflict with XML tag names.
# Insert text directly in to the builder's target.
def _text(text)
@target << text
end
# Insert special instruction.
def _special(open, close, data=nil, attrs=nil, order=[])
_indent
@target << open
@target << data if data
_insert_attributes(attrs, order) if attrs
@target << close
_newline
end
# Start an XML tag. If <tt>end_too</tt> is true, then the start
# tag is also the end tag (e.g. <br/>
def _start_tag(sym, attrs, end_too=false)
@target << "<#{sym}"
_insert_attributes(attrs)
@target << "/" if end_too
@target << ">"
end
# Insert an ending tag.
def _end_tag(sym)
@target << "</#{sym}>"
end
# Insert the attributes (given in the hash).
def _insert_attributes(attrs, order=[])
return if attrs.nil?
order.each do |k|
v = attrs[k]
@target << %{ #{k}="#{_attr_value(v)}"} if v # " WART
end
attrs.each do |k, v|
@target << %{ #{k}="#{_attr_value(v)}"} unless order.member?(k) # " WART
end
end
def _attr_value(value)
case value
when Symbol
value.to_s
else
_escape_quote(value.to_s)
end
end
def _ensure_no_block(got_block)
if got_block
fail IllegalBlockError,
"Blocks are not allowed on XML instructions"
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/builder-2.1.2/lib/builder/xmlbase.rb | provider/vendor/gems/builder-2.1.2/lib/builder/xmlbase.rb | #!/usr/bin/env ruby
require 'builder/blankslate'
module Builder
# Generic error for builder
class IllegalBlockError < RuntimeError; end
# XmlBase is a base class for building XML builders. See
# Builder::XmlMarkup and Builder::XmlEvents for examples.
class XmlBase < BlankSlate
# Create an XML markup builder.
#
# out:: Object receiving the markup. +out+ must respond to
# <tt><<</tt>.
# indent:: Number of spaces used for indentation (0 implies no
# indentation and no line breaks).
# initial:: Level of initial indentation.
#
def initialize(indent=0, initial=0)
@indent = indent
@level = initial
end
# Create a tag named +sym+. Other than the first argument which
# is the tag name, the arguements are the same as the tags
# implemented via <tt>method_missing</tt>.
def tag!(sym, *args, &block)
method_missing(sym.to_sym, *args, &block)
end
# Create XML markup based on the name of the method. This method
# is never invoked directly, but is called for each markup method
# in the markup block.
def method_missing(sym, *args, &block)
text = nil
attrs = nil
sym = "#{sym}:#{args.shift}" if args.first.kind_of?(Symbol)
args.each do |arg|
case arg
when Hash
attrs ||= {}
attrs.merge!(arg)
else
text ||= ''
text << arg.to_s
end
end
if block
unless text.nil?
raise ArgumentError, "XmlMarkup cannot mix a text argument with a block"
end
_indent
_start_tag(sym, attrs)
_newline
_nested_structures(block)
_indent
_end_tag(sym)
_newline
elsif text.nil?
_indent
_start_tag(sym, attrs, true)
_newline
else
_indent
_start_tag(sym, attrs)
text! text
_end_tag(sym)
_newline
end
@target
end
# Append text to the output target. Escape any markup. May be
# used within the markup brakets as:
#
# builder.p { |b| b.br; b.text! "HI" } #=> <p><br/>HI</p>
def text!(text)
_text(_escape(text))
end
# Append text to the output target without escaping any markup.
# May be used within the markup brakets as:
#
# builder.p { |x| x << "<br/>HI" } #=> <p><br/>HI</p>
#
# This is useful when using non-builder enabled software that
# generates strings. Just insert the string directly into the
# builder without changing the inserted markup.
#
# It is also useful for stacking builder objects. Builders only
# use <tt><<</tt> to append to the target, so by supporting this
# method/operation builders can use other builders as their
# targets.
def <<(text)
_text(text)
end
# For some reason, nil? is sent to the XmlMarkup object. If nil?
# is not defined and method_missing is invoked, some strange kind
# of recursion happens. Since nil? won't ever be an XML tag, it
# is pretty safe to define it here. (Note: this is an example of
# cargo cult programming,
# cf. http://fishbowl.pastiche.org/2004/10/13/cargo_cult_programming).
def nil?
false
end
private
require 'builder/xchar'
def _escape(text)
text.to_xs
end
def _escape_quote(text)
_escape(text).gsub(%r{"}, '"') # " WART
end
def _newline
return if @indent == 0
text! "\n"
end
def _indent
return if @indent == 0 || @level == 0
text!(" " * (@level * @indent))
end
def _nested_structures(block)
@level += 1
block.call(self)
ensure
@level -= 1
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/builder-2.1.2/lib/builder/xchar.rb | provider/vendor/gems/builder-2.1.2/lib/builder/xchar.rb | #!/usr/bin/env ruby
# The XChar library is provided courtesy of Sam Ruby (See
# http://intertwingly.net/stories/2005/09/28/xchar.rb)
# --------------------------------------------------------------------
# If the Builder::XChar module is not currently defined, fail on any
# name clashes in standard library classes.
module Builder
def self.check_for_name_collision(klass, method_name, defined_constant=nil)
if klass.instance_methods.include?(method_name)
fail RuntimeError,
"Name Collision: Method '#{method_name}' is already defined in #{klass}"
end
end
end
if ! defined?(Builder::XChar)
Builder.check_for_name_collision(String, "to_xs")
Builder.check_for_name_collision(Fixnum, "xchr")
end
######################################################################
module Builder
####################################################################
# XML Character converter, from Sam Ruby:
# (see http://intertwingly.net/stories/2005/09/28/xchar.rb).
#
module XChar # :nodoc:
# See
# http://intertwingly.net/stories/2004/04/14/i18n.html#CleaningWindows
# for details.
CP1252 = { # :nodoc:
128 => 8364, # euro sign
130 => 8218, # single low-9 quotation mark
131 => 402, # latin small letter f with hook
132 => 8222, # double low-9 quotation mark
133 => 8230, # horizontal ellipsis
134 => 8224, # dagger
135 => 8225, # double dagger
136 => 710, # modifier letter circumflex accent
137 => 8240, # per mille sign
138 => 352, # latin capital letter s with caron
139 => 8249, # single left-pointing angle quotation mark
140 => 338, # latin capital ligature oe
142 => 381, # latin capital letter z with caron
145 => 8216, # left single quotation mark
146 => 8217, # right single quotation mark
147 => 8220, # left double quotation mark
148 => 8221, # right double quotation mark
149 => 8226, # bullet
150 => 8211, # en dash
151 => 8212, # em dash
152 => 732, # small tilde
153 => 8482, # trade mark sign
154 => 353, # latin small letter s with caron
155 => 8250, # single right-pointing angle quotation mark
156 => 339, # latin small ligature oe
158 => 382, # latin small letter z with caron
159 => 376, # latin capital letter y with diaeresis
}
# See http://www.w3.org/TR/REC-xml/#dt-chardata for details.
PREDEFINED = {
38 => '&', # ampersand
60 => '<', # left angle bracket
62 => '>', # right angle bracket
}
# See http://www.w3.org/TR/REC-xml/#charsets for details.
VALID = [
0x9, 0xA, 0xD,
(0x20..0xD7FF),
(0xE000..0xFFFD),
(0x10000..0x10FFFF)
]
end
end
######################################################################
# Enhance the Fixnum class with a XML escaped character conversion.
#
class Fixnum
XChar = Builder::XChar if ! defined?(XChar)
# XML escaped version of chr
def xchr
n = XChar::CP1252[self] || self
case n when *XChar::VALID
XChar::PREDEFINED[n] or (n<128 ? n.chr : "&##{n};")
else
'*'
end
end
end
######################################################################
# Enhance the String class with a XML escaped character version of
# to_s.
#
class String
# XML escaped version of to_s
def to_xs
unpack('U*').map {|n| n.xchr}.join # ASCII, UTF-8
rescue
unpack('C*').map {|n| n.xchr}.join # ISO-8859-1, WIN-1252
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/builder-2.1.2/lib/builder/blankslate.rb | provider/vendor/gems/builder-2.1.2/lib/builder/blankslate.rb | #!/usr/bin/env ruby
#--
# Copyright 2004, 2006 by Jim Weirich (jim@weirichhouse.org).
# All rights reserved.
# Permission is granted for use, copying, modification, distribution,
# and distribution of modified versions of this work as long as the
# above copyright notice is included.
#++
require 'blankslate'
######################################################################
# BlankSlate has been promoted to a top level name and is now
# available as a standalone gem. We make the name available in the
# Builder namespace for compatibility.
#
module Builder
BlankSlate = ::BlankSlate
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/ci_reporter-1.6.2/spec/spec_helper.rb | provider/vendor/gems/ci_reporter-1.6.2/spec/spec_helper.rb | # Copyright (c) 2006-2010 Nick Sieger <nicksieger@gmail.com>
# See the file LICENSE.txt included with the distribution for
# software license details.
require 'rubygems'
gem 'rspec'
require 'spec'
unless defined?(CI_REPORTER_LIB)
CI_REPORTER_LIB = File.expand_path(File.dirname(__FILE__) + "/../lib")
$: << CI_REPORTER_LIB
end
require 'ci/reporter/core'
require 'ci/reporter/test_unit'
require 'ci/reporter/rspec'
REPORTS_DIR = File.dirname(__FILE__) + "/reports" unless defined?(REPORTS_DIR)
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/ci_reporter-1.6.2/spec/ci/reporter/cucumber_spec.rb | provider/vendor/gems/ci_reporter-1.6.2/spec/ci/reporter/cucumber_spec.rb | # Copyright (c) 2006-2010 Nick Sieger <nicksieger@gmail.com>
# See the file LICENSE.txt included with the distribution for
# software license details.
require File.dirname(__FILE__) + "/../../spec_helper.rb"
require 'ci/reporter/cucumber'
describe "The Cucumber reporter" do
describe CI::Reporter::CucumberFailure do
before(:each) do
@klass = mock("class")
@klass.stub!(:name).and_return("Exception name")
@exception = mock("exception")
@exception.stub!(:class).and_return(@klass)
@exception.stub!(:message).and_return("Exception message")
@exception.stub!(:backtrace).and_return(["First line", "Second line"])
@step = mock("step")
@step.stub!(:exception).and_return(@exception)
@cucumber_failure = CI::Reporter::CucumberFailure.new(@step)
end
it "should always return true for failure?" do
@cucumber_failure.should be_failure
end
it "should always return false for error?" do
@cucumber_failure.should_not be_error
end
it "should propagate the name as the underlying exception's class name" do
@step.should_receive(:exception)
@exception.should_receive(:class)
@klass.should_receive(:name)
@cucumber_failure.name.should == "Exception name"
end
it "should propagate the message as the underlying exception's message" do
@step.should_receive(:exception)
@exception.should_receive(:message)
@cucumber_failure.message.should == "Exception message"
end
it "should propagate and format the exception's backtrace" do
@step.should_receive(:exception)
@exception.should_receive(:backtrace)
@cucumber_failure.location.should == "First line\nSecond line"
end
end
describe CI::Reporter::Cucumber do
before(:each) do
@step_mother = mock("step_mother")
@io = mock("io")
@report_manager = mock("report_manager")
CI::Reporter::ReportManager.stub!(:new).and_return(@report_manager)
end
def new_instance
CI::Reporter::Cucumber.new(@step_mother, @io, {})
end
it "should create a new report manager to report on test success/failure" do
CI::Reporter::ReportManager.should_receive(:new)
new_instance
end
it "should record the feature name when a new feature is visited" do
cucumber = new_instance
cucumber.visit_feature_name("Some feature name")
cucumber.feature_name.should == "Some feature name"
end
it "should record only the first line of a feature name" do
cucumber = new_instance
cucumber.visit_feature_name("Some feature name\nLonger description")
cucumber.feature_name.should == "Some feature name"
end
describe "when visiting a new scenario" do
before(:each) do
@cucumber = new_instance
@cucumber.visit_feature_name("Demo feature")
@test_suite = mock("test_suite", :start => nil, :finish => nil)
CI::Reporter::TestSuite.stub!(:new).and_return(@test_suite)
@feature_element = mock("feature_element", :accept => true)
@report_manager.stub!(:write_report)
end
it "should create a new test suite" do
# FIXME: @name is feature_element purely as a by-product of the
# mocking framework implementation. But then again, using
# +instance_variable_get+ in the first place is a bit icky.
CI::Reporter::TestSuite.should_receive(:new).with("Demo feature feature_element")
@cucumber.visit_feature_element(@feature_element)
end
it "should indicate that the test suite has started" do
@test_suite.should_receive(:start)
@cucumber.visit_feature_element(@feature_element)
end
it "should indicate that the test suite has finished" do
@test_suite.should_receive(:finish)
@cucumber.visit_feature_element(@feature_element)
end
it "should ask the report manager to write a report" do
@report_manager.should_receive(:write_report).with(@test_suite)
@cucumber.visit_feature_element(@feature_element)
end
end
describe "when visiting a step inside a scenario" do
before(:each) do
@testcases = []
@test_suite = mock("test_suite", :testcases => @testcases)
@cucumber = new_instance
@cucumber.stub!(:test_suite).and_return(@test_suite)
@test_case = mock("test_case", :start => nil, :finish => nil, :name => "Step Name")
CI::Reporter::TestCase.stub!(:new).and_return(@test_case)
@step = mock("step", :accept => true, :status => :passed)
@step.stub!(:name).and_return("Step Name")
end
it "should create a new test case" do
CI::Reporter::TestCase.should_receive(:new).with("Step Name")
@cucumber.visit_step(@step)
end
it "should indicate that the test case has started" do
@test_case.should_receive(:start)
@cucumber.visit_step(@step)
end
it "should indicate that the test case has finished" do
@test_case.should_receive(:finish)
@cucumber.visit_step(@step)
end
it "should add the test case to the suite's list of cases" do
@testcases.should be_empty
@cucumber.visit_step(@step)
@testcases.should_not be_empty
@testcases.first.should == @test_case
end
it "should alter the name of a test case that is pending to include '(PENDING)'" do
@step.stub!(:status).and_return(:pending)
@test_case.should_receive(:name=).with("Step Name (PENDING)")
@cucumber.visit_step(@step)
end
it "should alter the name of a test case that is undefined to include '(PENDING)'" do
@step.stub!(:status).and_return(:undefined)
@test_case.should_receive(:name=).with("Step Name (PENDING)")
@cucumber.visit_step(@step)
end
it "should alter the name of a test case that was skipped to include '(SKIPPED)'" do
@step.stub!(:status).and_return(:skipped)
@test_case.should_receive(:name=).with("Step Name (SKIPPED)")
@cucumber.visit_step(@step)
end
describe "that fails" do
before(:each) do
@step.stub!(:status).and_return(:failed)
@failures = []
@test_case.stub!(:failures).and_return(@failures)
@cucumber_failure = mock("cucumber_failure")
CI::Reporter::CucumberFailure.stub!(:new).and_return(@cucumber_failure)
end
it "should create a new cucumber failure with that step" do
CI::Reporter::CucumberFailure.should_receive(:new).with(@step)
@cucumber.visit_step(@step)
end
it "should add the failure to the suite's list of failures" do
@failures.should be_empty
@cucumber.visit_step(@step)
@failures.should_not be_empty
@failures.first.should == @cucumber_failure
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/ci_reporter-1.6.2/spec/ci/reporter/output_capture_spec.rb | provider/vendor/gems/ci_reporter-1.6.2/spec/ci/reporter/output_capture_spec.rb | # Copyright (c) 2006-2010 Nick Sieger <nicksieger@gmail.com>
# See the file LICENSE.txt included with the distribution for
# software license details.
require File.dirname(__FILE__) + "/../../spec_helper.rb"
require 'rexml/document'
describe "Output capture" do
before(:each) do
@suite = CI::Reporter::TestSuite.new "test"
end
it "should save stdout and stderr messages written during the test run" do
@suite.start
puts "Hello"
$stderr.print "Hi"
@suite.finish
@suite.stdout.should == "Hello\n"
@suite.stderr.should == "Hi"
end
it "should include system-out and system-err elements in the xml output" do
@suite.start
puts "Hello"
$stderr.print "Hi"
@suite.finish
root = REXML::Document.new(@suite.to_xml).root
root.elements.to_a('//system-out').length.should == 1
root.elements.to_a('//system-err').length.should == 1
root.elements.to_a('//system-out').first.texts.first.to_s.strip.should == "Hello"
root.elements.to_a('//system-err').first.texts.first.to_s.strip.should == "Hi"
end
it "should return $stdout and $stderr to original value after finish" do
out, err = $stdout, $stderr
@suite.start
$stdout.object_id.should_not == out.object_id
$stderr.object_id.should_not == err.object_id
@suite.finish
$stdout.object_id.should == out.object_id
$stderr.object_id.should == err.object_id
end
it "should capture only during run of owner test suite" do
$stdout.print "A"
$stderr.print "A"
@suite.start
$stdout.print "B"
$stderr.print "B"
@suite.finish
$stdout.print "C"
$stderr.print "C"
@suite.stdout.should == "B"
@suite.stderr.should == "B"
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/ci_reporter-1.6.2/spec/ci/reporter/report_manager_spec.rb | provider/vendor/gems/ci_reporter-1.6.2/spec/ci/reporter/report_manager_spec.rb | # Copyright (c) 2006-2010 Nick Sieger <nicksieger@gmail.com>
# See the file LICENSE.txt included with the distribution for
# software license details.
require File.dirname(__FILE__) + "/../../spec_helper.rb"
describe "The ReportManager" do
before(:each) do
@reports_dir = REPORTS_DIR
end
after(:each) do
FileUtils.rm_rf @reports_dir
ENV["CI_REPORTS"] = nil
end
it "should create the report directory according to the given prefix" do
CI::Reporter::ReportManager.new("spec")
File.directory?(@reports_dir).should be_true
end
it "should create the report directory based on CI_REPORTS environment variable if set" do
@reports_dir = "#{Dir.getwd}/dummy"
ENV["CI_REPORTS"] = @reports_dir
CI::Reporter::ReportManager.new("spec")
File.directory?(@reports_dir).should be_true
end
it "should write reports based on name and xml content of a test suite" do
reporter = CI::Reporter::ReportManager.new("spec")
suite = mock("test suite")
suite.should_receive(:name).and_return("some test suite name")
suite.should_receive(:to_xml).and_return("<xml></xml>")
reporter.write_report(suite)
filename = "#{REPORTS_DIR}/SPEC-some-test-suite-name.xml"
File.exist?(filename).should be_true
File.open(filename) {|f| f.read.should == "<xml></xml>"}
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/ci_reporter-1.6.2/spec/ci/reporter/rspec_spec.rb | provider/vendor/gems/ci_reporter-1.6.2/spec/ci/reporter/rspec_spec.rb | # Copyright (c) 2006-2010 Nick Sieger <nicksieger@gmail.com>
# See the file LICENSE.txt included with the distribution for
# software license details.
require File.dirname(__FILE__) + "/../../spec_helper.rb"
require 'stringio'
describe "The RSpec reporter" do
before(:each) do
@error = mock("error")
@error.stub!(:expectation_not_met?).and_return(false)
@error.stub!(:pending_fixed?).and_return(false)
@report_mgr = mock("report manager")
@options = mock("options")
@args = [@options, StringIO.new("")]
@args.shift if Spec::VERSION::MAJOR == 1 && Spec::VERSION::MINOR < 1
@fmt = CI::Reporter::RSpec.new *@args
@fmt.report_manager = @report_mgr
@formatter = mock("formatter")
@fmt.formatter = @formatter
end
it "should use a progress bar formatter by default" do
fmt = CI::Reporter::RSpec.new *@args
fmt.formatter.should be_instance_of(Spec::Runner::Formatter::ProgressBarFormatter)
end
it "should use a specdoc formatter for RSpecDoc" do
fmt = CI::Reporter::RSpecDoc.new *@args
fmt.formatter.should be_instance_of(Spec::Runner::Formatter::SpecdocFormatter)
end
it "should create a test suite with one success, one failure, and one pending" do
@report_mgr.should_receive(:write_report).and_return do |suite|
suite.testcases.length.should == 3
suite.testcases[0].should_not be_failure
suite.testcases[0].should_not be_error
suite.testcases[1].should be_error
suite.testcases[2].name.should =~ /\(PENDING\)/
end
example_group = mock "example group"
example_group.stub!(:description).and_return "A context"
@formatter.should_receive(:start).with(3)
@formatter.should_receive(:example_group_started).with(example_group)
@formatter.should_receive(:example_started).exactly(3).times
@formatter.should_receive(:example_passed).once
@formatter.should_receive(:example_failed).once
@formatter.should_receive(:example_pending).once
@formatter.should_receive(:start_dump).once
@formatter.should_receive(:dump_failure).once
@formatter.should_receive(:dump_summary).once
@formatter.should_receive(:dump_pending).once
@formatter.should_receive(:close).once
@fmt.start(3)
@fmt.example_group_started(example_group)
@fmt.example_started("should pass")
@fmt.example_passed("should pass")
@fmt.example_started("should fail")
@fmt.example_failed("should fail", 1, @error)
@fmt.example_started("should be pending")
@fmt.example_pending("A context", "should be pending", "Not Yet Implemented")
@fmt.start_dump
@fmt.dump_failure(1, mock("failure"))
@fmt.dump_summary(0.1, 3, 1, 1)
@fmt.dump_pending
@fmt.close
end
it "should support RSpec 1.0.8 #add_behavior" do
@formatter.should_receive(:start)
@formatter.should_receive(:add_behaviour).with("A context")
@formatter.should_receive(:example_started).once
@formatter.should_receive(:example_passed).once
@formatter.should_receive(:dump_summary)
@report_mgr.should_receive(:write_report)
@fmt.start(2)
@fmt.add_behaviour("A context")
@fmt.example_started("should pass")
@fmt.example_passed("should pass")
@fmt.dump_summary(0.1, 1, 0, 0)
end
it "should use the example #description method when available" do
group = mock "example group"
group.stub!(:description).and_return "group description"
example = mock "example"
example.stub!(:description).and_return "should do something"
@formatter.should_receive(:start)
@formatter.should_receive(:example_group_started).with(group)
@formatter.should_receive(:example_started).with(example).once
@formatter.should_receive(:example_passed).once
@formatter.should_receive(:dump_summary)
@report_mgr.should_receive(:write_report).and_return do |suite|
suite.testcases.last.name.should == "should do something"
end
@fmt.start(2)
@fmt.example_group_started(group)
@fmt.example_started(example)
@fmt.example_passed(example)
@fmt.dump_summary(0.1, 1, 0, 0)
end
it "should create a test suite with failure in before(:all)" do
example_group = mock "example group"
example_group.stub!(:description).and_return "A context"
@formatter.should_receive(:start)
@formatter.should_receive(:example_group_started).with(example_group)
@formatter.should_receive(:example_started).once
@formatter.should_receive(:example_failed).once
@formatter.should_receive(:dump_summary)
@report_mgr.should_receive(:write_report)
@fmt.start(2)
@fmt.example_group_started(example_group)
@fmt.example_failed("should fail", 1, @error)
@fmt.dump_summary(0.1, 1, 0, 0)
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/ci_reporter-1.6.2/spec/ci/reporter/test_suite_spec.rb | provider/vendor/gems/ci_reporter-1.6.2/spec/ci/reporter/test_suite_spec.rb | # Copyright (c) 2006-2010 Nick Sieger <nicksieger@gmail.com>
# See the file LICENSE.txt included with the distribution for
# software license details.
require File.dirname(__FILE__) + "/../../spec_helper.rb"
require 'rexml/document'
describe "A TestSuite" do
before(:each) do
@suite = CI::Reporter::TestSuite.new("example suite")
end
it "should collect timings when start and finish are invoked in sequence" do
@suite.start
@suite.finish
@suite.time.should >= 0
end
it "should aggregate tests" do
@suite.start
@suite.testcases << CI::Reporter::TestCase.new("example test")
@suite.finish
@suite.tests.should == 1
end
it "should stringify the name for cases when the object passed in is not a string" do
name = Object.new
def name.to_s; "object name"; end
CI::Reporter::TestSuite.new(name).name.should == "object name"
end
it "should indicate number of failures and errors" do
failure = mock("failure")
failure.stub!(:failure?).and_return true
failure.stub!(:error?).and_return false
error = mock("error")
error.stub!(:failure?).and_return false
error.stub!(:error?).and_return true
@suite.start
@suite.testcases << CI::Reporter::TestCase.new("example test")
@suite.testcases << CI::Reporter::TestCase.new("failure test")
@suite.testcases.last.failures << failure
@suite.testcases << CI::Reporter::TestCase.new("error test")
@suite.testcases.last.failures << error
@suite.finish
@suite.tests.should == 3
@suite.failures.should == 1
@suite.errors.should == 1
end
end
describe "TestSuite xml" do
before(:each) do
@suite = CI::Reporter::TestSuite.new("example suite")
@suite.assertions = 11
begin
raise StandardError, "an exception occurred"
rescue => e
@exception = e
end
end
it "should contain Ant/JUnit-formatted description of entire suite" do
failure = mock("failure")
failure.stub!(:failure?).and_return true
failure.stub!(:error?).and_return false
failure.stub!(:name).and_return "failure"
failure.stub!(:message).and_return "There was a failure"
failure.stub!(:location).and_return @exception.backtrace.join("\n")
error = mock("error")
error.stub!(:failure?).and_return false
error.stub!(:error?).and_return true
error.stub!(:name).and_return "error"
error.stub!(:message).and_return "There was a error"
error.stub!(:location).and_return @exception.backtrace.join("\n")
@suite.start
@suite.testcases << CI::Reporter::TestCase.new("example test")
@suite.testcases << CI::Reporter::TestCase.new("skipped test").tap {|tc| tc.skipped = true }
@suite.testcases << CI::Reporter::TestCase.new("failure test")
@suite.testcases.last.failures << failure
@suite.testcases << CI::Reporter::TestCase.new("error test")
@suite.testcases.last.failures << error
@suite.finish
xml = @suite.to_xml
doc = REXML::Document.new(xml)
testsuite = doc.root.elements.to_a("/testsuite")
testsuite.length.should == 1
testsuite = testsuite.first
testsuite.attributes["name"].should == "example suite"
testsuite.attributes["assertions"].should == "11"
testcases = testsuite.elements.to_a("testcase")
testcases.length.should == 4
end
it "should contain full exception type and message in location element" do
failure = mock("failure")
failure.stub!(:failure?).and_return true
failure.stub!(:error?).and_return false
failure.stub!(:name).and_return "failure"
failure.stub!(:message).and_return "There was a failure"
failure.stub!(:location).and_return @exception.backtrace.join("\n")
@suite.start
@suite.testcases << CI::Reporter::TestCase.new("example test")
@suite.testcases << CI::Reporter::TestCase.new("failure test")
@suite.testcases.last.failures << failure
@suite.finish
xml = @suite.to_xml
doc = REXML::Document.new(xml)
elem = doc.root.elements.to_a("/testsuite/testcase[@name='failure test']/failure").first
location = elem.texts.join
location.should =~ Regexp.new(failure.message)
location.should =~ Regexp.new(failure.name)
end
it "should filter attributes properly for invalid characters" do
failure = mock("failure")
failure.stub!(:failure?).and_return true
failure.stub!(:error?).and_return false
failure.stub!(:name).and_return "failure"
failure.stub!(:message).and_return "There was a <failure>\nReason: blah"
failure.stub!(:location).and_return @exception.backtrace.join("\n")
@suite.start
@suite.testcases << CI::Reporter::TestCase.new("failure test")
@suite.testcases.last.failures << failure
@suite.finish
xml = @suite.to_xml
xml.should =~ %r/message="There was a <failure>\.\.\."/
end
end
describe "A TestCase" do
before(:each) do
@tc = CI::Reporter::TestCase.new("example test")
end
it "should collect timings when start and finish are invoked in sequence" do
@tc.start
@tc.finish
@tc.time.should >= 0
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/ci_reporter-1.6.2/spec/ci/reporter/test_unit_spec.rb | provider/vendor/gems/ci_reporter-1.6.2/spec/ci/reporter/test_unit_spec.rb | # Copyright (c) 2006-2010 Nick Sieger <nicksieger@gmail.com>
# See the file LICENSE.txt included with the distribution for
# software license details.
require File.dirname(__FILE__) + "/../../spec_helper.rb"
describe "The TestUnit reporter" do
before(:each) do
@report_mgr = mock("report manager")
@testunit = CI::Reporter::TestUnit.new(nil, @report_mgr)
@result = mock("result")
@result.stub!(:assertion_count).and_return(7)
end
it "should build suites based on adjacent tests with the same class name" do
@suite = nil
@report_mgr.should_receive(:write_report).once.and_return {|suite| @suite = suite }
@testunit.started(@result)
@testunit.test_started("test_one(TestCaseClass)")
@testunit.test_finished("test_one(TestCaseClass)")
@testunit.test_started("test_two(TestCaseClass)")
@testunit.test_finished("test_two(TestCaseClass)")
@testunit.finished(10)
@suite.name.should == "TestCaseClass"
@suite.testcases.length.should == 2
@suite.testcases.first.name.should == "test_one"
@suite.testcases.first.should_not be_failure
@suite.testcases.first.should_not be_error
@suite.testcases.last.name.should == "test_two"
@suite.testcases.last.should_not be_failure
@suite.testcases.last.should_not be_error
end
it "should build two suites when encountering different class names" do
@suites = []
@report_mgr.should_receive(:write_report).twice.and_return {|suite| @suites << suite }
@testunit.started(@result)
@testunit.test_started("test_one(TestCaseClass)")
@testunit.test_finished("test_one(TestCaseClass)")
@testunit.test_started("test_two(AnotherTestCaseClass)")
@testunit.test_finished("test_two(AnotherTestCaseClass)")
@testunit.finished(10)
@suites.first.name.should == "TestCaseClass"
@suites.first.testcases.length.should == 1
@suites.first.testcases.first.name.should == "test_one"
@suites.first.testcases.first.assertions.should == 7
@suites.last.name.should == "AnotherTestCaseClass"
@suites.last.testcases.length.should == 1
@suites.last.testcases.first.name.should == "test_two"
@suites.last.testcases.first.assertions.should == 0
end
it "should record assertion counts during test run" do
@suite = nil
@report_mgr.should_receive(:write_report).and_return {|suite| @suite = suite }
@testunit.started(@result)
@testunit.test_started("test_one(TestCaseClass)")
@testunit.test_finished("test_one(TestCaseClass)")
@testunit.finished(10)
@suite.assertions.should == 7
@suite.testcases.last.assertions.should == 7
end
it "should add failures to testcases when encountering a fault" do
@failure = Test::Unit::Failure.new("test_one(TestCaseClass)", "somewhere:10", "it failed")
@suite = nil
@report_mgr.should_receive(:write_report).once.and_return {|suite| @suite = suite }
@testunit.started(@result)
@testunit.test_started("test_one(TestCaseClass)")
@testunit.fault(@failure)
@testunit.test_finished("test_one(TestCaseClass)")
@testunit.finished(10)
@suite.name.should == "TestCaseClass"
@suite.testcases.length.should == 1
@suite.testcases.first.name.should == "test_one"
@suite.testcases.first.should be_failure
end
it "should add errors to testcases when encountering a fault" do
begin
raise StandardError, "error"
rescue => e
@error = Test::Unit::Error.new("test_two(TestCaseClass)", e)
end
@suite = nil
@report_mgr.should_receive(:write_report).once.and_return {|suite| @suite = suite }
@testunit.started(@result)
@testunit.test_started("test_one(TestCaseClass)")
@testunit.test_finished("test_one(TestCaseClass)")
@testunit.test_started("test_two(TestCaseClass)")
@testunit.fault(@error)
@testunit.test_finished("test_two(TestCaseClass)")
@testunit.finished(10)
@suite.name.should == "TestCaseClass"
@suite.testcases.length.should == 2
@suite.testcases.first.name.should == "test_one"
@suite.testcases.first.should_not be_failure
@suite.testcases.first.should_not be_error
@suite.testcases.last.name.should == "test_two"
@suite.testcases.last.should_not be_failure
@suite.testcases.last.should be_error
end
it "should add multiple failures to a testcase" do
@failure1 = Test::Unit::Failure.new("test_one(TestCaseClass)", "somewhere:10", "it failed")
@failure2 = Test::Unit::Failure.new("test_one(TestCaseClass)", "somewhere:12", "it failed again in teardown")
@suite = nil
@report_mgr.should_receive(:write_report).once.and_return {|suite| @suite = suite }
@testunit.started(@result)
@testunit.test_started("test_one(TestCaseClass)")
@testunit.fault(@failure1)
@testunit.fault(@failure2)
@testunit.test_finished("test_one(TestCaseClass)")
@testunit.finished(10)
@suite.name.should == "TestCaseClass"
@suite.testcases.length.should == 1
@suite.testcases.first.name.should == "test_one"
@suite.testcases.first.should be_failure
@suite.testcases.first.failures.size.should == 2
@suite.failures.should == 2
end
it "should count test case names that don't conform to the standard pattern" do
@suite = nil
@report_mgr.should_receive(:write_report).once.and_return {|suite| @suite = suite }
@testunit.started(@result)
@testunit.test_started("some unknown test")
@testunit.test_finished("some unknown test")
@testunit.finished(10)
@suite.name.should == "unknown-1"
@suite.testcases.length.should == 1
@suite.testcases.first.name.should == "some unknown test"
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/ci_reporter-1.6.2/spec/ci/reporter/rake/rake_tasks_spec.rb | provider/vendor/gems/ci_reporter-1.6.2/spec/ci/reporter/rake/rake_tasks_spec.rb | # Copyright (c) 2006-2010 Nick Sieger <nicksieger@gmail.com>
# See the file LICENSE.txt included with the distribution for
# software license details.
require File.dirname(__FILE__) + "/../../../spec_helper.rb"
require 'rake'
def save_env(v)
ENV["PREV_#{v}"] = ENV[v]
end
def restore_env(v)
ENV[v] = ENV["PREV_#{v}"]
ENV.delete("PREV_#{v}")
end
describe "ci_reporter ci:setup:testunit task" do
before(:each) do
@rake = Rake::Application.new
Rake.application = @rake
load CI_REPORTER_LIB + '/ci/reporter/rake/test_unit.rb'
save_env "CI_REPORTS"
save_env "TESTOPTS"
ENV["CI_REPORTS"] = "some-bogus-nonexistent-directory-that-wont-fail-rm_rf"
end
after(:each) do
restore_env "TESTOPTS"
restore_env "CI_REPORTS"
Rake.application = nil
end
it "should set ENV['TESTOPTS'] to include test/unit setup file" do
@rake["ci:setup:testunit"].invoke
ENV["TESTOPTS"].should =~ /test_unit_loader/
end
it "should append to ENV['TESTOPTS'] if it already contains a value" do
ENV["TESTOPTS"] = "somevalue".freeze
@rake["ci:setup:testunit"].invoke
ENV["TESTOPTS"].should =~ /somevalue.*test_unit_loader/
end
end
describe "ci_reporter ci:setup:rspec task" do
before(:each) do
@rake = Rake::Application.new
Rake.application = @rake
load CI_REPORTER_LIB + '/ci/reporter/rake/rspec.rb'
save_env "CI_REPORTS"
save_env "SPEC_OPTS"
ENV["CI_REPORTS"] = "some-bogus-nonexistent-directory-that-wont-fail-rm_rf"
end
after(:each) do
restore_env "SPEC_OPTS"
restore_env "CI_REPORTS"
Rake.application = nil
end
it "should set ENV['SPEC_OPTS'] to include rspec formatter args" do
@rake["ci:setup:rspec"].invoke
ENV["SPEC_OPTS"].should =~ /--require.*rspec_loader.*--format.*CI::Reporter::RSpec/
end
it "should set ENV['SPEC_OPTS'] to include rspec doc formatter if task is ci:setup:rspecdoc" do
@rake["ci:setup:rspecdoc"].invoke
ENV["SPEC_OPTS"].should =~ /--require.*rspec_loader.*--format.*CI::Reporter::RSpecDoc/
end
it "should append to ENV['SPEC_OPTS'] if it already contains a value" do
ENV["SPEC_OPTS"] = "somevalue".freeze
@rake["ci:setup:rspec"].invoke
ENV["SPEC_OPTS"].should =~ /somevalue.*--require.*rspec_loader.*--format.*CI::Reporter::RSpec/
end
end
describe "ci_reporter ci:setup:cucumber task" do
before(:each) do
@rake = Rake::Application.new
Rake.application = @rake
load CI_REPORTER_LIB + '/ci/reporter/rake/cucumber.rb'
save_env "CI_REPORTS"
save_env "CUCUMBER_OPTS"
ENV["CI_REPORTS"] = "some-bogus-nonexistent-directory-that-wont-fail-rm_rf"
end
after(:each) do
restore_env "CUCUMBER_OPTS"
restore_env "CI_REPORTS"
Rake.application = nil
end
it "should set ENV['CUCUMBER_OPTS'] to include cucumber formatter args" do
@rake["ci:setup:cucumber"].invoke
ENV["CUCUMBER_OPTS"].should =~ /--require.*cucumber_loader.*--format.*CI::Reporter::Cucumber/
end
it "should append to ENV['CUCUMBER_OPTS'] if it already contains a value" do
ENV["CUCUMBER_OPTS"] = "somevalue".freeze
@rake["ci:setup:cucumber"].invoke
ENV["CUCUMBER_OPTS"].should =~ /somevalue.*--require.*cucumber_loader.*--format.*CI::Reporter::Cucumber/
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/core.rb | provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/core.rb | # Copyright (c) 2006-2010 Nick Sieger <nicksieger@gmail.com>
# See the file LICENSE.txt included with the distribution for
# software license details.
require 'ci/reporter/test_suite'
require 'ci/reporter/report_manager'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/cucumber.rb | provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/cucumber.rb | # Copyright (c) 2006-2010 Nick Sieger <nicksieger@gmail.com>
# See the file LICENSE.txt included with the distribution for
# software license details.
require 'ci/reporter/core'
tried_gem = false
begin
require 'cucumber'
require 'cucumber/ast/visitor'
rescue LoadError
unless tried_gem
tried_gem = true
require 'rubygems'
gem 'cucumber'
retry
end
end
module CI
module Reporter
class CucumberFailure
attr_reader :step
def initialize(step)
@step = step
end
def failure?
true
end
def error?
!failure?
end
def name
step.exception.class.name
end
def message
step.exception.message
end
def location
step.exception.backtrace.join("\n")
end
end
class Cucumber < ::Cucumber::Ast::Visitor
attr_accessor :test_suite, :report_manager, :feature_name
def initialize(step_mother, io, options)
self.report_manager = ReportManager.new("features")
super(step_mother)
end
def visit_feature_name(name)
self.feature_name = name.split("\n").first
super
end
def visit_feature_element(feature_element)
self.test_suite = TestSuite.new("#{feature_name} #{feature_element.instance_variable_get("@name")}")
test_suite.start
return_value = super
test_suite.finish
report_manager.write_report(test_suite)
self.test_suite = nil
return_value
end
def visit_step(step)
test_case = TestCase.new(step.name)
test_case.start
return_value = super
test_case.finish
case step.status
when :pending, :undefined
test_case.name = "#{test_case.name} (PENDING)"
when :skipped
test_case.name = "#{test_case.name} (SKIPPED)"
when :failed
test_case.failures << CucumberFailure.new(step)
end
test_suite.testcases << test_case
return_value
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/version.rb | provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/version.rb | module CI
module Reporter
VERSION = "1.6.2"
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/test_unit.rb | provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/test_unit.rb | # Copyright (c) 2006-2010 Nick Sieger <nicksieger@gmail.com>
# See the file LICENSE.txt included with the distribution for
# software license details.
require 'ci/reporter/core'
require 'test/unit'
require 'test/unit/ui/console/testrunner'
module CI
module Reporter
# Factory for constructing either a CI::Reporter::TestUnitFailure or CI::Reporter::TestUnitError depending on the result
# of the test.
class Failure
def self.new(fault)
return TestUnitFailure.new(fault) if fault.kind_of?(Test::Unit::Failure)
return TestUnitSkipped.new(fault) if Test::Unit.constants.include?("Omission") && (fault.kind_of?(Test::Unit::Omission) || fault.kind_of?(Test::Unit::Pending))
TestUnitError.new(fault)
end
end
# Wrapper around a <code>Test::Unit</code> error to be used by the test suite to interpret results.
class TestUnitError
def initialize(fault) @fault = fault end
def failure?() false end
def error?() true end
def name() @fault.exception.class.name end
def message() @fault.exception.message end
def location() @fault.exception.backtrace.join("\n") end
end
# Wrapper around a <code>Test::Unit</code> failure to be used by the test suite to interpret results.
class TestUnitFailure
def initialize(fault) @fault = fault end
def failure?() true end
def error?() false end
def name() Test::Unit::AssertionFailedError.name end
def message() @fault.message end
def location() @fault.location.join("\n") end
end
# Wrapper around a <code>Test::Unit</code> 2.0 omission.
class TestUnitSkipped
def initialize(fault) @fault = fault end
def failure?() false end
def error?() false end
def name() Test::Unit::Omission.name end
def message() @fault.message end
def location() @fault.location.join("\n") end
end
# Replacement Mediator that adds listeners to capture the results of the <code>Test::Unit</code> runs.
class TestUnit < Test::Unit::UI::TestRunnerMediator
def initialize(suite, report_mgr = nil)
super(suite)
@report_manager = report_mgr || ReportManager.new("test")
add_listener(Test::Unit::UI::TestRunnerMediator::STARTED, &method(:started))
add_listener(Test::Unit::TestCase::STARTED, &method(:test_started))
add_listener(Test::Unit::TestCase::FINISHED, &method(:test_finished))
add_listener(Test::Unit::TestResult::FAULT, &method(:fault))
add_listener(Test::Unit::UI::TestRunnerMediator::FINISHED, &method(:finished))
end
def started(result)
@suite_result = result
@last_assertion_count = 0
@current_suite = nil
@unknown_count = 0
@result_assertion_count = 0
end
def test_started(name)
test_name, suite_name = extract_names(name)
unless @current_suite && @current_suite.name == suite_name
finish_suite
start_suite(suite_name)
end
start_test(test_name)
end
def test_finished(name)
finish_test
end
def fault(fault)
tc = @current_suite.testcases.last
tc.failures << Failure.new(fault)
end
def finished(elapsed_time)
finish_suite
end
private
def extract_names(name)
match = name.match(/(.*)\(([^)]*)\)/)
if match
[match[1], match[2]]
else
@unknown_count += 1
[name, "unknown-#{@unknown_count}"]
end
end
def start_suite(suite_name)
@current_suite = TestSuite.new(suite_name)
@current_suite.start
end
def finish_suite
if @current_suite
@current_suite.finish
@current_suite.assertions = @suite_result.assertion_count - @last_assertion_count
@last_assertion_count = @suite_result.assertion_count
@report_manager.write_report(@current_suite)
end
end
def start_test(test_name)
tc = TestCase.new(test_name)
tc.start
@current_suite.testcases << tc
end
def finish_test
tc = @current_suite.testcases.last
tc.finish
tc.assertions = @suite_result.assertion_count - @result_assertion_count
@result_assertion_count = @suite_result.assertion_count
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/report_manager.rb | provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/report_manager.rb | # Copyright (c) 2006-2010 Nick Sieger <nicksieger@gmail.com>
# See the file LICENSE.txt included with the distribution for
# software license details.
require 'fileutils'
module CI #:nodoc:
module Reporter #:nodoc:
class ReportManager
def initialize(prefix)
@basedir = ENV['CI_REPORTS'] || File.expand_path("#{Dir.getwd}/#{prefix.downcase}/reports")
@basename = "#{@basedir}/#{prefix.upcase}"
FileUtils.mkdir_p(@basedir)
end
def write_report(suite)
File.open("#{@basename}-#{suite.name.gsub(/[^a-zA-Z0-9]+/, '-')}.xml", "w") do |f|
f << suite.to_xml
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/rspec.rb | provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/rspec.rb | # Copyright (c) 2006-2010 Nick Sieger <nicksieger@gmail.com>
# See the file LICENSE.txt included with the distribution for
# software license details.
require 'ci/reporter/core'
tried_gem = false
begin
require 'spec'
require 'spec/runner/formatter/progress_bar_formatter'
require 'spec/runner/formatter/specdoc_formatter'
rescue LoadError
unless tried_gem
tried_gem = true
require 'rubygems'
gem 'rspec'
retry
end
end
module CI
module Reporter
# Wrapper around a <code>RSpec</code> error or failure to be used by the test suite to interpret results.
class RSpecFailure
def initialize(failure)
@failure = failure
end
def failure?
@failure.expectation_not_met?
end
def error?
!@failure.expectation_not_met?
end
def name() @failure.exception.class.name end
def message() @failure.exception.message end
def location() @failure.exception.backtrace.join("\n") end
end
# Custom +RSpec+ formatter used to hook into the spec runs and capture results.
class RSpec < Spec::Runner::Formatter::BaseFormatter
attr_accessor :report_manager
attr_accessor :formatter
def initialize(*args)
super
@formatter ||= Spec::Runner::Formatter::ProgressBarFormatter.new(*args)
@report_manager = ReportManager.new("spec")
@suite = nil
end
def start(spec_count)
@formatter.start(spec_count)
end
# rspec 0.9
def add_behaviour(name)
@formatter.add_behaviour(name)
new_suite(name)
end
# Compatibility with rspec < 1.2.4
def add_example_group(example_group)
@formatter.add_example_group(example_group)
new_suite(example_group.description)
end
# rspec >= 1.2.4
def example_group_started(example_group)
@formatter.example_group_started(example_group)
new_suite(example_group.description)
end
def example_started(name)
@formatter.example_started(name)
name = name.description if name.respond_to?(:description)
spec = TestCase.new name
@suite.testcases << spec
spec.start
end
def example_failed(name, counter, failure)
@formatter.example_failed(name, counter, failure)
# In case we fail in before(:all)
if @suite.testcases.empty?
example_started(name)
end
spec = @suite.testcases.last
spec.finish
spec.failures << RSpecFailure.new(failure)
end
def example_passed(name)
@formatter.example_passed(name)
spec = @suite.testcases.last
spec.finish
end
def example_pending(*args)
@formatter.example_pending(*args)
spec = @suite.testcases.last
spec.finish
spec.name = "#{spec.name} (PENDING)"
spec.skipped = true
end
def start_dump
@formatter.start_dump
end
def dump_failure(*args)
@formatter.dump_failure(*args)
end
def dump_summary(*args)
@formatter.dump_summary(*args)
write_report
end
def dump_pending
@formatter.dump_pending
end
def close
@formatter.close
end
private
def write_report
@suite.finish
@report_manager.write_report(@suite)
end
def new_suite(name)
write_report if @suite
@suite = TestSuite.new name
@suite.start
end
end
class RSpecDoc < RSpec
def initialize(*args)
@formatter = Spec::Runner::Formatter::SpecdocFormatter.new(*args)
super
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/test_suite.rb | provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/test_suite.rb | # Copyright (c) 2006-2010 Nick Sieger <nicksieger@gmail.com>
# See the file LICENSE.txt included with the distribution for
# software license details.
require 'delegate'
require 'stringio'
module CI
module Reporter
# Emulates/delegates IO to $stdout or $stderr in order to capture output to report in the XML file.
class OutputCapture < DelegateClass(IO)
# Start capturing IO, using the given block to assign self to the proper IO global.
def initialize(io, &assign)
super
@delegate_io = io
@captured_io = StringIO.new
@assign_block = assign
@assign_block.call self
end
# Finalize the capture and reset to the original IO object.
def finish
@assign_block.call @delegate_io
@captured_io.string
end
# setup tee methods
%w(<< print printf putc puts write).each do |m|
module_eval(<<-EOS, __FILE__, __LINE__)
def #{m}(*args, &block)
@delegate_io.send(:#{m}, *args, &block)
@captured_io.send(:#{m}, *args, &block)
end
EOS
end
end
# Basic structure representing the running of a test suite. Used to time tests and store results.
class TestSuite < Struct.new(:name, :tests, :time, :failures, :errors, :skipped, :assertions)
attr_accessor :testcases
attr_accessor :stdout, :stderr
def initialize(name)
super(name.to_s) # RSpec passes a "description" object instead of a string
@testcases = []
end
# Starts timing the test suite.
def start
@start = Time.now
unless ENV['CI_CAPTURE'] == "off"
@capture_out = OutputCapture.new($stdout) {|io| $stdout = io }
@capture_err = OutputCapture.new($stderr) {|io| $stderr = io }
end
end
# Finishes timing the test suite.
def finish
self.tests = testcases.size
self.time = Time.now - @start
self.failures = testcases.inject(0) {|sum,tc| sum += tc.failures.select{|f| f.failure? }.size }
self.errors = testcases.inject(0) {|sum,tc| sum += tc.failures.select{|f| f.error? }.size }
self.skipped = testcases.inject(0) {|sum,tc| sum += (tc.skipped? ? 1 : 0) }
self.stdout = @capture_out.finish if @capture_out
self.stderr = @capture_err.finish if @capture_err
end
# Creates the xml builder instance used to create the report xml document.
def create_builder
begin
require 'rubygems'
gem 'builder'
rescue LoadError
end
require 'builder'
# :escape_attrs is obsolete in a newer version, but should do no harm
Builder::XmlMarkup.new(:indent => 2, :escape_attrs => true)
end
# Creates an xml string containing the test suite results.
def to_xml
builder = create_builder
# more recent version of Builder doesn't need the escaping
def builder.trunc!(txt)
txt.sub(/\n.*/m, '...')
end
builder.instruct!
attrs = {}
each_pair {|k,v| attrs[k] = builder.trunc!(v.to_s) unless v.nil? || v.to_s.empty? }
builder.testsuite(attrs) do
@testcases.each do |tc|
tc.to_xml(builder)
end
builder.tag! "system-out" do
builder.text! self.stdout
end
builder.tag! "system-err" do
builder.text! self.stderr
end
end
end
end
# Structure used to represent an individual test case. Used to time the test and store the result.
class TestCase < Struct.new(:name, :time, :assertions)
attr_accessor :failures
attr_accessor :skipped
def initialize(*args)
super
@failures = []
end
# Starts timing the test.
def start
@start = Time.now
end
# Finishes timing the test.
def finish
self.time = Time.now - @start
end
# Returns non-nil if the test failed.
def failure?
!failures.empty? && failures.detect {|f| f.failure? }
end
# Returns non-nil if the test had an error.
def error?
!failures.empty? && failures.detect {|f| f.error? }
end
def skipped?
return skipped
end
# Writes xml representing the test result to the provided builder.
def to_xml(builder)
attrs = {}
each_pair {|k,v| attrs[k] = builder.trunc!(v.to_s) unless v.nil? || v.to_s.empty?}
builder.testcase(attrs) do
if skipped
builder.skipped
else
failures.each do |failure|
builder.failure(:type => builder.trunc!(failure.name), :message => builder.trunc!(failure.message)) do
builder.text!(failure.message + " (#{failure.name})\n")
builder.text!(failure.location)
end
end
end
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/rake/cucumber.rb | provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/rake/cucumber.rb | # Copyright (c) 2006-2010 Nick Sieger <nicksieger@gmail.com>
# See the file LICENSE.txt included with the distribution for
# software license details.
namespace :ci do
namespace :setup do
task :cucumber_report_cleanup do
rm_rf ENV["CI_REPORTS"] || "features/reports"
end
task :cucumber => :cucumber_report_cleanup do
spec_opts = ["--require", "#{File.dirname(__FILE__)}/cucumber_loader.rb",
"--format", "CI::Reporter::Cucumber"].join(" ")
ENV["CUCUMBER_OPTS"] = "#{ENV['CUCUMBER_OPTS']} #{spec_opts}"
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/rake/cucumber_loader.rb | provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/rake/cucumber_loader.rb | # Copyright (c) 2006-2010 Nick Sieger <nicksieger@gmail.com>
# See the file LICENSE.txt included with the distribution for
# software license details.
$: << File.dirname(__FILE__) + "/../../.."
require 'ci/reporter/cucumber'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/rake/test_unit.rb | provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/rake/test_unit.rb | # Copyright (c) 2006-2010 Nick Sieger <nicksieger@gmail.com>
# See the file LICENSE.txt included with the distribution for
# software license details.
namespace :ci do
namespace :setup do
task :testunit do
rm_rf ENV["CI_REPORTS"] || "test/reports"
ENV["TESTOPTS"] = "#{ENV["TESTOPTS"]} #{File.dirname(__FILE__)}/test_unit_loader.rb"
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/rake/rspec_loader.rb | provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/rake/rspec_loader.rb | # Copyright (c) 2006-2010 Nick Sieger <nicksieger@gmail.com>
# See the file LICENSE.txt included with the distribution for
# software license details.
$: << File.dirname(__FILE__) + "/../../.."
require 'ci/reporter/rspec'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/rake/rspec.rb | provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/rake/rspec.rb | # Copyright (c) 2006-2010 Nick Sieger <nicksieger@gmail.com>
# See the file LICENSE.txt included with the distribution for
# software license details.
namespace :ci do
namespace :setup do
task :spec_report_cleanup do
rm_rf ENV["CI_REPORTS"] || "spec/reports"
end
task :rspec => :spec_report_cleanup do
spec_opts = ["--require", "#{File.dirname(__FILE__)}/rspec_loader.rb",
"--format", "CI::Reporter::RSpec"].join(" ")
ENV["SPEC_OPTS"] = "#{ENV['SPEC_OPTS']} #{spec_opts}"
end
task :rspecdoc => :spec_report_cleanup do
spec_opts = ["--require", "#{File.dirname(__FILE__)}/rspec_loader.rb",
"--format", "CI::Reporter::RSpecDoc"].join(" ")
ENV["SPEC_OPTS"] = "#{ENV['SPEC_OPTS']} #{spec_opts}"
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/rake/test_unit_loader.rb | provider/vendor/gems/ci_reporter-1.6.2/lib/ci/reporter/rake/test_unit_loader.rb | # Copyright (c) 2006-2010 Nick Sieger <nicksieger@gmail.com>
# See the file LICENSE.txt included with the distribution for
# software license details.
$: << File.dirname(__FILE__) + "/../../.."
require 'ci/reporter/test_unit'
module Test #:nodoc:all
module Unit
module UI
module Console
class TestRunner
def create_mediator(suite)
# swap in our custom mediator
return CI::Reporter::TestUnit.new(suite)
end
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/install.rb | provider/vendor/rails/activerecord/install.rb | require 'rbconfig'
require 'find'
require 'ftools'
include Config
# this was adapted from rdoc's install.rb by ways of Log4r
$sitedir = CONFIG["sitelibdir"]
unless $sitedir
version = CONFIG["MAJOR"] + "." + CONFIG["MINOR"]
$libdir = File.join(CONFIG["libdir"], "ruby", version)
$sitedir = $:.find {|x| x =~ /site_ruby/ }
if !$sitedir
$sitedir = File.join($libdir, "site_ruby")
elsif $sitedir !~ Regexp.quote(version)
$sitedir = File.join($sitedir, version)
end
end
# the actual gruntwork
Dir.chdir("lib")
Find.find("active_record", "active_record.rb") { |f|
if f[-3..-1] == ".rb"
File::install(f, File.join($sitedir, *f.split(/\//)), 0644, true)
else
File::makedirs(File.join($sitedir, *f.split(/\//)))
end
}
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/config.rb | provider/vendor/rails/activerecord/test/config.rb | TEST_ROOT = File.expand_path(File.dirname(__FILE__))
ASSETS_ROOT = TEST_ROOT + "/assets"
FIXTURES_ROOT = TEST_ROOT + "/fixtures"
MIGRATIONS_ROOT = TEST_ROOT + "/migrations"
SCHEMA_ROOT = TEST_ROOT + "/schema"
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/schema_authorization_test_postgresql.rb | provider/vendor/rails/activerecord/test/cases/schema_authorization_test_postgresql.rb | require "cases/helper"
class SchemaThing < ActiveRecord::Base
end
class SchemaAuthorizationTest < ActiveRecord::TestCase
self.use_transactional_fixtures = false
TABLE_NAME = 'schema_things'
COLUMNS = [
'id serial primary key',
'name character varying(50)'
]
USERS = ['rails_pg_schema_user1', 'rails_pg_schema_user2']
def setup
@connection = ActiveRecord::Base.connection
@connection.execute "SET search_path TO '$user',public"
set_session_auth
USERS.each do |u|
@connection.execute "CREATE USER #{u}" rescue nil
@connection.execute "CREATE SCHEMA AUTHORIZATION #{u}" rescue nil
set_session_auth u
@connection.execute "CREATE TABLE #{TABLE_NAME} (#{COLUMNS.join(',')})"
@connection.execute "INSERT INTO #{TABLE_NAME} (name) VALUES ('#{u}')"
set_session_auth
end
end
def teardown
set_session_auth
@connection.execute "RESET search_path"
USERS.each do |u|
@connection.execute "DROP SCHEMA #{u} CASCADE"
@connection.execute "DROP USER #{u}"
end
end
def test_schema_invisible
assert_raise(ActiveRecord::StatementInvalid) do
set_session_auth
@connection.execute "SELECT * FROM #{TABLE_NAME}"
end
end
def test_schema_uniqueness
assert_nothing_raised do
set_session_auth
USERS.each do |u|
set_session_auth u
assert_equal u, @connection.select_value("SELECT name FROM #{TABLE_NAME} WHERE id = 1")
set_session_auth
end
end
end
def test_sequence_schema_caching
assert_nothing_raised do
USERS.each do |u|
set_session_auth u
st = SchemaThing.new :name => 'TEST1'
st.save!
st = SchemaThing.new :id => 5, :name => 'TEST2'
st.save!
set_session_auth
end
end
end
private
def set_session_auth auth = nil
@connection.execute "SET SESSION AUTHORIZATION #{auth || 'default'}"
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/pk_test.rb | provider/vendor/rails/activerecord/test/cases/pk_test.rb | require "cases/helper"
require 'models/topic'
require 'models/reply'
require 'models/subscriber'
require 'models/movie'
require 'models/keyboard'
require 'models/mixed_case_monkey'
class PrimaryKeysTest < ActiveRecord::TestCase
fixtures :topics, :subscribers, :movies, :mixed_case_monkeys
def test_integer_key
topic = Topic.find(1)
assert_equal(topics(:first).author_name, topic.author_name)
topic = Topic.find(2)
assert_equal(topics(:second).author_name, topic.author_name)
topic = Topic.new
topic.title = "New Topic"
assert_equal(nil, topic.id)
assert_nothing_raised { topic.save! }
id = topic.id
topicReloaded = Topic.find(id)
assert_equal("New Topic", topicReloaded.title)
end
def test_customized_primary_key_auto_assigns_on_save
Keyboard.delete_all
keyboard = Keyboard.new(:name => 'HHKB')
assert_nothing_raised { keyboard.save! }
assert_equal keyboard.id, Keyboard.find_by_name('HHKB').id
end
def test_customized_primary_key_can_be_get_before_saving
keyboard = Keyboard.new
assert_nil keyboard.id
assert_nothing_raised { assert_nil keyboard.key_number }
end
def test_customized_string_primary_key_settable_before_save
subscriber = Subscriber.new
assert_nothing_raised { subscriber.id = 'webster123' }
assert_equal 'webster123', subscriber.id
assert_equal 'webster123', subscriber.nick
end
def test_string_key
subscriber = Subscriber.find(subscribers(:first).nick)
assert_equal(subscribers(:first).name, subscriber.name)
subscriber = Subscriber.find(subscribers(:second).nick)
assert_equal(subscribers(:second).name, subscriber.name)
subscriber = Subscriber.new
subscriber.id = "jdoe"
assert_equal("jdoe", subscriber.id)
subscriber.name = "John Doe"
assert_nothing_raised { subscriber.save! }
assert_equal("jdoe", subscriber.id)
subscriberReloaded = Subscriber.find("jdoe")
assert_equal("John Doe", subscriberReloaded.name)
end
def test_find_with_more_than_one_string_key
assert_equal 2, Subscriber.find(subscribers(:first).nick, subscribers(:second).nick).length
end
def test_primary_key_prefix
ActiveRecord::Base.primary_key_prefix_type = :table_name
Topic.reset_primary_key
assert_equal "topicid", Topic.primary_key
ActiveRecord::Base.primary_key_prefix_type = :table_name_with_underscore
Topic.reset_primary_key
assert_equal "topic_id", Topic.primary_key
ActiveRecord::Base.primary_key_prefix_type = nil
Topic.reset_primary_key
assert_equal "id", Topic.primary_key
end
def test_delete_should_quote_pkey
assert_nothing_raised { MixedCaseMonkey.delete(1) }
end
def test_update_counters_should_quote_pkey_and_quote_counter_columns
assert_nothing_raised { MixedCaseMonkey.update_counters(1, :fleaCount => 99) }
end
def test_find_with_one_id_should_quote_pkey
assert_nothing_raised { MixedCaseMonkey.find(1) }
end
def test_find_with_multiple_ids_should_quote_pkey
assert_nothing_raised { MixedCaseMonkey.find([1,2]) }
end
def test_instance_update_should_quote_pkey
assert_nothing_raised { MixedCaseMonkey.find(1).save }
end
def test_instance_destroy_should_quote_pkey
assert_nothing_raised { MixedCaseMonkey.find(1).destroy }
end
def test_supports_primary_key
assert_nothing_raised NoMethodError do
ActiveRecord::Base.connection.supports_primary_key?
end
end
def test_primary_key_returns_value_if_it_exists
if ActiveRecord::Base.connection.supports_primary_key?
assert_equal 'id', ActiveRecord::Base.connection.primary_key('developers')
end
end
def test_primary_key_returns_nil_if_it_does_not_exist
if ActiveRecord::Base.connection.supports_primary_key?
assert_nil ActiveRecord::Base.connection.primary_key('developers_projects')
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/migration_test.rb | provider/vendor/rails/activerecord/test/cases/migration_test.rb | require "cases/helper"
require 'bigdecimal/util'
require 'models/person'
require 'models/topic'
require 'models/developer'
require MIGRATIONS_ROOT + "/valid/1_people_have_last_names"
require MIGRATIONS_ROOT + "/valid/2_we_need_reminders"
require MIGRATIONS_ROOT + "/decimal/1_give_me_big_numbers"
require MIGRATIONS_ROOT + "/interleaved/pass_3/2_i_raise_on_down"
if ActiveRecord::Base.connection.supports_migrations?
class BigNumber < ActiveRecord::Base; end
class Reminder < ActiveRecord::Base; end
class ActiveRecord::Migration
class <<self
attr_accessor :message_count
def puts(text="")
self.message_count ||= 0
self.message_count += 1
end
end
end
class MigrationTableAndIndexTest < ActiveRecord::TestCase
def test_add_schema_info_respects_prefix_and_suffix
conn = ActiveRecord::Base.connection
conn.drop_table(ActiveRecord::Migrator.schema_migrations_table_name) if conn.table_exists?(ActiveRecord::Migrator.schema_migrations_table_name)
ActiveRecord::Base.table_name_prefix = 'foo_'
ActiveRecord::Base.table_name_suffix = '_bar'
conn.drop_table(ActiveRecord::Migrator.schema_migrations_table_name) if conn.table_exists?(ActiveRecord::Migrator.schema_migrations_table_name)
conn.initialize_schema_migrations_table
assert_equal "foo_unique_schema_migrations_bar", conn.indexes(ActiveRecord::Migrator.schema_migrations_table_name)[0][:name]
ensure
ActiveRecord::Base.table_name_prefix = ""
ActiveRecord::Base.table_name_suffix = ""
end
end
class MigrationTest < ActiveRecord::TestCase
self.use_transactional_fixtures = false
fixtures :people
def setup
ActiveRecord::Migration.verbose = true
PeopleHaveLastNames.message_count = 0
end
def teardown
ActiveRecord::Base.connection.initialize_schema_migrations_table
ActiveRecord::Base.connection.execute "DELETE FROM #{ActiveRecord::Migrator.schema_migrations_table_name}"
%w(reminders people_reminders prefix_reminders_suffix).each do |table|
Reminder.connection.drop_table(table) rescue nil
end
Reminder.reset_column_information
%w(last_name key bio age height wealth birthday favorite_day
moment_of_truth male administrator funny).each do |column|
Person.connection.remove_column('people', column) rescue nil
end
Person.connection.remove_column("people", "first_name") rescue nil
Person.connection.remove_column("people", "middle_name") rescue nil
Person.connection.add_column("people", "first_name", :string, :limit => 40)
Person.reset_column_information
end
def test_add_index
# Limit size of last_name and key columns to support Firebird index limitations
Person.connection.add_column "people", "last_name", :string, :limit => 100
Person.connection.add_column "people", "key", :string, :limit => 100
Person.connection.add_column "people", "administrator", :boolean
assert_nothing_raised { Person.connection.add_index("people", "last_name") }
assert_nothing_raised { Person.connection.remove_index("people", "last_name") }
# Orcl nds shrt indx nms. Sybs 2.
# OpenBase does not have named indexes. You must specify a single column name
unless current_adapter?(:OracleAdapter, :SybaseAdapter, :OpenBaseAdapter)
assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"]) }
assert_nothing_raised { Person.connection.remove_index("people", :column => ["last_name", "first_name"]) }
assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"]) }
assert_nothing_raised { Person.connection.remove_index("people", :name => "index_people_on_last_name_and_first_name") }
assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"]) }
assert_nothing_raised { Person.connection.remove_index("people", "last_name_and_first_name") }
assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"]) }
assert_nothing_raised { Person.connection.remove_index("people", ["last_name", "first_name"]) }
end
# quoting
# Note: changed index name from "key" to "key_idx" since "key" is a Firebird reserved word
# OpenBase does not have named indexes. You must specify a single column name
unless current_adapter?(:OpenBaseAdapter)
Person.update_all "#{Person.connection.quote_column_name 'key'}=#{Person.connection.quote_column_name 'id'}" #some databases (including sqlite2 won't add a unique index if existing data non unique)
assert_nothing_raised { Person.connection.add_index("people", ["key"], :name => "key_idx", :unique => true) }
assert_nothing_raised { Person.connection.remove_index("people", :name => "key_idx", :unique => true) }
end
# Sybase adapter does not support indexes on :boolean columns
# OpenBase does not have named indexes. You must specify a single column
unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter)
assert_nothing_raised { Person.connection.add_index("people", %w(last_name first_name administrator), :name => "named_admin") }
assert_nothing_raised { Person.connection.remove_index("people", :name => "named_admin") }
end
end
def testing_table_with_only_foo_attribute
Person.connection.create_table :testings, :id => false do |t|
t.column :foo, :string
end
yield Person.connection
ensure
Person.connection.drop_table :testings rescue nil
end
protected :testing_table_with_only_foo_attribute
def test_create_table_without_id
testing_table_with_only_foo_attribute do |connection|
assert_equal connection.columns(:testings).size, 1
end
end
def test_add_column_with_primary_key_attribute
testing_table_with_only_foo_attribute do |connection|
assert_nothing_raised { connection.add_column :testings, :id, :primary_key }
assert_equal connection.columns(:testings).size, 2
end
end
def test_create_table_adds_id
Person.connection.create_table :testings do |t|
t.column :foo, :string
end
assert_equal %w(foo id),
Person.connection.columns(:testings).map { |c| c.name }.sort
ensure
Person.connection.drop_table :testings rescue nil
end
def test_create_table_with_not_null_column
assert_nothing_raised do
Person.connection.create_table :testings do |t|
t.column :foo, :string, :null => false
end
end
assert_raise(ActiveRecord::StatementInvalid) do
Person.connection.execute "insert into testings (foo) values (NULL)"
end
ensure
Person.connection.drop_table :testings rescue nil
end
def test_create_table_with_defaults
# MySQL doesn't allow defaults on TEXT or BLOB columns.
mysql = current_adapter?(:MysqlAdapter)
Person.connection.create_table :testings do |t|
t.column :one, :string, :default => "hello"
t.column :two, :boolean, :default => true
t.column :three, :boolean, :default => false
t.column :four, :integer, :default => 1
t.column :five, :text, :default => "hello" unless mysql
end
columns = Person.connection.columns(:testings)
one = columns.detect { |c| c.name == "one" }
two = columns.detect { |c| c.name == "two" }
three = columns.detect { |c| c.name == "three" }
four = columns.detect { |c| c.name == "four" }
five = columns.detect { |c| c.name == "five" } unless mysql
assert_equal "hello", one.default
assert_equal true, two.default
assert_equal false, three.default
assert_equal 1, four.default
assert_equal "hello", five.default unless mysql
ensure
Person.connection.drop_table :testings rescue nil
end
def test_create_table_with_limits
assert_nothing_raised do
Person.connection.create_table :testings do |t|
t.column :foo, :string, :limit => 255
t.column :default_int, :integer
t.column :one_int, :integer, :limit => 1
t.column :four_int, :integer, :limit => 4
t.column :eight_int, :integer, :limit => 8
t.column :eleven_int, :integer, :limit => 11
end
end
columns = Person.connection.columns(:testings)
foo = columns.detect { |c| c.name == "foo" }
assert_equal 255, foo.limit
default = columns.detect { |c| c.name == "default_int" }
one = columns.detect { |c| c.name == "one_int" }
four = columns.detect { |c| c.name == "four_int" }
eight = columns.detect { |c| c.name == "eight_int" }
eleven = columns.detect { |c| c.name == "eleven_int" }
if current_adapter?(:PostgreSQLAdapter)
assert_equal 'integer', default.sql_type
assert_equal 'smallint', one.sql_type
assert_equal 'integer', four.sql_type
assert_equal 'bigint', eight.sql_type
assert_equal 'integer', eleven.sql_type
elsif current_adapter?(:MysqlAdapter)
assert_match 'int(11)', default.sql_type
assert_match 'tinyint', one.sql_type
assert_match 'int', four.sql_type
assert_match 'bigint', eight.sql_type
assert_match 'int(11)', eleven.sql_type
elsif current_adapter?(:OracleAdapter)
assert_equal 'NUMBER(38)', default.sql_type
assert_equal 'NUMBER(1)', one.sql_type
assert_equal 'NUMBER(4)', four.sql_type
assert_equal 'NUMBER(8)', eight.sql_type
end
ensure
Person.connection.drop_table :testings rescue nil
end
def test_create_table_with_primary_key_prefix_as_table_name_with_underscore
ActiveRecord::Base.primary_key_prefix_type = :table_name_with_underscore
Person.connection.create_table :testings do |t|
t.column :foo, :string
end
assert_equal %w(foo testing_id), Person.connection.columns(:testings).map { |c| c.name }.sort
ensure
Person.connection.drop_table :testings rescue nil
ActiveRecord::Base.primary_key_prefix_type = nil
end
def test_create_table_with_primary_key_prefix_as_table_name
ActiveRecord::Base.primary_key_prefix_type = :table_name
Person.connection.create_table :testings do |t|
t.column :foo, :string
end
assert_equal %w(foo testingid), Person.connection.columns(:testings).map { |c| c.name }.sort
ensure
Person.connection.drop_table :testings rescue nil
ActiveRecord::Base.primary_key_prefix_type = nil
end
def test_create_table_with_force_true_does_not_drop_nonexisting_table
if Person.connection.table_exists?(:testings2)
Person.connection.drop_table :testings2
end
# using a copy as we need the drop_table method to
# continue to work for the ensure block of the test
temp_conn = Person.connection.dup
temp_conn.expects(:drop_table).never
temp_conn.create_table :testings2, :force => true do |t|
t.column :foo, :string
end
ensure
Person.connection.drop_table :testings2 rescue nil
end
def test_create_table_with_timestamps_should_create_datetime_columns
table_name = :testings
Person.connection.create_table table_name do |t|
t.timestamps
end
created_columns = Person.connection.columns(table_name)
created_at_column = created_columns.detect {|c| c.name == 'created_at' }
updated_at_column = created_columns.detect {|c| c.name == 'updated_at' }
assert created_at_column.null
assert updated_at_column.null
ensure
Person.connection.drop_table table_name rescue nil
end
def test_create_table_with_timestamps_should_create_datetime_columns_with_options
table_name = :testings
Person.connection.create_table table_name do |t|
t.timestamps :null => false
end
created_columns = Person.connection.columns(table_name)
created_at_column = created_columns.detect {|c| c.name == 'created_at' }
updated_at_column = created_columns.detect {|c| c.name == 'updated_at' }
assert !created_at_column.null
assert !updated_at_column.null
ensure
Person.connection.drop_table table_name rescue nil
end
# Sybase, and SQLite3 will not allow you to add a NOT NULL
# column to a table without a default value.
unless current_adapter?(:SybaseAdapter, :SQLiteAdapter)
def test_add_column_not_null_without_default
Person.connection.create_table :testings do |t|
t.column :foo, :string
end
Person.connection.add_column :testings, :bar, :string, :null => false
assert_raise(ActiveRecord::StatementInvalid) do
Person.connection.execute "insert into testings (foo, bar) values ('hello', NULL)"
end
ensure
Person.connection.drop_table :testings rescue nil
end
end
def test_add_column_not_null_with_default
Person.connection.create_table :testings do |t|
t.column :foo, :string
end
con = Person.connection
Person.connection.enable_identity_insert("testings", true) if current_adapter?(:SybaseAdapter)
Person.connection.execute "insert into testings (#{con.quote_column_name('id')}, #{con.quote_column_name('foo')}) values (1, 'hello')"
Person.connection.enable_identity_insert("testings", false) if current_adapter?(:SybaseAdapter)
assert_nothing_raised {Person.connection.add_column :testings, :bar, :string, :null => false, :default => "default" }
assert_raise(ActiveRecord::StatementInvalid) do
unless current_adapter?(:OpenBaseAdapter)
Person.connection.execute "insert into testings (#{con.quote_column_name('id')}, #{con.quote_column_name('foo')}, #{con.quote_column_name('bar')}) values (2, 'hello', NULL)"
else
Person.connection.insert("INSERT INTO testings (#{con.quote_column_name('id')}, #{con.quote_column_name('foo')}, #{con.quote_column_name('bar')}) VALUES (2, 'hello', NULL)",
"Testing Insert","id",2)
end
end
ensure
Person.connection.drop_table :testings rescue nil
end
# We specifically do a manual INSERT here, and then test only the SELECT
# functionality. This allows us to more easily catch INSERT being broken,
# but SELECT actually working fine.
def test_native_decimal_insert_manual_vs_automatic
correct_value = '0012345678901234567890.0123456789'.to_d
Person.delete_all
Person.connection.add_column "people", "wealth", :decimal, :precision => '30', :scale => '10'
Person.reset_column_information
# Do a manual insertion
if current_adapter?(:OracleAdapter)
Person.connection.execute "insert into people (id, wealth) values (people_seq.nextval, 12345678901234567890.0123456789)"
elsif current_adapter?(:OpenBaseAdapter) || (current_adapter?(:MysqlAdapter) && Mysql.client_version < 50003) #before mysql 5.0.3 decimals stored as strings
Person.connection.execute "insert into people (wealth) values ('12345678901234567890.0123456789')"
else
Person.connection.execute "insert into people (wealth) values (12345678901234567890.0123456789)"
end
# SELECT
row = Person.find(:first)
assert_kind_of BigDecimal, row.wealth
# If this assert fails, that means the SELECT is broken!
unless current_adapter?(:SQLite3Adapter)
assert_equal correct_value, row.wealth
end
# Reset to old state
Person.delete_all
# Now use the Rails insertion
assert_nothing_raised { Person.create :wealth => BigDecimal.new("12345678901234567890.0123456789") }
# SELECT
row = Person.find(:first)
assert_kind_of BigDecimal, row.wealth
# If these asserts fail, that means the INSERT (create function, or cast to SQL) is broken!
unless current_adapter?(:SQLite3Adapter)
assert_equal correct_value, row.wealth
end
# Reset to old state
Person.connection.del_column "people", "wealth" rescue nil
Person.reset_column_information
end
def test_add_column_with_precision_and_scale
Person.connection.add_column 'people', 'wealth', :decimal, :precision => 9, :scale => 7
Person.reset_column_information
wealth_column = Person.columns_hash['wealth']
assert_equal 9, wealth_column.precision
assert_equal 7, wealth_column.scale
end
def test_native_types
Person.delete_all
Person.connection.add_column "people", "last_name", :string
Person.connection.add_column "people", "bio", :text
Person.connection.add_column "people", "age", :integer
Person.connection.add_column "people", "height", :float
Person.connection.add_column "people", "wealth", :decimal, :precision => '30', :scale => '10'
Person.connection.add_column "people", "birthday", :datetime
Person.connection.add_column "people", "favorite_day", :date
Person.connection.add_column "people", "moment_of_truth", :datetime
Person.connection.add_column "people", "male", :boolean
Person.reset_column_information
assert_nothing_raised do
Person.create :first_name => 'bob', :last_name => 'bobsen',
:bio => "I was born ....", :age => 18, :height => 1.78,
:wealth => BigDecimal.new("12345678901234567890.0123456789"),
:birthday => 18.years.ago, :favorite_day => 10.days.ago,
:moment_of_truth => "1782-10-10 21:40:18", :male => true
end
bob = Person.find(:first)
assert_equal 'bob', bob.first_name
assert_equal 'bobsen', bob.last_name
assert_equal "I was born ....", bob.bio
assert_equal 18, bob.age
# Test for 30 significent digits (beyond the 16 of float), 10 of them
# after the decimal place.
unless current_adapter?(:SQLite3Adapter)
assert_equal BigDecimal.new("0012345678901234567890.0123456789"), bob.wealth
end
assert_equal true, bob.male?
assert_equal String, bob.first_name.class
assert_equal String, bob.last_name.class
assert_equal String, bob.bio.class
assert_equal Fixnum, bob.age.class
assert_equal Time, bob.birthday.class
if current_adapter?(:OracleAdapter, :SybaseAdapter)
# Sybase, and Oracle don't differentiate between date/time
assert_equal Time, bob.favorite_day.class
else
assert_equal Date, bob.favorite_day.class
end
# Test DateTime column and defaults, including timezone.
# FIXME: moment of truth may be Time on 64-bit platforms.
if bob.moment_of_truth.is_a?(DateTime)
with_env_tz 'US/Eastern' do
assert_equal DateTime.local_offset, bob.moment_of_truth.offset
assert_not_equal 0, bob.moment_of_truth.offset
assert_not_equal "Z", bob.moment_of_truth.zone
# US/Eastern is -5 hours from GMT
assert_equal Rational(-5, 24), bob.moment_of_truth.offset
assert_match /\A-05:?00\Z/, bob.moment_of_truth.zone #ruby 1.8.6 uses HH:MM, prior versions use HHMM
assert_equal DateTime::ITALY, bob.moment_of_truth.start
end
end
assert_equal TrueClass, bob.male?.class
assert_kind_of BigDecimal, bob.wealth
end
if current_adapter?(:MysqlAdapter)
def test_unabstracted_database_dependent_types
Person.delete_all
ActiveRecord::Migration.add_column :people, :intelligence_quotient, :tinyint
Person.reset_column_information
assert_match /tinyint/, Person.columns_hash['intelligence_quotient'].sql_type
ensure
ActiveRecord::Migration.remove_column :people, :intelligence_quotient rescue nil
end
end
def test_add_remove_single_field_using_string_arguments
assert !Person.column_methods_hash.include?(:last_name)
ActiveRecord::Migration.add_column 'people', 'last_name', :string
Person.reset_column_information
assert Person.column_methods_hash.include?(:last_name)
ActiveRecord::Migration.remove_column 'people', 'last_name'
Person.reset_column_information
assert !Person.column_methods_hash.include?(:last_name)
end
def test_add_remove_single_field_using_symbol_arguments
assert !Person.column_methods_hash.include?(:last_name)
ActiveRecord::Migration.add_column :people, :last_name, :string
Person.reset_column_information
assert Person.column_methods_hash.include?(:last_name)
ActiveRecord::Migration.remove_column :people, :last_name
Person.reset_column_information
assert !Person.column_methods_hash.include?(:last_name)
end
def test_add_rename
Person.delete_all
begin
Person.connection.add_column "people", "girlfriend", :string
Person.reset_column_information
Person.create :girlfriend => 'bobette'
Person.connection.rename_column "people", "girlfriend", "exgirlfriend"
Person.reset_column_information
bob = Person.find(:first)
assert_equal "bobette", bob.exgirlfriend
ensure
Person.connection.remove_column("people", "girlfriend") rescue nil
Person.connection.remove_column("people", "exgirlfriend") rescue nil
end
end
def test_rename_column_using_symbol_arguments
begin
names_before = Person.find(:all).map(&:first_name)
Person.connection.rename_column :people, :first_name, :nick_name
Person.reset_column_information
assert Person.column_names.include?("nick_name")
assert_equal names_before, Person.find(:all).map(&:nick_name)
ensure
Person.connection.remove_column("people","nick_name")
Person.connection.add_column("people","first_name", :string)
end
end
def test_rename_column
begin
names_before = Person.find(:all).map(&:first_name)
Person.connection.rename_column "people", "first_name", "nick_name"
Person.reset_column_information
assert Person.column_names.include?("nick_name")
assert_equal names_before, Person.find(:all).map(&:nick_name)
ensure
Person.connection.remove_column("people","nick_name")
Person.connection.add_column("people","first_name", :string)
end
end
def test_rename_column_preserves_default_value_not_null
begin
default_before = Developer.connection.columns("developers").find { |c| c.name == "salary" }.default
assert_equal 70000, default_before
Developer.connection.rename_column "developers", "salary", "anual_salary"
Developer.reset_column_information
assert Developer.column_names.include?("anual_salary")
default_after = Developer.connection.columns("developers").find { |c| c.name == "anual_salary" }.default
assert_equal 70000, default_after
ensure
Developer.connection.rename_column "developers", "anual_salary", "salary"
Developer.reset_column_information
end
end
def test_rename_nonexistent_column
ActiveRecord::Base.connection.create_table(:hats) do |table|
table.column :hat_name, :string, :default => nil
end
exception = if current_adapter?(:PostgreSQLAdapter)
ActiveRecord::StatementInvalid
else
ActiveRecord::ActiveRecordError
end
assert_raise(exception) do
Person.connection.rename_column "hats", "nonexistent", "should_fail"
end
ensure
ActiveRecord::Base.connection.drop_table(:hats)
end
def test_rename_column_with_sql_reserved_word
begin
assert_nothing_raised { Person.connection.rename_column "people", "first_name", "group" }
Person.reset_column_information
assert Person.column_names.include?("group")
ensure
Person.connection.remove_column("people", "group") rescue nil
Person.connection.add_column("people", "first_name", :string) rescue nil
end
end
def test_rename_column_with_an_index
ActiveRecord::Base.connection.create_table(:hats) do |table|
table.column :hat_name, :string, :limit => 100
table.column :hat_size, :integer
end
Person.connection.add_index :hats, :hat_name
assert_nothing_raised do
Person.connection.rename_column "hats", "hat_name", "name"
end
ensure
ActiveRecord::Base.connection.drop_table(:hats)
end
def test_remove_column_with_index
ActiveRecord::Base.connection.create_table(:hats) do |table|
table.column :hat_name, :string, :limit => 100
table.column :hat_size, :integer
end
ActiveRecord::Base.connection.add_index "hats", "hat_size"
assert_nothing_raised { Person.connection.remove_column("hats", "hat_size") }
ensure
ActiveRecord::Base.connection.drop_table(:hats)
end
def test_remove_column_with_multi_column_index
ActiveRecord::Base.connection.create_table(:hats) do |table|
table.column :hat_name, :string, :limit => 100
table.column :hat_size, :integer
table.column :hat_style, :string, :limit => 100
end
ActiveRecord::Base.connection.add_index "hats", ["hat_style", "hat_size"], :unique => true
assert_nothing_raised { Person.connection.remove_column("hats", "hat_size") }
ensure
ActiveRecord::Base.connection.drop_table(:hats)
end
def test_change_type_of_not_null_column
assert_nothing_raised do
Topic.connection.change_column "topics", "written_on", :datetime, :null => false
Topic.reset_column_information
Topic.connection.change_column "topics", "written_on", :datetime, :null => false
Topic.reset_column_information
end
end
def test_rename_table
begin
ActiveRecord::Base.connection.create_table :octopuses do |t|
t.column :url, :string
end
ActiveRecord::Base.connection.rename_table :octopuses, :octopi
# Using explicit id in insert for compatibility across all databases
con = ActiveRecord::Base.connection
con.enable_identity_insert("octopi", true) if current_adapter?(:SybaseAdapter)
assert_nothing_raised { con.execute "INSERT INTO octopi (#{con.quote_column_name('id')}, #{con.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')" }
con.enable_identity_insert("octopi", false) if current_adapter?(:SybaseAdapter)
assert_equal 'http://www.foreverflying.com/octopus-black7.jpg', ActiveRecord::Base.connection.select_value("SELECT url FROM octopi WHERE id=1")
ensure
ActiveRecord::Base.connection.drop_table :octopuses rescue nil
ActiveRecord::Base.connection.drop_table :octopi rescue nil
end
end
def test_change_column_nullability
Person.delete_all
Person.connection.add_column "people", "funny", :boolean
Person.reset_column_information
assert Person.columns_hash["funny"].null, "Column 'funny' must initially allow nulls"
Person.connection.change_column "people", "funny", :boolean, :null => false, :default => true
Person.reset_column_information
assert !Person.columns_hash["funny"].null, "Column 'funny' must *not* allow nulls at this point"
Person.connection.change_column "people", "funny", :boolean, :null => true
Person.reset_column_information
assert Person.columns_hash["funny"].null, "Column 'funny' must allow nulls again at this point"
end
def test_rename_table_with_an_index
begin
ActiveRecord::Base.connection.create_table :octopuses do |t|
t.column :url, :string
end
ActiveRecord::Base.connection.add_index :octopuses, :url
ActiveRecord::Base.connection.rename_table :octopuses, :octopi
# Using explicit id in insert for compatibility across all databases
con = ActiveRecord::Base.connection
con.enable_identity_insert("octopi", true) if current_adapter?(:SybaseAdapter)
assert_nothing_raised { con.execute "INSERT INTO octopi (#{con.quote_column_name('id')}, #{con.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')" }
con.enable_identity_insert("octopi", false) if current_adapter?(:SybaseAdapter)
assert_equal 'http://www.foreverflying.com/octopus-black7.jpg', ActiveRecord::Base.connection.select_value("SELECT url FROM octopi WHERE id=1")
assert ActiveRecord::Base.connection.indexes(:octopi).first.columns.include?("url")
ensure
ActiveRecord::Base.connection.drop_table :octopuses rescue nil
ActiveRecord::Base.connection.drop_table :octopi rescue nil
end
end
def test_change_column
Person.connection.add_column 'people', 'age', :integer
old_columns = Person.connection.columns(Person.table_name, "#{name} Columns")
assert old_columns.find { |c| c.name == 'age' and c.type == :integer }
assert_nothing_raised { Person.connection.change_column "people", "age", :string }
new_columns = Person.connection.columns(Person.table_name, "#{name} Columns")
assert_nil new_columns.find { |c| c.name == 'age' and c.type == :integer }
assert new_columns.find { |c| c.name == 'age' and c.type == :string }
old_columns = Topic.connection.columns(Topic.table_name, "#{name} Columns")
assert old_columns.find { |c| c.name == 'approved' and c.type == :boolean and c.default == true }
assert_nothing_raised { Topic.connection.change_column :topics, :approved, :boolean, :default => false }
new_columns = Topic.connection.columns(Topic.table_name, "#{name} Columns")
assert_nil new_columns.find { |c| c.name == 'approved' and c.type == :boolean and c.default == true }
assert new_columns.find { |c| c.name == 'approved' and c.type == :boolean and c.default == false }
assert_nothing_raised { Topic.connection.change_column :topics, :approved, :boolean, :default => true }
end
def test_change_column_with_nil_default
Person.connection.add_column "people", "contributor", :boolean, :default => true
Person.reset_column_information
assert Person.new.contributor?
assert_nothing_raised { Person.connection.change_column "people", "contributor", :boolean, :default => nil }
Person.reset_column_information
assert !Person.new.contributor?
assert_nil Person.new.contributor
ensure
Person.connection.remove_column("people", "contributor") rescue nil
end
def test_change_column_with_new_default
Person.connection.add_column "people", "administrator", :boolean, :default => true
Person.reset_column_information
assert Person.new.administrator?
assert_nothing_raised { Person.connection.change_column "people", "administrator", :boolean, :default => false }
Person.reset_column_information
assert !Person.new.administrator?
ensure
Person.connection.remove_column("people", "administrator") rescue nil
end
def test_change_column_default
Person.connection.change_column_default "people", "first_name", "Tester"
Person.reset_column_information
assert_equal "Tester", Person.new.first_name
end
def test_change_column_quotes_column_names
Person.connection.create_table :testings do |t|
t.column :select, :string
end
assert_nothing_raised { Person.connection.change_column :testings, :select, :string, :limit => 10 }
assert_nothing_raised { Person.connection.execute "insert into testings (#{Person.connection.quote_column_name('select')}) values ('7 chars')" }
ensure
Person.connection.drop_table :testings rescue nil
end
def test_keeping_default_and_notnull_constaint_on_change
Person.connection.create_table :testings do |t|
t.column :title, :string
end
person_klass = Class.new(Person)
person_klass.set_table_name 'testings'
person_klass.connection.add_column "testings", "wealth", :integer, :null => false, :default => 99
person_klass.reset_column_information
assert_equal 99, person_klass.columns_hash["wealth"].default
assert_equal false, person_klass.columns_hash["wealth"].null
assert_nothing_raised {person_klass.connection.execute("insert into testings (title) values ('tester')")}
# change column default to see that column doesn't lose its not null definition
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | true |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/attribute_methods_test.rb | provider/vendor/rails/activerecord/test/cases/attribute_methods_test.rb | require "cases/helper"
require 'models/topic'
require 'models/minimalistic'
class AttributeMethodsTest < ActiveRecord::TestCase
fixtures :topics
def setup
@old_suffixes = ActiveRecord::Base.send(:attribute_method_suffixes).dup
@target = Class.new(ActiveRecord::Base)
@target.table_name = 'topics'
end
def teardown
ActiveRecord::Base.send(:attribute_method_suffixes).clear
ActiveRecord::Base.attribute_method_suffix *@old_suffixes
end
def test_match_attribute_method_query_returns_match_data
assert_not_nil md = @target.match_attribute_method?('title=')
assert_equal 'title', md.pre_match
assert_equal ['='], md.captures
%w(_hello_world ist! _maybe?).each do |suffix|
@target.class_eval "def attribute#{suffix}(*args) args end"
@target.attribute_method_suffix suffix
assert_not_nil md = @target.match_attribute_method?("title#{suffix}")
assert_equal 'title', md.pre_match
assert_equal [suffix], md.captures
end
end
def test_declared_attribute_method_affects_respond_to_and_method_missing
topic = @target.new(:title => 'Budget')
assert topic.respond_to?('title')
assert_equal 'Budget', topic.title
assert !topic.respond_to?('title_hello_world')
assert_raise(NoMethodError) { topic.title_hello_world }
%w(_hello_world _it! _candidate= able?).each do |suffix|
@target.class_eval "def attribute#{suffix}(*args) args end"
@target.attribute_method_suffix suffix
meth = "title#{suffix}"
assert topic.respond_to?(meth)
assert_equal ['title'], topic.send(meth)
assert_equal ['title', 'a'], topic.send(meth, 'a')
assert_equal ['title', 1, 2, 3], topic.send(meth, 1, 2, 3)
end
end
def test_should_unserialize_attributes_for_frozen_records
myobj = {:value1 => :value2}
topic = Topic.create("content" => myobj)
topic.freeze
assert_equal myobj, topic.content
end
def test_typecast_attribute_from_select_to_false
topic = Topic.create(:title => 'Budget')
topic = Topic.find(:first, :select => "topics.*, 1=2 as is_test")
assert !topic.is_test?
end
def test_typecast_attribute_from_select_to_true
topic = Topic.create(:title => 'Budget')
topic = Topic.find(:first, :select => "topics.*, 2=2 as is_test")
assert topic.is_test?
end
def test_kernel_methods_not_implemented_in_activerecord
%w(test name display y).each do |method|
assert !ActiveRecord::Base.instance_method_already_implemented?(method), "##{method} is defined"
end
end
def test_primary_key_implemented
assert Class.new(ActiveRecord::Base).instance_method_already_implemented?('id')
end
def test_defined_kernel_methods_implemented_in_model
%w(test name display y).each do |method|
klass = Class.new ActiveRecord::Base
klass.class_eval "def #{method}() 'defined #{method}' end"
assert klass.instance_method_already_implemented?(method), "##{method} is not defined"
end
end
def test_defined_kernel_methods_implemented_in_model_abstract_subclass
%w(test name display y).each do |method|
abstract = Class.new ActiveRecord::Base
abstract.class_eval "def #{method}() 'defined #{method}' end"
abstract.abstract_class = true
klass = Class.new abstract
assert klass.instance_method_already_implemented?(method), "##{method} is not defined"
end
end
def test_raises_dangerous_attribute_error_when_defining_activerecord_method_in_model
%w(save create_or_update).each do |method|
klass = Class.new ActiveRecord::Base
klass.class_eval "def #{method}() 'defined #{method}' end"
assert_raise ActiveRecord::DangerousAttributeError do
klass.instance_method_already_implemented?(method)
end
end
end
def test_only_time_related_columns_are_meant_to_be_cached_by_default
expected = %w(datetime timestamp time date).sort
assert_equal expected, ActiveRecord::Base.attribute_types_cached_by_default.map(&:to_s).sort
end
def test_declaring_attributes_as_cached_adds_them_to_the_attributes_cached_by_default
default_attributes = Topic.cached_attributes
Topic.cache_attributes :replies_count
expected = default_attributes + ["replies_count"]
assert_equal expected.sort, Topic.cached_attributes.sort
Topic.instance_variable_set "@cached_attributes", nil
end
def test_time_related_columns_are_actually_cached
column_types = %w(datetime timestamp time date).map(&:to_sym)
column_names = Topic.columns.select{|c| column_types.include?(c.type) }.map(&:name)
assert_equal column_names.sort, Topic.cached_attributes.sort
assert_equal time_related_columns_on_topic.sort, Topic.cached_attributes.sort
end
def test_accessing_cached_attributes_caches_the_converted_values_and_nothing_else
t = topics(:first)
cache = t.instance_variable_get "@attributes_cache"
assert_not_nil cache
assert cache.empty?
all_columns = Topic.columns.map(&:name)
cached_columns = time_related_columns_on_topic
uncached_columns = all_columns - cached_columns
all_columns.each do |attr_name|
attribute_gets_cached = Topic.cache_attribute?(attr_name)
val = t.send attr_name unless attr_name == "type"
if attribute_gets_cached
assert cached_columns.include?(attr_name)
assert_equal val, cache[attr_name]
else
assert uncached_columns.include?(attr_name)
assert !cache.include?(attr_name)
end
end
end
def test_time_attributes_are_retrieved_in_current_time_zone
in_time_zone "Pacific Time (US & Canada)" do
utc_time = Time.utc(2008, 1, 1)
record = @target.new
record[:written_on] = utc_time
assert_equal utc_time, record.written_on # record.written on is equal to (i.e., simultaneous with) utc_time
assert_kind_of ActiveSupport::TimeWithZone, record.written_on # but is a TimeWithZone
assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone # and is in the current Time.zone
assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time # and represents time values adjusted accordingly
end
end
def test_setting_time_zone_aware_attribute_to_utc
in_time_zone "Pacific Time (US & Canada)" do
utc_time = Time.utc(2008, 1, 1)
record = @target.new
record.written_on = utc_time
assert_equal utc_time, record.written_on
assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time
end
end
def test_setting_time_zone_aware_attribute_in_other_time_zone
utc_time = Time.utc(2008, 1, 1)
cst_time = utc_time.in_time_zone("Central Time (US & Canada)")
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new
record.written_on = cst_time
assert_equal utc_time, record.written_on
assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time
end
end
def test_setting_time_zone_aware_attribute_with_string
utc_time = Time.utc(2008, 1, 1)
(-11..13).each do |timezone_offset|
time_string = utc_time.in_time_zone(timezone_offset).to_s
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new
record.written_on = time_string
assert_equal Time.zone.parse(time_string), record.written_on
assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time
end
end
end
def test_setting_time_zone_aware_attribute_to_blank_string_returns_nil
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new
record.written_on = ' '
assert_nil record.written_on
end
end
def test_setting_time_zone_aware_attribute_interprets_time_zone_unaware_string_in_time_zone
time_string = 'Tue Jan 01 00:00:00 2008'
(-11..13).each do |timezone_offset|
in_time_zone timezone_offset do
record = @target.new
record.written_on = time_string
assert_equal Time.zone.parse(time_string), record.written_on
assert_equal ActiveSupport::TimeZone[timezone_offset], record.written_on.time_zone
assert_equal Time.utc(2008, 1, 1), record.written_on.time
end
end
end
def test_setting_time_zone_aware_attribute_in_current_time_zone
utc_time = Time.utc(2008, 1, 1)
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new
record.written_on = utc_time.in_time_zone
assert_equal utc_time, record.written_on
assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time
end
end
def test_setting_time_zone_conversion_for_attributes_should_write_value_on_class_variable
Topic.skip_time_zone_conversion_for_attributes = [:field_a]
Minimalistic.skip_time_zone_conversion_for_attributes = [:field_b]
assert_equal [:field_a], Topic.skip_time_zone_conversion_for_attributes
assert_equal [:field_b], Minimalistic.skip_time_zone_conversion_for_attributes
end
def test_read_attributes_respect_access_control
privatize("title")
topic = @target.new(:title => "The pros and cons of programming naked.")
assert !topic.respond_to?(:title)
exception = assert_raise(NoMethodError) { topic.title }
assert_equal "Attempt to call private method", exception.message
assert_equal "I'm private", topic.send(:title)
end
def test_write_attributes_respect_access_control
privatize("title=(value)")
topic = @target.new
assert !topic.respond_to?(:title=)
exception = assert_raise(NoMethodError) { topic.title = "Pants"}
assert_equal "Attempt to call private method", exception.message
topic.send(:title=, "Very large pants")
end
def test_question_attributes_respect_access_control
privatize("title?")
topic = @target.new(:title => "Isaac Newton's pants")
assert !topic.respond_to?(:title?)
exception = assert_raise(NoMethodError) { topic.title? }
assert_equal "Attempt to call private method", exception.message
assert topic.send(:title?)
end
def test_bulk_update_respects_access_control
privatize("title=(value)")
assert_raise(ActiveRecord::UnknownAttributeError) { topic = @target.new(:title => "Rants about pants") }
assert_raise(ActiveRecord::UnknownAttributeError) { @target.new.attributes = { :title => "Ants in pants" } }
end
private
def time_related_columns_on_topic
Topic.columns.select{|c| [:time, :date, :datetime, :timestamp].include?(c.type)}.map(&:name)
end
def in_time_zone(zone)
old_zone = Time.zone
old_tz = ActiveRecord::Base.time_zone_aware_attributes
Time.zone = zone ? ActiveSupport::TimeZone[zone] : nil
ActiveRecord::Base.time_zone_aware_attributes = !zone.nil?
yield
ensure
Time.zone = old_zone
ActiveRecord::Base.time_zone_aware_attributes = old_tz
end
def privatize(method_signature)
@target.class_eval <<-private_method
private
def #{method_signature}
"I'm private"
end
private_method
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/locking_test.rb | provider/vendor/rails/activerecord/test/cases/locking_test.rb | require "cases/helper"
require 'models/person'
require 'models/reader'
require 'models/legacy_thing'
require 'models/reference'
class LockWithoutDefault < ActiveRecord::Base; end
class LockWithCustomColumnWithoutDefault < ActiveRecord::Base
set_table_name :lock_without_defaults_cust
set_locking_column :custom_lock_version
end
class ReadonlyFirstNamePerson < Person
attr_readonly :first_name
end
class OptimisticLockingTest < ActiveRecord::TestCase
fixtures :people, :legacy_things, :references
# need to disable transactional fixtures, because otherwise the sqlite3
# adapter (at least) chokes when we try and change the schema in the middle
# of a test (see test_increment_counter_*).
self.use_transactional_fixtures = false
def test_lock_existing
p1 = Person.find(1)
p2 = Person.find(1)
assert_equal 0, p1.lock_version
assert_equal 0, p2.lock_version
p1.first_name = 'stu'
p1.save!
assert_equal 1, p1.lock_version
assert_equal 0, p2.lock_version
p2.first_name = 'sue'
assert_raise(ActiveRecord::StaleObjectError) { p2.save! }
end
def test_lock_destroy
p1 = Person.find(1)
p2 = Person.find(1)
assert_equal 0, p1.lock_version
assert_equal 0, p2.lock_version
p1.first_name = 'stu'
p1.save!
assert_equal 1, p1.lock_version
assert_equal 0, p2.lock_version
assert_raises(ActiveRecord::StaleObjectError) { p2.destroy }
assert p1.destroy
assert_equal true, p1.frozen?
assert_raises(ActiveRecord::RecordNotFound) { Person.find(1) }
end
def test_lock_repeating
p1 = Person.find(1)
p2 = Person.find(1)
assert_equal 0, p1.lock_version
assert_equal 0, p2.lock_version
p1.first_name = 'stu'
p1.save!
assert_equal 1, p1.lock_version
assert_equal 0, p2.lock_version
p2.first_name = 'sue'
assert_raise(ActiveRecord::StaleObjectError) { p2.save! }
p2.first_name = 'sue2'
assert_raise(ActiveRecord::StaleObjectError) { p2.save! }
end
def test_lock_new
p1 = Person.new(:first_name => 'anika')
assert_equal 0, p1.lock_version
p1.first_name = 'anika2'
p1.save!
p2 = Person.find(p1.id)
assert_equal 0, p1.lock_version
assert_equal 0, p2.lock_version
p1.first_name = 'anika3'
p1.save!
assert_equal 1, p1.lock_version
assert_equal 0, p2.lock_version
p2.first_name = 'sue'
assert_raise(ActiveRecord::StaleObjectError) { p2.save! }
end
def test_lock_new_with_nil
p1 = Person.new(:first_name => 'anika')
p1.save!
p1.lock_version = nil # simulate bad fixture or column with no default
p1.save!
assert_equal 1, p1.lock_version
end
def test_lock_column_name_existing
t1 = LegacyThing.find(1)
t2 = LegacyThing.find(1)
assert_equal 0, t1.version
assert_equal 0, t2.version
t1.tps_report_number = 700
t1.save!
assert_equal 1, t1.version
assert_equal 0, t2.version
t2.tps_report_number = 800
assert_raise(ActiveRecord::StaleObjectError) { t2.save! }
end
def test_lock_column_is_mass_assignable
p1 = Person.create(:first_name => 'bianca')
assert_equal 0, p1.lock_version
assert_equal p1.lock_version, Person.new(p1.attributes).lock_version
p1.first_name = 'bianca2'
p1.save!
assert_equal 1, p1.lock_version
assert_equal p1.lock_version, Person.new(p1.attributes).lock_version
end
def test_lock_without_default_sets_version_to_zero
t1 = LockWithoutDefault.new
assert_equal 0, t1.lock_version
end
def test_lock_with_custom_column_without_default_sets_version_to_zero
t1 = LockWithCustomColumnWithoutDefault.new
assert_equal 0, t1.custom_lock_version
end
def test_readonly_attributes
assert_equal Set.new([ 'first_name' ]), ReadonlyFirstNamePerson.readonly_attributes
p = ReadonlyFirstNamePerson.create(:first_name => "unchangeable name")
p.reload
assert_equal "unchangeable name", p.first_name
p.update_attributes(:first_name => "changed name")
p.reload
assert_equal "unchangeable name", p.first_name
end
{ :lock_version => Person, :custom_lock_version => LegacyThing }.each do |name, model|
define_method("test_increment_counter_updates_#{name}") do
counter_test model, 1 do |id|
model.increment_counter :test_count, id
end
end
define_method("test_decrement_counter_updates_#{name}") do
counter_test model, -1 do |id|
model.decrement_counter :test_count, id
end
end
define_method("test_update_counters_updates_#{name}") do
counter_test model, 1 do |id|
model.update_counters id, :test_count => 1
end
end
end
def test_quote_table_name
ref = references(:michael_magician)
ref.favourite = !ref.favourite
assert ref.save
end
# Useful for partial updates, don't only update the lock_version if there
# is nothing else being updated.
def test_update_without_attributes_does_not_only_update_lock_version
assert_nothing_raised do
p1 = Person.new(:first_name => 'anika')
p1.send(:update_with_lock, [])
end
end
private
def add_counter_column_to(model)
model.connection.add_column model.table_name, :test_count, :integer, :null => false, :default => 0
model.reset_column_information
# OpenBase does not set a value to existing rows when adding a not null default column
model.update_all(:test_count => 0) if current_adapter?(:OpenBaseAdapter)
end
def remove_counter_column_from(model)
model.connection.remove_column model.table_name, :test_count
model.reset_column_information
end
def counter_test(model, expected_count)
add_counter_column_to(model)
object = model.find(:first)
assert_equal 0, object.test_count
assert_equal 0, object.send(model.locking_column)
yield object.id
object.reload
assert_equal expected_count, object.test_count
assert_equal 1, object.send(model.locking_column)
ensure
remove_counter_column_from(model)
end
end
# TODO: test against the generated SQL since testing locking behavior itself
# is so cumbersome. Will deadlock Ruby threads if the underlying db.execute
# blocks, so separate script called by Kernel#system is needed.
# (See exec vs. async_exec in the PostgreSQL adapter.)
# TODO: The Sybase, and OpenBase adapters currently have no support for pessimistic locking
unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter)
class PessimisticLockingTest < ActiveRecord::TestCase
self.use_transactional_fixtures = false
fixtures :people, :readers
def setup
# Avoid introspection queries during tests.
Person.columns; Reader.columns
end
# Test typical find.
def test_sane_find_with_lock
assert_nothing_raised do
Person.transaction do
Person.find 1, :lock => true
end
end
end
# Test scoped lock.
def test_sane_find_with_scoped_lock
assert_nothing_raised do
Person.transaction do
Person.with_scope(:find => { :lock => true }) do
Person.find 1
end
end
end
end
# PostgreSQL protests SELECT ... FOR UPDATE on an outer join.
unless current_adapter?(:PostgreSQLAdapter)
# Test locked eager find.
def test_eager_find_with_lock
assert_nothing_raised do
Person.transaction do
Person.find 1, :include => :readers, :lock => true
end
end
end
end
# Locking a record reloads it.
def test_sane_lock_method
assert_nothing_raised do
Person.transaction do
person = Person.find 1
old, person.first_name = person.first_name, 'fooman'
person.lock!
assert_equal old, person.first_name
end
end
end
if current_adapter?(:PostgreSQLAdapter, :OracleAdapter)
use_concurrent_connections
def test_no_locks_no_wait
first, second = duel { Person.find 1 }
assert first.end > second.end
end
def test_second_lock_waits
assert [0.2, 1, 5].any? { |zzz|
first, second = duel(zzz) { Person.find 1, :lock => true }
second.end > first.end
}
end
protected
def duel(zzz = 5)
t0, t1, t2, t3 = nil, nil, nil, nil
a = Thread.new do
t0 = Time.now
Person.transaction do
yield
sleep zzz # block thread 2 for zzz seconds
end
t1 = Time.now
end
b = Thread.new do
sleep zzz / 2.0 # ensure thread 1 tx starts first
t2 = Time.now
Person.transaction { yield }
t3 = Time.now
end
a.join
b.join
assert t1 > t0 + zzz
assert t2 > t0
assert t3 > t2
[t0.to_f..t1.to_f, t2.to_f..t3.to_f]
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/class_inheritable_attributes_test.rb | provider/vendor/rails/activerecord/test/cases/class_inheritable_attributes_test.rb | require 'test/unit'
require "cases/helper"
require 'active_support/core_ext/class/inheritable_attributes'
class A
include ClassInheritableAttributes
end
class B < A
write_inheritable_array "first", [ :one, :two ]
end
class C < A
write_inheritable_array "first", [ :three ]
end
class D < B
write_inheritable_array "first", [ :four ]
end
class ClassInheritableAttributesTest < ActiveRecord::TestCase
def test_first_level
assert_equal [ :one, :two ], B.read_inheritable_attribute("first")
assert_equal [ :three ], C.read_inheritable_attribute("first")
end
def test_second_level
assert_equal [ :one, :two, :four ], D.read_inheritable_attribute("first")
assert_equal [ :one, :two ], B.read_inheritable_attribute("first")
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/connection_test_mysql.rb | provider/vendor/rails/activerecord/test/cases/connection_test_mysql.rb | require "cases/helper"
class MysqlConnectionTest < ActiveRecord::TestCase
def setup
super
@connection = ActiveRecord::Base.connection
end
def test_mysql_reconnect_attribute_after_connection_with_reconnect_true
run_without_connection do |orig_connection|
ActiveRecord::Base.establish_connection(orig_connection.merge({:reconnect => true}))
assert ActiveRecord::Base.connection.raw_connection.reconnect
end
end
def test_mysql_reconnect_attribute_after_connection_with_reconnect_false
run_without_connection do |orig_connection|
ActiveRecord::Base.establish_connection(orig_connection.merge({:reconnect => false}))
assert !ActiveRecord::Base.connection.raw_connection.reconnect
end
end
def test_no_automatic_reconnection_after_timeout
assert @connection.active?
@connection.update('set @@wait_timeout=1')
sleep 2
assert !@connection.active?
end
def test_successful_reconnection_after_timeout_with_manual_reconnect
assert @connection.active?
@connection.update('set @@wait_timeout=1')
sleep 2
@connection.reconnect!
assert @connection.active?
end
def test_successful_reconnection_after_timeout_with_verify
assert @connection.active?
@connection.update('set @@wait_timeout=1')
sleep 2
@connection.verify!
assert @connection.active?
end
private
def run_without_connection
original_connection = ActiveRecord::Base.remove_connection
begin
yield original_connection
ensure
ActiveRecord::Base.establish_connection(original_connection)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/autosave_association_test.rb | provider/vendor/rails/activerecord/test/cases/autosave_association_test.rb | require 'cases/helper'
require 'models/bird'
require 'models/company'
require 'models/customer'
require 'models/developer'
require 'models/order'
require 'models/parrot'
require 'models/person'
require 'models/pirate'
require 'models/post'
require 'models/reader'
require 'models/ship'
require 'models/ship_part'
require 'models/treasure'
class TestAutosaveAssociationsInGeneral < ActiveRecord::TestCase
def test_autosave_should_be_a_valid_option_for_has_one
assert base.valid_keys_for_has_one_association.include?(:autosave)
end
def test_autosave_should_be_a_valid_option_for_belongs_to
assert base.valid_keys_for_belongs_to_association.include?(:autosave)
end
def test_autosave_should_be_a_valid_option_for_has_many
assert base.valid_keys_for_has_many_association.include?(:autosave)
end
def test_autosave_should_be_a_valid_option_for_has_and_belongs_to_many
assert base.valid_keys_for_has_and_belongs_to_many_association.include?(:autosave)
end
private
def base
ActiveRecord::Base
end
end
class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase
def test_should_save_parent_but_not_invalid_child
firm = Firm.new(:name => 'GlobalMegaCorp')
assert firm.valid?
firm.build_account_using_primary_key
assert !firm.build_account_using_primary_key.valid?
assert firm.save
assert firm.account_using_primary_key.new_record?
end
def test_save_fails_for_invalid_has_one
firm = Firm.find(:first)
assert firm.valid?
firm.account = Account.new
assert !firm.account.valid?
assert !firm.valid?
assert !firm.save
assert_equal "is invalid", firm.errors.on("account")
end
def test_save_succeeds_for_invalid_has_one_with_validate_false
firm = Firm.find(:first)
assert firm.valid?
firm.unvalidated_account = Account.new
assert !firm.unvalidated_account.valid?
assert firm.valid?
assert firm.save
end
def test_build_before_child_saved
firm = Firm.find(1)
account = firm.account.build("credit_limit" => 1000)
assert_equal account, firm.account
assert account.new_record?
assert firm.save
assert_equal account, firm.account
assert !account.new_record?
end
def test_build_before_either_saved
firm = Firm.new("name" => "GlobalMegaCorp")
firm.account = account = Account.new("credit_limit" => 1000)
assert_equal account, firm.account
assert account.new_record?
assert firm.save
assert_equal account, firm.account
assert !account.new_record?
end
def test_assignment_before_parent_saved
firm = Firm.new("name" => "GlobalMegaCorp")
firm.account = a = Account.find(1)
assert firm.new_record?
assert_equal a, firm.account
assert firm.save
assert_equal a, firm.account
assert_equal a, firm.account(true)
end
def test_assignment_before_either_saved
firm = Firm.new("name" => "GlobalMegaCorp")
firm.account = a = Account.new("credit_limit" => 1000)
assert firm.new_record?
assert a.new_record?
assert_equal a, firm.account
assert firm.save
assert !firm.new_record?
assert !a.new_record?
assert_equal a, firm.account
assert_equal a, firm.account(true)
end
def test_not_resaved_when_unchanged
firm = Firm.find(:first, :include => :account)
firm.name += '-changed'
assert_queries(1) { firm.save! }
firm = Firm.find(:first)
firm.account = Account.find(:first)
assert_queries(Firm.partial_updates? ? 0 : 1) { firm.save! }
firm = Firm.find(:first).clone
firm.account = Account.find(:first)
assert_queries(2) { firm.save! }
firm = Firm.find(:first).clone
firm.account = Account.find(:first).clone
assert_queries(2) { firm.save! }
end
end
class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::TestCase
def test_should_save_parent_but_not_invalid_child
client = Client.new(:name => 'Joe (the Plumber)')
assert client.valid?
client.build_firm
assert !client.firm.valid?
assert client.save
assert client.firm.new_record?
end
def test_save_fails_for_invalid_belongs_to
assert log = AuditLog.create(:developer_id => 0, :message => "")
log.developer = Developer.new
assert !log.developer.valid?
assert !log.valid?
assert !log.save
assert_equal "is invalid", log.errors.on("developer")
end
def test_save_succeeds_for_invalid_belongs_to_with_validate_false
assert log = AuditLog.create(:developer_id => 0, :message=> "")
log.unvalidated_developer = Developer.new
assert !log.unvalidated_developer.valid?
assert log.valid?
assert log.save
end
def test_assignment_before_parent_saved
client = Client.find(:first)
apple = Firm.new("name" => "Apple")
client.firm = apple
assert_equal apple, client.firm
assert apple.new_record?
assert client.save
assert apple.save
assert !apple.new_record?
assert_equal apple, client.firm
assert_equal apple, client.firm(true)
end
def test_assignment_before_either_saved
final_cut = Client.new("name" => "Final Cut")
apple = Firm.new("name" => "Apple")
final_cut.firm = apple
assert final_cut.new_record?
assert apple.new_record?
assert final_cut.save
assert !final_cut.new_record?
assert !apple.new_record?
assert_equal apple, final_cut.firm
assert_equal apple, final_cut.firm(true)
end
def test_store_two_association_with_one_save
num_orders = Order.count
num_customers = Customer.count
order = Order.new
customer1 = order.billing = Customer.new
customer2 = order.shipping = Customer.new
assert order.save
assert_equal customer1, order.billing
assert_equal customer2, order.shipping
order.reload
assert_equal customer1, order.billing
assert_equal customer2, order.shipping
assert_equal num_orders +1, Order.count
assert_equal num_customers +2, Customer.count
end
def test_store_association_in_two_relations_with_one_save
num_orders = Order.count
num_customers = Customer.count
order = Order.new
customer = order.billing = order.shipping = Customer.new
assert order.save
assert_equal customer, order.billing
assert_equal customer, order.shipping
order.reload
assert_equal customer, order.billing
assert_equal customer, order.shipping
assert_equal num_orders +1, Order.count
assert_equal num_customers +1, Customer.count
end
def test_store_association_in_two_relations_with_one_save_in_existing_object
num_orders = Order.count
num_customers = Customer.count
order = Order.create
customer = order.billing = order.shipping = Customer.new
assert order.save
assert_equal customer, order.billing
assert_equal customer, order.shipping
order.reload
assert_equal customer, order.billing
assert_equal customer, order.shipping
assert_equal num_orders +1, Order.count
assert_equal num_customers +1, Customer.count
end
def test_store_association_in_two_relations_with_one_save_in_existing_object_with_values
num_orders = Order.count
num_customers = Customer.count
order = Order.create
customer = order.billing = order.shipping = Customer.new
assert order.save
assert_equal customer, order.billing
assert_equal customer, order.shipping
order.reload
customer = order.billing = order.shipping = Customer.new
assert order.save
order.reload
assert_equal customer, order.billing
assert_equal customer, order.shipping
assert_equal num_orders +1, Order.count
assert_equal num_customers +2, Customer.count
end
end
class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCase
fixtures :companies, :people
def test_invalid_adding
firm = Firm.find(1)
assert !(firm.clients_of_firm << c = Client.new)
assert c.new_record?
assert !firm.valid?
assert !firm.save
assert c.new_record?
end
def test_invalid_adding_before_save
no_of_firms = Firm.count
no_of_clients = Client.count
new_firm = Firm.new("name" => "A New Firm, Inc")
new_firm.clients_of_firm.concat([c = Client.new, Client.new("name" => "Apple")])
assert c.new_record?
assert !c.valid?
assert !new_firm.valid?
assert !new_firm.save
assert c.new_record?
assert new_firm.new_record?
end
def test_invalid_adding_with_validate_false
firm = Firm.find(:first)
client = Client.new
firm.unvalidated_clients_of_firm << client
assert firm.valid?
assert !client.valid?
assert firm.save
assert client.new_record?
end
def test_valid_adding_with_validate_false
no_of_clients = Client.count
firm = Firm.find(:first)
client = Client.new("name" => "Apple")
assert firm.valid?
assert client.valid?
assert client.new_record?
firm.unvalidated_clients_of_firm << client
assert firm.save
assert !client.new_record?
assert_equal no_of_clients+1, Client.count
end
def test_invalid_build
new_client = companies(:first_firm).clients_of_firm.build
assert new_client.new_record?
assert !new_client.valid?
assert_equal new_client, companies(:first_firm).clients_of_firm.last
assert !companies(:first_firm).save
assert new_client.new_record?
assert_equal 1, companies(:first_firm).clients_of_firm(true).size
end
def test_adding_before_save
no_of_firms = Firm.count
no_of_clients = Client.count
new_firm = Firm.new("name" => "A New Firm, Inc")
c = Client.new("name" => "Apple")
new_firm.clients_of_firm.push Client.new("name" => "Natural Company")
assert_equal 1, new_firm.clients_of_firm.size
new_firm.clients_of_firm << c
assert_equal 2, new_firm.clients_of_firm.size
assert_equal no_of_firms, Firm.count # Firm was not saved to database.
assert_equal no_of_clients, Client.count # Clients were not saved to database.
assert new_firm.save
assert !new_firm.new_record?
assert !c.new_record?
assert_equal new_firm, c.firm
assert_equal no_of_firms+1, Firm.count # Firm was saved to database.
assert_equal no_of_clients+2, Client.count # Clients were saved to database.
assert_equal 2, new_firm.clients_of_firm.size
assert_equal 2, new_firm.clients_of_firm(true).size
end
def test_assign_ids
firm = Firm.new("name" => "Apple")
firm.client_ids = [companies(:first_client).id, companies(:second_client).id]
firm.save
firm.reload
assert_equal 2, firm.clients.length
assert firm.clients.include?(companies(:second_client))
end
def test_assign_ids_for_through_a_belongs_to
post = Post.new(:title => "Assigning IDs works!", :body => "You heared it here first, folks!")
post.person_ids = [people(:david).id, people(:michael).id]
post.save
post.reload
assert_equal 2, post.people.length
assert post.people.include?(people(:david))
end
def test_build_before_save
company = companies(:first_firm)
new_client = assert_no_queries { company.clients_of_firm.build("name" => "Another Client") }
assert !company.clients_of_firm.loaded?
company.name += '-changed'
assert_queries(2) { assert company.save }
assert !new_client.new_record?
assert_equal 2, company.clients_of_firm(true).size
end
def test_build_many_before_save
company = companies(:first_firm)
new_clients = assert_no_queries { company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) }
company.name += '-changed'
assert_queries(3) { assert company.save }
assert_equal 3, company.clients_of_firm(true).size
end
def test_build_via_block_before_save
company = companies(:first_firm)
new_client = assert_no_queries { company.clients_of_firm.build {|client| client.name = "Another Client" } }
assert !company.clients_of_firm.loaded?
company.name += '-changed'
assert_queries(2) { assert company.save }
assert !new_client.new_record?
assert_equal 2, company.clients_of_firm(true).size
end
def test_build_many_via_block_before_save
company = companies(:first_firm)
new_clients = assert_no_queries do
company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) do |client|
client.name = "changed"
end
end
company.name += '-changed'
assert_queries(3) { assert company.save }
assert_equal 3, company.clients_of_firm(true).size
end
def test_replace_on_new_object
firm = Firm.new("name" => "New Firm")
firm.clients = [companies(:second_client), Client.new("name" => "New Client")]
assert firm.save
firm.reload
assert_equal 2, firm.clients.length
assert firm.clients.include?(Client.find_by_name("New Client"))
end
end
class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase
self.use_transactional_fixtures = false
def setup
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@ship = @pirate.create_ship(:name => 'Nights Dirty Lightning')
end
# reload
def test_a_marked_for_destruction_record_should_not_be_be_marked_after_reload
@pirate.mark_for_destruction
@pirate.ship.mark_for_destruction
assert !@pirate.reload.marked_for_destruction?
assert !@pirate.ship.marked_for_destruction?
end
# has_one
def test_should_destroy_a_child_association_as_part_of_the_save_transaction_if_it_was_marked_for_destroyal
assert !@pirate.ship.marked_for_destruction?
@pirate.ship.mark_for_destruction
id = @pirate.ship.id
assert @pirate.ship.marked_for_destruction?
assert Ship.find_by_id(id)
@pirate.save
assert_nil @pirate.reload.ship
assert_nil Ship.find_by_id(id)
end
def test_should_skip_validation_on_a_child_association_if_marked_for_destruction
@pirate.ship.name = ''
assert !@pirate.valid?
@pirate.ship.mark_for_destruction
assert_difference('Ship.count', -1) { @pirate.save! }
end
def test_should_rollback_destructions_if_an_exception_occurred_while_saving_a_child
# Stub the save method of the @pirate.ship instance to destroy and then raise an exception
class << @pirate.ship
def save(*args)
super
destroy
raise 'Oh noes!'
end
end
assert_raise(RuntimeError) { assert !@pirate.save }
assert_not_nil @pirate.reload.ship
end
# belongs_to
def test_should_destroy_a_parent_association_as_part_of_the_save_transaction_if_it_was_marked_for_destroyal
assert !@ship.pirate.marked_for_destruction?
@ship.pirate.mark_for_destruction
id = @ship.pirate.id
assert @ship.pirate.marked_for_destruction?
assert Pirate.find_by_id(id)
@ship.save
assert_nil @ship.reload.pirate
assert_nil Pirate.find_by_id(id)
end
def test_should_skip_validation_on_a_parent_association_if_marked_for_destruction
@ship.pirate.catchphrase = ''
assert !@ship.valid?
@ship.pirate.mark_for_destruction
assert_difference('Pirate.count', -1) { @ship.save! }
end
def test_should_rollback_destructions_if_an_exception_occurred_while_saving_a_parent
# Stub the save method of the @ship.pirate instance to destroy and then raise an exception
class << @ship.pirate
def save(*args)
super
destroy
raise 'Oh noes!'
end
end
assert_raise(RuntimeError) { assert !@ship.save }
assert_not_nil @ship.reload.pirate
end
# has_many & has_and_belongs_to
%w{ parrots birds }.each do |association_name|
define_method("test_should_destroy_#{association_name}_as_part_of_the_save_transaction_if_they_were_marked_for_destroyal") do
2.times { |i| @pirate.send(association_name).create!(:name => "#{association_name}_#{i}") }
assert !@pirate.send(association_name).any? { |child| child.marked_for_destruction? }
@pirate.send(association_name).each { |child| child.mark_for_destruction }
klass = @pirate.send(association_name).first.class
ids = @pirate.send(association_name).map(&:id)
assert @pirate.send(association_name).all? { |child| child.marked_for_destruction? }
ids.each { |id| assert klass.find_by_id(id) }
@pirate.save
assert @pirate.reload.send(association_name).empty?
ids.each { |id| assert_nil klass.find_by_id(id) }
end
define_method("test_should_skip_validation_on_the_#{association_name}_association_if_marked_for_destruction") do
2.times { |i| @pirate.send(association_name).create!(:name => "#{association_name}_#{i}") }
children = @pirate.send(association_name)
children.each { |child| child.name = '' }
assert !@pirate.valid?
children.each { |child| child.mark_for_destruction }
assert_difference("#{association_name.classify}.count", -2) { @pirate.save! }
end
define_method("test_should_rollback_destructions_if_an_exception_occurred_while_saving_#{association_name}") do
2.times { |i| @pirate.send(association_name).create!(:name => "#{association_name}_#{i}") }
before = @pirate.send(association_name).map { |c| c }
# Stub the save method of the first child to destroy and the second to raise an exception
class << before.first
def save(*args)
super
destroy
end
end
class << before.last
def save(*args)
super
raise 'Oh noes!'
end
end
assert_raise(RuntimeError) { assert !@pirate.save }
assert_equal before, @pirate.reload.send(association_name)
end
# Add and remove callbacks tests for association collections.
%w{ method proc }.each do |callback_type|
define_method("test_should_run_add_callback_#{callback_type}s_for_#{association_name}") do
association_name_with_callbacks = "#{association_name}_with_#{callback_type}_callbacks"
pirate = Pirate.new(:catchphrase => "Arr")
pirate.send(association_name_with_callbacks).build(:name => "Crowe the One-Eyed")
expected = [
"before_adding_#{callback_type}_#{association_name.singularize}_<new>",
"after_adding_#{callback_type}_#{association_name.singularize}_<new>"
]
assert_equal expected, pirate.ship_log
end
define_method("test_should_run_remove_callback_#{callback_type}s_for_#{association_name}") do
association_name_with_callbacks = "#{association_name}_with_#{callback_type}_callbacks"
@pirate.send(association_name_with_callbacks).create!(:name => "Crowe the One-Eyed")
@pirate.send(association_name_with_callbacks).each { |c| c.mark_for_destruction }
child_id = @pirate.send(association_name_with_callbacks).first.id
@pirate.ship_log.clear
@pirate.save
expected = [
"before_removing_#{callback_type}_#{association_name.singularize}_#{child_id}",
"after_removing_#{callback_type}_#{association_name.singularize}_#{child_id}"
]
assert_equal expected, @pirate.ship_log
end
end
end
end
class TestAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase
self.use_transactional_fixtures = false
def setup
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@ship = @pirate.create_ship(:name => 'Nights Dirty Lightning')
end
def test_should_still_work_without_an_associated_model
@ship.destroy
@pirate.reload.catchphrase = "Arr"
@pirate.save
assert 'Arr', @pirate.reload.catchphrase
end
def test_should_automatically_save_the_associated_model
@pirate.ship.name = 'The Vile Insanity'
@pirate.save
assert_equal 'The Vile Insanity', @pirate.reload.ship.name
end
def test_should_automatically_save_bang_the_associated_model
@pirate.ship.name = 'The Vile Insanity'
@pirate.save!
assert_equal 'The Vile Insanity', @pirate.reload.ship.name
end
def test_should_automatically_validate_the_associated_model
@pirate.ship.name = ''
assert !@pirate.valid?
assert !@pirate.errors.on(:ship_name).blank?
end
def test_should_merge_errors_on_the_associated_models_onto_the_parent_even_if_it_is_not_valid
@pirate.ship.name = nil
@pirate.catchphrase = nil
assert !@pirate.valid?
assert !@pirate.errors.on(:ship_name).blank?
assert !@pirate.errors.on(:catchphrase).blank?
end
def test_should_still_allow_to_bypass_validations_on_the_associated_model
@pirate.catchphrase = ''
@pirate.ship.name = ''
@pirate.save(false)
assert_equal ['', ''], [@pirate.reload.catchphrase, @pirate.ship.name]
end
def test_should_allow_to_bypass_validations_on_associated_models_at_any_depth
2.times { |i| @pirate.ship.parts.create!(:name => "part #{i}") }
@pirate.catchphrase = ''
@pirate.ship.name = ''
@pirate.ship.parts.each { |part| part.name = '' }
@pirate.save(false)
values = [@pirate.reload.catchphrase, @pirate.ship.name, *@pirate.ship.parts.map(&:name)]
assert_equal ['', '', '', ''], values
end
def test_should_still_raise_an_ActiveRecordRecord_Invalid_exception_if_we_want_that
@pirate.ship.name = ''
assert_raise(ActiveRecord::RecordInvalid) do
@pirate.save!
end
end
def test_should_rollback_any_changes_if_an_exception_occurred_while_saving
before = [@pirate.catchphrase, @pirate.ship.name]
@pirate.catchphrase = 'Arr'
@pirate.ship.name = 'The Vile Insanity'
# Stub the save method of the @pirate.ship instance to raise an exception
class << @pirate.ship
def save(*args)
super
raise 'Oh noes!'
end
end
assert_raise(RuntimeError) { assert !@pirate.save }
assert_equal before, [@pirate.reload.catchphrase, @pirate.ship.name]
end
def test_should_not_load_the_associated_model
assert_queries(1) { @pirate.catchphrase = 'Arr'; @pirate.save! }
end
end
class TestAutosaveAssociationOnABelongsToAssociation < ActiveRecord::TestCase
self.use_transactional_fixtures = false
def setup
@ship = Ship.create(:name => 'Nights Dirty Lightning')
@pirate = @ship.create_pirate(:catchphrase => "Don' botharrr talkin' like one, savvy?")
end
def test_should_still_work_without_an_associated_model
@pirate.destroy
@ship.reload.name = "The Vile Insanity"
@ship.save
assert 'The Vile Insanity', @ship.reload.name
end
def test_should_automatically_save_the_associated_model
@ship.pirate.catchphrase = 'Arr'
@ship.save
assert_equal 'Arr', @ship.reload.pirate.catchphrase
end
def test_should_automatically_save_bang_the_associated_model
@ship.pirate.catchphrase = 'Arr'
@ship.save!
assert_equal 'Arr', @ship.reload.pirate.catchphrase
end
def test_should_automatically_validate_the_associated_model
@ship.pirate.catchphrase = ''
assert !@ship.valid?
assert !@ship.errors.on(:pirate_catchphrase).blank?
end
def test_should_merge_errors_on_the_associated_model_onto_the_parent_even_if_it_is_not_valid
@ship.name = nil
@ship.pirate.catchphrase = nil
assert !@ship.valid?
assert !@ship.errors.on(:name).blank?
assert !@ship.errors.on(:pirate_catchphrase).blank?
end
def test_should_still_allow_to_bypass_validations_on_the_associated_model
@ship.pirate.catchphrase = ''
@ship.name = ''
@ship.save(false)
assert_equal ['', ''], [@ship.reload.name, @ship.pirate.catchphrase]
end
def test_should_still_raise_an_ActiveRecordRecord_Invalid_exception_if_we_want_that
@ship.pirate.catchphrase = ''
assert_raise(ActiveRecord::RecordInvalid) do
@ship.save!
end
end
def test_should_rollback_any_changes_if_an_exception_occurred_while_saving
before = [@ship.pirate.catchphrase, @ship.name]
@ship.pirate.catchphrase = 'Arr'
@ship.name = 'The Vile Insanity'
# Stub the save method of the @ship.pirate instance to raise an exception
class << @ship.pirate
def save(*args)
super
raise 'Oh noes!'
end
end
assert_raise(RuntimeError) { assert !@ship.save }
# TODO: Why does using reload on @ship looses the associated pirate?
assert_equal before, [@ship.pirate.reload.catchphrase, @ship.reload.name]
end
def test_should_not_load_the_associated_model
assert_queries(1) { @ship.name = 'The Vile Insanity'; @ship.save! }
end
end
module AutosaveAssociationOnACollectionAssociationTests
def test_should_automatically_save_the_associated_models
new_names = ['Grace OMalley', 'Privateers Greed']
@pirate.send(@association_name).each_with_index { |child, i| child.name = new_names[i] }
@pirate.save
assert_equal new_names, @pirate.reload.send(@association_name).map(&:name)
end
def test_should_automatically_save_bang_the_associated_models
new_names = ['Grace OMalley', 'Privateers Greed']
@pirate.send(@association_name).each_with_index { |child, i| child.name = new_names[i] }
@pirate.save!
assert_equal new_names, @pirate.reload.send(@association_name).map(&:name)
end
def test_should_automatically_validate_the_associated_models
@pirate.send(@association_name).each { |child| child.name = '' }
assert !@pirate.valid?
assert_equal "can't be blank", @pirate.errors.on("#{@association_name}_name")
assert @pirate.errors.on(@association_name).blank?
end
def test_should_not_use_default_invalid_error_on_associated_models
@pirate.send(@association_name).build(:name => '')
assert !@pirate.valid?
assert_equal "can't be blank", @pirate.errors.on("#{@association_name}_name")
assert @pirate.errors.on(@association_name).blank?
end
def test_should_merge_errors_on_the_associated_models_onto_the_parent_even_if_it_is_not_valid
@pirate.send(@association_name).each { |child| child.name = '' }
@pirate.catchphrase = nil
assert !@pirate.valid?
assert_equal "can't be blank", @pirate.errors.on("#{@association_name}_name")
assert !@pirate.errors.on(:catchphrase).blank?
end
def test_should_allow_to_bypass_validations_on_the_associated_models_on_update
@pirate.catchphrase = ''
@pirate.send(@association_name).each { |child| child.name = '' }
assert @pirate.save(false)
assert_equal ['', '', ''], [
@pirate.reload.catchphrase,
@pirate.send(@association_name).first.name,
@pirate.send(@association_name).last.name
]
end
def test_should_validation_the_associated_models_on_create
assert_no_difference("#{ @association_name == :birds ? 'Bird' : 'Parrot' }.count") do
2.times { @pirate.send(@association_name).build }
@pirate.save(true)
end
end
def test_should_allow_to_bypass_validations_on_the_associated_models_on_create
assert_difference("#{ @association_name == :birds ? 'Bird' : 'Parrot' }.count", +2) do
2.times { @pirate.send(@association_name).build }
@pirate.save(false)
end
end
def test_should_rollback_any_changes_if_an_exception_occurred_while_saving
before = [@pirate.catchphrase, *@pirate.send(@association_name).map(&:name)]
new_names = ['Grace OMalley', 'Privateers Greed']
@pirate.catchphrase = 'Arr'
@pirate.send(@association_name).each_with_index { |child, i| child.name = new_names[i] }
# Stub the save method of the first child instance to raise an exception
class << @pirate.send(@association_name).first
def save(*args)
super
raise 'Oh noes!'
end
end
assert_raise(RuntimeError) { assert !@pirate.save }
assert_equal before, [@pirate.reload.catchphrase, *@pirate.send(@association_name).map(&:name)]
end
def test_should_still_raise_an_ActiveRecordRecord_Invalid_exception_if_we_want_that
@pirate.send(@association_name).each { |child| child.name = '' }
assert_raise(ActiveRecord::RecordInvalid) do
@pirate.save!
end
end
def test_should_not_load_the_associated_models_if_they_were_not_loaded_yet
assert_queries(1) { @pirate.catchphrase = 'Arr'; @pirate.save! }
@pirate.send(@association_name).class # hack to load the target
assert_queries(3) do
@pirate.catchphrase = 'Yarr'
new_names = ['Grace OMalley', 'Privateers Greed']
@pirate.send(@association_name).each_with_index { |child, i| child.name = new_names[i] }
@pirate.save!
end
end
end
class TestAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCase
self.use_transactional_fixtures = false
def setup
@association_name = :birds
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@child_1 = @pirate.birds.create(:name => 'Posideons Killer')
@child_2 = @pirate.birds.create(:name => 'Killer bandita Dionne')
end
include AutosaveAssociationOnACollectionAssociationTests
end
class TestAutosaveAssociationOnAHasAndBelongsToManyAssociation < ActiveRecord::TestCase
self.use_transactional_fixtures = false
def setup
@association_name = :parrots
@habtm = true
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@child_1 = @pirate.parrots.create(:name => 'Posideons Killer')
@child_2 = @pirate.parrots.create(:name => 'Killer bandita Dionne')
end
include AutosaveAssociationOnACollectionAssociationTests
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/connection_pool_test.rb | provider/vendor/rails/activerecord/test/cases/connection_pool_test.rb | require "cases/helper"
class ConnectionManagementTest < ActiveRecord::TestCase
def setup
@env = {}
@app = stub('App')
@management = ActiveRecord::ConnectionAdapters::ConnectionManagement.new(@app)
@connections_cleared = false
ActiveRecord::Base.stubs(:clear_active_connections!).with { @connections_cleared = true }
end
test "clears active connections after each call" do
@app.expects(:call).with(@env)
@management.call(@env)
assert @connections_cleared
end
test "doesn't clear active connections when running in a test case" do
@env['rack.test'] = true
@app.expects(:call).with(@env)
@management.call(@env)
assert !@connections_cleared
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/transactions_test.rb | provider/vendor/rails/activerecord/test/cases/transactions_test.rb | require "cases/helper"
require 'models/topic'
require 'models/reply'
require 'models/developer'
require 'models/book'
class TransactionTest < ActiveRecord::TestCase
self.use_transactional_fixtures = false
fixtures :topics, :developers
def setup
@first, @second = Topic.find(1, 2).sort_by { |t| t.id }
end
def test_successful
Topic.transaction do
@first.approved = true
@second.approved = false
@first.save
@second.save
end
assert Topic.find(1).approved?, "First should have been approved"
assert !Topic.find(2).approved?, "Second should have been unapproved"
end
def transaction_with_return
Topic.transaction do
@first.approved = true
@second.approved = false
@first.save
@second.save
return
end
end
def test_successful_with_return
class << Topic.connection
alias :real_commit_db_transaction :commit_db_transaction
def commit_db_transaction
$committed = true
real_commit_db_transaction
end
end
$committed = false
transaction_with_return
assert $committed
assert Topic.find(1).approved?, "First should have been approved"
assert !Topic.find(2).approved?, "Second should have been unapproved"
ensure
class << Topic.connection
alias :commit_db_transaction :real_commit_db_transaction rescue nil
end
end
def test_successful_with_instance_method
@first.transaction do
@first.approved = true
@second.approved = false
@first.save
@second.save
end
assert Topic.find(1).approved?, "First should have been approved"
assert !Topic.find(2).approved?, "Second should have been unapproved"
end
def test_failing_on_exception
begin
Topic.transaction do
@first.approved = true
@second.approved = false
@first.save
@second.save
raise "Bad things!"
end
rescue
# caught it
end
assert @first.approved?, "First should still be changed in the objects"
assert !@second.approved?, "Second should still be changed in the objects"
assert !Topic.find(1).approved?, "First shouldn't have been approved"
assert Topic.find(2).approved?, "Second should still be approved"
end
def test_raising_exception_in_callback_rollbacks_in_save
add_exception_raising_after_save_callback_to_topic
begin
@first.approved = true
@first.save
flunk
rescue => e
assert_equal "Make the transaction rollback", e.message
assert !Topic.find(1).approved?
ensure
remove_exception_raising_after_save_callback_to_topic
end
end
def test_cancellation_from_before_destroy_rollbacks_in_destroy
add_cancelling_before_destroy_with_db_side_effect_to_topic
begin
nbooks_before_destroy = Book.count
status = @first.destroy
assert !status
assert_nothing_raised(ActiveRecord::RecordNotFound) { @first.reload }
assert_equal nbooks_before_destroy, Book.count
ensure
remove_cancelling_before_destroy_with_db_side_effect_to_topic
end
end
def test_cancellation_from_before_filters_rollbacks_in_save
%w(validation save).each do |filter|
send("add_cancelling_before_#{filter}_with_db_side_effect_to_topic")
begin
nbooks_before_save = Book.count
original_author_name = @first.author_name
@first.author_name += '_this_should_not_end_up_in_the_db'
status = @first.save
assert !status
assert_equal original_author_name, @first.reload.author_name
assert_equal nbooks_before_save, Book.count
ensure
send("remove_cancelling_before_#{filter}_with_db_side_effect_to_topic")
end
end
end
def test_cancellation_from_before_filters_rollbacks_in_save!
%w(validation save).each do |filter|
send("add_cancelling_before_#{filter}_with_db_side_effect_to_topic")
begin
nbooks_before_save = Book.count
original_author_name = @first.author_name
@first.author_name += '_this_should_not_end_up_in_the_db'
@first.save!
flunk
rescue => e
assert_equal original_author_name, @first.reload.author_name
assert_equal nbooks_before_save, Book.count
ensure
send("remove_cancelling_before_#{filter}_with_db_side_effect_to_topic")
end
end
end
def test_callback_rollback_in_create
new_topic = Topic.new(
:title => "A new topic",
:author_name => "Ben",
:author_email_address => "ben@example.com",
:written_on => "2003-07-16t15:28:11.2233+01:00",
:last_read => "2004-04-15",
:bonus_time => "2005-01-30t15:28:00.00+01:00",
:content => "Have a nice day",
:approved => false)
new_record_snapshot = new_topic.new_record?
id_present = new_topic.has_attribute?(Topic.primary_key)
id_snapshot = new_topic.id
# Make sure the second save gets the after_create callback called.
2.times do
begin
add_exception_raising_after_create_callback_to_topic
new_topic.approved = true
new_topic.save
flunk
rescue => e
assert_equal "Make the transaction rollback", e.message
assert_equal new_record_snapshot, new_topic.new_record?, "The topic should have its old new_record value"
assert_equal id_snapshot, new_topic.id, "The topic should have its old id"
assert_equal id_present, new_topic.has_attribute?(Topic.primary_key)
ensure
remove_exception_raising_after_create_callback_to_topic
end
end
end
def test_nested_explicit_transactions
Topic.transaction do
Topic.transaction do
@first.approved = true
@second.approved = false
@first.save
@second.save
end
end
assert Topic.find(1).approved?, "First should have been approved"
assert !Topic.find(2).approved?, "Second should have been unapproved"
end
def test_manually_rolling_back_a_transaction
Topic.transaction do
@first.approved = true
@second.approved = false
@first.save
@second.save
raise ActiveRecord::Rollback
end
assert @first.approved?, "First should still be changed in the objects"
assert !@second.approved?, "Second should still be changed in the objects"
assert !Topic.find(1).approved?, "First shouldn't have been approved"
assert Topic.find(2).approved?, "Second should still be approved"
end
def test_invalid_keys_for_transaction
assert_raise ArgumentError do
Topic.transaction :nested => true do
end
end
end
def test_force_savepoint_in_nested_transaction
Topic.transaction do
@first.approved = true
@second.approved = false
@first.save!
@second.save!
begin
Topic.transaction :requires_new => true do
@first.happy = false
@first.save!
raise
end
rescue
end
end
assert @first.reload.approved?
assert !@second.reload.approved?
end if Topic.connection.supports_savepoints?
def test_no_savepoint_in_nested_transaction_without_force
Topic.transaction do
@first.approved = true
@second.approved = false
@first.save!
@second.save!
begin
Topic.transaction do
@first.approved = false
@first.save!
raise
end
rescue
end
end
assert !@first.reload.approved?
assert !@second.reload.approved?
end if Topic.connection.supports_savepoints?
def test_many_savepoints
Topic.transaction do
@first.content = "One"
@first.save!
begin
Topic.transaction :requires_new => true do
@first.content = "Two"
@first.save!
begin
Topic.transaction :requires_new => true do
@first.content = "Three"
@first.save!
begin
Topic.transaction :requires_new => true do
@first.content = "Four"
@first.save!
raise
end
rescue
end
@three = @first.reload.content
raise
end
rescue
end
@two = @first.reload.content
raise
end
rescue
end
@one = @first.reload.content
end
assert_equal "One", @one
assert_equal "Two", @two
assert_equal "Three", @three
end if Topic.connection.supports_savepoints?
def test_rollback_when_commit_raises
Topic.connection.expects(:begin_db_transaction)
Topic.connection.expects(:commit_db_transaction).raises('OH NOES')
Topic.connection.expects(:outside_transaction?).returns(false)
Topic.connection.expects(:rollback_db_transaction)
assert_raise RuntimeError do
Topic.transaction do
# do nothing
end
end
end
if current_adapter?(:PostgreSQLAdapter) && defined?(PGconn::PQTRANS_IDLE)
def test_outside_transaction_works
assert Topic.connection.outside_transaction?
Topic.connection.begin_db_transaction
assert !Topic.connection.outside_transaction?
Topic.connection.rollback_db_transaction
assert Topic.connection.outside_transaction?
end
def test_rollback_wont_be_executed_if_no_transaction_active
assert_raise RuntimeError do
Topic.transaction do
Topic.connection.rollback_db_transaction
Topic.connection.expects(:rollback_db_transaction).never
raise "Rails doesn't scale!"
end
end
end
def test_open_transactions_count_is_reset_to_zero_if_no_transaction_active
Topic.transaction do
Topic.transaction do
Topic.connection.rollback_db_transaction
end
assert_equal 0, Topic.connection.open_transactions
end
assert_equal 0, Topic.connection.open_transactions
end
end
def test_sqlite_add_column_in_transaction
return true unless current_adapter?(:SQLite3Adapter, :SQLiteAdapter)
# Test first if column creation/deletion works correctly when no
# transaction is in place.
#
# We go back to the connection for the column queries because
# Topic.columns is cached and won't report changes to the DB
assert_nothing_raised do
Topic.reset_column_information
Topic.connection.add_column('topics', 'stuff', :string)
assert Topic.column_names.include?('stuff')
Topic.reset_column_information
Topic.connection.remove_column('topics', 'stuff')
assert !Topic.column_names.include?('stuff')
end
if Topic.connection.supports_ddl_transactions?
assert_nothing_raised do
Topic.transaction { Topic.connection.add_column('topics', 'stuff', :string) }
end
else
Topic.transaction do
assert_raise(ActiveRecord::StatementInvalid) { Topic.connection.add_column('topics', 'stuff', :string) }
raise ActiveRecord::Rollback
end
end
end
private
def add_exception_raising_after_save_callback_to_topic
Topic.class_eval { def after_save() raise "Make the transaction rollback" end }
end
def remove_exception_raising_after_save_callback_to_topic
Topic.class_eval { remove_method :after_save }
end
def add_exception_raising_after_create_callback_to_topic
Topic.class_eval { def after_create() raise "Make the transaction rollback" end }
end
def remove_exception_raising_after_create_callback_to_topic
Topic.class_eval { remove_method :after_create }
end
%w(validation save destroy).each do |filter|
define_method("add_cancelling_before_#{filter}_with_db_side_effect_to_topic") do
Topic.class_eval "def before_#{filter}() Book.create; false end"
end
define_method("remove_cancelling_before_#{filter}_with_db_side_effect_to_topic") do
Topic.class_eval "remove_method :before_#{filter}"
end
end
end
class TransactionsWithTransactionalFixturesTest < ActiveRecord::TestCase
self.use_transactional_fixtures = true
fixtures :topics
def test_automatic_savepoint_in_outer_transaction
@first = Topic.find(1)
begin
Topic.transaction do
@first.approved = true
@first.save!
raise
end
rescue
assert !@first.reload.approved?
end
end
def test_no_automatic_savepoint_for_inner_transaction
@first = Topic.find(1)
Topic.transaction do
@first.approved = true
@first.save!
begin
Topic.transaction do
@first.approved = false
@first.save!
raise
end
rescue
end
end
assert !@first.reload.approved?
end
end if Topic.connection.supports_savepoints?
if current_adapter?(:PostgreSQLAdapter)
class ConcurrentTransactionTest < TransactionTest
use_concurrent_connections
# This will cause transactions to overlap and fail unless they are performed on
# separate database connections.
def test_transaction_per_thread
assert_nothing_raised do
threads = (1..3).map do
Thread.new do
Topic.transaction do
topic = Topic.find(1)
topic.approved = !topic.approved?
topic.save!
topic.approved = !topic.approved?
topic.save!
end
end
end
threads.each { |t| t.join }
end
end
# Test for dirty reads among simultaneous transactions.
def test_transaction_isolation__read_committed
# Should be invariant.
original_salary = Developer.find(1).salary
temporary_salary = 200000
assert_nothing_raised do
threads = (1..3).map do
Thread.new do
Developer.transaction do
# Expect original salary.
dev = Developer.find(1)
assert_equal original_salary, dev.salary
dev.salary = temporary_salary
dev.save!
# Expect temporary salary.
dev = Developer.find(1)
assert_equal temporary_salary, dev.salary
dev.salary = original_salary
dev.save!
# Expect original salary.
dev = Developer.find(1)
assert_equal original_salary, dev.salary
end
end
end
# Keep our eyes peeled.
threads << Thread.new do
10.times do
sleep 0.05
Developer.transaction do
# Always expect original salary.
assert_equal original_salary, Developer.find(1).salary
end
end
end
threads.each { |t| t.join }
end
assert_equal original_salary, Developer.find(1).salary
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/active_schema_test_mysql.rb | provider/vendor/rails/activerecord/test/cases/active_schema_test_mysql.rb | require "cases/helper"
class ActiveSchemaTest < ActiveRecord::TestCase
def setup
ActiveRecord::ConnectionAdapters::MysqlAdapter.class_eval do
alias_method :execute_without_stub, :execute
def execute(sql, name = nil) return sql end
end
end
def teardown
ActiveRecord::ConnectionAdapters::MysqlAdapter.class_eval do
remove_method :execute
alias_method :execute, :execute_without_stub
end
end
def test_drop_table
assert_equal "DROP TABLE `people`", drop_table(:people)
end
if current_adapter?(:MysqlAdapter)
def test_create_mysql_database_with_encoding
assert_equal "CREATE DATABASE `matt` DEFAULT CHARACTER SET `utf8`", create_database(:matt)
assert_equal "CREATE DATABASE `aimonetti` DEFAULT CHARACTER SET `latin1`", create_database(:aimonetti, {:charset => 'latin1'})
assert_equal "CREATE DATABASE `matt_aimonetti` DEFAULT CHARACTER SET `big5` COLLATE `big5_chinese_ci`", create_database(:matt_aimonetti, {:charset => :big5, :collation => :big5_chinese_ci})
end
def test_recreate_mysql_database_with_encoding
create_database(:luca, {:charset => 'latin1'})
assert_equal "CREATE DATABASE `luca` DEFAULT CHARACTER SET `latin1`", recreate_database(:luca, {:charset => 'latin1'})
end
end
def test_add_column
assert_equal "ALTER TABLE `people` ADD `last_name` varchar(255)", add_column(:people, :last_name, :string)
end
def test_add_column_with_limit
assert_equal "ALTER TABLE `people` ADD `key` varchar(32)", add_column(:people, :key, :string, :limit => 32)
end
def test_drop_table_with_specific_database
assert_equal "DROP TABLE `otherdb`.`people`", drop_table('otherdb.people')
end
def test_add_timestamps
with_real_execute do
begin
ActiveRecord::Base.connection.create_table :delete_me do |t|
end
ActiveRecord::Base.connection.add_timestamps :delete_me
assert column_present?('delete_me', 'updated_at', 'datetime')
assert column_present?('delete_me', 'created_at', 'datetime')
ensure
ActiveRecord::Base.connection.drop_table :delete_me rescue nil
end
end
end
def test_remove_timestamps
with_real_execute do
begin
ActiveRecord::Base.connection.create_table :delete_me do |t|
t.timestamps
end
ActiveRecord::Base.connection.remove_timestamps :delete_me
assert !column_present?('delete_me', 'updated_at', 'datetime')
assert !column_present?('delete_me', 'created_at', 'datetime')
ensure
ActiveRecord::Base.connection.drop_table :delete_me rescue nil
end
end
end
private
def with_real_execute
#we need to actually modify some data, so we make execute point to the original method
ActiveRecord::ConnectionAdapters::MysqlAdapter.class_eval do
alias_method :execute_with_stub, :execute
alias_method :execute, :execute_without_stub
end
yield
ensure
#before finishing, we restore the alias to the mock-up method
ActiveRecord::ConnectionAdapters::MysqlAdapter.class_eval do
alias_method :execute, :execute_with_stub
end
end
def method_missing(method_symbol, *arguments)
ActiveRecord::Base.connection.send(method_symbol, *arguments)
end
def column_present?(table_name, column_name, type)
results = ActiveRecord::Base.connection.select_all("SHOW FIELDS FROM #{table_name} LIKE '#{column_name}'")
results.first && results.first['Type'] == type
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/date_time_test.rb | provider/vendor/rails/activerecord/test/cases/date_time_test.rb | require "cases/helper"
require 'models/topic'
require 'models/task'
class DateTimeTest < ActiveRecord::TestCase
def test_saves_both_date_and_time
time_values = [1807, 2, 10, 15, 30, 45]
now = DateTime.civil(*time_values)
task = Task.new
task.starting = now
task.save!
# check against Time.local_time, since some platforms will return a Time instead of a DateTime
assert_equal Time.local_time(*time_values), Task.find(task.id).starting
end
def test_assign_empty_date_time
task = Task.new
task.starting = ''
task.ending = nil
assert_nil task.starting
assert_nil task.ending
end
def test_assign_empty_date
topic = Topic.new
topic.last_read = ''
assert_nil topic.last_read
end
def test_assign_empty_time
topic = Topic.new
topic.bonus_time = ''
assert_nil topic.bonus_time
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/readonly_test.rb | provider/vendor/rails/activerecord/test/cases/readonly_test.rb | require "cases/helper"
require 'models/post'
require 'models/comment'
require 'models/developer'
require 'models/project'
require 'models/reader'
require 'models/person'
# Dummy class methods to test implicit association scoping.
def Comment.foo() find :first end
def Project.foo() find :first end
class ReadOnlyTest < ActiveRecord::TestCase
fixtures :posts, :comments, :developers, :projects, :developers_projects
def test_cant_save_readonly_record
dev = Developer.find(1)
assert !dev.readonly?
dev.readonly!
assert dev.readonly?
assert_nothing_raised do
dev.name = 'Luscious forbidden fruit.'
assert !dev.save
dev.name = 'Forbidden.'
end
assert_raise(ActiveRecord::ReadOnlyRecord) { dev.save }
assert_raise(ActiveRecord::ReadOnlyRecord) { dev.save! }
end
def test_find_with_readonly_option
Developer.find(:all).each { |d| assert !d.readonly? }
Developer.find(:all, :readonly => false).each { |d| assert !d.readonly? }
Developer.find(:all, :readonly => true).each { |d| assert d.readonly? }
end
def test_find_with_joins_option_implies_readonly
# Blank joins don't count.
Developer.find(:all, :joins => ' ').each { |d| assert !d.readonly? }
Developer.find(:all, :joins => ' ', :readonly => false).each { |d| assert !d.readonly? }
# Others do.
Developer.find(:all, :joins => ', projects').each { |d| assert d.readonly? }
Developer.find(:all, :joins => ', projects', :readonly => false).each { |d| assert !d.readonly? }
end
def test_habtm_find_readonly
dev = Developer.find(1)
assert !dev.projects.empty?
assert dev.projects.all?(&:readonly?)
assert dev.projects.find(:all).all?(&:readonly?)
assert dev.projects.find(:all, :readonly => true).all?(&:readonly?)
end
def test_has_many_find_readonly
post = Post.find(1)
assert !post.comments.empty?
assert !post.comments.any?(&:readonly?)
assert !post.comments.find(:all).any?(&:readonly?)
assert post.comments.find(:all, :readonly => true).all?(&:readonly?)
end
def test_has_many_with_through_is_not_implicitly_marked_readonly
assert people = Post.find(1).people
assert !people.any?(&:readonly?)
end
def test_readonly_scoping
Post.with_scope(:find => { :conditions => '1=1' }) do
assert !Post.find(1).readonly?
assert Post.find(1, :readonly => true).readonly?
assert !Post.find(1, :readonly => false).readonly?
end
Post.with_scope(:find => { :joins => ' ' }) do
assert !Post.find(1).readonly?
assert Post.find(1, :readonly => true).readonly?
assert !Post.find(1, :readonly => false).readonly?
end
# Oracle barfs on this because the join includes unqualified and
# conflicting column names
unless current_adapter?(:OracleAdapter)
Post.with_scope(:find => { :joins => ', developers' }) do
assert Post.find(1).readonly?
assert Post.find(1, :readonly => true).readonly?
assert !Post.find(1, :readonly => false).readonly?
end
end
Post.with_scope(:find => { :readonly => true }) do
assert Post.find(1).readonly?
assert Post.find(1, :readonly => true).readonly?
assert !Post.find(1, :readonly => false).readonly?
end
end
def test_association_collection_method_missing_scoping_not_readonly
assert !Developer.find(1).projects.foo.readonly?
assert !Post.find(1).comments.foo.readonly?
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/ar_schema_test.rb | provider/vendor/rails/activerecord/test/cases/ar_schema_test.rb | require "cases/helper"
if ActiveRecord::Base.connection.supports_migrations?
class ActiveRecordSchemaTest < ActiveRecord::TestCase
self.use_transactional_fixtures = false
def setup
@connection = ActiveRecord::Base.connection
end
def teardown
@connection.drop_table :fruits rescue nil
end
def test_schema_define
ActiveRecord::Schema.define(:version => 7) do
create_table :fruits do |t|
t.column :color, :string
t.column :fruit_size, :string # NOTE: "size" is reserved in Oracle
t.column :texture, :string
t.column :flavor, :string
end
end
assert_nothing_raised { @connection.select_all "SELECT * FROM fruits" }
assert_nothing_raised { @connection.select_all "SELECT * FROM schema_migrations" }
assert_equal 7, ActiveRecord::Migrator::current_version
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/lifecycle_test.rb | provider/vendor/rails/activerecord/test/cases/lifecycle_test.rb | require "cases/helper"
require 'models/topic'
require 'models/developer'
require 'models/reply'
require 'models/minimalistic'
class Topic; def after_find() end end
class Developer; def after_find() end end
class SpecialDeveloper < Developer; end
class TopicManualObserver
include Singleton
attr_reader :action, :object, :callbacks
def initialize
Topic.add_observer(self)
@callbacks = []
end
def update(callback_method, object)
@callbacks << { "callback_method" => callback_method, "object" => object }
end
def has_been_notified?
!@callbacks.empty?
end
end
class TopicaAuditor < ActiveRecord::Observer
observe :topic
attr_reader :topic
def after_find(topic)
@topic = topic
end
end
class TopicObserver < ActiveRecord::Observer
attr_reader :topic
def after_find(topic)
@topic = topic
end
end
class MinimalisticObserver < ActiveRecord::Observer
attr_reader :minimalistic
def after_find(minimalistic)
@minimalistic = minimalistic
end
end
class MultiObserver < ActiveRecord::Observer
attr_reader :record
def self.observed_class() [ Topic, Developer ] end
cattr_reader :last_inherited
@@last_inherited = nil
def observed_class_inherited_with_testing(subclass)
observed_class_inherited_without_testing(subclass)
@@last_inherited = subclass
end
alias_method_chain :observed_class_inherited, :testing
def after_find(record)
@record = record
end
end
class LifecycleTest < ActiveRecord::TestCase
fixtures :topics, :developers, :minimalistics
def test_before_destroy
original_count = Topic.count
(topic_to_be_destroyed = Topic.find(1)).destroy
assert_equal original_count - (1 + topic_to_be_destroyed.replies.size), Topic.count
end
def test_after_save
ActiveRecord::Base.observers = :topic_manual_observer
ActiveRecord::Base.instantiate_observers
topic = Topic.find(1)
topic.title = "hello"
topic.save
assert TopicManualObserver.instance.has_been_notified?
assert_equal :after_save, TopicManualObserver.instance.callbacks.last["callback_method"]
end
def test_observer_update_on_save
ActiveRecord::Base.observers = TopicManualObserver
ActiveRecord::Base.instantiate_observers
topic = Topic.find(1)
assert TopicManualObserver.instance.has_been_notified?
assert_equal :after_find, TopicManualObserver.instance.callbacks.first["callback_method"]
end
def test_auto_observer
topic_observer = TopicaAuditor.instance
assert_nil TopicaAuditor.observed_class
assert_equal [Topic], TopicaAuditor.instance.observed_classes.to_a
topic = Topic.find(1)
assert_equal topic.title, topic_observer.topic.title
end
def test_inferred_auto_observer
topic_observer = TopicObserver.instance
assert_equal Topic, TopicObserver.observed_class
topic = Topic.find(1)
assert_equal topic.title, topic_observer.topic.title
end
def test_observing_two_classes
multi_observer = MultiObserver.instance
topic = Topic.find(1)
assert_equal topic.title, multi_observer.record.title
developer = Developer.find(1)
assert_equal developer.name, multi_observer.record.name
end
def test_observing_subclasses
multi_observer = MultiObserver.instance
developer = SpecialDeveloper.find(1)
assert_equal developer.name, multi_observer.record.name
klass = Class.new(Developer)
assert_equal klass, multi_observer.last_inherited
developer = klass.find(1)
assert_equal developer.name, multi_observer.record.name
end
def test_after_find_can_be_observed_when_its_not_defined_on_the_model
observer = MinimalisticObserver.instance
assert_equal Minimalistic, MinimalisticObserver.observed_class
minimalistic = Minimalistic.find(1)
assert_equal minimalistic, observer.minimalistic
end
def test_after_find_can_be_observed_when_its_defined_on_the_model
observer = TopicObserver.instance
assert_equal Topic, TopicObserver.observed_class
topic = Topic.find(1)
assert_equal topic, observer.topic
end
def test_after_find_is_not_created_if_its_not_used
# use a fresh class so an observer can't have defined an
# after_find on it
model_class = Class.new(ActiveRecord::Base)
observer_class = Class.new(ActiveRecord::Observer)
observer_class.observe(model_class)
observer = observer_class.instance
assert !model_class.method_defined?(:after_find)
end
def test_after_find_is_not_clobbered_if_it_already_exists
# use a fresh observer class so we can instantiate it (Observer is
# a Singleton)
model_class = Class.new(ActiveRecord::Base) do
def after_find; end
end
original_method = model_class.instance_method(:after_find)
observer_class = Class.new(ActiveRecord::Observer) do
def after_find; end
end
observer_class.observe(model_class)
observer = observer_class.instance
assert_equal original_method, model_class.instance_method(:after_find)
end
def test_invalid_observer
assert_raise(ArgumentError) { Topic.observers = Object.new; Topic.instantiate_observers }
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/modules_test.rb | provider/vendor/rails/activerecord/test/cases/modules_test.rb | require "cases/helper"
require 'models/company_in_module'
class ModulesTest < ActiveRecord::TestCase
fixtures :accounts, :companies, :projects, :developers
def setup
# need to make sure Object::Firm and Object::Client are not defined,
# so that constantize will not be able to cheat when having to load namespaced classes
@undefined_consts = {}
[:Firm, :Client].each do |const|
@undefined_consts.merge! const => Object.send(:remove_const, const) if Object.const_defined?(const)
end
end
def teardown
# reinstate the constants that we undefined in the setup
@undefined_consts.each do |constant, value|
Object.send :const_set, constant, value unless value.nil?
end
end
def test_module_spanning_associations
firm = MyApplication::Business::Firm.find(:first)
assert !firm.clients.empty?, "Firm should have clients"
assert_nil firm.class.table_name.match('::'), "Firm shouldn't have the module appear in its table name"
end
def test_module_spanning_has_and_belongs_to_many_associations
project = MyApplication::Business::Project.find(:first)
project.developers << MyApplication::Business::Developer.create("name" => "John")
assert "John", project.developers.last.name
end
def test_associations_spanning_cross_modules
account = MyApplication::Billing::Account.find(:first, :order => 'id')
assert_kind_of MyApplication::Business::Firm, account.firm
assert_kind_of MyApplication::Billing::Firm, account.qualified_billing_firm
assert_kind_of MyApplication::Billing::Firm, account.unqualified_billing_firm
assert_kind_of MyApplication::Billing::Nested::Firm, account.nested_qualified_billing_firm
assert_kind_of MyApplication::Billing::Nested::Firm, account.nested_unqualified_billing_firm
end
def test_find_account_and_include_company
account = MyApplication::Billing::Account.find(1, :include => :firm)
assert_kind_of MyApplication::Business::Firm, account.instance_variable_get('@firm')
assert_kind_of MyApplication::Business::Firm, account.firm
end
def test_table_name
assert_equal 'accounts', MyApplication::Billing::Account.table_name, 'table_name for ActiveRecord model in module'
assert_equal 'companies', MyApplication::Business::Client.table_name, 'table_name for ActiveRecord model subclass'
assert_equal 'company_contacts', MyApplication::Business::Client::Contact.table_name, 'table_name for ActiveRecord model enclosed by another ActiveRecord model'
end
def test_assign_ids
firm = MyApplication::Business::Firm.first
assert_nothing_raised NameError, "Should be able to resolve all class constants via reflection" do
firm.client_ids = [MyApplication::Business::Client.first.id]
end
end
# need to add an eager loading condition to force the eager loading model into
# the old join model, to test that. See http://dev.rubyonrails.org/ticket/9640
def test_eager_loading_in_modules
clients = []
assert_nothing_raised NameError, "Should be able to resolve all class constants via reflection" do
clients << MyApplication::Business::Client.find(3, :include => {:firm => :account}, :conditions => 'accounts.id IS NOT NULL')
clients << MyApplication::Business::Client.find(3, :include => {:firm => :account})
end
clients.each do |client|
assert_no_queries do
assert_not_nil(client.firm.account)
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/copy_table_test_sqlite.rb | provider/vendor/rails/activerecord/test/cases/copy_table_test_sqlite.rb | require "cases/helper"
class CopyTableTest < ActiveRecord::TestCase
fixtures :companies, :comments
def setup
@connection = ActiveRecord::Base.connection
class << @connection
public :copy_table, :table_structure, :indexes
end
end
def test_copy_table(from = 'customers', to = 'customers2', options = {})
assert_nothing_raised {copy_table(from, to, options)}
assert_equal row_count(from), row_count(to)
if block_given?
yield from, to, options
else
assert_equal column_names(from), column_names(to)
end
@connection.drop_table(to) rescue nil
end
def test_copy_table_renaming_column
test_copy_table('customers', 'customers2',
:rename => {'name' => 'person_name'}) do |from, to, options|
expected = column_values(from, 'name')
assert expected.any?, 'only nils in resultset; real values are needed'
assert_equal expected, column_values(to, 'person_name')
end
end
def test_copy_table_with_index
test_copy_table('comments', 'comments_with_index') do
@connection.add_index('comments_with_index', ['post_id', 'type'])
test_copy_table('comments_with_index', 'comments_with_index2') do
assert_equal table_indexes_without_name('comments_with_index'),
table_indexes_without_name('comments_with_index2')
end
end
end
def test_copy_table_without_primary_key
test_copy_table('developers_projects', 'programmers_projects')
end
def test_copy_table_with_id_col_that_is_not_primary_key
test_copy_table('goofy_string_id', 'goofy_string_id2') do |from, to, options|
original_id = @connection.columns('goofy_string_id').detect{|col| col.name == 'id' }
copied_id = @connection.columns('goofy_string_id2').detect{|col| col.name == 'id' }
assert_equal original_id.type, copied_id.type
assert_equal original_id.sql_type, copied_id.sql_type
assert_equal original_id.limit, copied_id.limit
assert_equal original_id.primary, copied_id.primary
end
end
protected
def copy_table(from, to, options = {})
@connection.copy_table(from, to, {:temporary => true}.merge(options))
end
def column_names(table)
@connection.table_structure(table).map {|column| column['name']}
end
def column_values(table, column)
@connection.select_all("SELECT #{column} FROM #{table} ORDER BY id").map {|row| row[column]}
end
def table_indexes_without_name(table)
@connection.indexes('comments_with_index').delete(:name)
end
def row_count(table)
@connection.select_one("SELECT COUNT(*) AS count FROM #{table}")['count']
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/synonym_test_oracle.rb | provider/vendor/rails/activerecord/test/cases/synonym_test_oracle.rb | require "cases/helper"
require 'models/topic'
require 'models/subject'
# confirm that synonyms work just like tables; in this case
# the "subjects" table in Oracle (defined in oci.sql) is just
# a synonym to the "topics" table
class TestOracleSynonym < ActiveRecord::TestCase
def test_oracle_synonym
topic = Topic.new
subject = Subject.new
assert_equal(topic.attributes, subject.attributes)
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/inheritance_test.rb | provider/vendor/rails/activerecord/test/cases/inheritance_test.rb | require "cases/helper"
require 'models/company'
require 'models/project'
require 'models/subscriber'
class InheritanceTest < ActiveRecord::TestCase
fixtures :companies, :projects, :subscribers, :accounts
def test_class_with_store_full_sti_class_returns_full_name
old = ActiveRecord::Base.store_full_sti_class
ActiveRecord::Base.store_full_sti_class = true
assert_equal 'Namespaced::Company', Namespaced::Company.sti_name
ensure
ActiveRecord::Base.store_full_sti_class = old
end
def test_class_without_store_full_sti_class_returns_demodulized_name
old = ActiveRecord::Base.store_full_sti_class
ActiveRecord::Base.store_full_sti_class = false
assert_equal 'Company', Namespaced::Company.sti_name
ensure
ActiveRecord::Base.store_full_sti_class = old
end
def test_should_store_demodulized_class_name_with_store_full_sti_class_option_disabled
old = ActiveRecord::Base.store_full_sti_class
ActiveRecord::Base.store_full_sti_class = false
item = Namespaced::Company.new
assert_equal 'Company', item[:type]
ensure
ActiveRecord::Base.store_full_sti_class = old
end
def test_should_store_full_class_name_with_store_full_sti_class_option_enabled
old = ActiveRecord::Base.store_full_sti_class
ActiveRecord::Base.store_full_sti_class = true
item = Namespaced::Company.new
assert_equal 'Namespaced::Company', item[:type]
ensure
ActiveRecord::Base.store_full_sti_class = old
end
def test_different_namespace_subclass_should_load_correctly_with_store_full_sti_class_option
old = ActiveRecord::Base.store_full_sti_class
ActiveRecord::Base.store_full_sti_class = true
item = Namespaced::Company.create :name => "Wolverine 2"
assert_not_nil Company.find(item.id)
assert_not_nil Namespaced::Company.find(item.id)
ensure
ActiveRecord::Base.store_full_sti_class = old
end
def test_company_descends_from_active_record
assert_raise(NoMethodError) { ActiveRecord::Base.descends_from_active_record? }
assert AbstractCompany.descends_from_active_record?, 'AbstractCompany should descend from ActiveRecord::Base'
assert Company.descends_from_active_record?, 'Company should descend from ActiveRecord::Base'
assert !Class.new(Company).descends_from_active_record?, 'Company subclass should not descend from ActiveRecord::Base'
end
def test_a_bad_type_column
#SQLServer need to turn Identity Insert On before manually inserting into the Identity column
if current_adapter?(:SybaseAdapter)
Company.connection.execute "SET IDENTITY_INSERT companies ON"
end
Company.connection.insert "INSERT INTO companies (id, #{QUOTED_TYPE}, name) VALUES(100, 'bad_class!', 'Not happening')"
#We then need to turn it back Off before continuing.
if current_adapter?(:SybaseAdapter)
Company.connection.execute "SET IDENTITY_INSERT companies OFF"
end
assert_raise(ActiveRecord::SubclassNotFound) { Company.find(100) }
end
def test_inheritance_find
assert Company.find(1).kind_of?(Firm), "37signals should be a firm"
assert Firm.find(1).kind_of?(Firm), "37signals should be a firm"
assert Company.find(2).kind_of?(Client), "Summit should be a client"
assert Client.find(2).kind_of?(Client), "Summit should be a client"
end
def test_alt_inheritance_find
switch_to_alt_inheritance_column
test_inheritance_find
switch_to_default_inheritance_column
end
def test_inheritance_find_all
companies = Company.find(:all, :order => 'id')
assert companies[0].kind_of?(Firm), "37signals should be a firm"
assert companies[1].kind_of?(Client), "Summit should be a client"
end
def test_alt_inheritance_find_all
switch_to_alt_inheritance_column
test_inheritance_find_all
switch_to_default_inheritance_column
end
def test_inheritance_save
firm = Firm.new
firm.name = "Next Angle"
firm.save
next_angle = Company.find(firm.id)
assert next_angle.kind_of?(Firm), "Next Angle should be a firm"
end
def test_alt_inheritance_save
switch_to_alt_inheritance_column
test_inheritance_save
switch_to_default_inheritance_column
end
def test_inheritance_condition
assert_equal 9, Company.count
assert_equal 2, Firm.count
assert_equal 3, Client.count
end
def test_alt_inheritance_condition
switch_to_alt_inheritance_column
test_inheritance_condition
switch_to_default_inheritance_column
end
def test_finding_incorrect_type_data
assert_raise(ActiveRecord::RecordNotFound) { Firm.find(2) }
assert_nothing_raised { Firm.find(1) }
end
def test_alt_finding_incorrect_type_data
switch_to_alt_inheritance_column
test_finding_incorrect_type_data
switch_to_default_inheritance_column
end
def test_update_all_within_inheritance
Client.update_all "name = 'I am a client'"
assert_equal "I am a client", Client.find(:all).first.name
assert_equal "37signals", Firm.find(:all).first.name
end
def test_alt_update_all_within_inheritance
switch_to_alt_inheritance_column
test_update_all_within_inheritance
switch_to_default_inheritance_column
end
def test_destroy_all_within_inheritance
Client.destroy_all
assert_equal 0, Client.count
assert_equal 2, Firm.count
end
def test_alt_destroy_all_within_inheritance
switch_to_alt_inheritance_column
test_destroy_all_within_inheritance
switch_to_default_inheritance_column
end
def test_find_first_within_inheritance
assert_kind_of Firm, Company.find(:first, :conditions => "name = '37signals'")
assert_kind_of Firm, Firm.find(:first, :conditions => "name = '37signals'")
assert_nil Client.find(:first, :conditions => "name = '37signals'")
end
def test_alt_find_first_within_inheritance
switch_to_alt_inheritance_column
test_find_first_within_inheritance
switch_to_default_inheritance_column
end
def test_complex_inheritance
very_special_client = VerySpecialClient.create("name" => "veryspecial")
assert_equal very_special_client, VerySpecialClient.find(:first, :conditions => "name = 'veryspecial'")
assert_equal very_special_client, SpecialClient.find(:first, :conditions => "name = 'veryspecial'")
assert_equal very_special_client, Company.find(:first, :conditions => "name = 'veryspecial'")
assert_equal very_special_client, Client.find(:first, :conditions => "name = 'veryspecial'")
assert_equal 1, Client.find(:all, :conditions => "name = 'Summit'").size
assert_equal very_special_client, Client.find(very_special_client.id)
end
def test_alt_complex_inheritance
switch_to_alt_inheritance_column
test_complex_inheritance
switch_to_default_inheritance_column
end
def test_eager_load_belongs_to_something_inherited
account = Account.find(1, :include => :firm)
assert_not_nil account.instance_variable_get("@firm"), "nil proves eager load failed"
end
def test_eager_load_belongs_to_primary_key_quoting
con = Account.connection
assert_sql(/\(#{con.quote_table_name('companies')}.#{con.quote_column_name('id')} = 1\)/) do
Account.find(1, :include => :firm)
end
end
def test_alt_eager_loading
switch_to_alt_inheritance_column
test_eager_load_belongs_to_something_inherited
switch_to_default_inheritance_column
end
def test_inheritance_without_mapping
assert_kind_of SpecialSubscriber, SpecialSubscriber.find("webster132")
assert_nothing_raised { s = SpecialSubscriber.new("name" => "And breaaaaathe!"); s.id = 'roger'; s.save }
end
private
def switch_to_alt_inheritance_column
# we don't want misleading test results, so get rid of the values in the type column
Company.find(:all, :order => 'id').each do |c|
c['type'] = nil
c.save
end
[ Company, Firm, Client].each { |klass| klass.reset_column_information }
Company.set_inheritance_column('ruby_type')
end
def switch_to_default_inheritance_column
[ Company, Firm, Client].each { |klass| klass.reset_column_information }
Company.set_inheritance_column('type')
end
end
class InheritanceComputeTypeTest < ActiveRecord::TestCase
fixtures :companies
def setup
ActiveSupport::Dependencies.log_activity = true
end
def teardown
ActiveSupport::Dependencies.log_activity = false
self.class.const_remove :FirmOnTheFly rescue nil
Firm.const_remove :FirmOnTheFly rescue nil
end
def test_instantiation_doesnt_try_to_require_corresponding_file
foo = Firm.find(:first).clone
foo.ruby_type = foo.type = 'FirmOnTheFly'
foo.save!
# Should fail without FirmOnTheFly in the type condition.
assert_raise(ActiveRecord::RecordNotFound) { Firm.find(foo.id) }
# Nest FirmOnTheFly in the test case where Dependencies won't see it.
self.class.const_set :FirmOnTheFly, Class.new(Firm)
assert_raise(ActiveRecord::SubclassNotFound) { Firm.find(foo.id) }
# Nest FirmOnTheFly in Firm where Dependencies will see it.
# This is analogous to nesting models in a migration.
Firm.const_set :FirmOnTheFly, Class.new(Firm)
# And instantiate will find the existing constant rather than trying
# to require firm_on_the_fly.
assert_nothing_raised { assert_kind_of Firm::FirmOnTheFly, Firm.find(foo.id) }
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/adapter_test.rb | provider/vendor/rails/activerecord/test/cases/adapter_test.rb | require "cases/helper"
class AdapterTest < ActiveRecord::TestCase
def setup
@connection = ActiveRecord::Base.connection
end
def test_tables
tables = @connection.tables
assert tables.include?("accounts")
assert tables.include?("authors")
assert tables.include?("tasks")
assert tables.include?("topics")
end
def test_table_exists?
assert @connection.table_exists?("accounts")
assert !@connection.table_exists?("nonexistingtable")
end
def test_indexes
idx_name = "accounts_idx"
if @connection.respond_to?(:indexes)
indexes = @connection.indexes("accounts")
assert indexes.empty?
@connection.add_index :accounts, :firm_id, :name => idx_name
indexes = @connection.indexes("accounts")
assert_equal "accounts", indexes.first.table
# OpenBase does not have the concept of a named index
# Indexes are merely properties of columns.
assert_equal idx_name, indexes.first.name unless current_adapter?(:OpenBaseAdapter)
assert !indexes.first.unique
assert_equal ["firm_id"], indexes.first.columns
else
warn "#{@connection.class} does not respond to #indexes"
end
ensure
@connection.remove_index(:accounts, :name => idx_name) rescue nil
end
def test_current_database
if @connection.respond_to?(:current_database)
assert_equal ENV['ARUNIT_DB_NAME'] || "activerecord_unittest", @connection.current_database
end
end
if current_adapter?(:MysqlAdapter)
def test_charset
assert_not_nil @connection.charset
assert_not_equal 'character_set_database', @connection.charset
assert_equal @connection.show_variable('character_set_database'), @connection.charset
end
def test_collation
assert_not_nil @connection.collation
assert_not_equal 'collation_database', @connection.collation
assert_equal @connection.show_variable('collation_database'), @connection.collation
end
def test_show_nonexistent_variable_returns_nil
assert_nil @connection.show_variable('foo_bar_baz')
end
def test_not_specifying_database_name_for_cross_database_selects
assert_nothing_raised do
ActiveRecord::Base.establish_connection({
:adapter => 'mysql',
:username => 'rails'
})
ActiveRecord::Base.connection.execute "SELECT activerecord_unittest.pirates.*, activerecord_unittest2.courses.* FROM activerecord_unittest.pirates, activerecord_unittest2.courses"
end
ActiveRecord::Base.establish_connection 'arunit'
end
end
if current_adapter?(:PostgreSQLAdapter)
def test_encoding
assert_not_nil @connection.encoding
end
end
def test_table_alias
def @connection.test_table_alias_length() 10; end
class << @connection
alias_method :old_table_alias_length, :table_alias_length
alias_method :table_alias_length, :test_table_alias_length
end
assert_equal 'posts', @connection.table_alias_for('posts')
assert_equal 'posts_comm', @connection.table_alias_for('posts_comments')
assert_equal 'dbo_posts', @connection.table_alias_for('dbo.posts')
class << @connection
remove_method :table_alias_length
alias_method :table_alias_length, :old_table_alias_length
end
end
# test resetting sequences in odd tables in postgreSQL
if ActiveRecord::Base.connection.respond_to?(:reset_pk_sequence!)
require 'models/movie'
require 'models/subscriber'
def test_reset_empty_table_with_custom_pk
Movie.delete_all
Movie.connection.reset_pk_sequence! 'movies'
assert_equal 1, Movie.create(:name => 'fight club').id
end
if ActiveRecord::Base.connection.adapter_name != "FrontBase"
def test_reset_table_with_non_integer_pk
Subscriber.delete_all
Subscriber.connection.reset_pk_sequence! 'subscribers'
sub = Subscriber.new(:name => 'robert drake')
sub.id = 'bob drake'
assert_nothing_raised { sub.save! }
end
end
end
def test_add_limit_offset_should_sanitize_sql_injection_for_limit_without_comas
sql_inject = "1 select * from schema"
assert_equal " LIMIT 1", @connection.add_limit_offset!("", :limit=>sql_inject)
if current_adapter?(:MysqlAdapter)
assert_equal " LIMIT 7, 1", @connection.add_limit_offset!("", :limit=>sql_inject, :offset=>7)
else
assert_equal " LIMIT 1 OFFSET 7", @connection.add_limit_offset!("", :limit=>sql_inject, :offset=>7)
end
end
def test_add_limit_offset_should_sanitize_sql_injection_for_limit_with_comas
sql_inject = "1, 7 procedure help()"
if current_adapter?(:MysqlAdapter)
assert_equal " LIMIT 1,7", @connection.add_limit_offset!("", :limit=>sql_inject)
assert_equal " LIMIT 7, 1", @connection.add_limit_offset!("", :limit=> '1 ; DROP TABLE USERS', :offset=>7)
else
assert_equal " LIMIT 1,7", @connection.add_limit_offset!("", :limit=>sql_inject)
assert_equal " LIMIT 1,7 OFFSET 7", @connection.add_limit_offset!("", :limit=>sql_inject, :offset=>7)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/active_schema_test_postgresql.rb | provider/vendor/rails/activerecord/test/cases/active_schema_test_postgresql.rb | require 'cases/helper'
class PostgresqlActiveSchemaTest < Test::Unit::TestCase
def setup
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.class_eval do
alias_method :real_execute, :execute
def execute(sql, name = nil) sql end
end
end
def teardown
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.send(:alias_method, :execute, :real_execute)
end
def test_create_database_with_encoding
assert_equal %(CREATE DATABASE "matt" ENCODING = 'utf8'), create_database(:matt)
assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'latin1'), create_database(:aimonetti, :encoding => :latin1)
end
private
def method_missing(method_symbol, *arguments)
ActiveRecord::Base.connection.send(method_symbol, *arguments)
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/finder_test.rb | provider/vendor/rails/activerecord/test/cases/finder_test.rb | require "cases/helper"
require 'models/post'
require 'models/author'
require 'models/categorization'
require 'models/comment'
require 'models/company'
require 'models/topic'
require 'models/reply'
require 'models/entrant'
require 'models/developer'
require 'models/customer'
require 'models/job'
require 'models/categorization'
class DynamicFinderMatchTest < ActiveRecord::TestCase
def test_find_no_match
assert_nil ActiveRecord::DynamicFinderMatch.match("not_a_finder")
end
def test_find_by
match = ActiveRecord::DynamicFinderMatch.match("find_by_age_and_sex_and_location")
assert_not_nil match
assert match.finder?
assert_equal :first, match.finder
assert_equal %w(age sex location), match.attribute_names
end
def find_by_bang
match = ActiveRecord::DynamicFinderMatch.match("find_by_age_and_sex_and_location!")
assert_not_nil match
assert match.finder?
assert match.bang?
assert_equal :first, match.finder
assert_equal %w(age sex location), match.attribute_names
end
def test_find_all_by
match = ActiveRecord::DynamicFinderMatch.match("find_all_by_age_and_sex_and_location")
assert_not_nil match
assert match.finder?
assert_equal :all, match.finder
assert_equal %w(age sex location), match.attribute_names
end
def test_find_or_initialize_by
match = ActiveRecord::DynamicFinderMatch.match("find_or_initialize_by_age_and_sex_and_location")
assert_not_nil match
assert !match.finder?
assert match.instantiator?
assert_equal :first, match.finder
assert_equal :new, match.instantiator
assert_equal %w(age sex location), match.attribute_names
end
def test_find_or_create_by
match = ActiveRecord::DynamicFinderMatch.match("find_or_create_by_age_and_sex_and_location")
assert_not_nil match
assert !match.finder?
assert match.instantiator?
assert_equal :first, match.finder
assert_equal :create, match.instantiator
assert_equal %w(age sex location), match.attribute_names
end
end
class FinderTest < ActiveRecord::TestCase
fixtures :companies, :topics, :entrants, :developers, :developers_projects, :posts, :comments, :accounts, :authors, :customers
def test_find
assert_equal(topics(:first).title, Topic.find(1).title)
end
# find should handle strings that come from URLs
# (example: Category.find(params[:id]))
def test_find_with_string
assert_equal(Topic.find(1).title,Topic.find("1").title)
end
def test_exists
assert Topic.exists?(1)
assert Topic.exists?("1")
assert Topic.exists?(:author_name => "David")
assert Topic.exists?(:author_name => "Mary", :approved => true)
assert Topic.exists?(["parent_id = ?", 1])
assert !Topic.exists?(45)
begin
assert !Topic.exists?("foo")
rescue ActiveRecord::StatementInvalid
# PostgreSQL complains about string comparison with integer field
rescue Exception
flunk
end
assert_raise(NoMethodError) { Topic.exists?([1,2]) }
end
def test_exists_returns_true_with_one_record_and_no_args
assert Topic.exists?
end
def test_does_not_exist_with_empty_table_and_no_args_given
Topic.delete_all
assert !Topic.exists?
end
def test_exists_with_aggregate_having_three_mappings
existing_address = customers(:david).address
assert Customer.exists?(:address => existing_address)
end
def test_exists_with_aggregate_having_three_mappings_with_one_difference
existing_address = customers(:david).address
assert !Customer.exists?(:address =>
Address.new(existing_address.street, existing_address.city, existing_address.country + "1"))
assert !Customer.exists?(:address =>
Address.new(existing_address.street, existing_address.city + "1", existing_address.country))
assert !Customer.exists?(:address =>
Address.new(existing_address.street + "1", existing_address.city, existing_address.country))
end
def test_exists_with_scoped_include
Developer.with_scope(:find => { :include => :projects, :order => "projects.name" }) do
assert Developer.exists?
end
end
def test_find_by_array_of_one_id
assert_kind_of(Array, Topic.find([ 1 ]))
assert_equal(1, Topic.find([ 1 ]).length)
end
def test_find_by_ids
assert_equal 2, Topic.find(1, 2).size
assert_equal topics(:second).title, Topic.find([2]).first.title
end
def test_find_by_ids_with_limit_and_offset
assert_equal 2, Entrant.find([1,3,2], :limit => 2).size
assert_equal 1, Entrant.find([1,3,2], :limit => 3, :offset => 2).size
# Also test an edge case: If you have 11 results, and you set a
# limit of 3 and offset of 9, then you should find that there
# will be only 2 results, regardless of the limit.
devs = Developer.find :all
last_devs = Developer.find devs.map(&:id), :limit => 3, :offset => 9
assert_equal 2, last_devs.size
end
def test_find_an_empty_array
assert_equal [], Topic.find([])
end
def test_find_by_ids_missing_one
assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1, 2, 45) }
end
def test_find_all_with_limit
assert_equal(2, Entrant.find(:all, :limit => 2).size)
assert_equal(0, Entrant.find(:all, :limit => 0).size)
end
def test_find_all_with_prepared_limit_and_offset
entrants = Entrant.find(:all, :order => "id ASC", :limit => 2, :offset => 1)
assert_equal(2, entrants.size)
assert_equal(entrants(:second).name, entrants.first.name)
assert_equal 3, Entrant.count
entrants = Entrant.find(:all, :order => "id ASC", :limit => 2, :offset => 2)
assert_equal(1, entrants.size)
assert_equal(entrants(:third).name, entrants.first.name)
end
def test_find_all_with_limit_and_offset_and_multiple_order_clauses
first_three_posts = Post.find :all, :order => 'author_id, id', :limit => 3, :offset => 0
second_three_posts = Post.find :all, :order => ' author_id,id ', :limit => 3, :offset => 3
last_posts = Post.find :all, :order => ' author_id, id ', :limit => 3, :offset => 6
assert_equal [[0,3],[1,1],[1,2]], first_three_posts.map { |p| [p.author_id, p.id] }
assert_equal [[1,4],[1,5],[1,6]], second_three_posts.map { |p| [p.author_id, p.id] }
assert_equal [[2,7]], last_posts.map { |p| [p.author_id, p.id] }
end
def test_find_with_group
developers = Developer.find(:all, :group => "salary", :select => "salary")
assert_equal 4, developers.size
assert_equal 4, developers.map(&:salary).uniq.size
end
def test_find_with_group_and_having
developers = Developer.find(:all, :group => "salary", :having => "sum(salary) > 10000", :select => "salary")
assert_equal 3, developers.size
assert_equal 3, developers.map(&:salary).uniq.size
assert developers.all? { |developer| developer.salary > 10000 }
end
def test_find_with_group_and_sanitized_having
developers = Developer.find(:all, :group => "salary", :having => ["sum(salary) > ?", 10000], :select => "salary")
assert_equal 3, developers.size
assert_equal 3, developers.map(&:salary).uniq.size
assert developers.all? { |developer| developer.salary > 10000 }
end
def test_find_with_entire_select_statement
topics = Topic.find_by_sql "SELECT * FROM topics WHERE author_name = 'Mary'"
assert_equal(1, topics.size)
assert_equal(topics(:second).title, topics.first.title)
end
def test_find_with_prepared_select_statement
topics = Topic.find_by_sql ["SELECT * FROM topics WHERE author_name = ?", "Mary"]
assert_equal(1, topics.size)
assert_equal(topics(:second).title, topics.first.title)
end
def test_find_by_sql_with_sti_on_joined_table
accounts = Account.find_by_sql("SELECT * FROM accounts INNER JOIN companies ON companies.id = accounts.firm_id")
assert_equal [Account], accounts.collect(&:class).uniq
end
def test_find_first
first = Topic.find(:first, :conditions => "title = 'The First Topic'")
assert_equal(topics(:first).title, first.title)
end
def test_find_first_failing
first = Topic.find(:first, :conditions => "title = 'The First Topic!'")
assert_nil(first)
end
def test_first
assert_equal topics(:second).title, Topic.first(:conditions => "title = 'The Second Topic of the day'").title
end
def test_first_failing
assert_nil Topic.first(:conditions => "title = 'The Second Topic of the day!'")
end
def test_unexisting_record_exception_handling
assert_raise(ActiveRecord::RecordNotFound) {
Topic.find(1).parent
}
Topic.find(2).topic
end
def test_find_only_some_columns
topic = Topic.find(1, :select => "author_name")
assert_raise(ActiveRecord::MissingAttributeError) {topic.title}
assert_equal "David", topic.author_name
assert !topic.attribute_present?("title")
#assert !topic.respond_to?("title")
assert topic.attribute_present?("author_name")
assert topic.respond_to?("author_name")
end
def test_find_on_blank_conditions
[nil, " ", [], {}].each do |blank|
assert_nothing_raised { Topic.find(:first, :conditions => blank) }
end
end
def test_find_on_blank_bind_conditions
[ [""], ["",{}] ].each do |blank|
assert_nothing_raised { Topic.find(:first, :conditions => blank) }
end
end
def test_find_on_array_conditions
assert Topic.find(1, :conditions => ["approved = ?", false])
assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => ["approved = ?", true]) }
end
def test_find_on_hash_conditions
assert Topic.find(1, :conditions => { :approved => false })
assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :approved => true }) }
end
def test_find_on_hash_conditions_with_explicit_table_name
assert Topic.find(1, :conditions => { 'topics.approved' => false })
assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { 'topics.approved' => true }) }
end
def test_find_on_hash_conditions_with_hashed_table_name
assert Topic.find(1, :conditions => {:topics => { :approved => false }})
assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => {:topics => { :approved => true }}) }
end
def test_find_with_hash_conditions_on_joined_table
firms = Firm.all :joins => :account, :conditions => {:accounts => { :credit_limit => 50 }}
assert_equal 1, firms.size
assert_equal companies(:first_firm), firms.first
end
def test_find_with_hash_conditions_on_joined_table_and_with_range
firms = DependentFirm.all :joins => :account, :conditions => {:name => 'RailsCore', :accounts => { :credit_limit => 55..60 }}
assert_equal 1, firms.size
assert_equal companies(:rails_core), firms.first
end
def test_find_on_hash_conditions_with_explicit_table_name_and_aggregate
david = customers(:david)
assert Customer.find(david.id, :conditions => { 'customers.name' => david.name, :address => david.address })
assert_raise(ActiveRecord::RecordNotFound) {
Customer.find(david.id, :conditions => { 'customers.name' => david.name + "1", :address => david.address })
}
end
def test_find_on_association_proxy_conditions
assert_equal [1, 2, 3, 5, 6, 7, 8, 9, 10], Comment.find_all_by_post_id(authors(:david).posts).map(&:id).sort
end
def test_find_on_hash_conditions_with_range
assert_equal [1,2], Topic.find(:all, :conditions => { :id => 1..2 }).map(&:id).sort
assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :id => 2..3 }) }
end
def test_find_on_hash_conditions_with_end_exclusive_range
assert_equal [1,2,3], Topic.find(:all, :conditions => { :id => 1..3 }).map(&:id).sort
assert_equal [1,2], Topic.find(:all, :conditions => { :id => 1...3 }).map(&:id).sort
assert_raise(ActiveRecord::RecordNotFound) { Topic.find(3, :conditions => { :id => 2...3 }) }
end
def test_find_on_hash_conditions_with_multiple_ranges
assert_equal [1,2,3], Comment.find(:all, :conditions => { :id => 1..3, :post_id => 1..2 }).map(&:id).sort
assert_equal [1], Comment.find(:all, :conditions => { :id => 1..1, :post_id => 1..10 }).map(&:id).sort
end
def test_find_on_multiple_hash_conditions
assert Topic.find(1, :conditions => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => false })
assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => true }) }
assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :author_name => "David", :title => "HHC", :replies_count => 1, :approved => false }) }
assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => true }) }
end
def test_condition_interpolation
assert_kind_of Firm, Company.find(:first, :conditions => ["name = '%s'", "37signals"])
assert_nil Company.find(:first, :conditions => ["name = '%s'", "37signals!"])
assert_nil Company.find(:first, :conditions => ["name = '%s'", "37signals!' OR 1=1"])
assert_kind_of Time, Topic.find(:first, :conditions => ["id = %d", 1]).written_on
end
def test_condition_array_interpolation
assert_kind_of Firm, Company.find(:first, :conditions => ["name = '%s'", "37signals"])
assert_nil Company.find(:first, :conditions => ["name = '%s'", "37signals!"])
assert_nil Company.find(:first, :conditions => ["name = '%s'", "37signals!' OR 1=1"])
assert_kind_of Time, Topic.find(:first, :conditions => ["id = %d", 1]).written_on
end
def test_condition_hash_interpolation
assert_kind_of Firm, Company.find(:first, :conditions => { :name => "37signals"})
assert_nil Company.find(:first, :conditions => { :name => "37signals!"})
assert_kind_of Time, Topic.find(:first, :conditions => {:id => 1}).written_on
end
def test_hash_condition_find_malformed
assert_raise(ActiveRecord::StatementInvalid) {
Company.find(:first, :conditions => { :id => 2, :dhh => true })
}
end
def test_hash_condition_find_with_escaped_characters
Company.create("name" => "Ain't noth'n like' \#stuff")
assert Company.find(:first, :conditions => { :name => "Ain't noth'n like' \#stuff" })
end
def test_hash_condition_find_with_array
p1, p2 = Post.find(:all, :limit => 2, :order => 'id asc')
assert_equal [p1, p2], Post.find(:all, :conditions => { :id => [p1, p2] }, :order => 'id asc')
assert_equal [p1, p2], Post.find(:all, :conditions => { :id => [p1, p2.id] }, :order => 'id asc')
end
def test_hash_condition_find_with_nil
topic = Topic.find(:first, :conditions => { :last_read => nil } )
assert_not_nil topic
assert_nil topic.last_read
end
def test_hash_condition_find_with_aggregate_having_one_mapping
balance = customers(:david).balance
assert_kind_of Money, balance
found_customer = Customer.find(:first, :conditions => {:balance => balance})
assert_equal customers(:david), found_customer
end
def test_hash_condition_find_with_aggregate_attribute_having_same_name_as_field_and_key_value_being_aggregate
gps_location = customers(:david).gps_location
assert_kind_of GpsLocation, gps_location
found_customer = Customer.find(:first, :conditions => {:gps_location => gps_location})
assert_equal customers(:david), found_customer
end
def test_hash_condition_find_with_aggregate_having_one_mapping_and_key_value_being_attribute_value
balance = customers(:david).balance
assert_kind_of Money, balance
found_customer = Customer.find(:first, :conditions => {:balance => balance.amount})
assert_equal customers(:david), found_customer
end
def test_hash_condition_find_with_aggregate_attribute_having_same_name_as_field_and_key_value_being_attribute_value
gps_location = customers(:david).gps_location
assert_kind_of GpsLocation, gps_location
found_customer = Customer.find(:first, :conditions => {:gps_location => gps_location.gps_location})
assert_equal customers(:david), found_customer
end
def test_hash_condition_find_with_aggregate_having_three_mappings
address = customers(:david).address
assert_kind_of Address, address
found_customer = Customer.find(:first, :conditions => {:address => address})
assert_equal customers(:david), found_customer
end
def test_hash_condition_find_with_one_condition_being_aggregate_and_another_not
address = customers(:david).address
assert_kind_of Address, address
found_customer = Customer.find(:first, :conditions => {:address => address, :name => customers(:david).name})
assert_equal customers(:david), found_customer
end
def test_bind_variables
assert_kind_of Firm, Company.find(:first, :conditions => ["name = ?", "37signals"])
assert_nil Company.find(:first, :conditions => ["name = ?", "37signals!"])
assert_nil Company.find(:first, :conditions => ["name = ?", "37signals!' OR 1=1"])
assert_kind_of Time, Topic.find(:first, :conditions => ["id = ?", 1]).written_on
assert_raise(ActiveRecord::PreparedStatementInvalid) {
Company.find(:first, :conditions => ["id=? AND name = ?", 2])
}
assert_raise(ActiveRecord::PreparedStatementInvalid) {
Company.find(:first, :conditions => ["id=?", 2, 3, 4])
}
end
def test_bind_variables_with_quotes
Company.create("name" => "37signals' go'es agains")
assert Company.find(:first, :conditions => ["name = ?", "37signals' go'es agains"])
end
def test_named_bind_variables_with_quotes
Company.create("name" => "37signals' go'es agains")
assert Company.find(:first, :conditions => ["name = :name", {:name => "37signals' go'es agains"}])
end
def test_bind_arity
assert_nothing_raised { bind '' }
assert_raise(ActiveRecord::PreparedStatementInvalid) { bind '', 1 }
assert_raise(ActiveRecord::PreparedStatementInvalid) { bind '?' }
assert_nothing_raised { bind '?', 1 }
assert_raise(ActiveRecord::PreparedStatementInvalid) { bind '?', 1, 1 }
end
def test_named_bind_variables
assert_equal '1', bind(':a', :a => 1) # ' ruby-mode
assert_equal '1 1', bind(':a :a', :a => 1) # ' ruby-mode
assert_nothing_raised { bind("'+00:00'", :foo => "bar") }
assert_kind_of Firm, Company.find(:first, :conditions => ["name = :name", { :name => "37signals" }])
assert_nil Company.find(:first, :conditions => ["name = :name", { :name => "37signals!" }])
assert_nil Company.find(:first, :conditions => ["name = :name", { :name => "37signals!' OR 1=1" }])
assert_kind_of Time, Topic.find(:first, :conditions => ["id = :id", { :id => 1 }]).written_on
end
def test_bind_enumerable
quoted_abc = %(#{ActiveRecord::Base.connection.quote('a')},#{ActiveRecord::Base.connection.quote('b')},#{ActiveRecord::Base.connection.quote('c')})
assert_equal '1,2,3', bind('?', [1, 2, 3])
assert_equal quoted_abc, bind('?', %w(a b c))
assert_equal '1,2,3', bind(':a', :a => [1, 2, 3])
assert_equal quoted_abc, bind(':a', :a => %w(a b c)) # '
require 'set'
assert_equal '1,2,3', bind('?', Set.new([1, 2, 3]))
assert_equal quoted_abc, bind('?', Set.new(%w(a b c)))
assert_equal '1,2,3', bind(':a', :a => Set.new([1, 2, 3]))
assert_equal quoted_abc, bind(':a', :a => Set.new(%w(a b c))) # '
end
def test_bind_empty_enumerable
quoted_nil = ActiveRecord::Base.connection.quote(nil)
assert_equal quoted_nil, bind('?', [])
assert_equal " in (#{quoted_nil})", bind(' in (?)', [])
assert_equal "foo in (#{quoted_nil})", bind('foo in (?)', [])
end
def test_bind_string
assert_equal ActiveRecord::Base.connection.quote(''), bind('?', '')
end
def test_bind_chars
quoted_bambi = ActiveRecord::Base.connection.quote("Bambi")
quoted_bambi_and_thumper = ActiveRecord::Base.connection.quote("Bambi\nand\nThumper")
assert_equal "name=#{quoted_bambi}", bind('name=?', "Bambi")
assert_equal "name=#{quoted_bambi_and_thumper}", bind('name=?', "Bambi\nand\nThumper")
assert_equal "name=#{quoted_bambi}", bind('name=?', "Bambi".mb_chars)
assert_equal "name=#{quoted_bambi_and_thumper}", bind('name=?', "Bambi\nand\nThumper".mb_chars)
end
def test_bind_record
o = Struct.new(:quoted_id).new(1)
assert_equal '1', bind('?', o)
os = [o] * 3
assert_equal '1,1,1', bind('?', os)
end
def test_named_bind_with_postgresql_type_casts
l = Proc.new { bind(":a::integer '2009-01-01'::date", :a => '10') }
assert_nothing_raised(&l)
assert_equal "#{ActiveRecord::Base.quote_value('10')}::integer '2009-01-01'::date", l.call
end
def test_string_sanitation
assert_not_equal "#{ActiveRecord::Base.connection.quoted_string_prefix}'something ' 1=1'", ActiveRecord::Base.sanitize("something ' 1=1")
assert_equal "#{ActiveRecord::Base.connection.quoted_string_prefix}'something; select table'", ActiveRecord::Base.sanitize("something; select table")
end
def test_count
assert_equal(0, Entrant.count(:conditions => "id > 3"))
assert_equal(1, Entrant.count(:conditions => ["id > ?", 2]))
assert_equal(2, Entrant.count(:conditions => ["id > ?", 1]))
end
def test_count_by_sql
assert_equal(0, Entrant.count_by_sql("SELECT COUNT(*) FROM entrants WHERE id > 3"))
assert_equal(1, Entrant.count_by_sql(["SELECT COUNT(*) FROM entrants WHERE id > ?", 2]))
assert_equal(2, Entrant.count_by_sql(["SELECT COUNT(*) FROM entrants WHERE id > ?", 1]))
end
def test_dynamic_finders_should_go_through_the_find_class_method
Topic.expects(:find).with(:first, :conditions => { :title => 'The First Topic!' })
Topic.find_by_title("The First Topic!")
Topic.expects(:find).with(:last, :conditions => { :title => 'The Last Topic!' })
Topic.find_last_by_title("The Last Topic!")
Topic.expects(:find).with(:all, :conditions => { :title => 'A Topic.' })
Topic.find_all_by_title("A Topic.")
Topic.expects(:find).with(:first, :conditions => { :title => 'Does not exist yet for sure!' }).times(2)
Topic.find_or_initialize_by_title('Does not exist yet for sure!')
Topic.find_or_create_by_title('Does not exist yet for sure!')
end
def test_find_by_one_attribute
assert_equal topics(:first), Topic.find_by_title("The First Topic")
assert_nil Topic.find_by_title("The First Topic!")
end
def test_find_by_one_attribute_bang
assert_equal topics(:first), Topic.find_by_title!("The First Topic")
assert_raise(ActiveRecord::RecordNotFound) { Topic.find_by_title!("The First Topic!") }
end
def test_find_by_one_attribute_caches_dynamic_finder
# ensure this test can run independently of order
class << Topic; self; end.send(:remove_method, :find_by_title) if Topic.public_methods.any? { |m| m.to_s == 'find_by_title' }
assert !Topic.public_methods.any? { |m| m.to_s == 'find_by_title' }
t = Topic.find_by_title("The First Topic")
assert Topic.public_methods.any? { |m| m.to_s == 'find_by_title' }
end
def test_dynamic_finder_returns_same_results_after_caching
# ensure this test can run independently of order
class << Topic; self; end.send(:remove_method, :find_by_title) if Topic.public_method_defined?(:find_by_title)
t = Topic.find_by_title("The First Topic")
assert_equal t, Topic.find_by_title("The First Topic") # find_by_title has been cached
end
def test_find_by_one_attribute_with_order_option
assert_equal accounts(:signals37), Account.find_by_credit_limit(50, :order => 'id')
assert_equal accounts(:rails_core_account), Account.find_by_credit_limit(50, :order => 'id DESC')
end
def test_find_by_one_attribute_with_conditions
assert_equal accounts(:rails_core_account), Account.find_by_credit_limit(50, :conditions => ['firm_id = ?', 6])
end
def test_find_by_one_attribute_that_is_an_aggregate
address = customers(:david).address
assert_kind_of Address, address
found_customer = Customer.find_by_address(address)
assert_equal customers(:david), found_customer
end
def test_find_by_one_attribute_that_is_an_aggregate_with_one_attribute_difference
address = customers(:david).address
assert_kind_of Address, address
missing_address = Address.new(address.street, address.city, address.country + "1")
assert_nil Customer.find_by_address(missing_address)
missing_address = Address.new(address.street, address.city + "1", address.country)
assert_nil Customer.find_by_address(missing_address)
missing_address = Address.new(address.street + "1", address.city, address.country)
assert_nil Customer.find_by_address(missing_address)
end
def test_find_by_two_attributes_that_are_both_aggregates
balance = customers(:david).balance
address = customers(:david).address
assert_kind_of Money, balance
assert_kind_of Address, address
found_customer = Customer.find_by_balance_and_address(balance, address)
assert_equal customers(:david), found_customer
end
def test_find_by_two_attributes_with_one_being_an_aggregate
balance = customers(:david).balance
assert_kind_of Money, balance
found_customer = Customer.find_by_balance_and_name(balance, customers(:david).name)
assert_equal customers(:david), found_customer
end
def test_dynamic_finder_on_one_attribute_with_conditions_caches_method
# ensure this test can run independently of order
class << Account; self; end.send(:remove_method, :find_by_credit_limit) if Account.public_methods.any? { |m| m.to_s == 'find_by_credit_limit' }
assert !Account.public_methods.any? { |m| m.to_s == 'find_by_credit_limit' }
a = Account.find_by_credit_limit(50, :conditions => ['firm_id = ?', 6])
assert Account.public_methods.any? { |m| m.to_s == 'find_by_credit_limit' }
end
def test_dynamic_finder_on_one_attribute_with_conditions_returns_same_results_after_caching
# ensure this test can run independently of order
class << Account; self; end.send(:remove_method, :find_by_credit_limit) if Account.public_methods.any? { |m| m.to_s == 'find_by_credit_limit' }
a = Account.find_by_credit_limit(50, :conditions => ['firm_id = ?', 6])
assert_equal a, Account.find_by_credit_limit(50, :conditions => ['firm_id = ?', 6]) # find_by_credit_limit has been cached
end
def test_find_by_one_attribute_with_several_options
assert_equal accounts(:unknown), Account.find_by_credit_limit(50, :order => 'id DESC', :conditions => ['id != ?', 3])
end
def test_find_by_one_missing_attribute
assert_raise(NoMethodError) { Topic.find_by_undertitle("The First Topic!") }
end
def test_find_by_invalid_method_syntax
assert_raise(NoMethodError) { Topic.fail_to_find_by_title("The First Topic") }
assert_raise(NoMethodError) { Topic.find_by_title?("The First Topic") }
assert_raise(NoMethodError) { Topic.fail_to_find_or_create_by_title("Nonexistent Title") }
assert_raise(NoMethodError) { Topic.find_or_create_by_title?("Nonexistent Title") }
end
def test_find_by_two_attributes
assert_equal topics(:first), Topic.find_by_title_and_author_name("The First Topic", "David")
assert_nil Topic.find_by_title_and_author_name("The First Topic", "Mary")
end
def test_find_last_by_one_attribute
assert_equal Topic.last, Topic.find_last_by_title(Topic.last.title)
assert_nil Topic.find_last_by_title("A title with no matches")
end
def test_find_last_by_one_attribute_caches_dynamic_finder
# ensure this test can run independently of order
class << Topic; self; end.send(:remove_method, :find_last_by_title) if Topic.public_methods.any? { |m| m.to_s == 'find_last_by_title' }
assert !Topic.public_methods.any? { |m| m.to_s == 'find_last_by_title' }
t = Topic.find_last_by_title(Topic.last.title)
assert Topic.public_methods.any? { |m| m.to_s == 'find_last_by_title' }
end
def test_find_last_by_invalid_method_syntax
assert_raise(NoMethodError) { Topic.fail_to_find_last_by_title("The First Topic") }
assert_raise(NoMethodError) { Topic.find_last_by_title?("The First Topic") }
end
def test_find_last_by_one_attribute_with_several_options
assert_equal accounts(:signals37), Account.find_last_by_credit_limit(50, :order => 'id DESC', :conditions => ['id != ?', 3])
end
def test_find_last_by_one_missing_attribute
assert_raise(NoMethodError) { Topic.find_last_by_undertitle("The Last Topic!") }
end
def test_find_last_by_two_attributes
topic = Topic.last
assert_equal topic, Topic.find_last_by_title_and_author_name(topic.title, topic.author_name)
assert_nil Topic.find_last_by_title_and_author_name(topic.title, "Anonymous")
end
def test_find_all_by_one_attribute
topics = Topic.find_all_by_content("Have a nice day")
assert_equal 2, topics.size
assert topics.include?(topics(:first))
assert_equal [], Topic.find_all_by_title("The First Topic!!")
end
def test_find_all_by_one_attribute_that_is_an_aggregate
balance = customers(:david).balance
assert_kind_of Money, balance
found_customers = Customer.find_all_by_balance(balance)
assert_equal 1, found_customers.size
assert_equal customers(:david), found_customers.first
end
def test_find_all_by_two_attributes_that_are_both_aggregates
balance = customers(:david).balance
address = customers(:david).address
assert_kind_of Money, balance
assert_kind_of Address, address
found_customers = Customer.find_all_by_balance_and_address(balance, address)
assert_equal 1, found_customers.size
assert_equal customers(:david), found_customers.first
end
def test_find_all_by_two_attributes_with_one_being_an_aggregate
balance = customers(:david).balance
assert_kind_of Money, balance
found_customers = Customer.find_all_by_balance_and_name(balance, customers(:david).name)
assert_equal 1, found_customers.size
assert_equal customers(:david), found_customers.first
end
def test_find_all_by_one_attribute_with_options
topics = Topic.find_all_by_content("Have a nice day", :order => "id DESC")
assert topics(:first), topics.last
topics = Topic.find_all_by_content("Have a nice day", :order => "id")
assert topics(:first), topics.first
end
def test_find_all_by_array_attribute
assert_equal 2, Topic.find_all_by_title(["The First Topic", "The Second Topic of the day"]).size
end
def test_find_all_by_boolean_attribute
topics = Topic.find_all_by_approved(false)
assert_equal 1, topics.size
assert topics.include?(topics(:first))
topics = Topic.find_all_by_approved(true)
assert_equal 3, topics.size
assert topics.include?(topics(:second))
end
def test_find_by_nil_attribute
topic = Topic.find_by_last_read nil
assert_not_nil topic
assert_nil topic.last_read
end
def test_find_all_by_nil_attribute
topics = Topic.find_all_by_last_read nil
assert_equal 3, topics.size
assert topics.collect(&:last_read).all?(&:nil?)
end
def test_find_by_nil_and_not_nil_attributes
topic = Topic.find_by_last_read_and_author_name nil, "Mary"
assert_equal "Mary", topic.author_name
end
def test_find_all_by_nil_and_not_nil_attributes
topics = Topic.find_all_by_last_read_and_author_name nil, "Mary"
assert_equal 1, topics.size
assert_equal "Mary", topics[0].author_name
end
def test_find_or_create_from_one_attribute
number_of_companies = Company.count
sig38 = Company.find_or_create_by_name("38signals")
assert_equal number_of_companies + 1, Company.count
assert_equal sig38, Company.find_or_create_by_name("38signals")
assert !sig38.new_record?
end
def test_find_or_create_from_two_attributes
number_of_topics = Topic.count
another = Topic.find_or_create_by_title_and_author_name("Another topic","John")
assert_equal number_of_topics + 1, Topic.count
assert_equal another, Topic.find_or_create_by_title_and_author_name("Another topic", "John")
assert !another.new_record?
end
def test_find_or_create_from_two_attributes_with_one_being_an_aggregate
number_of_customers = Customer.count
created_customer = Customer.find_or_create_by_balance_and_name(Money.new(123), "Elizabeth")
assert_equal number_of_customers + 1, Customer.count
assert_equal created_customer, Customer.find_or_create_by_balance(Money.new(123), "Elizabeth")
assert !created_customer.new_record?
end
def test_find_or_create_from_one_attribute_and_hash
number_of_companies = Company.count
sig38 = Company.find_or_create_by_name({:name => "38signals", :firm_id => 17, :client_of => 23})
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | true |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/serialization_test.rb | provider/vendor/rails/activerecord/test/cases/serialization_test.rb | require "cases/helper"
require 'models/contact'
class SerializationTest < ActiveRecord::TestCase
FORMATS = [ :xml, :json ]
def setup
@contact_attributes = {
:name => 'aaron stack',
:age => 25,
:avatar => 'binarydata',
:created_at => Time.utc(2006, 8, 1),
:awesome => false,
:preferences => { :gem => '<strong>ruby</strong>' }
}
@contact = Contact.new(@contact_attributes)
end
def test_serialize_should_be_reversible
for format in FORMATS
@serialized = Contact.new.send("to_#{format}")
contact = Contact.new.send("from_#{format}", @serialized)
assert_equal @contact_attributes.keys.collect(&:to_s).sort, contact.attributes.keys.collect(&:to_s).sort, "For #{format}"
end
end
def test_serialize_should_allow_attribute_only_filtering
for format in FORMATS
@serialized = Contact.new(@contact_attributes).send("to_#{format}", :only => [ :age, :name ])
contact = Contact.new.send("from_#{format}", @serialized)
assert_equal @contact_attributes[:name], contact.name, "For #{format}"
assert_nil contact.avatar, "For #{format}"
end
end
def test_serialize_should_allow_attribute_except_filtering
for format in FORMATS
@serialized = Contact.new(@contact_attributes).send("to_#{format}", :except => [ :age, :name ])
contact = Contact.new.send("from_#{format}", @serialized)
assert_nil contact.name, "For #{format}"
assert_nil contact.age, "For #{format}"
assert_equal @contact_attributes[:awesome], contact.awesome, "For #{format}"
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/unconnected_test.rb | provider/vendor/rails/activerecord/test/cases/unconnected_test.rb | require "cases/helper"
class TestRecord < ActiveRecord::Base
end
class TestUnconnectedAdapter < ActiveRecord::TestCase
self.use_transactional_fixtures = false
def setup
@underlying = ActiveRecord::Base.connection
@specification = ActiveRecord::Base.remove_connection
end
def teardown
@underlying = nil
ActiveRecord::Base.establish_connection(@specification)
end
def test_connection_no_longer_established
assert_raise(ActiveRecord::ConnectionNotEstablished) do
TestRecord.find(1)
end
assert_raise(ActiveRecord::ConnectionNotEstablished) do
TestRecord.new.save
end
end
def test_underlying_adapter_no_longer_active
assert !@underlying.active?, "Removed adapter should no longer be active"
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/repair_helper.rb | provider/vendor/rails/activerecord/test/cases/repair_helper.rb | module ActiveRecord
module Testing
module RepairHelper
def self.included(base)
base.class_eval do
extend ClassMethods
end
end
module Toolbox
def self.record_validations(*model_classes)
model_classes.inject({}) do |repair, klass|
repair[klass] ||= {}
[:validate, :validate_on_create, :validate_on_update].each do |callback|
the_callback = klass.instance_variable_get("@#{callback.to_s}_callbacks")
repair[klass][callback] = (the_callback.nil? ? nil : the_callback.dup)
end
repair
end
end
def self.reset_validations(recorded)
recorded.each do |klass, repairs|
[:validate, :validate_on_create, :validate_on_update].each do |callback|
klass.instance_variable_set("@#{callback.to_s}_callbacks", repairs[callback])
end
end
end
end
module ClassMethods
def repair_validations(*model_classes)
setup do
@validation_repairs = ActiveRecord::Testing::RepairHelper::Toolbox.record_validations(*model_classes)
end
teardown do
ActiveRecord::Testing::RepairHelper::Toolbox.reset_validations(@validation_repairs)
end
end
end
def repair_validations(*model_classes, &block)
validation_repairs = ActiveRecord::Testing::RepairHelper::Toolbox.record_validations(*model_classes)
return block.call
ensure
ActiveRecord::Testing::RepairHelper::Toolbox.reset_validations(validation_repairs)
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/validations_i18n_test.rb | provider/vendor/rails/activerecord/test/cases/validations_i18n_test.rb | require "cases/helper"
require 'models/topic'
require 'models/reply'
require 'models/person'
module ActiveRecordValidationsI18nTestHelper
def store_translations(*args)
data = args.extract_options!
locale = args.shift || 'en'
I18n.backend.send(:init_translations)
I18n.backend.store_translations(locale, :activerecord => data)
end
def delete_translation(key)
I18n.backend.instance_eval do
keys = I18n.send(:normalize_translation_keys, 'en', key, nil)
keys.inject(translations) { |result, k| keys.last == k ? result.delete(k.to_sym) : result[k.to_sym] }
end
end
def reset_callbacks(*models)
models.each do |model|
model.instance_variable_set("@validate_callbacks", ActiveSupport::Callbacks::CallbackChain.new)
model.instance_variable_set("@validate_on_create_callbacks", ActiveSupport::Callbacks::CallbackChain.new)
model.instance_variable_set("@validate_on_update_callbacks", ActiveSupport::Callbacks::CallbackChain.new)
end
end
end
# DEPRECATIONS
class ActiveRecordValidationsI18nDeprecationsTests < ActiveSupport::TestCase
test "default_error_messages is deprecated and can be removed in Rails 3 / ActiveModel" do
assert_deprecated('ActiveRecord::Errors.default_error_messages') do
ActiveRecord::Errors.default_error_messages
end
end
test "%s interpolation syntax in error messages still works" do
ActiveSupport::Deprecation.silence do
result = I18n.t :does_not_exist, :default => "%s interpolation syntax is deprecated", :value => 'this'
assert_equal result, "this interpolation syntax is deprecated"
end
end
test "%s interpolation syntax in error messages is deprecated" do
assert_deprecated('using %s in messages') do
I18n.t :does_not_exist, :default => "%s interpolation syntax is deprected", :value => 'this'
end
end
test "%d interpolation syntax in error messages still works" do
ActiveSupport::Deprecation.silence do
result = I18n.t :does_not_exist, :default => "%d interpolation syntaxes are deprecated", :count => 2
assert_equal result, "2 interpolation syntaxes are deprecated"
end
end
test "%d interpolation syntax in error messages is deprecated" do
assert_deprecated('using %d in messages') do
I18n.t :does_not_exist, :default => "%d interpolation syntaxes are deprected", :count => 2
end
end
end
# ACTIVERECORD VALIDATIONS
#
# For each validation:
#
# * test expect that it adds an error with the appropriate arguments
# * test that it looks up the correct default message
class ActiveRecordValidationsI18nTests < ActiveSupport::TestCase
include ActiveRecordValidationsI18nTestHelper
def setup
reset_callbacks(Topic)
@topic = Topic.new
@reply = Reply.new
@old_load_path, @old_backend = I18n.load_path, I18n.backend
I18n.load_path.clear
I18n.backend = I18n::Backend::Simple.new
I18n.backend.store_translations('en', :activerecord => {:errors => {:messages => {:custom => nil}}})
end
def teardown
reset_callbacks(Topic)
I18n.load_path.replace(@old_load_path)
I18n.backend = @old_backend
end
def expect_error_added(model, attribute, type, options)
model.errors.expects(:add).with(attribute, type, options)
yield
model.valid?
end
def assert_message_translations(model, attribute, type, &block)
assert_default_message_translation(model, attribute, type, &block)
reset_callbacks(model.class)
model.errors.clear
assert_custom_message_translation(model, attribute, type, &block)
end
def assert_custom_message_translation(model, attribute, type)
store_translations(:errors => { :models => { model.class.name.underscore => { :attributes => { attribute => { type => 'custom message' } } } } })
yield
model.valid?
assert_equal 'custom message', model.errors.on(attribute)
end
def assert_default_message_translation(model, attribute, type)
store_translations(:errors => { :messages => { type => 'default message' } })
yield
model.valid?
assert_equal 'default message', model.errors.on(attribute)
end
def unique_topic
@unique ||= Topic.create(:title => 'unique!')
end
def replied_topic
@replied_topic ||= begin
topic = Topic.create(:title => "topic")
topic.replies << Reply.new
topic
end
end
# validates_confirmation_of
test "#validates_confirmation_of given no custom message" do
expect_error_added(@topic, :title, :confirmation, :default => nil) do
Topic.validates_confirmation_of :title
@topic.title = 'title'
@topic.title_confirmation = 'foo'
end
end
test "#validates_confirmation_of given a custom message" do
expect_error_added(@topic, :title, :confirmation, :default => 'custom') do
Topic.validates_confirmation_of :title, :message => 'custom'
@topic.title_confirmation = 'foo'
end
end
test "#validates_confirmation_of finds the correct message translations" do
assert_message_translations(@topic, :title, :confirmation) do
Topic.validates_confirmation_of :title
@topic.title_confirmation = 'foo'
end
end
# validates_acceptance_of
test "#validates_acceptance_of given no custom message" do
expect_error_added(@topic, :title, :accepted, :default => nil) do
Topic.validates_acceptance_of :title, :allow_nil => false
end
end
test "#validates_acceptance_of given a custom message" do
expect_error_added(@topic, :title, :accepted, :default => 'custom') do
Topic.validates_acceptance_of :title, :message => 'custom', :allow_nil => false
end
end
test "#validates_acceptance_of finds the correct message translations" do
assert_message_translations(@topic, :title, :accepted) do
Topic.validates_acceptance_of :title, :allow_nil => false
end
end
# validates_presence_of
test "#validates_presence_of given no custom message" do
expect_error_added(@topic, :title, :blank, :default => nil) do
Topic.validates_presence_of :title
end
end
test "#validates_presence_of given a custom message" do
expect_error_added(@topic, :title, :blank, :default => 'custom') do
Topic.validates_presence_of :title, :message => 'custom'
end
end
test "#validates_presence_of finds the correct message translations" do
assert_message_translations(@topic, :title, :blank) do
Topic.validates_presence_of :title
end
end
# validates_length_of :too_short
test "#validates_length_of (:too_short) and no custom message" do
expect_error_added(@topic, :title, :too_short, :default => nil, :count => 3) do
Topic.validates_length_of :title, :within => 3..5
end
end
test "#validates_length_of (:too_short) and a custom message" do
expect_error_added(@topic, :title, :too_short, :default => 'custom', :count => 3) do
Topic.validates_length_of :title, :within => 3..5, :too_short => 'custom'
end
end
test "#validates_length_of (:too_short) finds the correct message translations" do
assert_message_translations(@topic, :title, :too_short) do
Topic.validates_length_of :title, :within => 3..5
end
end
# validates_length_of :too_long
test "#validates_length_of (:too_long) and no custom message" do
expect_error_added(@topic, :title, :too_long, :default => nil, :count => 5) do
Topic.validates_length_of :title, :within => 3..5
@topic.title = 'this title is too long'
end
end
test "#validates_length_of (:too_long) and a custom message" do
expect_error_added(@topic, :title, :too_long, :default => 'custom', :count => 5) do
Topic.validates_length_of :title, :within => 3..5, :too_long => 'custom'
@topic.title = 'this title is too long'
end
end
test "#validates_length_of (:too_long) finds the correct message translations" do
assert_message_translations(@topic, :title, :too_long) do
Topic.validates_length_of :title, :within => 3..5
@topic.title = 'this title is too long'
end
end
# validates_length_of :is
test "#validates_length_of (:is) and no custom message" do
expect_error_added(@topic, :title, :wrong_length, :default => nil, :count => 5) do
Topic.validates_length_of :title, :is => 5
@topic.title = 'this title has the wrong length'
end
end
test "#validates_length_of (:is) and a custom message" do
expect_error_added(@topic, :title, :wrong_length, :default => 'custom', :count => 5) do
Topic.validates_length_of :title, :is => 5, :wrong_length => 'custom'
@topic.title = 'this title has the wrong length'
end
end
test "#validates_length_of (:is) finds the correct message translations" do
assert_message_translations(@topic, :title, :wrong_length) do
Topic.validates_length_of :title, :is => 5
@topic.title = 'this title has the wrong length'
end
end
# validates_uniqueness_of
test "#validates_uniqueness_of and no custom message" do
expect_error_added(@topic, :title, :taken, :default => nil, :value => 'unique!') do
Topic.validates_uniqueness_of :title
@topic.title = unique_topic.title
end
end
test "#validates_uniqueness_of and a custom message" do
expect_error_added(@topic, :title, :taken, :default => 'custom', :value => 'unique!') do
Topic.validates_uniqueness_of :title, :message => 'custom'
@topic.title = unique_topic.title
end
end
test "#validates_uniqueness_of finds the correct message translations" do
assert_message_translations(@topic, :title, :taken) do
Topic.validates_uniqueness_of :title
@topic.title = unique_topic.title
end
end
# validates_format_of
test "#validates_format_of and no custom message" do
expect_error_added(@topic, :title, :invalid, :default => nil, :value => '72x') do
Topic.validates_format_of :title, :with => /^[1-9][0-9]*$/
@topic.title = '72x'
end
end
test "#validates_format_of and a custom message" do
expect_error_added(@topic, :title, :invalid, :default => 'custom', :value => '72x') do
Topic.validates_format_of :title, :with => /^[1-9][0-9]*$/, :message => 'custom'
@topic.title = '72x'
end
end
test "#validates_format_of finds the correct message translations" do
assert_message_translations(@topic, :title, :invalid) do
Topic.validates_format_of :title, :with => /^[1-9][0-9]*$/
@topic.title = '72x'
end
end
# validates_inclusion_of
test "#validates_inclusion_of and no custom message" do
list = %w(a b c)
expect_error_added(@topic, :title, :inclusion, :default => nil, :value => 'z') do
Topic.validates_inclusion_of :title, :in => list
@topic.title = 'z'
end
end
test "#validates_inclusion_of and a custom message" do
list = %w(a b c)
expect_error_added(@topic, :title, :inclusion, :default => 'custom', :value => 'z') do
Topic.validates_inclusion_of :title, :in => list, :message => 'custom'
@topic.title = 'z'
end
end
test "#validates_inclusion_of finds the correct message translations" do
list = %w(a b c)
assert_message_translations(@topic, :title, :inclusion) do
Topic.validates_inclusion_of :title, :in => list
@topic.title = 'z'
end
end
# validates_exclusion_of
test "#validates_exclusion_of and no custom message" do
list = %w(a b c)
expect_error_added(@topic, :title, :exclusion, :default => nil, :value => 'a') do
Topic.validates_exclusion_of :title, :in => list
@topic.title = 'a'
end
end
test "#validates_exclusion_of and a custom message" do
list = %w(a b c)
expect_error_added(@topic, :title, :exclusion, :default => 'custom', :value => 'a') do
Topic.validates_exclusion_of :title, :in => list, :message => 'custom'
@topic.title = 'a'
end
end
test "#validates_exclusion_of finds the correct message translations" do
list = %w(a b c)
assert_message_translations(@topic, :title, :exclusion) do
Topic.validates_exclusion_of :title, :in => list
@topic.title = 'a'
end
end
# validates_numericality_of :not_a_number, without :only_integer
test "#validates_numericality_of (:not_a_number, w/o :only_integer) no custom message" do
expect_error_added(@topic, :title, :not_a_number, :default => nil, :value => 'a') do
Topic.validates_numericality_of :title
@topic.title = 'a'
end
end
test "#validates_numericality_of (:not_a_number, w/o :only_integer) and a custom message" do
expect_error_added(@topic, :title, :not_a_number, :default => 'custom', :value => 'a') do
Topic.validates_numericality_of :title, :message => 'custom'
@topic.title = 'a'
end
end
test "#validates_numericality_of (:not_a_number, w/o :only_integer) finds the correct message translations" do
assert_message_translations(@topic, :title, :not_a_number) do
Topic.validates_numericality_of :title
@topic.title = 'a'
end
end
# validates_numericality_of :not_a_number, with :only_integer
test "#validates_numericality_of (:not_a_number, with :only_integer) no custom message" do
expect_error_added(@topic, :title, :not_a_number, :default => nil, :value => 'a') do
Topic.validates_numericality_of :title, :only_integer => true
@topic.title = 'a'
end
end
test "#validates_numericality_of (:not_a_number, with :only_integer) and a custom message" do
expect_error_added(@topic, :title, :not_a_number, :default => 'custom', :value => 'a') do
Topic.validates_numericality_of :title, :only_integer => true, :message => 'custom'
@topic.title = 'a'
end
end
test "#validates_numericality_of (:not_a_number, with :only_integer) finds the correct message translations" do
assert_message_translations(@topic, :title, :not_a_number) do
Topic.validates_numericality_of :title, :only_integer => true
@topic.title = 'a'
end
end
# validates_numericality_of :odd
test "#validates_numericality_of (:odd) no custom message" do
expect_error_added(@topic, :title, :odd, :default => nil, :value => 0) do
Topic.validates_numericality_of :title, :only_integer => true, :odd => true
@topic.title = 0
end
end
test "#validates_numericality_of (:odd) and a custom message" do
expect_error_added(@topic, :title, :odd, :default => 'custom', :value => 0) do
Topic.validates_numericality_of :title, :only_integer => true, :odd => true, :message => 'custom'
@topic.title = 0
end
end
test "#validates_numericality_of (:odd) finds the correct message translations" do
assert_message_translations(@topic, :title, :odd) do
Topic.validates_numericality_of :title, :only_integer => true, :odd => true
@topic.title = 0
end
end
# validates_numericality_of :even
test "#validates_numericality_of (:even) no custom message" do
expect_error_added(@topic, :title, :even, :default => nil, :value => 1) do
Topic.validates_numericality_of :title, :only_integer => true, :even => true
@topic.title = 1
end
end
test "#validates_numericality_of (:even) and a custom message" do
expect_error_added(@topic, :title, :even, :default => 'custom', :value => 1) do
Topic.validates_numericality_of :title, :only_integer => true, :even => true, :message => 'custom'
@topic.title = 1
end
end
test "#validates_numericality_of (:even) finds the correct message translations" do
assert_message_translations(@topic, :title, :even) do
Topic.validates_numericality_of :title, :only_integer => true, :even => true
@topic.title = 1
end
end
# validates_numericality_of :less_than
test "#validates_numericality_of (:less_than) no custom message" do
expect_error_added(@topic, :title, :less_than, :default => nil, :value => 1, :count => 0) do
Topic.validates_numericality_of :title, :only_integer => true, :less_than => 0
@topic.title = 1
end
end
test "#validates_numericality_of (:less_than) and a custom message" do
expect_error_added(@topic, :title, :less_than, :default => 'custom', :value => 1, :count => 0) do
Topic.validates_numericality_of :title, :only_integer => true, :less_than => 0, :message => 'custom'
@topic.title = 1
end
end
test "#validates_numericality_of (:less_than) finds the correct message translations" do
assert_message_translations(@topic, :title, :less_than) do
Topic.validates_numericality_of :title, :only_integer => true, :less_than => 0
@topic.title = 1
end
end
# validates_associated
test "#validates_associated no custom message" do
expect_error_added(replied_topic, :replies, :invalid, :default => nil, :value => replied_topic.replies) do
Topic.validates_associated :replies
end
end
test "#validates_associated and a custom message" do
expect_error_added(replied_topic, :replies, :invalid, :default => 'custom', :value => replied_topic.replies) do
Topic.validates_associated :replies, :message => 'custom'
end
end
test "#validates_associated finds the correct message translations" do
assert_message_translations(replied_topic, :replies, :invalid) do
Topic.validates_associated :replies
end
end
end
# ACTIVERECORD ERROR
#
# * test that it passes given interpolation arguments, the human model name and human attribute name
# * test that it looks messages up with the the correct keys
# * test that it looks up the correct default messages
class ActiveRecordErrorI18nTests < ActiveSupport::TestCase
include ActiveRecordValidationsI18nTestHelper
def setup
@reply = Reply.new
@old_backend, I18n.backend = I18n.backend, I18n::Backend::Simple.new
end
def teardown
I18n.backend = @old_backend
I18n.locale = nil
end
def assert_error_message(message, *args)
assert_equal message, ActiveRecord::Error.new(@reply, *args).message
end
def assert_full_message(message, *args)
assert_equal message, ActiveRecord::Error.new(@reply, *args).full_message
end
test "#generate_message passes the model attribute value for interpolation" do
store_translations(:errors => { :messages => { :foo => "You fooed: {{value}}." } })
@reply.title = "da title"
assert_error_message 'You fooed: da title.', :title, :foo
end
test "#generate_message passes the human_name of the model for interpolation" do
store_translations(
:errors => { :messages => { :foo => "You fooed: {{model}}." } },
:models => { :topic => 'da topic' }
)
assert_error_message 'You fooed: da topic.', :title, :foo
end
test "#generate_message passes the human_name of the attribute for interpolation" do
store_translations(
:errors => { :messages => { :foo => "You fooed: {{attribute}}." } },
:attributes => { :topic => { :title => 'da topic title' } }
)
assert_error_message 'You fooed: da topic title.', :title, :foo
end
# generate_message will look up the key for the error message (e.g. :blank) in these namespaces:
#
# activerecord.errors.models.reply.attributes.title
# activerecord.errors.models.reply
# activerecord.errors.models.topic.attributes.title
# activerecord.errors.models.topic
# [default from class level :validates_foo statement if this is a String]
# activerecord.errors.messages
test "#generate_message key fallbacks (given a String as key)" do
store_translations(
:errors => {
:models => {
:reply => {
:attributes => { :title => { :custom => 'activerecord.errors.models.reply.attributes.title.custom' } },
:custom => 'activerecord.errors.models.reply.custom'
},
:topic => {
:attributes => { :title => { :custom => 'activerecord.errors.models.topic.attributes.title.custom' } },
:custom => 'activerecord.errors.models.topic.custom'
}
},
:messages => {
:custom => 'activerecord.errors.messages.custom',
:kaputt => 'activerecord.errors.messages.kaputt'
}
}
)
assert_error_message 'activerecord.errors.models.reply.attributes.title.custom', :title, :kaputt, :message => 'custom'
delete_translation :'activerecord.errors.models.reply.attributes.title.custom'
assert_error_message 'activerecord.errors.models.reply.custom', :title, :kaputt, :message => 'custom'
delete_translation :'activerecord.errors.models.reply.custom'
assert_error_message 'activerecord.errors.models.topic.attributes.title.custom', :title, :kaputt, :message => 'custom'
delete_translation :'activerecord.errors.models.topic.attributes.title.custom'
assert_error_message 'activerecord.errors.models.topic.custom', :title, :kaputt, :message => 'custom'
delete_translation :'activerecord.errors.models.topic.custom'
assert_error_message 'activerecord.errors.messages.custom', :title, :kaputt, :message => 'custom'
delete_translation :'activerecord.errors.messages.custom'
# Implementing this would clash with the AR default behaviour of using validates_foo :message => 'foo'
# as an untranslated string. I.e. at this point we can either fall back to the given string from the
# class-level macro (validates_*) or fall back to the default message for this validation type.
# assert_error_message 'activerecord.errors.messages.kaputt', :title, :kaputt, :message => 'custom'
assert_error_message 'custom', :title, :kaputt, :message => 'custom'
end
test "#generate_message key fallbacks (given a Symbol as key)" do
store_translations(
:errors => {
:models => {
:reply => {
:attributes => { :title => { :kaputt => 'activerecord.errors.models.reply.attributes.title.kaputt' } },
:kaputt => 'activerecord.errors.models.reply.kaputt'
},
:topic => {
:attributes => { :title => { :kaputt => 'activerecord.errors.models.topic.attributes.title.kaputt' } },
:kaputt => 'activerecord.errors.models.topic.kaputt'
}
},
:messages => {
:kaputt => 'activerecord.errors.messages.kaputt'
}
}
)
assert_error_message 'activerecord.errors.models.reply.attributes.title.kaputt', :title, :kaputt
delete_translation :'activerecord.errors.models.reply.attributes.title.kaputt'
assert_error_message 'activerecord.errors.models.reply.kaputt', :title, :kaputt
delete_translation :'activerecord.errors.models.reply.kaputt'
assert_error_message 'activerecord.errors.models.topic.attributes.title.kaputt', :title, :kaputt
delete_translation :'activerecord.errors.models.topic.attributes.title.kaputt'
assert_error_message 'activerecord.errors.models.topic.kaputt', :title, :kaputt
delete_translation :'activerecord.errors.models.topic.kaputt'
assert_error_message 'activerecord.errors.messages.kaputt', :title, :kaputt
end
# full_messages
test "#full_message with no format present" do
store_translations(:errors => { :messages => { :kaputt => 'is kaputt' } })
assert_full_message 'Title is kaputt', :title, :kaputt
end
test "#full_message with a format present" do
store_translations(:errors => { :messages => { :kaputt => 'is kaputt' }, :full_messages => { :format => '{{attribute}}: {{message}}' } })
assert_full_message 'Title: is kaputt', :title, :kaputt
end
test "#full_message with a type specific format present" do
store_translations(:errors => { :messages => { :kaputt => 'is kaputt' }, :full_messages => { :kaputt => '{{attribute}} {{message}}!' } })
assert_full_message 'Title is kaputt!', :title, :kaputt
end
test "#full_message with class-level specified custom message" do
store_translations(:errors => { :messages => { :broken => 'is kaputt' }, :full_messages => { :broken => '{{attribute}} {{message}}?!' } })
assert_full_message 'Title is kaputt?!', :title, :kaputt, :message => :broken
end
# switch locales
test "#message allows to switch locales" do
store_translations(:en, :errors => { :messages => { :kaputt => 'is kaputt' } })
store_translations(:de, :errors => { :messages => { :kaputt => 'ist kaputt' } })
assert_error_message 'is kaputt', :title, :kaputt
I18n.locale = :de
assert_error_message 'ist kaputt', :title, :kaputt
I18n.locale = :en
assert_error_message 'is kaputt', :title, :kaputt
end
test "#full_message allows to switch locales" do
store_translations(:en, :errors => { :messages => { :kaputt => 'is kaputt' } }, :attributes => { :topic => { :title => 'The title' } })
store_translations(:de, :errors => { :messages => { :kaputt => 'ist kaputt' } }, :attributes => { :topic => { :title => 'Der Titel' } })
assert_full_message 'The title is kaputt', :title, :kaputt
I18n.locale = :de
assert_full_message 'Der Titel ist kaputt', :title, :kaputt
I18n.locale = :en
assert_full_message 'The title is kaputt', :title, :kaputt
end
end
# ACTIVERECORD DEFAULT ERROR MESSAGES
#
# * test that Error generates the default error messages
class ActiveRecordDefaultErrorMessagesI18nTests < ActiveSupport::TestCase
def assert_default_error_message(message, *args)
assert_equal message, error_message(*args)
end
def error_message(*args)
ActiveRecord::Error.new(Topic.new, :title, *args).message
end
# used by: validates_inclusion_of
test "default error message: inclusion" do
assert_default_error_message 'is not included in the list', :inclusion, :value => 'title'
end
# used by: validates_exclusion_of
test "default error message: exclusion" do
assert_default_error_message 'is reserved', :exclusion, :value => 'title'
end
# used by: validates_associated and validates_format_of
test "default error message: invalid" do
assert_default_error_message 'is invalid', :invalid, :value => 'title'
end
# used by: validates_confirmation_of
test "default error message: confirmation" do
assert_default_error_message "doesn't match confirmation", :confirmation, :default => nil
end
# used by: validates_acceptance_of
test "default error message: accepted" do
assert_default_error_message "must be accepted", :accepted
end
# used by: add_on_empty
test "default error message: empty" do
assert_default_error_message "can't be empty", :empty
end
# used by: add_on_blank
test "default error message: blank" do
assert_default_error_message "can't be blank", :blank
end
# used by: validates_length_of
test "default error message: too_long" do
assert_default_error_message "is too long (maximum is 10 characters)", :too_long, :count => 10
end
# used by: validates_length_of
test "default error message: too_short" do
assert_default_error_message "is too short (minimum is 10 characters)", :too_short, :count => 10
end
# used by: validates_length_of
test "default error message: wrong_length" do
assert_default_error_message "is the wrong length (should be 10 characters)", :wrong_length, :count => 10
end
# used by: validates_uniqueness_of
test "default error message: taken" do
assert_default_error_message "has already been taken", :taken, :value => 'title'
end
# used by: validates_numericality_of
test "default error message: not_a_number" do
assert_default_error_message "is not a number", :not_a_number, :value => 'title'
end
# used by: validates_numericality_of
test "default error message: greater_than" do
assert_default_error_message "must be greater than 10", :greater_than, :value => 'title', :count => 10
end
# used by: validates_numericality_of
test "default error message: greater_than_or_equal_to" do
assert_default_error_message "must be greater than or equal to 10", :greater_than_or_equal_to, :value => 'title', :count => 10
end
# used by: validates_numericality_of
test "default error message: equal_to" do
assert_default_error_message "must be equal to 10", :equal_to, :value => 'title', :count => 10
end
# used by: validates_numericality_of
test "default error message: less_than" do
assert_default_error_message "must be less than 10", :less_than, :value => 'title', :count => 10
end
# used by: validates_numericality_of
test "default error message: less_than_or_equal_to" do
assert_default_error_message "must be less than or equal to 10", :less_than_or_equal_to, :value => 'title', :count => 10
end
# used by: validates_numericality_of
test "default error message: odd" do
assert_default_error_message "must be odd", :odd, :value => 'title', :count => 10
end
# used by: validates_numericality_of
test "default error message: even" do
assert_default_error_message "must be even", :even, :value => 'title', :count => 10
end
test "custom message string interpolation" do
assert_equal 'custom message title', error_message(:invalid, :default => 'custom message {{value}}', :value => 'title')
end
end
# ACTIVERECORD VALIDATION ERROR MESSAGES - FULL STACK
#
# * test a few combinations full stack to ensure the tests above are correct
class I18nPerson < Person
end
class ActiveRecordValidationsI18nFullStackTests < ActiveSupport::TestCase
include ActiveRecordValidationsI18nTestHelper
def setup
reset_callbacks(I18nPerson)
@old_backend, I18n.backend = I18n.backend, I18n::Backend::Simple.new
@person = I18nPerson.new
end
def teardown
reset_callbacks(I18nPerson)
I18n.backend = @old_backend
end
def assert_name_invalid(message)
yield
@person.valid?
assert_equal message, @person.errors.on(:name)
end
# Symbols as class-level validation messages
test "Symbol as class level validation message translated per attribute (translation on child class)" do
assert_name_invalid("is broken") do
store_translations :errors => {:models => {:i18n_person => {:attributes => {:name => {:broken => "is broken"}}}}}
I18nPerson.validates_presence_of :name, :message => :broken
end
end
test "Symbol as class level validation message translated per attribute (translation on base class)" do
assert_name_invalid("is broken") do
store_translations :errors => {:models => {:person => {:attributes => {:name => {:broken => "is broken"}}}}}
I18nPerson.validates_presence_of :name, :message => :broken
end
end
test "Symbol as class level validation message translated per model (translation on child class)" do
assert_name_invalid("is broken") do
store_translations :errors => {:models => {:i18n_person => {:broken => "is broken"}}}
I18nPerson.validates_presence_of :name, :message => :broken
end
end
test "Symbol as class level validation message translated per model (translation on base class)" do
assert_name_invalid("is broken") do
store_translations :errors => {:models => {:person => {:broken => "is broken"}}}
I18nPerson.validates_presence_of :name, :message => :broken
end
end
test "Symbol as class level validation message translated as error message" do
assert_name_invalid("is broken") do
store_translations :errors => {:messages => {:broken => "is broken"}}
I18nPerson.validates_presence_of :name, :message => :broken
end
end
# Strings as class-level validation messages
test "String as class level validation message translated per attribute (translation on child class)" do
assert_name_invalid("is broken") do
store_translations :errors => {:models => {:i18n_person => {:attributes => {:name => {"is broken" => "is broken"}}}}}
I18nPerson.validates_presence_of :name, :message => "is broken"
end
end
test "String as class level validation message translated per attribute (translation on base class)" do
assert_name_invalid("is broken") do
store_translations :errors => {:models => {:person => {:attributes => {:name => {"is broken" => "is broken"}}}}}
I18nPerson.validates_presence_of :name, :message => "is broken"
end
end
test "String as class level validation message translated per model (translation on child class)" do
assert_name_invalid("is broken") do
store_translations :errors => {:models => {:i18n_person => {"is broken" => "is broken"}}}
I18nPerson.validates_presence_of :name, :message => "is broken"
end
end
test "String as class level validation message translated per model (translation on base class)" do
assert_name_invalid("is broken") do
store_translations :errors => {:models => {:person => {"is broken" => "is broken"}}}
I18nPerson.validates_presence_of :name, :message => "is broken"
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | true |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/method_scoping_test.rb | provider/vendor/rails/activerecord/test/cases/method_scoping_test.rb | require "cases/helper"
require 'models/post'
require 'models/author'
require 'models/developer'
require 'models/project'
require 'models/comment'
require 'models/category'
class MethodScopingTest < ActiveRecord::TestCase
fixtures :authors, :developers, :projects, :comments, :posts, :developers_projects
def test_set_conditions
Developer.with_scope(:find => { :conditions => 'just a test...' }) do
assert_equal 'just a test...', Developer.send(:current_scoped_methods)[:find][:conditions]
end
end
def test_scoped_find
Developer.with_scope(:find => { :conditions => "name = 'David'" }) do
assert_nothing_raised { Developer.find(1) }
end
end
def test_scoped_find_first
Developer.with_scope(:find => { :conditions => "salary = 100000" }) do
assert_equal Developer.find(10), Developer.find(:first, :order => 'name')
end
end
def test_scoped_find_last
highest_salary = Developer.find(:first, :order => "salary DESC")
Developer.with_scope(:find => { :order => "salary" }) do
assert_equal highest_salary, Developer.last
end
end
def test_scoped_find_last_preserves_scope
lowest_salary = Developer.find(:first, :order => "salary ASC")
highest_salary = Developer.find(:first, :order => "salary DESC")
Developer.with_scope(:find => { :order => "salary" }) do
assert_equal highest_salary, Developer.last
assert_equal lowest_salary, Developer.first
end
end
def test_scoped_find_combines_conditions
Developer.with_scope(:find => { :conditions => "salary = 9000" }) do
assert_equal developers(:poor_jamis), Developer.find(:first, :conditions => "name = 'Jamis'")
end
end
def test_scoped_find_sanitizes_conditions
Developer.with_scope(:find => { :conditions => ['salary = ?', 9000] }) do
assert_equal developers(:poor_jamis), Developer.find(:first)
end
end
def test_scoped_find_combines_and_sanitizes_conditions
Developer.with_scope(:find => { :conditions => ['salary = ?', 9000] }) do
assert_equal developers(:poor_jamis), Developer.find(:first, :conditions => ['name = ?', 'Jamis'])
end
end
def test_scoped_find_all
Developer.with_scope(:find => { :conditions => "name = 'David'" }) do
assert_equal [developers(:david)], Developer.find(:all)
end
end
def test_scoped_find_select
Developer.with_scope(:find => { :select => "id, name" }) do
developer = Developer.find(:first, :conditions => "name = 'David'")
assert_equal "David", developer.name
assert !developer.has_attribute?(:salary)
end
end
def test_options_select_replaces_scope_select
Developer.with_scope(:find => { :select => "id, name" }) do
developer = Developer.find(:first, :select => 'id, salary', :conditions => "name = 'David'")
assert_equal 80000, developer.salary
assert !developer.has_attribute?(:name)
end
end
def test_scoped_count
Developer.with_scope(:find => { :conditions => "name = 'David'" }) do
assert_equal 1, Developer.count
end
Developer.with_scope(:find => { :conditions => 'salary = 100000' }) do
assert_equal 8, Developer.count
assert_equal 1, Developer.count(:conditions => "name LIKE 'fixture_1%'")
end
end
def test_scoped_find_include
# with the include, will retrieve only developers for the given project
scoped_developers = Developer.with_scope(:find => { :include => :projects }) do
Developer.find(:all, :conditions => 'projects.id = 2')
end
assert scoped_developers.include?(developers(:david))
assert !scoped_developers.include?(developers(:jamis))
assert_equal 1, scoped_developers.size
end
def test_scoped_find_joins
scoped_developers = Developer.with_scope(:find => { :joins => 'JOIN developers_projects ON id = developer_id' } ) do
Developer.find(:all, :conditions => 'developers_projects.project_id = 2')
end
assert scoped_developers.include?(developers(:david))
assert !scoped_developers.include?(developers(:jamis))
assert_equal 1, scoped_developers.size
assert_equal developers(:david).attributes, scoped_developers.first.attributes
end
def test_scoped_find_using_new_style_joins
scoped_developers = Developer.with_scope(:find => { :joins => :projects }) do
Developer.find(:all, :conditions => 'projects.id = 2')
end
assert scoped_developers.include?(developers(:david))
assert !scoped_developers.include?(developers(:jamis))
assert_equal 1, scoped_developers.size
assert_equal developers(:david).attributes, scoped_developers.first.attributes
end
def test_scoped_find_merges_old_style_joins
scoped_authors = Author.with_scope(:find => { :joins => 'INNER JOIN posts ON authors.id = posts.author_id ' }) do
Author.find(:all, :select => 'DISTINCT authors.*', :joins => 'INNER JOIN comments ON posts.id = comments.post_id', :conditions => 'comments.id = 1')
end
assert scoped_authors.include?(authors(:david))
assert !scoped_authors.include?(authors(:mary))
assert_equal 1, scoped_authors.size
assert_equal authors(:david).attributes, scoped_authors.first.attributes
end
def test_scoped_find_merges_new_style_joins
scoped_authors = Author.with_scope(:find => { :joins => :posts }) do
Author.find(:all, :select => 'DISTINCT authors.*', :joins => :comments, :conditions => 'comments.id = 1')
end
assert scoped_authors.include?(authors(:david))
assert !scoped_authors.include?(authors(:mary))
assert_equal 1, scoped_authors.size
assert_equal authors(:david).attributes, scoped_authors.first.attributes
end
def test_scoped_find_merges_new_and_old_style_joins
scoped_authors = Author.with_scope(:find => { :joins => :posts }) do
Author.find(:all, :select => 'DISTINCT authors.*', :joins => 'JOIN comments ON posts.id = comments.post_id', :conditions => 'comments.id = 1')
end
assert scoped_authors.include?(authors(:david))
assert !scoped_authors.include?(authors(:mary))
assert_equal 1, scoped_authors.size
assert_equal authors(:david).attributes, scoped_authors.first.attributes
end
def test_scoped_find_merges_string_array_style_and_string_style_joins
scoped_authors = Author.with_scope(:find => { :joins => ["INNER JOIN posts ON posts.author_id = authors.id"]}) do
Author.find(:all, :select => 'DISTINCT authors.*', :joins => 'INNER JOIN comments ON posts.id = comments.post_id', :conditions => 'comments.id = 1')
end
assert scoped_authors.include?(authors(:david))
assert !scoped_authors.include?(authors(:mary))
assert_equal 1, scoped_authors.size
assert_equal authors(:david).attributes, scoped_authors.first.attributes
end
def test_scoped_find_merges_string_array_style_and_hash_style_joins
scoped_authors = Author.with_scope(:find => { :joins => :posts}) do
Author.find(:all, :select => 'DISTINCT authors.*', :joins => ['INNER JOIN comments ON posts.id = comments.post_id'], :conditions => 'comments.id = 1')
end
assert scoped_authors.include?(authors(:david))
assert !scoped_authors.include?(authors(:mary))
assert_equal 1, scoped_authors.size
assert_equal authors(:david).attributes, scoped_authors.first.attributes
end
def test_scoped_find_merges_joins_and_eliminates_duplicate_string_joins
scoped_authors = Author.with_scope(:find => { :joins => 'INNER JOIN posts ON posts.author_id = authors.id'}) do
Author.find(:all, :select => 'DISTINCT authors.*', :joins => ["INNER JOIN posts ON posts.author_id = authors.id", "INNER JOIN comments ON posts.id = comments.post_id"], :conditions => 'comments.id = 1')
end
assert scoped_authors.include?(authors(:david))
assert !scoped_authors.include?(authors(:mary))
assert_equal 1, scoped_authors.size
assert_equal authors(:david).attributes, scoped_authors.first.attributes
end
def test_scoped_find_strips_spaces_from_string_joins_and_eliminates_duplicate_string_joins
scoped_authors = Author.with_scope(:find => { :joins => ' INNER JOIN posts ON posts.author_id = authors.id '}) do
Author.find(:all, :select => 'DISTINCT authors.*', :joins => ['INNER JOIN posts ON posts.author_id = authors.id'], :conditions => 'posts.id = 1')
end
assert scoped_authors.include?(authors(:david))
assert !scoped_authors.include?(authors(:mary))
assert_equal 1, scoped_authors.size
assert_equal authors(:david).attributes, scoped_authors.first.attributes
end
def test_scoped_count_include
# with the include, will retrieve only developers for the given project
Developer.with_scope(:find => { :include => :projects }) do
assert_equal 1, Developer.count(:conditions => 'projects.id = 2')
end
end
def test_scoped_create
new_comment = nil
VerySpecialComment.with_scope(:create => { :post_id => 1 }) do
assert_equal({ :post_id => 1 }, VerySpecialComment.send(:current_scoped_methods)[:create])
new_comment = VerySpecialComment.create :body => "Wonderful world"
end
assert Post.find(1).comments.include?(new_comment)
end
def test_immutable_scope
options = { :conditions => "name = 'David'" }
Developer.with_scope(:find => options) do
assert_equal %w(David), Developer.find(:all).map { |d| d.name }
options[:conditions] = "name != 'David'"
assert_equal %w(David), Developer.find(:all).map { |d| d.name }
end
scope = { :find => { :conditions => "name = 'David'" }}
Developer.with_scope(scope) do
assert_equal %w(David), Developer.find(:all).map { |d| d.name }
scope[:find][:conditions] = "name != 'David'"
assert_equal %w(David), Developer.find(:all).map { |d| d.name }
end
end
def test_scoped_with_duck_typing
scoping = Struct.new(:method_scoping).new(:find => { :conditions => ["name = ?", 'David'] })
Developer.with_scope(scoping) do
assert_equal %w(David), Developer.find(:all).map { |d| d.name }
end
end
def test_ensure_that_method_scoping_is_correctly_restored
scoped_methods = Developer.instance_eval('current_scoped_methods')
begin
Developer.with_scope(:find => { :conditions => "name = 'Jamis'" }) do
raise "an exception"
end
rescue
end
assert_equal scoped_methods, Developer.instance_eval('current_scoped_methods')
end
end
class NestedScopingTest < ActiveRecord::TestCase
fixtures :authors, :developers, :projects, :comments, :posts
def test_merge_options
Developer.with_scope(:find => { :conditions => 'salary = 80000' }) do
Developer.with_scope(:find => { :limit => 10 }) do
merged_option = Developer.instance_eval('current_scoped_methods')[:find]
assert_equal({ :conditions => 'salary = 80000', :limit => 10 }, merged_option)
end
end
end
def test_merge_inner_scope_has_priority
Developer.with_scope(:find => { :limit => 5 }) do
Developer.with_scope(:find => { :limit => 10 }) do
merged_option = Developer.instance_eval('current_scoped_methods')[:find]
assert_equal({ :limit => 10 }, merged_option)
end
end
end
def test_replace_options
Developer.with_scope(:find => { :conditions => "name = 'David'" }) do
Developer.with_exclusive_scope(:find => { :conditions => "name = 'Jamis'" }) do
assert_equal({:find => { :conditions => "name = 'Jamis'" }}, Developer.instance_eval('current_scoped_methods'))
assert_equal({:find => { :conditions => "name = 'Jamis'" }}, Developer.send(:scoped_methods)[-1])
end
end
end
def test_append_conditions
Developer.with_scope(:find => { :conditions => "name = 'David'" }) do
Developer.with_scope(:find => { :conditions => 'salary = 80000' }) do
appended_condition = Developer.instance_eval('current_scoped_methods')[:find][:conditions]
assert_equal("(name = 'David') AND (salary = 80000)", appended_condition)
assert_equal(1, Developer.count)
end
Developer.with_scope(:find => { :conditions => "name = 'Maiha'" }) do
assert_equal(0, Developer.count)
end
end
end
def test_merge_and_append_options
Developer.with_scope(:find => { :conditions => 'salary = 80000', :limit => 10 }) do
Developer.with_scope(:find => { :conditions => "name = 'David'" }) do
merged_option = Developer.instance_eval('current_scoped_methods')[:find]
assert_equal({ :conditions => "(salary = 80000) AND (name = 'David')", :limit => 10 }, merged_option)
end
end
end
def test_nested_scoped_find
Developer.with_scope(:find => { :conditions => "name = 'Jamis'" }) do
Developer.with_exclusive_scope(:find => { :conditions => "name = 'David'" }) do
assert_nothing_raised { Developer.find(1) }
assert_equal('David', Developer.find(:first).name)
end
assert_equal('Jamis', Developer.find(:first).name)
end
end
def test_nested_scoped_find_include
Developer.with_scope(:find => { :include => :projects }) do
Developer.with_scope(:find => { :conditions => "projects.id = 2" }) do
assert_nothing_raised { Developer.find(1) }
assert_equal('David', Developer.find(:first).name)
end
end
end
def test_nested_scoped_find_merged_include
# :include's remain unique and don't "double up" when merging
Developer.with_scope(:find => { :include => :projects, :conditions => "projects.id = 2" }) do
Developer.with_scope(:find => { :include => :projects }) do
assert_equal 1, Developer.instance_eval('current_scoped_methods')[:find][:include].length
assert_equal('David', Developer.find(:first).name)
end
end
# the nested scope doesn't remove the first :include
Developer.with_scope(:find => { :include => :projects, :conditions => "projects.id = 2" }) do
Developer.with_scope(:find => { :include => [] }) do
assert_equal 1, Developer.instance_eval('current_scoped_methods')[:find][:include].length
assert_equal('David', Developer.find(:first).name)
end
end
# mixing array and symbol include's will merge correctly
Developer.with_scope(:find => { :include => [:projects], :conditions => "projects.id = 2" }) do
Developer.with_scope(:find => { :include => :projects }) do
assert_equal 1, Developer.instance_eval('current_scoped_methods')[:find][:include].length
assert_equal('David', Developer.find(:first).name)
end
end
end
def test_nested_scoped_find_replace_include
Developer.with_scope(:find => { :include => :projects }) do
Developer.with_exclusive_scope(:find => { :include => [] }) do
assert_equal 0, Developer.instance_eval('current_scoped_methods')[:find][:include].length
end
end
end
def test_three_level_nested_exclusive_scoped_find
Developer.with_scope(:find => { :conditions => "name = 'Jamis'" }) do
assert_equal('Jamis', Developer.find(:first).name)
Developer.with_exclusive_scope(:find => { :conditions => "name = 'David'" }) do
assert_equal('David', Developer.find(:first).name)
Developer.with_exclusive_scope(:find => { :conditions => "name = 'Maiha'" }) do
assert_equal(nil, Developer.find(:first))
end
# ensure that scoping is restored
assert_equal('David', Developer.find(:first).name)
end
# ensure that scoping is restored
assert_equal('Jamis', Developer.find(:first).name)
end
end
def test_merged_scoped_find
poor_jamis = developers(:poor_jamis)
Developer.with_scope(:find => { :conditions => "salary < 100000" }) do
Developer.with_scope(:find => { :offset => 1, :order => 'id asc' }) do
assert_sql /ORDER BY id asc / do
assert_equal(poor_jamis, Developer.find(:first, :order => 'id asc'))
end
end
end
end
def test_merged_scoped_find_sanitizes_conditions
Developer.with_scope(:find => { :conditions => ["name = ?", 'David'] }) do
Developer.with_scope(:find => { :conditions => ['salary = ?', 9000] }) do
assert_raise(ActiveRecord::RecordNotFound) { developers(:poor_jamis) }
end
end
end
def test_nested_scoped_find_combines_and_sanitizes_conditions
Developer.with_scope(:find => { :conditions => ["name = ?", 'David'] }) do
Developer.with_exclusive_scope(:find => { :conditions => ['salary = ?', 9000] }) do
assert_equal developers(:poor_jamis), Developer.find(:first)
assert_equal developers(:poor_jamis), Developer.find(:first, :conditions => ['name = ?', 'Jamis'])
end
end
end
def test_merged_scoped_find_combines_and_sanitizes_conditions
Developer.with_scope(:find => { :conditions => ["name = ?", 'David'] }) do
Developer.with_scope(:find => { :conditions => ['salary > ?', 9000] }) do
assert_equal %w(David), Developer.find(:all).map { |d| d.name }
end
end
end
def test_nested_scoped_create
comment = nil
Comment.with_scope(:create => { :post_id => 1}) do
Comment.with_scope(:create => { :post_id => 2}) do
assert_equal({ :post_id => 2 }, Comment.send(:current_scoped_methods)[:create])
comment = Comment.create :body => "Hey guys, nested scopes are broken. Please fix!"
end
end
assert_equal 2, comment.post_id
end
def test_nested_exclusive_scope_for_create
comment = nil
Comment.with_scope(:create => { :body => "Hey guys, nested scopes are broken. Please fix!" }) do
Comment.with_exclusive_scope(:create => { :post_id => 1 }) do
assert_equal({ :post_id => 1 }, Comment.send(:current_scoped_methods)[:create])
comment = Comment.create :body => "Hey guys"
end
end
assert_equal 1, comment.post_id
assert_equal 'Hey guys', comment.body
end
def test_merged_scoped_find_on_blank_conditions
[nil, " ", [], {}].each do |blank|
Developer.with_scope(:find => {:conditions => blank}) do
Developer.with_scope(:find => {:conditions => blank}) do
assert_nothing_raised { Developer.find(:first) }
end
end
end
end
def test_merged_scoped_find_on_blank_bind_conditions
[ [""], ["",{}] ].each do |blank|
Developer.with_scope(:find => {:conditions => blank}) do
Developer.with_scope(:find => {:conditions => blank}) do
assert_nothing_raised { Developer.find(:first) }
end
end
end
end
def test_immutable_nested_scope
options1 = { :conditions => "name = 'Jamis'" }
options2 = { :conditions => "name = 'David'" }
Developer.with_scope(:find => options1) do
Developer.with_exclusive_scope(:find => options2) do
assert_equal %w(David), Developer.find(:all).map { |d| d.name }
options1[:conditions] = options2[:conditions] = nil
assert_equal %w(David), Developer.find(:all).map { |d| d.name }
end
end
end
def test_immutable_merged_scope
options1 = { :conditions => "name = 'Jamis'" }
options2 = { :conditions => "salary > 10000" }
Developer.with_scope(:find => options1) do
Developer.with_scope(:find => options2) do
assert_equal %w(Jamis), Developer.find(:all).map { |d| d.name }
options1[:conditions] = options2[:conditions] = nil
assert_equal %w(Jamis), Developer.find(:all).map { |d| d.name }
end
end
end
def test_ensure_that_method_scoping_is_correctly_restored
Developer.with_scope(:find => { :conditions => "name = 'David'" }) do
scoped_methods = Developer.instance_eval('current_scoped_methods')
begin
Developer.with_scope(:find => { :conditions => "name = 'Maiha'" }) do
raise "an exception"
end
rescue
end
assert_equal scoped_methods, Developer.instance_eval('current_scoped_methods')
end
end
def test_nested_scoped_find_merges_old_style_joins
scoped_authors = Author.with_scope(:find => { :joins => 'INNER JOIN posts ON authors.id = posts.author_id' }) do
Author.with_scope(:find => { :joins => 'INNER JOIN comments ON posts.id = comments.post_id' }) do
Author.find(:all, :select => 'DISTINCT authors.*', :conditions => 'comments.id = 1')
end
end
assert scoped_authors.include?(authors(:david))
assert !scoped_authors.include?(authors(:mary))
assert_equal 1, scoped_authors.size
assert_equal authors(:david).attributes, scoped_authors.first.attributes
end
def test_nested_scoped_find_merges_new_style_joins
scoped_authors = Author.with_scope(:find => { :joins => :posts }) do
Author.with_scope(:find => { :joins => :comments }) do
Author.find(:all, :select => 'DISTINCT authors.*', :conditions => 'comments.id = 1')
end
end
assert scoped_authors.include?(authors(:david))
assert !scoped_authors.include?(authors(:mary))
assert_equal 1, scoped_authors.size
assert_equal authors(:david).attributes, scoped_authors.first.attributes
end
def test_nested_scoped_find_merges_new_and_old_style_joins
scoped_authors = Author.with_scope(:find => { :joins => :posts }) do
Author.with_scope(:find => { :joins => 'INNER JOIN comments ON posts.id = comments.post_id' }) do
Author.find(:all, :select => 'DISTINCT authors.*', :joins => '', :conditions => 'comments.id = 1')
end
end
assert scoped_authors.include?(authors(:david))
assert !scoped_authors.include?(authors(:mary))
assert_equal 1, scoped_authors.size
assert_equal authors(:david).attributes, scoped_authors.first.attributes
end
end
class HasManyScopingTest< ActiveRecord::TestCase
fixtures :comments, :posts
def setup
@welcome = Post.find(1)
end
def test_forwarding_of_static_methods
assert_equal 'a comment...', Comment.what_are_you
assert_equal 'a comment...', @welcome.comments.what_are_you
end
def test_forwarding_to_scoped
assert_equal 4, Comment.search_by_type('Comment').size
assert_equal 2, @welcome.comments.search_by_type('Comment').size
end
def test_forwarding_to_dynamic_finders
assert_equal 4, Comment.find_all_by_type('Comment').size
assert_equal 2, @welcome.comments.find_all_by_type('Comment').size
end
def test_nested_scope
Comment.with_scope(:find => { :conditions => '1=1' }) do
assert_equal 'a comment...', @welcome.comments.what_are_you
end
end
end
class HasAndBelongsToManyScopingTest< ActiveRecord::TestCase
fixtures :posts, :categories, :categories_posts
def setup
@welcome = Post.find(1)
end
def test_forwarding_of_static_methods
assert_equal 'a category...', Category.what_are_you
assert_equal 'a category...', @welcome.categories.what_are_you
end
def test_forwarding_to_dynamic_finders
assert_equal 4, Category.find_all_by_type('SpecialCategory').size
assert_equal 0, @welcome.categories.find_all_by_type('SpecialCategory').size
assert_equal 2, @welcome.categories.find_all_by_type('Category').size
end
def test_nested_scope
Category.with_scope(:find => { :conditions => '1=1' }) do
assert_equal 'a comment...', @welcome.comments.what_are_you
end
end
end
class DefaultScopingTest < ActiveRecord::TestCase
fixtures :developers
def test_default_scope
expected = Developer.find(:all, :order => 'salary DESC').collect { |dev| dev.salary }
received = DeveloperOrderedBySalary.find(:all).collect { |dev| dev.salary }
assert_equal expected, received
end
def test_default_scope_with_conditions_string
assert_equal Developer.find_all_by_name('David').map(&:id).sort, DeveloperCalledDavid.all.map(&:id).sort
assert_equal nil, DeveloperCalledDavid.create!.name
end
def test_default_scope_with_conditions_hash
assert_equal Developer.find_all_by_name('Jamis').map(&:id).sort, DeveloperCalledJamis.all.map(&:id).sort
assert_equal 'Jamis', DeveloperCalledJamis.create!.name
end
def test_default_scoping_with_threads
scope = [{ :create => {}, :find => { :order => 'salary DESC' } }]
2.times do
Thread.new { assert_equal scope, DeveloperOrderedBySalary.send(:scoped_methods) }.join
end
end
def test_default_scoping_with_inheritance
scope = [{ :create => {}, :find => { :order => 'salary DESC' } }]
# Inherit a class having a default scope and define a new default scope
klass = Class.new(DeveloperOrderedBySalary)
klass.send :default_scope, {}
# Scopes added on children should append to parent scope
expected_klass_scope = [{ :create => {}, :find => { :order => 'salary DESC' }}, { :create => {}, :find => {} }]
assert_equal expected_klass_scope, klass.send(:scoped_methods)
# Parent should still have the original scope
assert_equal scope, DeveloperOrderedBySalary.send(:scoped_methods)
end
def test_method_scope
expected = Developer.find(:all, :order => 'name DESC').collect { |dev| dev.salary }
received = DeveloperOrderedBySalary.all_ordered_by_name.collect { |dev| dev.salary }
assert_equal expected, received
end
def test_nested_scope
expected = Developer.find(:all, :order => 'name DESC').collect { |dev| dev.salary }
received = DeveloperOrderedBySalary.with_scope(:find => { :order => 'name DESC'}) do
DeveloperOrderedBySalary.find(:all).collect { |dev| dev.salary }
end
assert_equal expected, received
end
def test_named_scope_overwrites_default
expected = Developer.find(:all, :order => 'name DESC').collect { |dev| dev.name }
received = DeveloperOrderedBySalary.by_name.find(:all).collect { |dev| dev.name }
assert_equal expected, received
end
def test_nested_exclusive_scope
expected = Developer.find(:all, :limit => 100).collect { |dev| dev.salary }
received = DeveloperOrderedBySalary.with_exclusive_scope(:find => { :limit => 100 }) do
DeveloperOrderedBySalary.find(:all).collect { |dev| dev.salary }
end
assert_equal expected, received
end
def test_overwriting_default_scope
expected = Developer.find(:all, :order => 'salary').collect { |dev| dev.salary }
received = DeveloperOrderedBySalary.find(:all, :order => 'salary').collect { |dev| dev.salary }
assert_equal expected, received
end
end
=begin
# We disabled the scoping for has_one and belongs_to as we can't think of a proper use case
class BelongsToScopingTest< ActiveRecord::TestCase
fixtures :comments, :posts
def setup
@greetings = Comment.find(1)
end
def test_forwarding_of_static_method
assert_equal 'a post...', Post.what_are_you
assert_equal 'a post...', @greetings.post.what_are_you
end
def test_forwarding_to_dynamic_finders
assert_equal 4, Post.find_all_by_type('Post').size
assert_equal 1, @greetings.post.find_all_by_type('Post').size
end
end
class HasOneScopingTest< ActiveRecord::TestCase
fixtures :comments, :posts
def setup
@sti_comments = Post.find(4)
end
def test_forwarding_of_static_methods
assert_equal 'a comment...', Comment.what_are_you
assert_equal 'a very special comment...', @sti_comments.very_special_comment.what_are_you
end
def test_forwarding_to_dynamic_finders
assert_equal 1, Comment.find_all_by_type('VerySpecialComment').size
assert_equal 1, @sti_comments.very_special_comment.find_all_by_type('VerySpecialComment').size
assert_equal 0, @sti_comments.very_special_comment.find_all_by_type('Comment').size
end
end
=end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/invalid_date_test.rb | provider/vendor/rails/activerecord/test/cases/invalid_date_test.rb | require 'cases/helper'
require 'models/topic'
class InvalidDateTest < Test::Unit::TestCase
def test_assign_valid_dates
valid_dates = [[2007, 11, 30], [1993, 2, 28], [2008, 2, 29]]
invalid_dates = [[2007, 11, 31], [1993, 2, 29], [2007, 2, 29]]
topic = Topic.new
valid_dates.each do |date_src|
topic = Topic.new("last_read(1i)" => date_src[0].to_s, "last_read(2i)" => date_src[1].to_s, "last_read(3i)" => date_src[2].to_s)
assert_equal(topic.last_read, Date.new(*date_src))
end
invalid_dates.each do |date_src|
assert_nothing_raised do
topic = Topic.new({"last_read(1i)" => date_src[0].to_s, "last_read(2i)" => date_src[1].to_s, "last_read(3i)" => date_src[2].to_s})
assert_equal(topic.last_read, Time.local(*date_src).to_date, "The date should be modified according to the behaviour of the Time object")
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/fixtures_test.rb | provider/vendor/rails/activerecord/test/cases/fixtures_test.rb | require "cases/helper"
require 'models/post'
require 'models/binary'
require 'models/topic'
require 'models/computer'
require 'models/developer'
require 'models/company'
require 'models/task'
require 'models/reply'
require 'models/joke'
require 'models/course'
require 'models/category'
require 'models/parrot'
require 'models/pirate'
require 'models/treasure'
require 'models/matey'
require 'models/ship'
require 'models/book'
class FixturesTest < ActiveRecord::TestCase
self.use_instantiated_fixtures = true
self.use_transactional_fixtures = false
fixtures :topics, :developers, :accounts, :tasks, :categories, :funny_jokes, :binaries
FIXTURES = %w( accounts binaries companies customers
developers developers_projects entrants
movies projects subscribers topics tasks )
MATCH_ATTRIBUTE_NAME = /[a-zA-Z][-_\w]*/
def test_clean_fixtures
FIXTURES.each do |name|
fixtures = nil
assert_nothing_raised { fixtures = create_fixtures(name) }
assert_kind_of(Fixtures, fixtures)
fixtures.each { |name, fixture|
fixture.each { |key, value|
assert_match(MATCH_ATTRIBUTE_NAME, key)
}
}
end
end
def test_multiple_clean_fixtures
fixtures_array = nil
assert_nothing_raised { fixtures_array = create_fixtures(*FIXTURES) }
assert_kind_of(Array, fixtures_array)
fixtures_array.each { |fixtures| assert_kind_of(Fixtures, fixtures) }
end
def test_attributes
topics = create_fixtures("topics")
assert_equal("The First Topic", topics["first"]["title"])
assert_nil(topics["second"]["author_email_address"])
end
def test_inserts
topics = create_fixtures("topics")
first_row = ActiveRecord::Base.connection.select_one("SELECT * FROM topics WHERE author_name = 'David'")
assert_equal("The First Topic", first_row["title"])
second_row = ActiveRecord::Base.connection.select_one("SELECT * FROM topics WHERE author_name = 'Mary'")
assert_nil(second_row["author_email_address"])
end
if ActiveRecord::Base.connection.supports_migrations?
def test_inserts_with_pre_and_suffix
# Reset cache to make finds on the new table work
Fixtures.reset_cache
ActiveRecord::Base.connection.create_table :prefix_topics_suffix do |t|
t.column :title, :string
t.column :author_name, :string
t.column :author_email_address, :string
t.column :written_on, :datetime
t.column :bonus_time, :time
t.column :last_read, :date
t.column :content, :string
t.column :approved, :boolean, :default => true
t.column :replies_count, :integer, :default => 0
t.column :parent_id, :integer
t.column :type, :string, :limit => 50
end
# Store existing prefix/suffix
old_prefix = ActiveRecord::Base.table_name_prefix
old_suffix = ActiveRecord::Base.table_name_suffix
# Set a prefix/suffix we can test against
ActiveRecord::Base.table_name_prefix = 'prefix_'
ActiveRecord::Base.table_name_suffix = '_suffix'
topics = create_fixtures("topics")
first_row = ActiveRecord::Base.connection.select_one("SELECT * FROM prefix_topics_suffix WHERE author_name = 'David'")
assert_equal("The First Topic", first_row["title"])
second_row = ActiveRecord::Base.connection.select_one("SELECT * FROM prefix_topics_suffix WHERE author_name = 'Mary'")
assert_nil(second_row["author_email_address"])
# This checks for a caching problem which causes a bug in the fixtures
# class-level configuration helper.
assert_not_nil topics, "Fixture data inserted, but fixture objects not returned from create"
ensure
# Restore prefix/suffix to its previous values
ActiveRecord::Base.table_name_prefix = old_prefix
ActiveRecord::Base.table_name_suffix = old_suffix
ActiveRecord::Base.connection.drop_table :prefix_topics_suffix rescue nil
end
end
def test_insert_with_datetime
topics = create_fixtures("tasks")
first = Task.find(1)
assert first
end
def test_logger_level_invariant
level = ActiveRecord::Base.logger.level
create_fixtures('topics')
assert_equal level, ActiveRecord::Base.logger.level
end
def test_instantiation
topics = create_fixtures("topics")
assert_kind_of Topic, topics["first"].find
end
def test_complete_instantiation
assert_equal 4, @topics.size
assert_equal "The First Topic", @first.title
end
def test_fixtures_from_root_yml_with_instantiation
# assert_equal 2, @accounts.size
assert_equal 50, @unknown.credit_limit
end
def test_erb_in_fixtures
assert_equal 11, @developers.size
assert_equal "fixture_5", @dev_5.name
end
def test_empty_yaml_fixture
assert_not_nil Fixtures.new( Account.connection, "accounts", 'Account', FIXTURES_ROOT + "/naked/yml/accounts")
end
def test_empty_yaml_fixture_with_a_comment_in_it
assert_not_nil Fixtures.new( Account.connection, "companies", 'Company', FIXTURES_ROOT + "/naked/yml/companies")
end
def test_dirty_dirty_yaml_file
assert_raise(Fixture::FormatError) do
Fixtures.new( Account.connection, "courses", 'Course', FIXTURES_ROOT + "/naked/yml/courses")
end
end
def test_empty_csv_fixtures
assert_not_nil Fixtures.new( Account.connection, "accounts", 'Account', FIXTURES_ROOT + "/naked/csv/accounts")
end
def test_omap_fixtures
assert_nothing_raised do
fixtures = Fixtures.new(Account.connection, 'categories', 'Category', FIXTURES_ROOT + "/categories_ordered")
i = 0
fixtures.each do |name, fixture|
assert_equal "fixture_no_#{i}", name
assert_equal "Category #{i}", fixture['name']
i += 1
end
end
end
def test_yml_file_in_subdirectory
assert_equal(categories(:sub_special_1).name, "A special category in a subdir file")
assert_equal(categories(:sub_special_1).class, SpecialCategory)
end
def test_subsubdir_file_with_arbitrary_name
assert_equal(categories(:sub_special_3).name, "A special category in an arbitrarily named subsubdir file")
assert_equal(categories(:sub_special_3).class, SpecialCategory)
end
def test_binary_in_fixtures
assert_equal 1, @binaries.size
data = File.open(ASSETS_ROOT + "/flowers.jpg", 'rb') { |f| f.read }
data.force_encoding('ASCII-8BIT') if data.respond_to?(:force_encoding)
data.freeze
assert_equal data, @flowers.data
end
end
if Account.connection.respond_to?(:reset_pk_sequence!)
class FixturesResetPkSequenceTest < ActiveRecord::TestCase
fixtures :accounts
fixtures :companies
def setup
@instances = [Account.new(:credit_limit => 50), Company.new(:name => 'RoR Consulting')]
Fixtures.reset_cache # make sure tables get reinitialized
end
def test_resets_to_min_pk_with_specified_pk_and_sequence
@instances.each do |instance|
model = instance.class
model.delete_all
model.connection.reset_pk_sequence!(model.table_name, model.primary_key, model.sequence_name)
instance.save!
assert_equal 1, instance.id, "Sequence reset for #{model.table_name} failed."
end
end
def test_resets_to_min_pk_with_default_pk_and_sequence
@instances.each do |instance|
model = instance.class
model.delete_all
model.connection.reset_pk_sequence!(model.table_name)
instance.save!
assert_equal 1, instance.id, "Sequence reset for #{model.table_name} failed."
end
end
def test_create_fixtures_resets_sequences_when_not_cached
@instances.each do |instance|
max_id = create_fixtures(instance.class.table_name).inject(0) do |max_id, (name, fixture)|
fixture_id = fixture['id'].to_i
fixture_id > max_id ? fixture_id : max_id
end
# Clone the last fixture to check that it gets the next greatest id.
instance.save!
assert_equal max_id + 1, instance.id, "Sequence reset for #{instance.class.table_name} failed."
end
end
end
end
class FixturesWithoutInstantiationTest < ActiveRecord::TestCase
self.use_instantiated_fixtures = false
fixtures :topics, :developers, :accounts
def test_without_complete_instantiation
assert_nil @first
assert_nil @topics
assert_nil @developers
assert_nil @accounts
end
def test_fixtures_from_root_yml_without_instantiation
assert_nil @unknown
end
def test_accessor_methods
assert_equal "The First Topic", topics(:first).title
assert_equal "Jamis", developers(:jamis).name
assert_equal 50, accounts(:signals37).credit_limit
end
def test_accessor_methods_with_multiple_args
assert_equal 2, topics(:first, :second).size
assert_raise(StandardError) { topics([:first, :second]) }
end
def test_reloading_fixtures_through_accessor_methods
assert_equal "The First Topic", topics(:first).title
@loaded_fixtures['topics']['first'].expects(:find).returns(stub(:title => "Fresh Topic!"))
assert_equal "Fresh Topic!", topics(:first, true).title
end
end
class FixturesWithoutInstanceInstantiationTest < ActiveRecord::TestCase
self.use_instantiated_fixtures = true
self.use_instantiated_fixtures = :no_instances
fixtures :topics, :developers, :accounts
def test_without_instance_instantiation
assert_nil @first
assert_not_nil @topics
assert_not_nil @developers
assert_not_nil @accounts
end
end
class TransactionalFixturesTest < ActiveRecord::TestCase
self.use_instantiated_fixtures = true
self.use_transactional_fixtures = true
fixtures :topics
def test_destroy
assert_not_nil @first
@first.destroy
end
def test_destroy_just_kidding
assert_not_nil @first
end
end
class MultipleFixturesTest < ActiveRecord::TestCase
fixtures :topics
fixtures :developers, :accounts
def test_fixture_table_names
assert_equal %w(topics developers accounts), fixture_table_names
end
end
class SetupTest < ActiveRecord::TestCase
# fixtures :topics
def setup
@first = true
end
def test_nothing
end
end
class SetupSubclassTest < SetupTest
def setup
super
@second = true
end
def test_subclassing_should_preserve_setups
assert @first
assert @second
end
end
class OverlappingFixturesTest < ActiveRecord::TestCase
fixtures :topics, :developers
fixtures :developers, :accounts
def test_fixture_table_names
assert_equal %w(topics developers accounts), fixture_table_names
end
end
class ForeignKeyFixturesTest < ActiveRecord::TestCase
fixtures :fk_test_has_pk, :fk_test_has_fk
# if foreign keys are implemented and fixtures
# are not deleted in reverse order then this test
# case will raise StatementInvalid
def test_number1
assert true
end
def test_number2
assert true
end
end
class CheckSetTableNameFixturesTest < ActiveRecord::TestCase
set_fixture_class :funny_jokes => 'Joke'
fixtures :funny_jokes
# Set to false to blow away fixtures cache and ensure our fixtures are loaded
# and thus takes into account our set_fixture_class
self.use_transactional_fixtures = false
def test_table_method
assert_kind_of Joke, funny_jokes(:a_joke)
end
end
class FixtureNameIsNotTableNameFixturesTest < ActiveRecord::TestCase
set_fixture_class :items => Book
fixtures :items
# Set to false to blow away fixtures cache and ensure our fixtures are loaded
# and thus takes into account our set_fixture_class
self.use_transactional_fixtures = false
def test_named_accessor
assert_kind_of Book, items(:dvd)
end
end
class FixtureNameIsNotTableNameMultipleFixturesTest < ActiveRecord::TestCase
set_fixture_class :items => Book, :funny_jokes => Joke
fixtures :items, :funny_jokes
# Set to false to blow away fixtures cache and ensure our fixtures are loaded
# and thus takes into account our set_fixture_class
self.use_transactional_fixtures = false
def test_named_accessor_of_differently_named_fixture
assert_kind_of Book, items(:dvd)
end
def test_named_accessor_of_same_named_fixture
assert_kind_of Joke, funny_jokes(:a_joke)
end
end
class CustomConnectionFixturesTest < ActiveRecord::TestCase
set_fixture_class :courses => Course
fixtures :courses
# Set to false to blow away fixtures cache and ensure our fixtures are loaded
# and thus takes into account our set_fixture_class
self.use_transactional_fixtures = false
def test_connection
assert_kind_of Course, courses(:ruby)
assert_equal Course.connection, courses(:ruby).connection
end
end
class InvalidTableNameFixturesTest < ActiveRecord::TestCase
fixtures :funny_jokes
# Set to false to blow away fixtures cache and ensure our fixtures are loaded
# and thus takes into account our lack of set_fixture_class
self.use_transactional_fixtures = false
def test_raises_error
assert_raise FixtureClassNotFound do
funny_jokes(:a_joke)
end
end
end
class CheckEscapedYamlFixturesTest < ActiveRecord::TestCase
set_fixture_class :funny_jokes => 'Joke'
fixtures :funny_jokes
# Set to false to blow away fixtures cache and ensure our fixtures are loaded
# and thus takes into account our set_fixture_class
self.use_transactional_fixtures = false
def test_proper_escaped_fixture
assert_equal "The \\n Aristocrats\nAte the candy\n", funny_jokes(:another_joke).name
end
end
class DevelopersProject; end
class ManyToManyFixturesWithClassDefined < ActiveRecord::TestCase
fixtures :developers_projects
def test_this_should_run_cleanly
assert true
end
end
class FixturesBrokenRollbackTest < ActiveRecord::TestCase
def blank_setup; end
alias_method :ar_setup_fixtures, :setup_fixtures
alias_method :setup_fixtures, :blank_setup
alias_method :setup, :blank_setup
def blank_teardown; end
alias_method :ar_teardown_fixtures, :teardown_fixtures
alias_method :teardown_fixtures, :blank_teardown
alias_method :teardown, :blank_teardown
def test_no_rollback_in_teardown_unless_transaction_active
assert_equal 0, ActiveRecord::Base.connection.open_transactions
assert_raise(RuntimeError) { ar_setup_fixtures }
assert_equal 0, ActiveRecord::Base.connection.open_transactions
assert_nothing_raised { ar_teardown_fixtures }
assert_equal 0, ActiveRecord::Base.connection.open_transactions
end
private
def load_fixtures
raise 'argh'
end
end
class LoadAllFixturesTest < ActiveRecord::TestCase
self.fixture_path = FIXTURES_ROOT + "/all"
fixtures :all
def test_all_there
assert_equal %w(developers people tasks), fixture_table_names.sort
end
end
class FasterFixturesTest < ActiveRecord::TestCase
fixtures :categories, :authors
def load_extra_fixture(name)
fixture = create_fixtures(name)
assert fixture.is_a?(Fixtures)
@loaded_fixtures[fixture.table_name] = fixture
end
def test_cache
assert Fixtures.fixture_is_cached?(ActiveRecord::Base.connection, 'categories')
assert Fixtures.fixture_is_cached?(ActiveRecord::Base.connection, 'authors')
assert_no_queries do
create_fixtures('categories')
create_fixtures('authors')
end
load_extra_fixture('posts')
assert Fixtures.fixture_is_cached?(ActiveRecord::Base.connection, 'posts')
self.class.setup_fixture_accessors('posts')
assert_equal 'Welcome to the weblog', posts(:welcome).title
end
end
class FoxyFixturesTest < ActiveRecord::TestCase
fixtures :parrots, :parrots_pirates, :pirates, :treasures, :mateys, :ships, :computers, :developers
def test_identifies_strings
assert_equal(Fixtures.identify("foo"), Fixtures.identify("foo"))
assert_not_equal(Fixtures.identify("foo"), Fixtures.identify("FOO"))
end
def test_identifies_symbols
assert_equal(Fixtures.identify(:foo), Fixtures.identify(:foo))
end
def test_identifies_consistently
assert_equal 1281023246, Fixtures.identify(:ruby)
assert_equal 2140105598, Fixtures.identify(:sapphire_2)
end
TIMESTAMP_COLUMNS = %w(created_at created_on updated_at updated_on)
def test_populates_timestamp_columns
TIMESTAMP_COLUMNS.each do |property|
assert_not_nil(parrots(:george).send(property), "should set #{property}")
end
end
def test_does_not_populate_timestamp_columns_if_model_has_set_record_timestamps_to_false
TIMESTAMP_COLUMNS.each do |property|
assert_nil(ships(:black_pearl).send(property), "should not set #{property}")
end
end
def test_populates_all_columns_with_the_same_time
last = nil
TIMESTAMP_COLUMNS.each do |property|
current = parrots(:george).send(property)
last ||= current
assert_equal(last, current)
last = current
end
end
def test_only_populates_columns_that_exist
assert_not_nil(pirates(:blackbeard).created_on)
assert_not_nil(pirates(:blackbeard).updated_on)
end
def test_preserves_existing_fixture_data
assert_equal(2.weeks.ago.to_date, pirates(:redbeard).created_on.to_date)
assert_equal(2.weeks.ago.to_date, pirates(:redbeard).updated_on.to_date)
end
def test_generates_unique_ids
assert_not_nil(parrots(:george).id)
assert_not_equal(parrots(:george).id, parrots(:louis).id)
end
def test_automatically_sets_primary_key
assert_not_nil(ships(:black_pearl))
end
def test_preserves_existing_primary_key
assert_equal(2, ships(:interceptor).id)
end
def test_resolves_belongs_to_symbols
assert_equal(parrots(:george), pirates(:blackbeard).parrot)
end
def test_ignores_belongs_to_symbols_if_association_and_foreign_key_are_named_the_same
assert_equal(developers(:david), computers(:workstation).developer)
end
def test_supports_join_tables
assert(pirates(:blackbeard).parrots.include?(parrots(:george)))
assert(pirates(:blackbeard).parrots.include?(parrots(:louis)))
assert(parrots(:george).pirates.include?(pirates(:blackbeard)))
end
def test_supports_inline_habtm
assert(parrots(:george).treasures.include?(treasures(:diamond)))
assert(parrots(:george).treasures.include?(treasures(:sapphire)))
assert(!parrots(:george).treasures.include?(treasures(:ruby)))
end
def test_supports_inline_habtm_with_specified_id
assert(parrots(:polly).treasures.include?(treasures(:ruby)))
assert(parrots(:polly).treasures.include?(treasures(:sapphire)))
assert(!parrots(:polly).treasures.include?(treasures(:diamond)))
end
def test_supports_yaml_arrays
assert(parrots(:louis).treasures.include?(treasures(:diamond)))
assert(parrots(:louis).treasures.include?(treasures(:sapphire)))
end
def test_strips_DEFAULTS_key
assert_raise(StandardError) { parrots(:DEFAULTS) }
# this lets us do YAML defaults and not have an extra fixture entry
%w(sapphire ruby).each { |t| assert(parrots(:davey).treasures.include?(treasures(t))) }
end
def test_supports_label_interpolation
assert_equal("frederick", parrots(:frederick).name)
end
def test_supports_polymorphic_belongs_to
assert_equal(pirates(:redbeard), treasures(:sapphire).looter)
assert_equal(parrots(:louis), treasures(:ruby).looter)
end
def test_only_generates_a_pk_if_necessary
m = Matey.find(:first)
m.pirate = pirates(:blackbeard)
m.target = pirates(:redbeard)
end
def test_supports_sti
assert_kind_of DeadParrot, parrots(:polly)
assert_equal pirates(:blackbeard), parrots(:polly).killer
end
end
class ActiveSupportSubclassWithFixturesTest < ActiveRecord::TestCase
fixtures :parrots
# This seemingly useless assertion catches a bug that caused the fixtures
# setup code call nil[]
def test_foo
assert_equal parrots(:louis), Parrot.find_by_name("King Louis")
end
end
class FixtureLoadingTest < ActiveRecord::TestCase
def test_logs_message_for_failed_dependency_load
ActiveRecord::TestCase.expects(:require_dependency).with(:does_not_exist).raises(LoadError)
ActiveRecord::Base.logger.expects(:warn)
ActiveRecord::TestCase.try_to_load_dependency(:does_not_exist)
end
def test_does_not_logs_message_for_successful_dependency_load
ActiveRecord::TestCase.expects(:require_dependency).with(:works_out_fine)
ActiveRecord::Base.logger.expects(:warn).never
ActiveRecord::TestCase.try_to_load_dependency(:works_out_fine)
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/column_definition_test.rb | provider/vendor/rails/activerecord/test/cases/column_definition_test.rb | require "cases/helper"
class ColumnDefinitionTest < ActiveRecord::TestCase
def setup
@adapter = ActiveRecord::ConnectionAdapters::AbstractAdapter.new(nil)
def @adapter.native_database_types
{:string => "varchar"}
end
end
# Avoid column definitions in create table statements like:
# `title` varchar(255) DEFAULT NULL
def test_should_not_include_default_clause_when_default_is_null
column = ActiveRecord::ConnectionAdapters::Column.new("title", nil, "varchar(20)")
column_def = ActiveRecord::ConnectionAdapters::ColumnDefinition.new(
@adapter, column.name, "string",
column.limit, column.precision, column.scale, column.default, column.null)
assert_equal "title varchar(20)", column_def.to_sql
end
def test_should_include_default_clause_when_default_is_present
column = ActiveRecord::ConnectionAdapters::Column.new("title", "Hello", "varchar(20)")
column_def = ActiveRecord::ConnectionAdapters::ColumnDefinition.new(
@adapter, column.name, "string",
column.limit, column.precision, column.scale, column.default, column.null)
assert_equal %Q{title varchar(20) DEFAULT 'Hello'}, column_def.to_sql
end
def test_should_specify_not_null_if_null_option_is_false
column = ActiveRecord::ConnectionAdapters::Column.new("title", "Hello", "varchar(20)", false)
column_def = ActiveRecord::ConnectionAdapters::ColumnDefinition.new(
@adapter, column.name, "string",
column.limit, column.precision, column.scale, column.default, column.null)
assert_equal %Q{title varchar(20) DEFAULT 'Hello' NOT NULL}, column_def.to_sql
end
if current_adapter?(:MysqlAdapter)
def test_should_set_default_for_mysql_binary_data_types
binary_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", "a", "binary(1)")
assert_equal "a", binary_column.default
varbinary_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", "a", "varbinary(1)")
assert_equal "a", varbinary_column.default
end
def test_should_not_set_default_for_blob_and_text_data_types
assert_raise ArgumentError do
ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", "a", "blob")
end
assert_raise ArgumentError do
ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", "Hello", "text")
end
text_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", nil, "text")
assert_equal nil, text_column.default
not_null_text_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", nil, "text", false)
assert_equal "", not_null_text_column.default
end
def test_has_default_should_return_false_for_blog_and_test_data_types
blob_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", nil, "blob")
assert !blob_column.has_default?
text_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", nil, "text")
assert !text_column.has_default?
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/batches_test.rb | provider/vendor/rails/activerecord/test/cases/batches_test.rb | require 'cases/helper'
require 'models/post'
class EachTest < ActiveRecord::TestCase
fixtures :posts
def setup
@posts = Post.all(:order => "id asc")
@total = Post.count
end
def test_each_should_excecute_one_query_per_batch
assert_queries(Post.count + 1) do
Post.find_each(:batch_size => 1) do |post|
assert_kind_of Post, post
end
end
end
def test_each_should_raise_if_the_order_is_set
assert_raise(RuntimeError) do
Post.find_each(:order => "title") { |post| post }
end
end
def test_each_should_raise_if_the_limit_is_set
assert_raise(RuntimeError) do
Post.find_each(:limit => 1) { |post| post }
end
end
def test_find_in_batches_should_return_batches
assert_queries(Post.count + 1) do
Post.find_in_batches(:batch_size => 1) do |batch|
assert_kind_of Array, batch
assert_kind_of Post, batch.first
end
end
end
def test_find_in_batches_should_start_from_the_start_option
assert_queries(Post.count) do
Post.find_in_batches(:batch_size => 1, :start => 2) do |batch|
assert_kind_of Array, batch
assert_kind_of Post, batch.first
end
end
end
def test_find_in_batches_shouldnt_excute_query_unless_needed
post_count = Post.count
assert_queries(2) do
Post.find_in_batches(:batch_size => post_count) {|batch| assert_kind_of Array, batch }
end
assert_queries(1) do
Post.find_in_batches(:batch_size => post_count + 1) {|batch| assert_kind_of Array, batch }
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/callbacks_observers_test.rb | provider/vendor/rails/activerecord/test/cases/callbacks_observers_test.rb | require "cases/helper"
class Comment < ActiveRecord::Base
attr_accessor :callers
before_validation :record_callers
def after_validation
record_callers
end
def record_callers
callers << self.class if callers
end
end
class CommentObserver < ActiveRecord::Observer
attr_accessor :callers
def after_validation(model)
callers << self.class if callers
end
end
class CallbacksObserversTest < ActiveRecord::TestCase
def test_model_callbacks_fire_before_observers_are_notified
callers = []
comment = Comment.new
comment.callers = callers
CommentObserver.instance.callers = callers
comment.valid?
assert_equal [Comment, Comment, CommentObserver], callers, "model callbacks did not fire before observers were notified"
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/named_scope_test.rb | provider/vendor/rails/activerecord/test/cases/named_scope_test.rb | require "cases/helper"
require 'models/post'
require 'models/topic'
require 'models/comment'
require 'models/reply'
require 'models/author'
require 'models/developer'
class NamedScopeTest < ActiveRecord::TestCase
fixtures :posts, :authors, :topics, :comments, :author_addresses
def test_implements_enumerable
assert !Topic.find(:all).empty?
assert_equal Topic.find(:all), Topic.base
assert_equal Topic.find(:all), Topic.base.to_a
assert_equal Topic.find(:first), Topic.base.first
assert_equal Topic.find(:all), Topic.base.map { |i| i }
end
def test_found_items_are_cached
Topic.columns
all_posts = Topic.base
assert_queries(1) do
all_posts.collect
all_posts.collect
end
end
def test_reload_expires_cache_of_found_items
all_posts = Topic.base
all_posts.inspect
new_post = Topic.create!
assert !all_posts.include?(new_post)
assert all_posts.reload.include?(new_post)
end
def test_delegates_finds_and_calculations_to_the_base_class
assert !Topic.find(:all).empty?
assert_equal Topic.find(:all), Topic.base.find(:all)
assert_equal Topic.find(:first), Topic.base.find(:first)
assert_equal Topic.count, Topic.base.count
assert_equal Topic.average(:replies_count), Topic.base.average(:replies_count)
end
def test_scope_should_respond_to_own_methods_and_methods_of_the_proxy
assert Topic.approved.respond_to?(:proxy_found)
assert Topic.approved.respond_to?(:count)
assert Topic.approved.respond_to?(:length)
end
def test_respond_to_respects_include_private_parameter
assert !Topic.approved.respond_to?(:load_found)
assert Topic.approved.respond_to?(:load_found, true)
end
def test_subclasses_inherit_scopes
assert Topic.scopes.include?(:base)
assert Reply.scopes.include?(:base)
assert_equal Reply.find(:all), Reply.base
end
def test_scopes_with_options_limit_finds_to_those_matching_the_criteria_specified
assert !Topic.find(:all, :conditions => {:approved => true}).empty?
assert_equal Topic.find(:all, :conditions => {:approved => true}), Topic.approved
assert_equal Topic.count(:conditions => {:approved => true}), Topic.approved.count
end
def test_scopes_with_string_name_can_be_composed
# NOTE that scopes defined with a string as a name worked on their own
# but when called on another scope the other scope was completely replaced
assert_equal Topic.replied.approved, Topic.replied.approved_as_string
end
def test_scopes_can_be_specified_with_deep_hash_conditions
assert_equal Topic.replied.approved, Topic.replied.approved_as_hash_condition
end
def test_scopes_are_composable
assert_equal (approved = Topic.find(:all, :conditions => {:approved => true})), Topic.approved
assert_equal (replied = Topic.find(:all, :conditions => 'replies_count > 0')), Topic.replied
assert !(approved == replied)
assert !(approved & replied).empty?
assert_equal approved & replied, Topic.approved.replied
end
def test_procedural_scopes
topics_written_before_the_third = Topic.find(:all, :conditions => ['written_on < ?', topics(:third).written_on])
topics_written_before_the_second = Topic.find(:all, :conditions => ['written_on < ?', topics(:second).written_on])
assert_not_equal topics_written_before_the_second, topics_written_before_the_third
assert_equal topics_written_before_the_third, Topic.written_before(topics(:third).written_on)
assert_equal topics_written_before_the_second, Topic.written_before(topics(:second).written_on)
end
def test_procedural_scopes_returning_nil
all_topics = Topic.find(:all)
assert_equal all_topics, Topic.written_before(nil)
end
def test_scopes_with_joins
address = author_addresses(:david_address)
posts_with_authors_at_address = Post.find(
:all, :joins => 'JOIN authors ON authors.id = posts.author_id',
:conditions => [ 'authors.author_address_id = ?', address.id ]
)
assert_equal posts_with_authors_at_address, Post.with_authors_at_address(address)
end
def test_scopes_with_joins_respects_custom_select
address = author_addresses(:david_address)
posts_with_authors_at_address_titles = Post.find(:all,
:select => 'title',
:joins => 'JOIN authors ON authors.id = posts.author_id',
:conditions => [ 'authors.author_address_id = ?', address.id ]
)
assert_equal posts_with_authors_at_address_titles, Post.with_authors_at_address(address).find(:all, :select => 'title')
end
def test_extensions
assert_equal 1, Topic.anonymous_extension.one
assert_equal 2, Topic.named_extension.two
end
def test_multiple_extensions
assert_equal 2, Topic.multiple_extensions.extension_two
assert_equal 1, Topic.multiple_extensions.extension_one
end
def test_has_many_associations_have_access_to_named_scopes
assert_not_equal Post.containing_the_letter_a, authors(:david).posts
assert !Post.containing_the_letter_a.empty?
assert_equal authors(:david).posts & Post.containing_the_letter_a, authors(:david).posts.containing_the_letter_a
end
def test_has_many_through_associations_have_access_to_named_scopes
assert_not_equal Comment.containing_the_letter_e, authors(:david).comments
assert !Comment.containing_the_letter_e.empty?
assert_equal authors(:david).comments & Comment.containing_the_letter_e, authors(:david).comments.containing_the_letter_e
end
def test_named_scopes_honor_current_scopes_from_when_defined
assert !Post.ranked_by_comments.limit(5).empty?
assert !authors(:david).posts.ranked_by_comments.limit(5).empty?
assert_not_equal Post.ranked_by_comments.limit(5), authors(:david).posts.ranked_by_comments.limit(5)
assert_not_equal Post.top(5), authors(:david).posts.top(5)
assert_equal authors(:david).posts.ranked_by_comments.limit(5), authors(:david).posts.top(5)
assert_equal Post.ranked_by_comments.limit(5), Post.top(5)
end
def test_active_records_have_scope_named__all__
assert !Topic.find(:all).empty?
assert_equal Topic.find(:all), Topic.base
end
def test_active_records_have_scope_named__scoped__
assert !Topic.find(:all, scope = {:conditions => "content LIKE '%Have%'"}).empty?
assert_equal Topic.find(:all, scope), Topic.scoped(scope)
end
def test_proxy_options
expected_proxy_options = { :conditions => { :approved => true } }
assert_equal expected_proxy_options, Topic.approved.proxy_options
end
def test_first_and_last_should_support_find_options
assert_equal Topic.base.first(:order => 'title'), Topic.base.find(:first, :order => 'title')
assert_equal Topic.base.last(:order => 'title'), Topic.base.find(:last, :order => 'title')
end
def test_first_and_last_should_allow_integers_for_limit
assert_equal Topic.base.first(2), Topic.base.to_a.first(2)
assert_equal Topic.base.last(2), Topic.base.to_a.last(2)
end
def test_first_and_last_should_not_use_query_when_results_are_loaded
topics = Topic.base
topics.reload # force load
assert_no_queries do
topics.first
topics.last
end
end
def test_first_and_last_find_options_should_use_query_when_results_are_loaded
topics = Topic.base
topics.reload # force load
assert_queries(2) do
topics.first(:order => 'title')
topics.last(:order => 'title')
end
end
def test_empty_should_not_load_results
topics = Topic.base
assert_queries(2) do
topics.empty? # use count query
topics.collect # force load
topics.empty? # use loaded (no query)
end
end
def test_any_should_not_load_results
topics = Topic.base
assert_queries(2) do
topics.any? # use count query
topics.collect # force load
topics.any? # use loaded (no query)
end
end
def test_any_should_call_proxy_found_if_using_a_block
topics = Topic.base
assert_queries(1) do
topics.expects(:empty?).never
topics.any? { true }
end
end
def test_any_should_not_fire_query_if_named_scope_loaded
topics = Topic.base
topics.collect # force load
assert_no_queries { assert topics.any? }
end
def test_should_build_with_proxy_options
topic = Topic.approved.build({})
assert topic.approved
end
def test_should_build_new_with_proxy_options
topic = Topic.approved.new
assert topic.approved
end
def test_should_create_with_proxy_options
topic = Topic.approved.create({})
assert topic.approved
end
def test_should_create_with_bang_with_proxy_options
topic = Topic.approved.create!({})
assert topic.approved
end
def test_should_build_with_proxy_options_chained
topic = Topic.approved.by_lifo.build({})
assert topic.approved
assert_equal 'lifo', topic.author_name
end
def test_find_all_should_behave_like_select
assert_equal Topic.base.select(&:approved), Topic.base.find_all(&:approved)
end
def test_rand_should_select_a_random_object_from_proxy
assert Topic.approved.rand.is_a?(Topic)
end
def test_should_use_where_in_query_for_named_scope
assert_equal Developer.find_all_by_name('Jamis').to_set, Developer.find_all_by_id(Developer.jamises).to_set
end
def test_size_should_use_count_when_results_are_not_loaded
topics = Topic.base
assert_queries(1) do
assert_sql(/COUNT/i) { topics.size }
end
end
def test_size_should_use_length_when_results_are_loaded
topics = Topic.base
topics.reload # force load
assert_no_queries do
topics.size # use loaded (no query)
end
end
def test_chaining_with_duplicate_joins
join = "INNER JOIN comments ON comments.post_id = posts.id"
post = Post.find(1)
assert_equal post.comments.size, Post.scoped(:joins => join).scoped(:joins => join, :conditions => "posts.id = #{post.id}").size
end
def test_chaining_should_use_latest_conditions_when_creating
post = Topic.rejected.new
assert !post.approved?
post = Topic.rejected.approved.new
assert post.approved?
post = Topic.approved.rejected.new
assert !post.approved?
post = Topic.approved.rejected.approved.new
assert post.approved?
end
def test_chaining_should_use_latest_conditions_when_searching
# Normal hash conditions
assert_equal Topic.all(:conditions => {:approved => true}), Topic.rejected.approved.all
assert_equal Topic.all(:conditions => {:approved => false}), Topic.approved.rejected.all
# Nested hash conditions with same keys
assert_equal [posts(:sti_comments)], Post.with_special_comments.with_very_special_comments.all
# Nested hash conditions with different keys
assert_equal [posts(:sti_comments)], Post.with_special_comments.with_post(4).all.uniq
end
def test_named_scopes_batch_finders
assert_equal 3, Topic.approved.count
assert_queries(4) do
Topic.approved.find_each(:batch_size => 1) {|t| assert t.approved? }
end
assert_queries(2) do
Topic.approved.find_in_batches(:batch_size => 2) do |group|
group.each {|t| assert t.approved? }
end
end
end
def test_table_names_for_chaining_scopes_with_and_without_table_name_included
assert_nothing_raised do
Comment.for_first_post.for_first_author.all
end
end
end
class DynamicScopeMatchTest < ActiveRecord::TestCase
def test_scoped_by_no_match
assert_nil ActiveRecord::DynamicScopeMatch.match("not_scoped_at_all")
end
def test_scoped_by
match = ActiveRecord::DynamicScopeMatch.match("scoped_by_age_and_sex_and_location")
assert_not_nil match
assert match.scope?
assert_equal %w(age sex location), match.attribute_names
end
end
class DynamicScopeTest < ActiveRecord::TestCase
def test_dynamic_scope
assert_equal Post.scoped_by_author_id(1).find(1), Post.find(1)
assert_equal Post.scoped_by_author_id_and_title(1, "Welcome to the weblog").first, Post.find(:first, :conditions => { :author_id => 1, :title => "Welcome to the weblog"})
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/query_cache_test.rb | provider/vendor/rails/activerecord/test/cases/query_cache_test.rb | require "cases/helper"
require 'models/topic'
require 'models/reply'
require 'models/task'
require 'models/course'
require 'models/category'
require 'models/post'
class QueryCacheTest < ActiveRecord::TestCase
fixtures :tasks, :topics, :categories, :posts, :categories_posts
def test_find_queries
assert_queries(2) { Task.find(1); Task.find(1) }
end
def test_find_queries_with_cache
Task.cache do
assert_queries(1) { Task.find(1); Task.find(1) }
end
end
def test_count_queries_with_cache
Task.cache do
assert_queries(1) { Task.count; Task.count }
end
end
def test_query_cache_dups_results_correctly
Task.cache do
now = Time.now.utc
task = Task.find 1
assert_not_equal now, task.starting
task.starting = now
task.reload
assert_not_equal now, task.starting
end
end
def test_cache_is_flat
Task.cache do
Topic.columns # don't count this query
assert_queries(1) { Topic.find(1); Topic.find(1); }
end
ActiveRecord::Base.cache do
assert_queries(1) { Task.find(1); Task.find(1) }
end
end
def test_cache_does_not_wrap_string_results_in_arrays
Task.cache do
assert_instance_of String, Task.connection.select_value("SELECT count(*) AS count_all FROM tasks")
end
end
end
class QueryCacheExpiryTest < ActiveRecord::TestCase
fixtures :tasks, :posts, :categories, :categories_posts
def test_find
Task.connection.expects(:clear_query_cache).times(1)
assert !Task.connection.query_cache_enabled
Task.cache do
assert Task.connection.query_cache_enabled
Task.find(1)
Task.uncached do
assert !Task.connection.query_cache_enabled
Task.find(1)
end
assert Task.connection.query_cache_enabled
end
assert !Task.connection.query_cache_enabled
end
def test_update
Task.connection.expects(:clear_query_cache).times(2)
Task.cache do
task = Task.find(1)
task.starting = Time.now.utc
task.save!
end
end
def test_destroy
Task.connection.expects(:clear_query_cache).times(2)
Task.cache do
Task.find(1).destroy
end
end
def test_insert
ActiveRecord::Base.connection.expects(:clear_query_cache).times(2)
Task.cache do
Task.create!
end
end
def test_cache_is_expired_by_habtm_update
ActiveRecord::Base.connection.expects(:clear_query_cache).times(2)
ActiveRecord::Base.cache do
c = Category.find(:first)
p = Post.find(:first)
p.categories << c
end
end
def test_cache_is_expired_by_habtm_delete
ActiveRecord::Base.connection.expects(:clear_query_cache).times(2)
ActiveRecord::Base.cache do
c = Category.find(1)
p = Post.find(1)
assert p.categories.any?
p.categories.delete_all
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/reserved_word_test_mysql.rb | provider/vendor/rails/activerecord/test/cases/reserved_word_test_mysql.rb | require "cases/helper"
class Group < ActiveRecord::Base
Group.table_name = 'group'
belongs_to :select, :class_name => 'Select'
has_one :values
end
class Select < ActiveRecord::Base
Select.table_name = 'select'
has_many :groups
end
class Values < ActiveRecord::Base
Values.table_name = 'values'
end
class Distinct < ActiveRecord::Base
Distinct.table_name = 'distinct'
has_and_belongs_to_many :selects
has_many :values, :through => :groups
end
# a suite of tests to ensure the ConnectionAdapters#MysqlAdapter can handle tables with
# reserved word names (ie: group, order, values, etc...)
class MysqlReservedWordTest < ActiveRecord::TestCase
def setup
@connection = ActiveRecord::Base.connection
# we call execute directly here (and do similar below) because ActiveRecord::Base#create_table()
# will fail with these table names if these test cases fail
create_tables_directly 'group'=>'id int auto_increment primary key, `order` varchar(255), select_id int',
'select'=>'id int auto_increment primary key',
'values'=>'id int auto_increment primary key, group_id int',
'distinct'=>'id int auto_increment primary key',
'distincts_selects'=>'distinct_id int, select_id int'
end
def teardown
drop_tables_directly ['group', 'select', 'values', 'distinct', 'distincts_selects', 'order']
end
# create tables with reserved-word names and columns
def test_create_tables
assert_nothing_raised {
@connection.create_table :order do |t|
t.column :group, :string
end
}
end
# rename tables with reserved-word names
def test_rename_tables
assert_nothing_raised { @connection.rename_table(:group, :order) }
end
# alter column with a reserved-word name in a table with a reserved-word name
def test_change_columns
assert_nothing_raised { @connection.change_column_default(:group, :order, 'whatever') }
#the quoting here will reveal any double quoting issues in change_column's interaction with the column method in the adapter
assert_nothing_raised { @connection.change_column('group', 'order', :Int, :default => 0) }
assert_nothing_raised { @connection.rename_column(:group, :order, :values) }
end
# dump structure of table with reserved word name
def test_structure_dump
assert_nothing_raised { @connection.structure_dump }
end
# introspect table with reserved word name
def test_introspect
assert_nothing_raised { @connection.columns(:group) }
assert_nothing_raised { @connection.indexes(:group) }
end
#fixtures
self.use_instantiated_fixtures = true
self.use_transactional_fixtures = false
#fixtures :group
def test_fixtures
f = create_test_fixtures :select, :distinct, :group, :values, :distincts_selects
assert_nothing_raised {
f.each do |x|
x.delete_existing_fixtures
end
}
assert_nothing_raised {
f.each do |x|
x.insert_fixtures
end
}
end
#activerecord model class with reserved-word table name
def test_activerecord_model
create_test_fixtures :select, :distinct, :group, :values, :distincts_selects
x = nil
assert_nothing_raised { x = Group.new }
x.order = 'x'
assert_nothing_raised { x.save }
x.order = 'y'
assert_nothing_raised { x.save }
assert_nothing_raised { y = Group.find_by_order('y') }
assert_nothing_raised { y = Group.find(1) }
x = Group.find(1)
end
# has_one association with reserved-word table name
def test_has_one_associations
create_test_fixtures :select, :distinct, :group, :values, :distincts_selects
v = nil
assert_nothing_raised { v = Group.find(1).values }
assert_equal v.id, 2
end
# belongs_to association with reserved-word table name
def test_belongs_to_associations
create_test_fixtures :select, :distinct, :group, :values, :distincts_selects
gs = nil
assert_nothing_raised { gs = Select.find(2).groups }
assert_equal gs.length, 2
assert(gs.collect{|x| x.id}.sort == [2, 3])
end
# has_and_belongs_to_many with reserved-word table name
def test_has_and_belongs_to_many
create_test_fixtures :select, :distinct, :group, :values, :distincts_selects
s = nil
assert_nothing_raised { s = Distinct.find(1).selects }
assert_equal s.length, 2
assert(s.collect{|x|x.id}.sort == [1, 2])
end
# activerecord model introspection with reserved-word table and column names
def test_activerecord_introspection
assert_nothing_raised { Group.table_exists? }
assert_nothing_raised { Group.columns }
end
# Calculations
def test_calculations_work_with_reserved_words
assert_nothing_raised { Group.count }
end
def test_associations_work_with_reserved_words
assert_nothing_raised { Select.find(:all, :include => [:groups]) }
end
#the following functions were added to DRY test cases
private
# custom fixture loader, uses Fixtures#create_fixtures and appends base_path to the current file's path
def create_test_fixtures(*fixture_names)
Fixtures.create_fixtures(FIXTURES_ROOT + "/reserved_words", fixture_names)
end
# custom drop table, uses execute on connection to drop a table if it exists. note: escapes table_name
def drop_tables_directly(table_names, connection = @connection)
table_names.each do |name|
connection.execute("DROP TABLE IF EXISTS `#{name}`")
end
end
# custom create table, uses execute on connection to create a table, note: escapes table_name, does NOT escape columns
def create_tables_directly (tables, connection = @connection)
tables.each do |table_name, column_properties|
connection.execute("CREATE TABLE `#{table_name}` ( #{column_properties} )")
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/database_statements_test.rb | provider/vendor/rails/activerecord/test/cases/database_statements_test.rb | require "cases/helper"
class DatabaseStatementsTest < ActiveRecord::TestCase
def setup
@connection = ActiveRecord::Base.connection
end
def test_insert_should_return_the_inserted_id
id = @connection.insert("INSERT INTO accounts (firm_id,credit_limit) VALUES (42,5000)")
assert_not_nil id
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/datatype_test_postgresql.rb | provider/vendor/rails/activerecord/test/cases/datatype_test_postgresql.rb | require "cases/helper"
class PostgresqlArray < ActiveRecord::Base
end
class PostgresqlMoney < ActiveRecord::Base
end
class PostgresqlNumber < ActiveRecord::Base
end
class PostgresqlTime < ActiveRecord::Base
end
class PostgresqlNetworkAddress < ActiveRecord::Base
end
class PostgresqlBitString < ActiveRecord::Base
end
class PostgresqlOid < ActiveRecord::Base
end
class PostgresqlDataTypeTest < ActiveRecord::TestCase
self.use_transactional_fixtures = false
def setup
@connection = ActiveRecord::Base.connection
@connection.execute("set lc_monetary = 'C'")
@connection.execute("INSERT INTO postgresql_arrays (commission_by_quarter, nicknames) VALUES ( '{35000,21000,18000,17000}', '{foo,bar,baz}' )")
@first_array = PostgresqlArray.find(1)
@connection.execute("INSERT INTO postgresql_moneys (wealth) VALUES ('567.89'::money)")
@connection.execute("INSERT INTO postgresql_moneys (wealth) VALUES ('-567.89'::money)")
@first_money = PostgresqlMoney.find(1)
@second_money = PostgresqlMoney.find(2)
@connection.execute("INSERT INTO postgresql_numbers (single, double) VALUES (123.456, 123456.789)")
@first_number = PostgresqlNumber.find(1)
@connection.execute("INSERT INTO postgresql_times (time_interval) VALUES ('1 year 2 days ago')")
@first_time = PostgresqlTime.find(1)
@connection.execute("INSERT INTO postgresql_network_addresses (cidr_address, inet_address, mac_address) VALUES('192.168.0/24', '172.16.1.254/32', '01:23:45:67:89:0a')")
@first_network_address = PostgresqlNetworkAddress.find(1)
@connection.execute("INSERT INTO postgresql_bit_strings (bit_string, bit_string_varying) VALUES (B'00010101', X'15')")
@first_bit_string = PostgresqlBitString.find(1)
@connection.execute("INSERT INTO postgresql_oids (obj_id) VALUES (1234)")
@first_oid = PostgresqlOid.find(1)
end
def test_data_type_of_array_types
assert_equal :string, @first_array.column_for_attribute(:commission_by_quarter).type
assert_equal :string, @first_array.column_for_attribute(:nicknames).type
end
def test_data_type_of_money_types
assert_equal :decimal, @first_money.column_for_attribute(:wealth).type
end
def test_data_type_of_number_types
assert_equal :float, @first_number.column_for_attribute(:single).type
assert_equal :float, @first_number.column_for_attribute(:double).type
end
def test_data_type_of_time_types
assert_equal :string, @first_time.column_for_attribute(:time_interval).type
end
def test_data_type_of_network_address_types
assert_equal :string, @first_network_address.column_for_attribute(:cidr_address).type
assert_equal :string, @first_network_address.column_for_attribute(:inet_address).type
assert_equal :string, @first_network_address.column_for_attribute(:mac_address).type
end
def test_data_type_of_bit_string_types
assert_equal :string, @first_bit_string.column_for_attribute(:bit_string).type
assert_equal :string, @first_bit_string.column_for_attribute(:bit_string_varying).type
end
def test_data_type_of_oid_types
assert_equal :integer, @first_oid.column_for_attribute(:obj_id).type
end
def test_array_values
assert_equal '{35000,21000,18000,17000}', @first_array.commission_by_quarter
assert_equal '{foo,bar,baz}', @first_array.nicknames
end
def test_money_values
assert_equal 567.89, @first_money.wealth
assert_equal -567.89, @second_money.wealth
end
def test_number_values
assert_equal 123.456, @first_number.single
assert_equal 123456.789, @first_number.double
end
def test_time_values
assert_equal '-1 years -2 days', @first_time.time_interval
end
def test_network_address_values
assert_equal '192.168.0.0/24', @first_network_address.cidr_address
assert_equal '172.16.1.254', @first_network_address.inet_address
assert_equal '01:23:45:67:89:0a', @first_network_address.mac_address
end
def test_bit_string_values
assert_equal '00010101', @first_bit_string.bit_string
assert_equal '00010101', @first_bit_string.bit_string_varying
end
def test_oid_values
assert_equal 1234, @first_oid.obj_id
end
def test_update_integer_array
new_value = '{32800,95000,29350,17000}'
assert @first_array.commission_by_quarter = new_value
assert @first_array.save
assert @first_array.reload
assert_equal @first_array.commission_by_quarter, new_value
assert @first_array.commission_by_quarter = new_value
assert @first_array.save
assert @first_array.reload
assert_equal @first_array.commission_by_quarter, new_value
end
def test_update_text_array
new_value = '{robby,robert,rob,robbie}'
assert @first_array.nicknames = new_value
assert @first_array.save
assert @first_array.reload
assert_equal @first_array.nicknames, new_value
assert @first_array.nicknames = new_value
assert @first_array.save
assert @first_array.reload
assert_equal @first_array.nicknames, new_value
end
def test_update_money
new_value = BigDecimal.new('123.45')
assert @first_money.wealth = new_value
assert @first_money.save
assert @first_money.reload
assert_equal new_value, @first_money.wealth
end
def test_update_number
new_single = 789.012
new_double = 789012.345
assert @first_number.single = new_single
assert @first_number.double = new_double
assert @first_number.save
assert @first_number.reload
assert_equal @first_number.single, new_single
assert_equal @first_number.double, new_double
end
def test_update_time
assert @first_time.time_interval = '2 years 3 minutes'
assert @first_time.save
assert @first_time.reload
assert_equal @first_time.time_interval, '2 years 00:03:00'
end
def test_update_network_address
new_cidr_address = '10.1.2.3/32'
new_inet_address = '10.0.0.0/8'
new_mac_address = 'bc:de:f0:12:34:56'
assert @first_network_address.cidr_address = new_cidr_address
assert @first_network_address.inet_address = new_inet_address
assert @first_network_address.mac_address = new_mac_address
assert @first_network_address.save
assert @first_network_address.reload
assert_equal @first_network_address.cidr_address, new_cidr_address
assert_equal @first_network_address.inet_address, new_inet_address
assert_equal @first_network_address.mac_address, new_mac_address
end
def test_update_bit_string
new_bit_string = '11111111'
new_bit_string_varying = 'FF'
assert @first_bit_string.bit_string = new_bit_string
assert @first_bit_string.bit_string_varying = new_bit_string_varying
assert @first_bit_string.save
assert @first_bit_string.reload
assert_equal @first_bit_string.bit_string, new_bit_string
assert_equal @first_bit_string.bit_string, @first_bit_string.bit_string_varying
end
def test_update_oid
new_value = 567890
assert @first_oid.obj_id = new_value
assert @first_oid.save
assert @first_oid.reload
assert_equal @first_oid.obj_id, new_value
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/multiple_db_test.rb | provider/vendor/rails/activerecord/test/cases/multiple_db_test.rb | require "cases/helper"
require 'models/entrant'
# So we can test whether Course.connection survives a reload.
require_dependency 'models/course'
class MultipleDbTest < ActiveRecord::TestCase
self.use_transactional_fixtures = false
def setup
@courses = create_fixtures("courses") { Course.retrieve_connection }
@entrants = create_fixtures("entrants")
end
def test_connected
assert_not_nil Entrant.connection
assert_not_nil Course.connection
end
def test_proper_connection
assert_not_equal(Entrant.connection, Course.connection)
assert_equal(Entrant.connection, Entrant.retrieve_connection)
assert_equal(Course.connection, Course.retrieve_connection)
assert_equal(ActiveRecord::Base.connection, Entrant.connection)
end
def test_find
c1 = Course.find(1)
assert_equal "Ruby Development", c1.name
c2 = Course.find(2)
assert_equal "Java Development", c2.name
e1 = Entrant.find(1)
assert_equal "Ruby Developer", e1.name
e2 = Entrant.find(2)
assert_equal "Ruby Guru", e2.name
e3 = Entrant.find(3)
assert_equal "Java Lover", e3.name
end
def test_associations
c1 = Course.find(1)
assert_equal 2, c1.entrants.count
e1 = Entrant.find(1)
assert_equal e1.course.id, c1.id
c2 = Course.find(2)
assert_equal 1, c2.entrants.count
e3 = Entrant.find(3)
assert_equal e3.course.id, c2.id
end
def test_course_connection_should_survive_dependency_reload
assert Course.connection
ActiveSupport::Dependencies.clear
Object.send(:remove_const, :Course)
require_dependency 'models/course'
assert Course.connection
end
def test_transactions_across_databases
c1 = Course.find(1)
e1 = Entrant.find(1)
begin
Course.transaction do
Entrant.transaction do
c1.name = "Typo"
e1.name = "Typo"
c1.save
e1.save
raise "No I messed up."
end
end
rescue
# Yup caught it
end
assert_equal "Typo", c1.name
assert_equal "Typo", e1.name
assert_equal "Ruby Development", Course.find(1).name
assert_equal "Ruby Developer", Entrant.find(1).name
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/reload_models_test.rb | provider/vendor/rails/activerecord/test/cases/reload_models_test.rb | require "cases/helper"
require 'models/owner'
require 'models/pet'
class ReloadModelsTest < ActiveRecord::TestCase
fixtures :pets
def test_has_one_with_reload
pet = Pet.find_by_name('parrot')
pet.owner = Owner.find_by_name('ashley')
# Reload the class Owner, simulating auto-reloading of model classes in a
# development environment. Note that meanwhile the class Pet is not
# reloaded, simulating a class that is present in a plugin.
Object.class_eval { remove_const :Owner }
Kernel.load(File.expand_path(File.join(File.dirname(__FILE__), "../models/owner.rb")))
pet = Pet.find_by_name('parrot')
pet.owner = Owner.find_by_name('ashley')
assert_equal pet.owner, Owner.find_by_name('ashley')
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/calculations_test.rb | provider/vendor/rails/activerecord/test/cases/calculations_test.rb | require "cases/helper"
require 'models/company'
require 'models/topic'
require 'models/edge'
require 'models/owner'
require 'models/pet'
require 'models/toy'
require 'models/club'
require 'models/organization'
Company.has_many :accounts
class NumericData < ActiveRecord::Base
self.table_name = 'numeric_data'
end
class CalculationsTest < ActiveRecord::TestCase
fixtures :companies, :accounts, :topics, :owners, :pets, :toys
def test_should_sum_field
assert_equal 318, Account.sum(:credit_limit)
end
def test_should_average_field
value = Account.average(:credit_limit)
assert_kind_of BigDecimal, value
assert_equal BigDecimal.new('53.0'), value
end
def test_should_return_nil_as_average
assert_nil NumericData.average(:bank_balance)
end
def test_type_cast_calculated_value_should_convert_db_averages_of_fixnum_class_to_decimal
assert_equal 0, NumericData.send(:type_cast_calculated_value, 0, nil, 'avg')
assert_equal 53.0, NumericData.send(:type_cast_calculated_value, 53, nil, 'avg')
end
def test_should_get_maximum_of_field
assert_equal 60, Account.maximum(:credit_limit)
end
def test_should_get_maximum_of_field_with_include
assert_equal 50, Account.maximum(:credit_limit, :include => :firm, :conditions => "companies.name != 'Summit'")
end
def test_should_get_maximum_of_field_with_scoped_include
Account.with_scope :find => { :include => :firm, :conditions => "companies.name != 'Summit'" } do
assert_equal 50, Account.maximum(:credit_limit)
end
end
def test_should_get_minimum_of_field
assert_equal 50, Account.minimum(:credit_limit)
end
def test_should_group_by_field
c = Account.sum(:credit_limit, :group => :firm_id)
[1,6,2].each { |firm_id| assert c.keys.include?(firm_id) }
end
def test_should_group_by_summed_field
c = Account.sum(:credit_limit, :group => :firm_id)
assert_equal 50, c[1]
assert_equal 105, c[6]
assert_equal 60, c[2]
end
def test_should_order_by_grouped_field
c = Account.sum(:credit_limit, :group => :firm_id, :order => "firm_id")
assert_equal [1, 2, 6, 9], c.keys.compact
end
def test_should_order_by_calculation
c = Account.sum(:credit_limit, :group => :firm_id, :order => "sum_credit_limit desc, firm_id")
assert_equal [105, 60, 53, 50, 50], c.keys.collect { |k| c[k] }
assert_equal [6, 2, 9, 1], c.keys.compact
end
def test_should_limit_calculation
c = Account.sum(:credit_limit, :conditions => "firm_id IS NOT NULL",
:group => :firm_id, :order => "firm_id", :limit => 2)
assert_equal [1, 2], c.keys.compact
end
def test_should_limit_calculation_with_offset
c = Account.sum(:credit_limit, :conditions => "firm_id IS NOT NULL",
:group => :firm_id, :order => "firm_id", :limit => 2, :offset => 1)
assert_equal [2, 6], c.keys.compact
end
def test_should_group_by_summed_field_having_condition
c = Account.sum(:credit_limit, :group => :firm_id,
:having => 'sum(credit_limit) > 50')
assert_nil c[1]
assert_equal 105, c[6]
assert_equal 60, c[2]
end
def test_should_group_by_summed_field_having_sanitized_condition
c = Account.sum(:credit_limit, :group => :firm_id,
:having => ['sum(credit_limit) > ?', 50])
assert_nil c[1]
assert_equal 105, c[6]
assert_equal 60, c[2]
end
def test_should_group_by_summed_association
c = Account.sum(:credit_limit, :group => :firm)
assert_equal 50, c[companies(:first_firm)]
assert_equal 105, c[companies(:rails_core)]
assert_equal 60, c[companies(:first_client)]
end
def test_should_sum_field_with_conditions
assert_equal 105, Account.sum(:credit_limit, :conditions => 'firm_id = 6')
end
def test_should_return_zero_if_sum_conditions_return_nothing
assert_equal 0, Account.sum(:credit_limit, :conditions => '1 = 2')
assert_equal 0, companies(:rails_core).companies.sum(:id, :conditions => '1 = 2')
end
def test_sum_should_return_valid_values_for_decimals
NumericData.create(:bank_balance => 19.83)
assert_equal 19.83, NumericData.sum(:bank_balance)
end
def test_should_group_by_summed_field_with_conditions
c = Account.sum(:credit_limit, :conditions => 'firm_id > 1',
:group => :firm_id)
assert_nil c[1]
assert_equal 105, c[6]
assert_equal 60, c[2]
end
def test_should_group_by_summed_field_with_conditions_and_having
c = Account.sum(:credit_limit, :conditions => 'firm_id > 1',
:group => :firm_id,
:having => 'sum(credit_limit) > 60')
assert_nil c[1]
assert_equal 105, c[6]
assert_nil c[2]
end
def test_should_group_by_fields_with_table_alias
c = Account.sum(:credit_limit, :group => 'accounts.firm_id')
assert_equal 50, c[1]
assert_equal 105, c[6]
assert_equal 60, c[2]
end
def test_should_calculate_with_invalid_field
assert_equal 6, Account.calculate(:count, '*')
assert_equal 6, Account.calculate(:count, :all)
end
def test_should_calculate_grouped_with_invalid_field
c = Account.count(:all, :group => 'accounts.firm_id')
assert_equal 1, c[1]
assert_equal 2, c[6]
assert_equal 1, c[2]
end
def test_should_calculate_grouped_association_with_invalid_field
c = Account.count(:all, :group => :firm)
assert_equal 1, c[companies(:first_firm)]
assert_equal 2, c[companies(:rails_core)]
assert_equal 1, c[companies(:first_client)]
end
def test_should_group_by_association_with_non_numeric_foreign_key
ActiveRecord::Base.connection.expects(:select_all).returns([{"count_all" => 1, "firm_id" => "ABC"}])
firm = mock()
firm.expects(:id).returns("ABC")
firm.expects(:class).returns(Firm)
Company.expects(:find).with(["ABC"]).returns([firm])
column = mock()
column.expects(:name).at_least_once.returns(:firm_id)
column.expects(:type_cast).with("ABC").returns("ABC")
Account.expects(:columns).at_least_once.returns([column])
c = Account.count(:all, :group => :firm)
first_key = c.keys.first
assert_equal Firm, first_key.class
assert_equal 1, c[first_key]
end
def test_should_calculate_grouped_association_with_foreign_key_option
Account.belongs_to :another_firm, :class_name => 'Firm', :foreign_key => 'firm_id'
c = Account.count(:all, :group => :another_firm)
assert_equal 1, c[companies(:first_firm)]
assert_equal 2, c[companies(:rails_core)]
assert_equal 1, c[companies(:first_client)]
end
def test_should_not_modify_options_when_using_includes
options = {:conditions => 'companies.id > 1', :include => :firm}
options_copy = options.dup
Account.count(:all, options)
assert_equal options_copy, options
end
def test_should_calculate_grouped_by_function
c = Company.count(:all, :group => "UPPER(#{QUOTED_TYPE})")
assert_equal 2, c[nil]
assert_equal 1, c['DEPENDENTFIRM']
assert_equal 3, c['CLIENT']
assert_equal 2, c['FIRM']
end
def test_should_calculate_grouped_by_function_with_table_alias
c = Company.count(:all, :group => "UPPER(companies.#{QUOTED_TYPE})")
assert_equal 2, c[nil]
assert_equal 1, c['DEPENDENTFIRM']
assert_equal 3, c['CLIENT']
assert_equal 2, c['FIRM']
end
def test_should_not_overshadow_enumerable_sum
assert_equal 6, [1, 2, 3].sum(&:abs)
end
def test_should_sum_scoped_field
assert_equal 15, companies(:rails_core).companies.sum(:id)
end
def test_should_sum_scoped_field_with_from
assert_equal Club.count, Organization.clubs.count
end
def test_should_sum_scoped_field_with_conditions
assert_equal 8, companies(:rails_core).companies.sum(:id, :conditions => 'id > 7')
end
def test_should_group_by_scoped_field
c = companies(:rails_core).companies.sum(:id, :group => :name)
assert_equal 7, c['Leetsoft']
assert_equal 8, c['Jadedpixel']
end
def test_should_group_by_summed_field_with_conditions_and_having
c = companies(:rails_core).companies.sum(:id, :group => :name,
:having => 'sum(id) > 7')
assert_nil c['Leetsoft']
assert_equal 8, c['Jadedpixel']
end
def test_should_reject_invalid_options
assert_nothing_raised do
[:count, :sum].each do |func|
# empty options are valid
Company.send(:validate_calculation_options, func)
# these options are valid for all calculations
[:select, :conditions, :joins, :order, :group, :having, :distinct].each do |opt|
Company.send(:validate_calculation_options, func, opt => true)
end
end
# :include is only valid on :count
Company.send(:validate_calculation_options, :count, :include => true)
end
assert_raise(ArgumentError) { Company.send(:validate_calculation_options, :sum, :foo => :bar) }
assert_raise(ArgumentError) { Company.send(:validate_calculation_options, :count, :foo => :bar) }
end
def test_should_count_selected_field_with_include
assert_equal 6, Account.count(:distinct => true, :include => :firm)
assert_equal 4, Account.count(:distinct => true, :include => :firm, :select => :credit_limit)
end
def test_should_count_manual_select_with_include
assert_equal 6, Account.count(:select => "DISTINCT accounts.id", :include => :firm)
end
def test_count_with_column_parameter
assert_equal 5, Account.count(:firm_id)
end
def test_count_with_column_and_options_parameter
assert_equal 2, Account.count(:firm_id, :conditions => "credit_limit = 50")
end
def test_count_with_no_parameters_isnt_deprecated
assert_not_deprecated { Account.count }
end
def test_count_with_too_many_parameters_raises
assert_raise(ArgumentError) { Account.count(1, 2, 3) }
end
def test_count_with_scoped_has_many_through_association
assert_equal 1, owners(:blackbeard).toys.with_name('Bone').count
end
def test_should_sum_expression
assert_equal '636', Account.sum("2 * credit_limit")
end
def test_count_with_from_option
assert_equal Company.count(:all), Company.count(:all, :from => 'companies')
assert_equal Account.count(:all, :conditions => "credit_limit = 50"),
Account.count(:all, :from => 'accounts', :conditions => "credit_limit = 50")
assert_equal Company.count(:type, :conditions => {:type => "Firm"}),
Company.count(:type, :conditions => {:type => "Firm"}, :from => 'companies')
end
def test_sum_with_from_option
assert_equal Account.sum(:credit_limit), Account.sum(:credit_limit, :from => 'accounts')
assert_equal Account.sum(:credit_limit, :conditions => "credit_limit > 50"),
Account.sum(:credit_limit, :from => 'accounts', :conditions => "credit_limit > 50")
end
def test_average_with_from_option
assert_equal Account.average(:credit_limit), Account.average(:credit_limit, :from => 'accounts')
assert_equal Account.average(:credit_limit, :conditions => "credit_limit > 50"),
Account.average(:credit_limit, :from => 'accounts', :conditions => "credit_limit > 50")
end
def test_minimum_with_from_option
assert_equal Account.minimum(:credit_limit), Account.minimum(:credit_limit, :from => 'accounts')
assert_equal Account.minimum(:credit_limit, :conditions => "credit_limit > 50"),
Account.minimum(:credit_limit, :from => 'accounts', :conditions => "credit_limit > 50")
end
def test_maximum_with_from_option
assert_equal Account.maximum(:credit_limit), Account.maximum(:credit_limit, :from => 'accounts')
assert_equal Account.maximum(:credit_limit, :conditions => "credit_limit > 50"),
Account.maximum(:credit_limit, :from => 'accounts', :conditions => "credit_limit > 50")
end
def test_from_option_with_specified_index
if Edge.connection.adapter_name == 'MySQL'
assert_equal Edge.count(:all), Edge.count(:all, :from => 'edges USE INDEX(unique_edge_index)')
assert_equal Edge.count(:all, :conditions => 'sink_id < 5'),
Edge.count(:all, :from => 'edges USE INDEX(unique_edge_index)', :conditions => 'sink_id < 5')
end
end
def test_from_option_with_table_different_than_class
assert_equal Account.count(:all), Company.count(:all, :from => 'accounts')
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/sanitize_test.rb | provider/vendor/rails/activerecord/test/cases/sanitize_test.rb | require "cases/helper"
require 'models/binary'
class SanitizeTest < ActiveRecord::TestCase
def setup
end
def test_sanitize_sql_array_handles_string_interpolation
quoted_bambi = ActiveRecord::Base.connection.quote_string("Bambi")
assert_equal "name=#{quoted_bambi}", Binary.send(:sanitize_sql_array, ["name=%s", "Bambi"])
assert_equal "name=#{quoted_bambi}", Binary.send(:sanitize_sql_array, ["name=%s", "Bambi".mb_chars])
quoted_bambi_and_thumper = ActiveRecord::Base.connection.quote_string("Bambi\nand\nThumper")
assert_equal "name=#{quoted_bambi_and_thumper}",Binary.send(:sanitize_sql_array, ["name=%s", "Bambi\nand\nThumper"])
assert_equal "name=#{quoted_bambi_and_thumper}",Binary.send(:sanitize_sql_array, ["name=%s", "Bambi\nand\nThumper".mb_chars])
end
def test_sanitize_sql_array_handles_bind_variables
quoted_bambi = ActiveRecord::Base.connection.quote("Bambi")
assert_equal "name=#{quoted_bambi}", Binary.send(:sanitize_sql_array, ["name=?", "Bambi"])
assert_equal "name=#{quoted_bambi}", Binary.send(:sanitize_sql_array, ["name=?", "Bambi".mb_chars])
quoted_bambi_and_thumper = ActiveRecord::Base.connection.quote("Bambi\nand\nThumper")
assert_equal "name=#{quoted_bambi_and_thumper}", Binary.send(:sanitize_sql_array, ["name=?", "Bambi\nand\nThumper"])
assert_equal "name=#{quoted_bambi_and_thumper}", Binary.send(:sanitize_sql_array, ["name=?", "Bambi\nand\nThumper".mb_chars])
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/schema_test_postgresql.rb | provider/vendor/rails/activerecord/test/cases/schema_test_postgresql.rb | require "cases/helper"
class SchemaTest < ActiveRecord::TestCase
self.use_transactional_fixtures = false
SCHEMA_NAME = 'test_schema'
SCHEMA2_NAME = 'test_schema2'
TABLE_NAME = 'things'
CAPITALIZED_TABLE_NAME = 'Things'
INDEX_A_NAME = 'a_index_things_on_name'
INDEX_B_NAME = 'b_index_things_on_different_columns_in_each_schema'
INDEX_A_COLUMN = 'name'
INDEX_B_COLUMN_S1 = 'email'
INDEX_B_COLUMN_S2 = 'moment'
COLUMNS = [
'id integer',
'name character varying(50)',
'email character varying(50)',
'moment timestamp without time zone default now()'
]
class Thing1 < ActiveRecord::Base
set_table_name "test_schema.things"
end
class Thing2 < ActiveRecord::Base
set_table_name "test_schema2.things"
end
class Thing3 < ActiveRecord::Base
set_table_name 'test_schema."things.table"'
end
class Thing4 < ActiveRecord::Base
set_table_name 'test_schema."Things"'
end
def setup
@connection = ActiveRecord::Base.connection
@connection.execute "CREATE SCHEMA #{SCHEMA_NAME} CREATE TABLE #{TABLE_NAME} (#{COLUMNS.join(',')})"
@connection.execute "CREATE TABLE #{SCHEMA_NAME}.\"#{TABLE_NAME}.table\" (#{COLUMNS.join(',')})"
@connection.execute "CREATE TABLE #{SCHEMA_NAME}.\"#{CAPITALIZED_TABLE_NAME}\" (#{COLUMNS.join(',')})"
@connection.execute "CREATE SCHEMA #{SCHEMA2_NAME} CREATE TABLE #{TABLE_NAME} (#{COLUMNS.join(',')})"
@connection.execute "CREATE INDEX #{INDEX_A_NAME} ON #{SCHEMA_NAME}.#{TABLE_NAME} USING btree (#{INDEX_A_COLUMN});"
@connection.execute "CREATE INDEX #{INDEX_A_NAME} ON #{SCHEMA2_NAME}.#{TABLE_NAME} USING btree (#{INDEX_A_COLUMN});"
@connection.execute "CREATE INDEX #{INDEX_B_NAME} ON #{SCHEMA_NAME}.#{TABLE_NAME} USING btree (#{INDEX_B_COLUMN_S1});"
@connection.execute "CREATE INDEX #{INDEX_B_NAME} ON #{SCHEMA2_NAME}.#{TABLE_NAME} USING btree (#{INDEX_B_COLUMN_S2});"
end
def teardown
@connection.execute "DROP SCHEMA #{SCHEMA2_NAME} CASCADE"
@connection.execute "DROP SCHEMA #{SCHEMA_NAME} CASCADE"
end
def test_with_schema_prefixed_table_name
assert_nothing_raised do
assert_equal COLUMNS, columns("#{SCHEMA_NAME}.#{TABLE_NAME}")
end
end
def test_with_schema_prefixed_capitalized_table_name
assert_nothing_raised do
assert_equal COLUMNS, columns("#{SCHEMA_NAME}.#{CAPITALIZED_TABLE_NAME}")
end
end
def test_with_schema_search_path
assert_nothing_raised do
with_schema_search_path(SCHEMA_NAME) do
assert_equal COLUMNS, columns(TABLE_NAME)
end
end
end
def test_proper_encoding_of_table_name
assert_equal '"table_name"', @connection.quote_table_name('table_name')
assert_equal '"table.name"', @connection.quote_table_name('"table.name"')
assert_equal '"schema_name"."table_name"', @connection.quote_table_name('schema_name.table_name')
assert_equal '"schema_name"."table.name"', @connection.quote_table_name('schema_name."table.name"')
assert_equal '"schema.name"."table_name"', @connection.quote_table_name('"schema.name".table_name')
assert_equal '"schema.name"."table.name"', @connection.quote_table_name('"schema.name"."table.name"')
end
def test_classes_with_qualified_schema_name
assert_equal 0, Thing1.count
assert_equal 0, Thing2.count
assert_equal 0, Thing3.count
assert_equal 0, Thing4.count
Thing1.create(:id => 1, :name => "thing1", :email => "thing1@localhost", :moment => Time.now)
assert_equal 1, Thing1.count
assert_equal 0, Thing2.count
assert_equal 0, Thing3.count
assert_equal 0, Thing4.count
Thing2.create(:id => 1, :name => "thing1", :email => "thing1@localhost", :moment => Time.now)
assert_equal 1, Thing1.count
assert_equal 1, Thing2.count
assert_equal 0, Thing3.count
assert_equal 0, Thing4.count
Thing3.create(:id => 1, :name => "thing1", :email => "thing1@localhost", :moment => Time.now)
assert_equal 1, Thing1.count
assert_equal 1, Thing2.count
assert_equal 1, Thing3.count
assert_equal 0, Thing4.count
Thing4.create(:id => 1, :name => "thing1", :email => "thing1@localhost", :moment => Time.now)
assert_equal 1, Thing1.count
assert_equal 1, Thing2.count
assert_equal 1, Thing3.count
assert_equal 1, Thing4.count
end
def test_raise_on_unquoted_schema_name
assert_raise(ActiveRecord::StatementInvalid) do
with_schema_search_path '$user,public'
end
end
def test_without_schema_search_path
assert_raise(ActiveRecord::StatementInvalid) { columns(TABLE_NAME) }
end
def test_ignore_nil_schema_search_path
assert_nothing_raised { with_schema_search_path nil }
end
def test_dump_indexes_for_schema_one
do_dump_index_tests_for_schema(SCHEMA_NAME, INDEX_A_COLUMN, INDEX_B_COLUMN_S1)
end
def test_dump_indexes_for_schema_two
do_dump_index_tests_for_schema(SCHEMA2_NAME, INDEX_A_COLUMN, INDEX_B_COLUMN_S2)
end
def test_with_uppercase_index_name
ActiveRecord::Base.connection.execute "CREATE INDEX \"things_Index\" ON #{SCHEMA_NAME}.things (name)"
assert_nothing_raised { ActiveRecord::Base.connection.remove_index :things, :name => "#{SCHEMA_NAME}.things_Index"}
ActiveRecord::Base.connection.execute "CREATE INDEX \"things_Index\" ON #{SCHEMA_NAME}.things (name)"
ActiveRecord::Base.connection.schema_search_path = SCHEMA_NAME
assert_nothing_raised { ActiveRecord::Base.connection.remove_index :things, :name => "things_Index"}
ActiveRecord::Base.connection.schema_search_path = "public"
end
private
def columns(table_name)
@connection.send(:column_definitions, table_name).map do |name, type, default|
"#{name} #{type}" + (default ? " default #{default}" : '')
end
end
def with_schema_search_path(schema_search_path)
@connection.schema_search_path = schema_search_path
yield if block_given?
ensure
@connection.schema_search_path = "'$user', public"
end
def do_dump_index_tests_for_schema(this_schema_name, first_index_column_name, second_index_column_name)
with_schema_search_path(this_schema_name) do
indexes = @connection.indexes(TABLE_NAME).sort_by {|i| i.name}
assert_equal 2,indexes.size
do_dump_index_assertions_for_one_index(indexes[0], INDEX_A_NAME, first_index_column_name)
do_dump_index_assertions_for_one_index(indexes[1], INDEX_B_NAME, second_index_column_name)
end
end
def do_dump_index_assertions_for_one_index(this_index, this_index_name, this_index_column)
assert_equal TABLE_NAME, this_index.table
assert_equal 1, this_index.columns.size
assert_equal this_index_column, this_index.columns[0]
assert_equal this_index_name, this_index.name
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/connection_test_firebird.rb | provider/vendor/rails/activerecord/test/cases/connection_test_firebird.rb | require "cases/helper"
class FirebirdConnectionTest < ActiveRecord::TestCase
def test_charset_properly_set
fb_conn = ActiveRecord::Base.connection.instance_variable_get(:@connection)
assert_equal 'UTF8', fb_conn.database.character_set
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/associations_test.rb | provider/vendor/rails/activerecord/test/cases/associations_test.rb | require "cases/helper"
require 'models/developer'
require 'models/project'
require 'models/company'
require 'models/topic'
require 'models/reply'
require 'models/computer'
require 'models/customer'
require 'models/order'
require 'models/categorization'
require 'models/category'
require 'models/post'
require 'models/author'
require 'models/comment'
require 'models/tag'
require 'models/tagging'
require 'models/person'
require 'models/reader'
require 'models/parrot'
require 'models/pirate'
require 'models/treasure'
require 'models/price_estimate'
require 'models/club'
require 'models/member'
require 'models/membership'
require 'models/sponsor'
class AssociationsTest < ActiveRecord::TestCase
fixtures :accounts, :companies, :developers, :projects, :developers_projects,
:computers, :people, :readers
def test_include_with_order_works
assert_nothing_raised {Account.find(:first, :order => 'id', :include => :firm)}
assert_nothing_raised {Account.find(:first, :order => :id, :include => :firm)}
end
def test_bad_collection_keys
assert_raise(ArgumentError, 'ActiveRecord should have barked on bad collection keys') do
Class.new(ActiveRecord::Base).has_many(:wheels, :name => 'wheels')
end
end
def test_should_construct_new_finder_sql_after_create
person = Person.new :first_name => 'clark'
assert_equal [], person.readers.find(:all)
person.save!
reader = Reader.create! :person => person, :post => Post.new(:title => "foo", :body => "bar")
assert person.readers.find(reader.id)
end
def test_force_reload
firm = Firm.new("name" => "A New Firm, Inc")
firm.save
firm.clients.each {|c|} # forcing to load all clients
assert firm.clients.empty?, "New firm shouldn't have client objects"
assert_equal 0, firm.clients.size, "New firm should have 0 clients"
client = Client.new("name" => "TheClient.com", "firm_id" => firm.id)
client.save
assert firm.clients.empty?, "New firm should have cached no client objects"
assert_equal 0, firm.clients.size, "New firm should have cached 0 clients count"
assert !firm.clients(true).empty?, "New firm should have reloaded client objects"
assert_equal 1, firm.clients(true).size, "New firm should have reloaded clients count"
end
def test_storing_in_pstore
require "tmpdir"
store_filename = File.join(Dir.tmpdir, "ar-pstore-association-test")
File.delete(store_filename) if File.exist?(store_filename)
require "pstore"
apple = Firm.create("name" => "Apple")
natural = Client.new("name" => "Natural Company")
apple.clients << natural
db = PStore.new(store_filename)
db.transaction do
db["apple"] = apple
end
db = PStore.new(store_filename)
db.transaction do
assert_equal "Natural Company", db["apple"].clients.first.name
end
end
end
class AssociationProxyTest < ActiveRecord::TestCase
fixtures :authors, :posts, :categorizations, :categories, :developers, :projects, :developers_projects
def test_proxy_accessors
welcome = posts(:welcome)
assert_equal welcome, welcome.author.proxy_owner
assert_equal welcome.class.reflect_on_association(:author), welcome.author.proxy_reflection
welcome.author.class # force load target
assert_equal welcome.author, welcome.author.proxy_target
david = authors(:david)
assert_equal david, david.posts.proxy_owner
assert_equal david.class.reflect_on_association(:posts), david.posts.proxy_reflection
david.posts.class # force load target
assert_equal david.posts, david.posts.proxy_target
assert_equal david, david.posts_with_extension.testing_proxy_owner
assert_equal david.class.reflect_on_association(:posts_with_extension), david.posts_with_extension.testing_proxy_reflection
david.posts_with_extension.class # force load target
assert_equal david.posts_with_extension, david.posts_with_extension.testing_proxy_target
end
def test_push_does_not_load_target
david = authors(:david)
david.posts << (post = Post.new(:title => "New on Edge", :body => "More cool stuff!"))
assert !david.posts.loaded?
assert david.posts.include?(post)
end
def test_push_has_many_through_does_not_load_target
david = authors(:david)
david.categories << categories(:technology)
assert !david.categories.loaded?
assert david.categories.include?(categories(:technology))
end
def test_push_followed_by_save_does_not_load_target
david = authors(:david)
david.posts << (post = Post.new(:title => "New on Edge", :body => "More cool stuff!"))
assert !david.posts.loaded?
david.save
assert !david.posts.loaded?
assert david.posts.include?(post)
end
def test_push_does_not_lose_additions_to_new_record
josh = Author.new(:name => "Josh")
josh.posts << Post.new(:title => "New on Edge", :body => "More cool stuff!")
assert josh.posts.loaded?
assert_equal 1, josh.posts.size
end
def test_save_on_parent_does_not_load_target
david = developers(:david)
assert !david.projects.loaded?
david.update_attribute(:created_at, Time.now)
assert !david.projects.loaded?
end
def test_inspect_does_not_reload_a_not_yet_loaded_target
andreas = Developer.new :name => 'Andreas', :log => 'new developer added'
assert !andreas.audit_logs.loaded?
assert_match(/message: "new developer added"/, andreas.audit_logs.inspect)
end
def test_save_on_parent_saves_children
developer = Developer.create :name => "Bryan", :salary => 50_000
assert_equal 1, developer.reload.audit_logs.size
end
def test_create_via_association_with_block
post = authors(:david).posts.create(:title => "New on Edge") {|p| p.body = "More cool stuff!"}
assert_equal post.title, "New on Edge"
assert_equal post.body, "More cool stuff!"
end
def test_create_with_bang_via_association_with_block
post = authors(:david).posts.create!(:title => "New on Edge") {|p| p.body = "More cool stuff!"}
assert_equal post.title, "New on Edge"
assert_equal post.body, "More cool stuff!"
end
def test_failed_reload_returns_nil
p = setup_dangling_association
assert_nil p.author.reload
end
def test_failed_reset_returns_nil
p = setup_dangling_association
assert_nil p.author.reset
end
def test_reload_returns_assocition
david = developers(:david)
assert_nothing_raised do
assert_equal david.projects, david.projects.reload.reload
end
end
def setup_dangling_association
josh = Author.create(:name => "Josh")
p = Post.create(:title => "New on Edge", :body => "More cool stuff!", :author => josh)
josh.destroy
p
end
end
class OverridingAssociationsTest < ActiveRecord::TestCase
class Person < ActiveRecord::Base; end
class DifferentPerson < ActiveRecord::Base; end
class PeopleList < ActiveRecord::Base
has_and_belongs_to_many :has_and_belongs_to_many, :before_add => :enlist
has_many :has_many, :before_add => :enlist
belongs_to :belongs_to
has_one :has_one
end
class DifferentPeopleList < PeopleList
# Different association with the same name, callbacks should be omitted here.
has_and_belongs_to_many :has_and_belongs_to_many, :class_name => 'DifferentPerson'
has_many :has_many, :class_name => 'DifferentPerson'
belongs_to :belongs_to, :class_name => 'DifferentPerson'
has_one :has_one, :class_name => 'DifferentPerson'
end
def test_habtm_association_redefinition_callbacks_should_differ_and_not_inherited
# redeclared association on AR descendant should not inherit callbacks from superclass
callbacks = PeopleList.read_inheritable_attribute(:before_add_for_has_and_belongs_to_many)
assert_equal([:enlist], callbacks)
callbacks = DifferentPeopleList.read_inheritable_attribute(:before_add_for_has_and_belongs_to_many)
assert_equal([], callbacks)
end
def test_has_many_association_redefinition_callbacks_should_differ_and_not_inherited
# redeclared association on AR descendant should not inherit callbacks from superclass
callbacks = PeopleList.read_inheritable_attribute(:before_add_for_has_many)
assert_equal([:enlist], callbacks)
callbacks = DifferentPeopleList.read_inheritable_attribute(:before_add_for_has_many)
assert_equal([], callbacks)
end
def test_habtm_association_redefinition_reflections_should_differ_and_not_inherited
assert_not_equal(
PeopleList.reflect_on_association(:has_and_belongs_to_many),
DifferentPeopleList.reflect_on_association(:has_and_belongs_to_many)
)
end
def test_has_many_association_redefinition_reflections_should_differ_and_not_inherited
assert_not_equal(
PeopleList.reflect_on_association(:has_many),
DifferentPeopleList.reflect_on_association(:has_many)
)
end
def test_belongs_to_association_redefinition_reflections_should_differ_and_not_inherited
assert_not_equal(
PeopleList.reflect_on_association(:belongs_to),
DifferentPeopleList.reflect_on_association(:belongs_to)
)
end
def test_has_one_association_redefinition_reflections_should_differ_and_not_inherited
assert_not_equal(
PeopleList.reflect_on_association(:has_one),
DifferentPeopleList.reflect_on_association(:has_one)
)
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/binary_test.rb | provider/vendor/rails/activerecord/test/cases/binary_test.rb | require "cases/helper"
# Without using prepared statements, it makes no sense to test
# BLOB data with DB2 or Firebird, because the length of a statement
# is limited to 32KB.
unless current_adapter?(:SybaseAdapter, :DB2Adapter, :FirebirdAdapter)
require 'models/binary'
class BinaryTest < ActiveRecord::TestCase
FIXTURES = %w(flowers.jpg example.log)
def test_load_save
Binary.delete_all
FIXTURES.each do |filename|
data = File.read(ASSETS_ROOT + "/#{filename}")
data.force_encoding('ASCII-8BIT') if data.respond_to?(:force_encoding)
data.freeze
bin = Binary.new(:data => data)
assert_equal data, bin.data, 'Newly assigned data differs from original'
bin.save!
assert_equal data, bin.data, 'Data differs from original after save'
assert_equal data, bin.reload.data, 'Reloaded data differs from original'
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/reflection_test.rb | provider/vendor/rails/activerecord/test/cases/reflection_test.rb | require "cases/helper"
require 'models/topic'
require 'models/customer'
require 'models/company'
require 'models/company_in_module'
require 'models/subscriber'
require 'models/pirate'
class ReflectionTest < ActiveRecord::TestCase
fixtures :topics, :customers, :companies, :subscribers
def setup
@first = Topic.find(1)
end
def test_column_null_not_null
subscriber = Subscriber.find(:first)
assert subscriber.column_for_attribute("name").null
assert !subscriber.column_for_attribute("nick").null
end
def test_read_attribute_names
assert_equal(
%w( id title author_name author_email_address bonus_time written_on last_read content approved replies_count parent_id parent_title type ).sort,
@first.attribute_names
)
end
def test_columns
assert_equal 13, Topic.columns.length
end
def test_columns_are_returned_in_the_order_they_were_declared
column_names = Topic.columns.map { |column| column.name }
assert_equal %w(id title author_name author_email_address written_on bonus_time last_read content approved replies_count parent_id parent_title type), column_names
end
def test_content_columns
content_columns = Topic.content_columns
content_column_names = content_columns.map {|column| column.name}
assert_equal 9, content_columns.length
assert_equal %w(title author_name author_email_address written_on bonus_time last_read content approved parent_title).sort, content_column_names.sort
end
def test_column_string_type_and_limit
assert_equal :string, @first.column_for_attribute("title").type
assert_equal 255, @first.column_for_attribute("title").limit
end
def test_column_null_not_null
subscriber = Subscriber.find(:first)
assert subscriber.column_for_attribute("name").null
assert !subscriber.column_for_attribute("nick").null
end
def test_human_name_for_column
assert_equal "Author name", @first.column_for_attribute("author_name").human_name
end
def test_integer_columns
assert_equal :integer, @first.column_for_attribute("id").type
end
def test_reflection_klass_for_nested_class_name
reflection = ActiveRecord::Reflection::MacroReflection.new(nil, nil, { :class_name => 'MyApplication::Business::Company' }, nil)
assert_nothing_raised do
assert_equal MyApplication::Business::Company, reflection.klass
end
end
def test_aggregation_reflection
reflection_for_address = ActiveRecord::Reflection::AggregateReflection.new(
:composed_of, :address, { :mapping => [ %w(address_street street), %w(address_city city), %w(address_country country) ] }, Customer
)
reflection_for_balance = ActiveRecord::Reflection::AggregateReflection.new(
:composed_of, :balance, { :class_name => "Money", :mapping => %w(balance amount) }, Customer
)
reflection_for_gps_location = ActiveRecord::Reflection::AggregateReflection.new(
:composed_of, :gps_location, { }, Customer
)
assert Customer.reflect_on_all_aggregations.include?(reflection_for_gps_location)
assert Customer.reflect_on_all_aggregations.include?(reflection_for_balance)
assert Customer.reflect_on_all_aggregations.include?(reflection_for_address)
assert_equal reflection_for_address, Customer.reflect_on_aggregation(:address)
assert_equal Address, Customer.reflect_on_aggregation(:address).klass
assert_equal Money, Customer.reflect_on_aggregation(:balance).klass
end
def test_reflect_on_all_autosave_associations
expected = Pirate.reflect_on_all_associations.select { |r| r.options[:autosave] }
received = Pirate.reflect_on_all_autosave_associations
assert !received.empty?
assert_not_equal Pirate.reflect_on_all_associations.length, received.length
assert_equal expected, received
end
def test_has_many_reflection
reflection_for_clients = ActiveRecord::Reflection::AssociationReflection.new(:has_many, :clients, { :order => "id", :dependent => :destroy }, Firm)
assert_equal reflection_for_clients, Firm.reflect_on_association(:clients)
assert_equal Client, Firm.reflect_on_association(:clients).klass
assert_equal 'companies', Firm.reflect_on_association(:clients).table_name
assert_equal Client, Firm.reflect_on_association(:clients_of_firm).klass
assert_equal 'companies', Firm.reflect_on_association(:clients_of_firm).table_name
end
def test_has_one_reflection
reflection_for_account = ActiveRecord::Reflection::AssociationReflection.new(:has_one, :account, { :foreign_key => "firm_id", :dependent => :destroy }, Firm)
assert_equal reflection_for_account, Firm.reflect_on_association(:account)
assert_equal Account, Firm.reflect_on_association(:account).klass
assert_equal 'accounts', Firm.reflect_on_association(:account).table_name
end
def test_belongs_to_inferred_foreign_key_from_assoc_name
Company.belongs_to :foo
assert_equal "foo_id", Company.reflect_on_association(:foo).primary_key_name
Company.belongs_to :bar, :class_name => "Xyzzy"
assert_equal "bar_id", Company.reflect_on_association(:bar).primary_key_name
Company.belongs_to :baz, :class_name => "Xyzzy", :foreign_key => "xyzzy_id"
assert_equal "xyzzy_id", Company.reflect_on_association(:baz).primary_key_name
end
def test_association_reflection_in_modules
assert_reflection MyApplication::Business::Firm,
:clients_of_firm,
:klass => MyApplication::Business::Client,
:class_name => 'Client',
:table_name => 'companies'
assert_reflection MyApplication::Billing::Account,
:firm,
:klass => MyApplication::Business::Firm,
:class_name => 'MyApplication::Business::Firm',
:table_name => 'companies'
assert_reflection MyApplication::Billing::Account,
:qualified_billing_firm,
:klass => MyApplication::Billing::Firm,
:class_name => 'MyApplication::Billing::Firm',
:table_name => 'companies'
assert_reflection MyApplication::Billing::Account,
:unqualified_billing_firm,
:klass => MyApplication::Billing::Firm,
:class_name => 'Firm',
:table_name => 'companies'
assert_reflection MyApplication::Billing::Account,
:nested_qualified_billing_firm,
:klass => MyApplication::Billing::Nested::Firm,
:class_name => 'MyApplication::Billing::Nested::Firm',
:table_name => 'companies'
assert_reflection MyApplication::Billing::Account,
:nested_unqualified_billing_firm,
:klass => MyApplication::Billing::Nested::Firm,
:class_name => 'Nested::Firm',
:table_name => 'companies'
end
def test_reflection_of_all_associations
# FIXME these assertions bust a lot
assert_equal 30, Firm.reflect_on_all_associations.size
assert_equal 23, Firm.reflect_on_all_associations(:has_many).size
assert_equal 7, Firm.reflect_on_all_associations(:has_one).size
assert_equal 0, Firm.reflect_on_all_associations(:belongs_to).size
end
def test_reflection_should_not_raise_error_when_compared_to_other_object
assert_nothing_raised { Firm.reflections[:clients] == Object.new }
end
def test_has_many_through_reflection
assert_kind_of ActiveRecord::Reflection::ThroughReflection, Subscriber.reflect_on_association(:books)
end
private
def assert_reflection(klass, association, options)
assert reflection = klass.reflect_on_association(association)
options.each do |method, value|
assert_equal(value, reflection.send(method))
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/schema_dumper_test.rb | provider/vendor/rails/activerecord/test/cases/schema_dumper_test.rb | require "cases/helper"
require 'stringio'
class SchemaDumperTest < ActiveRecord::TestCase
def standard_dump
stream = StringIO.new
ActiveRecord::SchemaDumper.ignore_tables = []
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream)
stream.string
end
def test_schema_dump
output = standard_dump
assert_match %r{create_table "accounts"}, output
assert_match %r{create_table "authors"}, output
assert_no_match %r{create_table "schema_migrations"}, output
end
def test_schema_dump_excludes_sqlite_sequence
output = standard_dump
assert_no_match %r{create_table "sqlite_sequence"}, output
end
def test_schema_dump_includes_camelcase_table_name
output = standard_dump
assert_match %r{create_table "CamelCase"}, output
end
def assert_line_up(lines, pattern, required = false)
return assert(true) if lines.empty?
matches = lines.map { |line| line.match(pattern) }
assert matches.all? if required
matches.compact!
return assert(true) if matches.empty?
assert_equal 1, matches.map{ |match| match.offset(0).first }.uniq.length
end
def column_definition_lines(output = standard_dump)
output.scan(/^( *)create_table.*?\n(.*?)^\1end/m).map{ |m| m.last.split(/\n/) }
end
def test_types_line_up
column_definition_lines.each do |column_set|
next if column_set.empty?
lengths = column_set.map do |column|
if match = column.match(/t\.(?:integer|decimal|float|datetime|timestamp|time|date|text|binary|string|boolean)\s+"/)
match[0].length
end
end
assert_equal 1, lengths.uniq.length
end
end
def test_arguments_line_up
column_definition_lines.each do |column_set|
assert_line_up(column_set, /:default => /)
assert_line_up(column_set, /:limit => /)
assert_line_up(column_set, /:null => /)
end
end
def test_no_dump_errors
output = standard_dump
assert_no_match %r{\# Could not dump table}, output
end
def test_schema_dump_includes_not_null_columns
stream = StringIO.new
ActiveRecord::SchemaDumper.ignore_tables = [/^[^r]/]
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream)
output = stream.string
assert_match %r{:null => false}, output
end
def test_schema_dump_includes_limit_constraint_for_integer_columns
stream = StringIO.new
ActiveRecord::SchemaDumper.ignore_tables = [/^(?!integer_limits)/]
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream)
output = stream.string
if current_adapter?(:PostgreSQLAdapter)
assert_match %r{c_int_1.*:limit => 2}, output
assert_match %r{c_int_2.*:limit => 2}, output
# int 3 is 4 bytes in postgresql
assert_match %r{c_int_3.*}, output
assert_no_match %r{c_int_3.*:limit}, output
assert_match %r{c_int_4.*}, output
assert_no_match %r{c_int_4.*:limit}, output
elsif current_adapter?(:MysqlAdapter)
assert_match %r{c_int_1.*:limit => 1}, output
assert_match %r{c_int_2.*:limit => 2}, output
assert_match %r{c_int_3.*:limit => 3}, output
assert_match %r{c_int_4.*}, output
assert_no_match %r{c_int_4.*:limit}, output
elsif current_adapter?(:SQLiteAdapter)
assert_match %r{c_int_1.*:limit => 1}, output
assert_match %r{c_int_2.*:limit => 2}, output
assert_match %r{c_int_3.*:limit => 3}, output
assert_match %r{c_int_4.*:limit => 4}, output
end
assert_match %r{c_int_without_limit.*}, output
assert_no_match %r{c_int_without_limit.*:limit}, output
if current_adapter?(:SQLiteAdapter)
assert_match %r{c_int_5.*:limit => 5}, output
assert_match %r{c_int_6.*:limit => 6}, output
assert_match %r{c_int_7.*:limit => 7}, output
assert_match %r{c_int_8.*:limit => 8}, output
else
assert_match %r{c_int_5.*:limit => 8}, output
assert_match %r{c_int_6.*:limit => 8}, output
assert_match %r{c_int_7.*:limit => 8}, output
assert_match %r{c_int_8.*:limit => 8}, output
end
end
def test_schema_dump_with_string_ignored_table
stream = StringIO.new
ActiveRecord::SchemaDumper.ignore_tables = ['accounts']
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream)
output = stream.string
assert_no_match %r{create_table "accounts"}, output
assert_match %r{create_table "authors"}, output
assert_no_match %r{create_table "schema_migrations"}, output
end
def test_schema_dump_with_regexp_ignored_table
stream = StringIO.new
ActiveRecord::SchemaDumper.ignore_tables = [/^account/]
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream)
output = stream.string
assert_no_match %r{create_table "accounts"}, output
assert_match %r{create_table "authors"}, output
assert_no_match %r{create_table "schema_migrations"}, output
end
def test_schema_dump_illegal_ignored_table_value
stream = StringIO.new
ActiveRecord::SchemaDumper.ignore_tables = [5]
assert_raise(StandardError) do
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream)
end
end
def test_schema_dumps_index_columns_in_right_order
index_definition = standard_dump.split(/\n/).grep(/add_index.*companies/).first.strip
assert_equal 'add_index "companies", ["firm_id", "type", "rating", "ruby_type"], :name => "company_index"', index_definition
end
def test_schema_dump_should_honor_nonstandard_primary_keys
output = standard_dump
match = output.match(%r{create_table "movies"(.*)do})
assert_not_nil(match, "nonstandardpk table not found")
assert_match %r(:primary_key => "movieid"), match[1], "non-standard primary key not preserved"
end
if current_adapter?(:MysqlAdapter)
def test_schema_dump_should_not_add_default_value_for_mysql_text_field
output = standard_dump
assert_match %r{t.text\s+"body",\s+:null => false$}, output
end
def test_schema_dump_includes_length_for_mysql_blob_and_text_fields
output = standard_dump
assert_match %r{t.binary\s+"tiny_blob",\s+:limit => 255$}, output
assert_match %r{t.binary\s+"normal_blob"$}, output
assert_match %r{t.binary\s+"medium_blob",\s+:limit => 16777215$}, output
assert_match %r{t.binary\s+"long_blob",\s+:limit => 2147483647$}, output
assert_match %r{t.text\s+"tiny_text",\s+:limit => 255$}, output
assert_match %r{t.text\s+"normal_text"$}, output
assert_match %r{t.text\s+"medium_text",\s+:limit => 16777215$}, output
assert_match %r{t.text\s+"long_text",\s+:limit => 2147483647$}, output
end
end
def test_schema_dump_includes_decimal_options
stream = StringIO.new
ActiveRecord::SchemaDumper.ignore_tables = [/^[^n]/]
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream)
output = stream.string
assert_match %r{:precision => 3,[[:space:]]+:scale => 2,[[:space:]]+:default => 2.78}, output
end
if current_adapter?(:PostgreSQLAdapter)
def test_schema_dump_includes_xml_shorthand_definition
output = standard_dump
if %r{create_table "postgresql_xml_data_type"} =~ output
assert_match %r{t.xml "data"}, output
end
end
end
def test_schema_dump_keeps_id_column_when_id_is_false_and_id_column_added
output = standard_dump
match = output.match(%r{create_table "goofy_string_id"(.*)do.*\n(.*)\n})
assert_not_nil(match, "goofy_string_id table not found")
assert_match %r(:id => false), match[1], "no table id not preserved"
assert_match %r{t.string[[:space:]]+"id",[[:space:]]+:null => false$}, match[2], "non-primary key id column not preserved"
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/aaa_create_tables_test.rb | provider/vendor/rails/activerecord/test/cases/aaa_create_tables_test.rb | # The filename begins with "aaa" to ensure this is the first test.
require "cases/helper"
class AAACreateTablesTest < ActiveRecord::TestCase
self.use_transactional_fixtures = false
def test_load_schema
eval(File.read(SCHEMA_ROOT + "/schema.rb"))
if File.exists?(adapter_specific_schema_file)
eval(File.read(adapter_specific_schema_file))
end
assert true
end
def test_drop_and_create_courses_table
eval(File.read(SCHEMA_ROOT + "/schema2.rb"))
assert true
end
private
def adapter_specific_schema_file
SCHEMA_ROOT + '/' + ActiveRecord::Base.connection.adapter_name.downcase + '_specific_schema.rb'
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/xml_serialization_test.rb | provider/vendor/rails/activerecord/test/cases/xml_serialization_test.rb | require "cases/helper"
require 'models/contact'
require 'models/post'
require 'models/author'
require 'models/tagging'
require 'models/comment'
require 'models/company_in_module'
class XmlSerializationTest < ActiveRecord::TestCase
def test_should_serialize_default_root
@xml = Contact.new.to_xml
assert_match %r{^<contact>}, @xml
assert_match %r{</contact>$}, @xml
end
def test_should_serialize_default_root_with_namespace
@xml = Contact.new.to_xml :namespace=>"http://xml.rubyonrails.org/contact"
assert_match %r{^<contact xmlns="http://xml.rubyonrails.org/contact">}, @xml
assert_match %r{</contact>$}, @xml
end
def test_should_serialize_custom_root
@xml = Contact.new.to_xml :root => 'xml_contact'
assert_match %r{^<xml-contact>}, @xml
assert_match %r{</xml-contact>$}, @xml
end
def test_should_allow_undasherized_tags
@xml = Contact.new.to_xml :root => 'xml_contact', :dasherize => false
assert_match %r{^<xml_contact>}, @xml
assert_match %r{</xml_contact>$}, @xml
assert_match %r{<created_at}, @xml
end
def test_should_allow_camelized_tags
@xml = Contact.new.to_xml :root => 'xml_contact', :camelize => true
assert_match %r{^<XmlContact>}, @xml
assert_match %r{</XmlContact>$}, @xml
assert_match %r{<CreatedAt}, @xml
end
def test_should_allow_skipped_types
@xml = Contact.new(:age => 25).to_xml :skip_types => true
assert %r{<age>25</age>}.match(@xml)
end
def test_should_include_yielded_additions
@xml = Contact.new.to_xml do |xml|
xml.creator "David"
end
assert_match %r{<creator>David</creator>}, @xml
end
end
class DefaultXmlSerializationTest < ActiveRecord::TestCase
def setup
@xml = Contact.new(:name => 'aaron stack', :age => 25, :avatar => 'binarydata', :created_at => Time.utc(2006, 8, 1), :awesome => false, :preferences => { :gem => 'ruby' }).to_xml
end
def test_should_serialize_string
assert_match %r{<name>aaron stack</name>}, @xml
end
def test_should_serialize_integer
assert_match %r{<age type="integer">25</age>}, @xml
end
def test_should_serialize_binary
assert_match %r{YmluYXJ5ZGF0YQ==\n</avatar>}, @xml
assert_match %r{<avatar(.*)(type="binary")}, @xml
assert_match %r{<avatar(.*)(encoding="base64")}, @xml
end
def test_should_serialize_datetime
assert_match %r{<created-at type=\"datetime\">2006-08-01T00:00:00Z</created-at>}, @xml
end
def test_should_serialize_boolean
assert_match %r{<awesome type=\"boolean\">false</awesome>}, @xml
end
def test_should_serialize_yaml
assert_match %r{<preferences type=\"yaml\">--- \n:gem: ruby\n</preferences>}, @xml
end
end
class NilXmlSerializationTest < ActiveRecord::TestCase
def setup
@xml = Contact.new.to_xml(:root => 'xml_contact')
end
def test_should_serialize_string
assert_match %r{<name nil="true"></name>}, @xml
end
def test_should_serialize_integer
assert %r{<age (.*)></age>}.match(@xml)
attributes = $1
assert_match %r{nil="true"}, attributes
assert_match %r{type="integer"}, attributes
end
def test_should_serialize_binary
assert %r{<avatar (.*)></avatar>}.match(@xml)
attributes = $1
assert_match %r{type="binary"}, attributes
assert_match %r{encoding="base64"}, attributes
assert_match %r{nil="true"}, attributes
end
def test_should_serialize_datetime
assert %r{<created-at (.*)></created-at>}.match(@xml)
attributes = $1
assert_match %r{nil="true"}, attributes
assert_match %r{type="datetime"}, attributes
end
def test_should_serialize_boolean
assert %r{<awesome (.*)></awesome>}.match(@xml)
attributes = $1
assert_match %r{type="boolean"}, attributes
assert_match %r{nil="true"}, attributes
end
def test_should_serialize_yaml
assert %r{<preferences(.*)></preferences>}.match(@xml)
attributes = $1
assert_match %r{type="yaml"}, attributes
assert_match %r{nil="true"}, attributes
end
end
class DatabaseConnectedXmlModuleSerializationTest < ActiveRecord::TestCase
fixtures :projects, :developers, :developers_projects
def test_module
project = MyApplication::Business::Project.find :first
xml = project.to_xml
assert_match %r{<my-application-business-project>}, xml
assert_match %r{</my-application-business-project>}, xml
end
def test_module_with_include
project = MyApplication::Business::Project.find :first
xml = project.to_xml :include => :developers
assert_match %r{<developer type="MyApplication::Business::Developer">}, xml
assert_match %r{</developer>}, xml
end
end
class DatabaseConnectedXmlSerializationTest < ActiveRecord::TestCase
fixtures :authors, :posts
# to_xml used to mess with the hash the user provided which
# caused the builder to be reused. This meant the document kept
# getting appended to.
def test_passing_hash_shouldnt_reuse_builder
options = {:include=>:posts}
david = authors(:david)
first_xml_size = david.to_xml(options).size
second_xml_size = david.to_xml(options).size
assert_equal first_xml_size, second_xml_size
end
def test_include_uses_association_name
xml = authors(:david).to_xml :include=>:hello_posts, :indent => 0
assert_match %r{<hello-posts type="array">}, xml
assert_match %r{<hello-post type="Post">}, xml
assert_match %r{<hello-post type="StiPost">}, xml
end
def test_included_associations_should_skip_types
xml = authors(:david).to_xml :include=>:hello_posts, :indent => 0, :skip_types => true
assert_match %r{<hello-posts>}, xml
assert_match %r{<hello-post>}, xml
assert_match %r{<hello-post>}, xml
end
def test_methods_are_called_on_object
xml = authors(:david).to_xml :methods => :label, :indent => 0
assert_match %r{<label>.*</label>}, xml
end
def test_should_not_call_methods_on_associations_that_dont_respond
xml = authors(:david).to_xml :include=>:hello_posts, :methods => :label, :indent => 2
assert !authors(:david).hello_posts.first.respond_to?(:label)
assert_match %r{^ <label>.*</label>}, xml
assert_no_match %r{^ <label>}, xml
end
def test_procs_are_called_on_object
proc = Proc.new { |options| options[:builder].tag!('nationality', 'Danish') }
xml = authors(:david).to_xml(:procs => [ proc ])
assert_match %r{<nationality>Danish</nationality>}, xml
end
def test_top_level_procs_arent_applied_to_associations
author_proc = Proc.new { |options| options[:builder].tag!('nationality', 'Danish') }
xml = authors(:david).to_xml(:procs => [ author_proc ], :include => :posts, :indent => 2)
assert_match %r{^ <nationality>Danish</nationality>}, xml
assert_no_match %r{^ {6}<nationality>Danish</nationality>}, xml
end
def test_procs_on_included_associations_are_called
posts_proc = Proc.new { |options| options[:builder].tag!('copyright', 'DHH') }
xml = authors(:david).to_xml(
:indent => 2,
:include => {
:posts => { :procs => [ posts_proc ] }
}
)
assert_no_match %r{^ <copyright>DHH</copyright>}, xml
assert_match %r{^ {6}<copyright>DHH</copyright>}, xml
end
def test_should_include_empty_has_many_as_empty_array
authors(:david).posts.delete_all
xml = authors(:david).to_xml :include=>:posts, :indent => 2
assert_equal [], Hash.from_xml(xml)['author']['posts']
assert_match %r{^ <posts type="array"/>}, xml
end
def test_should_has_many_array_elements_should_include_type_when_different_from_guessed_value
xml = authors(:david).to_xml :include=>:posts_with_comments, :indent => 2
assert Hash.from_xml(xml)
assert_match %r{^ <posts-with-comments type="array">}, xml
assert_match %r{^ <posts-with-comment type="Post">}, xml
assert_match %r{^ <posts-with-comment type="StiPost">}, xml
types = Hash.from_xml(xml)['author']['posts_with_comments'].collect {|t| t['type'] }
assert types.include?('SpecialPost')
assert types.include?('Post')
assert types.include?('StiPost')
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/pooled_connections_test.rb | provider/vendor/rails/activerecord/test/cases/pooled_connections_test.rb | require "cases/helper"
class PooledConnectionsTest < ActiveRecord::TestCase
def setup
super
@connection = ActiveRecord::Base.remove_connection
end
def teardown
ActiveRecord::Base.clear_all_connections!
ActiveRecord::Base.establish_connection(@connection)
super
end
def checkout_connections
ActiveRecord::Base.establish_connection(@connection.merge({:pool => 2, :wait_timeout => 0.3}))
@connections = []
@timed_out = 0
4.times do
Thread.new do
begin
@connections << ActiveRecord::Base.connection_pool.checkout
rescue ActiveRecord::ConnectionTimeoutError
@timed_out += 1
end
end.join
end
end
# Will deadlock due to lack of Monitor timeouts in 1.9
if RUBY_VERSION < '1.9'
def test_pooled_connection_checkout
checkout_connections
assert_equal @connections.length, 2
assert_equal @timed_out, 2
end
end
def checkout_checkin_connections(pool_size, threads)
ActiveRecord::Base.establish_connection(@connection.merge({:pool => pool_size, :wait_timeout => 0.5}))
@connection_count = 0
@timed_out = 0
threads.times do
Thread.new do
begin
conn = ActiveRecord::Base.connection_pool.checkout
sleep 0.1
ActiveRecord::Base.connection_pool.checkin conn
@connection_count += 1
rescue ActiveRecord::ConnectionTimeoutError
@timed_out += 1
end
end.join
end
end
def test_pooled_connection_checkin_one
checkout_checkin_connections 1, 2
assert_equal 2, @connection_count
assert_equal 0, @timed_out
end
def test_pooled_connection_checkin_two
checkout_checkin_connections 2, 3
assert_equal 3, @connection_count
assert_equal 0, @timed_out
end
def test_pooled_connection_checkout_existing_first
ActiveRecord::Base.establish_connection(@connection.merge({:pool => 1}))
conn_pool = ActiveRecord::Base.connection_pool
conn = conn_pool.checkout
conn_pool.checkin(conn)
conn = conn_pool.checkout
assert ActiveRecord::ConnectionAdapters::AbstractAdapter === conn
conn_pool.checkin(conn)
end
def test_not_connected_defined_connection_returns_false
ActiveRecord::Base.establish_connection(@connection)
assert ! ActiveRecord::Base.connected?
end
def test_undefined_connection_returns_false
old_handler = ActiveRecord::Base.connection_handler
ActiveRecord::Base.connection_handler = ActiveRecord::ConnectionAdapters::ConnectionHandler.new
assert_equal false, ActiveRecord::Base.connected?
ensure
ActiveRecord::Base.connection_handler = old_handler
end
end unless %w(FrontBase).include? ActiveRecord::Base.connection.adapter_name
class AllowConcurrencyDeprecatedTest < ActiveRecord::TestCase
def test_allow_concurrency_is_deprecated
assert_deprecated('ActiveRecord::Base.allow_concurrency') do
ActiveRecord::Base.allow_concurrency
end
assert_deprecated('ActiveRecord::Base.allow_concurrency=') do
ActiveRecord::Base.allow_concurrency = true
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/dirty_test.rb | provider/vendor/rails/activerecord/test/cases/dirty_test.rb | require 'cases/helper'
require 'models/topic' # For booleans
require 'models/pirate' # For timestamps
require 'models/parrot'
require 'models/person' # For optimistic locking
class Pirate # Just reopening it, not defining it
attr_accessor :detected_changes_in_after_update # Boolean for if changes are detected
attr_accessor :changes_detected_in_after_update # Actual changes
after_update :check_changes
private
# after_save/update in sweepers, observers, and the model itself
# can end up checking dirty status and acting on the results
def check_changes
if self.changed?
self.detected_changes_in_after_update = true
self.changes_detected_in_after_update = self.changes
end
end
end
class NumericData < ActiveRecord::Base
self.table_name = 'numeric_data'
end
class DirtyTest < ActiveRecord::TestCase
def test_attribute_changes
# New record - no changes.
pirate = Pirate.new
assert !pirate.catchphrase_changed?
assert_nil pirate.catchphrase_change
# Change catchphrase.
pirate.catchphrase = 'arrr'
assert pirate.catchphrase_changed?
assert_nil pirate.catchphrase_was
assert_equal [nil, 'arrr'], pirate.catchphrase_change
# Saved - no changes.
pirate.save!
assert !pirate.catchphrase_changed?
assert_nil pirate.catchphrase_change
# Same value - no changes.
pirate.catchphrase = 'arrr'
assert !pirate.catchphrase_changed?
assert_nil pirate.catchphrase_change
end
def test_aliased_attribute_changes
# the actual attribute here is name, title is an
# alias setup via alias_attribute
parrot = Parrot.new
assert !parrot.title_changed?
assert_nil parrot.title_change
parrot.name = 'Sam'
assert parrot.title_changed?
assert_nil parrot.title_was
assert_equal parrot.name_change, parrot.title_change
end
def test_nullable_number_not_marked_as_changed_if_new_value_is_blank
pirate = Pirate.new
["", nil].each do |value|
pirate.parrot_id = value
assert !pirate.parrot_id_changed?
assert_nil pirate.parrot_id_change
end
end
def test_nullable_decimal_not_marked_as_changed_if_new_value_is_blank
numeric_data = NumericData.new
["", nil].each do |value|
numeric_data.bank_balance = value
assert !numeric_data.bank_balance_changed?
assert_nil numeric_data.bank_balance_change
end
end
def test_nullable_float_not_marked_as_changed_if_new_value_is_blank
numeric_data = NumericData.new
["", nil].each do |value|
numeric_data.temperature = value
assert !numeric_data.temperature_changed?
assert_nil numeric_data.temperature_change
end
end
def test_nullable_integer_zero_to_string_zero_not_marked_as_changed
pirate = Pirate.new
pirate.parrot_id = 0
pirate.catchphrase = 'arrr'
assert pirate.save!
assert !pirate.changed?
pirate.parrot_id = '0'
assert !pirate.changed?
end
def test_zero_to_blank_marked_as_changed
pirate = Pirate.new
pirate.catchphrase = "Yarrrr, me hearties"
pirate.parrot_id = 1
pirate.save
# check the change from 1 to ''
pirate = Pirate.find_by_catchphrase("Yarrrr, me hearties")
pirate.parrot_id = ''
assert pirate.parrot_id_changed?
assert_equal([1, nil], pirate.parrot_id_change)
pirate.save
# check the change from nil to 0
pirate = Pirate.find_by_catchphrase("Yarrrr, me hearties")
pirate.parrot_id = 0
assert pirate.parrot_id_changed?
assert_equal([nil, 0], pirate.parrot_id_change)
pirate.save
# check the change from 0 to ''
pirate = Pirate.find_by_catchphrase("Yarrrr, me hearties")
pirate.parrot_id = ''
assert pirate.parrot_id_changed?
assert_equal([0, nil], pirate.parrot_id_change)
end
def test_object_should_be_changed_if_any_attribute_is_changed
pirate = Pirate.new
assert !pirate.changed?
assert_equal [], pirate.changed
assert_equal Hash.new, pirate.changes
pirate.catchphrase = 'arrr'
assert pirate.changed?
assert_nil pirate.catchphrase_was
assert_equal %w(catchphrase), pirate.changed
assert_equal({'catchphrase' => [nil, 'arrr']}, pirate.changes)
pirate.save
assert !pirate.changed?
assert_equal [], pirate.changed
assert_equal Hash.new, pirate.changes
end
def test_attribute_will_change!
pirate = Pirate.create!(:catchphrase => 'arr')
pirate.catchphrase << ' matey'
assert !pirate.catchphrase_changed?
assert pirate.catchphrase_will_change!
assert pirate.catchphrase_changed?
assert_equal ['arr matey', 'arr matey'], pirate.catchphrase_change
pirate.catchphrase << '!'
assert pirate.catchphrase_changed?
assert_equal ['arr matey', 'arr matey!'], pirate.catchphrase_change
end
def test_association_assignment_changes_foreign_key
pirate = Pirate.create!(:catchphrase => 'jarl')
pirate.parrot = Parrot.create!(:name => 'Lorre')
assert pirate.changed?
assert_equal %w(parrot_id), pirate.changed
end
def test_attribute_should_be_compared_with_type_cast
topic = Topic.new
assert topic.approved?
assert !topic.approved_changed?
# Coming from web form.
params = {:topic => {:approved => 1}}
# In the controller.
topic.attributes = params[:topic]
assert topic.approved?
assert !topic.approved_changed?
end
def test_partial_update
pirate = Pirate.new(:catchphrase => 'foo')
old_updated_on = 1.hour.ago.beginning_of_day
with_partial_updates Pirate, false do
assert_queries(2) { 2.times { pirate.save! } }
Pirate.update_all({ :updated_on => old_updated_on }, :id => pirate.id)
end
with_partial_updates Pirate, true do
assert_queries(0) { 2.times { pirate.save! } }
assert_equal old_updated_on, pirate.reload.updated_on
assert_queries(1) { pirate.catchphrase = 'bar'; pirate.save! }
assert_not_equal old_updated_on, pirate.reload.updated_on
end
end
def test_partial_update_with_optimistic_locking
person = Person.new(:first_name => 'foo')
old_lock_version = 1
with_partial_updates Person, false do
assert_queries(2) { 2.times { person.save! } }
Person.update_all({ :first_name => 'baz' }, :id => person.id)
end
with_partial_updates Person, true do
assert_queries(0) { 2.times { person.save! } }
assert_equal old_lock_version, person.reload.lock_version
assert_queries(1) { person.first_name = 'bar'; person.save! }
assert_not_equal old_lock_version, person.reload.lock_version
end
end
def test_changed_attributes_should_be_preserved_if_save_failure
pirate = Pirate.new
pirate.parrot_id = 1
assert !pirate.save
check_pirate_after_save_failure(pirate)
pirate = Pirate.new
pirate.parrot_id = 1
assert_raise(ActiveRecord::RecordInvalid) { pirate.save! }
check_pirate_after_save_failure(pirate)
end
def test_reload_should_clear_changed_attributes
pirate = Pirate.create!(:catchphrase => "shiver me timbers")
pirate.catchphrase = "*hic*"
assert pirate.changed?
pirate.reload
assert !pirate.changed?
end
def test_reverted_changes_are_not_dirty
phrase = "shiver me timbers"
pirate = Pirate.create!(:catchphrase => phrase)
pirate.catchphrase = "*hic*"
assert pirate.changed?
pirate.catchphrase = phrase
assert !pirate.changed?
end
def test_reverted_changes_are_not_dirty_after_multiple_changes
phrase = "shiver me timbers"
pirate = Pirate.create!(:catchphrase => phrase)
10.times do |i|
pirate.catchphrase = "*hic*" * i
assert pirate.changed?
end
assert pirate.changed?
pirate.catchphrase = phrase
assert !pirate.changed?
end
def test_reverted_changes_are_not_dirty_going_from_nil_to_value_and_back
pirate = Pirate.create!(:catchphrase => "Yar!")
pirate.parrot_id = 1
assert pirate.changed?
assert pirate.parrot_id_changed?
assert !pirate.catchphrase_changed?
pirate.parrot_id = nil
assert !pirate.changed?
assert !pirate.parrot_id_changed?
assert !pirate.catchphrase_changed?
end
def test_save_should_store_serialized_attributes_even_with_partial_updates
with_partial_updates(Topic) do
topic = Topic.create!(:content => {:a => "a"})
topic.content[:b] = "b"
#assert topic.changed? # Known bug, will fail
topic.save!
assert_equal "b", topic.content[:b]
topic.reload
assert_equal "b", topic.content[:b]
end
end
def test_save_should_not_save_serialized_attribute_with_partial_updates_if_not_present
with_partial_updates(Topic) do
Topic.create!(:author_name => 'Bill', :content => {:a => "a"})
topic = Topic.first(:select => 'id, author_name')
topic.update_attribute :author_name, 'John'
topic = Topic.first
assert_not_nil topic.content
end
end
private
def with_partial_updates(klass, on = true)
old = klass.partial_updates?
klass.partial_updates = on
yield
ensure
klass.partial_updates = old
end
def check_pirate_after_save_failure(pirate)
assert pirate.changed?
assert pirate.parrot_id_changed?
assert_equal %w(parrot_id), pirate.changed
assert_nil pirate.parrot_id_was
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activerecord/test/cases/helper.rb | provider/vendor/rails/activerecord/test/cases/helper.rb | $:.unshift(File.dirname(__FILE__) + '/../../lib')
$:.unshift(File.dirname(__FILE__) + '/../../../activesupport/lib')
require 'config'
require 'rubygems'
require 'test/unit'
require 'stringio'
require 'active_record'
require 'active_record/test_case'
require 'active_record/fixtures'
require 'connection'
require 'cases/repair_helper'
# Show backtraces for deprecated behavior for quicker cleanup.
ActiveSupport::Deprecation.debug = true
# Quote "type" if it's a reserved word for the current connection.
QUOTED_TYPE = ActiveRecord::Base.connection.quote_column_name('type')
def current_adapter?(*types)
types.any? do |type|
ActiveRecord::ConnectionAdapters.const_defined?(type) &&
ActiveRecord::Base.connection.is_a?(ActiveRecord::ConnectionAdapters.const_get(type))
end
end
ActiveRecord::Base.connection.class.class_eval do
IGNORED_SQL = [/^PRAGMA/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/, /^SAVEPOINT/, /^ROLLBACK TO SAVEPOINT/, /^RELEASE SAVEPOINT/, /SHOW FIELDS/]
def execute_with_query_record(sql, name = nil, &block)
$queries_executed ||= []
$queries_executed << sql unless IGNORED_SQL.any? { |r| sql =~ r }
execute_without_query_record(sql, name, &block)
end
alias_method_chain :execute, :query_record
end
# Make with_scope public for tests
class << ActiveRecord::Base
public :with_scope, :with_exclusive_scope
end
unless ENV['FIXTURE_DEBUG']
module ActiveRecord::TestFixtures::ClassMethods
def try_to_load_dependency_with_silence(*args)
ActiveRecord::Base.logger.silence { try_to_load_dependency_without_silence(*args)}
end
alias_method_chain :try_to_load_dependency, :silence
end
end
class ActiveSupport::TestCase
include ActiveRecord::TestFixtures
include ActiveRecord::Testing::RepairHelper
self.fixture_path = FIXTURES_ROOT
self.use_instantiated_fixtures = false
self.use_transactional_fixtures = true
def create_fixtures(*table_names, &block)
Fixtures.create_fixtures(ActiveSupport::TestCase.fixture_path, table_names, {}, &block)
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.