Updated to svn tags/tracks-1.6

This commit is contained in:
bsag 2008-06-03 19:40:22 +01:00
parent 103fcb8049
commit 02496f2d44
2274 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,131 @@
require File.dirname(__FILE__) + '/helper'
require 'will_paginate/core_ext'
class ArrayPaginationTest < Test::Unit::TestCase
def test_simple
collection = ('a'..'e').to_a
[{ :page => 1, :per_page => 3, :expected => %w( a b c ) },
{ :page => 2, :per_page => 3, :expected => %w( d e ) },
{ :page => 1, :per_page => 5, :expected => %w( a b c d e ) },
{ :page => 3, :per_page => 5, :expected => [] },
].
each do |conditions|
assert_equal conditions[:expected], collection.paginate(conditions.slice(:page, :per_page))
end
end
def test_defaults
result = (1..50).to_a.paginate
assert_equal 1, result.current_page
assert_equal 30, result.size
end
def test_deprecated_api
assert_deprecated 'paginate API' do
result = (1..50).to_a.paginate(2, 10)
assert_equal 2, result.current_page
assert_equal (11..20).to_a, result
assert_equal 50, result.total_entries
end
assert_deprecated { [].paginate nil }
end
def test_total_entries_has_precedence
result = %w(a b c).paginate :total_entries => 5
assert_equal 5, result.total_entries
end
def test_argument_error_with_params_and_another_argument
assert_raise ArgumentError do
[].paginate({}, 5)
end
end
def test_paginated_collection
entries = %w(a b c)
collection = create(2, 3, 10) do |pager|
assert_equal entries, pager.replace(entries)
end
assert_equal entries, collection
assert_respond_to_all collection, %w(page_count each offset size current_page per_page total_entries)
assert_kind_of Array, collection
assert_instance_of Array, collection.entries
assert_equal 3, collection.offset
assert_equal 4, collection.page_count
assert !collection.out_of_bounds?
end
def test_out_of_bounds
entries = create(2, 3, 2){}
assert entries.out_of_bounds?
entries = create(1, 3, 2){}
assert !entries.out_of_bounds?
end
def test_guessing_total_count
entries = create do |pager|
# collection is shorter than limit
pager.replace array
end
assert_equal 8, entries.total_entries
entries = create(2, 5, 10) do |pager|
# collection is shorter than limit, but we have an explicit count
pager.replace array
end
assert_equal 10, entries.total_entries
entries = create do |pager|
# collection is the same as limit; we can't guess
pager.replace array(5)
end
assert_equal nil, entries.total_entries
entries = create do |pager|
# collection is empty; we can't guess
pager.replace array(0)
end
assert_equal nil, entries.total_entries
end
def test_invalid_page
bad_input = [0, -1, nil, '', 'Schnitzel']
bad_input.each do |bad|
assert_raise(WillPaginate::InvalidPage) { create(bad) }
end
end
def test_invalid_per_page_setting
assert_raise(ArgumentError) { create(1, -1) }
end
private
def create(page = 2, limit = 5, total = nil, &block)
if block_given?
WillPaginate::Collection.create(page, limit, total, &block)
else
WillPaginate::Collection.new(page, limit, total)
end
end
def array(size = 3)
Array.new(size)
end
def collect_deprecations
old_behavior = WillPaginate::Deprecation.behavior
deprecations = []
WillPaginate::Deprecation.behavior = Proc.new do |message, callstack|
deprecations << message
end
result = yield
[result, deprecations]
ensure
WillPaginate::Deprecation.behavior = old_behavior
end
end

View file

@ -0,0 +1,23 @@
plugin_root = File.join(File.dirname(__FILE__), '..')
version = ENV['RAILS_VERSION']
version = nil if version and version == ""
# first look for a symlink to a copy of the framework
if !version and framework_root = ["#{plugin_root}/rails", "#{plugin_root}/../../rails"].find { |p| File.directory? p }
puts "found framework root: #{framework_root}"
# this allows for a plugin to be tested outside of an app and without Rails gems
$:.unshift "#{framework_root}/activesupport/lib", "#{framework_root}/activerecord/lib", "#{framework_root}/actionpack/lib"
else
# simply use installed gems if available
puts "using Rails#{version ? ' ' + version : nil} gems"
require 'rubygems'
if version
gem 'rails', version
else
gem 'actionpack'
gem 'activerecord'
end
end
$:.unshift "#{plugin_root}/lib"

9
vendor/plugins/will_paginate/test/console vendored Executable file
View file

@ -0,0 +1,9 @@
#!/usr/bin/env ruby
irb = RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? 'irb.bat' : 'irb'
libs = []
dirname = File.dirname(__FILE__)
libs << 'irb/completion'
libs << File.join(dirname, 'lib', 'load_fixtures')
exec "#{irb}#{libs.map{ |l| " -r #{l}" }.join} --simple-prompt"

View file

@ -0,0 +1,22 @@
sqlite3:
database: ":memory:"
adapter: sqlite3
timeout: 500
sqlite2:
database: ":memory:"
adapter: sqlite2
mysql:
adapter: mysql
username: rails
password: mislav
encoding: utf8
database: will_paginate_unittest
postgres:
adapter: postgresql
username: mislav
password: mislav
database: will_paginate_unittest
min_messages: warning

View file

@ -0,0 +1,322 @@
require File.dirname(__FILE__) + '/helper'
require File.dirname(__FILE__) + '/lib/activerecord_test_case'
require 'will_paginate'
WillPaginate.enable_activerecord
class FinderTest < ActiveRecordTestCase
fixtures :topics, :replies, :users, :projects, :developers_projects
def test_new_methods_presence
assert_respond_to_all Topic, %w(per_page paginate paginate_by_sql)
end
def test_simple_paginate
entries = Topic.paginate :page => nil
assert_equal 1, entries.current_page
assert_nil entries.previous_page
assert_nil entries.next_page
assert_equal 1, entries.page_count
assert_equal 4, entries.size
entries = Topic.paginate :page => 2
assert_equal 2, entries.current_page
assert_equal 1, entries.previous_page
assert_equal 1, entries.page_count
assert entries.empty?
end
def test_parameter_api
# :page parameter in options is required!
assert_raise(ArgumentError){ Topic.paginate }
assert_raise(ArgumentError){ Topic.paginate({}) }
# explicit :all should not break anything
assert_equal Topic.paginate(:page => nil), Topic.paginate(:all, :page => 1)
# :count could be nil and we should still not cry
assert_nothing_raised { Topic.paginate :page => 1, :count => nil }
end
def test_paginate_with_per_page
entries = Topic.paginate :page => 1, :per_page => 1
assert_equal 1, entries.size
assert_equal 4, entries.page_count
# Developer class has explicit per_page at 10
entries = Developer.paginate :page => 1
assert_equal 10, entries.size
assert_equal 2, entries.page_count
entries = Developer.paginate :page => 1, :per_page => 5
assert_equal 11, entries.total_entries
assert_equal 5, entries.size
assert_equal 3, entries.page_count
end
def test_paginate_with_order
entries = Topic.paginate :page => 1, :order => 'created_at desc'
expected = [topics(:futurama), topics(:harvey_birdman), topics(:rails), topics(:ar)].reverse
assert_equal expected, entries.to_a
assert_equal 1, entries.page_count
end
def test_paginate_with_conditions
entries = Topic.paginate :page => 1, :conditions => ["created_at > ?", 30.minutes.ago]
expected = [topics(:rails), topics(:ar)]
assert_equal expected, entries.to_a
assert_equal 1, entries.page_count
end
def test_paginate_with_include_and_conditions
entries = Topic.paginate \
:page => 1,
:include => :replies,
:conditions => "replies.content LIKE 'Bird%' ",
:per_page => 10
expected = Topic.find :all,
:include => 'replies',
:conditions => "replies.content LIKE 'Bird%' ",
:limit => 10
assert_equal expected, entries.to_a
assert_equal 1, entries.total_entries
end
def test_paginate_with_include_and_order
entries = Topic.paginate \
:page => 1,
:include => :replies,
:order => 'replies.created_at asc, topics.created_at asc',
:per_page => 10
expected = Topic.find :all,
:include => 'replies',
:order => 'replies.created_at asc, topics.created_at asc',
:limit => 10
assert_equal expected, entries.to_a
assert_equal 4, entries.total_entries
end
def test_paginate_associations_with_include
entries, project = nil, projects(:active_record)
assert_nothing_raised "THIS IS A BUG in Rails 1.2.3 that was fixed in [7326]. " +
"Please upgrade to the 1-2-stable branch or edge Rails." do
entries = project.topics.paginate \
:page => 1,
:include => :replies,
:conditions => "replies.content LIKE 'Nice%' ",
:per_page => 10
end
expected = Topic.find :all,
:include => 'replies',
:conditions => "project_id = #{project.id} AND replies.content LIKE 'Nice%' ",
:limit => 10
assert_equal expected, entries.to_a
end
def test_paginate_associations
dhh = users :david
expected_name_ordered = [projects(:action_controller), projects(:active_record)]
expected_id_ordered = [projects(:active_record), projects(:action_controller)]
# with association-specified order
entries = dhh.projects.paginate(:page => 1)
assert_equal expected_name_ordered, entries
assert_equal 2, entries.total_entries
# with explicit order
entries = dhh.projects.paginate(:page => 1, :order => 'projects.id')
assert_equal expected_id_ordered, entries
assert_equal 2, entries.total_entries
assert_nothing_raised { dhh.projects.find(:all, :order => 'projects.id', :limit => 4) }
entries = dhh.projects.paginate(:page => 1, :order => 'projects.id', :per_page => 4)
assert_equal expected_id_ordered, entries
# has_many with implicit order
topic = Topic.find(1)
expected = [replies(:spam), replies(:witty_retort)]
assert_equal expected.map(&:id).sort, topic.replies.paginate(:page => 1).map(&:id).sort
assert_equal expected.reverse, topic.replies.paginate(:page => 1, :order => 'replies.id ASC')
end
def test_paginate_association_extension
project = Project.find(:first)
entries = project.replies.paginate_recent :page => 1
assert_equal [replies(:brave)], entries
end
def test_paginate_with_joins
entries = Developer.paginate :page => 1,
:joins => 'LEFT JOIN developers_projects ON users.id = developers_projects.developer_id',
:conditions => 'project_id = 1'
assert_equal 2, entries.size
developer_names = entries.map { |d| d.name }
assert developer_names.include?('David')
assert developer_names.include?('Jamis')
expected = entries.to_a
entries = Developer.paginate :page => 1,
:joins => 'LEFT JOIN developers_projects ON users.id = developers_projects.developer_id',
:conditions => 'project_id = 1', :count => { :select => "users.id" }
assert_equal expected, entries.to_a
end
def test_paginate_with_group
entries = Developer.paginate :page => 1, :per_page => 10,
:group => 'salary', :select => 'salary', :order => 'salary'
expected = [ users(:david), users(:jamis), users(:dev_10), users(:poor_jamis) ].map(&:salary).sort
assert_equal expected, entries.map(&:salary)
end
def test_paginate_with_dynamic_finder
expected = [replies(:witty_retort), replies(:spam)]
assert_equal expected, Reply.paginate_by_topic_id(1, :page => 1)
entries = Developer.paginate :conditions => { :salary => 100000 }, :page => 1, :per_page => 5
assert_equal 8, entries.total_entries
assert_equal entries, Developer.paginate_by_salary(100000, :page => 1, :per_page => 5)
# dynamic finder + conditions
entries = Developer.paginate_by_salary(100000, :page => 1,
:conditions => ['id > ?', 6])
assert_equal 4, entries.total_entries
assert_equal (7..10).to_a, entries.map(&:id)
assert_raises NoMethodError do
Developer.paginate_by_inexistent_attribute 100000, :page => 1
end
end
def test_scoped_paginate
entries = Developer.with_poor_ones { Developer.paginate :page => 1 }
assert_equal 2, entries.size
assert_equal 2, entries.total_entries
end
def test_readonly
assert_nothing_raised { Developer.paginate :readonly => true, :page => 1 }
end
# this functionality is temporarily removed
def xtest_pagination_defines_method
pager = "paginate_by_created_at"
assert !User.methods.include?(pager), "User methods should not include `#{pager}` method"
# paginate!
assert 0, User.send(pager, nil, :page => 1).total_entries
# the paging finder should now be defined
assert User.methods.include?(pager), "`#{pager}` method should be defined on User"
end
# Is this Rails 2.0? Find out by testing find_all which was removed in [6998]
unless Developer.respond_to? :find_all
def test_paginate_array_of_ids
# AR finders also accept arrays of IDs
# (this was broken in Rails before [6912])
entries = Developer.paginate((1..8).to_a, :per_page => 3, :page => 2, :order => 'id')
assert_equal (4..6).to_a, entries.map(&:id)
assert_equal 8, entries.total_entries
end
end
uses_mocha 'internals' do
def test_implicit_all_with_dynamic_finders
Topic.expects(:find_all_by_foo).returns([])
Topic.expects(:count).returns(0)
Topic.paginate_by_foo :page => 1
end
def test_guessing_the_total_count
Topic.expects(:find).returns(Array.new(2))
Topic.expects(:count).never
entries = Topic.paginate :page => 2, :per_page => 4
assert_equal 6, entries.total_entries
end
def test_extra_parameters_stay_untouched
Topic.expects(:find).with(:all, {:foo => 'bar', :limit => 4, :offset => 0 }).returns(Array.new(5))
Topic.expects(:count).with({:foo => 'bar'}).returns(1)
Topic.paginate :foo => 'bar', :page => 1, :per_page => 4
end
def test_count_skips_select
Developer.stubs(:find).returns([])
Developer.expects(:count).with({}).returns(0)
Developer.paginate :select => 'salary', :page => 1
end
def test_count_select_when_distinct
Developer.stubs(:find).returns([])
Developer.expects(:count).with(:select => 'DISTINCT salary').returns(0)
Developer.paginate :select => 'DISTINCT salary', :page => 1
end
def test_should_use_scoped_finders_if_present
# scope-out compatibility
Topic.expects(:find_best).returns(Array.new(5))
Topic.expects(:with_best).returns(1)
Topic.paginate_best :page => 1, :per_page => 4
end
def test_paginate_by_sql
assert_respond_to Developer, :paginate_by_sql
Developer.expects(:find_by_sql).with(regexp_matches(/sql LIMIT 3(,| OFFSET) 3/)).returns([])
Developer.expects(:count_by_sql).with('SELECT COUNT(*) FROM (sql) AS count_table').returns(0)
entries = Developer.paginate_by_sql 'sql', :page => 2, :per_page => 3
end
def test_paginate_by_sql_respects_total_entries_setting
Developer.expects(:find_by_sql).returns([])
Developer.expects(:count_by_sql).never
entries = Developer.paginate_by_sql 'sql', :page => 1, :total_entries => 999
assert_equal 999, entries.total_entries
end
def test_paginate_by_sql_strips_order_by_when_counting
Developer.expects(:find_by_sql).returns([])
Developer.expects(:count_by_sql).with("SELECT COUNT(*) FROM (sql\n ) AS count_table").returns(0)
entries = Developer.paginate_by_sql "sql\n ORDER\nby foo, bar, `baz` ASC", :page => 1
end
# TODO: counts are still wrong
def test_ability_to_use_with_custom_finders
# acts_as_taggable defines find_tagged_with(tag, options)
Topic.expects(:find_tagged_with).with('will_paginate', :offset => 0, :limit => 5).returns([])
Topic.expects(:count).with({}).returns(0)
Topic.paginate_tagged_with 'will_paginate', :page => 1, :per_page => 5
end
def test_array_argument_doesnt_eliminate_count
ids = (1..8).to_a
Developer.expects(:find_all_by_id).returns([])
Developer.expects(:count).returns(0)
Developer.paginate_by_id(ids, :per_page => 3, :page => 2, :order => 'id')
end
def test_paginating_finder_doesnt_mangle_options
Developer.expects(:find).returns([])
Developer.expects(:count).returns(0)
options = { :page => 1 }
options.expects(:delete).never
options_before = options.dup
Developer.paginate(options)
assert_equal options, options_before
end
end
end

View file

@ -0,0 +1,3 @@
class Admin < User
has_many :companies, :finder_sql => 'SELECT * FROM companies'
end

View file

@ -0,0 +1,11 @@
class Developer < User
has_and_belongs_to_many :projects, :include => :topics, :order => 'projects.name'
def self.with_poor_ones(&block)
with_scope :find => { :conditions => ['salary <= ?', 80000], :order => 'salary' } do
yield
end
end
def self.per_page() 10 end
end

View file

@ -0,0 +1,13 @@
david_action_controller:
developer_id: 1
project_id: 2
joined_on: 2004-10-10
david_active_record:
developer_id: 1
project_id: 1
joined_on: 2004-10-10
jamis_active_record:
developer_id: 2
project_id: 1

View file

@ -0,0 +1,15 @@
class Project < ActiveRecord::Base
has_and_belongs_to_many :developers, :uniq => true
has_many :topics
# :finder_sql => 'SELECT * FROM topics WHERE (topics.project_id = #{id})',
# :counter_sql => 'SELECT COUNT(*) FROM topics WHERE (topics.project_id = #{id})'
has_many :replies, :through => :topics do
def find_recent(params = {})
with_scope :find => { :conditions => ['replies.created_at > ?', 15.minutes.ago] } do
find :all, params
end
end
end
end

View file

@ -0,0 +1,7 @@
action_controller:
id: 2
name: Active Controller
active_record:
id: 1
name: Active Record

View file

@ -0,0 +1,29 @@
witty_retort:
id: 1
topic_id: 1
content: Birdman is better!
created_at: <%= 6.hours.ago.to_s(:db) %>
another:
id: 2
topic_id: 2
content: Nuh uh!
created_at: <%= 1.hour.ago.to_s(:db) %>
spam:
id: 3
topic_id: 1
content: Nice site!
created_at: <%= 1.hour.ago.to_s(:db) %>
decisive:
id: 4
topic_id: 4
content: "I'm getting to the bottom of this"
created_at: <%= 30.minutes.ago.to_s(:db) %>
brave:
id: 5
topic_id: 4
content: "AR doesn't scare me a bit"
created_at: <%= 10.minutes.ago.to_s(:db) %>

View file

@ -0,0 +1,5 @@
class Reply < ActiveRecord::Base
belongs_to :topic, :include => [:replies]
validates_presence_of :content
end

View file

@ -0,0 +1,38 @@
ActiveRecord::Schema.define do
create_table "users", :force => true do |t|
t.column "name", :text
t.column "salary", :integer, :default => 70000
t.column "created_at", :datetime
t.column "updated_at", :datetime
t.column "type", :text
end
create_table "projects", :force => true do |t|
t.column "name", :text
end
create_table "developers_projects", :id => false, :force => true do |t|
t.column "developer_id", :integer, :null => false
t.column "project_id", :integer, :null => false
t.column "joined_on", :date
t.column "access_level", :integer, :default => 1
end
create_table "topics", :force => true do |t|
t.column "project_id", :integer
t.column "title", :string
t.column "subtitle", :string
t.column "content", :text
t.column "created_at", :datetime
t.column "updated_at", :datetime
end
create_table "replies", :force => true do |t|
t.column "content", :text
t.column "created_at", :datetime
t.column "updated_at", :datetime
t.column "topic_id", :integer
end
end

View file

@ -0,0 +1,4 @@
class Topic < ActiveRecord::Base
has_many :replies, :dependent => :destroy, :order => 'replies.created_at DESC'
belongs_to :project
end

View file

@ -0,0 +1,30 @@
futurama:
id: 1
title: Isnt futurama awesome?
subtitle: It really is, isnt it.
content: I like futurama
created_at: <%= 1.day.ago.to_s(:db) %>
updated_at:
harvey_birdman:
id: 2
title: Harvey Birdman is the king of all men
subtitle: yup
content: He really is
created_at: <%= 2.hours.ago.to_s(:db) %>
updated_at:
rails:
id: 3
project_id: 1
title: Rails is nice
subtitle: It makes me happy
content: except when I have to hack internals to fix pagination. even then really.
created_at: <%= 20.minutes.ago.to_s(:db) %>
ar:
id: 4
project_id: 1
title: ActiveRecord sometimes freaks me out
content: "I mean, what's the deal with eager loading?"
created_at: <%= 15.minutes.ago.to_s(:db) %>

View file

@ -0,0 +1,2 @@
class User < ActiveRecord::Base
end

View file

@ -0,0 +1,35 @@
david:
id: 1
name: David
salary: 80000
type: Developer
jamis:
id: 2
name: Jamis
salary: 150000
type: Developer
<% for digit in 3..10 %>
dev_<%= digit %>:
id: <%= digit %>
name: fixture_<%= digit %>
salary: 100000
type: Developer
<% end %>
poor_jamis:
id: 11
name: Jamis
salary: 9000
type: Developer
admin:
id: 12
name: admin
type: Admin
goofy:
id: 13
name: Goofy
type: Admin

View file

@ -0,0 +1,25 @@
require 'test/unit'
require 'rubygems'
# gem install redgreen for colored test output
begin require 'redgreen'; rescue LoadError; end
require File.join(File.dirname(__FILE__), 'boot') unless defined?(ActiveRecord)
class Test::Unit::TestCase
protected
def assert_respond_to_all object, methods
methods.each do |method|
[method.to_s, method.to_sym].each { |m| assert_respond_to object, m }
end
end
end
# Wrap tests that use Mocha and skip if unavailable.
def uses_mocha(test_name)
require 'mocha' unless Object.const_defined?(:Mocha)
rescue LoadError => load_error
$stderr.puts "Skipping #{test_name} tests. `gem install mocha` and try again."
else
yield
end

View file

@ -0,0 +1,23 @@
require File.join(File.dirname(__FILE__), 'activerecord_test_connector')
class ActiveRecordTestCase < Test::Unit::TestCase
# Set our fixture path
if ActiveRecordTestConnector.able_to_connect
self.fixture_path = File.join(File.dirname(__FILE__), '..', 'fixtures')
self.use_transactional_fixtures = true
end
def self.fixtures(*args)
super if ActiveRecordTestConnector.connected
end
def run(*args)
super if ActiveRecordTestConnector.connected
end
# Default so Test::Unit::TestCase doesn't complain
def test_truth
end
end
ActiveRecordTestConnector.setup

View file

@ -0,0 +1,60 @@
require 'active_record'
require 'active_record/version'
require 'active_record/fixtures'
class ActiveRecordTestConnector
cattr_accessor :able_to_connect
cattr_accessor :connected
# Set our defaults
self.connected = false
self.able_to_connect = true
def self.setup
unless self.connected || !self.able_to_connect
setup_connection
load_schema
# require_fixture_models
Dependencies.load_paths.unshift(File.dirname(__FILE__) + "/../fixtures")
self.connected = true
end
rescue Exception => e # errors from ActiveRecord setup
$stderr.puts "\nSkipping ActiveRecord assertion tests: #{e}"
#$stderr.puts " #{e.backtrace.join("\n ")}\n"
self.able_to_connect = false
end
private
def self.setup_connection
db = ENV['DB'].blank?? 'sqlite3' : ENV['DB']
configurations = YAML.load_file(File.join(File.dirname(__FILE__), '..', 'database.yml'))
raise "no configuration for '#{db}'" unless configurations.key? db
configuration = configurations[db]
ActiveRecord::Base.logger = Logger.new(STDOUT) if $0 == 'irb'
puts "using #{configuration['adapter']} adapter" unless ENV['DB'].blank?
ActiveRecord::Base.establish_connection(configuration)
ActiveRecord::Base.configurations = { db => configuration }
ActiveRecord::Base.connection
unless Object.const_defined?(:QUOTED_TYPE)
Object.send :const_set, :QUOTED_TYPE, ActiveRecord::Base.connection.quote_column_name('type')
end
end
def self.load_schema
ActiveRecord::Base.silence do
ActiveRecord::Migration.verbose = false
load File.dirname(__FILE__) + "/../fixtures/schema.rb"
end
end
def self.require_fixture_models
models = Dir.glob(File.dirname(__FILE__) + "/../fixtures/*.rb")
models = (models.grep(/user.rb/) + models).uniq
models.each { |f| require f }
end
end

View file

@ -0,0 +1,21 @@
require 'action_controller/test_process'
module HTML
class Node
def inner_text
children.map(&:inner_text).join('')
end
end
class Text
def inner_text
self.to_s
end
end
class Tag
def inner_text
childless?? '' : super
end
end
end

View file

@ -0,0 +1,13 @@
dirname = File.dirname(__FILE__)
require File.join(dirname, '..', 'boot')
require File.join(dirname, 'activerecord_test_connector')
# setup the connection
ActiveRecordTestConnector.setup
# load all fixtures
fixture_path = File.join(dirname, '..', 'fixtures')
Fixtures.create_fixtures(fixture_path, ActiveRecord::Base.connection.tables)
require 'will_paginate'
WillPaginate.enable_activerecord

View file

@ -0,0 +1,272 @@
require File.dirname(__FILE__) + '/helper'
require 'action_controller'
require File.dirname(__FILE__) + '/lib/html_inner_text'
ActionController::Routing::Routes.draw do |map|
map.connect ':controller/:action/:id'
end
ActionController::Base.perform_caching = false
require 'will_paginate'
WillPaginate.enable_actionpack
class PaginationTest < Test::Unit::TestCase
class DevelopersController < ActionController::Base
def list_developers
@options = session[:wp] || {}
@developers = (1..11).to_a.paginate(
:page => params[@options[:param_name] || :page] || 1,
:per_page => params[:per_page] || 4
)
render :inline => '<%= will_paginate @developers, @options %>'
end
def guess_collection_name
@developers = session[:wp]
@options = session[:wp_options]
render :inline => '<%= will_paginate @options %>'
end
protected
def rescue_errors(e) raise e end
def rescue_action(e) raise e end
end
def setup
@controller = DevelopersController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
super
end
def test_will_paginate
get :list_developers
entries = assigns :developers
assert entries
assert_equal 4, entries.size
assert_select 'div.pagination', 1, 'no main DIV' do |pagination|
assert_select 'a[href]', 3 do |elements|
validate_page_numbers [2,3,2], elements
assert_select elements.last, ':last-child', "Next &raquo;"
end
assert_select 'span', 2
assert_select 'span.disabled:first-child', "&laquo; Previous"
assert_select 'span.current', entries.current_page.to_s
assert_equal '&laquo; Previous 1 2 3 Next &raquo;', pagination.first.inner_text
end
end
def test_will_paginate_with_options
get :list_developers, { :page => 2 }, :wp => {
:class => 'will_paginate', :prev_label => 'Prev', :next_label => 'Next'
}
assert_response :success
entries = assigns :developers
assert entries
assert_equal 4, entries.size
assert_select 'div.will_paginate', 1, 'no main DIV' do
assert_select 'a[href]', 4 do |elements|
validate_page_numbers [1,1,3,3], elements
# test rel attribute values:
assert_select elements[1], 'a', '1' do |link|
assert_equal 'prev start', link.first['rel']
end
assert_select elements.first, 'a', "Prev" do |link|
assert_equal 'prev start', link.first['rel']
end
assert_select elements.last, 'a', "Next" do |link|
assert_equal 'next', link.first['rel']
end
end
assert_select 'span.current', entries.current_page.to_s
end
end
def test_will_paginate_without_container
get :list_developers, {}, :wp => { :container => false }
assert_select 'div.pagination', 0, 'no main DIV'
assert_select 'a[href]', 3
end
def test_will_paginate_without_page_links
get :list_developers, { :page => 2 }, :wp => { :page_links => false }
assert_select 'a[href]', 2 do |elements|
validate_page_numbers [1,3], elements
end
end
def test_will_paginate_preserves_parameters_on_get
get :list_developers, :foo => { :bar => 'baz' }
assert_links_match /foo%5Bbar%5D=baz/
end
def test_will_paginate_doesnt_preserve_parameters_on_post
post :list_developers, :foo => 'bar'
assert_no_links_match /foo=bar/
end
def test_adding_additional_parameters
get :list_developers, {}, :wp => { :params => { :foo => 'bar' } }
assert_links_match /foo=bar/
end
def test_removing_arbitrary_parameters
get :list_developers, { :foo => 'bar' }, :wp => { :params => { :foo => nil } }
assert_no_links_match /foo=bar/
end
def test_adding_additional_route_parameters
get :list_developers, {}, :wp => { :params => { :controller => 'baz' } }
assert_links_match %r{\Wbaz/list_developers\W}
end
def test_will_paginate_with_custom_page_param
get :list_developers, { :developers_page => 2 }, :wp => { :param_name => :developers_page }
assert_response :success
entries = assigns :developers
assert entries
assert_equal 4, entries.size
assert_select 'div.pagination', 1, 'no main DIV' do
assert_select 'a[href]', 4 do |elements|
validate_page_numbers [1,1,3,3], elements, :developers_page
end
assert_select 'span.current', entries.current_page.to_s
end
end
def test_will_paginate_windows
get :list_developers, { :page => 6, :per_page => 1 }, :wp => { :inner_window => 1 }
assert_response :success
entries = assigns :developers
assert entries
assert_equal 1, entries.size
assert_select 'div.pagination', 1, 'no main DIV' do |pagination|
assert_select 'a[href]', 8 do |elements|
validate_page_numbers [5,1,2,5,7,10,11,7], elements
assert_select elements.first, 'a', "&laquo; Previous"
assert_select elements.last, 'a', "Next &raquo;"
end
assert_select 'span.current', entries.current_page.to_s
assert_equal '&laquo; Previous 1 2 ... 5 6 7 ... 10 11 Next &raquo;', pagination.first.inner_text
end
end
def test_will_paginate_eliminates_small_gaps
get :list_developers, { :page => 6, :per_page => 1 }, :wp => { :inner_window => 2 }
assert_response :success
assert_select 'div.pagination', 1, 'no main DIV' do
assert_select 'a[href]', 12 do |elements|
validate_page_numbers [5,1,2,3,4,5,7,8,9,10,11,7], elements
end
end
end
def test_no_pagination
get :list_developers, :per_page => 12
entries = assigns :developers
assert_equal 1, entries.page_count
assert_equal 11, entries.size
assert_equal '', @response.body
end
def test_faulty_input_raises_error
assert_raise WillPaginate::InvalidPage do
get :list_developers, :page => 'foo'
end
end
uses_mocha 'helper internals' do
def test_collection_name_can_be_guessed
collection = mock
collection.expects(:page_count).returns(1)
get :guess_collection_name, {}, :wp => collection
end
end
def test_inferred_collection_name_raises_error_when_nil
ex = assert_raise ArgumentError do
get :guess_collection_name, {}, :wp => nil
end
assert ex.message.include?('@developers')
end
def test_setting_id_for_container
get :list_developers
assert_select 'div.pagination', 1 do |div|
assert_nil div.first['id']
end
# magic ID
get :list_developers, {}, :wp => { :id => true }
assert_select 'div.pagination', 1 do |div|
assert_equal 'fixnums_pagination', div.first['id']
end
# explicit ID
get :list_developers, {}, :wp => { :id => 'custom_id' }
assert_select 'div.pagination', 1 do |div|
assert_equal 'custom_id', div.first['id']
end
end
if ActionController::Base.respond_to? :rescue_responses
def test_rescue_response_hook_presence
assert_equal :not_found,
DevelopersController.rescue_responses['WillPaginate::InvalidPage']
end
end
protected
def validate_page_numbers expected, links, param_name = :page
param_pattern = /\W#{param_name}=([^&]*)/
assert_equal(expected, links.map { |e|
e['href'] =~ param_pattern
$1 ? $1.to_i : $1
})
end
def assert_links_match pattern
assert_select 'div.pagination a[href]' do |elements|
elements.each do |el|
assert_match pattern, el['href']
end
end
end
def assert_no_links_match pattern
assert_select 'div.pagination a[href]' do |elements|
elements.each do |el|
assert_no_match pattern, el['href']
end
end
end
end
class ViewHelpersTest < Test::Unit::TestCase
include WillPaginate::ViewHelpers
def test_page_entries_info
arr = ('a'..'z').to_a
collection = arr.paginate :page => 2, :per_page => 5
assert_equal %{Displaying entries <b>6&nbsp;-&nbsp;10</b> of <b>26</b> in total},
page_entries_info(collection)
collection = arr.paginate :page => 7, :per_page => 4
assert_equal %{Displaying entries <b>25&nbsp;-&nbsp;26</b> of <b>26</b> in total},
page_entries_info(collection)
end
end