calendarium.utils: 20 total statements, 100.0% covered

Generated: Sun 2013-03-24 21:11 CET

Source file: /home/tobi/Projects/calendarium/src/calendarium/utils.py

Stats: 18 executed, 0 missed, 2 excluded, 55 ignored

  1. """
  2. Utils for the ``calendarium`` app.
  3. The code of these utils is highly influenced by or taken from the utils of
  4. django-schedule:
  5. https://github.com/thauber/django-schedule/blob/master/schedule/utils.py
  6. """
  7. import time
  8. from django.utils import timezone
  9. def now(**kwargs):
  10. """
  11. Utility function to zero microseconds to avoid inaccuracy.
  12. I replaced the microseconds, because there is some slightly varying
  13. difference that occurs out of unknown reason. Since we probably never
  14. schedule events on microsecond basis, seconds and microseconds will be
  15. zeroed everywhere.
  16. """
  17. return timezone.now(**kwargs).replace(second=0, microsecond=0)
  18. def monday_of_week(year, week):
  19. """
  20. Returns a datetime for the monday of the given week of the given year.
  21. """
  22. str_time = time.strptime('{0} {1} 1'.format(year, week), '%Y %W %w')
  23. date = timezone.datetime(year=str_time.tm_year, month=str_time.tm_mon,
  24. day=str_time.tm_mday, tzinfo=timezone.utc)
  25. if timezone.datetime(year, 1, 4).isoweekday() > 4:
  26. # ISO 8601 where week 1 is the first week that has at least 4 days in
  27. # the current year
  28. date -= timezone.timedelta(days=7)
  29. return date
  30. class OccurrenceReplacer(object):
  31. """
  32. When getting a list of occurrences, the last thing that needs to be done
  33. before passing it forward is to make sure all of the occurrences that
  34. have been stored in the datebase replace, in the list you are returning,
  35. the generated ones that are equivalent. This class makes this easier.
  36. """
  37. def __init__(self, persisted_occurrences):
  38. lookup = [
  39. ((occ.event, occ.original_start, occ.original_end), occ) for
  40. occ in persisted_occurrences]
  41. self.lookup = dict(lookup)
  42. def get_occurrence(self, occ):
  43. """
  44. Return a persisted occurrences matching the occ and remove it from
  45. lookup since it has already been matched
  46. """
  47. return self.lookup.pop(
  48. (occ.event, occ.original_start, occ.original_end),
  49. occ)
  50. def has_occurrence(self, occ):
  51. return (occ.event, occ.original_start, occ.original_end) in self.lookup
  52. def get_additional_occurrences(self, start, end):
  53. """
  54. Return persisted occurrences which are now in the period
  55. """
  56. return [occ for key, occ in self.lookup.items() if (
  57. (end and occ.start < end)
  58. and occ.end >= start and not occ.cancelled)]