import: Ensure that .author gets set when importing RealmEmoji.

Sometimes we may get data to import, due to export bugs, malformed data
etc., which doesn't have the invariant of RealmEmoji.author always being
set. The import code should fix that, by choosing a reasonable default
and setting it.
This commit is contained in:
Mateusz Mandera 2022-02-11 18:21:38 +01:00
parent 30ac291eba
commit c6be15908c
2 changed files with 29 additions and 0 deletions

View File

@ -1018,6 +1018,18 @@ def do_import_realm(import_dir: Path, subdomain: str, processes: int = 1) -> Rea
update_model_ids(model, data, related_table)
bulk_import_model(data, model)
# Ensure RealmEmoji get the .author set to a reasonable default, if the value
# wasn't provided in the import data.
first_user_profile = (
UserProfile.objects.filter(realm=realm, is_active=True, role=UserProfile.ROLE_REALM_OWNER)
.order_by("id")
.first()
)
for realm_emoji in RealmEmoji.objects.filter(realm=realm):
if realm_emoji.author_id is None:
realm_emoji.author_id = first_user_profile.id
realm_emoji.save(update_fields=["author_id"])
if "zerver_huddle" in data:
update_model_ids(Huddle, data, "huddle")
# We don't import Huddle yet, since we don't have the data to

View File

@ -751,6 +751,18 @@ class RealmImportExportTest(ExportFile):
realm_user_default.twenty_four_hour_time = True
realm_user_default.save()
# We want to have an extra, malformed RealmEmoji with no .author
# to test that upon import that gets fixed.
with get_test_image_file("img.png") as img_file:
new_realm_emoji = check_add_realm_emoji(
realm=hamlet.realm, name="hawaii2", author=hamlet, image_file=img_file
)
assert new_realm_emoji is not None
original_realm_emoji_count = RealmEmoji.objects.count()
self.assertGreaterEqual(original_realm_emoji_count, 2)
new_realm_emoji.author = None
new_realm_emoji.save()
getters = self.get_realm_getters()
snapshots: Dict[str, object] = {}
@ -864,6 +876,11 @@ class RealmImportExportTest(ExportFile):
# with is_user_active=True used for everything.
self.assertTrue(Subscription.objects.filter(is_user_active=False).exists())
all_imported_realm_emoji = RealmEmoji.objects.filter(realm=imported_realm)
self.assertEqual(all_imported_realm_emoji.count(), original_realm_emoji_count)
for imported_realm_emoji in all_imported_realm_emoji:
self.assertNotEqual(imported_realm_emoji.author, None)
def get_realm_getters(self) -> List[Callable[[Realm], object]]:
names = set()
getters: List[Callable[[Realm], object]] = []