This fixes failing tests when the timezone is different than utc

There were several problems:
* Time.now returns the systems time, not the users time
* fixtures do not translate dates from timezone to utc, but stores the
  date verbatim
* calling a controller will set the timezone to the preference of the
  current_user. So it could be changed while you do not realize this. I
  fixed the failing test, but problems could be elsewhere
This commit is contained in:
Reinier Balt 2015-08-04 23:08:13 +02:00
parent 0b44fe3f08
commit e58379e81f
27 changed files with 221 additions and 214 deletions

View file

@ -1071,10 +1071,10 @@ end
if recurring_todo.todos.active.count == 0 if recurring_todo.todos.active.count == 0
# check for next todo either from the due date or the show_from date # check for next todo either from the due date or the show_from date
date_to_check = todo.due.nil? ? todo.show_from : todo.due date_to_check = todo.due || todo.show_from
# if both due and show_from are nil, check for a next todo from now # if both due and show_from are nil, check for a next todo from now
date_to_check = Time.zone.now if date_to_check.nil? date_to_check ||= Time.zone.now
if recurring_todo.active? && recurring_todo.continues_recurring?(date_to_check) if recurring_todo.active? && recurring_todo.continues_recurring?(date_to_check)
@ -1087,7 +1087,7 @@ end
# for tomorrow. # for tomorrow.
date = date_to_check.at_midnight >= Time.zone.now.at_midnight ? date_to_check : Time.zone.now-1.day date = date_to_check.at_midnight >= Time.zone.now.at_midnight ? date_to_check : Time.zone.now-1.day
new_recurring_todo = TodoFromRecurringTodo.new(current_user, recurring_todo).create(date.at_midnight) new_recurring_todo = TodoFromRecurringTodo.new(current_user, recurring_todo).create(date)
end end
end end
end end

View file

@ -5,7 +5,7 @@ module StatsHelper
end end
def month_and_year_label(i) def month_and_year_label(i)
t('date.month_names')[ (Time.now.mon - i -1 ) % 12 + 1 ]+ " " + (Time.now - i.months).year.to_s t('date.month_names')[ (Time.zone.now.mon - i -1 ) % 12 + 1 ]+ " " + (Time.zone.now - i.months).year.to_s
end end
def array_of_month_and_year_labels(count) def array_of_month_and_year_labels(count)
@ -13,7 +13,7 @@ module StatsHelper
end end
def month_label(i) def month_label(i)
t('date.month_names')[ (Time.now.mon - i -1 ) % 12 + 1 ] t('date.month_names')[ (Time.zone.now.mon - i -1 ) % 12 + 1 ]
end end
def array_of_month_labels(count) def array_of_month_labels(count)

View file

@ -151,7 +151,7 @@ module RecurringTodos
end end
def get_next_date(previous) def get_next_date(previous)
raise "Should not call AbstractRecurrencePattern.get_next_date directly. Overwrite in subclass" raise "Should not call AbstractRecurrencePattern.get_next_date directly. Override in subclass"
end end
def continues_recurring?(previous) def continues_recurring?(previous)
@ -174,13 +174,13 @@ module RecurringTodos
# same day as the previous # same day as the previous
def determine_start(previous, offset=0.day) def determine_start(previous, offset=0.day)
start = self.start_from || NullTime.new start = self.start_from || NullTime.new
now = Time.zone.now
if previous if previous
# check if the start_from date is later than previous. If so, use # check if the start_from date is later than previous. If so, use
# start_from as start to search for next date # start_from as start to search for next date
start > previous ? start : previous + offset start > previous ? start : previous + offset
else else
# skip to present # skip to present
now = Time.zone.now
start > now ? start : now start > now ? start : now
end end
end end
@ -199,32 +199,24 @@ module RecurringTodos
end end
def find_last_day_x_of_month(weekday, month, year) def find_last_day_x_of_month(weekday, month, year)
# count backwards. use UTC to avoid strange timezone oddities last_day = Time.zone.local(year, month, Time.days_in_month(month))
# where last_day -= 1.day seems to shift tz+0100 to tz+0000
last_day = Time.utc(year, month, Time.days_in_month(month))
while last_day.wday != weekday while last_day.wday != weekday
last_day -= 1.day last_day -= 1.day
end end
# convert back to local timezone last_day
Time.zone.local(last_day.year, last_day.month, last_day.day)
end end
def find_xth_day_of_month(x, weekday, month, year) def find_xth_day_of_month(x, weekday, month, year)
# 1-4th -> count upwards last -> count backwards. use UTC to avoid strange start = Time.zone.local(year,month,1)
# timezone oddities where last_day -= 1.day seems to shift tz+0100 to
# tz+0000
start = Time.utc(year,month,1)
n = x n = x
while n > 0 while n > 0
while start.wday() != weekday while start.wday() != weekday
start+= 1.day start += 1.day
end end
n -= 1 n -= 1
start+= 1.day unless n==0 start += 1.day unless n==0
end end
# convert back to local timezone start
Time.zone.local(start.year, start.month, start.day)
end end
end end
end end

View file

@ -82,18 +82,9 @@ module RecurringTodos
def find_specific_day_of_month(previous, start, n) def find_specific_day_of_month(previous, start, n)
if (previous && start.mday >= every_x_day) || (previous.nil? && start.mday > every_x_day) if (previous && start.mday >= every_x_day) || (previous.nil? && start.mday > every_x_day)
# there is no next day n in this month, search in next month # there is no next day n in this month, search in next month
# start += n.months
# start += n.months
#
# The above seems to not work. Fiddle with timezone. Looks like we hit a
# bug in rails here where 2008-12-01 +0100 plus 1.month becomes
# 2008-12-31 +0100. For now, just calculate in UTC and convert back to
# local timezone.
#
# TODO: recheck if future rails versions have this problem too
start = Time.utc(start.year, start.month, start.day)+n.months
end end
Time.zone.local(start.year, start.month, every_x_day) start.in_time_zone.change(day: every_x_day)
end end
def find_relative_day_of_month(start, n) def find_relative_day_of_month(start, n)
@ -101,13 +92,7 @@ module RecurringTodos
if the_next.nil? || the_next <= start if the_next.nil? || the_next <= start
# the nth day is already passed in this month, go to next month and try # the nth day is already passed in this month, go to next month and try
# again # again
the_next += n.months
# fiddle with timezone. Looks like we hit a bug in rails here where
# 2008-12-01 +0100 plus 1.month becomes 2008-12-31 +0100. For now, just
# calculate in UTC and convert back to local timezone.
# TODO: recheck if future rails versions have this problem too
the_next = Time.utc(the_next.year, the_next.month, the_next.day)+n.months
the_next = Time.zone.local(the_next.year, the_next.month, the_next.day)
# TODO: if there is still no match, start will be set to nil. if we ever # TODO: if there is still no match, start will be set to nil. if we ever
# support 5th day of the month, we need to handle this case # support 5th day of the month, we need to handle this case
@ -136,7 +121,5 @@ module RecurringTodos
day: day_of_week_as_text(day_of_week), day: day_of_week_as_text(day_of_week),
n_months: n_months) n_months: n_months)
end end
end end
end end

View file

@ -19,7 +19,7 @@ module Stats
end end
def first_action_at def first_action_at
first_action.created_at if first_action first_action.try(:created_at)
end end
def projects def projects

View file

@ -40,7 +40,7 @@
<% if @count -%> <% if @count -%>
<span id="badge_count" class="badge"><%= @count %></span> <span id="badge_count" class="badge"><%= @count %></span>
<% end -%> <% end -%>
<%= l(Date.today, :format => current_user.prefs.title_date_format) %> <%= l(Time.zone.today, :format => current_user.prefs.title_date_format) %>
</h1> </h1>
</div> </div>
<div id="minilinks"> <div id="minilinks">

View file

@ -16,7 +16,7 @@
</head><body> </head><body>
<% if current_user && !current_user.prefs.nil? -%> <% if current_user && !current_user.prefs.nil? -%>
<div id="topbar"><h1><% if @down_count -%><span class="count" id="badge_count"><%= @down_count %></span><% end -%> <%= <div id="topbar"><h1><% if @down_count -%><span class="count" id="badge_count"><%= @down_count %></span><% end -%> <%=
l(Date.today, :format => current_user.prefs.title_date_format) -%></h1> l(Time.zone.today, :format => current_user.prefs.title_date_format) -%></h1>
<ul class="nav"> <ul class="nav">
<li class="link"><%= (link_to(t('layouts.mobile_navigation.new_action'), new_todo_path(new_todo_params))) -%></li> <li class="link"><%= (link_to(t('layouts.mobile_navigation.new_action'), new_todo_path(new_todo_params))) -%></li>
<li class="link"><%= (link_to(t('layouts.mobile_navigation.home'), todos_path(:format => 'm'))) -%></li> <li class="link"><%= (link_to(t('layouts.mobile_navigation.home'), todos_path(:format => 'm'))) -%></li>

View file

@ -1,23 +1,22 @@
<%= pref_with_text_field('prefs', 'date_format') %> <%= pref_with_text_field('prefs', 'date_format') %>
<div class='prefs_example'>This will result in: <span id='prefs.date_format'><%= l(Date.today, :format => current_user.prefs.date_format) %></span></div> <div class='prefs_example'>This will result in: <span id='prefs.date_format'><%= l(Time.zone.today, :format => current_user.prefs.date_format) %></span></div>
<br/> <br/>
Or pick one of the following:<br/> Or pick one of the following:<br/>
<% %w{default short long longer}.each do |format| %> <% %w{default short long longer}.each do |format| %>
<%= radio_button_tag("date_picker1", t("date.formats.#{format}")) %> <%= l(Date.today, :format => format.to_sym) %> <br/> <%= radio_button_tag("date_picker1", t("date.formats.#{format}")) %> <%= l(Time.zone.today, :format => format.to_sym) %> <br/>
<% end %> <% end %>
<br/> <br/>
<%= pref_with_text_field('prefs', 'title_date_format') %> <%= pref_with_text_field('prefs', 'title_date_format') %>
<div class='prefs_example'>This will result in: <span id='prefs.title_date_format'><%= l(Date.today, :format => current_user.prefs.title_date_format) %></span></div> <div class='prefs_example'>This will result in: <span id='prefs.title_date_format'><%= l(Time.zone.today, :format => current_user.prefs.title_date_format) %></span></div>
<br/> <br/>
Or pick one of the following:<br/> Or pick one of the following:<br/>
<% %w{default short long longer}.each do |format| %> <% %w{default short long longer}.each do |format| %>
<%= radio_button_tag("date_picker2", t("date.formats.#{format}")) %> <%= l(Date.today, :format => format.to_sym) %> <br/> <%= radio_button_tag("date_picker2", t("date.formats.#{format}")) %> <%= l(Time.zone.today, :format => format.to_sym) %> <br/>
<% end %> <% end %>
<br/> <br/>
<%= pref('prefs', 'time_zone') { time_zone_select('prefs','time_zone') } %> <%= pref('prefs', 'time_zone') { time_zone_select('prefs','time_zone') } %>
<%= pref_with_select_field('prefs', "week_starts", (0..6).to_a.map {|num| [t('date.day_names')[num], num] }) %> <%= pref_with_select_field('prefs', "week_starts", (0..6).to_a.map {|num| [t('date.day_names')[num], num] }) %>

View file

@ -30,10 +30,10 @@ module Tracksapp
# configure Tracks to handle deployment in a subdir # configure Tracks to handle deployment in a subdir
config.relative_url_root = SITE_CONFIG['subdir'] if SITE_CONFIG['subdir'] config.relative_url_root = SITE_CONFIG['subdir'] if SITE_CONFIG['subdir']
# allow onenote:// and message:// as protocols for urls # allow onenote:// and message:// as protocols for urls
config.action_view.sanitized_allowed_protocols = 'onenote', 'message' config.action_view.sanitized_allowed_protocols = 'onenote', 'message'
config.middleware.insert_after ActionDispatch::ParamsParser, ActionDispatch::XmlParamsParser config.middleware.insert_after ActionDispatch::ParamsParser, ActionDispatch::XmlParamsParser
end end
end end

View file

@ -34,8 +34,6 @@ Rails.application.configure do
# Print deprecation notices to the stderr. # Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr config.active_support.deprecation = :stderr
config.time_zone = 'UTC'
# Raises error for missing translations # Raises error for missing translations
# config.action_view.raise_on_missing_translations = true # config.action_view.raise_on_missing_translations = true
end end

View file

@ -27,7 +27,7 @@ class TodoFromRecurringTodo
end end
def end_date def end_date
todo.due ? todo.due : todo.show_from todo.due || todo.show_from
end end
def attributes def attributes

View file

@ -184,7 +184,7 @@ class RecurringTodosControllerTest < ActionController::TestCase
# mark as active # mark as active
xhr :post, :toggle_check, :id=>1, :_source_view=>"" xhr :post, :toggle_check, :id=>1, :_source_view=>""
recurring_todo_1 = RecurringTodo.find(1) # reload seems to not work 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}" assert recurring_todo_1.active?, "recurring todo should be active but is #{recurring_todo_1.aasm.current_state}"
@ -203,7 +203,7 @@ class RecurringTodosControllerTest < ActionController::TestCase
# change due date in four days from now and show from 10 days before, i.e. 6 # change due date in four days from now and show from 10 days before, i.e. 6
# days ago # days ago
target_date = Time.now.utc + 4.days target_date = Time.zone.now + 4.days
@yearly.every_other1 = target_date.day @yearly.every_other1 = target_date.day
@yearly.every_other2 = target_date.month @yearly.every_other2 = target_date.month
@yearly.show_from_delta = 10 @yearly.show_from_delta = 10
@ -260,7 +260,7 @@ class RecurringTodosControllerTest < ActionController::TestCase
"recurring_show_days_before"=>"0", "recurring_show_days_before"=>"0",
"recurring_target"=>"due_date", "recurring_target"=>"due_date",
"recurring_show_always" => "1", "recurring_show_always" => "1",
"start_from"=>"1/10/2012", "start_from"=>"1/10/2012",
"weekly_every_x_week"=>"1", "weekly_every_x_week"=>"1",
"weekly_return_monday"=>"w", "weekly_return_monday"=>"w",
"yearly_day_of_week"=>"0", "yearly_day_of_week"=>"0",
@ -419,9 +419,9 @@ class RecurringTodosControllerTest < ActionController::TestCase
login_as(:admin_user) login_as(:admin_user)
rt = recurring_todos(:call_bill_gates_every_day) rt = recurring_todos(:call_bill_gates_every_day)
put :update, put :update,
"recurring_todo" => { "recurring_todo" => {
"description" => "changed", "description" => "changed",
"daily_selector" => "daily_every_x_day", "daily_selector" => "daily_every_x_day",
"daily_every_x_days" => "2", "daily_every_x_days" => "2",
"ends_on" => "no_end_date", "ends_on" => "no_end_date",
@ -433,7 +433,7 @@ class RecurringTodosControllerTest < ActionController::TestCase
"recurring_todo_edit_start_from" => "2/1/2013", "recurring_todo_edit_start_from" => "2/1/2013",
"end_date" => nil, "end_date" => nil,
"ends_on" => "no_end_date", "ends_on" => "no_end_date",
"id" => "#{rt.id}", "id" => "#{rt.id}",
"context_name" => "library", "context_name" => "library",
format: :js format: :js

View file

@ -45,11 +45,14 @@ class StatsControllerTest < ActionController::TestCase
def test_totals def test_totals
login_as(:admin_user) login_as(:admin_user)
get :index get :index
assert_response :success assert_response :success
totals = assigns['stats'].totals totals = assigns['stats'].totals
assert_equal 4, totals.tags assert_equal 4, totals.tags
assert_equal 2, totals.unique_tags assert_equal 2, totals.unique_tags
assert_equal 2.week.ago.utc.at_midnight, totals.first_action_at.utc.at_midnight
Time.zone = users(:admin_user).prefs.time_zone # calculations are done in users timezone
assert_equal 2.weeks.ago.at_midnight, totals.first_action_at.at_midnight
end end
def test_downdrill def test_downdrill
@ -128,15 +131,15 @@ class StatsControllerTest < ActionController::TestCase
# And they should be averaged over three months # 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'][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 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 (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" assert_equal (4)/3.0, assigns['actions_created_avg_last12months_array'][2], "two in fourth month"
# And the current month should be interpolated # And the current month should be interpolated
fraction = Time.zone.now.day.to_f / Time.zone.now.end_of_month.day.to_f 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*(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" 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 # And totals should be calculated
assert_equal 2, assigns['max'], "max of created or completed todos in one month" assert_equal 2, assigns['max'], "max of created or completed todos in one month"
end end
@ -168,7 +171,7 @@ class StatsControllerTest < ActionController::TestCase
login_as(:admin_user) login_as(:admin_user)
@current_user = User.find(users(:admin_user).id) @current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all @current_user.todos.delete_all
given_todos_for_stats given_todos_for_stats
# When I get the chart data # When I get the chart data
@ -176,7 +179,7 @@ class StatsControllerTest < ActionController::TestCase
assert_response :success assert_response :success
# only tests relevant differences with actions_done_last_12months_data # 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 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" assert_equal 2, assigns['max'], "two actions created on one day is max"
end end
@ -185,31 +188,31 @@ class StatsControllerTest < ActionController::TestCase
login_as(:admin_user) login_as(:admin_user)
@current_user = User.find(users(:admin_user).id) @current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all @current_user.todos.delete_all
given_todos_for_stats given_todos_for_stats
# When I get the chart data # When I get the chart data
get :actions_done_lastyears_data get :actions_done_lastyears_data
assert_response :success assert_response :success
# only tests difference with actions_done_last_12months_data # only tests difference with actions_done_last_12months_data
# And the last two months are corrected # 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'][23]
assert_equal 2/3.0, assigns['actions_done_avg_last_months_array'][24] assert_equal 2/3.0, assigns['actions_done_avg_last_months_array'][24]
end end
def test_actions_completion_time_data def test_actions_completion_time_data
login_as(:admin_user) login_as(:admin_user)
@current_user = User.find(users(:admin_user).id) @current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all @current_user.todos.delete_all
given_todos_for_stats given_todos_for_stats
# When I get the chart data # When I get the chart data
get :actions_completion_time_data get :actions_completion_time_data
assert_response :success assert_response :success
# do not test stuff already implicitly tested in other tests # 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 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 3, assigns['max_actions'], "3 completed within one week"
@ -222,13 +225,13 @@ class StatsControllerTest < ActionController::TestCase
login_as(:admin_user) login_as(:admin_user)
@current_user = User.find(users(:admin_user).id) @current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all @current_user.todos.delete_all
given_todos_for_stats given_todos_for_stats
# When I get the chart data # When I get the chart data
get :actions_running_time_data get :actions_running_time_data
assert_response :success assert_response :success
# do not test stuff already implicitly tested in other tests # 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 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 2, assigns['max_actions'], "2 actions running long together"
@ -241,13 +244,13 @@ class StatsControllerTest < ActionController::TestCase
login_as(:admin_user) login_as(:admin_user)
@current_user = User.find(users(:admin_user).id) @current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all @current_user.todos.delete_all
given_todos_for_stats given_todos_for_stats
# When I get the chart data # When I get the chart data
get :actions_open_per_week_data get :actions_open_per_week_data
assert_response :success assert_response :success
# do not test stuff already implicitly tested in other tests # 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 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 4, assigns['max_actions'], "4 actions running together"
@ -258,12 +261,12 @@ class StatsControllerTest < ActionController::TestCase
login_as(:admin_user) login_as(:admin_user)
@current_user = User.find(users(:admin_user).id) @current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all @current_user.todos.delete_all
given_todos_for_stats given_todos_for_stats
# Given todo1 is deferred (i.e. not visible) # Given todo1 is deferred (i.e. not visible)
@todo_today1.show_from = Time.zone.now + 1.week @todo_today1.show_from = Time.zone.now + 1.week
@todo_today1.save @todo_today1.save
# When I get the chart data # When I get the chart data
get :actions_visible_running_time_data get :actions_visible_running_time_data
assert_response :success assert_response :success
@ -281,7 +284,7 @@ class StatsControllerTest < ActionController::TestCase
login_as(:admin_user) login_as(:admin_user)
@current_user = User.find(users(:admin_user).id) @current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all @current_user.todos.delete_all
given_todos_for_stats given_todos_for_stats
# When I get the chart data # When I get the chart data
@ -311,7 +314,7 @@ class StatsControllerTest < ActionController::TestCase
login_as(:admin_user) login_as(:admin_user)
@current_user = User.find(users(:admin_user).id) @current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all @current_user.todos.delete_all
given_todos_for_stats given_todos_for_stats
# When I get the chart data # When I get the chart data
@ -335,12 +338,12 @@ class StatsControllerTest < ActionController::TestCase
assert_equal 14, assigns['data'].values[9], "pie slices limited to max 10; last pie contains sum of rest (in percentage)" 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" assert_equal "(others)", assigns['data'].labels[9], "pie slices limited to max 10; last slice contains label for others"
end end
def test_actions_day_of_week_all_data def test_actions_day_of_week_all_data
login_as(:admin_user) login_as(:admin_user)
@current_user = User.find(users(:admin_user).id) @current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all @current_user.todos.delete_all
given_todos_for_stats given_todos_for_stats
# When I get the chart data # When I get the chart data
@ -358,7 +361,7 @@ class StatsControllerTest < ActionController::TestCase
login_as(:admin_user) login_as(:admin_user)
@current_user = User.find(users(:admin_user).id) @current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all @current_user.todos.delete_all
given_todos_for_stats given_todos_for_stats
# When I get the chart data # When I get the chart data
@ -376,7 +379,7 @@ class StatsControllerTest < ActionController::TestCase
login_as(:admin_user) login_as(:admin_user)
@current_user = User.find(users(:admin_user).id) @current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all @current_user.todos.delete_all
given_todos_for_stats given_todos_for_stats
# When I get the chart data # When I get the chart data
@ -389,12 +392,12 @@ class StatsControllerTest < ActionController::TestCase
assert_not_nil assigns['actions_creation_hour_array'] assert_not_nil assigns['actions_creation_hour_array']
assert_not_nil assigns['actions_completion_hour_array'] assert_not_nil assigns['actions_completion_hour_array']
end end
def test_show_selected_actions_from_chart_avrt def test_show_selected_actions_from_chart_avrt
login_as(:admin_user) login_as(:admin_user)
@current_user = User.find(users(:admin_user).id) @current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all @current_user.todos.delete_all
given_todos_for_stats given_todos_for_stats
# When I get the chart data # When I get the chart data
@ -409,7 +412,7 @@ class StatsControllerTest < ActionController::TestCase
login_as(:admin_user) login_as(:admin_user)
@current_user = User.find(users(:admin_user).id) @current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all @current_user.todos.delete_all
given_todos_for_stats given_todos_for_stats
# When I get the chart data # When I get the chart data
@ -424,7 +427,7 @@ class StatsControllerTest < ActionController::TestCase
login_as(:admin_user) login_as(:admin_user)
@current_user = User.find(users(:admin_user).id) @current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all @current_user.todos.delete_all
given_todos_for_stats given_todos_for_stats
# When I get the chart data # When I get the chart data
@ -439,7 +442,7 @@ class StatsControllerTest < ActionController::TestCase
login_as(:admin_user) login_as(:admin_user)
@current_user = User.find(users(:admin_user).id) @current_user = User.find(users(:admin_user).id)
@current_user.todos.delete_all @current_user.todos.delete_all
given_todos_for_stats given_todos_for_stats
# When I get the chart data # When I get the chart data
@ -451,7 +454,7 @@ class StatsControllerTest < ActionController::TestCase
end end
private private
def given_todos_for_stats def given_todos_for_stats
# Given two todos created today # Given two todos created today
@todo_today1 = @current_user.todos.create!(:description => "created today1", :context => contexts(:office)) @todo_today1 = @current_user.todos.create!(:description => "created today1", :context => contexts(:office))
@ -491,7 +494,7 @@ class StatsControllerTest < ActionController::TestCase
def difference_in_days(date1, date2) def difference_in_days(date1, date2)
return ((date1.at_midnight-date2.at_midnight)/(60*60*24)).to_i return ((date1.at_midnight-date2.at_midnight)/(60*60*24)).to_i
end end
# assumes date1 > date2 # assumes date1 > date2
def difference_in_weeks(date1, date2) def difference_in_weeks(date1, date2)
return difference_in_days(date1, date2) / 7 return difference_in_days(date1, date2) / 7

View file

@ -120,7 +120,7 @@ class TodosControllerTest < ActionController::TestCase
assert_response :success assert_response :success
assert_equal 3, @tagged assert_equal 3, @tagged
end end
def test_find_tagged_with_terms_separated_with_dot def test_find_tagged_with_terms_separated_with_dot
login_as :admin_user login_as :admin_user
create_todo(description: "test dotted tag", tag_list: "first.last, second") create_todo(description: "test dotted tag", tag_list: "first.last, second")
@ -408,7 +408,7 @@ class TodosControllerTest < ActionController::TestCase
####### #######
# defer # defer
####### #######
def test_update_clearing_show_from_makes_todo_active def test_update_clearing_show_from_makes_todo_active
t = Todo.find(1) t = Todo.find(1)
@ -437,7 +437,7 @@ class TodosControllerTest < ActionController::TestCase
# given a todo in the tickler that should be activated # given a todo in the tickler that should be activated
travel_to 2.weeks.ago do travel_to 2.weeks.ago do
create_todo( create_todo(
description: "tickler", description: "tickler",
show_from: 1.week.from_now. show_from: 1.week.from_now.
in_time_zone(users(:admin_user).prefs.time_zone). in_time_zone(users(:admin_user).prefs.time_zone).
strftime("#{users(:admin_user).prefs.date_format}")) strftime("#{users(:admin_user).prefs.date_format}"))
@ -715,17 +715,25 @@ class TodosControllerTest < ActionController::TestCase
end end
def test_toggle_check_on_rec_todo_show_from_today def test_toggle_check_on_rec_todo_show_from_today
# warning: the Time.zone set in site.yml will be overwritten by
# :admin_user.prefs.time_zone in ApplicationController. This messes with
# the calculation. So set time_zone to admin_user's time_zone setting
Time.zone = users(:admin_user).prefs.time_zone
travel_to Time.zone.local(2014, 1, 15) do travel_to Time.zone.local(2014, 1, 15) do
today = Time.zone.now.at_midnight
login_as(:admin_user) login_as(:admin_user)
# link todo_1 and recurring_todo_1 # link todo_1 and recurring_todo_1
recurring_todo_1 = RecurringTodo.find(1) recurring_todo_1 = RecurringTodo.find(1)
todo_1 = Todo.where(:recurring_todo_id => 1).first todo_1 = Todo.where(:recurring_todo_id => 1).first
today = Time.zone.now.at_midnight
todo_1.due = today todo_1.due = today
assert todo_1.save assert todo_1.save
# change recurrence pattern to monthly and set show_from to today # change recurrence pattern to monthly on a specific
# day (recurrence_selector=0) and set show_from
# (every_other2=1) to today
recurring_todo_1.target = 'show_from_date' recurring_todo_1.target = 'show_from_date'
recurring_todo_1.recurring_period = 'monthly' recurring_todo_1.recurring_period = 'monthly'
recurring_todo_1.recurrence_selector = 0 recurring_todo_1.recurrence_selector = 0
@ -746,15 +754,13 @@ class TodosControllerTest < ActionController::TestCase
assert_not_equal todo_1.id, new_todo.id, "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 not the same as todo_1"
assert !new_todo.show_from.nil?, "check that the new_todo is in the tickler to show next month" assert !new_todo.show_from.nil?, "check that the new_todo is in the tickler to show next month"
# do not use today here. It somehow gets messed up with the timezone calculation. assert_equal today + 1.month, new_todo.show_from
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 end
end end
def test_check_for_next_todo def test_check_for_next_todo
login_as :admin_user login_as :admin_user
Time.zone = users(:admin_user).prefs.time_zone
tomorrow = Time.zone.now + 1.day tomorrow = Time.zone.now + 1.day
@ -791,6 +797,7 @@ class TodosControllerTest < ActionController::TestCase
def test_check_for_next_todo_monthly def test_check_for_next_todo_monthly
login_as :admin_user login_as :admin_user
Time.zone = users(:admin_user).prefs.time_zone
tomorrow = Time.zone.now + 1.day tomorrow = Time.zone.now + 1.day
@ -1024,13 +1031,13 @@ class TodosControllerTest < ActionController::TestCase
private private
def create_todo(params={}) def create_todo(params={})
defaults = { source_view: 'todo', defaults = { source_view: 'todo',
context_name: "library", project_name: "Build a working time machine", context_name: "library", project_name: "Build a working time machine",
notes: "note", description: "a new todo", due: nil, tag_list: "a,b,c"} notes: "note", description: "a new todo", due: nil, tag_list: "a,b,c"}
params=params.reverse_merge(defaults) params=params.reverse_merge(defaults)
put :create, _source_view: params[:_source_view], put :create, _source_view: params[:_source_view],
context_name: params[:context_name], project_name: params[:project_name], tag_list: params[:tag_list], context_name: params[:context_name], project_name: params[:project_name], tag_list: params[:tag_list],
todo: {notes: params[:notes], description: params[:description], due: params[:due], show_from: params[:show_from]} todo: {notes: params[:notes], description: params[:description], due: params[:due], show_from: params[:show_from]}
end end

View file

@ -1,8 +1,11 @@
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html # Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
<%
def today # Please note that dates in yml are not converted to utc timezone like
Time.now.utc.to_s(:db) # rails does automatically in models or controllers! Convert to utc manually!
<%
def today
Time.zone.now.utc.to_s(:db)
end end
%> %>

View file

@ -1,16 +1,19 @@
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html # Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
<%
def today # Please note that dates in yml are not converted to utc timezone like
Time.now.utc.to_s(:db) # rails does automatically in models or controllers! Convert to utc manually!
<%
def today
Time.zone.now.utc.to_s(:db)
end end
def next_week def next_week
1.week.from_now.utc.to_s(:db) 1.week.from_now.utc.to_s(:db)
end
def last_week
1.week.ago.utc.to_s(:db)
end end
def last_week
1.week.ago.utc.to_s(:db)
end
%> %>
first_notes: first_notes:

View file

@ -1,7 +1,10 @@
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html # Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
# Please note that dates in yml are not converted to utc timezone like
# rails does automatically in models or controllers! Convert to utc manually!
<% <%
def today def today
Time.zone.now.beginning_of_day.to_s(:db) Time.zone.now.utc.beginning_of_day.to_s(:db)
end end
%> %>

View file

@ -1,26 +1,29 @@
# Please note that dates in yml are not converted to utc timezone like
# rails does automatically in models or controllers! Convert to utc manually!
<% <%
def today def today
Time.zone.now.beginning_of_day.to_s(:db) Time.zone.now.utc.beginning_of_day.to_s(:db)
end end
def next_week def next_week
1.week.from_now.beginning_of_day.to_s(:db) 1.week.from_now.utc.beginning_of_day.to_s(:db)
end end
def last_week def last_week
1.week.ago.beginning_of_day.to_s(:db) 1.week.ago.utc.beginning_of_day.to_s(:db)
end end
def two_weeks_ago def two_weeks_ago
2.weeks.ago.beginning_of_day.to_s(:db) 2.weeks.ago.utc.beginning_of_day.to_s(:db)
end end
def two_weeks_hence def two_weeks_hence
2.weeks.from_now.beginning_of_day.to_s(:db) 2.weeks.from_now.utc.beginning_of_day.to_s(:db)
end end
def way_back def way_back
Time.zone.local(2008,1,1).to_s(:db) Time.zone.local(2008,1,1).utc.to_s(:db)
end end
%> %>

View file

@ -1,17 +1,27 @@
# please note that dates in yml are not converted to utc timezone like
# rails does automatically in models or controllers! Convert to utc manually!
<%
def today
Time.zone.now.utc.beginning_of_day.to_s(:db)
end
%>
foo: foo:
id: 1 id: 1
name: foo name: foo
created_at: <%= Time.now.utc.to_s(:db) %> created_at: <%= today %>
updated_at: <%= Time.now.utc.to_s(:db) %> updated_at: <%= today %>
bar: bar:
id: 2 id: 2
name: bar name: bar
created_at: <%= Time.now.utc.to_s(:db) %> created_at: <%= today %>
updated_at: <%= Time.now.utc.to_s(:db) %> updated_at: <%= today %>
baz: baz:
id: 3 id: 3
name: baz name: baz
created_at: <%= Time.now.utc.to_s(:db) %> created_at: <%= today %>
updated_at: <%= Time.now.utc.to_s(:db) %> updated_at: <%= today %>

View file

@ -1,26 +1,27 @@
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html # Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
<%
Time.zone = SITE_CONFIG['time_zone'] # Please note that dates in yml are not converted to utc timezone like
# rails does automatically in models or controllers! Convert to utc manually!
def today <%
Time.zone.now.beginning_of_day.to_s(:db) def today
Time.zone.now.utc.beginning_of_day.to_s(:db)
end end
def next_week def next_week
1.week.from_now.beginning_of_day.to_s(:db) 1.week.from_now.utc.beginning_of_day.to_s(:db)
end end
def last_week def last_week
1.week.ago.beginning_of_day.to_s(:db) 1.week.ago.utc.beginning_of_day.to_s(:db)
end end
def two_weeks_ago def two_weeks_ago
2.weeks.ago.beginning_of_day.to_s(:db) 2.weeks.ago.utc.beginning_of_day.to_s(:db)
end end
def two_weeks_hence def two_weeks_hence
2.weeks.from_now.beginning_of_day.to_s(:db) 2.weeks.from_now.utc.beginning_of_day.to_s(:db)
end end
%> %>
@ -192,7 +193,7 @@ call_stock_broker:
due: ~ due: ~
completed_at: ~ completed_at: ~
user_id: 1 user_id: 1
select_delorean_model: select_delorean_model:
id: 15 id: 15
context_id: 6 context_id: 6
@ -254,4 +255,3 @@ email_broker:
description: Ask about better stocks description: Ask about better stocks
notes: ~ notes: ~
state: pending state: pending

View file

@ -98,7 +98,7 @@ class ProjectTest < ActiveSupport::TestCase
assert_equal :completed, @timemachine.aasm.current_state assert_equal :completed, @timemachine.aasm.current_state
assert @timemachine.completed? assert @timemachine.completed?
assert_not_nil @timemachine.completed_at, "completed_at not expected to be nil" assert_not_nil @timemachine.completed_at, "completed_at not expected to be nil"
assert_in_delta Time.now, @timemachine.completed_at, 1 assert_in_delta Time.zone.now, @timemachine.completed_at, 1
end end
def test_delete_project_deletes_todos_within_it def test_delete_project_deletes_todos_within_it
@ -254,5 +254,4 @@ class ProjectTest < ActiveSupport::TestCase
p.reload p.reload
assert_equal 4, p.running_time assert_equal 4, p.running_time
end end
end end

View file

@ -11,7 +11,7 @@ class RecurringTodoTest < ActiveSupport::TestCase
@every_month = @monthly_every_last_friday @every_month = @monthly_every_last_friday
@yearly = recurring_todos(:birthday_reinier) @yearly = recurring_todos(:birthday_reinier)
@today = Time.now.utc @today = Time.zone.now
@tomorrow = @today + 1.day @tomorrow = @today + 1.day
@in_three_days = @today + 3.days @in_three_days = @today + 3.days
@in_four_days = @in_three_days + 1.day # need a day after start_from @in_four_days = @in_three_days + 1.day # need a day after start_from
@ -63,19 +63,19 @@ class RecurringTodoTest < ActiveSupport::TestCase
# #
# start_from is way_back # start_from is way_back
due_date1 = @yearly.get_due_date(nil) due_date1 = @yearly.get_due_date(nil)
due_date2 = @yearly.get_due_date(Time.now.utc + 1.day) due_date2 = @yearly.get_due_date(Time.zone.now + 1.day)
assert_equal due_date1, due_date2 assert_equal due_date1, due_date2
# start_from is in the future # start_from is in the future
@yearly.start_from = Time.now.utc + 1.week @yearly.start_from = Time.zone.now + 1.week
due_date1 = @yearly.get_due_date(nil) due_date1 = @yearly.get_due_date(nil)
due_date2 = @yearly.get_due_date(Time.now.utc + 1.day) due_date2 = @yearly.get_due_date(Time.zone.now + 1.day)
assert_equal due_date1, due_date2 assert_equal due_date1, due_date2
# start_from is nil # start_from is nil
@yearly.start_from = nil @yearly.start_from = nil
due_date1 = @yearly.get_due_date(nil) due_date1 = @yearly.get_due_date(nil)
due_date2 = @yearly.get_due_date(Time.now.utc + 1.day) due_date2 = @yearly.get_due_date(Time.zone.now + 1.day)
assert_equal due_date1, due_date2 assert_equal due_date1, due_date2
end end
@ -117,7 +117,7 @@ class RecurringTodoTest < ActiveSupport::TestCase
assert_equal Time.zone.local(2021,6,8), @yearly.get_due_date(Time.zone.local(2019,6,1)) # also next year assert_equal Time.zone.local(2021,6,8), @yearly.get_due_date(Time.zone.local(2019,6,1)) # also next year
assert_equal Time.zone.local(2021,6,8), @yearly.get_due_date(Time.zone.local(2020,6,15)) # also next year assert_equal Time.zone.local(2021,6,8), @yearly.get_due_date(Time.zone.local(2020,6,15)) # also next year
this_year = Time.now.utc.year this_year = Time.zone.now.utc.year
@yearly.start_from = Time.zone.local(this_year+1,6,12) @yearly.start_from = Time.zone.local(this_year+1,6,12)
due_date = @yearly.get_due_date(nil) due_date = @yearly.get_due_date(nil)
assert_equal due_date.year, this_year+2 assert_equal due_date.year, this_year+2
@ -168,4 +168,4 @@ class RecurringTodoTest < ActiveSupport::TestCase
assert_equal true, @every_day.continues_recurring?(@in_three_days) assert_equal true, @every_day.continues_recurring?(@in_three_days)
assert_equal 0, @every_day.occurrences_count assert_equal 0, @every_day.occurrences_count
end end
end end

View file

@ -8,7 +8,7 @@ module RecurringTodos
def setup def setup
super super
@admin = users(:admin_user) @admin = users(:admin_user)
end end
def test_pattern_builds_from_existing_recurring_todo def test_pattern_builds_from_existing_recurring_todo
rt = @admin.recurring_todos.first rt = @admin.recurring_todos.first
@ -121,9 +121,9 @@ module RecurringTodos
def test_determine_start def test_determine_start
travel_to Time.zone.local(2013,1,1) do travel_to Time.zone.local(2013,1,1) do
rt = create_recurring_todo rt = create_recurring_todo
assert_equal "2013-01-01 00:00:00", rt.send(:determine_start, nil).to_s(:db), "no previous date, use today" assert_equal Time.zone.parse("2013-01-01 00:00:00"), rt.send(:determine_start, nil), "no previous date, use today"
assert_equal "2013-01-01 00:00:00", rt.send(:determine_start, nil, 1.day).to_s(:db), "no previous date, use today without offset" assert_equal Time.zone.parse("2013-01-01 00:00:00"), rt.send(:determine_start, nil, 1.day).to_s(:db), "no previous date, use today without offset"
assert_equal "2013-01-02 00:00:00", rt.send(:determine_start, Time.zone.now, 1.day).to_s(:db), "use previous date and offset" assert_equal Time.zone.parse("2013-01-02 00:00:00"), rt.send(:determine_start, Time.zone.now, 1.day).to_s(:db), "use previous date and offset"
end end
end end
@ -131,14 +131,14 @@ module RecurringTodos
rt = create_recurring_todo rt = create_recurring_todo
# march 2014 has 5 saturdays, the last will return the 5th # march 2014 has 5 saturdays, the last will return the 5th
assert_equal "2014-03-01 00:00:00", rt.send(:get_xth_day_of_month, 1, 6, 3, 2014).to_s(:db) assert_equal Time.zone.parse("2014-03-01 00:00:00"), rt.send(:get_xth_day_of_month, 1, 6, 3, 2014).to_s(:db)
assert_equal "2014-03-22 00:00:00", rt.send(:get_xth_day_of_month, 4, 6, 3, 2014).to_s(:db) assert_equal Time.zone.parse("2014-03-22 00:00:00"), rt.send(:get_xth_day_of_month, 4, 6, 3, 2014).to_s(:db)
assert_equal "2014-03-29 00:00:00", rt.send(:get_xth_day_of_month, 5, 6, 3, 2014).to_s(:db) assert_equal Time.zone.parse("2014-03-29 00:00:00"), rt.send(:get_xth_day_of_month, 5, 6, 3, 2014).to_s(:db)
# march 2014 has 4 fridays, the last will return the 4th # march 2014 has 4 fridays, the last will return the 4th
assert_equal "2014-03-07 00:00:00", rt.send(:get_xth_day_of_month, 1, 5, 3, 2014).to_s(:db) assert_equal Time.zone.parse("2014-03-07 00:00:00"), rt.send(:get_xth_day_of_month, 1, 5, 3, 2014).to_s(:db)
assert_equal "2014-03-28 00:00:00", rt.send(:get_xth_day_of_month, 4, 5, 3, 2014).to_s(:db) assert_equal Time.zone.parse("2014-03-28 00:00:00"), rt.send(:get_xth_day_of_month, 4, 5, 3, 2014).to_s(:db)
assert_equal "2014-03-28 00:00:00", rt.send(:get_xth_day_of_month, 5, 5, 3, 2014).to_s(:db) assert_equal Time.zone.parse("2014-03-28 00:00:00"), rt.send(:get_xth_day_of_month, 5, 5, 3, 2014).to_s(:db)
assert_raise(RuntimeError, "should check on valid weekdays"){ rt.send(:get_xth_day_of_month, 5, 9, 3, 2014) } assert_raise(RuntimeError, "should check on valid weekdays"){ rt.send(:get_xth_day_of_month, 5, 9, 3, 2014) }
assert_raise(RuntimeError, "should check on valid count x"){ rt.send(:get_xth_day_of_month, 6, 5, 3, 2014) } assert_raise(RuntimeError, "should check on valid count x"){ rt.send(:get_xth_day_of_month, 6, 5, 3, 2014) }
@ -166,4 +166,4 @@ module RecurringTodos
end end
end end

View file

@ -16,14 +16,14 @@ class TodoCreateParamsHelperTest < ActiveSupport::TestCase
end end
def test_show_from_accessor def test_show_from_accessor
expected_date = Time.now expected_date = Time.zone.now
params = ActionController::Parameters.new({ 'todo' => { 'show_from' => expected_date}}) params = ActionController::Parameters.new({ 'todo' => { 'show_from' => expected_date}})
params_helper = Todos::TodoCreateParamsHelper.new(params, users(:admin_user)) params_helper = Todos::TodoCreateParamsHelper.new(params, users(:admin_user))
assert_equal(expected_date, params_helper.show_from) assert_equal(expected_date, params_helper.show_from)
end end
def test_due_accessor def test_due_accessor
expected_date = Time.now expected_date = Time.zone.now
params = ActionController::Parameters.new({ 'todo' => { 'due' => expected_date}}) params = ActionController::Parameters.new({ 'todo' => { 'due' => expected_date}})
params_helper = Todos::TodoCreateParamsHelper.new(params, users(:admin_user)) params_helper = Todos::TodoCreateParamsHelper.new(params, users(:admin_user))
assert_equal(expected_date, params_helper.due) assert_equal(expected_date, params_helper.due)
@ -119,5 +119,4 @@ class TodoCreateParamsHelperTest < ActiveSupport::TestCase
params_helper = Todos::TodoCreateParamsHelper.new(params, users(:admin_user)) params_helper = Todos::TodoCreateParamsHelper.new(params, users(:admin_user))
assert_equal false, params_helper.context_specified_by_name? assert_equal false, params_helper.context_specified_by_name?
end end
end end

View file

@ -22,8 +22,8 @@ class TodoTest < ActiveSupport::TestCase
assert_equal "Call Bill Gates to find out how much he makes per day", @not_completed1.description assert_equal "Call Bill Gates to find out how much he makes per day", @not_completed1.description
assert_nil @not_completed1.notes assert_nil @not_completed1.notes
assert @not_completed1.completed? == false assert @not_completed1.completed? == false
assert_equal 1.week.ago.beginning_of_day.strftime("%Y-%m-%d %H:%M"), @not_completed1.created_at.beginning_of_day.strftime("%Y-%m-%d %H:%M") assert_equal 1.week.ago.utc.beginning_of_day, @not_completed1.created_at.utc
assert_equal 2.week.from_now.beginning_of_day.strftime("%Y-%m-%d"), @not_completed1.due.strftime("%Y-%m-%d") assert_equal 2.week.from_now.utc.beginning_of_day, @not_completed1.due.utc
assert_nil @not_completed1.completed_at assert_nil @not_completed1.completed_at
assert_equal 1, @not_completed1.user_id assert_equal 1, @not_completed1.user_id
end end
@ -72,26 +72,26 @@ class TodoTest < ActiveSupport::TestCase
def test_validate_show_from_must_be_a_date_in_the_future def test_validate_show_from_must_be_a_date_in_the_future
t = @not_completed2 t = @not_completed2
t.show_from = 1.week.ago t.show_from = 1.week.ago
assert !t.save, "todo should not be saved without validation errors" assert !t.save, "todo should not be saved without validation errors"
assert_equal 1, t.errors.count assert_equal 1, t.errors.count
assert_equal "must be a date in the future", t.errors[:show_from][0] assert_equal "must be a date in the future", t.errors[:show_from][0]
end end
def test_validate_circular_dependencies def test_validate_circular_dependencies
@completed.activate! @completed.activate!
@not_completed3=@completed @not_completed3=@completed
# 2 -> 1 # 2 -> 1
@not_completed1.add_predecessor(@not_completed2) @not_completed1.add_predecessor(@not_completed2)
assert @not_completed1.save! assert @not_completed1.save!
assert_equal 1, @not_completed2.successors.count assert_equal 1, @not_completed2.successors.count
# 3 -> 2 -> 1 # 3 -> 2 -> 1
@not_completed2.add_predecessor(@not_completed3) @not_completed2.add_predecessor(@not_completed3)
assert @not_completed2.save! assert @not_completed2.save!
assert_equal 1, @not_completed3.successors.count assert_equal 1, @not_completed3.successors.count
# 1 -> 3 -> 2 -> 1 == circle # 1 -> 3 -> 2 -> 1 == circle
assert_raises ActiveRecord::RecordInvalid do assert_raises ActiveRecord::RecordInvalid do
@not_completed3.add_predecessor(@not_completed1) @not_completed3.add_predecessor(@not_completed1)
@ -131,7 +131,7 @@ class TodoTest < ActiveSupport::TestCase
t.toggle_completion! t.toggle_completion!
assert_equal :active, t.aasm.current_state assert_equal :active, t.aasm.current_state
end end
def test_toggle_completion_with_show_from_in_future def test_toggle_completion_with_show_from_in_future
t = @not_completed1 t = @not_completed1
t.show_from= 1.week.from_now t.show_from= 1.week.from_now
@ -140,12 +140,12 @@ class TodoTest < ActiveSupport::TestCase
t.toggle_completion! t.toggle_completion!
assert_equal :completed, t.aasm.current_state assert_equal :completed, t.aasm.current_state
end end
def test_toggle_completion_with_show_from_in_past def test_toggle_completion_with_show_from_in_past
t = @not_completed1 t = @not_completed1
t.update_attribute(:show_from, 1.week.ago) t.update_attribute(:show_from, 1.week.ago)
assert_equal :active, t.aasm.current_state assert_equal :active, t.aasm.current_state
assert t.toggle_completion!, "shoud be able to mark active todo complete even if show_from is set in the past" assert t.toggle_completion!, "shoud be able to mark active todo complete even if show_from is set in the past"
assert_equal :completed, t.aasm.current_state assert_equal :completed, t.aasm.current_state
end end
@ -219,7 +219,7 @@ class TodoTest < ActiveSupport::TestCase
# And I update the state of the todo from its project # And I update the state of the todo from its project
new_todo.update_state_from_project new_todo.update_state_from_project
# Then the todo should be hidden # Then the todo should be hidden
assert new_todo.hidden? assert new_todo.hidden?
end end
def test_initial_state_defaults_to_active def test_initial_state_defaults_to_active
@ -280,7 +280,7 @@ class TodoTest < ActiveSupport::TestCase
assert todo.pending?, "todo with predecessor should be blocked" assert todo.pending?, "todo with predecessor should be blocked"
# cannot activate if part of hidden project # cannot activate if part of hidden project
assert_raise(AASM::InvalidTransition) { todo.activate! } assert_raise(AASM::InvalidTransition) { todo.activate! }
todo.remove_predecessor(todo2) todo.remove_predecessor(todo2)
assert todo.reload.hidden?, "todo should be put back in hidden state" assert todo.reload.hidden?, "todo should be put back in hidden state"
@ -337,7 +337,7 @@ class TodoTest < ActiveSupport::TestCase
@not_completed1.add_predecessor(@not_completed2) @not_completed1.add_predecessor(@not_completed2)
@not_completed1.save_predecessors @not_completed1.save_predecessors
# blocking is not done automagically # blocking is not done automagically
@not_completed1.block! @not_completed1.block!
assert @not_completed1.uncompleted_predecessors? assert @not_completed1.uncompleted_predecessors?
assert @not_completed1.pending?, "a todo with predecessors should be pending" assert @not_completed1.pending?, "a todo with predecessors should be pending"
@ -358,7 +358,7 @@ class TodoTest < ActiveSupport::TestCase
@not_completed1.add_predecessor_list("#{@not_completed2.id}, #{@not_completed3.id}") @not_completed1.add_predecessor_list("#{@not_completed2.id}, #{@not_completed3.id}")
@not_completed1.save_predecessors @not_completed1.save_predecessors
# blocking is not done automagically # blocking is not done automagically
@not_completed1.block! @not_completed1.block!
# Then @completed1 should have predecessors and should be blocked # Then @completed1 should have predecessors and should be blocked
assert @not_completed1.uncompleted_predecessors? assert @not_completed1.uncompleted_predecessors?
@ -526,18 +526,18 @@ class TodoTest < ActiveSupport::TestCase
assert !older_created_todos.include?(todo_now) assert !older_created_todos.include?(todo_now)
assert !recent_created_todos.include?(todo_old) assert !recent_created_todos.include?(todo_old)
end end
def test_notes_are_rendered_on_save def test_notes_are_rendered_on_save
user = @completed.user user = @completed.user
todo = user.todos.create(:description => "test", :context => @completed.context) todo = user.todos.create(:description => "test", :context => @completed.context)
assert_nil todo.notes assert_nil todo.notes
assert_nil todo.rendered_notes assert_nil todo.rendered_notes
todo.notes = "*test*" todo.notes = "*test*"
todo.save! todo.save!
todo.reload todo.reload
assert_equal "*test*", todo.notes assert_equal "*test*", todo.notes
assert_equal "<p><strong>test</strong></p>", todo.rendered_notes assert_equal "<p><strong>test</strong></p>", todo.rendered_notes
end end

View file

@ -75,7 +75,7 @@ class UserTest < ActiveSupport::TestCase
assert_equal "is too long (maximum is 80 characters)", u.errors[:login][0] assert_equal "is too long (maximum is 80 characters)", u.errors[:login][0]
end end
end end
def test_validate_correct_length_login def test_validate_correct_length_login
assert_difference 'User.count' do assert_difference 'User.count' do
create_user :login => generate_random_string(6) create_user :login => generate_random_string(6)
@ -206,14 +206,14 @@ class UserTest < ActiveSupport::TestCase
def test_find_and_activate_deferred_todos_that_are_ready def test_find_and_activate_deferred_todos_that_are_ready
assert_equal 1, @admin_user.deferred_todos.count assert_equal 1, @admin_user.deferred_todos.count
@admin_user.deferred_todos[0].show_from = Time.now.utc - 5.seconds @admin_user.deferred_todos[0].show_from = Time.zone.now - 5.seconds
@admin_user.deferred_todos[0].save(:validate => false) @admin_user.deferred_todos[0].save(:validate => false)
@admin_user.deferred_todos.reload @admin_user.deferred_todos.reload
@admin_user.deferred_todos.find_and_activate_ready @admin_user.deferred_todos.find_and_activate_ready
@admin_user.deferred_todos.reload @admin_user.deferred_todos.reload
assert_equal 0, @admin_user.deferred_todos.count assert_equal 0, @admin_user.deferred_todos.count
end end
def test_sort_active_projects_alphabetically def test_sort_active_projects_alphabetically
u = users(:admin_user) u = users(:admin_user)
u.projects.alphabetize(:state => "active") u.projects.alphabetize(:state => "active")
@ -221,7 +221,7 @@ class UserTest < ActiveSupport::TestCase
assert_equal 2, projects(:gardenclean).position assert_equal 2, projects(:gardenclean).position
assert_equal 3, projects(:moremoney).position assert_equal 3, projects(:moremoney).position
end end
def test_sort_active_projects_alphabetically_case_insensitive def test_sort_active_projects_alphabetically_case_insensitive
u = users(:admin_user) u = users(:admin_user)
projects(:timemachine).name = projects(:timemachine).name.downcase projects(:timemachine).name = projects(:timemachine).name.downcase
@ -264,22 +264,22 @@ class UserTest < ActiveSupport::TestCase
users(:other_user).update_attributes(:password => 'new password', :password_confirmation => 'new password') users(:other_user).update_attributes(:password => 'new password', :password_confirmation => 'new password')
assert_equal users(:other_user), User.authenticate('jane', 'new password') assert_equal users(:other_user), User.authenticate('jane', 'new password')
end end
def test_should_not_rehash_password def test_should_not_rehash_password
users(:other_user).update_attributes(:login => 'jane2') users(:other_user).update_attributes(:login => 'jane2')
assert_equal users(:other_user), User.authenticate('jane2', 'sesame') assert_equal users(:other_user), User.authenticate('jane2', 'sesame')
end end
def test_should_authenticate_user def test_should_authenticate_user
assert_equal users(:other_user), User.authenticate('jane', 'sesame') assert_equal users(:other_user), User.authenticate('jane', 'sesame')
end end
def test_should_set_remember_token def test_should_set_remember_token
users(:other_user).remember_me users(:other_user).remember_me
assert_not_nil users(:other_user).remember_token assert_not_nil users(:other_user).remember_token
assert_not_nil users(:other_user).remember_token_expires_at assert_not_nil users(:other_user).remember_token_expires_at
end end
def test_should_unset_remember_token def test_should_unset_remember_token
users(:other_user).remember_me users(:other_user).remember_me
assert_not_nil users(:other_user).remember_token assert_not_nil users(:other_user).remember_token
@ -319,7 +319,7 @@ class UserTest < ActiveSupport::TestCase
u.projects.actionize u.projects.actionize
assert_equal "3,2,1", u.projects.reload.map(&:id).join(",") assert_equal "3,2,1", u.projects.reload.map(&:id).join(",")
end end
def test_remember_token def test_remember_token
@ -389,12 +389,12 @@ class UserTest < ActiveSupport::TestCase
assert_equal expect_notes_count, Note.count, "expected #{nr_of_notes} notes to be gone" assert_equal expect_notes_count, Note.count, "expected #{nr_of_notes} notes to be gone"
assert_equal expect_deps_count, Dependency.count, "expected #{nr_of_deps} dependencies to be gone" assert_equal expect_deps_count, Dependency.count, "expected #{nr_of_deps} dependencies to be gone"
end end
protected protected
def create_user(options = {}) def create_user(options = {})
options[:password_confirmation] = options[:password] unless options.has_key?(:password_confirmation) || !options.has_key?(:password) options[:password_confirmation] = options[:password] unless options.has_key?(:password_confirmation) || !options.has_key?(:password)
User.create({ :login => 'quire', :password => 'quire', :password_confirmation => 'quire' }.merge(options)) User.create({ :login => 'quire', :password => 'quire', :password_confirmation => 'quire' }.merge(options))
end end
end end

View file

@ -3,7 +3,12 @@ require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help' require 'rails/test_help'
# set config for tests. Overwrite those read from config/site.yml. Use inject to avoid warning about changing CONSTANT # set config for tests. Overwrite those read from config/site.yml. Use inject to avoid warning about changing CONSTANT
{ "authentication_schemes" => ["database"], "prefered_auth" => "database", "email_dispatch" => nil}.inject( SITE_CONFIG ) { |h, elem| h[elem[0]] = elem[1]; h } {
"authentication_schemes" => ["database"],
"prefered_auth" => "database",
"email_dispatch" => nil,
"time_zone" => "Amsterdam" # force UTC+1 so Travis triggers time zone failures
}.inject( SITE_CONFIG ) { |h, elem| h[elem[0]] = elem[1]; h }
class ActiveSupport::TestCase class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
@ -47,11 +52,11 @@ class ActiveSupport::TestCase
end end
return string return string
end end
def assert_equal_dmy(date1, date2) def assert_equal_dmy(date1, date2)
assert_equal date1.strftime("%d-%m-%y"), date2.strftime("%d-%m-%y") assert_equal date1.strftime("%d-%m-%y"), date2.strftime("%d-%m-%y")
end end
def xml_document def xml_document
@xml_document ||= HTML::Document.new(@response.body, false, true) @xml_document ||= HTML::Document.new(@response.body, false, true)
end end
@ -63,43 +68,43 @@ class ActiveSupport::TestCase
end end
class ActionController::TestCase class ActionController::TestCase
def login_as(user) def login_as(user)
@request.session['user_id'] = user ? users(user).id : nil @request.session['user_id'] = user ? users(user).id : nil
end end
def assert_ajax_create_increments_count(name) def assert_ajax_create_increments_count(name)
assert_count_after_ajax_create(name, get_class_count + 1) assert_count_after_ajax_create(name, get_class_count + 1)
end end
def assert_ajax_create_does_not_increment_count(name) def assert_ajax_create_does_not_increment_count(name)
assert_count_after_ajax_create(name, get_class_count) assert_count_after_ajax_create(name, get_class_count)
end end
def assert_count_after_ajax_create(name, expected_count) def assert_count_after_ajax_create(name, expected_count)
ajax_create(name) ajax_create(name)
assert_equal(expected_count, get_class_count) assert_equal(expected_count, get_class_count)
end end
def ajax_create(name) def ajax_create(name)
xhr :post, :create, get_model_class.downcase => {:name => name} xhr :post, :create, get_model_class.downcase => {:name => name}
end end
def assert_xml_select(*args, &block) def assert_xml_select(*args, &block)
@html_document = xml_document @html_document = xml_document
assert_select(*args, &block) assert_select(*args, &block)
end end
private private
def get_model_class def get_model_class
@controller.class.to_s.tableize.split("_")[0].camelcase.singularize #don't ask... converts ContextsController to Context @controller.class.to_s.tableize.split("_")[0].camelcase.singularize #don't ask... converts ContextsController to Context
end end
def get_class_count def get_class_count
eval("#{get_model_class}.count") eval("#{get_model_class}.count")
end end
end end
class ActionDispatch::IntegrationTest class ActionDispatch::IntegrationTest
@ -137,7 +142,7 @@ class ActionDispatch::IntegrationTest
def assert_401_unauthorized_admin def assert_401_unauthorized_admin
assert_response_and_body 401, "401 Unauthorized: Only admin users are allowed access to this function." assert_response_and_body 401, "401 Unauthorized: Only admin users are allowed access to this function."
end end
def assert_responses_with_error(error_msg) def assert_responses_with_error(error_msg)
assert_response 409 assert_response 409
assert_xml_select 'errors' do assert_xml_select 'errors' do