def handle(self, *args, **options):
        import_update()

        translation.activate(settings.LANGUAGE_CODE)

        notifier = NotifyUsers()
        notifier.notify_all()
    def handle(self, *args, **options):
        input_file: Path = options["input"]

        logger.info("Loading the data")
        with input_file.open() as fp:
            json_data = json.load(fp)
            if json_data["format_version"] != format_version:
                raise CommandError(
                    f"This version of {settings.PRODUCT_NAME} can only import json format version {format_version}, "
                    f"but the json file you provided is version {json_data['format_version']}"
                )
            ris_data: RisData = converter.structure(json_data, RisData)

        body = models.Body.objects.filter(name=ris_data.meta.name).first()
        if not body:
            logger.info("Building the body")

            if options["ags"] or ris_data.meta.ags:
                ags = options["ags"] or ris_data.meta.ags
            else:
                ags = city_to_ags(ris_data.meta.name, False)
                if not ags:
                    raise RuntimeError(
                        f"Failed to determine the Amtliche Gemeindeschlüssel for '{ris_data.meta.name}'. "
                        f"Please look it up yourself and specify it with `--ags`"
                    )
                logger.info(f"The Amtliche Gemeindeschlüssel is {ags}")
            body = models.Body(
                name=ris_data.meta.name, short_name=ris_data.meta.name, ags=ags
            )
            body.save()
            if not options["skip_body_extra"]:
                import_outline(body)
                import_streets(body)
        else:
            logging.info("Using existing body")

        # TODO: Re-enable this after some more thorough testing
        # handle_counts(ris_data, options["allow_shrinkage"])

        import_data(body, ris_data)

        fix_sort_date(datetime.datetime.now(tz=tz.tzlocal()))

        if not options["skip_download"]:
            Importer(BaseLoader(dict()), force_singlethread=True).load_files(
                fallback_city=body.short_name
            )

        if not options["no_notify_users"]:
            logger.info("Sending notifications")
            NotifyUsers().notify_all()
def test_import_json(send_mail_function):
    """This test runs with elasticsearch if available and otherwise uses saved responses"""
    # Create the base state
    old = load_ris_data("importer/test-data/amtzell_old.json")
    body = Body(name=old.meta.name, short_name=old.meta.name, ags=old.meta.ags)
    body.save()

    import_data(body, old)

    actual = make_db_snapshot()
    expected = json.loads(
        Path("importer/test-data/amtzell_old_db.json").read_text())
    assert expected == actual

    last_notification = timezone.now()

    # Create notification
    user = User(username="******", email="*****@*****.**")
    user.save()
    UserProfile.objects.create(user=user)

    user_alert = UserAlert(
        user=user,
        search_string="Digitalisierungsstrategie",
        created=datetime.fromisoformat("2008-01-01T12:00:00+01:00"),
    )
    user_alert.save()

    # Import the new data
    new = load_ris_data("importer/test-data/amtzell_new.json")
    import_data(body, new)

    actual = make_db_snapshot()
    expected = json.loads(
        Path("importer/test-data/amtzell_new_db.json").read_text())
    assert expected == actual

    # Check that the notification was sent
    elasticsearch_mock = ElasticsearchMock({
        "importer/test-data/notification_request.json":
        "importer/test-data/notification_response.json"
    })
    if is_es_online():
        context = contextlib.nullcontext()
    else:
        context = mock.patch(
            "elasticsearch_dsl.search.get_connection",
            new=lambda _alias: elasticsearch_mock,
        )
    with context:
        if is_es_online():
            notifier = NotifyUsers(last_notification)
        else:
            notifier = NotifyUsers(
                datetime.fromisoformat("2020-05-17T12:07:37.887853+00:00"))
        notifier.notify_all()

        assert send_mail_function.call_count == 1
        assert send_mail_function.call_args[0][0] == "*****@*****.**"
        assert "Digitalisierungsstrategie" in send_mail_function.call_args[0][
            2]
        assert "Digitalisierungsstrategie" in send_mail_function.call_args[0][
            3]
Beispiel #4
0
    def handle(self, *args, **options):
        translation.activate(settings.LANGUAGE_CODE)

        notifier = NotifyUsers(options["override_since"], options["simulate"])
        notifier.notify_all()