<commit_before>/*
 * Copyright 2020, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package io.spine.testing.server.blackbox;

import io.spine.core.Subscribe;
import io.spine.server.event.AbstractEventSubscriber;
import io.spine.system.server.HandlerFailedUnexpectedly;

import static io.spine.json.Json.toJson;
import static java.lang.String.format;
import static java.lang.System.lineSeparator;
import static org.junit.jupiter.api.Assertions.fail;

/**
 * Performs logging of failed signals handling or fails the test depending the current
 * context exception tolerance.
 */
final class ExceptionGuard extends AbstractEventSubscriber implements ExceptionLogging {

    private ExceptionTolerance tolerance = ExceptionTolerance.RAISE;

    @Subscribe
    void on(HandlerFailedUnexpectedly event) {
        String msg = format(
                "The entity (state type `%s`) could not handle the signal `%s`:%n%s%n",
                event.getEntity().getTypeUrl(),
                event.getHandledSignal().getTypeUrl(),
                event.getError().getMessage()
        );
        switch (tolerance){
            case LOG:
                log(msg, event);
                break;
            case RAISE:
            default:
                fail(() -> msg + lineSeparator() + toJson(event));
        }
    }

    /**
     * Asks the guard to tolerate exceptions.
     */
    void tolerate() {
        tolerance = ExceptionTolerance.LOG;
    }
}<commit_msg>Refactor the guard to not die within an infinite `HandlerFailedUnexpectedly` loop while using `@Subscribe` and throwing AssertionFailedError.<commit_after>/*
 * Copyright 2020, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package io.spine.testing.server.blackbox;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableSet;
import io.spine.server.event.AbstractEventSubscriber;
import io.spine.server.type.EventClass;
import io.spine.server.type.EventEnvelope;
import io.spine.system.server.HandlerFailedUnexpectedly;

import static io.spine.json.Json.toJson;
import static java.lang.String.format;
import static java.lang.System.lineSeparator;
import static org.junit.jupiter.api.Assertions.fail;

/**
 * Performs logging of failed signals handling or fails the test depending the current
 * context exception tolerance.
 */
final class ExceptionGuard extends AbstractEventSubscriber implements ExceptionLogging {

    private ExceptionTolerance tolerance = ExceptionTolerance.RAISE;

    @Override
    public ImmutableSet<EventClass> messageClasses() {
        return EventClass.setOf(HandlerFailedUnexpectedly.class);
    }

    /**
     * Always dispatched {@link HandlerFailedUnexpectedly} event.
     */
    @Override
    public boolean canDispatch(EventEnvelope eventEnvelope) {
        return true;
    }

    @Override
    protected void handle(EventEnvelope eventEnvelope) {
        HandlerFailedUnexpectedly event = (HandlerFailedUnexpectedly) eventEnvelope.message();
        on(event);
    }

    /**
     * Throws an {@link org.opentest4j.AssertionFailedError AssertionFailedError}
     * unless the guard is configured to {@linkplain #tolerate() tolerate} exceptions.
     *
     * <p>If the guard is tolerating exceptions, logs the handler failure.
     */
    @VisibleForTesting
    void on(HandlerFailedUnexpectedly event) {
        String msg = format(
                "The entity (state type `%s`) could not handle the signal `%s`:%n%s%n",
                event.getEntity().getTypeUrl(),
                event.getHandledSignal().getTypeUrl(),
                event.getError().getMessage()
        );
        switch (tolerance) {
            case LOG:
                log(msg, event);
                break;
            case RAISE:
            default:
                fail(() -> msg + lineSeparator() + toJson(event));
        }
    }

    /**
     * Asks the guard to tolerate exceptions.
     */
    void tolerate() {
        tolerance = ExceptionTolerance.LOG;
    }

    /**
     * {@inheritDoc}
     *
     * <p>The {@code BlackBoxBoundedContext} only consumes domestic events.
     */
    @Override
    public ImmutableSet<EventClass> domesticEventClasses() {
        return eventClasses();
    }

    /**
     * {@inheritDoc}
     *
     * <p>The {@code BlackBoxBoundedContext} does not consume external events.
     */
    @Override
    public ImmutableSet<EventClass> externalEventClasses() {
        return ImmutableSet.of();
    }
}
{'fraction_non_alphanumeric': 0.0829137822529893, 'fraction_numerical': 0.0014159848961611077, 'mean_word_length': 3.1359791802212102, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6747379', 'n_tokens_mistral': 1745, 'n_tokens_neox': 1603, 'n_words': 578}