How to use Timer class of org.mockito.internal.util package

Best Mockito code snippet using org.mockito.internal.util.Timer

Source:BaseTestHBaseClient.java Github

copy

Full Screen

...50import org.jboss.netty.channel.socket.SocketChannelConfig;51import org.jboss.netty.channel.socket.nio.NioClientBossPool;52import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;53import org.jboss.netty.channel.socket.nio.NioWorkerPool;54import org.jboss.netty.util.HashedWheelTimer;55import org.jboss.netty.util.Timeout;56import org.jboss.netty.util.TimerTask;57import org.junit.Before;58import org.junit.Ignore;59import org.mockito.invocation.InvocationOnMock;60import org.mockito.stubbing.Answer;61import org.powermock.api.mockito.PowerMockito;62import org.powermock.core.classloader.annotations.PrepareForTest;63import org.powermock.reflect.Whitebox;64import com.stumbleupon.async.Deferred;65@PrepareForTest({ HBaseClient.class, RegionClient.class, HBaseRpc.class, 66 GetRequest.class, RegionInfo.class, NioClientSocketChannelFactory.class, 67 Executors.class, HashedWheelTimer.class, NioClientBossPool.class, 68 NioWorkerPool.class })69@Ignore // ignore for test runners70public class BaseTestHBaseClient {71 protected static final Charset CHARSET = Charset.forName("ASCII");72 protected static final byte[] COMMA = { ',' };73 protected static final byte[] TIMESTAMP = "1234567890".getBytes();74 protected static final byte[] INFO = getStatic("INFO");75 protected static final byte[] REGIONINFO = getStatic("REGIONINFO");76 protected static final byte[] SERVER = getStatic("SERVER");77 protected static final byte[] TABLE = { 't', 'a', 'b', 'l', 'e' };78 protected static final byte[] KEY = { 'k', 'e', 'y' };79 protected static final byte[] KEY2 = { 'k', 'e', 'y', '2' };80 protected static final byte[] FAMILY = { 'f' };81 protected static final byte[] QUALIFIER = { 'q', 'u', 'a', 'l' };82 protected static final byte[] VALUE = { 'v', 'a', 'l', 'u', 'e' };83 protected static final byte[] EMPTY_ARRAY = new byte[0];84 protected static final KeyValue KV = new KeyValue(KEY, FAMILY, QUALIFIER, VALUE);85 protected static final RegionInfo meta = mkregion(".META.", ".META.,,1234567890");86 protected static final RegionInfo region = mkregion("table", "table,,1234567890");87 protected static final int RS_PORT = 50511;88 protected static final String ROOT_IP = "192.168.0.1";89 protected static final String META_IP = "192.168.0.2";90 protected static final String REGION_CLIENT_IP = "192.168.0.3";91 protected static String MOCK_RS_CLIENT_NAME = "Mock RegionClient";92 protected static String MOCK_ROOT_CLIENT_NAME = "Mock RootClient";93 protected static String MOCK_META_CLIENT_NAME = "Mock MetaClient";94 95 protected HBaseClient client = null;96 /** Extracted from {@link #client}. */97 protected ConcurrentSkipListMap<byte[], RegionInfo> regions_cache;98 /** Extracted from {@link #client}. */99 protected ConcurrentHashMap<RegionInfo, RegionClient> region2client;100 /** Extracted from {@link #client}. */101 protected ConcurrentHashMap<RegionClient, ArrayList<RegionInfo>> client2regions;102 /** Extracted from {@link #client}. */103 protected ConcurrentSkipListMap<byte[], ArrayList<HBaseRpc>> got_nsre;104 /** Extracted from {@link #client}. */105 protected HashMap<String, RegionClient> ip2client;106 /** Extracted from {@link #client}. */107 protected Counter num_nsre_rpcs;108 /** Fake client supposedly connected to -ROOT-. */109 protected RegionClient rootclient;110 /** Fake client supposedly connected to .META.. */111 protected RegionClient metaclient;112 /** Fake client supposedly connected to our fake test table. */113 protected RegionClient regionclient;114 /** Each new region client is dumped here */115 protected List<RegionClient> region_clients = new ArrayList<RegionClient>();116 /** Fake Zookeeper client */117 protected ZKClient zkclient;118 /** Fake channel factory */119 protected NioClientSocketChannelFactory channel_factory;120 /** Fake channel returned from the factory */121 protected SocketChannel chan;122 /** Fake timer for testing */123 protected FakeTimer timer;124 125 @Before126 public void before() throws Exception {127 region_clients.clear();128 rootclient = mock(RegionClient.class);129 when(rootclient.toString()).thenReturn(MOCK_ROOT_CLIENT_NAME);130 metaclient = mock(RegionClient.class);131 when(metaclient.toString()).thenReturn(MOCK_META_CLIENT_NAME);132 regionclient = mock(RegionClient.class);133 when(regionclient.toString()).thenReturn(MOCK_RS_CLIENT_NAME);134 zkclient = mock(ZKClient.class);135 channel_factory = mock(NioClientSocketChannelFactory.class);136 chan = mock(SocketChannel.class);137 timer = new FakeTimer();138 139 when(zkclient.getDeferredRoot()).thenReturn(new Deferred<Object>());140 PowerMockito.mockStatic(Executors.class);141 PowerMockito.when(Executors.defaultThreadFactory())142 .thenReturn(mock(ThreadFactory.class));143 PowerMockito.when(Executors.newCachedThreadPool())144 .thenReturn(mock(ExecutorService.class));145 PowerMockito.whenNew(NioClientSocketChannelFactory.class).withAnyArguments()146 .thenReturn(channel_factory);147 148 PowerMockito.whenNew(HashedWheelTimer.class).withAnyArguments()149 .thenReturn(timer);150 PowerMockito.whenNew(NioClientBossPool.class).withAnyArguments()151 .thenReturn(mock(NioClientBossPool.class));152 PowerMockito.whenNew(NioWorkerPool.class).withAnyArguments()153 .thenReturn(mock(NioWorkerPool.class));154 155 client = PowerMockito.spy(new HBaseClient("test-quorum-spec"));156 Whitebox.setInternalState(client, "zkclient", zkclient);157 Whitebox.setInternalState(client, "rootregion", rootclient);158 regions_cache = Whitebox.getInternalState(client, "regions_cache");159 region2client = Whitebox.getInternalState(client, "region2client");160 client2regions = Whitebox.getInternalState(client, "client2regions");161 got_nsre = Whitebox.getInternalState(client, "got_nsre");162 ip2client = Whitebox.getInternalState(client, "ip2client");163 injectRegionInCache(meta, metaclient, META_IP + ":" + RS_PORT);164 injectRegionInCache(region, regionclient, REGION_CLIENT_IP + ":" + RS_PORT);165 166 when(channel_factory.newChannel(any(ChannelPipeline.class)))167 .thenReturn(chan);168 when(chan.getConfig()).thenReturn(mock(SocketChannelConfig.class));169 when(rootclient.toString()).thenReturn("Mock RootClient");170 171 PowerMockito.doAnswer(new Answer<RegionClient>(){172 @Override173 public RegionClient answer(InvocationOnMock invocation) throws Throwable {174 final Object[] args = invocation.getArguments();175 final String endpoint = (String)args[0] + ":" + (Integer)args[1];176 final RegionClient rc = mock(RegionClient.class);177 when(rc.getRemoteAddress()).thenReturn(endpoint);178 client2regions.put(rc, new ArrayList<RegionInfo>());179 region_clients.add(rc);180 return rc;181 }182 }).when(client, "newClient", anyString(), anyInt());183 }184 185 /**186 * Injects an entry in the local caches of the client.187 */188 protected void injectRegionInCache(final RegionInfo region,189 final RegionClient client,190 final String ip) {191 regions_cache.put(region.name(), region);192 region2client.put(region, client);193 ArrayList<RegionInfo> regions = client2regions.get(client);194 if (regions == null) {195 regions = new ArrayList<RegionInfo>(1);196 client2regions.put(client, regions);197 }198 regions.add(region);199 ip2client.put(ip, client);200 }201 202 // ----------------- //203 // Helper functions. //204 // ----------------- //205 protected void clearCaches(){206 regions_cache.clear();207 region2client.clear();208 client2regions.clear();209 }210 211 protected static <T> T getStatic(final String fieldname) {212 return Whitebox.getInternalState(HBaseClient.class, fieldname);213 }214 /**215 * Creates a fake {@code .META.} row.216 * The row contains a single entry for all keys of {@link #TABLE}.217 */218 protected static ArrayList<KeyValue> metaRow() {219 return metaRow(HBaseClient.EMPTY_ARRAY, HBaseClient.EMPTY_ARRAY);220 }221 /**222 * Creates a fake {@code .META.} row.223 * The row contains a single entry for {@link #TABLE}.224 * @param start_key The start key of the region in this entry.225 * @param stop_key The stop key of the region in this entry.226 */227 protected static ArrayList<KeyValue> metaRow(final byte[] start_key,228 final byte[] stop_key) {229 final ArrayList<KeyValue> row = new ArrayList<KeyValue>(2);230 row.add(metaRegionInfo(start_key, stop_key, false, false, TABLE));231 row.add(new KeyValue(region.name(), INFO, SERVER, "localhost:54321".getBytes()));232 return row;233 }234 235 protected static KeyValue metaRegionInfo( final byte[] start_key, 236 final byte[] stop_key, final boolean offline, final boolean splitting, 237 final byte[] table) {238 final byte[] name = concat(table, COMMA, start_key, COMMA, TIMESTAMP);239 final byte is_splitting = (byte) (splitting ? 1 : 0);240 final byte[] regioninfo = concat(241 new byte[] {242 0, // version243 (byte) stop_key.length, // vint: stop key length244 },245 stop_key,246 offline ? new byte[] { 1 } : new byte[] { 0 }, // boolean: offline247 Bytes.fromLong(name.hashCode()), // long: region ID (make it random)248 new byte[] { (byte) name.length }, // vint: region name length249 name, // region name250 new byte[] {251 is_splitting, // boolean: splitting252 (byte) start_key.length, // vint: start key length253 },254 start_key255 );256 return new KeyValue(region.name(), INFO, REGIONINFO, regioninfo);257 }258 protected static RegionInfo mkregion(final String table, final String name) {259 return new RegionInfo(table.getBytes(), name.getBytes(),260 HBaseClient.EMPTY_ARRAY);261 }262 protected static byte[] anyBytes() {263 return any(byte[].class);264 }265 /** Concatenates byte arrays together. */266 protected static byte[] concat(final byte[]... arrays) {267 int len = 0;268 for (final byte[] array : arrays) {269 len += array.length;270 }271 final byte[] result = new byte[len];272 len = 0;273 for (final byte[] array : arrays) {274 System.arraycopy(array, 0, result, len, array.length);275 len += array.length;276 }277 return result;278 }279 /** Creates a new Deferred that's already called back. */280 protected static <T> Answer<Deferred<T>> newDeferred(final T result) {281 return new Answer<Deferred<T>>() {282 public Deferred<T> answer(final InvocationOnMock invocation) {283 return Deferred.fromResult(result);284 }285 };286 }287 /**288 * A fake {@link Timer} implementation that fires up tasks immediately.289 * Tasks are called immediately from the current thread and a history of the290 * various tasks is logged.291 */292 static final class FakeTimer extends HashedWheelTimer {293 final List<Map.Entry<TimerTask, Long>> tasks = 294 new ArrayList<Map.Entry<TimerTask, Long>>();295 final ArrayList<Timeout> timeouts = new ArrayList<Timeout>();296 boolean run = true;297 298 @Override299 public Timeout newTimeout(final TimerTask task,300 final long delay,301 final TimeUnit unit) {302 try {303 tasks.add(new AbstractMap.SimpleEntry<TimerTask, Long>(task, delay));304 if (run) {305 task.run(null); // Argument never used in this code base.306 }307 final Timeout timeout = mock(Timeout.class);308 timeouts.add(timeout);309 return timeout; // Return value never used in this code base.310 } catch (RuntimeException e) {311 throw e;312 } catch (Exception e) {313 throw new RuntimeException("Timer task failed: " + task, e);314 }315 }316 @Override317 public Set<Timeout> stop() {318 run = false;319 return new HashSet<Timeout>(timeouts);320 }321 }322 /**323 * A fake {@link org.jboss.netty.util.Timer} implementation.324 * Instead of executing the task it will store that task in a internal state325 * and provides a function to start the execution of the stored task.326 * This implementation thus allows the flexibility of simulating the327 * things that will be going on during the time out period of a TimerTask.328 * This was mainly return to simulate the timeout period for329 * alreadyNSREdRegion test, where the region will be in the NSREd mode only330 * during this timeout period, which was difficult to simulate using the331 * above {@link FakeTimer} implementation, as we don't get back the control332 * during the timeout period333 *334 * Here it will hold at most two Tasks. We have two tasks here because when335 * one is being executed, it may call for newTimeOut for another task.336 */337 static final class FakeTaskTimer extends HashedWheelTimer {338 protected TimerTask newPausedTask = null;339 protected TimerTask pausedTask = null;340 @Override341 public synchronized Timeout newTimeout(final TimerTask task,342 final long delay,343 final TimeUnit unit) {344 if (pausedTask == null) {345 pausedTask = task;346 } else if (newPausedTask == null) {347 newPausedTask = task;348 } else {349 throw new IllegalStateException("Cannot Pause Two Timer Tasks");350 }351 return null;352 }353 @Override354 public Set<Timeout> stop() {355 return null;356 }357 public boolean continuePausedTask() {358 if (pausedTask == null) {359 return false;360 }361 try {362 if (newPausedTask != null) {363 throw new IllegalStateException("Cannot be in this state");364 }365 pausedTask.run(null); // Argument never used in this code base366 pausedTask = newPausedTask;367 newPausedTask = null;368 return true;369 } catch (Exception e) {370 throw new RuntimeException("Timer task failed: " + pausedTask, e);371 }372 }373 }374 /**375 * Generate and return a mocked HBase RPC for testing purposes with a valid376 * Deferred that can be called on execution. 377 * @param deferred A deferred to watch for results378 * @return The RPC to pass through unit tests.379 */380 protected HBaseRpc getMockHBaseRpc(final Deferred<Object> deferred) {381 final HBaseRpc rpc = mock(HBaseRpc.class);382 rpc.attempt = 0;383 when(rpc.getDeferred()).thenReturn(deferred);384 when(rpc.toString()).thenReturn("MockRPC");...

Full Screen

Full Screen

Source:PulsarClientImplTest.java Github

copy

Full Screen

...32import io.netty.channel.ChannelFuture;33import io.netty.channel.ChannelHandlerContext;34import io.netty.channel.ChannelPromise;35import io.netty.channel.EventLoopGroup;36import io.netty.util.HashedWheelTimer;37import io.netty.util.concurrent.DefaultThreadFactory;38import java.lang.reflect.Field;39import java.net.InetSocketAddress;40import java.net.SocketAddress;41import java.util.ArrayList;42import java.util.Collections;43import java.util.List;44import java.util.concurrent.CompletableFuture;45import java.util.concurrent.ThreadFactory;46import java.util.regex.Pattern;47import lombok.Cleanup;48import org.apache.commons.lang3.tuple.Pair;49import org.apache.pulsar.client.api.PulsarClientException;50import org.apache.pulsar.client.impl.conf.ClientConfigurationData;51import org.apache.pulsar.client.impl.conf.ConsumerConfigurationData;52import org.apache.pulsar.client.util.ExecutorProvider;53import org.apache.pulsar.common.api.proto.CommandGetTopicsOfNamespace;54import org.apache.pulsar.common.naming.NamespaceName;55import org.apache.pulsar.common.naming.TopicName;56import org.apache.pulsar.common.partition.PartitionedTopicMetadata;57import org.apache.pulsar.common.util.netty.EventLoopUtil;58import org.mockito.Mockito;59import org.powermock.reflect.Whitebox;60import org.testng.annotations.AfterMethod;61import org.testng.annotations.BeforeMethod;62import org.testng.annotations.Test;63/**64 * PulsarClientImpl unit tests.65 */66public class PulsarClientImplTest {67 private PulsarClientImpl clientImpl;68 private EventLoopGroup eventLoopGroup;69 @BeforeMethod(alwaysRun = true)70 public void setup() throws PulsarClientException {71 ClientConfigurationData conf = new ClientConfigurationData();72 conf.setServiceUrl("pulsar://localhost:6650");73 initializeEventLoopGroup(conf);74 clientImpl = new PulsarClientImpl(conf, eventLoopGroup);75 }76 private void initializeEventLoopGroup(ClientConfigurationData conf) {77 ThreadFactory threadFactory = new DefaultThreadFactory("client-test-stats", Thread.currentThread().isDaemon());78 eventLoopGroup = EventLoopUtil.newEventLoopGroup(conf.getNumIoThreads(), false, threadFactory);79 }80 @AfterMethod(alwaysRun = true)81 public void teardown() throws Exception {82 if (clientImpl != null) {83 clientImpl.close();84 clientImpl = null;85 }86 if (eventLoopGroup != null) {87 eventLoopGroup.shutdownGracefully().get();88 eventLoopGroup = null;89 }90 }91 @Test92 public void testIsClosed() throws Exception {93 assertFalse(clientImpl.isClosed());94 clientImpl.close();95 assertTrue(clientImpl.isClosed());96 }97 @Test98 public void testConsumerIsClosed() throws Exception {99 // mock client connection100 LookupService lookup = mock(LookupService.class);101 when(lookup.getTopicsUnderNamespace(102 any(NamespaceName.class),103 any(CommandGetTopicsOfNamespace.Mode.class)))104 .thenReturn(CompletableFuture.completedFuture(Collections.emptyList()));105 when(lookup.getPartitionedTopicMetadata(any(TopicName.class)))106 .thenReturn(CompletableFuture.completedFuture(new PartitionedTopicMetadata()));107 when(lookup.getBroker(any(TopicName.class)))108 .thenReturn(CompletableFuture.completedFuture(109 Pair.of(mock(InetSocketAddress.class), mock(InetSocketAddress.class))));110 ConnectionPool pool = mock(ConnectionPool.class);111 ClientCnx cnx = mock(ClientCnx.class);112 ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);113 Channel channel = mock(Channel.class);114 when(channel.remoteAddress()).thenReturn(mock(SocketAddress.class));115 when(ctx.channel()).thenReturn(channel);116 when(ctx.writeAndFlush(any(), any(ChannelPromise.class))).thenReturn(mock(ChannelFuture.class));117 when(ctx.voidPromise()).thenReturn(mock(ChannelPromise.class));118 when(cnx.channel()).thenReturn(channel);119 when(cnx.ctx()).thenReturn(ctx);120 when(cnx.sendRequestWithId(any(ByteBuf.class), anyLong()))121 .thenReturn(CompletableFuture.completedFuture(mock(ProducerResponse.class)));122 when(pool.getConnection(any(InetSocketAddress.class), any(InetSocketAddress.class)))123 .thenReturn(CompletableFuture.completedFuture(cnx));124 Whitebox.setInternalState(clientImpl, "cnxPool", pool);125 Whitebox.setInternalState(clientImpl, "lookup", lookup);126 List<ConsumerBase<byte[]>> consumers = new ArrayList<>();127 /**128 * {@link org.apache.pulsar.client.impl.PulsarClientImpl#patternTopicSubscribeAsync}129 */130 ConsumerConfigurationData<byte[]> consumerConf0 = new ConsumerConfigurationData<>();131 consumerConf0.setSubscriptionName("test-subscription0");132 consumerConf0.setTopicsPattern(Pattern.compile("test-topic"));133 consumers.add((ConsumerBase) clientImpl.subscribeAsync(consumerConf0).get());134 /**135 * {@link org.apache.pulsar.client.impl.PulsarClientImpl#singleTopicSubscribeAsync}136 */137 ConsumerConfigurationData<byte[]> consumerConf1 = new ConsumerConfigurationData<>();138 consumerConf1.setSubscriptionName("test-subscription1");139 consumerConf1.setTopicNames(Collections.singleton("test-topic"));140 consumers.add((ConsumerBase) clientImpl.subscribeAsync(consumerConf1).get());141 /**142 * {@link org.apache.pulsar.client.impl.PulsarClientImpl#multiTopicSubscribeAsync}143 */144 ConsumerConfigurationData<byte[]> consumerConf2 = new ConsumerConfigurationData<>();145 consumerConf2.setSubscriptionName("test-subscription2");146 consumers.add((ConsumerBase) clientImpl.subscribeAsync(consumerConf2).get());147 consumers.forEach(consumer ->148 assertNotSame(consumer.getState(), HandlerState.State.Closed));149 clientImpl.close();150 consumers.forEach(consumer ->151 assertSame(consumer.getState(), HandlerState.State.Closed));152 }153 @Test154 public void testInitializeWithoutTimer() throws Exception {155 ClientConfigurationData conf = new ClientConfigurationData();156 conf.setServiceUrl("pulsar://localhost:6650");157 PulsarClientImpl client = new PulsarClientImpl(conf);158 HashedWheelTimer timer = mock(HashedWheelTimer.class);159 Field field = client.getClass().getDeclaredField("timer");160 field.setAccessible(true);161 field.set(client, timer);162 client.shutdown();163 verify(timer).stop();164 }165 @Test166 public void testInitializeWithTimer() throws PulsarClientException {167 ClientConfigurationData conf = new ClientConfigurationData();168 EventLoopGroup eventLoop = EventLoopUtil.newEventLoopGroup(1, false, new DefaultThreadFactory("test"));169 ConnectionPool pool = Mockito.spy(new ConnectionPool(conf, eventLoop));170 conf.setServiceUrl("pulsar://localhost:6650");171 HashedWheelTimer timer = new HashedWheelTimer();172 PulsarClientImpl client = new PulsarClientImpl(conf, eventLoop, pool, timer);173 client.shutdown();174 client.timer().stop();175 }176 @Test(expectedExceptions = PulsarClientException.class)177 public void testNewTransactionWhenDisable() throws Exception {178 ClientConfigurationData conf = new ClientConfigurationData();179 conf.setServiceUrl("pulsar://localhost:6650");180 conf.setEnableTransaction(false);181 PulsarClientImpl pulsarClient = null;182 try {183 pulsarClient = new PulsarClientImpl(conf);184 } catch (PulsarClientException e) {185 e.printStackTrace();...

Full Screen

Full Screen

Source:TestReencryptionHandler.java Github

copy

Full Screen

...91 Mockito.when(mockLocked.now(TimeUnit.MILLISECONDS))92 .thenReturn((long) 20000);93 Mockito.when(mockLocked.reset()).thenReturn(mockLocked);94 final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();95 Whitebox.setInternalState(rh, "throttleTimerAll", mockAll);96 Whitebox.setInternalState(rh, "throttleTimerLocked", mockLocked);97 Whitebox.setInternalState(rh, "taskQueue", queue);98 final StopWatch sw = new StopWatch().start();99 rh.getTraverser().throttle();100 sw.stop();101 assertTrue("should have throttled for at least 8 second",102 sw.now(TimeUnit.MILLISECONDS) > 8000);103 assertTrue("should have throttled for at most 12 second",104 sw.now(TimeUnit.MILLISECONDS) < 12000);105 }106 @Test107 public void testThrottleNoOp() throws Exception {108 final Configuration conf = new Configuration();109 conf.setDouble(DFS_NAMENODE_REENCRYPT_THROTTLE_LIMIT_HANDLER_RATIO_KEY,110 0.5);111 final ReencryptionHandler rh = mockReencryptionhandler(conf);112 // mock StopWatches so all = 30s, locked = 10s. With ratio = .5, throttle113 // should not happen.114 StopWatch mockAll = Mockito.mock(StopWatch.class);115 Mockito.when(mockAll.now()).thenReturn(new Long(30000));116 Mockito.when(mockAll.reset()).thenReturn(mockAll);117 StopWatch mockLocked = Mockito.mock(StopWatch.class);118 Mockito.when(mockLocked.now()).thenReturn(new Long(10000));119 Mockito.when(mockLocked.reset()).thenReturn(mockLocked);120 final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();121 Whitebox.setInternalState(rh, "throttleTimerAll", mockAll);122 Whitebox.setInternalState(rh, "throttleTimerLocked", mockLocked);123 Whitebox.setInternalState(rh, "taskQueue", queue);124 final Map<Long, ReencryptionUpdater.ZoneSubmissionTracker>125 submissions = new HashMap<>();126 Whitebox.setInternalState(rh, "submissions", submissions);127 StopWatch sw = new StopWatch().start();128 rh.getTraverser().throttle();129 sw.stop();130 assertTrue("should not have throttled",131 sw.now(TimeUnit.MILLISECONDS) < 1000);132 }133 @Test134 public void testThrottleConfigs() throws Exception {135 final Configuration conf = new Configuration();136 conf.setDouble(DFS_NAMENODE_REENCRYPT_THROTTLE_LIMIT_HANDLER_RATIO_KEY,...

Full Screen

Full Screen

Source:JobLauncherUnitTests.java Github

copy

Full Screen

...26import com.netflix.genie.test.categories.UnitTest;27import com.netflix.genie.web.services.JobSubmitterService;28import com.netflix.genie.web.util.MetricsUtils;29import io.micrometer.core.instrument.MeterRegistry;30import io.micrometer.core.instrument.Timer;31import org.junit.Before;32import org.junit.Test;33import org.junit.experimental.categories.Category;34import org.mockito.Mockito;35import org.mockito.MockitoAnnotations;36import java.util.List;37import java.util.concurrent.TimeUnit;38/**39 * Unit tests for the JobLauncher class.40 *41 * @author tgianos42 * @since 3.0.043 */44@Category(UnitTest.class)45public class JobLauncherUnitTests {46 private JobLauncher jobLauncher;47 private JobSubmitterService jobSubmitterService;48 private JobRequest jobRequest;49 private Cluster cluster;50 private Command command;51 private List<Application> applications;52 private MeterRegistry registry;53 private Timer timer;54 private int memory;55 /**56 * Setup for the tests.57 */58 @Before59 public void setup() {60 MockitoAnnotations.initMocks(this);61 this.jobRequest = Mockito.mock(JobRequest.class);62 this.cluster = Mockito.mock(Cluster.class);63 this.command = Mockito.mock(Command.class);64 this.applications = Lists.newArrayList(Mockito.mock(Application.class));65 this.jobSubmitterService = Mockito.mock(JobSubmitterService.class);66 this.memory = 1_024;67 this.registry = Mockito.mock(MeterRegistry.class);68 this.timer = Mockito.mock(Timer.class);69 Mockito70 .when(this.registry.timer(Mockito.eq(JobLauncher.JOB_SUBMIT_TIMER_NAME), Mockito.anySet()))71 .thenReturn(this.timer);72 this.jobLauncher = new JobLauncher(73 this.jobSubmitterService,74 this.jobRequest,75 this.cluster,76 this.command,77 this.applications,78 this.memory,79 this.registry80 );81 }82 /**...

Full Screen

Full Screen

Source:JobLauncherTest.java Github

copy

Full Screen

...25import com.netflix.genie.common.internal.dto.v4.Command;26import com.netflix.genie.web.services.JobSubmitterService;27import com.netflix.genie.web.util.MetricsUtils;28import io.micrometer.core.instrument.MeterRegistry;29import io.micrometer.core.instrument.Timer;30import org.junit.Before;31import org.junit.Test;32import org.mockito.Mockito;33import org.mockito.MockitoAnnotations;34import java.util.List;35import java.util.concurrent.TimeUnit;36/**37 * Unit tests for the JobLauncher class.38 *39 * @author tgianos40 * @since 3.0.041 */42public class JobLauncherTest {43 private JobLauncher jobLauncher;44 private JobSubmitterService jobSubmitterService;45 private JobRequest jobRequest;46 private Cluster cluster;47 private Command command;48 private List<Application> applications;49 private MeterRegistry registry;50 private Timer timer;51 private int memory;52 /**53 * Setup for the tests.54 */55 @Before56 public void setup() {57 MockitoAnnotations.initMocks(this);58 this.jobRequest = Mockito.mock(JobRequest.class);59 this.cluster = Mockito.mock(Cluster.class);60 this.command = Mockito.mock(Command.class);61 this.applications = Lists.newArrayList(Mockito.mock(Application.class));62 this.jobSubmitterService = Mockito.mock(JobSubmitterService.class);63 this.memory = 1_024;64 this.registry = Mockito.mock(MeterRegistry.class);65 this.timer = Mockito.mock(Timer.class);66 Mockito67 .when(this.registry.timer(Mockito.eq(JobLauncher.JOB_SUBMIT_TIMER_NAME), Mockito.anySet()))68 .thenReturn(this.timer);69 this.jobLauncher = new JobLauncher(70 this.jobSubmitterService,71 this.jobRequest,72 this.cluster,73 this.command,74 this.applications,75 this.memory,76 this.registry77 );78 }79 /**...

Full Screen

Full Screen

Source:TimerBeanTest.java Github

copy

Full Screen

...24import javax.faces.application.FacesMessage;25import org.junit.Before;26import org.junit.Test;27import org.oscm.test.stubs.OperatorServiceStub;28import org.oscm.types.enumtypes.TimerType;29import org.oscm.ui.beans.BaseBean;30import org.oscm.ui.stubs.FacesContextStub;31import org.oscm.internal.intf.OperatorService;32import org.oscm.internal.types.exception.ValidationException;33import org.oscm.internal.vo.VOTimerInfo;34/**35 * @author weiser36 * 37 */38public class TimerBeanTest {39 private TimerBean bean;40 private TimerBean timerBean;41 private OperatorService operatorService;42 protected String messageKey;43 protected boolean serviceCalled;44 protected List<VOTimerInfo> expirationInfo;45 private final List<FacesMessage> facesMessages = new ArrayList<FacesMessage>();46 @Before47 public void setup() {48 timerBean = spy(new TimerBean());49 operatorService = mock(OperatorService.class);50 doReturn(operatorService).when(timerBean).getOperatorService();51 new FacesContextStub(Locale.ENGLISH) {52 public void addMessage(String arg0, FacesMessage arg1) {53 facesMessages.add(arg1);54 }55 };56 final OperatorServiceStub stub = new OperatorServiceStub() {57 public List<VOTimerInfo> getTimerExpirationInformation() {58 serviceCalled = true;59 return expirationInfo;60 }61 public List<VOTimerInfo> reInitTimers() {62 serviceCalled = true;63 return expirationInfo;64 }65 };66 bean = new TimerBean() {67 private static final long serialVersionUID = 5713210290878291988L;68 protected OperatorService getOperatorService() {69 return stub;70 }71 protected void addMessage(final String clientId,72 final FacesMessage.Severity severity, final String key) {73 messageKey = key;74 }75 };76 expirationInfo = new ArrayList<VOTimerInfo>();77 VOTimerInfo o = new VOTimerInfo();78 o.setExpirationDate(new Date());79 o.setTimerType(TimerType.BILLING_INVOCATION.name());80 expirationInfo.add(o);81 }82 @Test83 public void testGetExpirationInfo() throws Exception {84 List<VOTimerInfo> list = bean.getExpirationInfo();85 assertEquals(expirationInfo, list);86 assertTrue(serviceCalled);87 // the second call must do no service call because the data is cached88 // but return the same data89 serviceCalled = false;90 list = bean.getExpirationInfo();91 assertEquals(expirationInfo, list);92 assertFalse(serviceCalled);93 }94 @Test95 public void testReInitTimers() throws Exception {96 String result = bean.reInitTimers();97 assertEquals(BaseBean.OUTCOME_SUCCESS, result);98 assertEquals(BaseOperatorBean.INFO_TASK_SUCCESSFUL, messageKey);99 assertTrue(serviceCalled);100 // reinit timers also returns the timer info - so the field must be not101 // null and thus no service must be called to get the timer information102 serviceCalled = false;103 List<VOTimerInfo> list = bean.getExpirationInfo();104 assertEquals(expirationInfo, list);105 assertFalse(serviceCalled);106 }107 @Test108 public void testReInitTimers_timerIntervalInvalid() throws Exception {109 // given110 doThrow(new ValidationException()).when(operatorService).reInitTimers();111 // when112 String result = timerBean.reInitTimers();113 // then114 assertEquals(BaseBean.OUTCOME_ERROR, result);115 }116}...

Full Screen

Full Screen

Source:TimerExecScheduler_Test.java Github

copy

Full Screen

...21import static org.mockito.Mockito.when;22import java.util.Collection;23import java.util.Collections;24import java.util.LinkedList;25import java.util.Timer;26import org.eclipse.rap.rwt.testfixture.internal.Fixture;27import org.eclipse.rap.rwt.testfixture.internal.NoOpRunnable;28import org.junit.After;29import org.junit.Before;30import org.junit.Test;31import org.mockito.ArgumentCaptor;32public class TimerExecScheduler_Test {33 private TimerExecScheduler scheduler;34 private Display display;35 private Collection<Throwable> exceptions;36 private Timer timer;37 @Before38 public void setUp() {39 Fixture.setUp();40 display = new Display();41 timer = mock( Timer.class );42 scheduler = new TimerExecScheduler( display ) {43 @Override44 Timer createTimer() {45 return timer;46 }47 @Override48 TimerExecTask createTask( Runnable runnable ) {49 TimerExecTask task = mock( TimerExecTask.class );50 when( task.getRunnable() ).thenReturn( runnable );51 return task;52 }53 };54 exceptions = Collections.synchronizedList( new LinkedList<Throwable>() );55 }56 @After57 public void tearDown() {58 Fixture.tearDown();59 }60 @Test61 public void testSchedule_schedulesRunnable() {62 Runnable runnable = mock( Runnable.class );63 scheduler.schedule( 23, runnable );64 ArgumentCaptor<TimerExecTask> taskCaptor = ArgumentCaptor.forClass( TimerExecTask.class );65 verify( timer ).schedule( taskCaptor.capture(), eq( 23L ) );66 assertSame( runnable, taskCaptor.getValue().getRunnable() );67 }68 @Test69 public void testSchedule_reschedulesSameRunnable() {70 Runnable runnable = mock( Runnable.class );71 scheduler.schedule( 23, runnable );72 scheduler.schedule( 42, runnable );73 ArgumentCaptor<TimerExecTask> taskCaptor = ArgumentCaptor.forClass( TimerExecTask.class );74 verify( timer ).schedule( taskCaptor.capture(), eq( 23L ) );75 verify( timer ).schedule( taskCaptor.capture(), eq( 42L ) );76 assertSame( taskCaptor.getAllValues().get( 0 ), taskCaptor.getAllValues().get( 1 ) );77 }78 @Test79 public void testCancel_cancelsTask() {80 Runnable runnable = mock( Runnable.class );81 scheduler.schedule( 23, runnable );82 scheduler.cancel( runnable );83 ArgumentCaptor<TimerExecTask> taskCaptor = ArgumentCaptor.forClass( TimerExecTask.class );84 verify( timer ).schedule( taskCaptor.capture(), eq( 23L ) );85 verify( taskCaptor.getValue() ).cancel();86 }87 @Test88 public void testCancel_cancelNonExistingTaskDoesNotFail() {89 scheduler.cancel( mock( Runnable.class ) );90 }91 @Test92 public void testCancel_removesTask() {93 Runnable runnable = mock( Runnable.class );94 scheduler.schedule( 23, runnable );95 scheduler.cancel( runnable );96 scheduler.schedule( 42, runnable );97 ArgumentCaptor<TimerExecTask> taskCaptor = ArgumentCaptor.forClass( TimerExecTask.class );98 verify( timer ).schedule( taskCaptor.capture(), eq( 23L ) );99 verify( timer ).schedule( taskCaptor.capture(), eq( 42L ) );100 assertNotSame( taskCaptor.getAllValues().get( 0 ), taskCaptor.getAllValues().get( 1 ) );101 }102 @Test103 public void testSerializationIsThreadSafe() throws Exception {104 scheduler = new TimerExecScheduler( display );105 Runnable runnable = new Runnable() {106 public void run() {107 try {108 scheduler.schedule( 1, new NoOpRunnable() );109 } catch( Throwable thr ) {110 exceptions.add( thr );111 }112 }113 };114 Thread[] threads = startThreads( 10, runnable );115 for( int i = 0; i < 5; i++ ) {116 serialize( scheduler );117 }118 joinThreads( threads );...

Full Screen

Full Screen

Source:TimerServiceTest.java Github

copy

Full Screen

...30import static org.mockito.Mockito.mock;31import static org.mockito.Mockito.times;32import static org.mockito.Mockito.verify;33import static org.mockito.Mockito.when;34public class TimerServiceTest extends TestLogger {35 /**36 * Test all timeouts registered can be unregistered37 * @throws Exception38 */39 @Test40 @SuppressWarnings("unchecked")41 public void testUnregisterAllTimeouts() throws Exception {42 // Prepare all instances.43 ScheduledExecutorService scheduledExecutorService = mock(ScheduledExecutorService.class);44 ScheduledFuture scheduledFuture = mock(ScheduledFuture.class);45 when(scheduledExecutorService.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)))46 .thenReturn(scheduledFuture);47 TimerService<AllocationID> timerService = new TimerService<>(scheduledExecutorService, 100L);48 TimeoutListener<AllocationID> listener = mock(TimeoutListener.class);49 timerService.start(listener);50 // Invoke register and unregister.51 timerService.registerTimeout(new AllocationID(), 10, TimeUnit.SECONDS);52 timerService.registerTimeout(new AllocationID(), 10, TimeUnit.SECONDS);53 timerService.unregisterAllTimeouts();54 // Verify.55 Map<?, ?> timeouts = (Map<?, ?>) Whitebox.getInternalState(timerService, "timeouts");56 assertTrue(timeouts.isEmpty());57 verify(scheduledFuture, times(2)).cancel(true);58 }59}...

Full Screen

Full Screen

Timer

Using AI Code Generation

copy

Full Screen

1import org.mockito.internal.util.Timer;2public class TimerTest {3 public static void main(String[] args) {4 Timer timer = new Timer();5 timer.start();6 try {7 Thread.sleep(1000);8 } catch (InterruptedException e) {9 e.printStackTrace();10 }11 timer.stop();12 System.out.println("time taken: " + timer.getElapsedMillis());13 }14}

Full Screen

Full Screen

Timer

Using AI Code Generation

copy

Full Screen

1package org.mockito.internal.util;2import java.util.*;3public class TimerTest {4 public static void main(String args[]) {5 Timer timer = new Timer();6 timer.schedule(new TimerTask() {7 public void run() {8 System.out.println("Timer task executed.");9 }10 }, 1000);11 try {12 Thread.sleep(5000);13 } catch (InterruptedException e) {14 e.printStackTrace();15 }16 timer.cancel();17 }18}19Java | org.mockito.internal.util.Timer.schedule(TimerTask, long)20Java | org.mockito.internal.util.Timer.schedule(TimerTask, long, long)21Java | org.mockito.internal.util.Timer.schedule(TimerTask, Date)22Java | org.mockito.internal.util.Timer.schedule(TimerTask, Date, long)23Java | org.mockito.internal.util.Timer.scheduleAtFixedRate(TimerTask, long, long)24Java | org.mockito.internal.util.Timer.scheduleAtFixedRate(TimerTask, Date, long)25Java | org.mockito.internal.util.Timer.cancel()26Java | org.mockito.internal.util.Timer.purge()27Java | org.mockito.internal.util.TimerTask.run()28Java | org.mockito.internal.util.TimerTask.cancel()29Java | org.mockito.internal.util.TimerTask.scheduledExecutionTime()30Java | org.mockito.internal.util.TimerTask.equals(Object)31Java | org.mockito.internal.util.TimerTask.hashCode()32Java | org.mockito.internal.util.TimerTask.toString()33Java | org.mockito.internal.util.TimerTask.clone()34Java | org.mockito.internal.util.TimerTask.getPeriod()35Java | org.mockito.internal.util.TimerTask.setPeriod(long)36Java | org.mockito.internal.util.TimerTask.getInitialDelay()37Java | org.mockito.internal.util.TimerTask.setInitialDelay(long)38Java | org.mockito.internal.util.TimerTask.getExecutionTime()39Java | org.mockito.internal.util.TimerTask.setExecutionTime(long)40Java | org.mockito.internal.util.TimerTask.getRepeatCount()41Java | org.mockito.internal.util.TimerTask.setRepeatCount(long)42Java | org.mockito.internal.util.TimerTask.getRepeatInterval()43Java | org.mockito.internal.util.TimerTask.setRepeatInterval(long)44Java | org.mockito.internal.util.TimerTask.isFixedRate()45Java | org.mockito.internal.util.TimerTask.setFixedRate(boolean)46Java | org.mockito.internal.util.TimerTask.isCancelled()47Java | org.mockito.internal.util.TimerTask.setCancelled(boolean)

Full Screen

Full Screen

Timer

Using AI Code Generation

copy

Full Screen

1import org.mockito.internal.util.Timer;2import org.mockito.internal.util.TimerFactory;3public class 1 {4 public static void main(String[] args) {5 Timer timer = TimerFactory.getTimer();6 timer.start();7 timer.stop();8 System.out.println(timer.getDuration());9 }10}

Full Screen

Full Screen

Timer

Using AI Code Generation

copy

Full Screen

1import org.mockito.internal.util.Timer;2import java.util.concurrent.TimeUnit;3public class Main {4 public static void main(String[] args) {5 Timer timer = new Timer();6 timer.start();7 System.out.println("Timer started");8 timer.getDuration(TimeUnit.MILLISECONDS);9 System.out.println("Timer stopped");10 }11}12Java | TimerTask run() method13Java | TimerTask cancel() method14Java | TimerTask scheduledExecutionTime() method15Java | Timer schedule(TimerTask task, long delay) method16Java | Timer schedule(TimerTask task, Date time) method17Java | Timer schedule(TimerTask task, long delay, long period) method18Java | Timer schedule(TimerTask task, Date firstTime, long period) method19Java | Timer scheduleAtFixedRate(TimerTask task, long delay, long period) method20Java | Timer scheduleAtFixedRate(TimerTask task, Date firstTime, long period) method21Java | Timer cancel() method22Java | Timer purge() method23Java | Timer getDelay() method24Java | Timer getPeriod() method25Java | Timer getInitialDelay() method26Java | Timer getDelay(TimeUnit unit) method27Java | Timer getInitialDelay(TimeUnit unit) method28Java | Timer getPeriod(TimeUnit unit) method29Java | Timer getExecutionTime() method30Java | Timer getExecutionTime(TimeUnit unit) method31Java | Timer getExecutionCount() method32Java | Timer getExecutionState() method33Java | Timer getTaskCount() method34Java | Timer getRemainingDelay() method35Java | Timer getRemainingDelay(TimeUnit unit) method36Java | Timer getAverageExecutionTime() method37Java | Timer getAverageExecutionTime(TimeUnit unit) method38Java | Timer getTotalExecutionTime() method39Java | Timer getTotalExecutionTime(TimeUnit unit) method40Java | Timer getMaximumExecutionTime() method41Java | Timer getMaximumExecutionTime(TimeUnit unit) method42Java | Timer getMinimumExecutionTime() method43Java | Timer getMinimumExecutionTime(TimeUnit unit) method44Java | Timer getMaximumRemainingDelay() method45Java | Timer getMaximumRemainingDelay(TimeUnit unit) method46Java | Timer getMinimumRemainingDelay() method47Java | Timer getMinimumRemainingDelay(TimeUnit

Full Screen

Full Screen

Timer

Using AI Code Generation

copy

Full Screen

1import org.mockito.internal.util.Timer;2import static org.mockito.internal.util.Timer.*;3public class 1 {4 public static void main(String args[]) {5 Timer timer = new Timer();6 timer.start();7 timer.stop();8 System.out.println("Time taken: " + timer.getTotalTimeMillis());9 }10}

Full Screen

Full Screen

Timer

Using AI Code Generation

copy

Full Screen

1import org.mockito.internal.util.Timer;2import org.mockito.internal.util.Timer;3public class MyClass {4 public static void main(String[] args) {5 Timer timer = new Timer();6 timer.start();7 timer.stop();8 System.out.println(timer.getDuration());9 }10}

Full Screen

Full Screen

Timer

Using AI Code Generation

copy

Full Screen

1import org.mockito.internal.util.Timer;2import org.mockito.internal.util.TimerImpl;3import org.mockito.internal.util.TimerImpl.TimerListener;4import org.mockito.internal.util.TimerImpl.TimerListener;5public class 1 {6 public static void main(String[] args) {7 Timer timer = new TimerImpl();8 TimerListener timerListener = new TimerListener() {9 public void onTimerTick() {10 System.out.println("tick");11 }12 };13 timer.schedule(timerListener, 0, 1000);14 try {15 Thread.sleep(5000);16 } catch (InterruptedException e) {17 e.printStackTrace();18 }19 timer.cancel();20 }21}

Full Screen

Full Screen

Timer

Using AI Code Generation

copy

Full Screen

1import org.mockito.internal.util.Timer;2public class 1 {3 public static void main(String[] args) {4 Timer timer = new Timer();5 timer.start();6 timer.stop();7 System.out.println("Execution time: " + timer.getElapsedMillis());8 }9}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Mockito automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used methods in Timer

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful