diff options
Diffstat (limited to 'ishtar_common/tests.py')
| -rw-r--r-- | ishtar_common/tests.py | 195 | 
1 files changed, 107 insertions, 88 deletions
| diff --git a/ishtar_common/tests.py b/ishtar_common/tests.py index 736deb1e4..014940c08 100644 --- a/ishtar_common/tests.py +++ b/ishtar_common/tests.py @@ -19,12 +19,14 @@  from bs4 import BeautifulSoup as Soup  import re  import csv +import copy  import datetime  import importlib  import io  import json  import os  import shutil +import sys  import tempfile  from time import time  import zipfile @@ -37,6 +39,7 @@ from django.apps import apps  from django.conf import settings  from django.contrib.auth.models import User, Permission  from django.contrib.contenttypes.models import ContentType +from django.contrib.gis.geos import GEOSGeometry  from django.core.cache import cache  from django.core.exceptions import ValidationError  from django.core.files import File as DjangoFile @@ -85,7 +88,12 @@ from ishtar_common.tasks import launch_export  from ishtar_common import utils_secretary  from django.contrib.staticfiles.testing import StaticLiveServerTestCase -from selenium.webdriver.firefox.webdriver import WebDriver + +if settings.SELENIUM_TEST: +    from selenium.webdriver.firefox.webdriver import WebDriver +    from selenium.webdriver.support.wait import WebDriverWait +    from selenium.webdriver.common.by import By +    from selenium.webdriver.support import expected_conditions as EC  COMMON_FIXTURES = [ @@ -245,8 +253,7 @@ class CommandsTestCase(TestCase):          """          Clean ishtar db          """ -        from archaeological_operations.models import Parcel - +        Parcel = apps.get_model("archaeological_operations", "Parcel")          p = Parcel.objects.create(              town=models.Town.objects.create(name="test", numero_insee="25000"),          ) @@ -454,8 +461,6 @@ class ManagedModelTestRunner(DiscoverRunner):      test_runner = TimedTextTestRunner      def setup_test_environment(self, *args, **kwargs): -        from django.apps import apps -          self.unmanaged_models = [m for m in apps.get_models() if not m._meta.managed]          for m in self.unmanaged_models:              m._meta.managed = True @@ -793,28 +798,18 @@ class SerializationTest(GenericSerializationTest, TestCase):      fixtures = COMMON_FIXTURES + WAREHOUSE_FIXTURES      def create_types(self): -        from archaeological_finds.models import ( -            MaterialTypeQualityType, -            ObjectTypeQualityType, -            AlterationType, -            AlterationCauseType, -            TreatmentEmergencyType, -            CommunicabilityType, -            FunctionalArea, -        ) -        from archaeological_operations.models import CulturalAttributionType - -        for model in ( -            models.LicenseType, -            MaterialTypeQualityType, -            ObjectTypeQualityType, -            AlterationType, -            AlterationCauseType, -            TreatmentEmergencyType, -            CommunicabilityType, -            CulturalAttributionType, -            FunctionalArea, +        for app, model_name in ( +            ("ishtar_common", "LicenseType"), +            ("archaeological_finds", "MaterialTypeQualityType"), +            ("archaeological_finds", "ObjectTypeQualityType"), +            ("archaeological_finds", "AlterationType"), +            ("archaeological_finds", "AlterationCauseType"), +            ("archaeological_finds", "TreatmentEmergencyType"), +            ("archaeological_finds", "CommunicabilityType"), +            ("archaeological_operations", "CulturalAttributionType"), +            ("archaeological_finds", "FunctionalArea"),          ): +            model = apps.get_model(app, model_name)              model.objects.create(txt_idx="test", label="Test")      def test_type_serialization(self): @@ -902,24 +897,30 @@ class SerializationTest(GenericSerializationTest, TestCase):      def create_document_default(self):          super(SerializationTest, self).create_document_default() -        from archaeological_operations.models import ( -            Operation, -            ArchaeologicalSite, -            OperationType, -        ) -        from archaeological_context_records.models import ContextRecord -        from archaeological_finds.models import Find, BaseFind -        from archaeological_warehouse.models import ( -            Warehouse, -            Container, -            ContainerLocalisation, -            WarehouseDivision, -            WarehouseDivisionLink, -            WarehouseType, -            ContainerType, -        ) - -        operation_type = OperationType.objects.all()[0] +        Operation = apps.get_model("archaeological_operations", "Operation") +        ArchaeologicalSite = apps.get_model( +            "archaeological_operations", "ArchaeologicalSite" +        ) +        ContextRecord = apps.get_model( +            "archaeological_context_records", "ContextRecord" +        ) +        Find = apps.get_model("archaeological_finds", "Find") +        BaseFind = apps.get_model("archaeological_finds", "BaseFind") +        Warehouse = apps.get_model("archaeological_warehouse", "Warehouse") +        WarehouseDivision = apps.get_model( +            "archaeological_warehouse", "WarehouseDivision" +        ) +        WarehouseDivisionLink = apps.get_model( +            "archaeological_warehouse", "WarehouseDivisionLink" +        ) +        WarehouseType = apps.get_model("archaeological_warehouse", "WarehouseType") +        ContainerType = apps.get_model("archaeological_warehouse", "ContainerType") +        Container = apps.get_model("archaeological_warehouse", "Container") +        ContainerLocalisation = apps.get_model( +            "archaeological_warehouse", "ContainerLocalisation" +        ) + +        operation_type = models.OperationType.objects.all()[0]          dct = {              "year": 2010,              "operation_type_id": operation_type.pk, @@ -1019,7 +1020,10 @@ class SerializationTest(GenericSerializationTest, TestCase):          docs = json.loads(res[("documents", "ishtar_common__Document")])          self.assertEqual(len(docs), 12) -        from archaeological_operations.models import Operation, ArchaeologicalSite +        Operation = apps.get_model("archaeological_operations", "Operation") +        ArchaeologicalSite = apps.get_model( +            "archaeological_operations", "ArchaeologicalSite" +        )          result_queryset = Operation.objects.filter(code_patriarche="66666")          res = self.generic_serialization_test( @@ -1041,7 +1045,9 @@ class SerializationTest(GenericSerializationTest, TestCase):          docs = json.loads(res[("documents", "ishtar_common__Document")])          self.assertEqual(len(docs), 6) -        from archaeological_context_records.models import ContextRecord +        ContextRecord = apps.get_model( +            "archaeological_context_records", "ContextRecord" +        )          result_queryset = ContextRecord.objects.filter(              id=ContextRecord.objects.all()[0].id @@ -1054,7 +1060,7 @@ class SerializationTest(GenericSerializationTest, TestCase):          docs = json.loads(res[("documents", "ishtar_common__Document")])          self.assertEqual(len(docs), 6) -        from archaeological_finds.models import Find +        Find = apps.get_model("archaeological_finds", "Find")          result_queryset = Find.objects.filter(id=Find.objects.all()[0].id)          res = self.generic_serialization_test( @@ -1065,7 +1071,7 @@ class SerializationTest(GenericSerializationTest, TestCase):          docs = json.loads(res[("documents", "ishtar_common__Document")])          self.assertEqual(len(docs), 6) -        from archaeological_warehouse.models import Warehouse +        Warehouse = apps.get_model("archaeological_warehouse", "Warehouse")          result_queryset = Warehouse.objects.filter(id=Warehouse.objects.all()[0].id)          res = self.generic_serialization_test( @@ -1100,8 +1106,8 @@ class SerializationTest(GenericSerializationTest, TestCase):              restore_serialized(zip_filename)      def test_type_restore(self): -        from archaeological_context_records.models import RelationType as CRRT -        from archaeological_operations.models import RelationType as OperationRT +        CRRT = apps.get_model("archaeological_context_records", "RelationType") +        OperationRT = apps.get_model("archaeological_operations", "RelationType")          cr_rel_type_nb = CRRT.objects.count()          ope_rel_type_nb = OperationRT.objects.count() @@ -1992,9 +1998,9 @@ class ShortMenuTest(TestCase):      def _create_ope(self, user=None):          if not user:              user = self.other_user -        from archaeological_operations.models import Operation, OperationType +        Operation = apps.get_model("archaeological_operations", "Operation") -        ope_type, created = OperationType.objects.get_or_create(label="test") +        ope_type, created = models.OperationType.objects.get_or_create(label="test")          idx = 1          while Operation.objects.filter(code_patriarche=str(idx)).count():              idx += 1 @@ -2075,7 +2081,8 @@ class ShortMenuTest(TestCase):          self.assertTrue(str(ope.cached_label) in response.content.decode())      def testFile(self): -        from archaeological_files.models import File, FileType +        File = apps.get_model("archaeological_files", "File") +        FileType = apps.get_model("archaeological_files", "FileType")          c = Client()          c.login(username=self.username, password=self.password) @@ -2113,8 +2120,10 @@ class ShortMenuTest(TestCase):          self.assertFalse(str(fle.cached_label) in response.content.decode())      def _create_cr(self): -        from archaeological_context_records.models import ContextRecord -        from archaeological_operations.models import Parcel +        ContextRecord = apps.get_model( +            "archaeological_context_records", "ContextRecord" +        ) +        Parcel = apps.get_model("archaeological_operations", "Parcel")          ope = self._create_ope()          town = models.Town.objects.create() @@ -2164,7 +2173,8 @@ class ShortMenuTest(TestCase):          self.assertTrue(str(cr.cached_label) in response.content.decode())      def _create_find(self): -        from archaeological_finds.models import BaseFind, Find +        Find = apps.get_model("archaeological_finds", "Find") +        BaseFind = apps.get_model("archaeological_finds", "BaseFind")          cr = self._create_cr()          base_find = BaseFind.objects.create(context_record=cr) @@ -2211,7 +2221,7 @@ class ShortMenuTest(TestCase):      def testBasket(self):          c = Client()          c.login(username=self.username, password=self.password) -        from archaeological_finds.models import FindBasket +        FindBasket = apps.get_model("archaeological_finds", "FindBasket")          basket = FindBasket.objects.create(              label="My basket", @@ -2232,7 +2242,8 @@ class ShortMenuTest(TestCase):      def test_treatment_file(self):          c = Client()          c.login(username=self.username, password=self.password) -        from archaeological_finds.models import TreatmentFile, TreatmentFileType +        TreatmentFile = apps.get_model("archaeological_finds", "TreatmentFile") +        TreatmentFileType = apps.get_model("archaeological_finds", "TreatmentFileType")          tf = TreatmentFile.objects.create(              type=TreatmentFileType.objects.create(), year=2050 @@ -2267,7 +2278,8 @@ class ShortMenuTest(TestCase):          self.assertFalse(str(tf.cached_label) in response.content.decode())      def _create_treatment(self): -        from archaeological_finds.models import Treatment, TreatmentState +        Treatment = apps.get_model("archaeological_finds", "Treatment") +        TreatmentState = apps.get_model("archaeological_finds", "TreatmentState")          completed, created = TreatmentState.objects.get_or_create(              txt_idx="completed", defaults={"executed": True, "label": "Done"} @@ -2367,7 +2379,7 @@ class ShortMenuTest(TestCase):      def test_basket_is_current_item(self):          c = Client()          c.login(username=self.username, password=self.password) -        from archaeological_finds.models import FindBasket +        FindBasket = apps.get_model("archaeological_finds", "FindBasket")          basket = FindBasket.objects.create(label="My basket", user=self.user.ishtaruser)          session = c.session @@ -2730,8 +2742,8 @@ class GeomaticTest(TestCase):              def save(self, *args, **kwargs):                  pass -        srs = models.SpatialReferenceSystem.objects.create( -            label="WGS84", txt_idx="wgs84", srid=4326 +        srs, __ = models.SpatialReferenceSystem.objects.get_or_create( +            srid=4326, defaults={"label": "WGS84", "txt_idx": "wgs84"}          )          obj = FakeGeomaticObject(x=2, y=3, z=4, spatial_reference_system=srs)          self.assertIsNone(obj.point_2d) @@ -2741,13 +2753,14 @@ class GeomaticTest(TestCase):      @staticmethod      def create_cr_with_bfs(ope, geom_ope, geom_cr, list_geom_bf, label_cr): -        from archaeological_operations.models import Operation -        from archaeological_context_records.models import ContextRecord -        from archaeological_finds.models import BaseFind, Find -        from django.contrib.gis.geos import GEOSGeometry -        from ishtar_common.models_common import SpatialReferenceSystem +        Operation = apps.get_model("archaeological_operations", "Operation") +        ContextRecord = apps.get_model( +            "archaeological_context_records", "ContextRecord" +        ) +        Find = apps.get_model("archaeological_finds", "Find") +        BaseFind = apps.get_model("archaeological_finds", "BaseFind") -        wgs84 = SpatialReferenceSystem.objects.get(srid=4326) +        wgs84 = models_common.SpatialReferenceSystem.objects.get(srid=4326)          poly_ope = (              "MULTIPOLYGON(((1 1,5 1,5 5,1 5,1 1),(2 2,2 3,3 3,3 2,2 2)),"              "((6 3,9 2,9 4,6 3)))" @@ -2931,8 +2944,7 @@ class GeomaticTest(TestCase):              self.assertEqual((round(item.x, 5), round(item.y, 5)), geom[1].coords)      def test_setUpDefaultGeoItems(self): -        from django.contrib.gis.geos import GEOSGeometry -        from archaeological_operations.models import Operation +        Operation = apps.get_model("archaeological_operations", "Operation")          username, password, user = create_superuser()          base_geoms, pks = self.setUpDefaultGeoItems(user) @@ -2993,10 +3005,11 @@ class GeomaticTest(TestCase):      @staticmethod      def geojson_geo_items(geoms, pks, test_get_geo_items=False): -        from archaeological_operations.models import Operation -        from archaeological_context_records.models import ContextRecord -        from archaeological_finds.models import BaseFind -        import copy +        Operation = apps.get_model("archaeological_operations", "Operation") +        ContextRecord = apps.get_model( +            "archaeological_context_records", "ContextRecord" +        ) +        BaseFind = apps.get_model("archaeological_finds", "BaseFind")          cache_dics_t, cache_dics_f = {}, {}          res = {} @@ -3658,12 +3671,11 @@ class TemplateGenerationTest(TestCase):  @tag("ui")  class SeleniumTests(StaticLiveServerTestCase): -    from selenium.webdriver.support.wait import WebDriverWait -    from selenium.webdriver.common.by import By -    from selenium.webdriver.support import expected_conditions as EC -      @classmethod      def setUpClass(cls): +        if not settings.SELENIUM_TEST: +            sys.stdout.write("UI test not activated. Set SELENIUM_TEST to True.") +            return          super().setUpClass()          cls.waiting_time = 20          cls.selenium = WebDriver() @@ -3671,10 +3683,15 @@ class SeleniumTests(StaticLiveServerTestCase):      @classmethod      def tearDownClass(cls): +        if not settings.SELENIUM_TEST: +            return          cls.selenium.quit()          super().tearDownClass()      def setUp(self): +        if not settings.SELENIUM_TEST: +            return +          # profile          profile = models.get_current_profile()          profile.mapping = True @@ -3687,7 +3704,7 @@ class SeleniumTests(StaticLiveServerTestCase):          # login          self.username, self.password, self.user = create_superuser()          self.selenium.get("%s%s" % (self.live_server_url, "/accounts/login/")) -        self.WebDriverWait(self.selenium, self.waiting_time).until( +        WebDriverWait(self.selenium, self.waiting_time).until(              lambda driver: driver.find_element_by_name("username")          )          username_input = self.selenium.find_element_by_name("username") @@ -3699,6 +3716,8 @@ class SeleniumTests(StaticLiveServerTestCase):          ).click()      def setUpDefaultGeoItems(self): +        if not settings.SELENIUM_TEST: +            return          return GeomaticTest.setUpDefaultGeoItems(self.user)      def default_geojson(self): @@ -3714,8 +3733,8 @@ class SeleniumTests(StaticLiveServerTestCase):          )      def wait_and_click(self, xpath): -        self.WebDriverWait(self.selenium, self.waiting_time).until( -            self.EC.visibility_of_element_located((self.By.XPATH, xpath)) +        WebDriverWait(self.selenium, self.waiting_time).until( +            EC.visibility_of_element_located((By.XPATH, xpath))          )          el = self.selenium.find_element_by_xpath(xpath)          self.scroll(el) @@ -3761,8 +3780,8 @@ class SeleniumTests(StaticLiveServerTestCase):          else:              xpath += slug_pk[4:] + '")]'          xpath += '/p/small[@title="ID interne" or @title="Internal ID"]' -        self.WebDriverWait(self.selenium, self.waiting_time).until( -            self.EC.visibility_of_element_located((self.By.XPATH, xpath)) +        WebDriverWait(self.selenium, self.waiting_time).until( +            EC.visibility_of_element_located((By.XPATH, xpath))          )          label = self.selenium.find_element_by_xpath(xpath).text          if slug_pk[:3] == "ope": @@ -3780,8 +3799,8 @@ class SeleniumTests(StaticLiveServerTestCase):      def assertNotInDOM(self, xpath):          self.selenium.implicitly_wait(self.waiting_time / 10)          try: -            self.WebDriverWait(self.selenium, self.waiting_time / 10).until( -                self.EC.visibility_of_element_located((self.By.XPATH, xpath)) +            WebDriverWait(self.selenium, self.waiting_time / 10).until( +                EC.visibility_of_element_located((By.XPATH, xpath))              )              found = True          except: @@ -3803,9 +3822,9 @@ class SeleniumTests(StaticLiveServerTestCase):          id = int(re.search(r"\d+$", mapid).group())          # TODO: use the map and not the map_features in the js function          if features_collecs: -            self.WebDriverWait(self.selenium, self.waiting_time).until( -                self.EC.visibility_of_element_located( -                    (self.By.ID, "http-geo-items-ready-" + slug_pk) +            WebDriverWait(self.selenium, self.waiting_time).until( +                EC.visibility_of_element_located( +                    (By.ID, "http-geo-items-ready-" + slug_pk)                  )              )          base_features, geo_items_feats = self.selenium.execute_script( | 
