From 1009b6c11ab808f5a156e184f5cb4b57e854728a Mon Sep 17 00:00:00 2001
From: Marte Fossum <myf@uio.no>
Date: Mon, 28 Nov 2022 13:49:02 +0100
Subject: [PATCH] Make test for unsupported fieldname and fix fieldname check

---
 greg/importers/orgreg.py                      | 12 +++--
 .../management/test_import_from_orgreg.py     | 44 ++++++++++++++++++-
 .../management/test_notification_publisher.py |  9 +++-
 greg/tests/test_tasks.py                      |  4 +-
 gregui/tests/api/views/test_invitation.py     |  2 +-
 5 files changed, 62 insertions(+), 9 deletions(-)

diff --git a/greg/importers/orgreg.py b/greg/importers/orgreg.py
index 18af6051..1d32d8df 100644
--- a/greg/importers/orgreg.py
+++ b/greg/importers/orgreg.py
@@ -26,7 +26,7 @@ logger = logging.getLogger(__name__)
 class OrgregImporter:
     processed: dict[int, OrganizationalUnit] = {}
 
-    def _upsert_extra_identities(self, ou: OrgUnit):
+    def upsert_extra_identities(self, ou: OrgUnit):
         """Upsert any configured extra IDs from orgreg."""
         for extra_id in settings.ORGREG_EXTRA_IDS:
             if "type" in extra_id.keys():
@@ -54,13 +54,19 @@ class OrgregImporter:
                         value = getattr(field, "nob")
                     else:
                         value = field
-                if value is not None and isinstance(value, str):
+                    if not isinstance(value, str):
+                        logger.warning(
+                            "Cannot find value: %s. Make sure 'fieldname' and 'subfield' are correctly given.",
+                            value,
+                        )
+                        continue
                     self._upsert_identifier(
                         settings.ORGREG_SOURCE,
                         extra_id["fieldname"],
                         value,
                         ou.ou_id,
                     )
+
             else:
                 logger.warning("Unsupported key value %s", extra_id.keys()[0])
 
@@ -183,7 +189,7 @@ class OrgregImporter:
             created = False
         for k, v in values.items():
             setattr(self.processed[ou.ou_id], k, v)
-        self._upsert_extra_identities(ou)
+        self.upsert_extra_identities(ou)
         self.processed[ou.ou_id].save()
         logger.info(
             "%s %s with %s",
diff --git a/greg/tests/management/test_import_from_orgreg.py b/greg/tests/management/test_import_from_orgreg.py
index 047822c5..9140582a 100644
--- a/greg/tests/management/test_import_from_orgreg.py
+++ b/greg/tests/management/test_import_from_orgreg.py
@@ -1,7 +1,26 @@
-import pytest
+import datetime
 
+import pytest
 from django.core.management import call_command
+from django.test import override_settings
 from django_q.models import Schedule
+from orgreg_client.models import OrgUnit
+
+from greg.importers.orgreg import OrgregImporter, OrganizationalUnit
+from greg.models import OuIdentifier
+
+
+@pytest.fixture
+def org_unit():
+    org_unit = OrgUnit(
+        ou_id=1,
+        valid_from=datetime.date(year=2020, month=2, day=6),
+        external_keys=[
+            {"type": "legacy_stedkode", "source_system": "sapuio", "value": "1"}
+        ],
+        shortname={"nob": "FOO"},
+    )
+    return org_unit
 
 
 @pytest.mark.django_db
@@ -11,3 +30,26 @@ def test_command_ou_init():
     assert Schedule.objects.all().count() == 1
     sc = Schedule.objects.first()
     assert sc.func == "greg.tasks.import_from_orgreg"
+
+
+@pytest.mark.django_db
+def test_upsert_extra_identities(org_unit):
+    organizational_unit = OrganizationalUnit.objects.create(
+        name_nb="foo_nb", name_en="foo_en"
+    )
+    org_importer = OrgregImporter()
+    org_importer.processed[org_unit.ou_id] = organizational_unit
+    org_importer.upsert_extra_identities(org_unit)
+    assert OuIdentifier.objects.all().count() == 2
+
+
+@pytest.mark.django_db
+@override_settings(ORGREG_EXTRA_IDS=[{"fieldname": "foo", "subfield": "nob"}])
+def test_upsert_wrong_extra_identities(org_unit):
+    organizational_unit = OrganizationalUnit.objects.create(
+        name_nb="foo_nb", name_en="foo_en"
+    )
+    org_importer = OrgregImporter()
+    org_importer.processed[org_unit.ou_id] = organizational_unit
+    org_importer.upsert_extra_identities(org_unit)
+    assert OuIdentifier.objects.all().count() == 0
diff --git a/greg/tests/management/test_notification_publisher.py b/greg/tests/management/test_notification_publisher.py
index 8adc7ba6..340bb543 100644
--- a/greg/tests/management/test_notification_publisher.py
+++ b/greg/tests/management/test_notification_publisher.py
@@ -1,5 +1,6 @@
 import json
 import pytest
+from django.test import override_settings
 
 from greg.management.commands.notification_publisher import (
     handle_one_notification,
@@ -45,7 +46,11 @@ def test_create_cloud_event_payload(role_type_notification):
 
 
 @pytest.mark.django_db
-def test_generate_routing_key(role_type_notification, settings):
+def test_generate_routing_key(role_type_notification):
     assert generate_routing_key(role_type_notification) == "role_type.update"
-    settings.NOTIFICATION_ROUTING_KEY_PREFIX = "foo."
+
+
+@pytest.mark.django_db
+@override_settings(NOTIFICATION_ROUTING_KEY_PREFIX="foo.")
+def test_override_generate_routing_key(role_type_notification):
     assert generate_routing_key(role_type_notification) == "foo.role_type.update"
diff --git a/greg/tests/test_tasks.py b/greg/tests/test_tasks.py
index 13bad3ed..583d470a 100644
--- a/greg/tests/test_tasks.py
+++ b/greg/tests/test_tasks.py
@@ -3,6 +3,7 @@ import datetime
 import pytest
 from django.conf import settings
 from django.core import mail
+from django.test import override_settings
 from orgreg_client import OrgUnit, OrgUnitList
 
 from greg.models import OrganizationalUnit, OuIdentifier
@@ -125,11 +126,10 @@ def test_run_twice(requests_mock, orgreg_response):
 
 
 @pytest.mark.django_db
+@override_settings(ORGREG_ACRONYMS=["nob"])
 def test_import_acronym(requests_mock, orgreg_response):
     requests_mock.get("https://example.com/orgreg/ou/", text=orgreg_response.json())
 
-    settings.ORGREG_ACRONYMS.append("nob")
-
     import_from_orgreg()
     assert OrganizationalUnit.objects.all().count() == 3
 
diff --git a/gregui/tests/api/views/test_invitation.py b/gregui/tests/api/views/test_invitation.py
index 3e0d7929..54370a36 100644
--- a/gregui/tests/api/views/test_invitation.py
+++ b/gregui/tests/api/views/test_invitation.py
@@ -257,7 +257,7 @@ def test_post_invited_info_invalid_national_id_number(client, invited_person):
         "person": {
             "private_mobile": "+4707543001",
             "private_email": "test@example.com",
-            "fnr": "123",
+            "fnr": "23478912378",
         }
     }
     url = reverse("gregui-v1:invited-info")
-- 
GitLab