org.awaitility.Awaitility Java Examples

The following examples show how to use org.awaitility.Awaitility. 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: ReadTimeoutTestCase.java    From quarkus with Apache License 2.0 7 votes vote down vote up
@Test
public void testReadSuccess() throws Exception {
    PostEndpoint.invoked = false;

    //make sure incomplete writes do not block threads
    //and that incoplete data is not delivered to the endpoint
    Socket socket = new Socket(url.getHost(), url.getPort());
    socket.getOutputStream().write(
            "POST /post HTTP/1.1\r\nHost: localhost\r\nContent-length:9\r\n\r\n12345".getBytes(StandardCharsets.UTF_8));
    socket.getOutputStream().flush();
    Thread.sleep(1);
    socket.getOutputStream().write(
            "6789".getBytes(StandardCharsets.UTF_8));
    socket.getOutputStream().flush();
    Awaitility.await().atMost(20, TimeUnit.SECONDS).pollInterval(50, TimeUnit.MILLISECONDS)
            .untilAsserted(new ThrowingRunnable() {
                @Override
                public void run() throws Throwable {
                    //make sure the read timed out and the endpoint was invoked
                    Assertions.assertTrue(PostEndpoint.invoked);
                }
            });
    socket.close();
}
 
Example #2
Source File: AbstractBaseITests.java    From java-spring-web with Apache License 2.0 7 votes vote down vote up
@Test
public void testAsyncDeferred() throws Exception {
    {
        getRestTemplate().getForEntity("/asyncDeferred", String.class);
        Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(1));
    }
    List<MockSpan> mockSpans = TracingBeansConfiguration.mockTracer.finishedSpans();
    Assert.assertEquals(1, mockSpans.size());
    assertOnErrors(mockSpans);

    MockSpan span = mockSpans.get(0);
    Assert.assertEquals("test", span.operationName());

    Assert.assertEquals(5, span.tags().size());
    Assert.assertEquals(Tags.SPAN_KIND_SERVER, span.tags().get(Tags.SPAN_KIND.getKey()));
    Assert.assertEquals("GET", span.tags().get(Tags.HTTP_METHOD.getKey()));
    Assert.assertEquals(getUrl("/asyncDeferred"), span.tags().get(Tags.HTTP_URL.getKey()));
    Assert.assertEquals(202, span.tags().get(Tags.HTTP_STATUS.getKey()));
    Assert.assertNotNull(span.tags().get(Tags.COMPONENT.getKey()));

    assertLogEvents(span.logEntries(), Arrays.asList("preHandle", "afterConcurrentHandlingStarted",
            "preHandle", "afterCompletion"));
}
 
Example #3
Source File: RedissonSubscribeReactiveTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribe() {
    RedissonConnectionFactory factory = new RedissonConnectionFactory(redisson);
    ReactiveRedisConnection connection = factory.getReactiveConnection();
    Mono<ReactiveSubscription> s = connection.pubSubCommands().createSubscription();
    AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
    ReactiveSubscription ss = s.block();

    ss.subscribe(ByteBuffer.wrap("test".getBytes())).block();
    ss.receive().doOnEach(message -> {
        msg.set(message.get().getMessage().array());
    }).subscribe();
    
    connection.pubSubCommands().publish(ByteBuffer.wrap("test".getBytes()), ByteBuffer.wrap("msg".getBytes())).block();

    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> Arrays.equals("msg".getBytes(), msg.get()));
    
    ss.unsubscribe();
    
    connection.pubSubCommands().publish(ByteBuffer.wrap("test".getBytes()), ByteBuffer.wrap("msg".getBytes())).block();
}
 
Example #4
Source File: VFSTransportTestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.ALL })
@Test(groups = { "wso2.esb" }, description = "Sending a file through VFS Transport : "
        + "transport.vfs.FileURI = Linux Path, " + "transport.vfs.ContentType = text/xml, "
        + "transport.vfs.FileNamePattern = - *\\.xml")
public void testVFSProxyFileURI_LinuxPath_ContentType_XML() throws Exception {

    //Related proxy : VFSProxy1
    File sourceFile = new File(pathToVfsDir + File.separator + "test.xml");
    File targetFile = new File(proxyVFSRoots.get("VFSProxy1") + File.separator + "in" + File.separator + "test.xml");
    File outfile = new File(proxyVFSRoots.get("VFSProxy1") + File.separator + "out" + File.separator + "out.xml");

    FileUtils.copyFile(sourceFile, targetFile);
    Awaitility.await().pollInterval(50, TimeUnit.MILLISECONDS).atMost(60, TimeUnit.SECONDS).until(isFileExist(outfile));
    Assert.assertTrue(outfile.exists());
    Assert.assertTrue(doesFileContain(outfile, "WSO2 Company"));
}
 
Example #5
Source File: ESBIntegrationTest.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private String retrieveArtifactUsingManagementApi(String artifactType) throws IOException {

        if (!isManagementApiAvailable) {
            Awaitility.await().pollInterval(50, TimeUnit.MILLISECONDS).atMost(DEFAULT_TIMEOUT, TimeUnit.SECONDS).
                    until(isManagementApiAvailable());
        }

        SimpleHttpClient client = new SimpleHttpClient();
        Map<String, String> headers = new HashMap<>();
        headers.put("Accept", "application/json");

        String endpoint = "https://" + hostName + ":" + (DEFAULT_INTERNAL_API_HTTPS_PORT + portOffset) + "/management/"
                + artifactType;

        HttpResponse response = client.doGet(endpoint, headers);
        return client.getResponsePayload(response);
    }
 
Example #6
Source File: MSMPCronForwarderCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@BeforeClass(alwaysRun = true)
protected void init() throws Exception {
    // START THE ESB
    super.init();
    // START THE SERVER
    tomcatServerManager =
            new TomcatServerManager(CustomerConfig.class.getName(), TomcatServerType.jaxrs.name(), 8080);

    tomcatServerManager.startServer();  // staring tomcat server instance
    Awaitility.await().pollInterval(50, TimeUnit.MILLISECONDS).atMost(60, TimeUnit.SECONDS)
              .until(isServerStarted());
    logAdmin = new LoggingAdminClient(contextUrls.getBackEndUrl(), getSessionCookie());
    serverConfigurationManager =
            new ServerConfigurationManager(new AutomationContext("ESB", TestUserMode.SUPER_TENANT_ADMIN));
    String carbonHome = System.getProperty(ServerConstants.CARBON_HOME);
    File log4jProperties = new File(carbonHome + File.separator + "conf" +
            File.separator + "log4j2.properties");
    applyProperty(log4jProperties, "logger.org-apache-synapse.level", "DEBUG");
    serverConfigurationManager.restartGracefully();
    super.init();
}
 
Example #7
Source File: SleuthSpanCreatorAspectMonoTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddErrorTagWhenExceptionOccurredInNewSpan() {
	try {
		Mono<String> mono = this.testBean.testMethod12("test");

		then(this.spans).isEmpty();

		mono.block();
	}
	catch (RuntimeException ignored) {
	}

	Awaitility.await().untilAsserted(() -> {
		then(this.spans).hasSize(1);
		then(this.spans.get(0).name()).isEqualTo("test-method12");
		then(this.spans.get(0).tags()).containsEntry("testTag12", "test");
		then(this.spans.get(0).error()).hasMessageContaining("test exception 12");
		then(this.spans.get(0).finishTimestamp()).isNotZero();
		then(this.tracer.currentSpan()).isNull();
	});
}
 
Example #8
Source File: Monitor.java    From elasticsearch-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Wait until the cluster has fully started (ie. all nodes have joined).
 * @param clusterName the ES cluster name
 * @param nodesCount the number of nodes in the cluster
 * @param timeout how many seconds to wait
 */
public void waitToStartCluster(final String clusterName, int nodesCount, int timeout)
{
    log.debug(String.format(
            "Waiting up to %ds for the Elasticsearch cluster to start ...",
            timeout));
    Awaitility.await()
            .atMost(timeout, TimeUnit.SECONDS)
            .pollDelay(1, TimeUnit.SECONDS)
            .pollInterval(1,  TimeUnit.SECONDS)
            .until(new Callable<Boolean>()
                    {
                        @Override
                        public Boolean call() throws Exception
                        {
                            return isClusterRunning(clusterName, nodesCount, client);
                        }
                    }
            );
    log.info("The Elasticsearch cluster has started");
}
 
Example #9
Source File: AsyncReferenceTest.java    From weld-vertx with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncReferenceCompletionStage(TestContext context) throws InterruptedException {
    BlockingFoo.reset();
    Async async = context.async(2);

    Hello hello = weld.select(Hello.class).get();
    hello.hello().thenAccept((m) -> {
        context.assertEquals("Foo", m);
        async.complete();
    });
    BlockingFoo.complete("Foo");
    Awaitility.await().atMost(Timeouts.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS).until(() -> hello.foo.isDone());
    hello.hello().thenAccept((m) -> {
        context.assertEquals("Foo", m);
        async.complete();
    });
}
 
Example #10
Source File: RedissonSubscribeTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnSubscribe() {
    RedissonConnection connection = new RedissonConnection(redisson);
    AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
    connection.subscribe(new MessageListener() {
        @Override
        public void onMessage(Message message, byte[] pattern) {
            msg.set(message.getBody());
        }
    }, "test".getBytes());
    
    connection.publish("test".getBytes(), "msg".getBytes());
    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> Arrays.equals("msg".getBytes(), msg.get()));
    
    connection.getSubscription().unsubscribe();
    
    
}
 
Example #11
Source File: WriteBehindCacheWriterTest.java    From caffeine with Apache License 2.0 6 votes vote down vote up
@Test
public void givenCacheUpdateOnMultipleKeys_writeBehindIsCalled() {
  AtomicBoolean writerCalled = new AtomicBoolean(false);
  AtomicInteger numberOfEntries = new AtomicInteger(0);

  // Given this cache...
  Cache<Long, ZonedDateTime> cache = Caffeine.newBuilder()
      .writer(new WriteBehindCacheWriter.Builder<Long, ZonedDateTime>()
          .bufferTime(1, TimeUnit.SECONDS)
          .coalesce(BinaryOperator.maxBy(ZonedDateTime::compareTo))
          .writeAction(entries -> {
            numberOfEntries.set(entries.size());
            writerCalled.set(true);
          }).build())
      .build();

  // When these cache updates happen ...
  cache.put(1L, ZonedDateTime.now());
  cache.put(2L, ZonedDateTime.now());
  cache.put(3L, ZonedDateTime.now());

  // Then the write behind action gets 3 entries to write
  Awaitility.await().untilTrue(writerCalled);
  Assert.assertEquals(3, numberOfEntries.intValue());
}
 
Example #12
Source File: TaskServiceTest.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Use-Case: manual execution, db check, repair, import
 * 
 * @throws Exception
 */
@Ignore("TODO fix test case")
@Test
public void triggerManual_HelloWorld() throws Exception{
	taskDescriptor = taskService.createTaskDescriptor(rwcLogContext);
	taskDescriptor.setOwner(owner);
	taskDescriptor.setReferenceId("manual_helloWorld");
	taskDescriptor.setRunContextParameter("testKey", "testValue");
	taskService.setActive(taskDescriptor, true);
	
	Optional<ITask> findExecutions = taskService.findLatestExecution(taskDescriptor);
	assertTrue(findExecutions.isPresent());
	
	ITask task =
		taskService.trigger(taskDescriptor, progressMonitor, TaskTriggerType.MANUAL, null);
	
	Awaitility.await().atMost(2, TimeUnit.SECONDS).until(taskDone(task));
	assertEquals(TaskState.COMPLETED, task.getState());
	
	findExecutions = taskService.findLatestExecution(taskDescriptor);
	assertTrue(findExecutions.isPresent());
	assertEquals(TaskState.COMPLETED, findExecutions.get().getState());
	assertTrue(findExecutions.get().getResult().containsKey("runnableExecDuration"));
}
 
Example #13
Source File: WaitUtils.java    From jaeger-analytics-java with Apache License 2.0 6 votes vote down vote up
public static void untilQueryHasTag(QueryServiceBlockingStub queryService, String service, String tagKey, String tagValue) {
  TraceQueryParameters queryParameters = TraceQueryParameters.newBuilder().setServiceName(service).build();

  Awaitility.await().atMost(10, TimeUnit.SECONDS).until(() -> {
    Iterator<SpansResponseChunk> traces = queryService
        .findTraces(FindTracesRequest.newBuilder().setQuery(queryParameters).build());

    while (traces.hasNext()) {
      SpansResponseChunk trace = traces.next();
      for (Span span: trace.getSpansList()) {
        for (KeyValue tag: span.getTagsList()) {
          if (tagKey.equals(tag.getKey()) && tagValue.equals(tag.getVStr())) {
            return true;
          }
        }
      }
    }
    return false;
  });
}
 
Example #14
Source File: BpelVersioningTest.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@Test(groups = {"wso2.bps", "wso2.bps.deployment"}, description = "Tests uploading Bpel Service with In memory", singleThreaded = true)
public void getVersion() throws RemoteException, XMLStreamException, InterruptedException,
        ProcessManagementException {

    Awaitility.await()
            .pollInterval(50, TimeUnit.MILLISECONDS)
            .atMost(MAX_TIME, TimeUnit.SECONDS)
            .until(isInforListAvailable("HelloWorld2"));
    List<String> processBefore = bpelProcessManagementClient.getProcessInfoList("HelloWorld2");
    activeStatus = new LinkedList<String>();
    for (String processid : processBefore) {
        if (bpelProcessManagementClient.getStatus(processid).equals("ACTIVE")) {
            activeStatus.add(processid);
        }
    }
    sendRequest();
}
 
Example #15
Source File: RabbitMQTerminationSubscriberTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void givenTwoTerminationSubscribersWhenAnEventIsSentItShouldBeReceivedByBoth() {
    TerminationSubscriber subscriber1 = subscriber();
    TerminationSubscriber subscriber2 = subscriber();

    Flux<Event> firstListener = Flux.from(subscriber1.listenEvents());
    Flux<Event> secondListener = Flux.from(subscriber2.listenEvents());

    sendEvents(subscriber1, COMPLETED_EVENT);

    List<Event> receivedEventsFirst = new ArrayList<>();
    firstListener.subscribe(receivedEventsFirst::add);
    List<Event> receivedEventsSecond = new ArrayList<>();
    secondListener.subscribe(receivedEventsSecond::add);

    Awaitility.await().atMost(ONE_MINUTE).until(() -> receivedEventsFirst.size() == 1 && receivedEventsSecond.size() == 1);

    assertThat(receivedEventsFirst).containsExactly(COMPLETED_EVENT);
    assertThat(receivedEventsSecond).containsExactly(COMPLETED_EVENT);
}
 
Example #16
Source File: MockSMTPServerTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void serverShouldActLikeDefaultAfterGettingEnoughMatches() {
    int numberOfAnswer = 4;
    MockSMTPBehavior behavior = new MockSMTPBehavior(
        MAIL_FROM,
        Condition.MATCH_ALL,
        new Response(SERVICE_NOT_AVAILABLE_421, "mock response"),
        MockSMTPBehavior.NumberOfAnswersPolicy.times(numberOfAnswer));

    behaviorRepository.setBehaviors(behavior);

    sendMessageIgnoreError(mail1);
    sendMessageIgnoreError(mail1);
    sendMessageIgnoreError(mail1);
    sendMessageIgnoreError(mail1);

    sendMessageIgnoreError(mail1);
    Awaitility.await().atMost(Duration.TEN_SECONDS)
        .untilAsserted(() -> assertThat(mailRepository.list()).hasSize(1));
}
 
Example #17
Source File: GcsSpringIntegrationTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void testFilePropagatedToLocalDirectory() {
	BlobId blobId = BlobId.of(this.cloudInputBucket, TEST_FILE_NAME);
	BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
	this.storage.create(blobInfo, "Hello World!".getBytes(StandardCharsets.UTF_8));

	Awaitility.await().atMost(15, TimeUnit.SECONDS)
			.untilAsserted(() -> {
				Path outputFile = Paths.get(this.outputFolder + "/" + TEST_FILE_NAME);
				assertThat(Files.exists(outputFile)).isTrue();
				assertThat(Files.isRegularFile(outputFile)).isTrue();

				String firstLine = Files.lines(outputFile).findFirst().get();
				assertThat(firstLine).isEqualTo("Hello World!");

				List<String> blobNamesInOutputBucket = new ArrayList<>();
				this.storage.list(this.cloudOutputBucket).iterateAll()
						.forEach((b) -> blobNamesInOutputBucket.add(b.getName()));

				assertThat(blobNamesInOutputBucket).contains(TEST_FILE_NAME);
			});
}
 
Example #18
Source File: VFSTransportTestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
@Test(groups = { "wso2.esb" }, description = "Sending a file through VFS Transport : "
        + "transport.vfs.FileURI = /home/someuser/somedir " + "transport.vfs.ContentType = text/plain, "
        + "transport.vfs.FileNamePattern = - *\\.txt, " + "transport.PollInterval=1,"
        + " transport.vfs.ReplyFileName = out.txt ")
public void testVFSProxyReplyFileName_Normal() throws Exception {

    //Related proxy : VFSProxy9
    File sourceFile = new File(pathToVfsDir + File.separator + "test.txt");
    File targetFile = new File(proxyVFSRoots.get("VFSProxy9") + File.separator + "in" + File.separator + "test.txt");
    File outfile = new File(proxyVFSRoots.get("VFSProxy9") + File.separator + "out" + File.separator + "out.txt");

    FileUtils.copyFile(sourceFile, targetFile);

    Awaitility.await().pollInterval(50, TimeUnit.MILLISECONDS).atMost(60, TimeUnit.SECONDS)
            .until(isFileExist(outfile));
    Assert.assertTrue(outfile.exists());
    Assert.assertTrue(doesFileContain(outfile, "[email protected]"));
}
 
Example #19
Source File: VFSTransportTestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
@Test(groups = { "wso2.esb" }, description = "Sending a file through VFS Transport : "
        + "transport.vfs.FileURI = /home/someuser/somedir " + "transport.vfs.ContentType = text/plain, "
        + "transport.vfs.FileNamePattern = - *\\.txt, " + "transport.PollInterval=1, "
        + "transport.vfs.ReplyFileName = not specified ")
public void testVFSProxyReplyFileName_NotSpecified() throws Exception {

    //Related proxy : VFSProxy11
    File sourceFile = new File(pathToVfsDir + File.separator + "test.txt");
    File targetFile = new File(proxyVFSRoots.get("VFSProxy11") + File.separator + "in" + File.separator + "test" +
            ".txt");
    File outfile = new File(proxyVFSRoots.get("VFSProxy11") + File.separator + "out" + File.separator + "response.xml");

    FileUtils.copyFile(sourceFile, targetFile);
    Awaitility.await().pollInterval(50, TimeUnit.MILLISECONDS).atMost(60, TimeUnit.SECONDS)
            .until(isFileExist(outfile));
    Assert.assertTrue(outfile.exists());
    Assert.assertTrue(doesFileContain(outfile, "[email protected]"));
}
 
Example #20
Source File: InterruptTest.java    From AILibs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Two timed computations are nested. The outer is canceled significantly (1s) earlier than the inner.
 *
 * @throws ExecutionException
 * @throws InterruptedException
 */
@Test
public void testNestedInterruptDuringExecutionWithOuterSignifiantlyEarlier() throws ExecutionException, InterruptedException {

	for (int i = 0; i < NUMBER_ITERATIONS_SHIFTED; i++) {

		/* test that InterruptException is thrown and that no interrupts are open */
		try {
			TimedComputation.compute(() -> TimedComputation.compute(new BusyBeaver(Long.MAX_VALUE), 2000, "inner interrupt"), 1000, "outer interrupt");
		} catch (AlgorithmTimeoutedException e) {

			/* this is expected behavior */
			assertTrue(GlobalTimer.getInstance().getActiveTasks().isEmpty());
			assertFalse(Interrupter.get().hasCurrentThreadOpenInterrupts());
			Awaitility.await().atLeast(2, TimeUnit.SECONDS);
			assertTrue(GlobalTimer.getInstance().getActiveTasks().isEmpty());
			assertFalse(Interrupter.get().hasCurrentThreadOpenInterrupts());
			continue;
		}
		fail("No exception was thrown, but an AlgorithmTimedoutedException should have been thrown!");
	}
}
 
Example #21
Source File: ResponsiveTest.java    From cloudinary_android with MIT License 6 votes vote down vote up
private void onlyWidthTest(String gravity, String cropMode, int stepSize, int minDimension, int maxDimension, int viewWidth, int viewHeight, final String expectedUrlSuffix) {
    final StatefulCallback callback = new StatefulCallback();

    new ResponsiveUrl(cloudinary, true, false, cropMode, gravity)
            .stepSize(stepSize)
            .minDimension(minDimension)
            .maxDimension(maxDimension)
            .generate("publicId", getImageView(viewWidth, viewHeight), callback);

    Awaitility.await().atMost(Duration.ONE_SECOND).until(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            return callback.url.endsWith(expectedUrlSuffix);
        }
    });
}
 
Example #22
Source File: VFSTransportTestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
@Test(groups = { "wso2.esb" }, description = "Sending a file through VFS Transport :"
        + " transport.vfs.FileURI = Linux Path, " + "transport.vfs.ContentType = text/xml, "
        + "transport.vfs.FileNamePattern = - *\\.xml " + "transport.vfs.ActionAfterFailure=NotSpecified")
public void testVFSProxyActionAfterFailure_NotSpecified() throws Exception {

    String proxyName = "VFSProxy14";
    File sourceFile = new File(pathToVfsDir + File.separator + "fail.xml");
    File targetFile = new File(proxyVFSRoots.get(proxyName) + File.separator + "in" + File.separator + "fail.xml");
    File outfile = new File(proxyVFSRoots.get(proxyName) + File.separator + "out" + File.separator + "out.xml");
    File originalFile = new File(proxyVFSRoots.get(proxyName) + File.separator + "failure" + File.separator + "fail.xml");

    FileUtils.copyFile(sourceFile, targetFile);
    Awaitility.await().pollInterval(50, TimeUnit.MILLISECONDS).atMost(60, TimeUnit.SECONDS)
            .until(isFileNotExist(targetFile));
    Awaitility.await().pollInterval(50, TimeUnit.MILLISECONDS).atMost(60, TimeUnit.SECONDS)
            .until(isFileNotExist(outfile));
    Assert.assertFalse(outfile.exists());
    Assert.assertFalse(originalFile.exists());
    Assert.assertFalse(
            new File(proxyVFSRoots.get(proxyName) + File.separator + "in" + File.separator + "fail.xml.lock").exists(),
            "lock file exists even after moving the failed file");
}
 
Example #23
Source File: RedissonSubscribeReactiveTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testTemplate() {
    RedissonConnectionFactory factory = new RedissonConnectionFactory(redisson);
    AtomicLong counter = new AtomicLong();

    ReactiveStringRedisTemplate template = new ReactiveStringRedisTemplate(factory);
    template.listenTo(ChannelTopic.of("test")).flatMap(message -> {
        counter.incrementAndGet();
        return Mono.empty();
    }).subscribe();

    template.listenTo(ChannelTopic.of("test2")).flatMap(message -> {
        counter.incrementAndGet();
        return Mono.empty();
    }).subscribe();

    ReactiveRedisConnection connection = factory.getReactiveConnection();
    connection.pubSubCommands().publish(ByteBuffer.wrap("test".getBytes()), ByteBuffer.wrap("msg".getBytes())).block();

    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> counter.get() == 1);
}
 
Example #24
Source File: LocalSampleAppIntegrationTest.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
private void waitForLogMessage(BufferedReader reader, String message) {
	Awaitility.await(message)
		.atMost(60, TimeUnit.SECONDS)
		.until(() -> {
			// drain all lines up to the one requested, or until no more lines in reader.
			while (reader.ready()) {
				String line = reader.readLine();

				if (line == null) {
					return false;
				}

				if (line.contains(message)) {
					return true;
				}
			}
			return false;
		});
}
 
Example #25
Source File: RedissonSubscribeReactiveTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnSubscribe() {
    RedissonConnectionFactory factory = new RedissonConnectionFactory(redisson);
    ReactiveRedisConnection connection = factory.getReactiveConnection();
    Mono<ReactiveSubscription> s = connection.pubSubCommands().createSubscription();
    AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
    ReactiveSubscription ss = s.block();

    ss.subscribe(ByteBuffer.wrap("test".getBytes())).block();
    ss.receive().doOnEach(message -> {
        msg.set(message.get().getMessage().array());
    }).subscribe();
    
    connection.pubSubCommands().publish(ByteBuffer.wrap("test".getBytes()), ByteBuffer.wrap("msg".getBytes())).block();
    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> Arrays.equals("msg".getBytes(), msg.get()));
    
    ss.unsubscribe();
    
    connection.pubSubCommands().publish(ByteBuffer.wrap("test".getBytes()), ByteBuffer.wrap("msg".getBytes())).block();
    
    
}
 
Example #26
Source File: Issue410Tests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
/**
 * Related to issue #1232
 */
@Test
public void should_pass_tracing_info_for_submitted_tasks_with_threadPoolTaskScheduler() {
	Span span = this.tracer.nextSpan().name("foo");
	log.info("Starting test");
	try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(span)) {
		String response = this.restTemplate.getForObject(
				"http://localhost:" + port() + "/threadPoolTaskScheduler_submit",
				String.class);

		then(response).isEqualTo(span.context().traceIdString());
		Awaitility.await().untilAsserted(() -> {
			then(this.asyncTask.getSpan().get()).isNotNull();
			then(this.asyncTask.getSpan().get().context().traceId())
					.isEqualTo(span.context().traceId());
		});
	}
	finally {
		span.finish();
	}

	then(this.tracer.currentSpan()).isNull();
}
 
Example #27
Source File: PolicyIdReferencePlaceholderResolverTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void resolvePolicyIdFromThingReturnsPolicyId() {

    final ReferencePlaceholder referencePlaceholder =
            ReferencePlaceholder.fromCharSequence("{{ ref:things/" + THING_ID + "/policyId }}")
                    .orElseThrow(IllegalStateException::new);

    final CompletionStage<String> policyIdCS = sut.resolve(referencePlaceholder, DittoHeaders.empty());

    final RetrieveThing retrieveThing = conciergeForwarderActorProbe.expectMsgClass(RetrieveThing.class);
    assertThat((CharSequence) retrieveThing.getThingEntityId()).isEqualTo(THING_ID);
    assertThat(retrieveThing.getSelectedFields()).contains(JsonFieldSelector.newInstance("policyId"));

    conciergeForwarderActorProbe.reply(RetrieveThingResponse.of(THING_ID,
            Thing.newBuilder().setPolicyId("namespace:myPolicy").build(), DittoHeaders.empty()));

    Awaitility.await()
            .atMost(org.awaitility.Duration.ONE_SECOND)
            .until(() -> policyIdCS.toCompletableFuture().isDone());
    assertThat(policyIdCS.toCompletableFuture())
            .isCompletedWithValue("namespace:myPolicy");
}
 
Example #28
Source File: InterruptTest.java    From AILibs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Two timed computations are nested. The outer is canceled significantly (1s) later than the inner.
 *
 * @throws ExecutionException
 * @throws InterruptedException
 * @throws AlgorithmTimeoutedException
 */
@Test
public void testNestedInterruptDuringExecutionWithOuterSignifiantlyLater() throws InterruptedException, AlgorithmTimeoutedException, ExecutionException {
	this.checkPreconditions();
	for (int i = 0; i < NUMBER_ITERATIONS_SHIFTED; i++) {

		/* test that InterruptException is thrown and that no interrupts are open */
		try {
			TimedComputation.compute(() -> TimedComputation.compute(new BusyBeaver(Long.MAX_VALUE), 1000, "inner interrupt"), 2000, "outer interrupt");
		} catch (ExecutionException e) {

			if (!(e.getCause() instanceof AlgorithmTimeoutedException)) {
				throw e;
			}

			/* this is expected behavior */
			assertTrue(GlobalTimer.getInstance().getActiveTasks().isEmpty());
			assertFalse(Interrupter.get().hasCurrentThreadOpenInterrupts());
			Awaitility.await().atLeast(2, TimeUnit.SECONDS);
			assertTrue(GlobalTimer.getInstance().getActiveTasks().isEmpty());
			assertFalse(Interrupter.get().hasCurrentThreadOpenInterrupts());
			continue;
		}
		fail("No exception was thrown, but an AlgorithmTimedoutedException should have been thrown!");
	}
}
 
Example #29
Source File: BadCLIOptionsPluginTest.java    From besu with Apache License 2.0 5 votes vote down vote up
private void waitForFile(final Path path) {
  final File file = path.toFile();
  Awaitility.waitAtMost(30, TimeUnit.SECONDS)
      .until(
          () -> {
            if (file.exists()) {
              try (final Stream<String> s = Files.lines(path)) {
                return s.count() > 0;
              }
            } else {
              return false;
            }
          });
}
 
Example #30
Source File: SynapseArtifactsHotDeploymentTestCase.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
@Test(groups = "wso2.esb",
      description = "Carbon Application Hot Deployment")
public void testHotDeployment() throws Exception {
    Awaitility.await().pollInterval(500, TimeUnit.MILLISECONDS).atMost(SERVICE_DEPLOYMENT_DELAY,
                                                                       TimeUnit.MILLISECONDS).until(
            isProxyHotDeployed(proxyName));

    assertTrue(checkProxyServiceExistence(proxyName), "Proxy Service Deployment failed");

    Awaitility.await().pollInterval(500, TimeUnit.MILLISECONDS).atMost(SERVICE_DEPLOYMENT_DELAY,
                                                                       TimeUnit.MILLISECONDS).until(
            isSequenceHotDeployed(sequenceName));
    assertTrue(checkSequenceExistence(sequenceName), "Sequence Deployment failed");

    Awaitility.await().pollInterval(500, TimeUnit.MILLISECONDS).atMost(SERVICE_DEPLOYMENT_DELAY,
                                                                       TimeUnit.MILLISECONDS).until(
            isEndpointHotDeployed(endpointName));
    assertTrue(checkEndpointExistence(endpointName), "Endpoint Deployment failed");

    Awaitility.await().pollInterval(500, TimeUnit.MILLISECONDS).atMost(SERVICE_DEPLOYMENT_DELAY,
                                                                       TimeUnit.MILLISECONDS).until(
            isApiHotDeployed(apiName));
    assertTrue(checkApiExistence(apiName), "API Deployment failed");

    Awaitility.await().pollInterval(500, TimeUnit.MILLISECONDS).atMost(SERVICE_DEPLOYMENT_DELAY,
                                                                       TimeUnit.MILLISECONDS).until(
            isLocalEntryHotDeployed(localEntryName));
    assertTrue(checkLocalEntryExistence(localEntryName), "Local Entry Deployment failed");

    Awaitility.await().pollInterval(500, TimeUnit.MILLISECONDS).atMost(SERVICE_DEPLOYMENT_DELAY,
                                                                       TimeUnit.MILLISECONDS).until(
            isMessageStoreHotDeployed(messageStoreName));
    assertTrue(checkMessageStoreExistence(messageStoreName), "Message Store Deployment failed");

    Awaitility.await().pollInterval(500, TimeUnit.MILLISECONDS).atMost(SERVICE_DEPLOYMENT_DELAY,
                                                                       TimeUnit.MILLISECONDS).until(
            isCAppHotDeployed(cAppName));
    assertTrue(checkCarbonAppExistence(cAppName), "Carbon application Deployment failed");
}