Search in sources :

Example 21 with Timeout

use of org.junit.jupiter.api.Timeout in project kafka by apache.

the class KafkaAdminClientTest method testCloseAdminClientInCallback.

/**
 * Test if admin client can be closed in the callback invoked when
 * an api call completes. If calling {@link Admin#close()} in callback, AdminClient thread hangs
 */
@Test
@Timeout(10)
public void testCloseAdminClientInCallback() throws InterruptedException {
    MockTime time = new MockTime();
    AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(time, mockCluster(3, 0));
    final ListTopicsResult result = env.adminClient().listTopics(new ListTopicsOptions().timeoutMs(1000));
    final KafkaFuture<Collection<TopicListing>> kafkaFuture = result.listings();
    final Semaphore callbackCalled = new Semaphore(0);
    kafkaFuture.whenComplete((topicListings, throwable) -> {
        env.close();
        callbackCalled.release();
    });
    // Advance time to timeout and complete listTopics request
    time.sleep(2000);
    callbackCalled.acquire();
}
Also used : DeletableTopicResultCollection(org.apache.kafka.common.message.DeleteTopicsResponseData.DeletableTopicResultCollection) CreatableTopicResultCollection(org.apache.kafka.common.message.CreateTopicsResponseData.CreatableTopicResultCollection) OffsetDeleteResponsePartitionCollection(org.apache.kafka.common.message.OffsetDeleteResponseData.OffsetDeleteResponsePartitionCollection) Collection(java.util.Collection) OffsetDeleteResponseTopicCollection(org.apache.kafka.common.message.OffsetDeleteResponseData.OffsetDeleteResponseTopicCollection) TopicCollection(org.apache.kafka.common.TopicCollection) DeletableGroupResultCollection(org.apache.kafka.common.message.DeleteGroupsResponseData.DeletableGroupResultCollection) Semaphore(java.util.concurrent.Semaphore) MockTime(org.apache.kafka.common.utils.MockTime) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Example 22 with Timeout

use of org.junit.jupiter.api.Timeout in project netty by netty.

the class AbstractSingleThreadEventLoopTest method testChannelsRegistered.

@Timeout(value = 5000, unit = TimeUnit.MILLISECONDS)
public void testChannelsRegistered() throws Exception {
    EventLoopGroup group = newEventLoopGroup();
    final SingleThreadEventLoop loop = (SingleThreadEventLoop) group.next();
    try {
        final Channel ch1 = newChannel();
        final Channel ch2 = newChannel();
        int rc = registeredChannels(loop);
        boolean channelCountSupported = rc != -1;
        if (channelCountSupported) {
            assertEquals(0, registeredChannels(loop));
        }
        assertTrue(loop.register(ch1).syncUninterruptibly().isSuccess());
        assertTrue(loop.register(ch2).syncUninterruptibly().isSuccess());
        if (channelCountSupported) {
            checkNumRegisteredChannels(loop, 2);
        }
        assertTrue(ch1.deregister().syncUninterruptibly().isSuccess());
        if (channelCountSupported) {
            checkNumRegisteredChannels(loop, 1);
        }
    } finally {
        group.shutdownGracefully();
    }
}
Also used : EventLoopGroup(io.netty.channel.EventLoopGroup) LocalServerChannel(io.netty.channel.local.LocalServerChannel) ServerChannel(io.netty.channel.ServerChannel) Channel(io.netty.channel.Channel) SingleThreadEventLoop(io.netty.channel.SingleThreadEventLoop) Timeout(org.junit.jupiter.api.Timeout)

Example 23 with Timeout

use of org.junit.jupiter.api.Timeout in project netty by netty.

the class DnsNameResolverTest method testDropAAAAResolveAllFast.

@Test
@Timeout(value = 2000, unit = TimeUnit.MILLISECONDS)
public void testDropAAAAResolveAllFast() throws IOException {
    final String host = "somehost.netty.io";
    TestDnsServer dnsServer2 = new TestDnsServer(new RecordStore() {

        @Override
        public Set<ResourceRecord> getRecords(QuestionRecord question) throws DnsException {
            String name = question.getDomainName();
            if (name.equals(host)) {
                Set<ResourceRecord> records = new HashSet<ResourceRecord>(2);
                records.add(new TestDnsServer.TestResourceRecord(name, RecordType.A, Collections.<String, Object>singletonMap(DnsAttribute.IP_ADDRESS.toLowerCase(), "10.0.0.1")));
                records.add(new TestDnsServer.TestResourceRecord(name, RecordType.A, Collections.<String, Object>singletonMap(DnsAttribute.IP_ADDRESS.toLowerCase(), "10.0.0.2")));
                return records;
            }
            return null;
        }
    });
    dnsServer2.start(true);
    DnsNameResolver resolver = null;
    try {
        DnsNameResolverBuilder builder = newResolver().recursionDesired(false).queryTimeoutMillis(10000).resolvedAddressTypes(ResolvedAddressTypes.IPV4_PREFERRED).completeOncePreferredResolved(true).maxQueriesPerResolve(16).nameServerProvider(new SingletonDnsServerAddressStreamProvider(dnsServer2.localAddress()));
        resolver = builder.build();
        List<InetAddress> addresses = resolver.resolveAll(host).syncUninterruptibly().getNow();
        assertEquals(2, addresses.size());
        for (InetAddress address : addresses) {
            assertThat(address, instanceOf(Inet4Address.class));
            assertEquals(host, address.getHostName());
        }
    } finally {
        dnsServer2.stop();
        if (resolver != null) {
            resolver.close();
        }
    }
}
Also used : QuestionRecord(org.apache.directory.server.dns.messages.QuestionRecord) Inet4Address(java.net.Inet4Address) Set(java.util.Set) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) ResourceRecord(org.apache.directory.server.dns.messages.ResourceRecord) DnsException(org.apache.directory.server.dns.DnsException) RecordStore(org.apache.directory.server.dns.store.RecordStore) InetAddress(java.net.InetAddress) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Example 24 with Timeout

use of org.junit.jupiter.api.Timeout in project netty by netty.

the class ThreadDeathWatcherTest method testWatch.

@Test
@Timeout(value = 10000, unit = TimeUnit.MILLISECONDS)
public void testWatch() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final Thread t = new Thread() {

        @Override
        public void run() {
            for (; ; ) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ignore) {
                    break;
                }
            }
        }
    };
    final Runnable task = new Runnable() {

        @Override
        public void run() {
            if (!t.isAlive()) {
                latch.countDown();
            }
        }
    };
    try {
        ThreadDeathWatcher.watch(t, task);
        fail("must reject to watch a non-alive thread.");
    } catch (IllegalArgumentException e) {
    // expected
    }
    t.start();
    ThreadDeathWatcher.watch(t, task);
    // As long as the thread is alive, the task should not run.
    assertThat(latch.await(750, TimeUnit.MILLISECONDS), is(false));
    // Interrupt the thread to terminate it.
    t.interrupt();
    // The task must be run on termination.
    latch.await();
}
Also used : CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Example 25 with Timeout

use of org.junit.jupiter.api.Timeout in project netty by netty.

the class ResourceLeakDetectorTest method testConcurrentUsage.

@Test
@Timeout(value = 60000, unit = TimeUnit.MILLISECONDS)
public void testConcurrentUsage() throws Throwable {
    final AtomicBoolean finished = new AtomicBoolean();
    final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
    // With 50 threads issue #6087 is reproducible on every run.
    Thread[] threads = new Thread[50];
    final CyclicBarrier barrier = new CyclicBarrier(threads.length);
    for (int i = 0; i < threads.length; i++) {
        Thread t = new Thread(new Runnable() {

            final Queue<LeakAwareResource> resources = new ArrayDeque<LeakAwareResource>(100);

            @Override
            public void run() {
                try {
                    barrier.await();
                    // Run 10000 times or until the test is marked as finished.
                    for (int b = 0; b < 1000 && !finished.get(); b++) {
                        // Allocate 100 LeakAwareResource per run and close them after it.
                        for (int a = 0; a < 100; a++) {
                            DefaultResource resource = new DefaultResource();
                            ResourceLeakTracker<Resource> leak = DefaultResource.detector.track(resource);
                            LeakAwareResource leakAwareResource = new LeakAwareResource(resource, leak);
                            resources.add(leakAwareResource);
                        }
                        if (closeResources(true)) {
                            finished.set(true);
                        }
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } catch (Throwable e) {
                    error.compareAndSet(null, e);
                } finally {
                    // Just close all resource now without assert it to eliminate more reports.
                    closeResources(false);
                }
            }

            private boolean closeResources(boolean checkClosed) {
                for (; ; ) {
                    LeakAwareResource r = resources.poll();
                    if (r == null) {
                        return false;
                    }
                    boolean closed = r.close();
                    if (checkClosed && !closed) {
                        error.compareAndSet(null, new AssertionError("ResourceLeak.close() returned 'false' but expected 'true'"));
                        return true;
                    }
                }
            }
        });
        threads[i] = t;
        t.start();
    }
    // Just wait until all threads are done.
    for (Thread t : threads) {
        t.join();
    }
    // Check if we had any leak reports in the ResourceLeakDetector itself
    DefaultResource.detector.assertNoErrors();
    assertNoErrors(error);
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayDeque(java.util.ArrayDeque) CyclicBarrier(java.util.concurrent.CyclicBarrier) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Aggregations

Timeout (org.junit.jupiter.api.Timeout)291 Test (org.junit.jupiter.api.Test)235 CountDownLatch (java.util.concurrent.CountDownLatch)71 ZooKeeper (org.apache.zookeeper.ZooKeeper)33 AtomicReference (java.util.concurrent.atomic.AtomicReference)32 ArrayList (java.util.ArrayList)31 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)29 RepeatedTest (org.junit.jupiter.api.RepeatedTest)29 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)29 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)28 LocalChannel (io.netty.channel.local.LocalChannel)27 CountdownWatcher (org.apache.zookeeper.test.ClientBase.CountdownWatcher)26 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)25 IOException (java.io.IOException)25 Bootstrap (io.netty.bootstrap.Bootstrap)24 MethodSource (org.junit.jupiter.params.provider.MethodSource)24 Channel (io.netty.channel.Channel)23 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)21 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)19 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)19