Java Code Examples for reactor.test.util.RaceTestUtils#race()

The following examples show how to use reactor.test.util.RaceTestUtils#race() . 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: FluxScanTest.java    From reactor-core with Apache License 2.0 8 votes vote down vote up
@Test
public void onNextAndCancelRaceDontPassNullToAccumulator() {
	AtomicBoolean accumulatorCheck = new AtomicBoolean(true);
	final AssertSubscriber<Integer> testSubscriber = AssertSubscriber.create();

	FluxScan.ScanSubscriber<Integer> sub =
			new FluxScan.ScanSubscriber<>(testSubscriber, (accumulated, next) -> {
				if (accumulated == null || next == null) {
					accumulatorCheck.set(false);
				}
				return next;
			});

	sub.onSubscribe(Operators.emptySubscription());

	for (int i = 0; i < 1000; i++) {
		RaceTestUtils.race(sub::cancel, () -> sub.onNext(1));

		testSubscriber.assertNoError();
		assertThat(accumulatorCheck).as("no NPE due to onNext/cancel race in round " + i).isTrue();
	}
}
 
Example 2
Source File: WorkerTaskTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void setFutureRunRace() {
	for (int i = 0; i < RACE_DEFAULT_LOOPS; i++) {
		Disposable.Composite set = Disposables.composite();
		final WorkerTask run = new WorkerTask(() -> {}, set);
		set.add(run);

		final FutureTask<Object> ft = new FutureTask<>(() -> {
		}, 0);

		Runnable r1 = () -> run.setFuture(ft);

		Runnable r2 = run::run;

		RaceTestUtils.race(r1, r2);

		assertThat(set.size()).isZero();
	}
}
 
Example 3
Source File: MonoCacheTimeTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void raceSubscribeAndCache() {
	AtomicInteger count = new AtomicInteger();
	Mono<Integer> source = Mono.fromCallable(count::getAndIncrement);

	for (int i = 0; i < 500; i++) {
		Mono<Integer> cached;
		if (i == 0) {
			cached = source.log().cache(Duration.ofSeconds(2));
		}
		else {
			cached = source.cache(Duration.ofSeconds(2));
		}
		RaceTestUtils.race(cached::subscribe, cached::subscribe);
	}

	assertThat(count.get()).isEqualTo(500);
}
 
Example 4
Source File: WorkerTaskTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void setFutureCancelRace() {
	for (int i = 0; i < RACE_DEFAULT_LOOPS; i++) {
		Disposable.Composite set = Disposables.composite();
		final WorkerTask run = new WorkerTask(() -> {}, set);
		set.add(run);

		final FutureTask<Object> ft = new FutureTask<>(() -> {
		}, 0);

		Runnable r1 = () -> run.setFuture(ft);

		Runnable r2 = run::dispose;

		RaceTestUtils.race(r1, r2);

		assertThat(set.size()).isZero();
	}
}
 
Example 5
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 6
Source File: FluxBufferTimeoutTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void flushShouldNotRaceWithNext() {
	Set<Integer> seen = new HashSet<>();
	Consumer<List<Integer>> consumer = integers -> {
		for (Integer i : integers) {
			if (!seen.add(i)) {
				throw new IllegalStateException("Duplicate! " + i);
			}
		}
	};
	CoreSubscriber<List<Integer>> actual = new LambdaSubscriber<>(consumer, null, null, null);

	FluxBufferTimeout.BufferTimeoutSubscriber<Integer, List<Integer>> test = new FluxBufferTimeout.BufferTimeoutSubscriber<Integer, List<Integer>>(
			actual, 3, 1000, TimeUnit.MILLISECONDS, Schedulers.boundedElastic().createWorker(), ArrayList::new);
	test.onSubscribe(Operators.emptySubscription());

	AtomicInteger counter = new AtomicInteger();
	for (int i = 0; i < 500; i++) {
		RaceTestUtils.race(
				() -> test.onNext(counter.getAndIncrement()),
				() -> test.flushCallback(null),
				Schedulers.boundedElastic()
		);
	}
}
 
Example 7
Source File: FluxCreateTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
void bufferSinkRaceNextCancel() {
	AtomicInteger discarded = new AtomicInteger();
	final Context context = Operators.discardLocalAdapter(String.class, s -> discarded.incrementAndGet()).apply(Context.empty());

	BufferAsyncSink<String> sink = new BufferAsyncSink<>(new BaseSubscriber<String>() {
		@Override
		protected void hookOnSubscribe(Subscription subscription) {
			//do not request
		}

		@Override
		public Context currentContext() {
			return context;
		}
	}, 10);

	RaceTestUtils.race(sink::cancel,
			() -> sink.next("foo"));

	assertThat(sink.queue.poll()).as("internal queue empty").isNull();
	assertThat(discarded).as("discarded").hasValue(1);
}
 
Example 8
Source File: FluxLimitRequestTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void raceRequest() {
	List<Long> requests = Collections.synchronizedList(new ArrayList<>());
	final Flux<Integer> flux = Flux.range(1, 1000)
	                               .doOnRequest(requests::add)
	                               .limitRequest(81);
	BaseSubscriber<Integer> base = new BaseSubscriber<Integer>() {
		@Override
		protected void hookOnSubscribe(Subscription subscription) {
		}
	};
	flux.subscribe(base);

	for (int i = 0; i < 11; i++) {
		final int idx = i;
		RaceTestUtils.race(
				() -> base.request(idx % 2 == 0 ? 10 : 8),
				() -> base.request(8)
		);
	}

	assertThat(requests.stream().mapToLong(l -> l).sum())
			.as("total request should match the limitRequest")
			.isEqualTo(81);
	assertThat(requests.subList(0, requests.size() - 2))
			.allMatch(l -> l % 2 == 0, "all requests except last two are even");
	assertThat(requests)
			.filteredOn(l -> l % 2 == 1)
			.as("only one odd element toward end")
			.hasSize(1);
}
 
Example 9
Source File: ListCompositeDisposableTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void removeConcurrent() {
	for (int i = 0; i < 500; i++) {
		final Disposable d1 = new FakeDisposable();
		final Disposable.Composite cd = new ListCompositeDisposable(d1);

		RaceTestUtils.race(() -> cd.remove(d1), cd::dispose, Schedulers.boundedElastic());
	}
}
 
Example 10
Source File: FluxExpandTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void depthCancelRace() {
	for (int i = 0; i < 1000; i++) {
		final AssertSubscriber<Integer> ts = AssertSubscriber.create(0);

		Flux.just(0)
		    .expandDeep(countDown)
		    .subscribe(ts);

		Runnable r1 = () -> ts.request(1);
		Runnable r2 = ts::cancel;

		RaceTestUtils.race(r1, r2, Schedulers.single());
	}
}
 
Example 11
Source File: FluxSwitchOnFirstTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Test
public void unitRequestRacingTest() {
    @SuppressWarnings("unchecked")
    BiFunction<FluxSwitchOnFirst.AbstractSwitchOnFirstMain, CoreSubscriber, InnerOperator>[] factories = new BiFunction[] {
            (parent, assertSubscriber) -> new FluxSwitchOnFirst.SwitchOnFirstControlSubscriber((FluxSwitchOnFirst.AbstractSwitchOnFirstMain) parent, (CoreSubscriber) assertSubscriber, true),
            (parent, assertSubscriber) -> new FluxSwitchOnFirst.SwitchOnFirstConditionalControlSubscriber((FluxSwitchOnFirst.AbstractSwitchOnFirstMain) parent, (Fuseable.ConditionalSubscriber) assertSubscriber, true)
    };
    for (BiFunction<FluxSwitchOnFirst.AbstractSwitchOnFirstMain, CoreSubscriber, InnerOperator> factory : factories) {
        for (int i = 0; i < 10000; i++) {
            FluxSwitchOnFirst.AbstractSwitchOnFirstMain mockParent = Mockito.mock(FluxSwitchOnFirst.AbstractSwitchOnFirstMain.class);
            Mockito.doNothing().when(mockParent).request(Mockito.anyLong());
            Mockito.doNothing().when(mockParent).cancel();
            Subscription mockSubscription = Mockito.mock(Subscription.class);
            ArgumentCaptor<Long> longArgumentCaptor = ArgumentCaptor.forClass(Long.class);
            Mockito.doNothing().when(mockSubscription).request(longArgumentCaptor.capture());
            Mockito.doNothing().when(mockSubscription).cancel();
            AssertSubscriber<Object> subscriber = AssertSubscriber.create(0);
            InnerOperator switchOnFirstControlSubscriber = factory.apply(mockParent, Operators.toConditionalSubscriber(subscriber));

            switchOnFirstControlSubscriber.request(10);
            RaceTestUtils.race(() -> switchOnFirstControlSubscriber.request(10), () -> switchOnFirstControlSubscriber.onSubscribe(mockSubscription), Schedulers.parallel());

            Assertions.assertThat(longArgumentCaptor.getAllValues().size()).isBetween(1, 2);
            if (longArgumentCaptor.getAllValues().size() == 1) {
                Assertions.assertThat(longArgumentCaptor.getValue()).isEqualTo(20L);
            }
            else if (longArgumentCaptor.getAllValues().size() == 2) {
                Assertions.assertThat(longArgumentCaptor.getAllValues()).containsExactly(10L, 10L);
            }
            else {
                Assertions.fail("Unexpected number of calls");
            }
        }
    }
}
 
Example 12
Source File: FluxBufferWhenTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 5000)
public void cancelWinsOverDrain() {
	Queue<List<Integer>> queue = Queues.<List<Integer>>small().get();
	queue.offer(Arrays.asList(1, 2, 3));

	AssertSubscriber<List<Integer>> actual = AssertSubscriber.create();

	BufferWhenMainSubscriber<Integer, String, Void, List<Integer>> main =
			new BufferWhenMainSubscriber<>(actual,
					ArrayList::new,
					() -> queue,
					Mono.just("open"),
					i -> Mono.never());
	main.onSubscribe(Operators.emptySubscription());

	RaceTestUtils.race(main,
			m -> {
				m.cancel();
				m.drain();
				return m;
			},
			m -> m.cancelled,
			(m1, m2) -> /* ignored */ true);

	assertThat(main.cancelled).as("cancelled").isTrue();
	//TODO windows went as far up as 3, verify if that is indeed concurrent cancels
	assertThat(main.windows).as("windows").isLessThan(4);
	assertThat(queue).as("queue was cleared").isEmpty();

	//we also check no values were drained to the actual
	assertThat(actual.values())
			.as("no buffer should be drained")
			.isEmpty();
}
 
Example 13
Source File: FluxSwitchOnFirstTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void racingTest() throws InterruptedException {
    for (int i = 0; i < 1000; i++) {
        @SuppressWarnings("unchecked")
        CoreSubscriber<? super Integer>[] subscribers = new CoreSubscriber[1];
        Subscription[] downstreamSubscriptions = new Subscription[1];
        Subscription[] innerSubscriptions = new Subscription[1];


        AtomicLong requested = new AtomicLong();

        Flux.range(0, 3)
                .doOnRequest(requested::addAndGet)
                .switchOnFirst((s, f) -> new Flux<Integer>() {

                    @Override
                    public void subscribe(CoreSubscriber<? super Integer> actual) {
                        subscribers[0] = actual;
                        f.subscribe(actual::onNext, actual::onError, actual::onComplete, (s) -> innerSubscriptions[0] = s);
                    }
                })
                .subscribe(__ -> {
                }, __ -> {
                }, () -> {
                }, s -> downstreamSubscriptions[0] = s);

        CoreSubscriber<? super Integer> subscriber = subscribers[0];
        Subscription downstreamSubscription = downstreamSubscriptions[0];
        Subscription innerSubscription = innerSubscriptions[0];
        downstreamSubscription.request(1);

        RaceTestUtils.race(() -> subscriber.onSubscribe(innerSubscription), () -> downstreamSubscription.request(1));

        Assertions.assertThat(requested.get()).isEqualTo(2);
    }
}
 
Example 14
Source File: FluxSwitchOnFirstTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Test
public void unitRequestsAreSerialTest() {
    @SuppressWarnings("unchecked")
    BiFunction<FluxSwitchOnFirst.AbstractSwitchOnFirstMain, CoreSubscriber, InnerOperator>[] factories = new BiFunction[] {
            (parent, assertSubscriber) -> new FluxSwitchOnFirst.SwitchOnFirstControlSubscriber((FluxSwitchOnFirst.AbstractSwitchOnFirstMain) parent, (CoreSubscriber) assertSubscriber, true),
            (parent, assertSubscriber) -> new FluxSwitchOnFirst.SwitchOnFirstConditionalControlSubscriber((FluxSwitchOnFirst.AbstractSwitchOnFirstMain) parent, (Fuseable.ConditionalSubscriber) assertSubscriber, true)
    };
    for (BiFunction<FluxSwitchOnFirst.AbstractSwitchOnFirstMain, CoreSubscriber, InnerOperator> factory : factories) {
        for (int i = 0; i < 100000; i++) {
            long[] valueHolder = new long[] { 0 };
            FluxSwitchOnFirst.AbstractSwitchOnFirstMain mockParent = Mockito.mock(FluxSwitchOnFirst.AbstractSwitchOnFirstMain.class);
            Mockito.doNothing().when(mockParent).request(Mockito.anyLong());
            Mockito.doNothing().when(mockParent).cancel();
            Subscription mockSubscription = Mockito.mock(Subscription.class);
            Mockito.doAnswer((a) -> valueHolder[0] += (long) a.getArgument(0)).when(mockSubscription).request(Mockito.anyLong());
            Mockito.doNothing().when(mockSubscription).cancel();
            AssertSubscriber<Object> subscriber = AssertSubscriber.create(0);
            InnerOperator switchOnFirstControlSubscriber = factory.apply(mockParent, Operators.toConditionalSubscriber(subscriber));

            switchOnFirstControlSubscriber.request(10);
            RaceTestUtils.race(() -> {
                        switchOnFirstControlSubscriber.request(10);
                        switchOnFirstControlSubscriber.request(10);
                        switchOnFirstControlSubscriber.request(10);
                        switchOnFirstControlSubscriber.request(10);
                    },
                    () -> switchOnFirstControlSubscriber.onSubscribe(mockSubscription),
                    Schedulers.parallel());

            switchOnFirstControlSubscriber.request(10);
            Assertions.assertThat(valueHolder[0])
                      .isEqualTo(60L);
            mockSubscription.toString();
        }
    }
}
 
Example 15
Source File: FluxBufferPredicateTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void requestRaceWithOnNext() {
	AtomicLong requested = new AtomicLong();
	TestPublisher<Integer> testPublisher = TestPublisher.create();
	FluxBufferPredicate<Integer, List<Integer>> bufferPredicate = new FluxBufferPredicate<>(
			testPublisher.flux().doOnRequest(requested::addAndGet),
			i -> true, ArrayList::new, FluxBufferPredicate.Mode.UNTIL);

	BaseSubscriber<List<Integer>> subscriber = new BaseSubscriber<List<Integer>>() {
		@Override
		protected void hookOnSubscribe(Subscription subscription) {
			request(1);
		}
	};
	bufferPredicate.subscribe(subscriber);
	@SuppressWarnings("unchecked")
	final FluxBufferPredicate.BufferPredicateSubscriber<Integer, List<Integer>> bufferPredicateSubscriber =
			(FluxBufferPredicate.BufferPredicateSubscriber<Integer, List<Integer>>) subscriber.subscription;

	for (int i = 0; i < 10; i++) {
		final int value = i;
		RaceTestUtils.race(() -> subscriber.request(1), () -> testPublisher.next(value));
	}
	for (int i = 0; i < bufferPredicateSubscriber.requestedFromSource; i++) {
		testPublisher.next(100 + i);
	}
	testPublisher.complete();

	assertThat(requested).as("total upstream request").hasValue(10 + 1);
}
 
Example 16
Source File: OnDiscardShouldNotLeakTest.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
@Test
public void ensureMultipleSubscribersSupportWithNoLeaksWhenRacingCancelAndOnNextAndRequest() {
	int subscriptionsNumber = discardScenario.subscriptionsNumber;
	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);

		if (subscriptionsNumber == 1) {
			Tracked value = tracker.track(1);
			RaceTestUtils.race(
					() -> RaceTestUtils.race(
							assertSubscriber::cancel,
							() -> assertSubscriber.request(Long.MAX_VALUE),
							scheduler),
					() -> testPublishers[0].next(value),
					scheduler);
		}
		else {
			int startIndex = --index[0];
			Tracked value1 = tracker.track(startIndex);
			int secondIndex = --index[0];
			Tracked value2 = tracker.track(secondIndex);
			Runnable action = () -> RaceTestUtils.race(
					() -> testPublishers[startIndex].next(value1),
					() -> testPublishers[secondIndex].next(value2),
					scheduler);

			while (index[0] > 0) {
				int nextIndex = --index[0];
				Tracked nextValue = tracker.track(nextIndex);
				Runnable nextAction = action;
				action = () -> RaceTestUtils.race(
						nextAction,
						() -> testPublishers[nextIndex].next(nextValue),
						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 17
Source File: ReconnectMonoTests.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldEstablishValueOnceInCaseOfRacingBetweenBlocks() {
  Duration timeout = Duration.ofMillis(100);
  for (int i = 0; i < 10000; i++) {
    final TestPublisher<String> cold = TestPublisher.createCold();
    cold.next("value" + i);

    final ReconnectMono<String> reconnectMono =
        cold.mono().as(source -> new ReconnectMono<>(source, onExpire(), onValue()));

    Assertions.assertThat(expired).isEmpty();
    Assertions.assertThat(received).isEmpty();

    Assertions.assertThat(cold.subscribeCount()).isZero();

    String[] values1 = new String[1];
    String[] values2 = new String[1];

    RaceTestUtils.race(
        () -> values1[0] = reconnectMono.block(timeout),
        () -> values2[0] = reconnectMono.block(timeout));

    Assertions.assertThat(values2).containsExactly("value" + i);
    Assertions.assertThat(values1).containsExactly("value" + i);

    Assertions.assertThat(reconnectMono.resolvingInner.subscribers)
        .isEqualTo(ResolvingOperator.READY);

    Assertions.assertThat(cold.subscribeCount()).isOne();

    Assertions.assertThat(
            reconnectMono.resolvingInner.add(
                new ResolvingOperator.MonoDeferredResolutionOperator<>(
                    reconnectMono.resolvingInner, MonoProcessor.create())))
        .isEqualTo(ResolvingOperator.READY_STATE);

    Assertions.assertThat(expired).isEmpty();
    Assertions.assertThat(received)
        .hasSize(1)
        .containsOnly(Tuples.of("value" + i, reconnectMono));

    received.clear();
  }
}
 
Example 18
Source File: ReconnectMonoTests.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldNotExpireNewlyResolvedValueIfSubscribeIsRacingWithInvalidates() {
  Hooks.onErrorDropped(t -> {});
  for (int i = 0; i < 10000; i++) {
    final int index = i;
    final TestPublisher<String> cold =
        TestPublisher.createNoncompliant(TestPublisher.Violation.REQUEST_OVERFLOW);

    final ReconnectMono<String> reconnectMono =
        cold.mono().as(source -> new ReconnectMono<>(source, onExpire(), onValue()));

    final MonoProcessor<String> processor = reconnectMono.subscribeWith(MonoProcessor.create());
    final MonoProcessor<String> racerProcessor = MonoProcessor.create();

    Assertions.assertThat(expired).isEmpty();
    Assertions.assertThat(received).isEmpty();

    reconnectMono.resolvingInner.mainSubscriber.onNext("value_to_expire" + i);
    reconnectMono.resolvingInner.mainSubscriber.onComplete();

    RaceTestUtils.race(
        () ->
            RaceTestUtils.race(
                reconnectMono::invalidate, reconnectMono::invalidate, Schedulers.parallel()),
        () -> {
          reconnectMono.subscribe(racerProcessor);
          if (!racerProcessor.isTerminated()) {
            reconnectMono.resolvingInner.mainSubscriber.onNext(
                "value_to_possibly_expire" + index);
            reconnectMono.resolvingInner.mainSubscriber.onComplete();
          }
        },
        Schedulers.parallel());

    Assertions.assertThat(processor.isTerminated()).isTrue();

    Assertions.assertThat(processor.peek()).isEqualTo("value_to_expire" + i);
    StepVerifier.create(racerProcessor)
        .expectNextMatches(
            (v) ->
                v.equals("value_to_possibly_expire" + index)
                    || v.equals("value_to_expire" + index))
        .expectComplete()
        .verify(Duration.ofMillis(100));

    if (expired.size() == 2) {
      Assertions.assertThat(expired)
          .hasSize(2)
          .containsExactly("value_to_expire" + i, "value_to_possibly_expire" + i);
    } else {
      Assertions.assertThat(expired).hasSize(1).containsOnly("value_to_expire" + i);
    }
    if (received.size() == 2) {
      Assertions.assertThat(received)
          .hasSize(2)
          .containsExactly(
              Tuples.of("value_to_expire" + i, reconnectMono),
              Tuples.of("value_to_possibly_expire" + i, reconnectMono));
    } else {
      Assertions.assertThat(received)
          .hasSize(1)
          .containsOnly(Tuples.of("value_to_expire" + i, reconnectMono));
    }

    expired.clear();
    received.clear();
  }
}
 
Example 19
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 20
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();
  }
}