org.junit.jupiter.api.RepeatedTest Java Examples

The following examples show how to use org.junit.jupiter.api.RepeatedTest. 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: CamelSinkAWSSQSITCase.java    From camel-kafka-connector with Apache License 2.0 6 votes vote down vote up
@DisabledIfSystemProperty(named = "aws-service.instance.type", matches = "remote")
@Test
@Timeout(value = 120)
@RepeatedTest(3)
public void testBasicSendReceiveUsingKafkaStyle() {
    try {
        Properties amazonProperties = awsService.getConnectionProperties();

        ConnectorPropertyFactory testProperties = CamelAWSSQSPropertyFactory
                .basic()
                .withName("CamelAwssqsSinkConnectorKafkaStyle")
                .withTopics(TestUtils.getDefaultTestTopic(this.getClass()))
                .withAmazonConfig(amazonProperties, CamelAWSSQSPropertyFactory.KAFKA_STYLE)
                .withQueueNameOrArn(queueName);

        runTest(testProperties);

    } catch (Exception e) {
        LOG.error("Amazon SQS test failed: {}", e.getMessage(), e);
        fail(e.getMessage());
    }
}
 
Example #2
Source File: ParallelExecutionSpringExtensionTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@RepeatedTest(10)
void runTestsInParallel() {
	Launcher launcher = LauncherFactory.create();
	SummaryGeneratingListener listener = new SummaryGeneratingListener();
	launcher.registerTestExecutionListeners(listener);

	LauncherDiscoveryRequest request = request()//
			.configurationParameter("junit.jupiter.execution.parallel.enabled", "true")//
			.configurationParameter("junit.jupiter.execution.parallel.config.dynamic.factor", "10")//
			.selectors(selectClass(TestCase.class))//
			.build();

	launcher.execute(request);

	assertEquals(NUM_TESTS, listener.getSummary().getTestsSucceededCount(),
			"number of tests executed successfully");
}
 
Example #3
Source File: BaseAuthRestTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
@RepeatedTest(100)
void testPost() {
    // This is a regression test in that we had a problem where the Vert.x request was not paused
    // before the authentication filters ran and the post message was thrown away by Vert.x because
    // RESTEasy hadn't registered its request handlers yet.
    given()
            .header("Authorization", "Basic am9objpqb2hu")
            .body("Bill")
            .contentType(ContentType.TEXT)
            .when()
            .post("/foo/mapped/rest")
            .then()
            .statusCode(200)
            .body(is("post success"));
}
 
Example #4
Source File: AbstractSubscriberAndProducerTest.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Tag("unstable")
@RepeatedTest(2)
public void asyncModeWithRacingTest() {
    List<Integer> integers = Flowable.range(0, 10000000)
                                     .toList()
                                     .blockingGet();

    TestSubscriberProducer<Integer> producer = Flowable.fromIterable(integers)
                                                       .hide()
                                                       .subscribeOn(Schedulers.io())
                                                       .observeOn(Schedulers.io(), true)
                                                       .subscribeWith(new TestSubscriberProducer<Integer>());

    TestCallStreamObserver<Integer> downstream = new TestCallStreamObserver<Integer>(executorService);
    producer.subscribe(downstream);

    racePauseResuming(downstream, 10000);

    Assertions.assertThat(downstream.awaitTerminal(1, TimeUnit.MINUTES)).isTrue();
    Assertions.assertThat(downstream.e).isNull();
    Assertions.assertThat(producer).hasFieldOrPropertyWithValue("sourceMode", 2);
    Assertions.assertThat(downstream.collected)
              .isEqualTo(integers);
    Assertions.assertThat(unhandledThrowable).isEmpty();
}
 
Example #5
Source File: AbstractSubscriberAndProducerTest.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@RepeatedTest(2)
public void syncModeWithRacingTest() throws InterruptedException {
    List<Integer> integers = Flowable.range(0, 10000000)
                                     .toList()
                                     .blockingGet();

    final CountDownLatch startedLatch = new CountDownLatch(1);
    final TestSubscriberProducer<Integer> producer = Flowable.fromIterable(integers)
                                                       .subscribeWith(new TestSubscriberProducer<Integer>());

    final TestCallStreamObserver<Integer> downstream =
        new TestCallStreamObserver<Integer>(executorService);
    executorService.execute(new Runnable() {
        @Override
        public void run() {
            producer.subscribe(downstream);
            startedLatch.countDown();
        }
    });

    startedLatch.await();

    racePauseResuming(downstream, 10000);

    Assertions.assertThat(downstream.awaitTerminal(1, TimeUnit.MINUTES)).isTrue();
    Assertions.assertThat(downstream.e).isNull();
    Assertions.assertThat(producer).hasFieldOrPropertyWithValue("sourceMode", 1);
    Assertions.assertThat(downstream.collected)
              .isEqualTo(integers);
    Assertions.assertThat(unhandledThrowable).isEmpty();
}
 
Example #6
Source File: ParallelExecutionSpringExtensionTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@RepeatedTest(10)
void runTestsInParallel() {
	Launcher launcher = LauncherFactory.create();
	SummaryGeneratingListener listener = new SummaryGeneratingListener();
	launcher.registerTestExecutionListeners(listener);

	LauncherDiscoveryRequest request = request()//
			.configurationParameter("junit.jupiter.execution.parallel.enabled", "true")//
			.configurationParameter("junit.jupiter.execution.parallel.config.dynamic.factor", "10")//
			.selectors(selectClass(TestCase.class))//
			.build();

	launcher.execute(request);

	assertEquals(NUM_TESTS, listener.getSummary().getTestsSucceededCount(),
			"number of tests executed successfully");
}
 
Example #7
Source File: CompositeMeterRegistryTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@RepeatedTest(100)
void meterRegistrationShouldWorkConcurrently() throws InterruptedException {
    this.composite.add(this.simple);

    String meterName = "test.counter";
    String tagName = "test.tag";

    int count = 10000;
    int tagCount = 100;
    ExecutorService executor = Executors.newFixedThreadPool(10);
    for (int i = 0; i < count; i++) {
        int tagValue = i % tagCount;
        executor.execute(() -> {
            Counter counter = Counter.builder(meterName).tag(tagName, String.valueOf(tagValue))
                    .register(this.composite);
            counter.increment();
        });
    }
    executor.shutdown();
    assertThat(executor.awaitTermination(1L, TimeUnit.SECONDS)).isTrue();
    for (int i = 0; i < tagCount; i++) {
        assertThat(this.composite.find(meterName).tag(tagName, String.valueOf(i)).counter().count())
                .isEqualTo(count / tagCount);
    }
}
 
Example #8
Source File: AbstractInventoryCountTests.java    From spring-cloud-stream-samples with Apache License 2.0 6 votes vote down vote up
@RepeatedTest(REPETITION_COUNT)
public void processAggregatedEventsForSingleKey() {
    Map<ProductKey, InventoryCountEvent> expectedCounts;
    expectedCounts = eventGenerator.generateRandomEvents(1, 5);

    Map<ProductKey, InventoryCountEvent> originalCount = consumeActualInventoryCountEvents(5);

    expectedCounts.forEach((key, value) ->
            assertThat(originalCount.get(key).getCount()).isEqualTo(value.getCount()));

    expectedCounts = eventGenerator.generateRandomEvents(1, 5);

    Map<ProductKey, InventoryCountEvent> actualCount = consumeActualInventoryCountEvents(5);

    expectedCounts.forEach((key, value) ->
            assertThat(actualCount.get(key).getCount()).isEqualTo(value.getCount()));
}
 
Example #9
Source File: DeterministicIdGenerationTest.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@RepeatedTest(10)
public void testDifferentDeterministicId() throws InterruptedException {

	Date date = new Date();

	SignatureParameters params = new SignatureParameters();
	params.setSigningCertificate(signingCert);
	params.bLevel().setSigningDate(date);
	String deterministicId1 = params.getDeterministicId();

	params = new SignatureParameters();
	params.bLevel().setSigningDate(date);
	String deterministicId2 = params.getDeterministicId();

	Thread.sleep(1); // 1 millisecond

	Date differentDate = new Date();

	params = new SignatureParameters();
	params.setSigningCertificate(signingCert);
	params.bLevel().setSigningDate(differentDate);
	String deterministicId3 = params.getDeterministicId();

	assertNotEquals(deterministicId1, deterministicId2);
	assertNotEquals(deterministicId1, deterministicId3);
}
 
Example #10
Source File: Bug661Test.java    From sarl with Apache License 2.0 6 votes vote down vote up
@RepeatedTest(5)
public void isSubtypeOf_01() throws Exception {
	ParseHelper<SarlScript> helper = getParseHelper();
	
	SarlScript mas0 = helper.parse(SNIPSET1);
	ResourceSet resourceSet = mas0.eResource().getResourceSet();
	SarlScript mas1 = helper.parse(SNIPSET1, resourceSet);

	assertSame(mas0.eResource().getResourceSet(), mas1.eResource().getResourceSet());
	
	JvmTypeReference reference0 = this.typeReferences.getTypeForName("boolean", mas0);
	
	StandardTypeReferenceOwner owner = new StandardTypeReferenceOwner(this.services, mas1);
	LightweightTypeReference reference1 = owner.newParameterizedTypeReference(this.typeReferences.findDeclaredType("boolean", mas1));
	
	assertTrue(reference1.isSubtypeOf(reference0.getType()));
}
 
Example #11
Source File: SessionQueriesTest.java    From Plan with GNU Lesser General Public License v3.0 6 votes vote down vote up
@RepeatedTest(3)
default void playersTableAndPlayerPageActivityIndexMatches() {
    prepareForSessionSave();
    List<Session> player1Sessions = RandomData.randomSessions(serverUUID(), worlds, playerUUID, player2UUID);
    List<Session> player2Sessions = RandomData.randomSessions(serverUUID(), worlds, player2UUID, playerUUID);
    player1Sessions.forEach(session -> execute(DataStoreQueries.storeSession(session)));
    player2Sessions.forEach(session -> execute(DataStoreQueries.storeSession(session)));

    long time = System.currentTimeMillis();
    long playtimeThreshold = RandomData.randomLong(TimeUnit.HOURS.toMillis(1L), TimeUnit.DAYS.toMillis(2L));

    PlayerContainer playerContainer = db().query(new PlayerContainerQuery(playerUUID));
    TablePlayer tablePlayer = db().query(new ServerTablePlayersQuery(serverUUID(), time, playtimeThreshold, 5))
            .stream().filter(player -> playerUUID.equals(player.getPlayerUUID())).findAny()
            .orElseThrow(AssertionError::new);

    SessionsMutator sessionsMutator = SessionsMutator.forContainer(playerContainer);
    long week = TimeAmount.WEEK.toMillis(1L);
    long weekAgo = time - week;
    long twoWeeksAgo = time - 2L * week;
    long threeWeeksAgo = time - 3L * week;
    SessionsMutator weekOne = sessionsMutator.filterSessionsBetween(weekAgo, time);
    SessionsMutator weekTwo = sessionsMutator.filterSessionsBetween(twoWeeksAgo, weekAgo);
    SessionsMutator weekThree = sessionsMutator.filterSessionsBetween(threeWeeksAgo, twoWeeksAgo);

    long playtime1 = weekOne.toActivePlaytime();
    long playtime2 = weekTwo.toActivePlaytime();
    long playtime3 = weekThree.toActivePlaytime();

    double expected = playerContainer.getActivityIndex(time, playtimeThreshold).getValue();
    double got = tablePlayer.getCurrentActivityIndex().orElseThrow(AssertionError::new).getValue();
    assertEquals(expected, got, 0.001,
            () -> "Activity Indexes between queries differed, expected: <" + expected + "> but was: <" + got + ">" +
                    ". Playtime for reference container: <w1:" + playtime1 + ", w2:" + playtime2 + ", w3:" + playtime3 + ">"
    );
}
 
Example #12
Source File: LegacyRandomDateTimesUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@RepeatedTest(100)
void givenNoRange_WhenGenTimestamp_ShouldGenerateRandomTimestamps() {
    Date random = LegacyRandomDateTimes.timestamp();

    assertThat(random)
            .isNotNull()
            .isBetween(MIN_DATE, MAX_DATE);
}
 
Example #13
Source File: VariableTest.java    From JsonTemplate with Apache License 2.0 5 votes vote down vote up
@RepeatedTest(TestUtils.REPEATED_COUNT)
void test_varsMapInMapParam() {
    Map<String, Object> values = new HashMap<>();
    values.put("min", 10);
    values.put("max", 20);
    JsonTemplate jsonTemplate = new JsonTemplate("{aField: @s(min=$min,max=$max)}")
            .withVars(values);
    DocumentContext document = parse(jsonTemplate);
    assertThat(document.read("$.aField", String.class).length(),
            is(both(greaterThanOrEqualTo(10)).and(lessThanOrEqualTo(20))));
}
 
Example #14
Source File: BaseAuthTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@RepeatedTest(100)
public void testPost() {
    // This is a regression test in that we had a problem where the Vert.x request was not paused
    // before the authentication filters ran and the post message was thrown away by Vert.x because
    // RESTEasy hadn't registered its request handlers yet.
    given()
            .header("Authorization", "Basic am9objpqb2hu")
            .body("Bill")
            .contentType(ContentType.TEXT)
            .when()
            .post("/foo/")
            .then()
            .statusCode(200)
            .body(is("hello Bill"));
}
 
Example #15
Source File: BearerTokenAuthorizationTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@RepeatedTest(20)
public void testOidcAndVertxHandler() {
    RestAssured.given().auth().oauth2(getAccessToken("alice"))
            .when().body("Hello World").post("/vertx")
            .then()
            .statusCode(200)
            .body(equalTo("Hello World"));
}
 
Example #16
Source File: RandomDateTimesUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@RepeatedTest(100)
void givenARange_WhenGenTimestamp_ShouldBeInRange() {
    Instant hundredYearsAgo = Instant.now().minus(Duration.ofDays(100 * 365));
    Instant tenDaysAgo = Instant.now().minus(Duration.ofDays(10));

    Instant random = RandomDateTimes.between(hundredYearsAgo, tenDaysAgo);
    assertThat(random).isBetween(hundredYearsAgo, tenDaysAgo);
}
 
Example #17
Source File: LegacyRandomDateTimesUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@RepeatedTest(100)
void givenARange_WhenGenTimestamp_ShouldBeInRange() {
    long aDay = TimeUnit.DAYS.toMillis(1);
    long now = new Date().getTime();

    Date hundredYearsAgo = new Date(now - aDay * 365 * 100);
    Date tenDaysAgo = new Date(now - aDay * 10);

    Date random = LegacyRandomDateTimes.between(hundredYearsAgo, tenDaysAgo);
    assertThat(random).isBetween(hundredYearsAgo, tenDaysAgo);
}
 
Example #18
Source File: Examples.java    From vertx-junit5 with Apache License 2.0 5 votes vote down vote up
@RepeatedTest(3)
void http_server_check_response(Vertx vertx, VertxTestContext testContext) {
  HttpClient client = vertx.createHttpClient();
  client.get(8080, "localhost", "/")
    .compose(HttpClientResponse::body)
    .onComplete(testContext.succeeding(buffer -> testContext.verify(() -> {
      assertThat(buffer.toString()).isEqualTo("Plop");
      testContext.completeNow();
    })));
}
 
Example #19
Source File: ChannelTest.java    From rabbitmq-mock with Apache License 2.0 5 votes vote down vote up
@RepeatedTest(31)
void basicConsume_concurrent_queue_access() throws IOException, TimeoutException, InterruptedException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {
            String queueName = channel.queueDeclare().getQueue();

            BlockingQueue<String> messages = new LinkedBlockingQueue<>();
            channel.basicConsume("", new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag,
                                           Envelope envelope,
                                           AMQP.BasicProperties properties,
                                           byte[] body) {
                    messages.offer(new String(body));
                }
            });

            int totalMessages = 101;
            for (int i = 1; i <= totalMessages; i++) {
                channel.basicPublish("", queueName, null, "test message".getBytes());
            }
            for (int i = 1; i <= totalMessages; i++) {
                assertThat(messages.poll(200L, TimeUnit.MILLISECONDS)).isNotNull();
            }
        }
    }
}
 
Example #20
Source File: PersonValidatorUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * Repeat the test ten times, that way we have a good shot at
 * running all of the data through at least once.
 * 
 * @param person
 *          A valid Person object to validate.
 */
@RepeatedTest(value = 10)
@DisplayName("All first names are valid")
public void validateFirstName(Person person) {
    try {
        assertTrue(PersonValidator.validateFirstName(person));
    } catch (PersonValidator.ValidationException e) {
        fail("Exception not expected: " + e.getLocalizedMessage());
    }
}
 
Example #21
Source File: ItemTests.java    From jpms-module-names with MIT License 5 votes vote down vote up
@RepeatedTest(20)
void valueCountUnderflowThrows(RepetitionInfo info) {
  var i = info.getCurrentRepetition();
  var line = "-" + ",-".repeat(i - 1);
  if (i < 9) {
    var e = assertThrows(IllegalArgumentException.class, () -> new Item(line));
    assertEquals("Expected at least 9 values, only got " + i + " in: " + line, e.getMessage());
  } else {
    assertDoesNotThrow(() -> new Item(line));
  }
}
 
Example #22
Source File: StreamObserverAndPublisherTest.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@RepeatedTest(2)
public void shouldSupportOnlySingleSubscriberTest() throws InterruptedException {
    for (int i = 0; i < 1000; i++) {
        final TestSubscriber<Integer> downstream1 = new TestSubscriber<Integer>(0);
        final TestSubscriber<Integer> downstream2 = new TestSubscriber<Integer>(0);
        final TestStreamObserverAndPublisher<Integer> processor = new TestStreamObserverAndPublisher<Integer>(null);
        final CountDownLatch latch = new CountDownLatch(1);
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                latch.countDown();
                processor.subscribe(downstream1);
                processor.onCompleted();
            }
        });
        latch.await();
        processor.subscribe(downstream2);
        processor.onCompleted();

        downstream1.awaitTerminalEvent();
        downstream2.awaitTerminalEvent();

        if (downstream1.errorCount() > 0) {
            downstream1.assertError(IllegalStateException.class)
                       .assertErrorMessage(
                           "TestStreamObserverAndPublisher allows only a single Subscriber");
        } else {
            downstream2.assertError(IllegalStateException.class)
                       .assertErrorMessage(
                           "TestStreamObserverAndPublisher allows only a single Subscriber");
        }
    }
}
 
Example #23
Source File: RedisWebFilterFactoriesLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@RepeatedTest(25)
public void whenCallRedisGetThroughGateway_thenOKStatusOrIsReceived() {
    String url = "http://localhost:" + port + "/redis/get";

    ResponseEntity<String> r = restTemplate.getForEntity(url, String.class);
    // assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);

    LOGGER.info("Received: status->{}, reason->{}, remaining->{}", 
      r.getStatusCodeValue(), r.getStatusCode().getReasonPhrase(), 
      r.getHeaders().get("X-RateLimit-Remaining"));
}
 
Example #24
Source File: XAdESExtensionWithContentTimestampTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@RepeatedTest(10)
public void test() {
	DSSDocument documentToSign = new FileDocument(new File("src/test/resources/sample.xml"));
	
	Date oneDayBefore = getDateWithHoursDifference(-24);
	
	XAdESSignatureParameters signatureParameters = new XAdESSignatureParameters();
	signatureParameters.bLevel().setSigningDate(oneDayBefore);
	signatureParameters.setSigningCertificate(getSigningCert());
	signatureParameters.setCertificateChain(getCertificateChain());
	signatureParameters.setSignaturePackaging(SignaturePackaging.ENVELOPING);
	signatureParameters.setSignatureLevel(SignatureLevel.XAdES_BASELINE_T);
	
	CertificateVerifier certificateVerifier = getCompleteCertificateVerifier();
	certificateVerifier.setAlertOnNoRevocationAfterBestSignatureTime(new ExceptionOnStatusAlert());
	XAdESService service = new XAdESService(certificateVerifier);
       service.setTspSource(getGoodTsaByTime(oneDayBefore));
	
	TimestampToken contentTimestamp = service.getContentTimestamp(documentToSign, signatureParameters);

	signatureParameters.setContentTimestamps(Arrays.asList(contentTimestamp));

	signatureParameters.bLevel().setSigningDate(getDateWithHoursDifference(24));
	service.setTspSource(getAlternateGoodTsa());

	ToBeSigned dataToSign = service.getDataToSign(documentToSign, signatureParameters);
	SignatureValue signatureValue = getToken().sign(dataToSign, signatureParameters.getDigestAlgorithm(),
			signatureParameters.getMaskGenerationFunction(), getPrivateKeyEntry());
	DSSDocument signedDocument = service.signDocument(documentToSign, signatureParameters, signatureValue);
	
	signatureParameters.setSignatureLevel(SignatureLevel.XAdES_BASELINE_LT);
	Exception exception = assertThrows(AlertException.class, () -> service.extendDocument(signedDocument, signatureParameters));
	assertTrue(exception.getMessage().contains("Fresh revocation data is missing for one or more certificate(s)."));
	
}
 
Example #25
Source File: AbstractSubscriberAndProducerTest.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Tag("unstable")
@RepeatedTest(2)
public void asyncModeWithRacingAndCancellationTest() throws InterruptedException {
    final CountDownLatch cancellationLatch = new CountDownLatch(1);

    List<Integer> integers = Flowable.range(0, 10000000)
                                     .toList()
                                     .blockingGet();

    TestSubscriberProducer<Integer> producer = Flowable.fromIterable(integers)
                                                       .hide()
                                                       .doOnCancel(new Action() {
                                                           @Override
                                                           public void run() {
                                                               cancellationLatch.countDown();
                                                           }
                                                       })
                                                       .subscribeOn(Schedulers.io())
                                                       .observeOn(Schedulers.io(), true)
                                                       .subscribeWith(new TestSubscriberProducer<Integer>());

    TestCallStreamObserver<Integer> downstream = new TestCallStreamObserver<Integer>(
        executorService);
    producer.subscribe(downstream);

    racePauseResuming(downstream, 100);

    producer.cancel();

    Assertions.assertThat(cancellationLatch.await(1, TimeUnit.MINUTES)).isTrue();

    Assertions.assertThat(downstream.done.getCount()).isEqualTo(1);
    Assertions.assertThat(downstream.e).isNull();
    Assertions.assertThat(producer).hasFieldOrPropertyWithValue("sourceMode", 2);
    Assertions.assertThat(downstream.collected)
              .isSubsetOf(integers);
    Assertions.assertThat(unhandledThrowable).isEmpty();
}
 
Example #26
Source File: CertificateSourceMultiThreadTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@RepeatedTest(5)
public void testMultiThreads() throws IOException {

	KeyStoreCertificateSource kscs = new KeyStoreCertificateSource(new File("src/test/resources/extract-tls.p12"), "PKCS12", "ks-password");
	List<CertificateToken> certificates = kscs.getCertificates();

	CommonCertificateSource sharedCertSource = new CommonCertificateSource();

	ExecutorService executor = Executors.newFixedThreadPool(20);

	List<Future<Integer>> futures = new ArrayList<>();

	for (int i = 0; i < 100; i++) {
		futures.add(executor.submit(new TestConcurrent(sharedCertSource, certificates)));

		// not shared
		futures.add(executor.submit(new TestConcurrent(new CommonCertificateSource(), certificates)));
	}

	for (Future<Integer> future : futures) {
		try {
			assertEquals(2438, future.get().intValue());
		} catch (Exception e) {
			fail(e.getMessage());
		}
	}

	executor.shutdown();

}
 
Example #27
Source File: UserServiceTests.java    From Building-Web-Apps-with-Spring-5-and-Angular with MIT License 5 votes vote down vote up
@Test
@RepeatedTest(5)
@DisplayName("Throws exception if user with given email does not exist")
public void Should_throwException_When_UserDoesNotExist() {
	String email = "[email protected]";
	Mockito.when(this.userDAO.findByEmail(email)).thenReturn(new ArrayList<User>());
	assertThatThrownBy(() -> this.userService.doesUserExist(email)).isInstanceOf(UserNotFoundException.class)
			.hasMessage("User does not exist in the database.");
}
 
Example #28
Source File: JUnit5HttpsApiTest.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@HttpApiName("${class}_${method}")
@RepeatedTest(5) // just ensure it is reentrant
void getProxy() throws Exception {
    final Response response = get();
    assertEquals(HttpURLConnection.HTTP_OK, response.status());
    assertEquals(new String(response.payload()), "worked as expected");
    assertEquals("text/plain", response.headers().get("content-type"));
    assertEquals("true", response.headers().get("mocked"));
    assertEquals("true", response.headers().get("X-Talend-Proxy-JUnit"));
}
 
Example #29
Source File: BlowfishTest.java    From drftpd with GNU General Public License v2.0 5 votes vote down vote up
@RepeatedTest(10000)
public void testECB() {
    BlowfishManager ecb = new BlowfishManager("drftpd", "ECB");
    String text = "You need to specify a Ident@IP to add " + Math.random();
    String encrypt = ecb.encrypt(text);
    String decrypt = ecb.decrypt(encrypt);
    assertEquals(decrypt, text);
}
 
Example #30
Source File: RandomDatesUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@RepeatedTest(100)
void givenARange_WhenGenDate_ShouldBeInRange() {
    LocalDate start = LocalDate.of(1989, Month.OCTOBER, 14);
    LocalDate end = LocalDate.now();

    LocalDate random = RandomDates.between(start, end);
    assertThat(random).isAfter(start).isBefore(end);
}