move tests to new directory

This commit is contained in:
Reinier Balt 2013-05-11 23:13:16 +02:00
parent 65859807ea
commit 0bc9b0397a
42 changed files with 23 additions and 32 deletions

View file

View file

@ -0,0 +1,42 @@
require_relative '../test_helper'
class CalendarControllerTest < ActionController::TestCase
def test_show
login_as(:admin_user)
get :show
projects = [projects(:timemachine),
projects(:moremoney),
projects(:gardenclean)]
due_today = [todos(:phone_grandfather),
todos(:call_bill_gates_every_day),
todos(:due_today)]
due_next_week = [todos(:buy_shares),
todos(:buy_stego_bait),
todos(:new_action_in_context)]
due_this_month = [todos(:call_bill),
todos(:call_dino_ext)]
assert_equal "calendar", assigns['source_view']
assert_equal projects, assigns['projects']
assert_equal due_today, assigns['calendar'].due_today
assert_equal [], assigns['calendar'].due_this_week
assert_equal due_next_week, assigns['calendar'].due_next_week
assert_equal due_this_month, assigns['calendar'].due_this_month
assert_equal [], assigns['calendar'].due_after_this_month
assert_equal 8, assigns['count']
end
def test_show_ics
login_as(:admin_user)
get :show, :format => 'ics'
assert_equal 8, assigns['due_all'].count
end
def test_show_xml
login_as(:admin_user)
get :show, :format => 'xml'
assert_equal 8, assigns['due_all'].count
end
end

View file

@ -0,0 +1,34 @@
require File.expand_path(File.dirname(__FILE__) + '/../test_helper')
class ContextActionsDataTest < ActionController::TestCase
tests StatsController
def test_total_with_more_than_10_items
login_as(:admin_user)
contexts = [
{'id' => 1, 'name' => 'one', 'total' => 11},
{'id' => 2, 'name' => 'two', 'total' => 4},
{'id' => 3, 'name' => 'three', 'total' => 8}
]
Stats::TopContextsQuery.any_instance.stubs(:result).returns contexts
get :context_total_actions_data
assert_equal [47, 17, 34], assigns[:data].values
end
def test_running_actions
login_as(:admin_user)
contexts = [
{'id' => 1, 'name' => 'one', 'total' => 11},
{'id' => 2, 'name' => 'two', 'total' => 4},
{'id' => 3, 'name' => 'three', 'total' => 8}
]
Stats::TopContextsQuery.any_instance.stubs(:result).returns contexts
get :context_running_actions_data
assert_equal [47, 17, 34], assigns[:data].values
end
end

View file

@ -0,0 +1,182 @@
require File.expand_path(File.dirname(__FILE__) + '/../test_helper')
class ContextsControllerTest < ActionController::TestCase
fixtures :users, :preferences, :contexts
def test_contexts_list
login_as :admin_user
get :index
end
def test_show_sets_title
login_as :admin_user
get :show, { :id => "1" }
assert_equal 'TRACKS::Context: agenda', assigns['page_title']
end
def test_show_renders_show_template
login_as :admin_user
get :show, { :id => "1" }
assert_template "contexts/show"
end
def test_get_edit_form_using_xhr
login_as(:admin_user)
xhr :get, :edit, :id => contexts(:errand).id
assert_response 200
end
def test_create_context_via_ajax_increments_number_of_context
login_as :other_user
assert_ajax_create_increments_count '@newcontext'
end
def test_update_handles_invalid_state_change
login_as :admin_user
context = users(:admin_user).contexts.first
xhr :put, :update, :id => context.id, :context => {:name => "@name", :state => 'closed'}
assert_response 200
assert /The context cannot be closed if you have uncompleted actions/.match(@response.body)
end
# TXT feed
def test_text_feed_content
login_as :admin_user
get :index, { :format => "txt" }
assert_equal 'text/plain', @response.content_type
assert !(/&nbsp;/.match(@response.body))
end
def test_text_feed_not_accessible_to_anonymous_user_without_token
login_as nil
get :index, { :format => "txt" }
assert_response 401
end
def test_text_feed_not_accessible_to_anonymous_user_with_invalid_token
login_as nil
get :index, { :format => "txt", :token => 'foo' }
assert_response 401
end
def test_text_feed_accessible_to_anonymous_user_with_valid_token
login_as nil
get :index, { :format => "txt", :token => users(:admin_user).token }
assert_response :ok
end
# REST xml
def test_show_xml_renders_context_to_xml
login_as :admin_user
get :show, { :id => "1", :format => 'xml' }
assert_equal contexts(:agenda).to_xml( :except => :user_id ), @response.body
end
def test_show_with_nil_context_returns_404
login_as :admin_user
get :show, { :id => "0" }
assert_equal 'Context not found', @response.body
assert_response 404
end
def test_show_xml_with_nil_context_returns_404
login_as :admin_user
get :show, { :id => "0", :format => 'xml' }
assert_response 404
assert_xml_select 'error', 'Context not found'
end
# RSS
def test_rss_feed_content
login_as :admin_user
get :index, { :format => "rss" }
assert_equal 'application/rss+xml', @response.content_type
#puts @response.body
assert_xml_select 'rss[version="2.0"]' do
assert_select 'channel' do
assert_select '>title', 'Tracks Contexts'
assert_select '>description', "Lists all the contexts for #{users(:admin_user).display_name}"
assert_select 'language', 'en-us'
assert_select 'ttl', '40'
end
assert_select 'item', 10 do
assert_select 'title', /.+/
assert_select 'description' do
assert_select_encoded do
assert_select 'p', /\d+&nbsp;actions. Context is (Active|Hidden)./
end
end
%w(guid link).each do |node|
assert_select node, /http:\/\/test.host\/contexts\/.+/
end
assert_select 'pubDate', contexts(:agenda).created_at.to_s(:rfc822)
end
end
end
def test_rss_feed_not_accessible_to_anonymous_user_without_token
login_as nil
get :index, { :format => "rss" }
assert_response 401
end
def test_rss_feed_not_accessible_to_anonymous_user_with_invalid_token
login_as nil
get :index, { :format => "rss", :token => 'foo' }
assert_response 401
end
def test_rss_feed_accessible_to_anonymous_user_with_valid_token
login_as nil
get :index, { :format => "rss", :token => users(:admin_user).token }
assert_response :ok
end
# ATOM
def test_atom_feed_content
login_as :admin_user
get :index, { :format => "atom" }
assert_equal 'application/atom+xml', @response.content_type
#puts @response.body
assert_xml_select 'feed[xmlns="http://www.w3.org/2005/Atom"]' do
assert_select '>title', 'Tracks Contexts'
assert_select '>subtitle', "Lists all the contexts for #{users(:admin_user).display_name}"
assert_select 'entry', 10 do
assert_select 'title', /.+/
assert_select 'content[type="html"]' do
assert_select_encoded do
assert_select 'p', /\d+&nbsp;actions. Context is (Active|Hidden)./
end
end
assert_select 'published', /(#{Regexp.escape(contexts(:agenda).created_at.xmlschema)}|#{Regexp.escape(contexts(:library).created_at.xmlschema)})/
end
end
end
def test_atom_feed_not_accessible_to_anonymous_user_without_token
login_as nil
get :index, { :format => "atom" }
assert_response 401
end
def test_atom_feed_not_accessible_to_anonymous_user_with_invalid_token
login_as nil
get :index, { :format => "atom", :token => 'foo' }
assert_response 401
end
def test_atom_feed_accessible_to_anonymous_user_with_valid_token
login_as nil
get :index, { :format => "atom", :token => users(:admin_user).token }
assert_response :ok
end
end

View file

@ -0,0 +1,26 @@
require File.expand_path(File.dirname(__FILE__) + '/../test_helper')
require 'data_controller'
# Re-raise errors caught by the controller.
class DataController; def rescue_action(e) raise e end; end
class DataControllerTest < ActionController::TestCase
fixtures :users, :preferences, :projects, :notes
def setup
@controller = DataController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
# Replace this with your real tests.
def test_csv_export_completes_without_error
login_as :admin_user
get :csv_notes
end
def test_yml_export_comleted_without_error
login_as :admin_user
get :yaml_export
end
end

View file

@ -0,0 +1,29 @@
require File.expand_path(File.dirname(__FILE__) + '/../test_helper')
class FeedlistControllerTest < ActionController::TestCase
def test_get_index_when_not_logged_in
get :index
assert_redirected_to login_path
end
def test_get_index_by_logged_in_user
login_as :other_user
get :index
assert_response :success
assert_equal "TRACKS::Feeds", assigns['page_title']
end
def test_get_feeds_for_context_using_xhr
login_as(:admin_user)
xhr :get, :get_feeds_for_context, :context_id => contexts(:errand).id
assert_response 200
end
def test_get_feeds_for_project_using_xhr
login_as(:admin_user)
xhr :get, :get_feeds_for_project, :project_id => projects(:timemachine).id
assert_response 200
end
end

View file

@ -0,0 +1,68 @@
require File.expand_path(File.dirname(__FILE__) + '/../test_helper')
class IntegrationsControllerTest < ActionController::TestCase
def setup
end
def test_page_load
login_as(:admin_user)
get :rest_api
assert_response :success
end
def test_cloudmailin_integration_success
SITE_CONFIG['cloudmailin'] = "123456789"
post :cloudmailin, {
"html"=>"",
"plain"=>"asdasd",
"x_to_header"=>"[\"81496ecea21032d35a7a@cloudmailin.net\"]",
"disposable"=>"",
"from"=>"5555555555@tmomail.net",
"signature"=>"e85e908fb893394762047c21e54ce248",
"to"=>"<123123@cloudmailin.net>",
"subject"=>"asd",
"x_cc_header"=>"",
"message"=>"Received: from VMBX103.ihostexchange.net ([192.168.3.3]) by\r\n HUB103.ihostexchange.net ([66.46.182.53]) with mapi; Wed, 5 Oct 2011 17:12:44\r\n -0400\r\nFrom: SMS User <5555555555@tmomail.net>\r\nTo: Tracks <123123@cloudmailin.net>\r\nDate: Wed, 5 Oct 2011 17:12:43 -0400\r\nSubject: asd\r\nThread-Topic: asd\r\nThread-Index: AcyDo4aig2wghvcsTAOkleWqi4t/FQ==\r\nMessage-ID: <7D7CB176-7559-4997-A301-8DF9726264C7@tmomail.net>\r\nAccept-Language: de-DE, en-US\r\nContent-Language: en-US\r\nX-MS-Has-Attach:\r\nX-MS-TNEF-Correlator:\r\nacceptlanguage: de-DE, en-US\r\nContent-Type: text/plain; charset=\"us-ascii\"\r\nContent-Transfer-Encoding: quoted-printable\r\nMIME-Version: 1.0\r\n\r\nasdasd\r\n"
}
assert_response :success
end
def test_cloudmailin_integration_invalid_signature
SITE_CONFIG['cloudmailin'] = "12345678901234567890"
post :cloudmailin, {
"html"=>"",
"plain"=>"asdasd",
"x_to_header"=>"[\"81496ecea21032d35a7a@cloudmailin.net\"]",
"disposable"=>"",
"from"=>"5555555555@tmomail.net",
"signature"=>"e85e908fb893394762047c21e54ce248",
"to"=>"<123123@cloudmailin.net>",
"subject"=>"asd",
"x_cc_header"=>"",
"message"=>"Received: from VMBX103.ihostexchange.net ([192.168.3.3]) by\r\n HUB103.ihostexchange.net ([66.46.182.53]) with mapi; Wed, 5 Oct 2011 17:12:44\r\n -0400\r\nFrom: SMS User <5555555555@tmomail.net>\r\nTo: Tracks <123123@cloudmailin.net>\r\nDate: Wed, 5 Oct 2011 17:12:43 -0400\r\nSubject: asd\r\nThread-Topic: asd\r\nThread-Index: AcyDo4aig2wghvcsTAOkleWqi4t/FQ==\r\nMessage-ID: <7D7CB176-7559-4997-A301-8DF9726264C7@tmomail.net>\r\nAccept-Language: de-DE, en-US\r\nContent-Language: en-US\r\nX-MS-Has-Attach:\r\nX-MS-TNEF-Correlator:\r\nacceptlanguage: de-DE, en-US\r\nContent-Type: text/plain; charset=\"us-ascii\"\r\nContent-Transfer-Encoding: quoted-printable\r\nMIME-Version: 1.0\r\n\r\nasdasd\r\n"
}
assert_response 403
end
def test_cloudmailin_integration_unknown_address
SITE_CONFIG['cloudmailin'] = "123456789"
post :cloudmailin, {
"html"=>"",
"plain"=>"asdasd",
"x_to_header"=>"[\"81496ecea21032d35a7a@cloudmailin.net\"]",
"disposable"=>"",
"from"=>"444444444444@tmomail.net",
"signature"=>"6d2df0e807bfa9b77d24c31dce6d4515",
"to"=>"<123123@cloudmailin.net>",
"subject"=>"asd",
"x_cc_header"=>"",
"message"=>"Received: from VMBX103.ihostexchange.net ([192.168.3.3]) by\r\n HUB103.ihostexchange.net ([66.46.182.53]) with mapi; Wed, 5 Oct 2011 17:12:44\r\n -0400\r\nFrom: SMS User <444444444444@tmomail.net>\r\nTo: Tracks <123123@cloudmailin.net>\r\nDate: Wed, 5 Oct 2011 17:12:43 -0400\r\nSubject: asd\r\nThread-Topic: asd\r\nThread-Index: AcyDo4aig2wghvcsTAOkleWqi4t/FQ==\r\nMessage-ID: <7D7CB176-7559-4997-A301-8DF9726264C7@tmomail.net>\r\nAccept-Language: de-DE, en-US\r\nContent-Language: en-US\r\nX-MS-Has-Attach:\r\nX-MS-TNEF-Correlator:\r\nacceptlanguage: de-DE, en-US\r\nContent-Type: text/plain; charset=\"us-ascii\"\r\nContent-Transfer-Encoding: quoted-printable\r\nMIME-Version: 1.0\r\n\r\nasdasd\r\n"
}
assert_response 404
end
end

View file

@ -0,0 +1,137 @@
require File.expand_path(File.dirname(__FILE__) + '/../test_helper')
class LoginControllerTest < ActionController::TestCase
fixtures :preferences, :users
def setup
end
#============================================
#Login and logout
#============================================
def test_invalid_login
post :login, {:user_login => 'cracker', :user_password => 'secret', :user_noexpiry => 'on'}
assert_response :success
assert(!session[:user_id])
assert_template "login"
end
def test_login_with_valid_admin_user
@request.session['return-to'] = "/bogus/location"
post :login, {:user_login => 'admin', :user_password => 'abracadabra', :user_noexpiry => 'on'}
user = User.find(session['user_id'])
assert_not_nil user
assert_equal user.id, session['user_id']
assert_equal user.login, "admin"
assert user.is_admin
assert_equal "Login successful: session will not expire.", flash[:notice]
assert_equal("http://#{@request.host}/bogus/location", @response.redirect_url)
end
def test_login_with_valid_standard_user
post :login, {:user_login => 'jane', :user_password => 'sesame', :user_noexpiry => 'off'}
user = User.find(session['user_id'])
assert_not_nil user
assert_equal user.id, session['user_id']
assert_equal user.login, "jane"
assert user.is_admin == false || user.is_admin == 0
assert_equal "Login successful: session will expire after 1 hour of inactivity.", flash[:notice]
assert_redirected_to root_url
end
def test_login_with_no_users_redirects_to_signup
User.delete_all
get :login
assert_redirected_to signup_url
end
def test_logout
login_as :admin_user
get :logout
assert_nil(session['user_id'])
assert_redirected_to login_url
end
# Test login with a bad password for existing user
#
def test_login_bad_password
post :login, {:user_login => 'jane', :user_password => 'wrong', :user_noexpiry => 'on'}
assert(!session[:user])
assert_equal "Login unsuccessful.", flash[:warning]
assert_response :success
end
def test_login_bad_login
post :login, {:user_login => 'blah', :user_password => 'sesame', :user_noexpiry => 'on'}
assert(!session[:user])
assert_equal "Login unsuccessful.", flash[:warning]
assert_response :success
end
def test_should_remember_me
post :login, :user_login => 'jane', :user_password => 'sesame', :user_noexpiry => "on"
assert_not_nil @response.cookies["auth_token"]
end
def test_should_not_remember_me
post :login, :user_login => 'jane', :user_password => 'sesame', :user_noexpiry => "off"
assert_nil @response.cookies["auth_token"]
end
def test_should_delete_token_on_logout
login_as :other_user
get :logout
assert_nil @response.cookies["auth_token"]
end
def test_should_login_with_cookie
users(:other_user).remember_me
@request.cookies["auth_token"] = auth_token_cookie_for(:other_user)
get :login
assert @controller.send(:logged_in?)
end
def test_should_fail_expired_cookie_login
users(:other_user).remember_me
users(:other_user).update_attribute :remember_token_expires_at, 5.minutes.ago.utc
@request.cookies["auth_token"] = auth_token_cookie_for(:other_user)
get :login
assert !@controller.send(:logged_in?)
end
def test_should_fail_cookie_login
users(:other_user).remember_me
@request.cookies["auth_token"] = 'invalid_auth_token'
get :login
assert !@controller.send(:logged_in?)
end
def test_current_user_nil
get :login
assert_nil @controller.current_user
end
def test_current_user_correct
post :login, {:user_login => 'jane', :user_password => 'sesame', :user_noexpiry => 'off'}
assert_equal users(:other_user), @controller.current_user
end
def test_prefs_nil
login_as nil
get :login
assert_nil @controller.prefs
end
def test_prefs_correct
post :login, {:user_login => 'jane', :user_password => 'sesame', :user_noexpiry => 'off'}
assert_equal users(:other_user).prefs, @controller.prefs
end
private
def auth_token_cookie_for(user)
users(user).remember_token
end
end

View file

@ -0,0 +1,86 @@
require File.expand_path(File.dirname(__FILE__) + '/../test_helper')
class MessageGatewayTest < ActiveSupport::TestCase
def setup
@user = users(:sms_user)
@inbox = contexts(:inbox)
end
def load_message(filename)
MessageGateway.receive(File.read(File.join(Rails.root, 'test', 'fixtures', filename)))
end
def test_sms_with_no_subject
todo_count = Todo.count
load_message('sample_sms.txt')
# assert some stuff about it being created
assert_equal(todo_count+1, Todo.count)
message_todo = Todo.where(:description => "message_content").first
assert_not_nil(message_todo)
assert_equal(@inbox, message_todo.context)
assert_equal(@user, message_todo.user)
end
def test_mms_with_subject
todo_count = Todo.count
load_message('sample_mms.txt')
# assert some stuff about it being created
assert_equal(todo_count+1, Todo.count)
message_todo = Todo.where(:description => "This is the subject").first
assert_not_nil(message_todo)
assert_equal(@inbox, message_todo.context)
assert_equal(@user, message_todo.user)
assert_equal("This is the message body", message_todo.notes)
end
def test_email_with_winmail_dat
todo_count = Todo.count
load_message('email_with_winmail.txt')
# assert some stuff about it being created
assert_equal(todo_count+1, Todo.count)
end
def test_email_with_multipart_attachments
todo_count = Todo.count
load_message('email_with_multipart.txt')
# assert some stuff about it being created
assert_equal(todo_count+1, Todo.count)
end
def test_no_user
todo_count = Todo.count
badmessage = File.read(File.join(Rails.root, 'test', 'fixtures', 'sample_sms.txt'))
badmessage.gsub!("5555555555", "notauser")
MessageGateway.receive(badmessage)
assert_equal(todo_count, Todo.count)
end
def test_direct_to_context
message = File.read(File.join(Rails.root, 'test', 'fixtures', 'sample_sms.txt'))
valid_context_msg = message.gsub('message_content', 'this is a task @ anothercontext')
invalid_context_msg = message.gsub('message_content', 'this is also a task @ notacontext')
MessageGateway.receive(valid_context_msg)
valid_context_todo = Todo.where(:description => "this is a task").first
assert_not_nil(valid_context_todo)
assert_equal(contexts(:anothercontext), valid_context_todo.context)
MessageGateway.receive(invalid_context_msg)
invalid_context_todo = Todo.where(:description => 'this is also a task').first
assert_not_nil(invalid_context_todo)
assert_equal(@inbox, invalid_context_todo.context)
end
end

View file

@ -0,0 +1,14 @@
require File.expand_path(File.dirname(__FILE__) + '/../test_helper')
class NotesControllerTest < ActionController::TestCase
def setup
end
def test_get_notes_page
login_as :admin_user
get :index
assert_response 200
end
end

View file

@ -0,0 +1,69 @@
require File.expand_path(File.dirname(__FILE__) + '/../test_helper')
class PreferencesControllerTest < ActionController::TestCase
def setup
super
assert_equal "test", Rails.env
assert_equal "change-me", Tracks::Config.salt
end
test "render_date_format requires login" do
get :render_date_format
assert_redirected_to login_path
end
test "calling render_date_format returns date" do
login_as :admin_user
get :render_date_format
assert_response :success
assert_equal I18n.l(Date.today, :format => "%Y-%m-%d"), @response.body
get(:render_date_format, {:date_format => "%A %Y"})
assert_response :success
assert_equal I18n.l(Date.today, :format => "%A %Y"), @response.body
end
test "index page requires login" do
get :index # should fail because no login
assert_redirected_to login_path
end
test "index sets prefs and user" do
login_as :admin_user
get :index
assert_response :success
assert_equal assigns['page_title'], "TRACKS::Preferences"
assert_not_nil assigns['prefs']
assert_not_nil assigns['user']
end
test "should update preferences" do
login_as :admin_user
post :update, {
:id => users(:admin_user).id,
:user => { :first_name => 'Jane', :last_name => 'Doe'},
:prefs => { :date_format => "%m-%d-%Y", :week_starts => "0", :show_number_completed => "10", :show_completed_projects_in_sidebar => "false", :show_hidden_contexts_in_sidebar => "false", :staleness_starts => "14", :due_style => "1" }}
updated_admin_user = users(:admin_user).reload
assert_not_nil updated_admin_user.preference
assert_equal 'Jane', updated_admin_user.first_name
assert_equal 'Doe', updated_admin_user.last_name
assert_redirected_to :action => 'index'
end
test "should not update password if left empty" do
login_as :admin_user
old_password_hash = users(:admin_user).password
post :update, {
:id => users(:admin_user).id,
:user => { :first_name => 'Jane', :last_name => 'Doe', :password => "", :password_confirmation => ""},
:prefs => { :date_format => "%m-%d-%Y", :week_starts => "0", :show_number_completed => "10", :show_completed_projects_in_sidebar => "false", :show_hidden_contexts_in_sidebar => "false", :staleness_starts => "14", :due_style => "1" }}
updated_admin_user = users(:admin_user).reload
assert_equal old_password_hash, updated_admin_user.password
end
end

View file

@ -0,0 +1,258 @@
require File.expand_path(File.dirname(__FILE__) + '/../test_helper')
class ProjectsControllerTest < ActionController::TestCase
def setup
end
def test_projects_list
login_as :admin_user
get :index
end
def test_show_exposes_deferred_todos
p = projects(:timemachine)
login_as :admin_user
get :show, :id => p.to_param
assert_not_nil assigns['deferred_todos']
assert_equal 1, assigns['deferred_todos'].size
t = p.todos.not_completed[0]
t.show_from = 1.days.from_now.utc
t.save!
get :show, :id => p.to_param
assert_equal 2, assigns['deferred_todos'].size
end
def test_show_exposes_next_project_in_same_state
login_as :admin_user
get :show, :id => projects(:timemachine).to_param
assert_equal(projects(:moremoney), assigns['next_project'])
end
def test_show_exposes_previous_project_in_same_state
login_as :admin_user
get :show, :id => projects(:moremoney).to_param
assert_equal(projects(:timemachine), assigns['previous_project'])
end
def test_create_project_via_ajax_increments_number_of_projects
login_as :other_user
assert_ajax_create_increments_count 'My New Project'
end
def test_todo_state_is_project_hidden_after_hiding_project
p = projects(:timemachine)
todos = p.todos.find_in_state(:all, :active)
login_as(:admin_user)
xhr :post, :update, :id => 1, "project"=>{"name"=>p.name, "description"=>p.description, "state"=>"hidden"}
todos.each do |t|
assert_equal :project_hidden, t.reload().aasm_current_state
end
assert p.reload().hidden?
end
def test_not_done_counts_after_hiding_and_unhiding_project
p = projects(:timemachine)
todos = p.todos.find_in_state(:all, :active)
login_as(:admin_user)
xhr :post, :update, :id => 1, "project"=>{"name"=>p.name, "description"=>p.description, "state"=>"hidden"}
xhr :post, :update, :id => 1, "project"=>{"name"=>p.name, "description"=>p.description, "state"=>"active"}
todos.each do |t|
assert_equal :active, t.reload().aasm_current_state
end
assert p.reload().active?
end
# RSS
def test_rss_feed_content
login_as(:admin_user)
get :index, { :format => "rss" }
assert_equal 'application/rss+xml', @response.content_type
#puts @response.body
assert_xml_select 'rss[version="2.0"]' do
assert_select 'channel' do
assert_select '>title', 'Tracks Projects'
assert_select '>description', "Lists all the projects for #{users(:admin_user).display_name}"
assert_select 'language', 'en-us'
assert_select 'ttl', '40'
end
assert_select 'item', 3 do
assert_select 'title', /.+/
assert_select 'description' do
assert_select_encoded do
assert_select 'p', /^\d+&nbsp;actions\. Project is (active|hidden|completed)\.$/
end
end
%w(guid link).each do |node|
assert_select node, /http:\/\/test.host\/projects\/.+/
end
assert_select 'pubDate', projects(:timemachine).updated_at.to_s(:rfc822)
end
end
end
def test_rss_feed_not_accessible_to_anonymous_user_without_token
login_as nil
get :index, { :format => "rss" }
assert_response 401
end
def test_rss_feed_not_accessible_to_anonymous_user_with_invalid_token
login_as nil
get :index, { :format => "rss", :token => 'foo' }
assert_response 401
end
def test_rss_feed_accessible_to_anonymous_user_with_valid_token
login_as nil
get :index, { :format => "rss", :token => users(:admin_user).token }
assert_response :ok
end
def test_atom_feed_content
login_as :admin_user
get :index, { :format => "atom" }
assert_equal 'application/atom+xml', @response.content_type
# puts @response.body
assert_xml_select 'feed[xmlns="http://www.w3.org/2005/Atom"]' do
assert_select '>title', 'Tracks Projects'
assert_select '>subtitle', "Lists all the projects for #{users(:admin_user).display_name}"
assert_select 'entry', 3 do
assert_select 'title', /.+/
assert_select 'content[type="html"]' do
assert_select_encoded do
assert_select 'p', /\d+&nbsp;actions. Project is (active|hidden|completed)./
end
end
assert_select 'published', /(#{Regexp.escape(projects(:timemachine).updated_at.xmlschema)}|#{Regexp.escape(projects(:moremoney).updated_at.xmlschema)})/
end
end
end
def test_atom_feed_not_accessible_to_anonymous_user_without_token
login_as nil
get :index, { :format => "atom" }
assert_response 401
end
def test_atom_feed_not_accessible_to_anonymous_user_with_invalid_token
login_as nil
get :index, { :format => "atom", :token => 'foo' }
assert_response 401
end
def test_atom_feed_accessible_to_anonymous_user_with_valid_token
login_as nil
get :index, { :format => "atom", :token => users(:admin_user).token }
assert_response :ok
end
def test_text_feed_content
login_as :admin_user
get :index, { :format => "txt" }
assert_equal 'text/plain', @response.content_type
assert !(/&nbsp;/.match(@response.body))
end
def test_text_feed_content_for_projects_with_no_actions
login_as :admin_user
p = projects(:timemachine)
p.todos.each { |t| t.destroy }
get :index, { :format => "txt", :only_active_with_no_next_actions => true }
assert (/^\s*BUILD A WORKING TIME MACHINE\s+0 actions. Project is active.\s*$/.match(@response.body))
assert !(/[1-9] actions/.match(@response.body))
end
def test_text_feed_not_accessible_to_anonymous_user_without_token
login_as nil
get :index, { :format => "txt" }
assert_response 401
end
def test_text_feed_not_accessible_to_anonymous_user_with_invalid_token
login_as nil
get :index, { :format => "txt", :token => 'foo' }
assert_response 401
end
def test_text_feed_accessible_to_anonymous_user_with_valid_token
login_as nil
get :index, { :format => "txt", :token => users(:admin_user).token }
assert_response :ok
end
def test_actionize_sorts_active_projects_by_number_of_tasks
login_as :admin_user
u = users(:admin_user)
post :actionize, :state => "active", :format => 'js'
assert_equal 1, projects(:gardenclean).position
assert_equal 2, projects(:moremoney).position
assert_equal 3, projects(:timemachine).position
end
def test_alphabetize_sorts_active_projects_alphabetically
login_as :admin_user
u = users(:admin_user)
post :alphabetize, :state => "active", :format => 'js'
assert_equal 1, projects(:timemachine).position
assert_equal 2, projects(:gardenclean).position
assert_equal 3, projects(:moremoney).position
end
def test_alphabetize_assigns_state
login_as :admin_user
post :alphabetize, :state => "active", :format => 'js'
assert_equal "active", assigns['state']
end
def test_alphabetize_assigns_projects
login_as :admin_user
post :alphabetize, :state => "active", :format => 'js'
exposed_projects = assigns['projects']
assert_equal 3, exposed_projects.length
assert_equal projects(:timemachine), exposed_projects[0]
assert_equal projects(:gardenclean), exposed_projects[1]
assert_equal projects(:moremoney), exposed_projects[2]
end
# XML (REST API)
def test_xml_content
login_as(:admin_user)
get :index, { :format => "xml" }
assert_equal 'application/xml', @response.content_type
assert_xml_select 'projects' do
assert_select 'project', 3 do
assert_select 'name', /.+/
assert_select 'state', 'active'
end
end
end
def test_xml_not_accessible_to_anonymous_user_without_token
login_as nil
get :index, { :format => "xml" }
assert_response 401
end
def test_xml_not_accessible_to_anonymous_user_with_invalid_token
login_as nil
get :index, { :format => "xml", :token => 'foo' }
assert_response 401
end
def test_xml_not_accessible_to_anonymous_user_with_valid_token
login_as nil
get :index, { :format => "xml", :token => users(:admin_user).token }
assert_response 401
end
end

View file

@ -0,0 +1,268 @@
require File.expand_path(File.dirname(__FILE__) + '/../test_helper')
class RecurringTodosControllerTest < ActionController::TestCase
def test_get_index_when_not_logged_in
get :index
assert_redirected_to login_path
end
def test_destroy_recurring_todo
login_as(:admin_user)
xhr :post, :destroy, :id => 1, :_source_view => 'todo'
begin
rc = RecurringTodo.find(1)
rescue
rc = nil
end
assert_nil rc
end
def test_new_recurring_todo
login_as(:admin_user)
orig_rt_count = RecurringTodo.count
orig_todo_count = Todo.count
put :create,
"context_name"=>"library",
"project_name"=>"Build a working time machine",
"recurring_todo" =>
{
"daily_every_x_days"=>"1",
"daily_selector"=>"daily_every_x_day",
"description"=>"new recurring pattern",
"end_date" => "31/08/2010",
"ends_on" => "ends_on_end_date",
"monthly_day_of_week" => "1",
"monthly_every_x_day" => "18",
"monthly_every_x_month2" => "1",
"monthly_every_x_month" => "1",
"monthly_every_xth_day"=>"1",
"monthly_selector"=>"monthly_every_x_day",
"notes"=>"with some notes",
"number_of_occurences" => "",
"recurring_period"=>"yearly",
"recurring_show_days_before"=>"10",
"recurring_target"=>"due_date",
"recurring_show_always" => "1",
"start_from"=>"18/08/2008",
"weekly_every_x_week"=>"1",
"weekly_return_monday"=>"m",
"yearly_day_of_week"=>"1",
"yearly_every_x_day"=>"8",
"yearly_every_xth_day"=>"1",
"yearly_month_of_year2"=>"8",
"yearly_month_of_year"=>"6",
"yearly_selector"=>"yearly_every_x_day"
},
"tag_list"=>"one, two, three, four"
# check new recurring todo added
assert_equal orig_rt_count+1, RecurringTodo.count
# check new todo added
assert_equal orig_todo_count+1, Todo.count
end
def test_recurring_todo_toggle_check
# the test fixtures did add recurring_todos but not the corresponding todos,
# so we check complete and uncheck to force creation of a todo from the
# pattern
login_as(:admin_user)
# mark as complete
xhr :post, :toggle_check, :id=>1, :_source_view=>""
recurring_todo_1 = RecurringTodo.find(1)
assert recurring_todo_1.completed?
# remove remaining todo
todo = Todo.where(:recurring_todo_id => 1).first
todo.recurring_todo_id = 2
todo.save
todo_count = Todo.count
# mark as active
xhr :post, :toggle_check, :id=>1, :_source_view=>""
recurring_todo_1 = RecurringTodo.find(1) # reload seems to not work
assert recurring_todo_1.active?, "recurring todo should be active but is #{recurring_todo_1.aasm_current_state}"
# by making active, a new todo should be created from the pattern
assert_equal todo_count+1, Todo.count
# find the new todo and check its description
new_todo = Todo.where(:recurring_todo_id => 1).first
assert_equal "Call Bill Gates every day", new_todo.description
end
def test_creating_recurring_todo_with_show_from_in_past
login_as(:admin_user)
@yearly = RecurringTodo.find(5) # yearly on june 8th
# change due date in four days from now and show from 10 days before, i.e. 6
# days ago
target_date = Time.now.utc + 4.days
@yearly.every_other1 = target_date.day
@yearly.every_other2 = target_date.month
@yearly.show_from_delta = 10
# unless @yearly.valid?
# @yearly.errors.each {|obj, error| puts error}
# end
assert @yearly.save
# toggle twice to force generation of new todo
xhr :post, :toggle_check, :id=>5, :_source_view=>""
xhr :post, :toggle_check, :id=>5, :_source_view=>""
new_todo = Todo.where(:recurring_todo_id => 5).first
# due date should be the target_date
assert_equal users(:admin_user).at_midnight(Date.new(target_date.year, target_date.month, target_date.day)), new_todo.due
# show_from should be nil since now+4.days-10.days is in the past
assert_equal nil, new_todo.show_from
end
def test_last_sunday_of_march
# this test is a duplicate of the unit test. Only this test covers the
# codepath in the controllers
Timecop.travel(Time.local(2012,1,1)) do
login_as(:admin_user)
orig_rt_count = RecurringTodo.count
orig_todo_count = Todo.count
put :create,
"context_name"=>"library",
"project_name"=>"Build a working time machine",
"recurring_todo" =>
{
"daily_every_x_days"=>"1",
"daily_selector"=>"daily_every_x_day",
"description"=>"new recurring pattern",
"end_date" => "",
"ends_on" => "no_end_date",
"monthly_day_of_week" => "1",
"monthly_every_x_day" => "22",
"monthly_every_x_month2" => "1",
"monthly_every_x_month" => "1",
"monthly_every_xth_day"=>"1",
"monthly_selector"=>"monthly_every_x_day",
"notes"=>"with some notes",
"number_of_occurences" => "",
"recurring_period"=>"yearly",
"recurring_show_days_before"=>"0",
"recurring_target"=>"due_date",
"recurring_show_always" => "1",
"start_from"=>"1/10/2012", # adjust after 2012
"weekly_every_x_week"=>"1",
"weekly_return_monday"=>"w",
"yearly_day_of_week"=>"0",
"yearly_every_x_day"=>"22",
"yearly_every_xth_day"=>"5",
"yearly_month_of_year2"=>"3",
"yearly_month_of_year"=>"10",
"yearly_selector"=>"yearly_every_xth_day"
},
"tag_list"=>"one, two, three, four"
# check new recurring todo added
assert_equal orig_rt_count+1, RecurringTodo.count
# check new todo added
assert_equal orig_todo_count+1, Todo.count
# find the newly created todo
new_todo = Todo.where(:description => "new recurring pattern").first
assert !new_todo.nil?
# the date should be 31 march 2013
assert_equal Time.zone.local(2013,3,31), new_todo.due
end
end
def test_recurring_todo_with_due_date_and_show_always
login_as(:admin_user)
orig_rt_count = RecurringTodo.count
orig_todo_count = Todo.count
put :create,
"context_name"=>"library",
"project_name"=>"Build a working time machine",
"recurring_todo" =>
{
"daily_every_x_days"=>"1",
"daily_selector"=>"daily_every_x_day",
"description"=>"new recurring pattern",
"end_date" => "",
"ends_on" => "no_end_date",
"monthly_day_of_week" => "1",
"monthly_every_x_day" => "22",
"monthly_every_x_month2" => "1",
"monthly_every_x_month" => "1",
"monthly_every_xth_day"=>"1",
"monthly_selector"=>"monthly_every_x_day",
"notes"=>"with some notes",
"number_of_occurences" => "",
"recurring_period"=>"yearly",
"recurring_show_always"=>"1",
"recurring_show_days_before"=>"0",
"recurring_target"=>"due_date",
"start_from"=>"1/10/2012", # adjust after 2012
"weekly_every_x_week"=>"1",
"weekly_return_monday"=>"w",
"yearly_day_of_week"=>"0",
"yearly_every_x_day"=>"22",
"yearly_every_xth_day"=>"5",
"yearly_month_of_year2"=>"3",
"yearly_month_of_year"=>"10",
"yearly_selector"=>"yearly_every_xth_day"
},
"tag_list"=>"one, two, three, four"
# check new recurring todo added
assert_equal orig_rt_count+1, RecurringTodo.count
# check new todo added
assert_equal orig_todo_count+1, Todo.count
# find the newly created recurring todo
recurring_todo = RecurringTodo.where(:description => "new recurring pattern").first
assert !recurring_todo.nil?
assert_equal "due_date", recurring_todo.target
assert_equal true, recurring_todo.show_always?
end
def test_find_and_inactivate
login_as(:admin_user)
rt = RecurringTodo.find(recurring_todos(:call_bill_gates_every_day).id)
todo = Todo.where(:recurring_todo_id => rt.id).first
assert_not_nil todo
assert_equal "active", todo.state, "todo should be active"
assert_equal "active", rt.state, "repeat pattern should be active"
get :index # will call find_and_inactivate
rt.reload
assert_equal "active", rt.state, "repeat pattern should still be active"
# disconnect todo from pattern thus leaving the pattern without
# any active todos, but in active state
todo.reload
todo.recurring_todo_id=nil
todo.save!
todo.reload
rt.reload
assert_equal "active", rt.state, "repeat pattern should still be active and not changed"
get :index
rt.reload
assert_equal "completed", rt.state, "repeat pattern should be completed"
end
end

View file

@ -0,0 +1,21 @@
require File.expand_path(File.dirname(__FILE__) + '/../test_helper')
class SearchControllerTest < ActionController::TestCase
def setup
end
def test_get_search_page
login_as :admin_user
get :index
assert_response 200
end
def test_search_for_todo_with_tag
login_as :admin_user
post :results, :search => "gates"
assert_response 200
assert_equal 3, assigns['count'], "should have found 3 todos"
end
end

View file

@ -0,0 +1,488 @@
require File.expand_path(File.dirname(__FILE__) + '/../test_helper')
class StatsControllerTest < ActionController::TestCase
def test_get_index_when_not_logged_in
get :index
assert_redirected_to login_url
end
def test_get_index
login_as(:admin_user)
get :index
assert_response :success
end
def test_get_charts
login_as(:admin_user)
%w{
actions_done_last30days_data
actions_done_last12months_data
actions_completion_time_data
actions_visible_running_time_data
actions_running_time_data
actions_open_per_week_data
actions_day_of_week_all_data
actions_day_of_week_30days_data
actions_time_of_day_all_data
actions_time_of_day_30days_data
}.each do |action|
get action
assert_response :success
assert_template "stats/"+action
end
%w{
context_total_actions_data
context_running_actions_data
}.each do |action|
get action
assert_response :success
assert_template "stats/pie_chart_data"
end
end
def test_totals
login_as(:admin_user)
get :index
assert_response :success
totals = assigns['stats'].totals
assert_equal 4, totals.tags
assert_equal 2, totals.unique_tags
assert_equal 2.week.ago.utc.at_midnight, totals.first_action_at.utc.at_midnight
end
def test_downdrill
login_as(:admin_user)
# drill down without parameters
# this will fail 500
#
# get :show_selected_actions_from_chart
# assert_response :not_found
# assert_template nil
# get week 0-1 for actions visible running
get :show_selected_actions_from_chart, :id => 'avrt', :index => 0
assert_response :success
assert_template "stats/show_selection_from_chart"
# get week 0 and further for actions visible running
get :show_selected_actions_from_chart, :id => 'avrt_end', :index => 0
assert_response :success
assert_template "stats/show_selection_from_chart"
# get week 0-1 for actions running
get :show_selected_actions_from_chart, :id => 'art', :index => 0
assert_response :success
assert_template "stats/show_selection_from_chart"
# get week 0 and further for actions running
get :show_selected_actions_from_chart, :id => 'art_end', :index => 0
assert_response :success
assert_template "stats/show_selection_from_chart"
end
def test_stats_render_when_tasks_have_no_taggings
login_as(:admin_user)
# using the default fixtures, todos have tags
get :index
assert_response :success
# clear taggings table and render again
Tagging.delete_all
get :index
assert_response :success
end
def test_actions_done_last12months_data
Timecop.travel(Time.local(2013, 1, 15)) do
login_as(:admin_user)
@current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all
given_todos_for_stats
# When I get the chart data
get :actions_done_last12months_data
assert_response :success
# Then the todos for the chart should be retrieved
assert_not_nil assigns['actions_done_last12months']
assert_not_nil assigns['actions_created_last12months']
assert_equal 7, assigns['actions_created_last12months'].count, "very old todo should not be retrieved"
# And they should be totalled in a hash
assert_equal 2, assigns['actions_created_last12months_array'][0], "there should be two todos in current month"
assert_equal 1, assigns['actions_created_last12months_array'][1], "there should be one todo in previous month"
assert_equal 1, assigns['actions_created_last12months_array'][2], "there should be one todo in two month ago"
assert_equal 1, assigns['actions_created_last12months_array'][3], "there should be one todo in three month ago"
assert_equal 2, assigns['actions_created_last12months_array'][4], "there should be two todos (1 created & 1 done) in four month ago"
assert_equal 1, assigns['actions_done_last12months_array'][1], "there should be one completed todo one-two months ago"
assert_equal 1, assigns['actions_done_last12months_array'][2], "there should be one completed todo two-three months ago"
assert_equal 1, assigns['actions_done_last12months_array'][4], "there should be one completed todo four-five months ago"
# And they should be averaged over three months
assert_equal 2/3.0, assigns['actions_done_avg_last12months_array'][1], "fourth month should be excluded"
assert_equal 2/3.0, assigns['actions_done_avg_last12months_array'][2], "fourth month should be included"
assert_equal (3)/3.0, assigns['actions_created_avg_last12months_array'][1], "one every month"
assert_equal (4)/3.0, assigns['actions_created_avg_last12months_array'][2], "two in fourth month"
# And the current month should be interpolated
fraction = Time.zone.now.day.to_f / Time.zone.now.end_of_month.day.to_f
assert_equal (2*(1/fraction)+2)/3.0, assigns['interpolated_actions_created_this_month'], "two this month and one in the last two months"
assert_equal (2)/3.0, assigns['interpolated_actions_done_this_month'], "none this month and one two the last two months"
# And totals should be calculated
assert_equal 2, assigns['max'], "max of created or completed todos in one month"
end
end
def test_actions_done_last30days_data
login_as(:admin_user)
@current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all
given_todos_for_stats
# When I get the chart data
get :actions_done_last30days_data
assert_response :success
# only tests relevant differences with actions_done_last_12months_data
assert_equal 31, assigns['actions_done_last30days_array'].size, "30 complete days plus 1 for the current day"
assert_equal 2, assigns['max'], "two actions created on one day is max"
end
def test_actions_done_lastyears_data
login_as(:admin_user)
@current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all
given_todos_for_stats
# When I get the chart data
get :actions_done_lastyears_data
assert_response :success
# only tests difference with actions_done_last_12months_data
# Then the count of months should be calculated
assert_equal 27, assigns['month_count'], "two years and three months of last todo"
# And the last two months are corrected
assert_equal 2/3.0, assigns['actions_done_avg_last_months_array'][23]
assert_equal 2/3.0, assigns['actions_done_avg_last_months_array'][24]
end
def test_actions_completion_time_data
login_as(:admin_user)
@current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all
given_todos_for_stats
# When I get the chart data
get :actions_completion_time_data
assert_response :success
# do not test stuff already implicitly tested in other tests
assert_equal 104, assigns['max_weeks'], "two years is 104 weeks (for completed_at)"
assert_equal 3, assigns['max_actions'], "3 completed within one week"
assert_equal 11, assigns['actions_completion_time_array'].size, "there should be 10 weeks of data + 1 for the rest"
assert_equal 1, assigns['actions_completion_time_array'][10], "there is one completed todo after the 10 weeks cut_off"
assert_equal 100.0, assigns['cum_percent_done'][10], "cumulative percentage should add up to 100%"
end
def test_actions_running_time_data
login_as(:admin_user)
@current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all
given_todos_for_stats
# When I get the chart data
get :actions_running_time_data
assert_response :success
# do not test stuff already implicitly tested in other tests
assert_equal 17, assigns['max_weeks'], "there are actions in the first 17 weeks of this year"
assert_equal 2, assigns['max_actions'], "2 actions running long together"
assert_equal 18, assigns['actions_running_time_array'].size, "there should be 17 weeks ( < cut_off) of data + 1 for the rest"
assert_equal 1, assigns['actions_running_time_array'][17], "there is one running todos in week 17 and zero after 17 weeks ( < cut off; ) "
assert_equal 100.0, assigns['cum_percent_done'][17], "cumulative percentage should add up to 100%"
end
def test_actions_open_per_week_data
login_as(:admin_user)
@current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all
given_todos_for_stats
# When I get the chart data
get :actions_open_per_week_data
assert_response :success
# do not test stuff already implicitly tested in other tests
assert_equal 17, assigns['max_weeks'], "there are actions in the first 17 weeks of this year"
assert_equal 4, assigns['max_actions'], "4 actions running together"
assert_equal 17, assigns['actions_open_per_week_array'].size, "there should be 17 weeks ( < cut_off) of data"
end
def test_actions_visible_running_time_data
login_as(:admin_user)
@current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all
given_todos_for_stats
# Given todo1 is deferred (i.e. not visible)
@todo_today1.show_from = Time.zone.now + 1.week
@todo_today1.save
# When I get the chart data
get :actions_visible_running_time_data
assert_response :success
# do not test stuff already implicitly tested in other tests
assert_equal 17, assigns['max_weeks'], "there are actions in the first 17 weeks of this year"
assert_equal 1, assigns['max_actions'], "1 action running long; 1 is deferred"
assert_equal 1, assigns['actions_running_time_array'][0], "there is one running todos and one deferred todo created in week 1"
assert_equal 18, assigns['actions_running_time_array'].size, "there should be 17 weeks ( < cut_off) of data + 1 for the rest"
assert_equal 1, assigns['actions_running_time_array'][17], "there is one running todos in week 17 and zero after 17 weeks ( < cut off; ) "
assert_equal 100.0, assigns['cum_percent_done'][17], "cumulative percentage should add up to 100%"
end
def test_context_total_actions_data
login_as(:admin_user)
@current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all
given_todos_for_stats
# When I get the chart data
get :context_total_actions_data
assert_response :success
assert_equal 9, assigns['data'].sum, "Nine todos in 1 context"
assert_equal 1, assigns['data'].values.size
# Given 10 more todos in 10 different contexts
1.upto(10) do |i|
context = @current_user.contexts.create!(:name => "context #{i}")
@current_user.todos.create!(:description => "created today with new context #{i}", :context => context)
end
# When I get the chart data
get :context_total_actions_data
assert_response :success
assert_equal 19, assigns['data'].sum, "added 10 todos"
assert_equal 10, assigns['data'].values.size, "pie slices limited to max 10"
assert_equal 10, assigns['data'].values[9], "pie slices limited to max 10; last pie contains sum of rest (in percentage)"
assert_equal "(others)", assigns['data'].labels[9], "pie slices limited to max 10; last slice contains label for others"
end
def test_context_running_actions_data
login_as(:admin_user)
@current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all
given_todos_for_stats
# When I get the chart data
get :context_running_actions_data
assert_response :success
assert_equal 4, assigns['data'].sum, "Four todos in 1 context"
assert_equal 1, assigns['data'].values.size
# Given 10 more todos in 10 different contexts
1.upto(10) do |i|
context = @current_user.contexts.create!(:name => "context #{i}")
@current_user.todos.create!(:description => "created today with new context #{i}", :context => context)
end
# When I get the chart data
get :context_running_actions_data
assert_response :success
assert_equal 10, assigns['data'].values.size, "pie slices limited to max 10"
assert_equal 14, assigns['data'].values[9], "pie slices limited to max 10; last pie contains sum of rest (in percentage)"
assert_equal "(others)", assigns['data'].labels[9], "pie slices limited to max 10; last slice contains label for others"
end
def test_actions_day_of_week_all_data
login_as(:admin_user)
@current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all
given_todos_for_stats
# When I get the chart data
get :actions_day_of_week_all_data
assert_response :success
# FIXME: testdata is relative from today, so not stable to test on day_of_week
# trivial not_nil tests
assert_not_nil assigns['max']
assert_not_nil assigns['actions_creation_day_array']
assert_not_nil assigns['actions_completion_day_array']
end
def test_actions_day_of_week_30days_data
login_as(:admin_user)
@current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all
given_todos_for_stats
# When I get the chart data
get :actions_day_of_week_30days_data
assert_response :success
# FIXME: testdata is relative from today, so not stable to test on day_of_week
# trivial not_nil tests
assert_not_nil assigns['max']
assert_not_nil assigns['actions_creation_day_array']
assert_not_nil assigns['actions_completion_day_array']
end
def test_actions_time_of_day_all_data
login_as(:admin_user)
@current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all
given_todos_for_stats
# When I get the chart data
get :actions_time_of_day_all_data
assert_response :success
# FIXME: testdata is relative from today, so not stable to test on day_of_week
# for now just trivial not_nil tests
assert_not_nil assigns['max']
assert_not_nil assigns['actions_creation_hour_array']
assert_not_nil assigns['actions_completion_hour_array']
end
def test_show_selected_actions_from_chart_avrt
login_as(:admin_user)
@current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all
given_todos_for_stats
# When I get the chart data
get :show_selected_actions_from_chart, {:id => "avrt", :index => 1}
assert_response :success
assert_equal false, assigns['further'] # not at end
assert_equal 0, assigns['count']
end
def test_show_selected_actions_from_chart_avrt_end
login_as(:admin_user)
@current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all
given_todos_for_stats
# When I get the chart data
get :show_selected_actions_from_chart, {:id => "avrt_end", :index => 1}
assert_response :success
assert assigns['further'] # at end
assert_equal 2, assigns['count']
end
def test_show_selected_actions_from_chart_art
login_as(:admin_user)
@current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all
given_todos_for_stats
# When I get the chart data
get :show_selected_actions_from_chart, {:id => "art", :index => 1}
assert_response :success
assert_equal false, assigns['further'] # not at end
assert_equal 0, assigns['count']
end
def test_show_selected_actions_from_chart_art_end
login_as(:admin_user)
@current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all
given_todos_for_stats
# When I get the chart data
get :show_selected_actions_from_chart, {:id => "art_end", :index => 1}
assert_response :success
assert assigns['further'] # at end
assert_equal 2, assigns['count']
end
private
def given_todos_for_stats
# Given two todos created today
@todo_today1 = @current_user.todos.create!(:description => "created today1", :context => contexts(:office))
@todo_today2 = @current_user.todos.create!(:description => "created today2", :context => contexts(:office))
# And a todo created a month ago
@todo_month1 = create_completed_todo_in_past(1.month+1.weeks+1.day, 1.month+1.day)
# And a todo created two months ago
@todo_month2 = create_completed_todo_in_past(2.months+2.days, 2.months+1.day)
# And a todo created three months ago
@todo_month3 = create_todo_in_past(3.months+1.day)
# And a todo created four months ago
@todo_month4 = create_todo_in_past(4.months+1.day)
# And a todo created four months ago
@todo_month5 = create_completed_todo_in_past(4.months+2.days, 4.months+1.day)
# And a todo created over a year ago
@todo_year1 = create_completed_todo_in_past(2.years+2.days, 2.years+1.day)
@todo_year2 = create_completed_todo_in_past(2.years+3.months, 2.years+1.day)
end
def create_todo_in_past(creation_time_in_past)
todo = @current_user.todos.create!(:description => "created #{creation_time_in_past} ago", :context => contexts(:office))
todo.created_at = Time.zone.now - creation_time_in_past
todo.save!
return todo
end
def create_completed_todo_in_past(creation_time_in_past, completed_time_in_past)
todo = @current_user.todos.create!(:description => "created #{creation_time_in_past} ago", :context => contexts(:office))
todo.complete!
todo.completed_at = Time.zone.now - completed_time_in_past
todo.created_at = Time.zone.now - creation_time_in_past
todo.save!
return todo
end
# assumes date1 > date2
def difference_in_days(date1, date2)
return ((date1.at_midnight-date2.at_midnight)/(60*60*24)).to_i
end
# assumes date1 > date2
def difference_in_weeks(date1, date2)
return difference_in_days(date1, date2) / 7
end
# assumes date1 > date2
def difference_in_months(date1, date2)
diff = (date1.year - date2.year)*12 + (date1.month - date2.month)
return diff-1 if date1.day - date2.day < 0 # correct for incomplete months
return diff
end
end

View file

@ -0,0 +1,923 @@
require File.expand_path(File.dirname(__FILE__) + '/../test_helper')
class TodosControllerTest < ActionController::TestCase
def test_get_index_when_not_logged_in
get :index
assert_redirected_to login_url
end
############################
# not done / deferred counts
############################
def test_not_done_counts
login_as(:admin_user)
get :index
assert_equal 2, projects(:timemachine).todos.active.count
assert_equal 3, contexts(:call).todos.not_completed.count
assert_equal 1, contexts(:lab).todos.not_completed.count
end
def test_cached_not_done_counts
login_as(:admin_user)
get :index
assert_equal 2, assigns['project_not_done_counts'][projects(:timemachine).id]
assert_equal 3, assigns['context_not_done_counts'][contexts(:call).id]
assert_equal 1, assigns['context_not_done_counts'][contexts(:lab).id]
end
def test_cached_not_done_counts_after_hiding_project
p = Project.find(1)
p.hide!
p.save!
login_as(:admin_user)
get :index
assert_equal nil, assigns['project_not_done_counts'][projects(:timemachine).id]
assert_equal 2, assigns['context_not_done_counts'][contexts(:call).id]
assert_equal nil, assigns['context_not_done_counts'][contexts(:lab).id]
end
def test_not_done_counts_after_hiding_project
p = Project.find(1)
p.hide!
p.save!
login_as(:admin_user)
get :index
assert_equal 0, projects(:timemachine).todos.active.count
assert_equal 2, contexts(:call).todos.active.count
assert_equal 0, contexts(:lab).todos.active.count
end
def test_not_done_counts_after_hiding_and_unhiding_project
p = Project.find(1)
p.hide!
p.save!
p.activate!
p.save!
login_as(:admin_user)
get :index
assert_equal 2, projects(:timemachine).todos.active.count
assert_equal 3, contexts(:call).todos.not_completed.count
assert_equal 1, contexts(:lab).todos.not_completed.count
end
def test_deferred_count_for_project_source_view
login_as(:admin_user)
xhr :post, :toggle_check, :id => 5, :_source_view => 'project'
assert_equal 1, assigns['remaining_deferred_or_pending_count']
xhr :post, :toggle_check, :id => 15, :_source_view => 'project'
assert_equal 0, assigns['remaining_deferred_or_pending_count']
end
#########
# tagging
#########
def test_tag_is_retrieved_properly
login_as(:admin_user)
get :index
t = assigns['not_done_todos'].find{|t| t.id == 2}
assert_equal 1, t.tags.count
assert_equal 'foo', t.tags[0].name
assert !t.starred?
end
def test_tagging_changes_to_tag_with_numbers
# by default has_many_polymorph searches for tags with given id if the tag is a number. we do not want that
login_as(:admin_user)
assert_difference 'Todo.count' do
put :create, :_source_view => 'todo', "context_name"=>"library", "project_name"=>"Build a working time machine", "todo"=>{
"notes"=>"", "description"=>"test tags", "due"=>"30/11/2006"},
"tag_list"=>"1234,5667,9876"
# default has_many_polymorphs will fail on these high numbers as tags with those id's do not exist
end
t = assigns['todo']
assert_equal t.description, "test tags"
assert_equal 3, t.tags.count
end
def test_tagging_changes_to_handle_empty_tags
# by default has_many_polymorph searches for tags with given id if the tag is a number. we do not want that
login_as(:admin_user)
assert_difference 'Todo.count' do
put :create, :_source_view => 'todo', "context_name"=>"library", "project_name"=>"Build a working time machine", "todo"=>{
"notes"=>"", "description"=>"test tags", "due"=>"30/11/2006"},
"tag_list"=>"a,,b"
# default has_many_polymorphs will fail on the empty tag
end
t = assigns['todo']
assert_equal t.description, "test tags"
assert_equal 2, t.tags.count
end
def test_find_tagged_with
login_as(:admin_user)
@user = User.find(@request.session['user_id'])
tag = Tag.where(:name => 'foo').first.taggings
@tagged = tag.count
get :tag, :name => 'foo'
assert_response :success
assert_equal 3, @tagged
end
def test_get_boolean_expression_from_parameters_of_tag_view_single_tag
login_as(:admin_user)
get :tag, :name => "single"
assert_equal true, assigns['single_tag'], "should recognize it is a single tag name"
assert_equal "single", assigns['tag_expr'][0][0], "should store the single tag"
assert_equal "single", assigns['tag_name'], "should store the single tag name"
end
def test_get_boolean_expression_from_parameters_of_tag_view_multiple_tags
login_as(:admin_user)
get :tag, :name => "multiple", :and => "tags", :and1 => "present", :and2 => "here"
assert_equal false, assigns['single_tag'], "should recognize it has multiple tags"
assert_equal 4, assigns['tag_expr'].size, "should have 4 AND expressions"
end
def test_get_boolean_expression_from_parameters_of_tag_view_multiple_tags_without_digitless_and
login_as(:admin_user)
get :tag, :name => "multiple", :and1 => "tags", :and2 => "present", :and3 => "here"
assert_equal false, assigns['single_tag'], "should recognize it has multiple tags"
assert_equal 4, assigns['tag_expr'].size, "should have 4 AND expressions"
end
def test_get_boolean_expression_from_parameters_of_tag_view_multiple_ORs
login_as(:admin_user)
get :tag, :name => "multiple,tags,present"
assert_equal false, assigns['single_tag'], "should recognize it has multiple tags"
assert_equal 1, assigns['tag_expr'].size, "should have 1 expressions"
assert_equal 3, assigns['tag_expr'][0].size, "should have 3 ORs in 1st expression"
end
def test_get_boolean_expression_from_parameters_of_tag_view_multiple_ORs_and_ANDS
login_as(:admin_user)
get :tag, :name => "multiple,tags,present", :and => "here,is,two", :and1=>"and,three"
assert_equal false, assigns['single_tag'], "should recognize it has multiple tags"
assert_equal 3, assigns['tag_expr'].size, "should have 3 expressions"
assert_equal 3, assigns['tag_expr'][0].size, "should have 3 ORs in 1st expression"
assert_equal 3, assigns['tag_expr'][1].size, "should have 3 ORs in 2nd expression"
assert_equal 2, assigns['tag_expr'][2].size, "should have 2 ORs in 3rd expression"
end
def test_set_right_title_tag_page
login_as(:admin_user)
get :tag, :name => "foo"
assert_equal "foo", assigns['tag_title']
get :tag, :name => "foo,bar", :and => "baz"
assert_equal "foo,bar AND baz", assigns['tag_title']
end
def test_set_default_tag
login_as(:admin_user)
get :tag, :name => "foo"
assert_equal "foo", assigns['initial_tags']
get :tag, :name => "foo,bar", :and => "baz"
assert_equal "foo", assigns['initial_tags']
end
###############
# creating todo
###############
def test_create_todo
assert_difference 'Todo.count' do
login_as(:admin_user)
put :create, :_source_view => 'todo', "context_name"=>"library", "project_name"=>"Build a working time machine", "todo"=>{"notes"=>"", "description"=>"Call Warren Buffet to find out how much he makes per day", "due"=>"30/11/2006"}, "tag_list"=>"foo bar"
end
end
def test_create_todo_via_xml
login_as(:admin_user)
assert_difference 'Todo.count' do
put :create, :format => "xml", "request" => { "context_name"=>"library", "project_name"=>"Build a working time machine", "todo"=>{"notes"=>"", "description"=>"Call Warren Buffet to find out how much he makes per day", "due"=>"30/11/2006"}, "tag_list"=>"foo bar" }
assert_response 201
end
end
def test_create_todo_via_xhr
login_as(:admin_user)
assert_difference 'Todo.count' do
xhr :put, :create, "context_name"=>"library", "project_name"=>"Build a working time machine", "todo"=>{"notes"=>"", "description"=>"Call Warren Buffet to find out how much he makes per day", "due"=>"30/11/2006"}, "tag_list"=>"foo bar"
assert_response 200
end
end
def test_fail_to_create_todo_via_xml
login_as(:admin_user)
# try to create with no context, which is not valid
put :create, :format => "xml", "request" => {
"project_name"=>"Build a working time machine",
"todo"=>{"notes"=>"", "description"=>"Call Warren Buffet to find out how much he makes per day", "due"=>"30/11/2006"}, "tag_list"=>"foo bar" }
assert_response 409
assert_xml_select "errors" do
assert_xml_select "error", "Context can't be blank"
end
end
def test_create_deferred_todo
original_todo_count = Todo.count
login_as(:admin_user)
put :create, :_source_view => 'todo', "context_name"=>"library", "project_name"=>"Build a working time machine", "todo"=>{"notes"=>"", "description"=>"Call Warren Buffet to find out how much he makes per day", "due"=>"30/11/2026", 'show_from' => '30/10/2026'}, "tag_list"=>"foo bar"
assert_equal original_todo_count + 1, Todo.count
end
def test_add_multiple_todos
login_as(:admin_user)
start_count = Todo.count
put :create, :_source_view => 'todo', "context_name"=>"library", "project_name"=>"Build a working time machine", "todo"=>{
:multiple_todos=>"a\nb\nmuch \"ado\" about \'nothing\'"}
assert_equal start_count+3, Todo.count, "two todos should have been added"
end
def test_add_multiple_todos_with_validation_error
login_as(:admin_user)
long_string = "a" * 500
start_count = Todo.count
put :create, :_source_view => 'todo', "context_name"=>"library", "project_name"=>"Build a working time machine", "todo"=>{
:multiple_todos=>"a\nb\nmuch \"ado\" about \'nothing\'\n#{long_string}"}
assert_equal start_count, Todo.count, "no todos should have been added"
end
def test_add_multiple_dependent_todos
login_as(:admin_user)
start_count = Todo.count
put :create, :_source_view => 'todo', "context_name"=>"library", "project_name"=>"Build a working time machine", "todo"=>{
:multiple_todos=>"a\nb"}, :todos_sequential => 'true'
put :create, :_source_view => 'todo', "context_name"=>"library", "project_name"=>"Build a working time machine", "todo"=>{
:multiple_todos=>"c\nd"}, :todos_sequential => 'false'
assert_equal start_count+4, Todo.count, "four todos should have been added"
# find a,b,c and d
%w{a b c d}.each do |todo|
eval "@#{todo} = Todo.where(:description => '#{todo}').first"
eval "assert !@#{todo}.nil?, 'a todo with description \"#{todo}\" should just have been added'"
end
assert @b.predecessors.include?(@a), "a should be a predeccesor of b"
assert !@d.predecessors.include?(@c), "c should not be a predecessor of d"
end
#########
# destroy
#########
def test_destroy_todo
login_as(:admin_user)
xhr :post, :destroy, :id => 1, :_source_view => 'todo'
todo = Todo.where(:id=>1).first
assert_nil todo
end
###############
# edit / update
###############
def test_get_edit_form_using_xhr
login_as(:admin_user)
xhr :get, :edit, :id => todos(:call_bill).id
assert_response 200
end
def test_update_todo_project
t = Todo.find(1)
login_as(:admin_user)
xhr :post, :update, :id => 1, :_source_view => 'todo', "context_name"=>"library", "project_name"=>"Build a working time machine", "todo"=>{"id"=>"1", "notes"=>"", "description"=>"Call Warren Buffet to find out how much he makes per day", "due"=>"30/11/2006"}, "tag_list"=>"foo bar"
t = Todo.find(1)
assert_equal 1, t.project_id
end
def test_update_todo_project_to_none
t = Todo.find(1)
login_as(:admin_user)
xhr :post, :update, :id => 1, :_source_view => 'todo', "context_name"=>"library", "project_name"=>"None", "todo"=>{"id"=>"1", "notes"=>"", "description"=>"Call Warren Buffet to find out how much he makes per day", "due"=>"30/11/2006"}, "tag_list"=>"foo bar"
t = Todo.find(1)
assert_nil t.project_id
end
def test_update_todo_to_deferred_is_reflected_in_badge_count
login_as(:admin_user)
get :index
assert_equal 11, assigns['count']
xhr :post, :update, :id => 1, :_source_view => 'todo', "context_name"=>"library", "project_name"=>"Make more money than Billy Gates", "todo"=>{"id"=>"1", "notes"=>"", "description"=>"Call Warren Buffet to find out how much he makes per day", "due"=>"30/11/2006", "show_from"=>"30/11/2030"}, "tag_list"=>"foo bar"
assert_equal 10, assigns['down_count']
end
def test_update_todo
t = Todo.find(1)
login_as(:admin_user)
xhr :post, :update, :id => 1, :_source_view => 'todo', "todo"=>{"context_id"=>"1", "project_id"=>"2", "id"=>"1", "notes"=>"", "description"=>"Call Warren Buffet to find out how much he makes per day", "due"=>"30/11/2006"}, "tag_list"=>"foo, bar"
t = Todo.find(1)
assert_equal "Call Warren Buffet to find out how much he makes per day", t.description
assert_equal "bar, foo", t.tag_list
expected = Date.new(2006,11,30)
actual = t.due.to_date
assert_equal expected, actual, "Expected #{expected.to_s(:db)}, was #{actual.to_s(:db)}"
end
def test_update_todos_with_blank_project_name
t = Todo.find(1)
login_as(:admin_user)
xhr :post, :update, :id => 1, :_source_view => 'todo', :project_name => '', "todo"=>{"id"=>"1", "notes"=>"", "description"=>"Call Warren Buffet to find out how much he makes per day", "due"=>"30/11/2006"}, "tag_list"=>"foo, bar"
t.reload
assert t.project.nil?
end
def test_update_todo_tags_to_none
t = Todo.find(1)
login_as(:admin_user)
xhr :post, :update, :id => 1, :_source_view => 'todo', "todo"=>{"context_id"=>"1", "project_id"=>"2", "id"=>"1", "notes"=>"", "description"=>"Call Warren Buffet to find out how much he makes per day", "due"=>"30/11/2006"}, "tag_list"=>""
t = Todo.find(1)
assert_equal true, t.tag_list.empty?
end
def test_update_todo_tags_with_whitespace_and_dots
t = Todo.find(1)
login_as(:admin_user)
taglist = " one , two,three ,four, 8.1.2, version1.5"
xhr :post, :update, :id => 1, :_source_view => 'todo', "todo"=>{"context_id"=>"1", "project_id"=>"2", "id"=>"1", "notes"=>"", "description"=>"Call Warren Buffet to find out how much he makes per day", "due"=>"30/11/2006"}, "tag_list"=>taglist
t = Todo.find(1)
assert_equal "8.1.2, four, one, three, two, version1.5", t.tag_list
end
def test_removing_hidden_project_activates_todo
login_as(:admin_user)
# get a project and hide it, todos in the project should be hidden
p = projects(:timemachine)
p.hide!
assert p.reload().hidden?
todo = p.todos.first
assert todo.project_hidden?, "todo should be project_hidden"
# clear project from todo: the todo should be unhidden
xhr :post, :update, :id => todo.id, :_source_view => 'todo', "project_name"=>"None", "todo"=>{}
assert assigns['project_changed'], "the project of the todo should be changed"
todo = Todo.find(todo.id) # reload does not seem to work anymore
assert todo.active?, "todo should be active"
end
def test_change_context_of_todo
# called by dragging a todo to another context container
login_as(:admin_user)
todo = users(:admin_user).todos.active.first
context = users(:admin_user).contexts.first
assert_not_equal todo.context.id, context.id
xhr :post, :change_context, :id => todo.id, :todo=>{:context_id => context.id}, :_source_view=>"todo"
assert assigns['context_changed'], "context should have changed"
assert_equal todo.id, assigns['todo'].id, 'correct todo should have been found'
assert_equal context.id, todo.reload.context.id, 'context of todo should be changed'
end
def test_update_clearing_show_from_makes_todo_active
t = Todo.find(1)
t.show_from = "01/01/2030"
assert t.deferred?
login_as(:admin_user)
xhr :post, :update, :id => 1, :_source_view => 'todo', "todo"=>{"show_from"=>""}, "tag_list"=>""
t = Todo.find(1)
assert t.active?
assert_nil t.show_from
end
def test_update_setting_show_from_makes_todo_deferred
t = Todo.find(1)
assert t.active?
login_as(:admin_user)
xhr :post, :update, :id => 1, :_source_view => 'todo', "todo"=>{"show_from"=>"01/01/2030"}, "tag_list"=>""
t = Todo.find(1)
assert t.deferred?
assert_not_nil t.show_from
end
#######
# feeds
#######
def test_rss_feed
login_as(:admin_user)
get :index, { :format => "rss" }
assert_equal 'application/rss+xml', @response.content_type
# puts @response.body
assert_xml_select 'rss[version="2.0"]' do
assert_select 'channel' do
assert_select '>title', 'Tracks Actions'
assert_select '>description', "Actions for #{users(:admin_user).display_name}"
assert_select 'language', 'en-us'
assert_select 'ttl', '40'
assert_select 'item', 17 do
assert_select 'title', /.+/
assert_select 'description', /.*/
assert_select 'link', %r{http://test.host/contexts/.+}
assert_select 'guid', %r{http://test.host/todos/.+}
assert_select 'pubDate', todos(:book).updated_at.to_s(:rfc822)
end
end
end
end
def test_rss_feed_with_limit
login_as(:admin_user)
get :index, { :format => "rss", :limit => '5' }
assert_xml_select 'rss[version="2.0"]' do
assert_select 'channel' do
assert_select '>title', 'Tracks Actions'
assert_select '>description', "Actions for #{users(:admin_user).display_name}"
assert_select 'item', 5 do
assert_select 'title', /.+/
assert_select 'description', /.*/
end
end
end
end
def test_rss_feed_not_accessible_to_anonymous_user_without_token
login_as nil
get :index, { :format => "rss" }
assert_response 401
end
def test_rss_feed_not_accessible_to_anonymous_user_with_invalid_token
login_as nil
get :index, { :format => "rss", :token => 'foo' }
assert_response 401
end
def test_rss_feed_accessible_to_anonymous_user_with_valid_token
login_as nil
get :index, { :format => "rss", :token => users(:admin_user).token }
assert_response :ok
end
def test_atom_feed_content
login_as :admin_user
get :index, { :format => "atom" }
assert_equal 'application/atom+xml', @response.content_type
# #puts @response.body
assert_xml_select 'feed[xmlns="http://www.w3.org/2005/Atom"]' do
assert_xml_select '>title', 'Tracks Actions'
assert_xml_select '>subtitle', "Actions for #{users(:admin_user).display_name}"
assert_xml_select 'entry', 17 do
assert_xml_select 'title', /.+/
assert_xml_select 'content[type="html"]', /.*/
assert_xml_select 'published', /(#{Regexp.escape(todos(:book).updated_at.xmlschema)}|#{Regexp.escape(projects(:moremoney).updated_at.xmlschema)})/
end
end
end
def test_atom_feed_not_accessible_to_anonymous_user_without_token
login_as nil
get :index, { :format => "atom" }
assert_response 401
end
def test_atom_feed_not_accessible_to_anonymous_user_with_invalid_token
login_as nil
get :index, { :format => "atom", :token => 'foo' }
assert_response 401
end
def test_atom_feed_accessible_to_anonymous_user_with_valid_token
login_as nil
get :index, { :format => "atom", :token => users(:admin_user).token }
assert_response :ok
end
def test_text_feed_content
login_as(:admin_user)
get :index, { :format => "txt" }
assert_equal 'text/plain', @response.content_type
assert !(/&nbsp;/.match(@response.body))
# #puts @response.body
end
def test_text_feed_not_accessible_to_anonymous_user_without_token
login_as nil
get :index, { :format => "txt" }
assert_response 401
end
def test_text_feed_not_accessible_to_anonymous_user_with_invalid_token
login_as nil
get :index, { :format => "txt", :token => 'foo' }
assert_response 401
end
def test_text_feed_accessible_to_anonymous_user_with_valid_token
login_as nil
get :index, { :format => "txt", :token => users(:admin_user).token }
assert_response :ok
end
def test_ical_feed_content
login_as :admin_user
get :index, { :format => "ics" }
assert_equal 'text/calendar', @response.content_type
assert !(/&nbsp;/.match(@response.body))
# #puts @response.body
end
def test_tag_text_feed_not_accessible_to_anonymous_user_without_token
login_as nil
get :tag, {:name => "foo", :format => "txt" }
assert_response 401
end
##############
# mobile index
##############
def test_mobile_index_uses_text_html_content_type
login_as(:admin_user)
get :index, { :format => "m" }
assert_equal 'text/html', @response.content_type
end
def test_mobile_index_assigns_down_count
login_as(:admin_user)
get :index, { :format => "m" }
assert_equal 11, assigns['down_count']
end
def test_mobile_redirect_to_login
get :index, { :format => "m" }
assert_redirected_to login_url(:format => "m")
end
###############
# mobile create
###############
def test_mobile_create_action_creates_a_new_todo
login_as(:admin_user)
post :create, {"format"=>"m", "todo"=>{"context_id"=>"2",
"due(1i)"=>"2007", "due(2i)"=>"1", "due(3i)"=>"2",
"show_from(1i)"=>"", "show_from(2i)"=>"", "show_from(3i)"=>"",
"project_id"=>"1",
"notes"=>"test notes", "description"=>"test_mobile_create_action"}}
t = Todo.where(:description => "test_mobile_create_action").first
assert_not_nil t
assert_equal 2, t.context_id
assert_equal 1, t.project_id
assert t.active?
assert_equal 'test notes', t.notes
assert_nil t.show_from
assert_equal Date.new(2007,1,2), t.due.to_date
end
def test_mobile_create_action_redirects_to_mobile_home_page_when_successful
login_as(:admin_user)
post :create, {"format"=>"m", "todo"=>{"context_id"=>"2",
"due(1i)"=>"2007", "due(2i)"=>"1", "due(3i)"=>"2",
"show_from(1i)"=>"", "show_from(2i)"=>"", "show_from(3i)"=>"",
"project_id"=>"1",
"notes"=>"test notes", "description"=>"test_mobile_create_action", "state"=>"0"}}
assert_redirected_to '/mobile'
end
def test_mobile_create_action_renders_new_template_when_save_fails
login_as(:admin_user)
post :create, {"format"=>"m", "todo"=>{"context_id"=>"2",
"due(1i)"=>"2007", "due(2i)"=>"1", "due(3i)"=>"2",
"show_from(1i)"=>"", "show_from(2i)"=>"", "show_from(3i)"=>"",
"project_id"=>"1",
"notes"=>"test notes"}, "tag_list"=>"test, test2"}
assert_template 'todos/new'
end
################
# recurring todo
################
def test_toggle_check_on_recurring_todo
login_as(:admin_user)
# link todo_1 and recurring_todo_1
recurring_todo_1 = RecurringTodo.find(1)
todo_1 = Todo.where(:recurring_todo_id => 1).first
# mark todo_1 as complete by toggle_check
xhr :post, :toggle_check, :id => todo_1.id, :_source_view => 'todo'
todo_1.reload
assert todo_1.completed?
# check that there is only one active todo belonging to recurring_todo
count = Todo.count(:all, :conditions => {:recurring_todo_id => recurring_todo_1.id, :state => 'active'})
assert_equal 1, count
# check there is a new todo linked to the recurring pattern
next_todo = Todo.find(:first, :conditions => {:recurring_todo_id => recurring_todo_1.id, :state => 'active'})
assert_equal "Call Bill Gates every day", next_todo.description
# check that the new todo is not the same as todo_1
assert_not_equal todo_1.id, next_todo.id
# change recurrence pattern to monthly and set show_from 2 days before due
# date this forces the next todo to be put in the tickler
recurring_todo_1.show_from_delta = 2
recurring_todo_1.show_always = 0
recurring_todo_1.target = 'due_date'
recurring_todo_1.recurring_period = 'monthly'
recurring_todo_1.recurrence_selector = 0
recurring_todo_1.every_other1 = 1
recurring_todo_1.every_other2 = 2
recurring_todo_1.every_other3 = 5
# use assert to catch validation errors if present. we need to replace
# this with a good factory implementation
assert recurring_todo_1.save
# mark next_todo as complete by toggle_check
xhr :post, :toggle_check, :id => next_todo.id, :_source_view => 'todo'
next_todo.reload
assert next_todo.completed?
# check that there are three todos belonging to recurring_todo: two
# completed and one deferred
count = Todo.count(:all, :conditions => {:recurring_todo_id => recurring_todo_1.id})
assert_equal 3, count
# check there is a new todo linked to the recurring pattern in the tickler
next_todo = Todo.find(:first, :conditions => {:recurring_todo_id => recurring_todo_1.id, :state => 'deferred'})
assert !next_todo.nil?
assert_equal "Call Bill Gates every day", next_todo.description
# check that the todo is in the tickler
assert !next_todo.show_from.nil?
end
def test_toggle_check_on_rec_todo_show_from_today
login_as(:admin_user)
# link todo_1 and recurring_todo_1
recurring_todo_1 = RecurringTodo.find(1)
#set_user_to_current_time_zone(recurring_todo_1.user)
todo_1 = Todo.where(:recurring_todo_id => 1).first
today = Time.zone.now.at_midnight
# change recurrence pattern to monthly and set show_from to today
recurring_todo_1.target = 'show_from_date'
recurring_todo_1.recurring_period = 'monthly'
recurring_todo_1.recurrence_selector = 0
recurring_todo_1.every_other1 = today.day
recurring_todo_1.every_other2 = 1
assert recurring_todo_1.save
# mark todo_1 as complete by toggle_check, this gets rid of todo_1 that was
# not correctly created from the adjusted recurring pattern we defined
# above.
xhr :post, :toggle_check, :id => todo_1.id, :_source_view => 'todo'
todo_1.reload
assert todo_1.completed?
# locate the new todo. This todo is created from the adjusted recurring
# pattern defined in this test
new_todo = Todo.where(:recurring_todo_id => recurring_todo_1.id, :state => 'active').first
assert !new_todo.nil?
# mark new_todo as complete by toggle_check
xhr :post, :toggle_check, :id => new_todo.id, :_source_view => 'todo'
new_todo.reload
assert todo_1.completed?
# locate the new todo in tickler
new_todo = Todo.where(:recurring_todo_id => recurring_todo_1.id, :state => 'deferred').first
assert !new_todo.nil?
assert_equal "Call Bill Gates every day", new_todo.description
# check that the new todo is not the same as todo_1
assert_not_equal todo_1.id, new_todo.id
# check that the new_todo is in the tickler to show next month
assert !new_todo.show_from.nil?
# do not use today here. It somehow gets messed up with the timezone calculation.
next_month = (Time.zone.now + 1.month).at_midnight
assert_equal next_month.utc.to_date.to_s(:db), new_todo.show_from.utc.to_date.to_s(:db)
end
def test_check_for_next_todo
login_as :admin_user
recurring_todo_1 = RecurringTodo.find(5)
@todo = Todo.where(:recurring_todo_id => 1).first
assert @todo.from_recurring_todo?
# rewire @todo to yearly recurring todo
@todo.recurring_todo_id = 5
# make todo due tomorrow and change recurring date also to tomorrow
@todo.due = Time.zone.now + 1.day
@todo.save
recurring_todo_1.every_other1 = @todo.due.day
recurring_todo_1.every_other2 = @todo.due.month
recurring_todo_1.save
# mark todo complete
xhr :post, :toggle_check, :id => @todo.id, :_source_view => 'todo'
@todo = Todo.find(@todo.id) #reload does not seem to work anymore
assert @todo.completed?
# check that there is no active todo
next_todo = Todo.where(:recurring_todo_id => recurring_todo_1.id, :state => 'active').first
assert next_todo.nil?
# check for new deferred todo
next_todo = Todo.where(:recurring_todo_id => recurring_todo_1.id, :state => 'deferred').first
assert !next_todo.nil?
# check that the due date of the new todo is later than tomorrow
assert next_todo.due > @todo.due
end
############
# todo notes
############
def test_url_with_slash_in_query_string_are_parsed_correctly
# See http://blog.swivel.com/code/2009/06/rails-auto_link-and-certain-query-strings.html
login_as(:admin_user)
todo = users(:admin_user).todos.first
url = "http://example.com/foo?bar=/baz"
todo.notes = "foo #{url} bar"
todo.save!
get :index
assert_select("a[href=#{url}]")
end
def test_format_note_normal
login_as(:admin_user)
todo = users(:admin_user).todos.first
todo.notes = "A normal description."
todo.save!
get :index
assert_select("div#notes_todo_#{todo.id}", "A normal description.")
end
def test_format_note_textile
login_as(:admin_user)
todo = users(:admin_user).todos.first
todo.notes = "A *bold description*."
todo.save!
get :index
assert_select("div#notes_todo_#{todo.id}", "A bold description.")
assert_select("div#notes_todo_#{todo.id} strong", "bold description")
end
def test_format_note_link
login_as(:admin_user)
todo = users(:admin_user).todos.first
todo.notes = "A link to http://github.com/."
todo.save!
get :index
assert_select("div#notes_todo_#{todo.id}", 'A link to http://github.com/.')
assert_select("div#notes_todo_#{todo.id} a[href=http://github.com/]", 'http://github.com/')
end
def test_format_note_link_message
login_as(:admin_user)
todo = users(:admin_user).todos.first
todo.raw_notes = "A Mail.app message://<ABCDEF-GHADB-123455-FOO-BAR@example.com> link"
todo.save!
get :index
assert_select("div#notes_todo_#{todo.id}", 'A Mail.app message://&lt;ABCDEF-GHADB-123455-FOO-BAR@example.com&gt; link')
assert_select("div#notes_todo_#{todo.id} a", 'message://&lt;ABCDEF-GHADB-123455-FOO-BAR@example.com&gt;')
assert_select("div#notes_todo_#{todo.id} a[href=message://&lt;ABCDEF-GHADB-123455-FOO-BAR@example.com&gt;]", 'message://&lt;ABCDEF-GHADB-123455-FOO-BAR@example.com&gt;')
end
def test_format_note_link_onenote
login_as(:admin_user)
todo = users(:admin_user).todos.first
todo.notes = ' "link me to onenote":onenote:///E:\OneNote\dir\notes.one#PAGE&section-id={FD597D3A-3793-495F-8345-23D34A00DD3B}&page-id={1C95A1C7-6408-4804-B3B5-96C28426022B}&end'
todo.save!
get :index
assert_select("div#notes_todo_#{todo.id}", 'link me to onenote')
assert_select("div#notes_todo_#{todo.id} a", 'link me to onenote')
assert_select("div#notes_todo_#{todo.id} a[href=onenote:///E:%5COneNote%5Cdir%5Cnotes.one#PAGE&amp;section-id=%7BFD597D3A-3793-495F-8345-23D34A00DD3B%7D&amp;page-id=%7B1C95A1C7-6408-4804-B3B5-96C28426022B%7D&amp;end]", 'link me to onenote')
end
##############
# dependencies
##############
def test_make_todo_dependent
login_as(:admin_user)
predecessor = todos(:call_bill)
successor = todos(:call_dino_ext)
# no predecessors yet
assert_equal 0, successor.predecessors.size
# add predecessor
put :add_predecessor, :predecessor=>predecessor.id, :successor=>successor.id
assert_equal 1, successor.predecessors.count
assert_equal predecessor.id, successor.predecessors.first.id
end
def test_make_todo_with_dependencies_dependent
login_as(:admin_user)
predecessor = todos(:call_bill)
successor = todos(:call_dino_ext)
other_todo = todos(:phone_grandfather)
# predecessor -> successor
put :add_predecessor, :predecessor=>predecessor.id, :successor=>successor.id
# other_todo -> predecessor -> successor
put :add_predecessor, :predecessor=>other_todo.id, :successor=>predecessor.id
assert_equal 1, successor.predecessors(true).count
assert_equal 0, other_todo.predecessors(true).count
assert_equal 1, predecessor.predecessors(true).count
assert_equal predecessor.id, successor.predecessors.first.id
assert_equal other_todo.id, predecessor.predecessors.first.id
end
def test_mingle_dependent_todos_leave
# based on #1271
login_as(:admin_user)
t1 = todos(:call_bill)
t2 = todos(:call_dino_ext)
t3 = todos(:phone_grandfather)
t4 = todos(:construct_dilation_device)
# t1 -> t2
put :add_predecessor, :predecessor=>t1.id, :successor=>t2.id
# t3 -> t4
put :add_predecessor, :predecessor=>t3.id, :successor=>t4.id
# t2 -> t4
put :add_predecessor, :predecessor=>t2.id, :successor=>t4.id
# should be: t1 -> t2 -> t4 and t3 -> t4
assert t4.predecessors.map(&:id).include?(t2.id)
assert t4.predecessors.map(&:id).include?(t3.id)
assert t2.predecessors.map(&:id).include?(t1.id)
end
def test_mingle_dependent_todos_root
# based on #1271
login_as(:admin_user)
t1 = todos(:call_bill)
t2 = todos(:call_dino_ext)
t3 = todos(:phone_grandfather)
t4 = todos(:construct_dilation_device)
# t1 -> t2
put :add_predecessor, :predecessor=>t1.id, :successor=>t2.id
# t3 -> t4
put :add_predecessor, :predecessor=>t3.id, :successor=>t4.id
# t3 -> t2
put :add_predecessor, :predecessor=>t3.id, :successor=>t2.id
# should be: t1 -> t2 and t3 -> t4 & t2
assert t3.successors.map(&:id).include?(t4.id)
assert t3.successors.map(&:id).include?(t2.id)
assert t2.predecessors.map(&:id).include?(t1.id)
assert t2.predecessors.map(&:id).include?(t3.id)
end
def test_unmingle_dependent_todos
# based on #1271
login_as(:admin_user)
t1 = todos(:call_bill)
t2 = todos(:call_dino_ext)
t3 = todos(:phone_grandfather)
t4 = todos(:construct_dilation_device)
# create same dependency tree as previous test
# should be: t1 -> t2 -> t4 and t3 -> t4
put :add_predecessor, :predecessor=>t1.id, :successor=>t2.id
put :add_predecessor, :predecessor=>t3.id, :successor=>t4.id
put :add_predecessor, :predecessor=>t2.id, :successor=>t4.id
# removing t4 as successor of t2 should leave t4 blocked with t3 as predecessor
put :remove_predecessor, :predecessor=>t2.id, :id=>t4.id
t4.reload
assert t4.pending?, "t4 should remain pending"
assert t4.predecessors.map(&:id).include?(t3.id)
end
end

View file

@ -0,0 +1,179 @@
require File.expand_path(File.dirname(__FILE__) + '/../test_helper')
class UsersControllerTest < ActionController::TestCase
def test_get_index_when_not_logged_in
get :index
assert_redirected_to login_path
end
def test_get_index_by_nonadmin
login_as :other_user
get :index
assert_response 401
end
def test_get_index_by_admin
login_as :admin_user
get :index
assert_response :success
assert_equal "TRACKS::Manage Users", assigns['page_title']
assert_equal 5, assigns['total_users']
assert_equal users_url, session['return-to']
end
def test_index_pagination_page_1
User.per_page = 1
login_as :admin_user
get :index
assert_equal assigns['users'],[User.where(:login => 'admin').first]
end
def test_index_pagination_page_2
User.per_page = 1
login_as :admin_user
get :index, :page => 2
assert_equal assigns['users'],[User.where(:login => 'jane').first]
end
def test_destroy_user
login_as :admin_user
@no_users_before = User.find(:all).size
user_id = users(:ldap_user).id
xhr :post, :destroy, :id => user_id.to_param
assert_equal @no_users_before-1, User.find(:all).size
end
def test_update_password_successful
get :change_password, :id => users(:admin_user).id
# should fail because no login
assert_redirected_to login_path
login_as :admin_user
@user = @request.session['user_id']
get :change_password, :id => users(:admin_user).id # should now pass because we're logged in
assert_response :success
assert_equal assigns['page_title'], "TRACKS::Change password"
post :update_password, :id => users(:admin_user).id, :user => {:password => 'newpassword', :password_confirmation => 'newpassword'}
assert_redirected_to preferences_path
@updated_user = User.find(users(:admin_user).id)
assert_not_nil User.authenticate(@updated_user.login, 'newpassword')
assert_equal "Password updated.", flash[:notice]
end
def test_update_password_no_confirmation
post :update_password, :id => users(:admin_user).id, :user => {:password => 'newpassword', :password_confirmation => 'wrong'}
# should fail because no login
assert_redirected_to login_path
login_as :admin_user
post :update_password, :id => users(:admin_user).id, :user => {:password => 'newpassword', :password_confirmation => 'wrong'}
assert_redirected_to change_password_user_path(users(:admin_user))
assert_equal 'Validation failed: Password doesn\'t match confirmation', flash[:error]
end
def test_update_password_validation_errors
post :update_password, :id => users(:admin_user).id
# should fail because no login
assert_redirected_to login_path
login_as :admin_user
post :update_password, :id => users(:admin_user).id, :user => {:password => 'ba', :password_confirmation => 'ba'}
assert_redirected_to change_password_user_path(User.find(users(:admin_user).id))
# For some reason, no errors are being raised now.
#assert_equal 1, users(:admin_user).errors.count
#assert_equal users(:admin_user).errors.on(:password), "is too short (min is 5 characters)"
assert_equal 'Validation failed: Password is too short (minimum is 5 characters)', flash[:error]
end
# ============================================
# Signup and creation of new users
# ============================================
def test_with_no_users
User.expects(:no_users_yet?).returns(true)
get :new
assert_match /get started/, assigns['heading']
assert_not_nil assigns[:user]
end
def test_create_adds_a_new_nonadmin_user
login_as :admin_user
post :create, :user => {:login => 'newbie', :password => 'newbiepass', :password_confirmation => 'newbiepass'}
newbie = User.where(:login => 'newbie').first
assert_equal newbie.login, "newbie"
assert newbie.is_admin == false || newbie.is_admin == 0
assert_not_nil newbie.preference # have user preferences been created?
assert_not_nil User.authenticate('newbie', 'newbiepass')
end
def test_create_redirects_to_home_page
login_as :admin_user
post :create, :user => {:login => 'newbie', :password => 'newbiepass', :password_confirmation => 'newbiepass'}
assert_redirected_to root_url
end
def test_create_sets_flash_message
login_as :admin_user
post :create, :user => {:login => 'newbie', :password => 'newbiepass', :password_confirmation => 'newbiepass'}
assert_equal "Signup successful for user newbie.", flash[:notice], "expected flash notice not found"
end
def test_create_adds_a_user
login_as :admin_user
assert_difference 'User.count' do
post :create, :user => {:login => 'newbie', :password => 'newbiepass', :password_confirmation => 'newbiepass'}
end
end
# Test whether signup of new users is denied to a non-admin user
#
def test_create_by_non_admin
login_as :other_user
assert_no_difference 'User.count' do
post :create, :user => {:login => 'newbie2', :password => 'newbiepass2', :password_confirmation => 'newbiepass2'}
end
assert_response :success
assert_template 'users/nosignup'
end
# ============================================
# Test validations
# ============================================
def test_create_with_invalid_password_does_not_add_a_new_user
login_as :admin_user
assert_no_difference 'User.count' do
post :create, :user => {:login => 'newbie', :password => '', :password_confirmation => ''}
end
end
def test_create_with_invalid_password_redirects_to_new_user_page
login_as :admin_user
post :create, :user => {:login => 'newbie', :password => '', :password_confirmation => ''}
assert_redirected_to signup_path
end
def test_create_with_invalid_login_does_not_add_a_new_user
login_as :admin_user
post :create, :user => {:login => 'n', :password => 'newbiepass', :password_confirmation => 'newbiepass'}
assert_redirected_to signup_path
end
def test_create_with_invalid_login_redirects_to_new_user_page
login_as :admin_user
post :create, :user => {:login => 'n', :password => 'newbiepass', :password_confirmation => 'newbiepass'}
assert_redirected_to signup_path
end
def test_create_with_duplicate_login_does_not_add_a_new_user
login_as :admin_user
assert_no_difference 'User.count' do
post :create, :user => {:login => 'jane', :password => 'newbiepass', :password_confirmation => 'newbiepass'}
end
end
def test_create_with_duplicate_login_redirects_to_new_user_page
login_as :admin_user
post :create, :user => {:login => 'jane', :password => 'newbiepass', :password_confirmation => 'newbiepass'}
assert_redirected_to signup_path
end
end