org.assertj.core.api.Assumptions Java Examples

The following examples show how to use org.assertj.core.api.Assumptions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RSocketRequesterTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@MethodSource("streamRacingCases")
public void ensuresCorrectOrderOfStreamIdIssuingInCaseOfRacing(
    BiFunction<ClientSocketRule, Payload, Publisher<?>> interaction1,
    BiFunction<ClientSocketRule, Payload, Publisher<?>> interaction2,
    FrameType interactionType1,
    FrameType interactionType2) {
  Assumptions.assumeThat(interactionType1).isNotEqualTo(METADATA_PUSH);
  Assumptions.assumeThat(interactionType2).isNotEqualTo(METADATA_PUSH);
  for (int i = 1; i < 10000; i += 4) {
    Payload payload = DefaultPayload.create("test", "test");
    Publisher<?> publisher1 = interaction1.apply(rule, payload);
    Publisher<?> publisher2 = interaction2.apply(rule, payload);
    RaceTestUtils.race(
        () -> publisher1.subscribe(AssertSubscriber.create()),
        () -> publisher2.subscribe(AssertSubscriber.create()));

    Assertions.assertThat(rule.connection.getSent())
        .extracting(FrameHeaderCodec::streamId)
        .containsExactly(i, i + 2);
    rule.connection.getSent().forEach(bb -> bb.release());
    rule.connection.getSent().clear();
  }
}
 
Example #2
Source File: FluxSwitchOnFirstTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeAbleToCancelSubscription() throws InterruptedException {
    Flux<Long> publisher = Flux.just(1L);
    ArrayList<Integer> capturedElementsNumber = new ArrayList<>();
    for (int i = 0; i < 10000; i++) {
        final ArrayList<Throwable> dropped = new ArrayList<>();
        final AtomicLong requested = new AtomicLong();
        final CountDownLatch latch = new CountDownLatch(1);
        final AssertSubscriber<Long> assertSubscriber = new AssertSubscriber<>(Context.of(Hooks.KEY_ON_ERROR_DROPPED, (Consumer<Throwable>) dropped::add), 0);
        final Flux<Long> switchTransformed = publisher
                                                .doOnRequest(requested::addAndGet)
                                                .doOnCancel(latch::countDown)
                                                .switchOnFirst((first, innerFlux) -> innerFlux.doOnComplete(latch::countDown));

        switchTransformed.subscribe(assertSubscriber);

        RaceTestUtils.race(assertSubscriber::cancel, () -> assertSubscriber.request(1));

        Assertions.assertThat(latch.await(500, TimeUnit.SECONDS)).isTrue();

        capturedElementsNumber.add(assertSubscriber.values().size());
    }

    Assumptions.assumeThat(capturedElementsNumber).contains(0);
    Assumptions.assumeThat(capturedElementsNumber).contains(1);
}
 
Example #3
Source File: ElasticsearchAvailable.java    From spring-data-examples with Apache License 2.0 5 votes vote down vote up
private void checkServerRunning() {

		try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
			CloseableHttpResponse response = client.execute(new HttpHead(url));
			if (response != null && response.getStatusLine() != null) {
				Assumptions.assumeThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
			}
		} catch (IOException e) {
			throw new AssumptionViolatedException(String.format("Elasticsearch Server seems to be down. %s", e.getMessage()));
		}
	}
 
Example #4
Source File: ElasticsearchAvailable.java    From spring-data-examples with Apache License 2.0 5 votes vote down vote up
private void checkServerRunning() {

		try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
			CloseableHttpResponse response = client.execute(new HttpHead(url));
			if (response != null && response.getStatusLine() != null) {
				Assumptions.assumeThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
			}
		} catch (IOException e) {
			throw new AssumptionViolatedException(String.format("Elasticsearch Server seems to be down. %s", e.getMessage()));
		}
	}
 
Example #5
Source File: DataChunkerTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void chunkShouldReturnSeveralArrayWhenInputBiggerThanChunkSize() {
    byte[] part1 = "1234567890".getBytes(StandardCharsets.UTF_8);
    byte[] part2 = "12345".getBytes(StandardCharsets.UTF_8);
    Assumptions.assumeThat(part1.length).isEqualTo(CHUNK_SIZE);
    byte[] data = Bytes.concat(part1, part2);

    Flux<ByteBuffer> chunks = testee.chunkStream(new ByteArrayInputStream(data), CHUNK_SIZE);

    assertThat(chunks.map(DataChunkerTest::read).toStream()).containsExactly(part1, part2);
}
 
Example #6
Source File: DataChunkerTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void chunkShouldReturnOneArrayWhenInputEqualsChunkSize() {
    byte[] data = "1234567890".getBytes(StandardCharsets.UTF_8);
    Assumptions.assumeThat(data.length).isEqualTo(CHUNK_SIZE);

    Flux<ByteBuffer> chunks = testee.chunkStream(new ByteArrayInputStream(data), CHUNK_SIZE);

    assertThat(chunks.map(DataChunkerTest::read).toStream()).containsExactly(data);
}
 
Example #7
Source File: DataChunkerTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void chunkShouldReturnSeveralArrayWhenInputBiggerThanChunkSize() {
    byte[] part1 = "1234567890".getBytes(StandardCharsets.UTF_8);
    byte[] part2 = "12345".getBytes(StandardCharsets.UTF_8);
    Assumptions.assumeThat(part1.length).isEqualTo(CHUNK_SIZE);
    byte[] data = Bytes.concat(part1, part2);

    Flux<ByteBuffer> chunks = testee.chunk(data, CHUNK_SIZE);

    assertThat(chunks.toStream()).containsExactly(ByteBuffer.wrap(part1), ByteBuffer.wrap(part2));
}
 
Example #8
Source File: DataChunkerTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void chunkShouldReturnOneArrayWhenInputEqualsChunkSize() {
    byte[] data = "1234567890".getBytes(StandardCharsets.UTF_8);
    Assumptions.assumeThat(data.length).isEqualTo(CHUNK_SIZE);

    Flux<ByteBuffer> chunks = testee.chunk(data, CHUNK_SIZE);

    assertThat(chunks.toStream()).containsExactly(ByteBuffer.wrap(data));
}
 
Example #9
Source File: CommandLineTest.java    From robozonky with Apache License 2.0 5 votes vote down vote up
@BeforeAll
static void ensureSecurityWorks() {
    /*
     * poorly configured JVMs in remote CI systems will fail here due to
     * https://stackoverflow.com/questions/27036588/errorcould-not-initialize-class-javax-crypto-jcesecurity
     */
    Assumptions.assumeThatCode(() -> {
        final String keyStorePassword = "password";
        final File keystore = File.createTempFile("robozonky-", ".keystore");
        keystore.delete();
        KeyStoreHandler.create(keystore, keyStorePassword.toCharArray());
    })
        .doesNotThrowAnyException();
}
 
Example #10
Source File: DefaultRSocketClientTests.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
@ParameterizedTest
@MethodSource("interactions")
@SuppressWarnings({"unchecked", "rawtypes"})
public void shouldHaveNoLeaksOnPayloadInCaseOfRacingOfOnNextAndCancel(
    BiFunction<RSocketClient, Publisher<Payload>, Publisher<?>> request, FrameType requestType)
    throws Throwable {
  Assumptions.assumeThat(requestType).isNotEqualTo(FrameType.REQUEST_CHANNEL);

  for (int i = 0; i < 10000; i++) {
    ClientSocketRule rule = new ClientSocketRule();
    rule.apply(
            new Statement() {
              @Override
              public void evaluate() {}
            },
            null)
        .evaluate();
    Payload payload = ByteBufPayload.create("test", "testMetadata");
    TestPublisher<Payload> testPublisher =
        TestPublisher.createNoncompliant(TestPublisher.Violation.DEFER_CANCELLATION);
    AssertSubscriber assertSubscriber = AssertSubscriber.create(0);

    Publisher<?> publisher = request.apply(rule.client, testPublisher);
    publisher.subscribe(assertSubscriber);

    testPublisher.assertWasNotRequested();

    assertSubscriber.request(1);

    testPublisher.assertWasRequested();
    testPublisher.assertMaxRequested(1);
    testPublisher.assertMinRequested(1);

    RaceTestUtils.race(
        () -> {
          testPublisher.next(payload);
          rule.delayer.run();
        },
        assertSubscriber::cancel);

    Collection<ByteBuf> sent = rule.connection.getSent();
    if (sent.size() == 1) {
      Assertions.assertThat(sent)
          .allMatch(bb -> FrameHeaderCodec.frameType(bb).equals(requestType))
          .allMatch(ReferenceCounted::release);
    } else if (sent.size() == 2) {
      Assertions.assertThat(sent)
          .first()
          .matches(bb -> FrameHeaderCodec.frameType(bb).equals(requestType))
          .matches(ReferenceCounted::release);
      Assertions.assertThat(sent)
          .element(1)
          .matches(bb -> FrameHeaderCodec.frameType(bb).equals(FrameType.CANCEL))
          .matches(ReferenceCounted::release);
    } else {
      Assertions.assertThat(sent).isEmpty();
    }

    rule.allocator.assertHasNoLeaks();
  }
}
 
Example #11
Source File: DefaultRSocketClientTests.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
@ParameterizedTest
@MethodSource("interactions")
@SuppressWarnings({"unchecked", "rawtypes"})
public void shouldPropagateDownstreamContext(
    BiFunction<RSocketClient, Publisher<Payload>, Publisher<?>> request, FrameType requestType) {
  Assumptions.assumeThat(requestType).isNotEqualTo(FrameType.REQUEST_CHANNEL);

  ByteBuf dataBuffer = rule.allocator.buffer();
  dataBuffer.writeCharSequence("test", CharsetUtil.UTF_8);

  ByteBuf metadataBuffer = rule.allocator.buffer();
  metadataBuffer.writeCharSequence("testMetadata", CharsetUtil.UTF_8);

  Payload payload = ByteBufPayload.create(dataBuffer, metadataBuffer);
  AssertSubscriber assertSubscriber = new AssertSubscriber(Context.of("test", "test"));

  Context[] receivedContext = new Context[1];
  Publisher<?> publisher =
      request.apply(
          rule.client,
          Mono.just(payload)
              .mergeWith(
                  Mono.subscriberContext()
                      .doOnNext(c -> receivedContext[0] = c)
                      .then(Mono.empty())));
  publisher.subscribe(assertSubscriber);

  rule.delayer.run();

  Collection<ByteBuf> sent = rule.connection.getSent();
  if (sent.size() == 1) {
    Assertions.assertThat(sent)
        .allMatch(bb -> FrameHeaderCodec.frameType(bb).equals(requestType))
        .allMatch(ReferenceCounted::release);
  } else if (sent.size() == 2) {
    Assertions.assertThat(sent)
        .first()
        .matches(bb -> FrameHeaderCodec.frameType(bb).equals(requestType))
        .matches(ReferenceCounted::release);
    Assertions.assertThat(sent)
        .element(1)
        .matches(bb -> FrameHeaderCodec.frameType(bb).equals(FrameType.CANCEL))
        .matches(ReferenceCounted::release);
  } else {
    Assertions.assertThat(sent).isEmpty();
  }

  Assertions.assertThat(receivedContext)
      .hasSize(1)
      .allSatisfy(
          c ->
              Assertions.assertThat(
                      c.stream()
                          .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)))
                  .containsKeys("test", DefaultRSocketClient.ON_DISCARD_KEY));

  rule.allocator.assertHasNoLeaks();
}
 
Example #12
Source File: DefaultRSocketClientTests.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
@ParameterizedTest
@MethodSource("interactions")
@SuppressWarnings({"unchecked", "rawtypes"})
public void shouldHaveNoLeaksOnPayloadInCaseOfRacingOfRequestAndCancel(
    BiFunction<RSocketClient, Publisher<Payload>, Publisher<?>> request, FrameType requestType)
    throws Throwable {
  Assumptions.assumeThat(requestType).isNotEqualTo(FrameType.REQUEST_CHANNEL);

  for (int i = 0; i < 10000; i++) {
    ClientSocketRule rule = new ClientSocketRule();
    rule.apply(
            new Statement() {
              @Override
              public void evaluate() {}
            },
            null)
        .evaluate();
    ByteBuf dataBuffer = rule.allocator.buffer();
    dataBuffer.writeCharSequence("test", CharsetUtil.UTF_8);

    ByteBuf metadataBuffer = rule.allocator.buffer();
    metadataBuffer.writeCharSequence("testMetadata", CharsetUtil.UTF_8);

    Payload payload = ByteBufPayload.create(dataBuffer, metadataBuffer);
    AssertSubscriber assertSubscriber = AssertSubscriber.create(0);

    Publisher<?> publisher = request.apply(rule.client, Mono.just(payload));
    publisher.subscribe(assertSubscriber);

    RaceTestUtils.race(
        () -> {
          assertSubscriber.request(1);
          rule.delayer.run();
        },
        assertSubscriber::cancel);

    Collection<ByteBuf> sent = rule.connection.getSent();
    if (sent.size() == 1) {
      Assertions.assertThat(sent)
          .allMatch(bb -> FrameHeaderCodec.frameType(bb).equals(requestType))
          .allMatch(ReferenceCounted::release);
    } else if (sent.size() == 2) {
      Assertions.assertThat(sent)
          .first()
          .matches(bb -> FrameHeaderCodec.frameType(bb).equals(requestType))
          .matches(ReferenceCounted::release);
      Assertions.assertThat(sent)
          .element(1)
          .matches(bb -> FrameHeaderCodec.frameType(bb).equals(FrameType.CANCEL))
          .matches(ReferenceCounted::release);
    } else {
      Assertions.assertThat(sent).isEmpty();
    }

    rule.allocator.assertHasNoLeaks();
  }
}
 
Example #13
Source File: OnDiscardShouldNotLeakTest.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
@Test
public void ensureNoLeaksPopulatedQueueAndRacingCancelAndRequest() {
	Assumptions.assumeThat(discardScenario.subscriptionsNumber).isOne();
	for (int i = 0; i < 10000; i++) {
		tracker.reset();
		TestPublisher<Tracked> testPublisher = TestPublisher.createNoncompliant(
				TestPublisher.Violation.DEFER_CANCELLATION,
				TestPublisher.Violation.REQUEST_OVERFLOW);
		@SuppressWarnings("unchecked")
		Publisher<Tracked> source = discardScenario.producePublisherFromSources(testPublisher);

		if (conditional) {
			if (source instanceof Flux) {
				source = ((Flux<Tracked>) source).filter(t -> true);
			}
			else {
				source = ((Mono<Tracked>) source).filter(t -> true);
			}
		}

		Scannable scannable = Scannable.from(source);
		Integer prefetch = scannable.scan(Scannable.Attr.PREFETCH);

		Assumptions.assumeThat(prefetch).isNotZero();

		AssertSubscriber<Tracked> assertSubscriber = new AssertSubscriber<>(Operators.enableOnDiscard(null, Tracked::safeRelease), 0);
		if (fused) {
			assertSubscriber.requestedFusionMode(Fuseable.ANY);
		}
		source.subscribe(assertSubscriber);

		testPublisher.next(tracker.track(1));
		testPublisher.next(tracker.track(2));
		testPublisher.next(tracker.track(3));
		testPublisher.next(tracker.track(4));

		RaceTestUtils.race(
				assertSubscriber::cancel,
				() -> assertSubscriber.request(Long.MAX_VALUE),
				scheduler);

		List<Tracked> values = assertSubscriber.values();
		values.forEach(Tracked::release);

		tracker.assertNoLeaks();
	}
}
 
Example #14
Source File: OnDiscardShouldNotLeakTest.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
@Test
public void ensureNoLeaksPopulatedQueueAndRacingCancelAndOverflowError() {
	Assumptions.assumeThat(discardScenario.subscriptionsNumber).isOne();
	for (int i = 0; i < 10000; i++) {
		tracker.reset();
		TestPublisher<Tracked> testPublisher = TestPublisher.createNoncompliant(
				TestPublisher.Violation.DEFER_CANCELLATION,
				TestPublisher.Violation.REQUEST_OVERFLOW);
		@SuppressWarnings("unchecked")
		Publisher<Tracked> source = discardScenario.producePublisherFromSources(testPublisher);

		if (conditional) {
			if (source instanceof Flux) {
				source = ((Flux<Tracked>) source).filter(t -> true);
			}
			else {
				source = ((Mono<Tracked>) source).filter(t -> true);
			}
		}

		Scannable scannable = Scannable.from(source);
		Integer capacity = scannable.scan(Scannable.Attr.CAPACITY);
		Integer prefetch = Math.min(scannable.scan(Scannable.Attr.PREFETCH),
				capacity == 0 ? Integer.MAX_VALUE : capacity);

		Assumptions.assumeThat(prefetch).isNotZero();
		Assumptions.assumeThat(prefetch).isNotEqualTo(Integer.MAX_VALUE);
		AssertSubscriber<Tracked> assertSubscriber = new AssertSubscriber<>(Operators.enableOnDiscard(null, Tracked::safeRelease), 0);
		if (fused) {
			assertSubscriber.requestedFusionMode(Fuseable.ANY);
		}
		source.subscribe(assertSubscriber);

		for (int j = 0; j < prefetch - 1; j++) {
			testPublisher.next(tracker.track(j));
		}

		Tracked lastValue = tracker.track(prefetch - 1);
		Tracked overflowValue1 = tracker.track(prefetch);
		Tracked overflowValue2 = tracker.track(prefetch + 1);

		RaceTestUtils.race(assertSubscriber::cancel, () -> {
			testPublisher.next(lastValue);
			testPublisher.next(overflowValue1);
			testPublisher.next(overflowValue2);
		});

		List<Tracked> values = assertSubscriber.values();
		values.forEach(Tracked::release);
		if (assertSubscriber.isTerminated()) {
			// has a chance to error with rejected exception
			assertSubscriber.assertError();
		}

		tracker.assertNoLeaks();
	}
}
 
Example #15
Source File: OnDiscardShouldNotLeakTest.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
@Test
public void ensureNoLeaksPopulatedQueueAndRacingCancelAndOnError() {
	Assumptions.assumeThat(discardScenario.subscriptionsNumber).isOne();
	for (int i = 0; i < 10000; i++) {
		tracker.reset();
		TestPublisher<Tracked> testPublisher = TestPublisher.createNoncompliant(
				TestPublisher.Violation.DEFER_CANCELLATION,
				TestPublisher.Violation.REQUEST_OVERFLOW);
		@SuppressWarnings("unchecked")
		Publisher<Tracked> source = discardScenario.producePublisherFromSources(testPublisher);

		if (conditional) {
			if (source instanceof Flux) {
				source = ((Flux<Tracked>) source).filter(t -> true);
			}
			else {
				source = ((Mono<Tracked>) source).filter(t -> true);
			}
		}

		Scannable scannable = Scannable.from(source);
		Integer prefetch = scannable.scan(Scannable.Attr.PREFETCH);

		Assumptions.assumeThat(prefetch).isNotZero();

		AssertSubscriber<Tracked> assertSubscriber = new AssertSubscriber<>(Operators.enableOnDiscard(null, Tracked::safeRelease), 0);
		if (fused) {
			assertSubscriber.requestedFusionMode(Fuseable.ANY);
		}
		source.subscribe(assertSubscriber);

		testPublisher.next(tracker.track(1));
		testPublisher.next(tracker.track(2));
		testPublisher.next(tracker.track(3));
		testPublisher.next(tracker.track(4));

		RaceTestUtils.race(
				assertSubscriber::cancel,
				() -> testPublisher.error(new RuntimeException("test")),
				scheduler);

		List<Tracked> values = assertSubscriber.values();
		values.forEach(Tracked::release);
		if (assertSubscriber.isTerminated()) {
			// has a chance to error with rejected exception
			assertSubscriber.assertError();
		}

		tracker.assertNoLeaks();
	}
}
 
Example #16
Source File: OnDiscardShouldNotLeakTest.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
@Test
public void ensureNoLeaksPopulatedQueueAndRacingCancelAndOnComplete() {
	Assumptions.assumeThat(discardScenario.subscriptionsNumber).isOne();
	for (int i = 0; i < 10000; i++) {
		tracker.reset();
		TestPublisher<Tracked> testPublisher = TestPublisher.createNoncompliant(
				TestPublisher.Violation.DEFER_CANCELLATION,
				TestPublisher.Violation.REQUEST_OVERFLOW);
		Publisher<Tracked> source = discardScenario.producePublisherFromSources(testPublisher);

		if (conditional) {
			if (source instanceof Flux) {
				source = ((Flux<Tracked>) source).filter(t -> true);
			}
			else {
				source = ((Mono<Tracked>) source).filter(t -> true);
			}
		}

		Scannable scannable = Scannable.from(source);
		Integer prefetch = scannable.scan(Scannable.Attr.PREFETCH);

		Assumptions.assumeThat(prefetch).isNotZero();

		AssertSubscriber<Tracked> assertSubscriber = new AssertSubscriber<>(Operators.enableOnDiscard(null, Tracked::safeRelease), 0);
		if (fused) {
			assertSubscriber.requestedFusionMode(Fuseable.ANY);
		}
		source.subscribe(assertSubscriber);

		testPublisher.next(tracker.track(1));
		testPublisher.next(tracker.track(2));
		testPublisher.next(tracker.track(3));
		testPublisher.next(tracker.track(4));

		RaceTestUtils.race(
				assertSubscriber::cancel,
				() -> testPublisher.complete(),
				scheduler);

		List<Tracked> values = assertSubscriber.values();
		values.forEach(Tracked::release);

		tracker.assertNoLeaks();
	}
}
 
Example #17
Source File: OnDiscardShouldNotLeakTest.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
@Test
public void ensureNoLeaksPopulatedQueueAndRacingCancelAndOnNext() {
	Assumptions.assumeThat(discardScenario.subscriptionsNumber).isOne();
	for (int i = 0; i < 10000; i++) {
		tracker.reset();
		TestPublisher<Tracked> testPublisher = TestPublisher.createNoncompliant(
				TestPublisher.Violation.DEFER_CANCELLATION,
				TestPublisher.Violation.REQUEST_OVERFLOW);
		Publisher<Tracked> source = discardScenario.producePublisherFromSources(testPublisher);

		if (conditional) {
			if (source instanceof Flux) {
				source = ((Flux<Tracked>) source).filter(t -> true);
			}
			else {
				source = ((Mono<Tracked>) source).filter(t -> true);
			}
		}

		Scannable scannable = Scannable.from(source);
		Integer prefetch = scannable.scan(Scannable.Attr.PREFETCH);

		Assumptions.assumeThat(prefetch).isNotZero();

		AssertSubscriber<Tracked> assertSubscriber = new AssertSubscriber<>(Operators.enableOnDiscard(null, Tracked::safeRelease), 0);
		if (fused) {
			assertSubscriber.requestedFusionMode(Fuseable.ANY);
		}
		source.subscribe(assertSubscriber);

		testPublisher.next(tracker.track(1));
		testPublisher.next(tracker.track(2));

		Tracked value3 = tracker.track(3);
		Tracked value4 = tracker.track(4);
		Tracked value5 = tracker.track(5);

		RaceTestUtils.race(assertSubscriber::cancel, () -> {
			testPublisher.next(value3);
			testPublisher.next(value4);
			testPublisher.next(value5);
		}, scheduler);

		List<Tracked> values = assertSubscriber.values();
		values.forEach(Tracked::release);

		tracker.assertNoLeaks();
	}
}
 
Example #18
Source File: OnDiscardShouldNotLeakTest.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
@Test
public void ensureMultipleSubscribersSupportWithNoLeaksWhenPopulatedQueueRacingCancelAndOnNextAndRequest() {
	int subscriptionsNumber = discardScenario.subscriptionsNumber;
	Assumptions.assumeThat(subscriptionsNumber).isGreaterThan(1);

	for (int i = 0; i < 10000; i++) {
		tracker.reset();
		int[] index = new int[]{subscriptionsNumber};
		TestPublisher<Tracked>[] testPublishers = new TestPublisher[subscriptionsNumber];

		for (int i1 = 0; i1 < subscriptionsNumber; i1++) {
			testPublishers[i1] = TestPublisher.createNoncompliant(
					TestPublisher.Violation.DEFER_CANCELLATION,
					TestPublisher.Violation.REQUEST_OVERFLOW);
		}

		Publisher<Tracked> source = discardScenario.producePublisherFromSources(testPublishers[0], Arrays.copyOfRange(testPublishers, 1, testPublishers.length));

		if (conditional) {
			if (source instanceof Flux) {
				source = ((Flux<Tracked>) source).filter(t -> true);
			}
			else {
				source = ((Mono<Tracked>) source).filter(t -> true);
			}
		}

		AssertSubscriber<Tracked> assertSubscriber = new AssertSubscriber<>(Operators.enableOnDiscard(null, Tracked::safeRelease), 0);
		if (fused) {
			assertSubscriber.requestedFusionMode(Fuseable.ANY);
		}
		source.subscribe(assertSubscriber);
		int startIndex = --index[0];
		Tracked value11 = tracker.track(startIndex+"1");
		Tracked value12 = tracker.track(startIndex+"2");
		Tracked value13 = tracker.track(startIndex+"3");
		Tracked value14 = tracker.track(startIndex+"4");
		int secondIndex = --index[0];
		Tracked value21 = tracker.track(secondIndex+"1");
		Tracked value22 = tracker.track(secondIndex+"2");
		Tracked value23 = tracker.track(secondIndex+"3");
		Tracked value24 = tracker.track(secondIndex+"4");
		Runnable action = () -> RaceTestUtils.race(
				() -> testPublishers[startIndex].next(value11, value12, value13, value14),
				() -> testPublishers[secondIndex].next(value21, value22, value23, value24),
				scheduler);

		while (index[0] > 0) {
			int nextIndex = --index[0];
			Tracked nextValue1 = tracker.track(nextIndex+"1");
			Tracked nextValue2 = tracker.track(nextIndex+"2");
			Tracked nextValue3 = tracker.track(nextIndex+"3");
			Tracked nextValue4 = tracker.track(nextIndex+"4");
			Runnable nextAction = action;
			action = () -> RaceTestUtils.race(
					nextAction,
					() -> testPublishers[nextIndex].next(nextValue1, nextValue2, nextValue3, nextValue4),
					scheduler);
		}
		RaceTestUtils.race(() ->
				RaceTestUtils.race(
						assertSubscriber::cancel,
						() -> assertSubscriber.request(Long.MAX_VALUE),
						scheduler),
				action,
				scheduler);
		List<Tracked> values = assertSubscriber.values();
		values.forEach(Tracked::release);

		tracker.assertNoLeaks();
	}
}
 
Example #19
Source File: MetricsNoMicrometerTest.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void assumeNoMicrometer() {
	Assumptions.assumeThat(Metrics.isInstrumentationAvailable())
	           .as("Micrometer on the classpath").isFalse();
}