@Test public void testCreateImageWithOptions() { Capture<Map<ComputeRpc.Option, Object>> capturedOptions = Capture.newInstance(); EasyMock.expect(computeRpcMock.createImage(eq(IMAGE.toPb()), capture(capturedOptions))) .andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.getService(); Operation operation = compute.create(IMAGE, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); assertEquals(23, selector.length()); assertEquals(globalOperation, operation); }
@After public void verifyMocks() { ctrl.verify(); ctrl.reset(); // Check capture created in the @Before method assertTrue(txConfigCapture.hasCaptured()); List<BaseTransactionConfig> txCfgs = txConfigCapture.getValues(); assertEquals(2, txCfgs.size()); // First backing store transaction should use default tx config assertEquals("default", txCfgs.get(0).getCustomOption(GraphDatabaseConfiguration.UNIQUE_INSTANCE_ID)); // Second backing store transaction should use global strong consistency config assertEquals("global", txCfgs.get(1).getCustomOption(GraphDatabaseConfiguration.UNIQUE_INSTANCE_ID)); // The order in which these transactions are opened isn't really significant; // testing them in order is kind of overspecifying the impl's behavior. // Could probably relax the ordering selectively here with some thought, but // I want to keep order checking on in general for the EasyMock control. }
/** * Used internally by the EasyMock framework to add a new captured value * * @param value * Value captured */ public void setValue(T value) { switch (type) { case NONE: break; case ALL: values.add(value); break; case FIRST: if (!hasCaptured()) { values.add(value); } break; case LAST: if (hasCaptured()) { reset(); } values.add(value); break; // ///CLOVER:OFF default: throw new IllegalArgumentException("Unknown capture type: " + type); // ///CLOVER:ON } }
final String errMsg = "some error"; final HttpServletRequest request = EasyMock.createStrictMock(HttpServletRequest.class); EasyMock.expect(request.getContentType()).andReturn(MediaType.APPLICATION_JSON).once(); EasyMock.expect(request.getRemoteAddr()).andReturn(ip).once(); final Capture<AuditInfo> auditInfoCapture = Capture.newInstance(); final LookupCoordinatorManager lookupCoordinatorManager = EasyMock.createStrictMock( LookupCoordinatorManager.class); Assert.assertTrue(auditInfoCapture.hasCaptured()); final AuditInfo auditInfo = auditInfoCapture.getValue(); Assert.assertEquals(author, auditInfo.getAuthor()); Assert.assertEquals(comment, auditInfo.getComment());
@Test public void testUploadFromByteArray() throws IOException { EasyMock.reset(mockS3); EasyMock.expect(mockS3.getRegion()).andReturn(Region.US_Standard); Capture<PutObjectRequest> por = new Capture<PutObjectRequest>(); EasyMock.expect(mockS3.putObject(EasyMock.capture(por))).andReturn(null); EasyMock.replay(mockS3); mapper.getS3ClientCache().useClient(mockS3); S3Link link = mapper.createS3Link(bucket, key); link.uploadFrom("Test".getBytes(StringUtils.UTF8)); ByteArrayOutputStream bos = new ByteArrayOutputStream(); InputStream is = por.getValue().getInputStream(); int currByte = -1; while ((currByte = is.read()) != -1) { bos.write(currByte); } assertArrayEquals(bos.toByteArray(), "Test".getBytes(StringUtils.UTF8)); EasyMock.verify(); }
Statement base = createMock("base", Statement.class); expect(log.getLevel()).andReturn(Level.OFF); log.setLevel(Level.FINE); expectLastCall().once(); final Capture<Handler> handlerCap = new Capture<>(); log.addHandler(capture(handlerCap)); expectLastCall().once(); base.evaluate(); expectLastCall()
@Test public void testStopSendingAfterClose() { replayOnSubscribe(); EasyMock.expect(session.getAsyncRemote()).andReturn(async).anyTimes(); final Capture<String> json = EasyMock.newCapture(CaptureType.ALL); async.sendText(EasyMock.capture(json), EasyMock.anyObject()); subscription.request(1); subscription.cancel(); EasyMock.replay(subscription, session, async); subscriber.onNext(ImmutableList.of(ImmutableMap.of("a", 1))); subscriber.close(); subscriber.onNext(ImmutableList.of(ImmutableMap.of("b", 2), ImmutableMap.of("c", 3))); assertEquals(ImmutableList.of("{\"a\":1}"), json.getValues()); EasyMock.verify(subscription, session, async); }
Schema writerSchema = Schema.create(Schema.Type.INT); AvroJob.setOutputKeySchema(job, writerSchema); TaskAttemptContext context = createMock(TaskAttemptContext.class); expect(context.getConfiguration()) .andReturn(job.getConfiguration()).anyTimes(); expect(context.getTaskAttemptID()) .andReturn(TaskAttemptID.forName("attempt_200707121733_0001_m_000000_0")) .anyTimes(); expect(context.getNumReduceTasks()).andReturn(1); Capture<CodecFactory> capturedCodecFactory = Capture.newInstance(); expect(recordWriterFactory.create(eq(writerSchema), anyObject(GenericData.class), = outputFormat.getRecordWriter(context); assertTrue(capturedCodecFactory.hasCaptured()); assertEquals(expectedCodec.toString(), capturedCodecFactory.getValue().toString()); verify(context);
@Test public void testSanity() throws Exception { replayOnSubscribe(); EasyMock.expect(session.getAsyncRemote()).andReturn(async).anyTimes(); final Capture<String> json = EasyMock.newCapture(CaptureType.ALL); async.sendText(EasyMock.capture(json), EasyMock.anyObject()); EasyMock.expectLastCall().times(3); subscription.request(1); EasyMock.expectLastCall().once(); session.close(EasyMock.anyObject()); EasyMock.expectLastCall().once(); subscription.cancel(); EasyMock.replay(subscription, session, async); subscriber.onNext(ImmutableList.of(ImmutableMap.of("a", 1), ImmutableMap.of("b", 2), ImmutableMap.of("c", 3))); assertEquals(ImmutableList.of("{\"a\":1}","{\"b\":2}","{\"c\":3}"), json.getValues()); subscriber.onComplete(); subscriber.close(); EasyMock.verify(subscription, session, async); }
private ClassicHttpResponse testRequestWithWeakETagValidatorIsNotAllowed(final String header) throws Exception { final Capture<ClassicHttpRequest> cap = EasyMock.newCapture(); EasyMock.expect( mockExecChain.proceed( EasyMock.capture(cap), EasyMock.isA(ExecChain.Scope.class))).andReturn(originResponse).times(0, 1); replayMocks(); final ClassicHttpResponse response = execute(request); verifyMocks(); // it's probably ok to return a 400 (Bad Request) to this client if (cap.hasCaptured()) { final ClassicHttpRequest forwarded = cap.getValue(); final Header h = forwarded.getFirstHeader(header); if (h != null) { Assert.assertFalse(h.getValue().startsWith("W/")); } } return response; }
@Test public void testRun() throws Exception HttpClient httpClient = EasyMock.createMock(HttpClient.class); final URL url = new URL("http://foo/druid/v2/"); Capture<Request> capturedRequest = EasyMock.newCapture(); EasyMock.expect( httpClient.go( EasyMock.capture(capturedRequest), .andReturn(futureResult) .times(1); .andReturn(futureException) .times(1); query = query.withOverriddenContext(ImmutableMap.of(DirectDruidClient.QUERY_FAIL_TIME, Long.MAX_VALUE)); Sequence s1 = client1.run(QueryPlus.wrap(query), defaultContext); Assert.assertTrue(capturedRequest.hasCaptured()); Assert.assertEquals(url, capturedRequest.getValue().getUrl()); Assert.assertEquals(HttpMethod.POST, capturedRequest.getValue().getMethod()); Assert.assertEquals(1, client1.getNumOpenConnections());
@Test public void testSaveAndRestore() throws IOException { expect(storageRpcMock.open(BLOB_INFO.toPb(), EMPTY_RPC_OPTIONS)).andReturn(UPLOAD_ID); Capture<byte[]> capturedBuffer = Capture.newInstance(CaptureType.ALL); Capture<Long> capturedPosition = Capture.newInstance(CaptureType.ALL); storageRpcMock.write( eq(UPLOAD_ID), capture(capturedBuffer), eq(0), captureLong(capturedPosition), eq(DEFAULT_CHUNK_SIZE), eq(false)); expectLastCall().times(2); replay(storageRpcMock); ByteBuffer buffer1 = randomBuffer(DEFAULT_CHUNK_SIZE); ByteBuffer buffer2 = randomBuffer(DEFAULT_CHUNK_SIZE); writer = new BlobWriteChannel(options, BLOB_INFO, EMPTY_RPC_OPTIONS); assertEquals(DEFAULT_CHUNK_SIZE, writer.write(buffer1)); assertArrayEquals(buffer1.array(), capturedBuffer.getValues().get(0)); assertEquals(new Long(0L), capturedPosition.getValues().get(0)); RestorableState<WriteChannel> writerState = writer.capture(); WriteChannel restoredWriter = writerState.restore(); assertEquals(DEFAULT_CHUNK_SIZE, restoredWriter.write(buffer2)); assertArrayEquals(buffer2.array(), capturedBuffer.getValues().get(1)); assertEquals(new Long(DEFAULT_CHUNK_SIZE), capturedPosition.getValues().get(1)); }
final Cache cache = EasyMock.createStrictMock(Cache.class); final Capture<Iterable<Cache.NamedKey>> cacheKeyCapture = EasyMock.newCapture(); EasyMock.expect(cache.getBulk(EasyMock.capture(cacheKeyCapture))) .andReturn(ImmutableMap.of()) .once(); EasyMock.replay(cache); client = makeClient(new ForegroundCachePopulator(JSON_MAPPER, new CachePopulatorStats(), -1), cache, limit); final DruidServer lastServer = servers[random.nextInt(servers.length)]; final DataSegment dataSegment = EasyMock.createNiceMock(DataSegment.class); EasyMock.expect(dataSegment.getId()).andReturn(SegmentId.dummy(DATA_SOURCE)).anyTimes(); EasyMock.replay(dataSegment); final ServerSelector selector = new ServerSelector( Assert.assertTrue("Capture cache keys", cacheKeyCapture.hasCaptured()); Assert.assertTrue("Cache key below limit", ImmutableList.copyOf(cacheKeyCapture.getValue()).size() <= limit); EasyMock.verify(cache); EasyMock.reset(cache); cacheKeyCapture.reset(); EasyMock.expect(cache.getBulk(EasyMock.capture(cacheKeyCapture))) .andReturn(ImmutableMap.of()) EasyMock.verify(cache); EasyMock.verify(dataSegment); Assert.assertTrue("Capture cache keys", cacheKeyCapture.hasCaptured()); Assert.assertTrue("Cache Keys empty", ImmutableList.copyOf(cacheKeyCapture.getValue()).isEmpty());
final String tier = "tier"; EasyMock.expect(druidServerConfig.getMaxSize()).andReturn(maxSize).once(); EasyMock.expect(segmentLoadDropMgr.getPendingDeleteSnapshot()).andReturn(ImmutableList.of(dataSegment)).once(); EasyMock.expect(druidServerConfig.getTier()).andReturn(tier).once(); EasyMock.expect(druidServerConfig.getPriority()).andReturn(priority).once(); EasyMock.expect(segmentManager.getDataSourceSizes()).andReturn(ImmutableMap.of(dataSource, size)); Assert.assertTrue(eventCapture.hasCaptured()); final List<Map<String, Object>> events = Lists.transform( eventCapture.getValues(), new Function<ServiceEventBuilder<ServiceMetricEvent>, Map<String, Object>>()
@Test public void testGetLicenseFromStringWithOptions() { Capture<Map<ComputeRpc.Option, Object>> capturedOptions = Capture.newInstance(); EasyMock.expect( computeRpcMock.getLicense( eq(PROJECT), eq(LICENSE_ID.getLicense()), capture(capturedOptions))) .andReturn(LICENSE.toPb()); EasyMock.replay(computeRpcMock); compute = options.getService(); License license = compute.getLicense(LICENSE_ID.getLicense(), LICENSE_OPTION_FIELDS); assertEquals(LICENSE, license); String selector = (String) capturedOptions.getValue().get(LICENSE_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("chargesUseFee")); assertEquals(22, selector.length()); assertEquals(LICENSE, license); }
final CountDownLatch queryIsRegistered = new CountDownLatch(1); Capture<ListenableFuture> capturedFuture = new Capture<>(); QueryWatcher watcher = EasyMock.createStrictMock(QueryWatcher.class); watcher.registerQuery( EasyMock.anyObject(), EasyMock.and(EasyMock.anyObject(), EasyMock.capture(capturedFuture)) ); EasyMock.expectLastCall() .andAnswer( new IAnswer<Void>() .once(); EasyMock.replay(watcher); queriesStarted.await(); Assert.assertTrue(capturedFuture.hasCaptured()); ListenableFuture future = capturedFuture.getValue();
new Random().nextBytes(bytes); final HttpEntity mockBody = EasyMock.createMockBuilder(ByteArrayEntity.class).withConstructor( new Object[] { bytes }).addMockedMethods("getContentLength").createNiceMock(); org.easymock.EasyMock.expect(mockBody.getContentLength()).andReturn(-1L).anyTimes(); post.setEntity(mockBody); final Capture<ClassicHttpRequest> reqCap = EasyMock.newCapture(); EasyMock.expect( mockExecChain.proceed( EasyMock.capture(reqCap), EasyMock.isA(ExecChain.Scope.class))).andReturn( originResponse).times(0, 1); EasyMock.verify(mockBody); if (reqCap.hasCaptured()) { final HttpRequest forwarded = reqCap.getValue(); Assert.assertNotNull(forwarded.getFirstHeader("Content-Length")); } else {
@SuppressWarnings("unchecked") @Test public void shouldCreateSessionWindowedStreamWithInactiviyGap() { EasyMock.expect(groupedStreamMock.windowedBy(EasyMock.capture(sessionWindows))).andReturn(sessionWindowed); EasyMock.expect(sessionWindowed.aggregate(same(initializer), same(aggregator), anyObject(Merger.class), same(materialized))).andReturn(null); EasyMock.replay(groupedStreamMock, aggregator, sessionWindowed); expression.applyAggregate(groupedStreamMock, initializer, aggregator, materialized); assertThat(sessionWindows.getValue().inactivityGap(), equalTo(5000L)); EasyMock.verify(groupedStreamMock); }
expect(server.getCapabilities()).andStubReturn(cap); expect(cap.getRequest()).andStubReturn(req); expect(req.getGetCapabilities()).andStubReturn(gcOpType); expect(gcOpType.getGet()) .andStubReturn( Sets.newHashSet(config.getLayers()), is(Sets.newHashSet(layerCapture.getValues()))); verify(server, cap, req, gcOpType, globalConfig);