Beispiel #1
0
    def validate(self, measure):
        # Return if the measure has no order number and, therefore, no order number origin
        if not measure.order_number:
            return

        # Get all individual countries / regions associated with the measure
        with override_current_transaction(self.transaction):
            if measure.geographical_area.area_code == AreaCode.GROUP:
                area_sids = set([
                    m.member.sid
                    for m in measure.geographical_area.memberships.current()
                ], )
            else:
                area_sids = set([measure.geographical_area.sid])

            # Get all individual countries / regions for each quota order number origin linked to the measure
            origins = QuotaOrderNumberOrigin.objects.current().filter(
                order_number__order_number=measure.order_number.order_number, )
            origin_sids = []
            for origin in origins:
                if origin.geographical_area.area_code == AreaCode.GROUP:
                    for a in [
                            m.member for m in
                            origin.geographical_area.memberships.current()
                    ]:
                        origin_sids.append(a.sid)
                else:
                    origin_sids.append(origin.geographical_area.sid)

            origin_sids = set(origin_sids)

            # Check that the geographical area sid is included in the list of origin area sids
            if any(area_sids - origin_sids):
                raise self.violation(measure)
Beispiel #2
0
def is_transaction_check_complete(check_id: int) -> bool:
    """Checks and returns whether the given transaction check is complete, and
    records the success if so."""

    check: TransactionCheck = TransactionCheck.objects.get(pk=check_id)
    check.completed = True

    with override_current_transaction(check.transaction):
        for model in check.transaction.tracked_models.all():
            applicable_checks = set(check.name
                                    for check in applicable_to(model))
            performed_checks = set(
                check.model_checks.filter(model=model).values_list(
                    "check_name",
                    flat=True,
                ), )

            if applicable_checks != performed_checks:
                check.completed = False
                break

    if check.completed:
        check.successful = not check.model_checks.filter(
            successful=False).exists()
        logger.info("Completed checking %s", check.transaction.summary)

    check.save()
    return check.completed
Beispiel #3
0
    def validate(self, measure):
        """
        Get all current QuotaOrderNumberOrigin objects associated with a
        measure's QuotaOrderNumber.

        Loop over these and raise a violation if the measure validity period is
        not contained by any of the origins
        """
        if not measure.order_number:
            return

        with override_current_transaction(self.transaction):
            contained_measure = measure.get_versions().current().get()

            origins = QuotaOrderNumberOrigin.objects.current().filter(
                order_number__order_number=measure.order_number.order_number, )

            for origin in origins:
                valid_between = origin.valid_between
                if validity_range_contains_range(
                        valid_between,
                        contained_measure.valid_between,
                ):
                    return

            raise self.violation(measure)
Beispiel #4
0
    def check(source, path, expected):
        approved = TransactionPartition.approved_partitions()
        for model in (source, *expected):
            assert model.transaction.partition in approved

        with override_current_transaction(Transaction.approved.last()):
            path_result = source.get_versions().current().follow_path(path)
            assert set(expected) == set(path_result)
Beispiel #5
0
def test_override_current_transaction():
    tx = factories.TransactionFactory.create()
    tx2 = factories.TransactionFactory.create()

    set_current_transaction(tx)

    with override_current_transaction(tx2):
        assert get_current_transaction() is tx2

    assert get_current_transaction() is tx
Beispiel #6
0
    def validate(self, measure):
        with override_current_transaction(self.transaction):
            measures = type(measure).objects.filter(pk=measure.pk)
            regulation_validity = measures.follow_path(
                "generating_regulation").get()
            replacements = measures.follow_path(
                "generating_regulation__replacements__enacting_regulation",
            ).filter(valid_between__contains=regulation_validity.valid_between)

            if replacements.exists():
                raise self.violation(measure)
Beispiel #7
0
def test_description_create_get_initial():
    """Test that, where more than one version of a certificate exists,
    get_initial returns only the current version."""
    certificate = factories.CertificateFactory.create()
    new_version = certificate.new_version(certificate.transaction.workbasket)
    view = CertificateDescriptionCreate(kwargs={
        "certificate_type__sid":
        certificate.certificate_type.sid,
        "sid":
        certificate.sid,
    }, )
    with override_current_transaction(new_version.transaction):
        initial = view.get_initial()

        assert initial["described_certificate"] == new_version
Beispiel #8
0
    def validate(self, order_number_origin):
        """
        Loop over measures that reference the same quota order number as origin.

        Get all the origins linked to this measure. Loop over these origins and
        check that every measure is contained by at least one origin.
        """
        with override_current_transaction(self.transaction):
            current_qs = order_number_origin.get_versions().current()
            contained_measures = current_qs.follow_path(
                self.contained_field_name)
            from measures.business_rules import ME119

            for measure in contained_measures:
                ME119(self.transaction).validate(measure)
Beispiel #9
0
    def check(
        factory: Type[DjangoModelFactory],
        business_rule: Type[ValidityPeriodContained],
        **factory_kwargs,
    ):
        container_validity, contained_validity, fully_spanned = spanning_dates

        contained = getattr(business_rule, "contained_field_name") or ""
        container = getattr(business_rule, "container_field_name") or ""

        # If the test is checking an UPDATE or a DELETE, set the dates to be
        # valid on the original version so that we can tell if it is
        # successfully checking the later version.
        validity_on_contained = (container_validity
                                 if update_type != UpdateType.CREATE else
                                 contained_validity)

        object = factory.create(
            **factory_kwargs,
            **{
                f"{contained}{'__' if contained else ''}valid_between":
                validity_on_contained,
                f"{contained}{'__' if contained else ''}update_type":
                UpdateType.CREATE,
                f"{container}{'__' if container else ''}valid_between":
                container_validity,
            },
        )
        workbasket = object.transaction.workbasket

        if update_type != UpdateType.CREATE:
            # Make a new version of the contained model with the actual dates we
            # are testing, first finding the correct contained model to use.
            contained_obj = object
            if contained:
                with override_current_transaction(
                        workbasket.current_transaction):
                    contained_obj = (object.get_versions().current().
                                     follow_path(contained).get())
            contained_obj.new_version(
                workbasket,
                valid_between=contained_validity,
                update_type=update_type,
            )

        error_expected = update_type != UpdateType.DELETE and not fully_spanned
        with raises_if(business_rule.Violation, error_expected):
            business_rule(workbasket.current_transaction).validate(object)
Beispiel #10
0
    def apply(self, model: TrackedModel, context: TransactionCheck):
        """Applies the check to the model and records success."""

        success, message = False, None
        try:
            with override_current_transaction(context.transaction):
                success, message = self.run(model)
        except Exception as e:
            success, message = False, str(e)
        finally:
            return TrackedModelCheck.objects.create(
                model=model,
                transaction_check=context,
                check_name=self.name,
                successful=success,
                message=message,
            )
Beispiel #11
0
def check_model(trackedmodel_id: int, context_id: int):
    """
    Runs all of the applicable checkers on the passed model ID, and records the
    results.

    Model checks are expected (from observation) to be short – on the order of
    6-7 seconds max. So if the check is taking considerably longer than this, it
    is probably broken and should be killed to free up the worker.
    """

    model: TrackedModel = TrackedModel.objects.get(pk=trackedmodel_id)
    context: TransactionCheck = TransactionCheck.objects.get(pk=context_id)
    transaction = context.transaction

    with override_current_transaction(transaction):
        for check in applicable_to(model):
            if not context.model_checks.filter(
                    model=model,
                    check_name=check.name,
            ).exists():
                # Run the checker on the model and record the result. (This is
                # not Celery ``apply`` but ``Checker.apply``).
                check.apply(model, context)
Beispiel #12
0
 def validate(self, model):
     with override_current_transaction(self.transaction):
         if self.violating_models(model).exists():
             raise self.violation(model)