@Test public void discardAdapterIsAdditive() { List<String> discardOrder = Collections.synchronizedList(new ArrayList<>(2)); Function<Context, Context> first = Operators.discardLocalAdapter(Number.class, i -> discardOrder.add("FIRST")); Function<Context, Context> second = Operators.discardLocalAdapter(Integer.class, i -> discardOrder.add("SECOND")); Context ctx = first.apply(second.apply(Context.empty())); Consumer<Object> test = ctx.getOrDefault(Hooks.KEY_ON_DISCARD, o -> {}); assertThat(test).isNotNull(); test.accept(1); assertThat(discardOrder).as("consumers were combined").containsExactly("FIRST", "SECOND"); }
public void assertPrimaryKey(String tableName, @Nullable String expectedPkName, String columnName, String... otherColumnNames) { try (Connection connection = getConnection()) { PK pk = pkOf(connection, tableName.toUpperCase(Locale.ENGLISH)); if (pk == null) { pkOf(connection, tableName.toLowerCase(Locale.ENGLISH)); } assertThat(pk).as("No primary key is defined on table %s", tableName).isNotNull(); if (expectedPkName != null) { assertThat(pk.getName()).isEqualToIgnoringCase(expectedPkName); } List<String> expectedColumns = ImmutableList.copyOf(Iterables.concat(Collections.singletonList(columnName), Arrays.asList(otherColumnNames))); assertThat(pk.getColumns()).as("Primary key does not have the '%s' expected columns", expectedColumns.size()).hasSize(expectedColumns.size()); Iterator<String> expectedColumnsIt = expectedColumns.iterator(); Iterator<String> actualColumnsIt = pk.getColumns().iterator(); while (expectedColumnsIt.hasNext() && actualColumnsIt.hasNext()) { assertThat(actualColumnsIt.next()).isEqualToIgnoringCase(expectedColumnsIt.next()); } } catch (SQLException e) { throw new IllegalStateException("Fail to check primary key", e); } }
@Test //see https://github.com/reactor/reactor-core/issues/951 public void gh951_withoutDoOnError() { List<String> events = new ArrayList<>(); Assertions.assertThatExceptionOfType(UnsupportedOperationException.class) .isThrownBy(Mono.just(true) .map(this::throwError) .doFinally(any -> events.add("doFinally " + any.toString())) ::subscribe) .withMessage("java.lang.IllegalStateException: boom"); Assertions.assertThat(events) .as("withoutDoOnError") .containsExactly("doFinally onError"); }
protected void assertPotentialOwners(Task task, int expectedSize, String... expectedNames) { List<OrganizationalEntity> potentialOwners = task.getPeopleAssignments().getPotentialOwners(); assertThat(potentialOwners).hasSize(expectedSize); if (expectedNames.length > 0) { assertThat(potentialOwners).as("No match for expected potential owner name") .extracting(OrganizationalEntity::getId) .contains(expectedNames); } }
.as("subscribe without consumer: map_doOnError_doFinally") .containsExactly("doOnError", "doFinally onError"); .as("subscribe without consumer: doFinally_map_doOnError") .containsExactly("doFinally cancel", "doOnError"); .as("subscribe without consumer: map_doFinally_doOnError") .containsExactly("doOnError", "doFinally onError");
.as("subscribe with consumer: map_doOnError_doFinally") .containsExactly("doOnError", "doFinally onError"); .as("subscribe with consumer: doFinally_map_doOnError") .containsExactly("doFinally cancel", "doOnError"); .as("subscribe with consumer: map_doFinally_doOnError") .containsExactly("doOnError", "doFinally onError");
@Test public void boundedDownStreamRequestOverflowsCap() { List<Long> requests = new ArrayList<>(); final Flux<Integer> source = Flux.range(1, 100) .doOnRequest(requests::add); Flux<Integer> test = new FluxLimitRequest<>(source, 10); StepVerifier.create(test, 0) .expectSubscription() .expectNoEvent(Duration.ofMillis(100)) .then(() -> assertThat(requests).as("no initial prefetch").isEmpty()) .thenRequest(4) .expectNext(1, 2, 3, 4) .then(() -> assertThat(requests) .as("request under cap should be propagated as is") .containsExactly(4L)) .thenRequest(18) .expectNext(5, 6, 7,8, 9, 10) .verifyComplete(); assertThat(requests) .as("limitRequest should rebatch last request") .containsExactly(4L, 6L); assertThat(requests.stream().mapToLong(l -> l).sum()) .as("total request should match the limitRequest") .isEqualTo(10); }
@Test public void captureNowInScheduledTask() { VirtualTimeScheduler vts = VirtualTimeScheduler.create(); List<Long> singleExecutionsTimestamps = new ArrayList<>(); List<Long> periodicExecutionTimestamps = new ArrayList<>(); try { vts.advanceTimeBy(Duration.ofMillis(100)); vts.schedule(() -> singleExecutionsTimestamps.add(vts.now(TimeUnit.MILLISECONDS)), 100, TimeUnit.MILLISECONDS); vts.schedule(() -> singleExecutionsTimestamps.add(vts.now(TimeUnit.MILLISECONDS)), 456, TimeUnit.MILLISECONDS); vts.schedulePeriodically(() -> periodicExecutionTimestamps.add(vts.now(TimeUnit.MILLISECONDS)), 0, 100, TimeUnit.MILLISECONDS); vts.advanceTimeBy(Duration.ofMillis(1000)); assertThat(singleExecutionsTimestamps) .as("single executions") .containsExactly(100L, 456L + 100L); assertThat(periodicExecutionTimestamps) .as("periodic executions") .containsExactly(100L, 200L, 300L, 400L, 500L, 600L, 700L, 800L, 900L, 1000L, 1100L); } finally { vts.dispose(); } }
@Test public void nestedSchedule() { VirtualTimeScheduler vts = VirtualTimeScheduler.create(); List<Long> singleExecutionsTimestamps = new ArrayList<>(); try { vts.schedule(() -> vts.schedule( () -> singleExecutionsTimestamps.add(vts.now(TimeUnit.MILLISECONDS)), 100, TimeUnit.MILLISECONDS ), 300, TimeUnit.MILLISECONDS); vts.advanceTimeBy(Duration.ofMillis(1000)); assertThat(singleExecutionsTimestamps) .as("single executions") .containsExactly(400L); } finally { vts.dispose(); } }
@Test public void all_core_metrics_are_in_core_bundle() { List<Metric> coreMetrics = CoreMetrics.getMetrics(); List<String> incorrectMetricDefinitions = new ArrayList<>(); for (Metric metric : coreMetrics) { if (metric.isHidden()) { continue; } String metricNamePropertyKey = "metric." + metric.getKey() + ".name"; String l10nMetricName = underTest.message(Locale.ENGLISH, metricNamePropertyKey, null); if (l10nMetricName == null) { incorrectMetricDefinitions.add(metricNamePropertyKey + "=" + metric.getName()); } else if (!l10nMetricName.equals(metric.getName())) { incorrectMetricDefinitions.add(metricNamePropertyKey + " is not consistent in core bundle and CoreMetrics"); } String metricDescriptionPropertyKey = "metric." + metric.getKey() + ".description"; String l10nMetricDescription = underTest.message(Locale.ENGLISH, metricDescriptionPropertyKey, null); if (l10nMetricDescription == null) { incorrectMetricDefinitions.add(metricDescriptionPropertyKey + "=" + metric.getDescription()); } else if (!l10nMetricDescription.equals(metric.getDescription())) { incorrectMetricDefinitions.add(metricDescriptionPropertyKey + " is not consistent in core bundle and CoreMetrics"); } } assertThat(incorrectMetricDefinitions).as("Metric definitions to fix in core bundle", incorrectMetricDefinitions.size()).isEmpty(); }
@Test public void resumeConditional() { RuntimeException nextError = new IllegalStateException("next"); List<Throwable> resumedErrors = new ArrayList<>(); List<Object> resumedValues = new ArrayList<>(); Context context = Context.of(OnNextFailureStrategy.KEY_ON_NEXT_ERROR_STRATEGY, OnNextFailureStrategy.resume((t, s) -> { resumedErrors.add(t); resumedValues.add(s); })); ConditionalAssertSubscriber<Integer> actual = new ConditionalAssertSubscriber<>(context); SignalPeekThrowNext<Integer> peekParent = new SignalPeekThrowNext<>(nextError); AssertQueueSubscription<Integer> qs = new AssertQueueSubscription<>(); PeekConditionalSubscriber<Integer> test = new PeekConditionalSubscriber<>(actual, peekParent); test.onSubscribe(qs); test.onNext(1); assertThat(actual.next).as("onNext skips").isEmpty(); assertThat(qs.requested).as("onNext requested more").isEqualTo(1); boolean tryOnNext = test.tryOnNext(2); assertThat(tryOnNext).as("tryOnNext skips").isFalse(); test.onComplete(); assertThat(actual.error).isNull(); assertThat(actual.completed).isTrue(); assertThat(resumedErrors).containsExactly(nextError, nextError); assertThat(resumedValues).containsExactly(1, 2); }
void assertAllRunningTasksMatch(final String environmentName, final String taskDefinition) throws InterruptedException { waitOrTimeout( RECONCILIATION_INTERVAL * 3 / 2, () -> assertThat(stack.describeTasks()) .as("Tasks launched by blox") .allSatisfy( t -> assertThat(t) .hasFieldOrPropertyWithValue("group", environmentName) .hasFieldOrPropertyWithValue("taskDefinitionArn", taskDefinition))); } }
@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); }
assertThat(actual.next).as("onNext skips").isEmpty(); assertThat(qs.requested).as("onNext requested more").isEqualTo(1);
@Test public void flakyTestsCanBeAddedToCategory() throws IOException { Category category = new Category() .setName(CATEGORY_NAME) .setMatchedStatuses(singletonList(Status.FAILED)) .setFlaky(true); Map<String, Object> meta = new HashMap<>(); meta.put("categories", singletonList(category)); List<LaunchResults> launchResultsList = createSingleLaunchResults( meta, createTestResult("asd\n", Status.FAILED, true) ); CategoriesPlugin plugin = new CategoriesPlugin(); plugin.aggregate(configuration, launchResultsList, reportPath); Set<TestResult> results = launchResultsList.get(0).getAllResults(); List<Category> categories = results.toArray(new TestResult[]{})[0] .getExtraBlock("categories"); assertThat(categories).as("test categories") .extracting(Category::getName) .containsExactly(category.getName()); assertThat(reportPath.resolve("data").resolve(JSON_FILE_NAME)) .exists(); }
@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(); }
@Test public void shouldReadEnvironmentProperties() throws Exception { EnvironmentItem[] expected = new EnvironmentItem[]{ new EnvironmentItem().setName("allure.test.run.id").setValues(singletonList("some-id")), new EnvironmentItem().setName("allure.test.run.name").setValues(singletonList("some-name")), new EnvironmentItem().setName("allure.test.property").setValues(singletonList("1")) }; List<EnvironmentItem> environment = process( asList( "allure1/sample-testsuite.json", generateTestSuiteJsonName(), "allure1/environment.properties", "environment.properties" ) ); assertThat(environment) .as("Unexpected environment properties have been read from properties file") .hasSize(3) .usingFieldByFieldElementComparator() .containsExactlyInAnyOrder(expected); }
@Test public void shouldReadEnvironmentXml() throws Exception { EnvironmentItem[] expected = new EnvironmentItem[]{ new EnvironmentItem().setName("my.properties.browser").setValues(singletonList("Firefox")), new EnvironmentItem().setName("my.properties.url").setValues(singletonList("http://yandex.ru")), new EnvironmentItem().setName("allure.test.property").setValues(singletonList("3")), }; List<EnvironmentItem> environment = process( asList( "allure1/sample-testsuite.json", generateTestSuiteJsonName(), "allure1/environment.xml", "environment.xml" ) ); assertThat(environment) .as("Unexpected environment properties have been read from xml file") .hasSize(3) .usingFieldByFieldElementComparator() .containsExactlyInAnyOrder(expected); }
@Test public void extraneousSmallRequestsNotPropagatedAsZero() { List<Long> requests = new ArrayList<>(); final Flux<Integer> source = Flux.range(1, 100) .doOnRequest(requests::add); Flux<Integer> test = new FluxLimitRequest<>(source, 11); StepVerifier.create(test, 0) .thenRequest(8) .thenRequest(2) .thenRequest(2) .thenRequest(2) .thenRequest(2) .expectNextCount(11) .verifyComplete(); assertThat(requests) .as("limitRequest should not propagate extraneous requests as zeros") .containsExactly(8L, 2L, 1L); }
@Test void readAvailableVersions() throws IOException { this.server.expect(requestTo("https://spring.io/project_metadata/spring-boot")) .andRespond(withSuccess( new ClassPathResource("metadata/sagan/spring-boot.json"), MediaType.APPLICATION_JSON)); List<DefaultMetadataElement> versions = new SpringBootMetadataReader( this.objectMapper, this.restTemplate, this.metadata.getConfiguration().getEnv().getSpringBootMetadataUrl()) .getBootVersions(); assertThat(versions).as("spring boot versions should not be null").isNotNull(); AtomicBoolean defaultFound = new AtomicBoolean(false); versions.forEach((it) -> { assertThat(it.getId()).as("Id must be set").isNotNull(); assertThat(it.getName()).as("Name must be set").isNotNull(); if (it.isDefault()) { if (defaultFound.get()) { fail("One default version was already found " + it.getId()); } defaultFound.set(true); } }); this.server.verify(); }