Skip to content

Commit

Permalink
Merge branch 'release/0.3.49' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
erikvw committed Mar 20, 2024
2 parents 5d72a33 + f1ddd9e commit 24e922e
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 48 deletions.
49 changes: 6 additions & 43 deletions edc_sites/site.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from __future__ import annotations

import dataclasses
import json
import sys
from copy import deepcopy
from typing import TYPE_CHECKING, Any
Expand Down Expand Up @@ -137,16 +136,17 @@ def register(self, *single_sites: SingleSite):
self.loaded = True
if "makemigrations" not in sys.argv:
for single_site in single_sites:
if get_insert_uat_subdomain():
domain = insert_into_domain(single_site.domain, self.uat_subdomain)
single_site = dataclasses.replace(single_site, domain=domain)

if single_site.site_id in self._registry:
raise AlreadyRegistered(f"Site already registered. Got `{single_site}`.")
if single_site.name in [s.name for s in self._registry.values()]:
elif single_site.name in [s.name for s in self._registry.values()]:
raise AlreadyRegisteredName(
f"Site with this name is already registered. Got `{single_site}`."
)
if get_insert_uat_subdomain():
domain = insert_into_domain(single_site.domain, self.uat_subdomain)
single_site = dataclasses.replace(single_site, domain=domain)
if single_site.domain in [s.domain for s in self._registry.values()]:
elif single_site.domain in [s.domain for s in self._registry.values()]:
raise AlreadyRegisteredDomain(
f"Site with this domain is already registered. Got `{single_site}`."
)
Expand Down Expand Up @@ -312,43 +312,6 @@ def get_current_country(self, request: WSGIRequest | None = None) -> str:
single_site = self.get_current_site(request)
return single_site.country

def check(self):
"""Checks the Site / SiteProfile tables are in sync"""
if not get_site_model_cls().objects.all().exists():
raise SitesCheckError("No sites have been imported. You need to run migrate")
ids1 = sorted(list(self.all()))
ids2 = [
x[0] for x in get_site_model_cls().objects.values_list("id").all().order_by("id")
]
if ids1 != ids2:
raise SitesCheckError(
f"Site table is out of sync. Got registered sites = {ids1}. "
f"Sites in Sites model = {ids2}. Try running migrate."
)
for site_id, single_site in self._registry.items():
site_obj = get_site_model_cls().objects.get(id=site_id)
for attr in ["name", "domain"]:
try:
self.get_by_attr(attr, getattr(site_obj, attr))
except SiteDoesNotExist as e:
raise SitesCheckError(f"{e}. Try running migrate.")
for attr in ["country", "country_code"]:
try:
self.get_by_attr(attr, getattr(site_obj.siteprofile, attr))
except SiteDoesNotExist as e:
raise SitesCheckError(f"{e}. Try running migrate.")
try:
self.get_by_attr(
"languages", json.loads(getattr(site_obj.siteprofile, "languages"))
)
except SiteDoesNotExist as e:
raise SitesCheckError(f"{e}. Try running migrate.")
if site_obj.siteprofile.title != single_site.description:
raise SitesCheckError(
f"No site exists with `title`=={site_obj.siteprofile.title}. "
"Try running migrate."
)

@staticmethod
def autodiscover(module_name=None, verbose=True):
"""Autodiscovers query rule classes in the sites.py file of
Expand Down
73 changes: 69 additions & 4 deletions edc_sites/system_checks.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,30 @@
import json
import sys

from django.core.checks import Error
from django.db import OperationalError

from edc_sites.site import SitesCheckError, sites
from edc_sites.single_site import SingleSite
from edc_sites.site import SitesCheckError
from edc_sites.site import sites as site_sites
from edc_sites.utils import get_site_model_cls


def sites_check(app_configs, **kwargs): # noqa
errors = []
if "migrate" not in sys.argv and "makemigrations" not in sys.argv:
try:
sites.check()
compare_single_sites_with_db()
except (SitesCheckError, OperationalError) as e:
errors.append(
Error(
e,
hint="Sites model is out-of-sync with registry.",
obj=sites,
obj=site_sites,
id="edc_sites.E001",
)
)
if not sites.all():
if not site_sites.all():
errors.append(
Error(
"No sites have been registered",
Expand All @@ -29,3 +33,64 @@ def sites_check(app_configs, **kwargs): # noqa
)

return errors


def compare_single_sites_with_db():
"""Checks the Site / SiteProfile tables are in sync"""
if not get_site_model_cls().objects.all().exists():
raise SitesCheckError("No sites have been imported. You need to run migrate")
ids1 = sorted(list(site_sites.all()))
ids2 = [x[0] for x in get_site_model_cls().objects.values_list("id").all().order_by("id")]
if ids1 != ids2:
raise SitesCheckError(
f"Site table is out of sync. Got registered sites = {ids1}. "
f"Sites in Sites model = {ids2}. Try running migrate."
)
for site_id, single_site in site_sites.all().items():
site_obj = get_site_model_cls().objects.get(id=site_id)
match_name_and_domain_or_raise(single_site, site_obj)
match_country_and_country_code_or_raise(single_site, site_obj)
match_languages_or_raise(single_site, site_obj)
match_title_with_description_or_raise(single_site, site_obj)


def match_name_and_domain_or_raise(single_site: SingleSite, site_obj):
for attr in ["name", "domain"]:
value1 = getattr(single_site, attr)
value2 = getattr(site_obj, attr)
if value1 != value2:
raise SitesCheckError(
f"Site table is out of sync. Checking {site_obj.site_id} {attr}. "
f"Try running migrate. Got {value1} != {value2}"
)


def match_country_and_country_code_or_raise(single_site: SingleSite, site_obj):
for attr in ["country", "country_code"]:
value1 = getattr(single_site, attr)
value2 = getattr(site_obj.siteprofile, attr)
if value1 != value2:
raise SitesCheckError(
f"Site table is out of sync. Checking {site_obj.site_id} {attr}. "
f"Try running migrate. Got {value1} != {value2}"
)


def match_languages_or_raise(single_site: SingleSite, site_obj):
value1 = single_site.languages
value2 = json.loads(getattr(site_obj.siteprofile, "languages"))
if value1 != value2:
raise SitesCheckError(
f"Site table is out of sync. Checking {site_obj.site_id} "
f"languages. Try running migrate. Got {value1} != {value2}"
)


def match_title_with_description_or_raise(single_site: SingleSite, site_obj):
value1 = site_obj.siteprofile.title
value2 = single_site.description
if value1 != value2:
raise SitesCheckError(
f"Site table is out of sync. Checking {site_obj.site_id} title/description. "
f"Try running migrate. Got {value1} != {value2}"
)
2 changes: 1 addition & 1 deletion runtests.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
template_dirs=[str(base_dir / app_name / "tests" / "templates")],
BASE_DIR=base_dir,
DEBUG=True,
KEY_PATH=str(base_dir / app_name / "tests" / "etc"),
DJANGO_CRYPTO_FIELDS_KEY_PATH=str(base_dir / app_name / "tests" / "etc"),
ETC_DIR=str(base_dir / app_name / "tests" / "etc"),
AUTO_CREATE_KEYS=False,
APP_NAME=app_name,
Expand Down

0 comments on commit 24e922e

Please sign in to comment.