1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
|
import abc
import datetime
import time
import unittest
import unittest.util
from decimal import Decimal
from keyword import kwlist
from dateutil.relativedelta import relativedelta
from exchangelib.errors import (
ErrorInvalidPropertySet,
ErrorInvalidValueForProperty,
ErrorIrresolvableConflict,
ErrorItemNotFound,
ErrorPropertyUpdate,
ErrorUnsupportedPathForQuery,
)
from exchangelib.extended_properties import ExternId
from exchangelib.fields import (
AttachmentField,
BodyField,
BooleanField,
ChoiceField,
CultureField,
FieldPath,
IdField,
IndexedField,
TextField,
)
from exchangelib.indexed_properties import MultiFieldIndexedElement, SingleFieldIndexedElement
from exchangelib.items import BaseItem, CalendarItem, Contact, DistributionList, Item, Task
from exchangelib.properties import Attendee, Mailbox
from exchangelib.queryset import Q
from exchangelib.util import value_to_xml_text
from ..common import (
EWSTest,
get_random_choice,
get_random_date,
get_random_datetime,
get_random_datetime_range,
get_random_decimal,
get_random_string,
get_random_substring,
)
class BaseItemTest(EWSTest, metaclass=abc.ABCMeta):
TEST_FOLDER = None
FOLDER_CLASS = None
ITEM_CLASS = None
@classmethod
def setUpClass(cls):
if cls is BaseItemTest:
raise unittest.SkipTest("Skip BaseItemTest, it's only for inheritance")
super().setUpClass()
def setUp(self):
super().setUp()
if self.TEST_FOLDER:
self.test_folder = getattr(self.account, self.TEST_FOLDER)
else:
self.test_folder = self.get_test_folder(self.account.inbox).save()
def tearDown(self):
# Delete all test items and delivery receipts
try:
self.test_folder.filter(
Q(categories__contains=self.categories) | Q(subject__startswith="Delivered: Subject: ")
).delete()
if not self.TEST_FOLDER:
self.test_folder.delete()
except Exception as e:
print(f"Exception in tearDown of {self}: {e}")
pass
super().tearDown()
def get_random_insert_kwargs(self):
insert_kwargs = {}
for f in self.ITEM_CLASS.FIELDS:
if not f.supports_version(self.account.version):
# Cannot be used with this EWS version
continue
if self.ITEM_CLASS == CalendarItem and f in CalendarItem.timezone_fields():
# Timezone fields will (and must) be populated automatically from the timestamp
continue
if f.is_read_only:
# These cannot be created
continue
if f.name == "mime_content":
# This needs special formatting. See separate test_mime_content() test
continue
if f.name == "attachments":
# Testing attachments is heavy. Leave this to specific tests
insert_kwargs[f.name] = []
continue
if f.name == "resources":
# The test server doesn't have any resources
insert_kwargs[f.name] = []
continue
if f.name == "optional_attendees":
# 'optional_attendees' and 'required_attendees' are mutually exclusive
insert_kwargs[f.name] = None
continue
if f.name == "start":
start = get_random_date()
insert_kwargs[f.name], insert_kwargs["end"] = get_random_datetime_range(
start_date=start, end_date=start, tz=self.account.default_timezone
)
insert_kwargs["recurrence"] = self.random_val(self.ITEM_CLASS.get_field_by_fieldname("recurrence"))
insert_kwargs["recurrence"].boundary.start = insert_kwargs[f.name].date()
continue
if f.name == "start_date":
insert_kwargs[f.name] = get_random_datetime().date()
insert_kwargs["due_date"] = insert_kwargs[f.name]
# Don't set 'recurrence' here. It's difficult to test updates so we'll test task recurrence separately
insert_kwargs["recurrence"] = None
continue
if f.name == "end":
continue
if f.name == "is_all_day":
# For CalendarItem instances, the 'is_all_day' attribute affects the 'start' and 'end' values. Changing
# from 'false' to 'true' removes the time part of these datetimes.
insert_kwargs["is_all_day"] = False
continue
if f.name == "recurrence":
continue
if f.name == "due_date":
continue
if f.name == "start_date":
continue
if f.name == "status":
# Start with an incomplete task
status = get_random_choice(set(f.supported_choices(version=self.account.version)) - {Task.COMPLETED})
insert_kwargs[f.name] = status
if status == Task.NOT_STARTED:
insert_kwargs["percent_complete"] = Decimal(0)
else:
insert_kwargs["percent_complete"] = get_random_decimal(1, 99)
continue
if f.name == "percent_complete":
continue
insert_kwargs[f.name] = self.random_val(f)
return insert_kwargs
def get_item_fields(self):
return (
self.ITEM_CLASS.get_field_by_fieldname("id"),
self.ITEM_CLASS.get_field_by_fieldname("changekey"),
) + tuple(f for f in self.ITEM_CLASS.FIELDS if f.name != "_id")
def get_random_update_kwargs(self, item, insert_kwargs):
update_kwargs = {}
for f in self.ITEM_CLASS.FIELDS:
if not f.supports_version(self.account.version):
# Cannot be used with this EWS version
continue
if self.ITEM_CLASS == CalendarItem and f in CalendarItem.timezone_fields():
# Timezone fields will (and must) be populated automatically from the timestamp
continue
if f.is_read_only:
# These cannot be changed
continue
if not item.is_draft and f.is_read_only_after_send:
# These cannot be changed when the item is no longer a draft
continue
if f.name == "message_id" and f.is_read_only_after_send:
# Cannot be updated, regardless of draft status
continue
if f.name == "attachments":
# Testing attachments is heavy. Leave this to specific tests
update_kwargs[f.name] = []
continue
if f.name == "resources":
# The test server doesn't have any resources
update_kwargs[f.name] = []
continue
if isinstance(f, AttachmentField):
# Attachments are handled separately
continue
if f.name == "start":
start = get_random_date(start_date=insert_kwargs["end"].date())
update_kwargs[f.name], update_kwargs["end"] = get_random_datetime_range(
start_date=start, end_date=start, tz=self.account.default_timezone
)
update_kwargs["recurrence"] = self.random_val(self.ITEM_CLASS.get_field_by_fieldname("recurrence"))
update_kwargs["recurrence"].boundary.start = update_kwargs[f.name].date()
continue
if f.name == "start_date":
update_kwargs[f.name] = get_random_datetime().date()
update_kwargs["due_date"] = update_kwargs[f.name]
# Don't set 'recurrence' here. It's difficult to test updates so we'll test task recurrence separately
update_kwargs["recurrence"] = None
continue
if f.name == "end":
continue
if f.name == "recurrence":
continue
if f.name == "due_date":
continue
if f.name == "start_date":
continue
if f.name == "status":
# Update task to a completed state
update_kwargs[f.name] = Task.COMPLETED
update_kwargs["percent_complete"] = Decimal(100)
continue
if f.name == "percent_complete":
continue
if f.name == "reminder_is_set":
if self.ITEM_CLASS == Task:
# Task type doesn't allow updating 'reminder_is_set' to True
update_kwargs[f.name] = False
else:
update_kwargs[f.name] = not insert_kwargs[f.name]
continue
if isinstance(f, BooleanField):
update_kwargs[f.name] = not insert_kwargs[f.name]
continue
if f.value_cls in (Mailbox, Attendee):
if insert_kwargs[f.name] is None:
update_kwargs[f.name] = self.random_val(f)
else:
update_kwargs[f.name] = None
continue
update_kwargs[f.name] = self.random_val(f)
if self.ITEM_CLASS == CalendarItem:
# EWS always sets due date to 'start'
update_kwargs["reminder_due_by"] = update_kwargs["start"]
if update_kwargs.get("is_all_day", False):
# For is_all_day items, EWS will remove the time part of start and end values
update_kwargs["start"] = update_kwargs["start"].date()
update_kwargs["end"] = (update_kwargs["end"] + datetime.timedelta(days=1)).date()
return update_kwargs
def get_test_item(self, categories=None, **kwargs):
folder = kwargs.pop("folder", self.test_folder)
item_kwargs = self.get_random_insert_kwargs()
item_kwargs["categories"] = categories or self.categories
return self.ITEM_CLASS(account=self.account, folder=folder, **item_kwargs)
def get_test_folder(self, folder=None):
return self.FOLDER_CLASS(parent=folder or self.test_folder, name=get_random_string(8))
def get_item_by_id(self, item, folder=None):
_id, changekey = item if isinstance(item, tuple) else (item.id, item.changekey)
return (folder or self.account.root).get(id=_id, changekey=changekey)
def safe_save(self, item, **kwargs):
# Sometimes, after somewhere between 2 and 20 updates, Exchange will decide to randomly update the changekey on
# its own. I cannot find any pattern to this, but tests that use the same item over and over to test updates on
# various fields become horribly unstable. This helper method hides that bug.
try:
item.save(**kwargs)
except ErrorIrresolvableConflict:
item.changekey = None
refreshed_item = self.get_item_by_id(item, item.folder)
item.changekey = refreshed_item.changekey
item.save(**kwargs)
def safe_cancel(self, item):
# See self.safe_save()
try:
item.cancel()
except ErrorIrresolvableConflict:
item.changekey = None
refreshed_item = self.get_item_by_id(item, item.folder)
item.changekey = refreshed_item.changekey
item.cancel()
class CommonItemTest(BaseItemTest):
@classmethod
def setUpClass(cls):
if cls is CommonItemTest:
raise unittest.SkipTest("Skip CommonItemTest, it's only for inheritance")
super().setUpClass()
def test_field_names(self):
# Test that fieldnames don't clash with Python keywords
for f in self.ITEM_CLASS.FIELDS:
self.assertNotIn(f.name, kwlist)
def test_magic(self):
item = self.get_test_item()
self.assertIn("subject=", str(item))
self.assertIn(item.__class__.__name__, repr(item))
def test_queryset_nonsearchable_fields(self):
for f in self.get_item_fields():
with self.subTest(f=f):
if f.is_searchable or isinstance(f, IdField) or not f.supports_version(self.account.version):
continue
if f.name in ("percent_complete", "allow_new_time_proposal"):
# These fields don't raise an error when used in a filter, but also don't match anything in a filter
continue
try:
filter_val = f.clean(self.random_val(f))
filter_kwargs = {f"{f.name}__in": filter_val} if f.is_list else {f.name: filter_val}
# We raise ValueError when searching on an is_searchable=False field
with self.assertRaises(ValueError):
list(self.test_folder.filter(**filter_kwargs))
# Make sure the is_searchable=False setting is correct by searching anyway and testing that this
# fails server-side. This only works for values that we are actually able to convert to a search
# string.
try:
value_to_xml_text(filter_val)
except TypeError:
continue
f.is_searchable = True
if f.name in ("reminder_due_by", "conversation_index"):
# Filtering is accepted but doesn't work
self.assertEqual(self.test_folder.filter(**filter_kwargs).count(), 0)
else:
try:
list(self.test_folder.filter(**filter_kwargs))
except (ErrorUnsupportedPathForQuery, ErrorInvalidValueForProperty):
pass
finally:
f.is_searchable = False
def _reduce_fields_for_filter(self, item, fields):
for f in fields:
if not f.supports_version(self.account.version):
# Cannot be used with this EWS version
continue
if not f.is_searchable:
# Cannot be used in a QuerySet
continue
if getattr(item, f.name) is None:
# We cannot filter on None values
continue
if self.ITEM_CLASS == Contact and f.name in ("body", "display_name"):
# filtering 'body' or 'display_name' on Contact items doesn't work at all. Error in EWS?
continue
yield f
def _run_filter_tests(self, qs, f, filter_kwargs, val):
for kw in filter_kwargs:
with self.subTest(f=f, kw=kw):
retries = 0
matches = qs.filter(**kw).count()
# __in with an empty list returns an empty result
expected = 0 if f.is_list and not val and list(kw)[0].endswith("__in") else 1
if f.is_complex and matches != expected:
# Complex fields sometimes fail a search using generated data. In practice, they almost always
# work anyway. Try a couple of times; it seems EWS has a search index that needs to catch up.
if isinstance(f, (BodyField, IndexedField)):
# These fields are particularly flaky when filtering. Give up early without failing.
continue
for _ in range(5):
retries += 1
time.sleep(retries * retries) # Exponential sleep
matches = qs.filter(**kw).count()
if matches == expected:
break
self.skipTest(f"Filter expression {kw} on complex field still failing after multiple retries")
self.assertEqual(matches, expected, (f.name, val, kw, retries))
def test_filter_on_simple_fields(self):
# Test that we can filter on all simple fields
item = self.get_test_item()
fields = []
for f in self._reduce_fields_for_filter(item, self.get_item_fields()):
if f.is_list:
continue
fields.append(f)
if not fields:
self.skipTest("No matching simple fields on this model")
item.save()
common_qs = self.test_folder.filter(categories__contains=self.categories)
for f in fields:
val = getattr(item, f.name)
# Filter with =, __in and __contains. We could have more filters here, but these should always match.
filter_kwargs = [{f.name: val}, {f"{f.name}__in": [val]}]
if isinstance(f, TextField) and not isinstance(f, ChoiceField):
# Choice fields cannot be filtered using __contains. Sort of makes sense.
filter_kwargs.append({f"{f.name}__contains": get_random_substring(val)})
self._run_filter_tests(common_qs, f, filter_kwargs, val)
def test_filter_on_list_fields(self):
# Test that we can filter on all list fields
item = self.get_test_item()
fields = []
for f in self._reduce_fields_for_filter(item, self.get_item_fields()):
if not f.is_list:
continue
if issubclass(f.value_cls, MultiFieldIndexedElement):
continue
if issubclass(f.value_cls, SingleFieldIndexedElement):
continue
# This test is exceptionally slow. Only test list fields that are not also found on the base Item class
if self.ITEM_CLASS != Item:
if f.name in Item.FIELDS:
continue
fields.append(f)
if not fields:
self.skipTest("No matching list fields on this model")
item.save()
common_qs = self.test_folder.filter(categories__contains=self.categories)
for f in fields:
val = getattr(item, f.name)
# Filter multi-value fields with =, __in and __contains
# Does not work in O365
# filter_kwargs = [{f"{f.name}__in": val}, {f"{f.name}__contains": val}]
filter_kwargs = [{f"{f.name}__in": val}]
self._run_filter_tests(common_qs, f, filter_kwargs, val)
def test_filter_on_single_field_index_fields(self):
# Test that we can filter on all index fields
item = self.get_test_item()
fields = []
for f in self._reduce_fields_for_filter(item, self.get_item_fields()):
if not issubclass(f.value_cls, SingleFieldIndexedElement):
continue
fields.append(f)
if not fields:
self.skipTest("No matching single index fields on this model")
item.save()
common_qs = self.test_folder.filter(categories__contains=self.categories)
for f in fields:
val = getattr(item, f.name)
# For these, we may filter by item or subfield value
filter_kwargs = []
for v in val:
for subfield in f.value_cls.supported_fields(version=self.account.version):
field_path = FieldPath(field=f, label=v.label, subfield=subfield)
path, subval = field_path.path, field_path.get_value(item)
if subval is None:
continue
filter_kwargs.extend(
[
{f.name: v},
{path: subval},
{f"{path}__in": [subval]},
{f"{path}__contains": get_random_substring(subval)},
]
)
self._run_filter_tests(common_qs, f, filter_kwargs, val)
def test_filter_on_multi_field_index_fields(self):
# Test that we can filter on all index fields
item = self.get_test_item()
fields = []
for f in self._reduce_fields_for_filter(item, self.get_item_fields()):
if not issubclass(f.value_cls, MultiFieldIndexedElement):
continue
fields.append(f)
if not fields:
self.skipTest("No matching multi index fields on this model")
item.save()
common_qs = self.test_folder.filter(categories__contains=self.categories)
for f in fields:
val = getattr(item, f.name)
# Filter multi-value fields with =, __in and __contains
# For these, we need to filter on the subfield
filter_kwargs = []
for v in val:
for subfield in f.value_cls.supported_fields(version=self.account.version):
field_path = FieldPath(field=f, label=v.label, subfield=subfield)
path, subval = field_path.path, field_path.get_value(item)
if subval is None:
continue
filter_kwargs.extend(
[{path: subval}, {f"{path}__in": [subval]}, {f"{path}__contains": get_random_substring(subval)}]
)
self._run_filter_tests(common_qs, f, filter_kwargs, val)
def test_text_field_settings(self):
# Test that the max_length and is_complex field settings are correctly set for text fields
for f in self.ITEM_CLASS.FIELDS:
with self.subTest(f=f):
if not f.supports_version(self.account.version):
# Cannot be used with this EWS version
continue
if not isinstance(f, TextField):
continue
if isinstance(f, ChoiceField):
# This one can't contain random values
continue
if isinstance(f, CultureField):
# This one can't contain random values
continue
if f.is_read_only:
continue
if f.name == "categories":
# We're filtering on this one, so leave it alone
continue
item = self.get_test_item().save()
old_max_length = getattr(f, "max_length", None)
old_is_complex = f.is_complex
try:
# Set a string long enough to not be handled by FindItems
f.max_length = 4000
if f.is_list:
setattr(
item, f.name, [get_random_string(f.max_length) for _ in range(len(getattr(item, f.name)))]
)
else:
setattr(item, f.name, get_random_string(f.max_length))
try:
self.safe_save(item, update_fields=[f.name])
except ErrorPropertyUpdate:
# Some fields throw this error when updated to a huge value
self.assertIn(f.name, ["given_name", "middle_name", "surname"])
continue
except ErrorInvalidPropertySet:
# Some fields can not be updated after save
self.assertTrue(f.is_read_only_after_send)
continue
# is_complex=True forces the query to use GetItems which will always get the full value
f.is_complex = True
new_full_item = self.test_folder.all().only(f.name).get(id=item.id)
new_full = getattr(new_full_item, f.name)
if old_max_length:
if f.is_list:
for s in new_full:
self.assertEqual(len(s), old_max_length, (f.name, len(s), old_max_length))
else:
self.assertEqual(len(new_full), old_max_length, (f.name, len(new_full), old_max_length))
# is_complex=False forces the query to use FindItems which will only get the short value
f.is_complex = False
new_short_item = {
i.id: i
for i in self.test_folder.all().only(f.name).filter(categories__contains=self.categories)
}[item.id]
new_short = getattr(new_short_item, f.name)
if not old_is_complex:
self.assertEqual(new_short, new_full, (f.name, new_short, new_full))
finally:
if old_max_length:
f.max_length = old_max_length
else:
delattr(f, "max_length")
f.is_complex = old_is_complex
def test_save_and_delete(self):
# Test that we can create, update and delete single items using methods directly on the item.
insert_kwargs = self.get_random_insert_kwargs()
insert_kwargs["categories"] = self.categories
item = self.ITEM_CLASS(folder=self.test_folder, **insert_kwargs)
self.assertIsNone(item.id)
self.assertIsNone(item.changekey)
# Create
item.save()
self.assertIsNotNone(item.id)
self.assertIsNotNone(item.changekey)
for k, v in insert_kwargs.items():
self.assertEqual(getattr(item, k), v, (k, getattr(item, k), v))
# Test that whatever we have locally also matches whatever is in the DB
fresh_item = self.get_item_by_id(item, folder=self.test_folder)
for f in self.ITEM_CLASS.FIELDS:
with self.subTest(f=f):
old, new = getattr(item, f.name), getattr(fresh_item, f.name)
if f.is_read_only and old is None:
# Some fields are automatically set server-side
continue
if f.name == "reminder_due_by":
# EWS sets a default value if it is not set on insert. Ignore
continue
if f.name == "mime_content":
# This will change depending on other contents fields
continue
if f.is_list:
old, new = set(old or ()), set(new or ())
self.assertEqual(old, new, (f.name, old, new))
# Update
update_kwargs = self.get_random_update_kwargs(item=item, insert_kwargs=insert_kwargs)
for k, v in update_kwargs.items():
setattr(item, k, v)
self.safe_save(item)
for k, v in update_kwargs.items():
with self.subTest(k=k):
self.assertEqual(getattr(item, k), v, (k, getattr(item, k), v))
# Test that whatever we have locally also matches whatever is in the DB
fresh_item = self.get_item_by_id(item, folder=self.test_folder)
for f in self.ITEM_CLASS.FIELDS:
with self.subTest(f=f):
old, new = getattr(item, f.name), getattr(fresh_item, f.name)
if f.is_read_only and old is None:
# Some fields are automatically updated server-side
continue
if f.name == "_id":
# We test this elsewhere, and changekey is not guaranteed to be the same - see self.safe_save()
continue
if f.name == "mime_content":
# This will change depending on other contents fields
continue
if f.name == "reminder_due_by":
if new is None:
# EWS does not always return a value if reminder_is_set is False.
continue
if old is not None:
# EWS sometimes randomly sets the new reminder due date to one month before or after we
# wanted it, and sometimes 30 days before or after. But only sometimes...
old_date = old.astimezone(self.account.default_timezone).date()
new_date = new.astimezone(self.account.default_timezone).date()
if getattr(item, "is_all_day", False) and old_date == new_date:
# There is some weirdness with the time part of the reminder_due_by value for all-day events
item.reminder_due_by = new
continue
if relativedelta(month=1) + new_date == old_date:
item.reminder_due_by = new
continue
if relativedelta(month=1) + old_date == new_date:
item.reminder_due_by = new
continue
if abs(old_date - new_date) == datetime.timedelta(days=30):
item.reminder_due_by = new
continue
if f.is_list:
old, new = set(old or ()), set(new or ())
self.assertEqual(old, new, (f.name, old, new))
# Hard delete
item_id = (item.id, item.changekey)
item.delete()
for e in self.account.fetch(ids=[item_id], folder=self.test_folder):
# It's gone from the account
self.assertIsInstance(e, ErrorItemNotFound)
# Really gone, not just changed ItemId
items = self.test_folder.filter(categories__contains=item.categories)
self.assertEqual(items.count(), 0)
def test_item_insert(self):
# Test insert
insert_kwargs = self.get_random_insert_kwargs()
insert_kwargs["categories"] = self.categories
item = self.ITEM_CLASS(folder=self.test_folder, **insert_kwargs)
# Test with generator as argument
insert_ids = self.test_folder.bulk_create(items=(i for i in (item,)))
self.assertEqual(len(insert_ids), 1)
self.assertIsInstance(insert_ids[0], BaseItem)
find_ids = list(self.test_folder.filter(categories__contains=item.categories).values_list("id", "changekey"))
self.assertEqual(len(find_ids), 1)
self.assertEqual(len(find_ids[0]), 2, find_ids[0])
self.assertEqual(insert_ids, find_ids)
# Test with generator as argument
item = list(self.account.fetch(ids=(i for i in find_ids), folder=self.test_folder))[0]
for f in self.ITEM_CLASS.FIELDS:
with self.subTest(f=f):
if not f.supports_version(self.account.version):
# Cannot be used with this EWS version
continue
if self.ITEM_CLASS == CalendarItem and f in CalendarItem.timezone_fields():
# Timezone fields will (and must) be populated automatically from the timestamp
continue
if f.is_read_only:
continue
if f.name == "reminder_due_by":
# EWS sets a default value if it is not set on insert. Ignore
continue
if f.name == "mime_content":
# This will change depending on other contents fields
continue
old, new = insert_kwargs[f.name], getattr(item, f.name)
if f.is_list:
old, new = set(old or ()), set(new or ())
self.assertEqual(old, new, (f.name, old, new))
def test_item_update(self):
# Test update
insert_kwargs = self.get_random_insert_kwargs()
insert_kwargs["categories"] = self.categories
item = self.ITEM_CLASS(folder=self.test_folder, **insert_kwargs).save()
update_kwargs = self.get_random_update_kwargs(item=item, insert_kwargs=insert_kwargs)
if self.ITEM_CLASS in (Contact, DistributionList):
# Contact and DistributionList don't support mime_type updates at all
update_kwargs.pop("mime_content", None)
update_fieldnames = [f for f in update_kwargs if f != "attachments"]
for k, v in update_kwargs.items():
setattr(item, k, v)
self.safe_save(item, update_fields=update_fieldnames)
item = self.get_item_by_id(item, folder=self.test_folder)
for f in self.ITEM_CLASS.FIELDS:
with self.subTest(f=f):
if not f.supports_version(self.account.version):
# Cannot be used with this EWS version
continue
if self.ITEM_CLASS == CalendarItem and f in CalendarItem.timezone_fields():
# Timezone fields will (and must) be populated automatically from the timestamp
continue
if f.is_read_only or f.is_read_only_after_send:
# These cannot be changed
continue
if f.name == "mime_content":
# This will change depending on other contents fields
continue
old, new = getattr(item, f.name), update_kwargs[f.name]
if f.name == "reminder_due_by":
if old is None:
# EWS does not always return a value if reminder_is_set is False. Set one now
item.reminder_due_by = new
continue
if new is not None:
# EWS sometimes randomly sets the new reminder due date to one month before or after we
# wanted it, and sometimes 30 days before or after. But only sometimes...
old_date = old.astimezone(self.account.default_timezone).date()
new_date = new.astimezone(self.account.default_timezone).date()
if getattr(item, "is_all_day", False) and old_date == new_date:
# There is some weirdness with the time part of the reminder_due_by value for all-day events
item.reminder_due_by = new
continue
if relativedelta(month=1) + new_date == old_date:
item.reminder_due_by = new
continue
if relativedelta(month=1) + old_date == new_date:
item.reminder_due_by = new
continue
if abs(old_date - new_date) == datetime.timedelta(days=30):
item.reminder_due_by = new
continue
if f.is_list:
old, new = set(old or ()), set(new or ())
self.assertEqual(old, new, (f.name, old, new))
def test_item_update_wipe(self):
# Test wiping or removing fields
insert_kwargs = self.get_random_insert_kwargs()
insert_kwargs["categories"] = self.categories
item = self.ITEM_CLASS(folder=self.test_folder, **insert_kwargs).save()
update_kwargs = self.get_random_update_kwargs(item=item, insert_kwargs=insert_kwargs)
if self.ITEM_CLASS in (Contact, DistributionList):
# Contact and DistributionList don't support mime_type updates at all
update_kwargs.pop("mime_content", None)
update_fieldnames = [f for f in update_kwargs if f != "attachments"]
wipe_kwargs = {}
for f in self.ITEM_CLASS.FIELDS:
if not f.supports_version(self.account.version):
# Cannot be used with this EWS version
continue
if self.ITEM_CLASS == CalendarItem and f in CalendarItem.timezone_fields():
# Timezone fields will (and must) be populated automatically from the timestamp
continue
if f.is_required or f.is_required_after_save:
# These cannot be deleted
continue
if f.is_read_only or f.is_read_only_after_send:
# These cannot be changed
continue
wipe_kwargs[f.name] = None
for k, v in wipe_kwargs.items():
setattr(item, k, v)
self.safe_save(item, update_fields=update_fieldnames)
item = self.get_item_by_id(item, folder=self.test_folder)
for f in self.ITEM_CLASS.FIELDS:
with self.subTest(f=f):
if not f.supports_version(self.account.version):
# Cannot be used with this EWS version
continue
if self.ITEM_CLASS == CalendarItem and f in CalendarItem.timezone_fields():
# Timezone fields will (and must) be populated automatically from the timestamp
continue
if f.is_required or f.is_required_after_save:
continue
if f.is_read_only or f.is_read_only_after_send:
continue
old, new = getattr(item, f.name), wipe_kwargs[f.name]
if f.is_list:
old, new = set(old or ()), set(new or ())
self.assertEqual(old, new, (f.name, old, new))
def test_item_update_extended_properties(self):
item = self.get_test_item().save()
item = self.get_item_by_id(item, folder=self.test_folder) # An Item saved in Inbox becomes a Message
item.__class__.register("extern_id", ExternId)
try:
# Test extern_id = None, which deletes the extended property entirely
extern_id = None
item.extern_id = extern_id
self.safe_save(item, update_fields=["extern_id"])
updated_item = self.get_item_by_id(item, folder=self.test_folder)
self.assertEqual(updated_item.extern_id, extern_id)
finally:
item.__class__.deregister("extern_id")
|