All patches and comments are welcome. Please squash your changes to logical
commits before using git-format-patch and git-send-email to
patches@git.madduck.net.
If you'd read over the Git project's submission guidelines and adhered to them,
I'd be especially grateful.
14 from .task import TaskWarrior, Task, ReadOnlyDictView, local_zone, DATE_FORMAT
16 # http://taskwarrior.org/docs/design/task.html , Section: The Attributes
17 TASK_STANDARD_ATTRS = (
40 total_seconds_2_6 = lambda x: x.microseconds / 1e6 + x.seconds + x.days * 24 * 3600
43 class TasklibTest(unittest.TestCase):
46 self.tmp = tempfile.mkdtemp(dir='.')
47 self.tw = TaskWarrior(data_location=self.tmp, taskrc_location='/')
50 shutil.rmtree(self.tmp)
53 class TaskFilterTest(TasklibTest):
55 def test_all_empty(self):
56 self.assertEqual(len(self.tw.tasks.all()), 0)
58 def test_all_non_empty(self):
59 Task(self.tw, description="test task").save()
60 self.assertEqual(len(self.tw.tasks.all()), 1)
61 self.assertEqual(self.tw.tasks.all()[0]['description'], 'test task')
62 self.assertEqual(self.tw.tasks.all()[0]['status'], 'pending')
64 def test_pending_non_empty(self):
65 Task(self.tw, description="test task").save()
66 self.assertEqual(len(self.tw.tasks.pending()), 1)
67 self.assertEqual(self.tw.tasks.pending()[0]['description'],
69 self.assertEqual(self.tw.tasks.pending()[0]['status'], 'pending')
71 def test_completed_empty(self):
72 Task(self.tw, description="test task").save()
73 self.assertEqual(len(self.tw.tasks.completed()), 0)
75 def test_completed_non_empty(self):
76 Task(self.tw, description="test task").save()
77 self.assertEqual(len(self.tw.tasks.completed()), 0)
78 self.tw.tasks.all()[0].done()
79 self.assertEqual(len(self.tw.tasks.completed()), 1)
81 def test_filtering_by_attribute(self):
82 Task(self.tw, description="no priority task").save()
83 Task(self.tw, priority="H", description="high priority task").save()
84 self.assertEqual(len(self.tw.tasks.all()), 2)
86 # Assert that the correct number of tasks is returned
87 self.assertEqual(len(self.tw.tasks.filter(priority="H")), 1)
89 # Assert that the correct tasks are returned
90 high_priority_task = self.tw.tasks.get(priority="H")
91 self.assertEqual(high_priority_task['description'], "high priority task")
93 def test_filtering_by_empty_attribute(self):
94 Task(self.tw, description="no priority task").save()
95 Task(self.tw, priority="H", description="high priority task").save()
96 self.assertEqual(len(self.tw.tasks.all()), 2)
98 # Assert that the correct number of tasks is returned
99 self.assertEqual(len(self.tw.tasks.filter(priority=None)), 1)
101 # Assert that the correct tasks are returned
102 no_priority_task = self.tw.tasks.get(priority=None)
103 self.assertEqual(no_priority_task['description'], "no priority task")
105 def test_filter_for_task_with_space_in_descripition(self):
106 task = Task(self.tw, description="test task")
109 filtered_task = self.tw.tasks.get(description="test task")
110 self.assertEqual(filtered_task['description'], "test task")
112 def test_filter_for_task_without_space_in_descripition(self):
113 task = Task(self.tw, description="test")
116 filtered_task = self.tw.tasks.get(description="test")
117 self.assertEqual(filtered_task['description'], "test")
119 def test_filter_for_task_with_space_in_project(self):
120 task = Task(self.tw, description="test", project="random project")
123 filtered_task = self.tw.tasks.get(project="random project")
124 self.assertEqual(filtered_task['project'], "random project")
126 def test_filter_for_task_without_space_in_project(self):
127 task = Task(self.tw, description="test", project="random")
130 filtered_task = self.tw.tasks.get(project="random")
131 self.assertEqual(filtered_task['project'], "random")
133 def test_filter_with_empty_uuid(self):
134 self.assertRaises(ValueError, lambda: self.tw.tasks.get(uuid=''))
136 def test_filter_dummy_by_status(self):
137 t = Task(self.tw, description="test")
140 tasks = self.tw.tasks.filter(status=t['status'])
141 self.assertEqual(list(tasks), [t])
143 def test_filter_dummy_by_uuid(self):
144 t = Task(self.tw, description="test")
147 tasks = self.tw.tasks.filter(uuid=t['uuid'])
148 self.assertEqual(list(tasks), [t])
150 def test_filter_dummy_by_entry(self):
151 t = Task(self.tw, description="test")
154 tasks = self.tw.tasks.filter(entry=t['entry'])
155 self.assertEqual(list(tasks), [t])
157 def test_filter_dummy_by_description(self):
158 t = Task(self.tw, description="test")
161 tasks = self.tw.tasks.filter(description=t['description'])
162 self.assertEqual(list(tasks), [t])
164 def test_filter_dummy_by_start(self):
165 t = Task(self.tw, description="test")
169 tasks = self.tw.tasks.filter(start=t['start'])
170 self.assertEqual(list(tasks), [t])
172 def test_filter_dummy_by_end(self):
173 t = Task(self.tw, description="test")
177 tasks = self.tw.tasks.filter(end=t['end'])
178 self.assertEqual(list(tasks), [t])
180 def test_filter_dummy_by_due(self):
181 t = Task(self.tw, description="test", due=datetime.datetime.now())
184 tasks = self.tw.tasks.filter(due=t['due'])
185 self.assertEqual(list(tasks), [t])
187 def test_filter_dummy_by_until(self):
188 t = Task(self.tw, description="test")
191 tasks = self.tw.tasks.filter(until=t['until'])
192 self.assertEqual(list(tasks), [t])
194 def test_filter_dummy_by_modified(self):
195 # Older TW version does not support bumping modified
197 if self.tw.version < six.text_type('2.2.0'):
198 # Python2.6 does not support SkipTest. As a workaround
199 # mark the test as passed by exiting.
200 if getattr(unittest, 'SkipTest', None) is not None:
201 raise unittest.SkipTest()
205 t = Task(self.tw, description="test")
208 tasks = self.tw.tasks.filter(modified=t['modified'])
209 self.assertEqual(list(tasks), [t])
211 def test_filter_dummy_by_scheduled(self):
212 t = Task(self.tw, description="test")
215 tasks = self.tw.tasks.filter(scheduled=t['scheduled'])
216 self.assertEqual(list(tasks), [t])
218 def test_filter_dummy_by_tags(self):
219 t = Task(self.tw, description="test", tags=["home"])
222 tasks = self.tw.tasks.filter(tags=t['tags'])
223 self.assertEqual(list(tasks), [t])
225 def test_filter_dummy_by_projects(self):
226 t = Task(self.tw, description="test", project="random")
229 tasks = self.tw.tasks.filter(project=t['project'])
230 self.assertEqual(list(tasks), [t])
232 def test_filter_by_priority(self):
233 t = Task(self.tw, description="test", priority="H")
236 tasks = self.tw.tasks.filter(priority=t['priority'])
237 self.assertEqual(list(tasks), [t])
240 class TaskTest(TasklibTest):
242 def test_create_unsaved_task(self):
243 # Make sure a new task is not saved unless explicitly called for
244 t = Task(self.tw, description="test task")
245 self.assertEqual(len(self.tw.tasks.all()), 0)
247 # TODO: once python 2.6 compatiblity is over, use context managers here
248 # and in all subsequent tests for assertRaises
250 def test_delete_unsaved_task(self):
251 t = Task(self.tw, description="test task")
252 self.assertRaises(Task.NotSaved, t.delete)
254 def test_complete_unsaved_task(self):
255 t = Task(self.tw, description="test task")
256 self.assertRaises(Task.NotSaved, t.done)
258 def test_refresh_unsaved_task(self):
259 t = Task(self.tw, description="test task")
260 self.assertRaises(Task.NotSaved, t.refresh)
262 def test_start_unsaved_task(self):
263 t = Task(self.tw, description="test task")
264 self.assertRaises(Task.NotSaved, t.start)
266 def test_delete_deleted_task(self):
267 t = Task(self.tw, description="test task")
271 self.assertRaises(Task.DeletedTask, t.delete)
273 def test_complete_completed_task(self):
274 t = Task(self.tw, description="test task")
278 self.assertRaises(Task.CompletedTask, t.done)
280 def test_start_completed_task(self):
281 t = Task(self.tw, description="test task")
285 self.assertRaises(Task.CompletedTask, t.start)
287 def test_complete_deleted_task(self):
288 t = Task(self.tw, description="test task")
292 self.assertRaises(Task.DeletedTask, t.done)
294 def test_start_completed_task(self):
295 t = Task(self.tw, description="test task")
299 self.assertRaises(Task.CompletedTask, t.start)
301 def test_starting_task(self):
302 t = Task(self.tw, description="test task")
303 now = t.datetime_normalizer(datetime.datetime.now())
307 self.assertTrue(now.replace(microsecond=0) <= t['start'])
308 self.assertEqual(t['status'], 'pending')
310 def test_completing_task(self):
311 t = Task(self.tw, description="test task")
312 now = t.datetime_normalizer(datetime.datetime.now())
316 self.assertTrue(now.replace(microsecond=0) <= t['end'])
317 self.assertEqual(t['status'], 'completed')
319 def test_deleting_task(self):
320 t = Task(self.tw, description="test task")
321 now = t.datetime_normalizer(datetime.datetime.now())
325 self.assertTrue(now.replace(microsecond=0) <= t['end'])
326 self.assertEqual(t['status'], 'deleted')
328 def test_modify_simple_attribute_without_space(self):
329 t = Task(self.tw, description="test")
332 self.assertEquals(t['description'], "test")
334 t['description'] = "test-modified"
337 self.assertEquals(t['description'], "test-modified")
339 def test_modify_simple_attribute_with_space(self):
340 # Space can pose problems with parsing
341 t = Task(self.tw, description="test task")
344 self.assertEquals(t['description'], "test task")
346 t['description'] = "test task modified"
349 self.assertEquals(t['description'], "test task modified")
351 def test_empty_dependency_set_of_unsaved_task(self):
352 t = Task(self.tw, description="test task")
353 self.assertEqual(t['depends'], set())
355 def test_empty_dependency_set_of_saved_task(self):
356 t = Task(self.tw, description="test task")
358 self.assertEqual(t['depends'], set())
360 def test_set_unsaved_task_as_dependency(self):
361 # Adds only one dependency to task with no dependencies
362 t = Task(self.tw, description="test task")
363 dependency = Task(self.tw, description="needs to be done first")
365 # We only save the parent task, dependency task is unsaved
367 t['depends'] = set([dependency])
369 self.assertRaises(Task.NotSaved, t.save)
371 def test_set_simple_dependency_set(self):
372 # Adds only one dependency to task with no dependencies
373 t = Task(self.tw, description="test task")
374 dependency = Task(self.tw, description="needs to be done first")
379 t['depends'] = set([dependency])
381 self.assertEqual(t['depends'], set([dependency]))
383 def test_set_complex_dependency_set(self):
384 # Adds two dependencies to task with no dependencies
385 t = Task(self.tw, description="test task")
386 dependency1 = Task(self.tw, description="needs to be done first")
387 dependency2 = Task(self.tw, description="needs to be done second")
393 t['depends'] = set([dependency1, dependency2])
395 self.assertEqual(t['depends'], set([dependency1, dependency2]))
397 def test_remove_from_dependency_set(self):
398 # Removes dependency from task with two dependencies
399 t = Task(self.tw, description="test task")
400 dependency1 = Task(self.tw, description="needs to be done first")
401 dependency2 = Task(self.tw, description="needs to be done second")
406 t['depends'] = set([dependency1, dependency2])
409 t['depends'].remove(dependency2)
412 self.assertEqual(t['depends'], set([dependency1]))
414 def test_add_to_dependency_set(self):
415 # Adds dependency to task with one dependencies
416 t = Task(self.tw, description="test task")
417 dependency1 = Task(self.tw, description="needs to be done first")
418 dependency2 = Task(self.tw, description="needs to be done second")
423 t['depends'] = set([dependency1])
426 t['depends'].add(dependency2)
429 self.assertEqual(t['depends'], set([dependency1, dependency2]))
431 def test_add_to_empty_dependency_set(self):
432 # Adds dependency to task with one dependencies
433 t = Task(self.tw, description="test task")
434 dependency = Task(self.tw, description="needs to be done first")
438 t['depends'].add(dependency)
441 self.assertEqual(t['depends'], set([dependency]))
443 def test_simple_dependency_set_save_repeatedly(self):
444 # Adds only one dependency to task with no dependencies
445 t = Task(self.tw, description="test task")
446 dependency = Task(self.tw, description="needs to be done first")
449 t['depends'] = set([dependency])
452 # We taint the task, but keep depends intact
453 t['description'] = "test task modified"
456 self.assertEqual(t['depends'], set([dependency]))
458 # We taint the task, but assign the same set to the depends
459 t['depends'] = set([dependency])
460 t['description'] = "test task modified again"
463 self.assertEqual(t['depends'], set([dependency]))
465 def test_compare_different_tasks(self):
466 # Negative: compare two different tasks
467 t1 = Task(self.tw, description="test task")
468 t2 = Task(self.tw, description="test task")
473 self.assertEqual(t1 == t2, False)
475 def test_compare_same_task_object(self):
476 # Compare Task object wit itself
477 t = Task(self.tw, description="test task")
480 self.assertEqual(t == t, True)
482 def test_compare_same_task(self):
483 # Compare the same task using two different objects
484 t1 = Task(self.tw, description="test task")
487 t2 = self.tw.tasks.get(uuid=t1['uuid'])
488 self.assertEqual(t1 == t2, True)
490 def test_compare_unsaved_tasks(self):
491 # t1 and t2 are unsaved tasks, considered to be unequal
492 # despite the content of data
493 t1 = Task(self.tw, description="test task")
494 t2 = Task(self.tw, description="test task")
496 self.assertEqual(t1 == t2, False)
498 def test_hash_unsaved_tasks(self):
499 # Considered equal, it's the same object
500 t1 = Task(self.tw, description="test task")
502 self.assertEqual(hash(t1) == hash(t2), True)
504 def test_hash_same_task(self):
505 # Compare the hash of the task using two different objects
506 t1 = Task(self.tw, description="test task")
509 t2 = self.tw.tasks.get(uuid=t1['uuid'])
510 self.assertEqual(t1.__hash__(), t2.__hash__())
512 def test_adding_task_with_priority(self):
513 t = Task(self.tw, description="test task", priority="M")
516 def test_removing_priority_with_none(self):
517 t = Task(self.tw, description="test task", priority="L")
520 # Remove the priority mark
524 # Assert that priority is not there after saving
525 self.assertEqual(t['priority'], None)
527 def test_adding_task_with_due_time(self):
528 t = Task(self.tw, description="test task", due=datetime.datetime.now())
531 def test_removing_due_time_with_none(self):
532 t = Task(self.tw, description="test task", due=datetime.datetime.now())
535 # Remove the due timestamp
539 # Assert that due timestamp is no longer there
540 self.assertEqual(t['due'], None)
542 def test_modified_fields_new_task(self):
545 # This should be empty with new task
546 self.assertEqual(set(t._modified_fields), set())
549 t['description'] = "test task"
550 self.assertEqual(set(t._modified_fields), set(['description']))
552 t['due'] = datetime.datetime(2014, 2, 14, 14, 14, 14) # <3
553 self.assertEqual(set(t._modified_fields), set(['description', 'due']))
555 t['project'] = "test project"
556 self.assertEqual(set(t._modified_fields),
557 set(['description', 'due', 'project']))
559 # List of modified fields should clear out when saved
561 self.assertEqual(set(t._modified_fields), set())
563 # Reassigning the fields with the same values now should not produce
565 t['description'] = "test task"
566 t['due'] = datetime.datetime(2014, 2, 14, 14, 14, 14) # <3
567 t['project'] = "test project"
568 self.assertEqual(set(t._modified_fields), set())
570 def test_modified_fields_loaded_task(self):
574 t['description'] = "test task"
575 t['due'] = datetime.datetime(2014, 2, 14, 14, 14, 14) # <3
576 t['project'] = "test project"
578 dependency = Task(self.tw, description="dependency")
580 t['depends'] = set([dependency])
582 # List of modified fields should clear out when saved
584 self.assertEqual(set(t._modified_fields), set())
586 # Get the task by using a filter by UUID
587 t2 = self.tw.tasks.get(uuid=t['uuid'])
589 # Reassigning the fields with the same values now should not produce
591 t['description'] = "test task"
592 t['due'] = datetime.datetime(2014, 2, 14, 14, 14, 14) # <3
593 t['project'] = "test project"
594 t['depends'] = set([dependency])
595 self.assertEqual(set(t._modified_fields), set())
597 def test_modified_fields_not_affected_by_reading(self):
600 for field in TASK_STANDARD_ATTRS:
603 self.assertEqual(set(t._modified_fields), set())
605 def test_setting_read_only_attrs_through_init(self):
606 # Test that we are unable to set readonly attrs through __init__
607 for readonly_key in Task.read_only_fields:
608 kwargs = {'description': 'test task', readonly_key: 'value'}
609 self.assertRaises(RuntimeError,
610 lambda: Task(self.tw, **kwargs))
612 def test_setting_read_only_attrs_through_setitem(self):
613 # Test that we are unable to set readonly attrs through __init__
614 for readonly_key in Task.read_only_fields:
615 t = Task(self.tw, description='test task')
616 self.assertRaises(RuntimeError,
617 lambda: t.__setitem__(readonly_key, 'value'))
619 def test_saving_unmodified_task(self):
620 t = Task(self.tw, description="test task")
624 def test_adding_tag_by_appending(self):
625 t = Task(self.tw, description="test task", tags=['test1'])
627 t['tags'].append('test2')
629 self.assertEqual(t['tags'], ['test1', 'test2'])
631 def test_adding_tag_by_appending_empty(self):
632 t = Task(self.tw, description="test task")
634 t['tags'].append('test')
636 self.assertEqual(t['tags'], ['test'])
638 def test_serializers_returning_empty_string_for_none(self):
639 # Test that any serializer returns '' when passed None
641 serializers = [getattr(t, serializer_name) for serializer_name in
642 filter(lambda x: x.startswith('serialize_'), dir(t))]
643 for serializer in serializers:
644 self.assertEqual(serializer(None), '')
646 def test_deserializer_returning_empty_value_for_empty_string(self):
647 # Test that any deserializer returns empty value when passed ''
649 deserializers = [getattr(t, deserializer_name) for deserializer_name in
650 filter(lambda x: x.startswith('deserialize_'), dir(t))]
651 for deserializer in deserializers:
652 self.assertTrue(deserializer('') in (None, [], set()))
654 def test_normalizers_handling_none(self):
655 # Test that any normalizer can handle None as a valid value
658 for key in TASK_STANDARD_ATTRS:
659 t._normalize(key, None)
661 def test_recurrent_task_generation(self):
662 today = datetime.date.today()
663 t = Task(self.tw, description="brush teeth",
664 due=today, recur="daily")
666 self.assertEqual(len(self.tw.tasks.pending()), 2)
668 def test_modify_number_of_tasks_at_once(self):
669 for i in range(1, 100):
670 Task(self.tw, description="test task %d" % i, tags=['test']).save()
672 self.tw.execute_command(['+test', 'mod', 'unified', 'description'])
675 class TaskFromHookTest(TasklibTest):
677 input_add_data = six.StringIO(
678 '{"description":"Buy some milk",'
679 '"entry":"20141118T050231Z",'
680 '"status":"pending",'
681 '"uuid":"a360fc44-315c-4366-b70c-ea7e7520b749"}')
683 input_modify_data = six.StringIO(input_add_data.getvalue() + '\n' +
684 '{"description":"Buy some milk finally",'
685 '"entry":"20141118T050231Z",'
686 '"status":"completed",'
687 '"uuid":"a360fc44-315c-4366-b70c-ea7e7520b749"}')
689 exported_raw_data = (
691 '"due":"20150101T232323Z",'
692 '"description":"test task"}')
694 def test_setting_up_from_add_hook_input(self):
695 t = Task.from_input(input_file=self.input_add_data, warrior=self.tw)
696 self.assertEqual(t['description'], "Buy some milk")
697 self.assertEqual(t.pending, True)
699 def test_setting_up_from_modified_hook_input(self):
700 t = Task.from_input(input_file=self.input_modify_data, modify=True,
702 self.assertEqual(t['description'], "Buy some milk finally")
703 self.assertEqual(t.pending, False)
704 self.assertEqual(t.completed, True)
706 self.assertEqual(t._original_data['status'], "pending")
707 self.assertEqual(t._original_data['description'], "Buy some milk")
708 self.assertEqual(set(t._modified_fields),
709 set(['status', 'description']))
711 def test_export_data(self):
712 t = Task(self.tw, description="test task",
714 due=pytz.utc.localize(datetime.datetime(2015,1,1,23,23,23)))
716 # Check that the output is a permutation of:
717 # {"project":"Home","description":"test task","due":"20150101232323Z"}
718 allowed_segments = self.exported_raw_data[1:-1].split(',')
720 '{' + ','.join(segments) + '}'
721 for segments in itertools.permutations(allowed_segments)
724 self.assertTrue(any(t.export_data() == expected
725 for expected in allowed_output))
727 class TimezoneAwareDatetimeTest(TasklibTest):
730 super(TimezoneAwareDatetimeTest, self).setUp()
731 self.zone = local_zone
732 self.localdate_naive = datetime.datetime(2015,2,2)
733 self.localtime_naive = datetime.datetime(2015,2,2,0,0,0)
734 self.localtime_aware = self.zone.localize(self.localtime_naive)
735 self.utctime_aware = self.localtime_aware.astimezone(pytz.utc)
737 def test_timezone_naive_datetime_setitem(self):
738 t = Task(self.tw, description="test task")
739 t['due'] = self.localtime_naive
740 self.assertEqual(t['due'], self.localtime_aware)
742 def test_timezone_naive_datetime_using_init(self):
743 t = Task(self.tw, description="test task", due=self.localtime_naive)
744 self.assertEqual(t['due'], self.localtime_aware)
746 def test_filter_by_naive_datetime(self):
747 t = Task(self.tw, description="task1", due=self.localtime_naive)
749 matching_tasks = self.tw.tasks.filter(due=self.localtime_naive)
750 self.assertEqual(len(matching_tasks), 1)
752 def test_serialize_naive_datetime(self):
753 t = Task(self.tw, description="task1", due=self.localtime_naive)
754 self.assertEqual(json.loads(t.export_data())['due'],
755 self.utctime_aware.strftime(DATE_FORMAT))
757 def test_timezone_naive_date_setitem(self):
758 t = Task(self.tw, description="test task")
759 t['due'] = self.localdate_naive
760 self.assertEqual(t['due'], self.localtime_aware)
762 def test_timezone_naive_date_using_init(self):
763 t = Task(self.tw, description="test task", due=self.localdate_naive)
764 self.assertEqual(t['due'], self.localtime_aware)
766 def test_filter_by_naive_date(self):
767 t = Task(self.tw, description="task1", due=self.localdate_naive)
769 matching_tasks = self.tw.tasks.filter(due=self.localdate_naive)
770 self.assertEqual(len(matching_tasks), 1)
772 def test_serialize_naive_date(self):
773 t = Task(self.tw, description="task1", due=self.localdate_naive)
774 self.assertEqual(json.loads(t.export_data())['due'],
775 self.utctime_aware.strftime(DATE_FORMAT))
777 def test_timezone_aware_datetime_setitem(self):
778 t = Task(self.tw, description="test task")
779 t['due'] = self.localtime_aware
780 self.assertEqual(t['due'], self.localtime_aware)
782 def test_timezone_aware_datetime_using_init(self):
783 t = Task(self.tw, description="test task", due=self.localtime_aware)
784 self.assertEqual(t['due'], self.localtime_aware)
786 def test_filter_by_aware_datetime(self):
787 t = Task(self.tw, description="task1", due=self.localtime_aware)
789 matching_tasks = self.tw.tasks.filter(due=self.localtime_aware)
790 self.assertEqual(len(matching_tasks), 1)
792 def test_serialize_aware_datetime(self):
793 t = Task(self.tw, description="task1", due=self.localtime_aware)
794 self.assertEqual(json.loads(t.export_data())['due'],
795 self.utctime_aware.strftime(DATE_FORMAT))
797 class DatetimeStringTest(TasklibTest):
799 def test_simple_now_conversion(self):
800 if self.tw.version < six.text_type('2.4.0'):
801 # Python2.6 does not support SkipTest. As a workaround
802 # mark the test as passed by exiting.
803 if getattr(unittest, 'SkipTest', None) is not None:
804 raise unittest.SkipTest()
808 t = Task(self.tw, description="test task", due="now")
809 now = local_zone.localize(datetime.datetime.now())
811 # Assert that both times are not more than 5 seconds apart
812 if sys.version > (2,6):
813 self.assertTrue((now - t['due']).total_seconds() < 5)
814 self.assertTrue((t['due'] - now).total_seconds() < 5)
816 self.assertTrue(total_seconds_2_6(now - t['due']) < 5)
817 self.assertTrue(total_seconds_2_6(t['due'] - now) < 5)
819 def test_simple_eoy_conversion(self):
820 if self.tw.version < six.text_type('2.4.0'):
821 # Python2.6 does not support SkipTest. As a workaround
822 # mark the test as passed by exiting.
823 if getattr(unittest, 'SkipTest', None) is not None:
824 raise unittest.SkipTest()
828 t = Task(self.tw, description="test task", due="eoy")
829 now = local_zone.localize(datetime.datetime.now())
830 eoy = local_zone.localize(datetime.datetime(
838 self.assertEqual(eoy, t['due'])
840 def test_complex_eoy_conversion(self):
841 if self.tw.version < six.text_type('2.4.0'):
842 # Python2.6 does not support SkipTest. As a workaround
843 # mark the test as passed by exiting.
844 if getattr(unittest, 'SkipTest', None) is not None:
845 raise unittest.SkipTest()
849 t = Task(self.tw, description="test task", due="eoy - 4 months")
850 now = local_zone.localize(datetime.datetime.now())
851 due_date = local_zone.localize(datetime.datetime(
858 )) - datetime.timedelta(0,4 * 30 * 86400)
859 self.assertEqual(due_date, t['due'])
861 def test_filtering_with_string_datetime(self):
862 if self.tw.version < six.text_type('2.4.0'):
863 # Python2.6 does not support SkipTest. As a workaround
864 # mark the test as passed by exiting.
865 if getattr(unittest, 'SkipTest', None) is not None:
866 raise unittest.SkipTest()
870 t = Task(self.tw, description="test task",
871 due=datetime.datetime.now() - datetime.timedelta(0,2))
873 self.assertEqual(len(self.tw.tasks.filter(due__before="now")), 1)
875 class AnnotationTest(TasklibTest):
878 super(AnnotationTest, self).setUp()
879 Task(self.tw, description="test task").save()
881 def test_adding_annotation(self):
882 task = self.tw.tasks.get()
883 task.add_annotation('test annotation')
884 self.assertEqual(len(task['annotations']), 1)
885 ann = task['annotations'][0]
886 self.assertEqual(ann['description'], 'test annotation')
888 def test_removing_annotation(self):
889 task = self.tw.tasks.get()
890 task.add_annotation('test annotation')
891 ann = task['annotations'][0]
893 self.assertEqual(len(task['annotations']), 0)
895 def test_removing_annotation_by_description(self):
896 task = self.tw.tasks.get()
897 task.add_annotation('test annotation')
898 task.remove_annotation('test annotation')
899 self.assertEqual(len(task['annotations']), 0)
901 def test_removing_annotation_by_obj(self):
902 task = self.tw.tasks.get()
903 task.add_annotation('test annotation')
904 ann = task['annotations'][0]
905 task.remove_annotation(ann)
906 self.assertEqual(len(task['annotations']), 0)
908 def test_annotation_after_modification(self):
909 task = self.tw.tasks.get()
910 task['project'] = 'test'
911 task.add_annotation('I should really do this task')
912 self.assertEqual(task['project'], 'test')
914 self.assertEqual(task['project'], 'test')
916 def test_serialize_annotations(self):
917 # Test that serializing annotations is possible
918 t = Task(self.tw, description="test")
921 t.add_annotation("annotation1")
922 t.add_annotation("annotation2")
924 data = t._serialize('annotations', t._data['annotations'])
926 self.assertEqual(len(data), 2)
927 self.assertEqual(type(data[0]), dict)
928 self.assertEqual(type(data[1]), dict)
930 self.assertEqual(data[0]['description'], "annotation1")
931 self.assertEqual(data[1]['description'], "annotation2")
934 class UnicodeTest(TasklibTest):
936 def test_unicode_task(self):
937 Task(self.tw, description="†åßk").save()
940 def test_non_unicode_task(self):
941 Task(self.tw, description="test task").save()
944 class ReadOnlyDictViewTest(unittest.TestCase):
947 self.sample = dict(l=[1,2,3], d={'k':'v'})
948 self.original_sample = copy.deepcopy(self.sample)
949 self.view = ReadOnlyDictView(self.sample)
951 def test_readonlydictview_getitem(self):
953 self.assertEqual(l, self.sample['l'])
955 # Assert that modification changed only copied value
957 self.assertNotEqual(l, self.sample['l'])
959 # Assert that viewed dict is not changed
960 self.assertEqual(self.sample, self.original_sample)
962 def test_readonlydictview_contains(self):
963 self.assertEqual('l' in self.view, 'l' in self.sample)
964 self.assertEqual('d' in self.view, 'd' in self.sample)
965 self.assertEqual('k' in self.view, 'k' in self.sample)
967 # Assert that viewed dict is not changed
968 self.assertEqual(self.sample, self.original_sample)
970 def test_readonlydictview_iter(self):
971 self.assertEqual(list(k for k in self.view),
972 list(k for k in self.sample))
974 # Assert the view is correct after modification
975 self.sample['new'] = 'value'
976 self.assertEqual(list(k for k in self.view),
977 list(k for k in self.sample))
979 def test_readonlydictview_len(self):
980 self.assertEqual(len(self.view), len(self.sample))
982 # Assert the view is correct after modification
983 self.sample['new'] = 'value'
984 self.assertEqual(len(self.view), len(self.sample))
986 def test_readonlydictview_get(self):
987 l = self.view.get('l')
988 self.assertEqual(l, self.sample.get('l'))
990 # Assert that modification changed only copied value
992 self.assertNotEqual(l, self.sample.get('l'))
994 # Assert that viewed dict is not changed
995 self.assertEqual(self.sample, self.original_sample)
997 def test_readonlydict_items(self):
998 view_items = self.view.items()
999 sample_items = list(self.sample.items())
1000 self.assertEqual(view_items, sample_items)
1002 view_items.append('newkey')
1003 self.assertNotEqual(view_items, sample_items)
1004 self.assertEqual(self.sample, self.original_sample)
1006 def test_readonlydict_values(self):
1007 view_values = self.view.values()
1008 sample_values = list(self.sample.values())
1009 self.assertEqual(view_values, sample_values)
1011 view_list_item = list(filter(lambda x: type(x) is list,
1013 view_list_item.append(4)
1014 self.assertNotEqual(view_values, sample_values)
1015 self.assertEqual(self.sample, self.original_sample)