src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
SelectorImpl extends Thread implements com.sun.corba.ee.spi.transport.Selector { @Transport public void registerForEvent(EventHandler eventHandler) { if (isClosed()) { closedEventHandler(); return; } if (eventHandler.shouldUseSelectThreadToWait()) { synchronized (deferredRegistrations) { deferredRegistr...
@Test public void whenRegisteringAcceptEventWithoutSelectThread_listenerThreadIsCreated() { eventHandler.setUseSelectThreadToWait(false); eventHandler.setInterestOps(SelectionKey.OP_ACCEPT); selector.registerForEvent(eventHandler); assertTrue(getWorkQueue().remove() instanceof ListenerThreadImpl); } @Test public void w...
SelectorImpl extends Thread implements com.sun.corba.ee.spi.transport.Selector { void runSelectionLoopOnce() throws IOException { beginSelect(); int n = 0; handleDeferredRegistrations(); enableInterestOps(); try { n = selector.select(timeout); } catch (IOException e) { display( "Exception in select:", e...
@Test public void whenIoAvailable_dispatchToEventHandler() throws IOException { registerEventHandler(); selectorStub.setReady(channel, SelectionKey.OP_READ); selector.runSelectionLoopOnce(); assertEquals(1, eventHandler.numInvocations); } @Test public void whenEventTimesOut_reportTimeout() throws IOException { register...
ConnectionImpl extends EventHandlerBase implements Connection, Work { public SocketChannel getSocketChannel() { return socketChannel; } ConnectionImpl(ORB orb); protected ConnectionImpl(ORB orb, boolean useSelectThreadToWait, boolean useWorkerThread); private ...
@Test(expected = RuntimeException.class) public void whenNioConfigureBlockingFails_throwException() throws IOException { SocketChannelFake socketChannel = getSocketChannel(); socketChannel.setFailToConfigureBlocking(); useNio(); }
IIOPProfileImpl extends IdentifiableBase implements IIOPProfile { @IsLocal public synchronized boolean isLocal() { if (!checkedIsLocal) { checkedIsLocal = true ; if (isForeignObject()) return false; final int port = proftemp.getPrimaryAddress().getPort(); final String host = proftemp.getPrimaryAddress().getHost() ; fin...
@Test public void whenForeignProfileOrbVersion_isLocalReturnsFalse() throws Exception { setOrbVersion(ORBVersionImpl.FOREIGN); assertThat(iiopProfile.isLocal(), is(false)); }
AnyImpl extends Any { public TypeCode type() { return typeCode; } AnyImpl(ORB orb); AnyImpl(ORB orb, Any obj); TypeCode type(); void type(TypeCode tc); @DynamicType boolean equal(Any otherAny); org.omg.CORBA.portable.OutputStream create_output_stream(); @DynamicType org.omg.CORBA.portable.InputStream create_input_stre...
@Test public void whenAnyCreated_typeIsNull() { assertEquals(TCKind.tk_null, any.type().kind()); }
AnyImpl extends Any { public byte extract_octet() { checkExtractBadOperation( TCKind._tk_octet ) ; return (byte)value; } AnyImpl(ORB orb); AnyImpl(ORB orb, Any obj); TypeCode type(); void type(TypeCode tc); @DynamicType boolean equal(Any otherAny); org.omg.CORBA.portable.OutputStream create_output_stream(); @DynamicTy...
@Test(expected = BAD_OPERATION.class) public void whenReadingUninitializedAny_throwException() { any.extract_octet(); }
PresentationDefaults { synchronized static PresentationManager.StubFactoryFactory getDynamicStubFactoryFactory() { if (dynamicImpl == null) dynamicImpl = new StubFactoryFactoryCodegenImpl(); return dynamicImpl ; } private PresentationDefaults(); synchronized static PresentationManager.StubFactoryFactory getStaticStubF...
@Test public void dynamicStubFactory_createsDynamicStubs() throws Exception { assertThat(PresentationDefaults.getDynamicStubFactoryFactory().createsDynamicStubs(), is(true)); }
PresentationDefaults { public synchronized static PresentationManager.StubFactoryFactory getStaticStubFactoryFactory() { if (staticImpl == null) staticImpl = new StubFactoryFactoryStaticImpl(); return staticImpl; } private PresentationDefaults(); synchronized static PresentationManager.StubFactoryFactory getStaticStub...
@Test public void staticStubFactory_doesNotCreateDynamicStubs() throws Exception { assertThat(PresentationDefaults.getStaticStubFactoryFactory().createsDynamicStubs(), is(false)); }
PresentationDefaults { public static PresentationManagerImpl makeOrbPresentationManager() { final boolean useDynamicStub = getBooleanPropertyValue( ORBConstants.USE_DYNAMIC_STUB_PROPERTY, inAppServer() ) ; final boolean debug = getBooleanPropertyValue( ORBConstants.DEBUG_DYNAMIC_STUB, false ) ; final PresentationManage...
@Test public void defaultOrbPresentationManager_createsDynamicStubs() throws Exception { assertThat(PresentationDefaults.makeOrbPresentationManager().useDynamicStubs(), is(true)); } @Test public void whenSystemPropertyFalse_presentationManagerCreatesStaticStubs() throws Exception { mementos.add(SystemPropertySupport.in...
Util { public static String getVersion () { return getVersion (DEFAULT_MESSAGE_RESOURCE); } static String getVersion(); static boolean isAttribute(String name, Hashtable symbolTable); static boolean isConst(String name, Hashtable symbolTable); static boolean isEnum(String name, Hashtable symbolTable); static boolean i...
@Test public void readVersionFromDefaultPropertyFile() throws Exception { assertThat(Util.getVersion(), containsString("4.02")); } @Test public void readVersionFromUnnamedPropertyFile() throws Exception { assertThat(Util.getVersion(""), containsString("4.02")); }
Util { public static String getMessage (String key) { if (messages == null) readMessages (); String message = messages.getProperty (key); if (message == null) message = getDefaultMessage (key); return message; } static String getVersion(); static boolean isAttribute(String name, Hashtable symbolTable); static boolean ...
@Test public void retrieveMessage() throws Exception { assertThat(Util.getMessage("EvaluationException.not"), equalTo("bitwise not")); } @Test public void substituteSingleParamMessage() throws Exception { assertThat(Util.getMessage("InvalidArgument.1", "zork"), equalTo("Invalid argument: zork.")); } @Test public void s...
AsmClassFactory implements ClassDefinitionFactory { static int getLatestVersion() { try { int latest = 0; for (Field field : Opcodes.class.getDeclaredFields()) { if (field.getName().startsWith("ASM") && field.getType().equals(int.class)) { latest = Math.max(latest, field.getInt(Opcodes.class)); } } return latest; } cat...
@Test public void canRetrieveLatestAsmVersion() { assertThat(AsmClassFactory.getLatestVersion(), equalTo(Opcodes.ASM6)); }
AdhocProject implements Project, FileOwnerQueryImplementation, ProjectConfiguration, ProjectActionPerformer, ActionProvider, LogicalViewProvider { @Override public FileObject getProjectDirectory() { return dir; } AdhocProject(FileObject dir, ProjectState state); @Override FileObject getProjectDirectory(...
@Test public void testGetProjectDirectory() { assertTrue(true); }
AdhocProject implements Project, FileOwnerQueryImplementation, ProjectConfiguration, ProjectActionPerformer, ActionProvider, LogicalViewProvider { @Override public Lookup getLookup() { return Lookups.fixed(this, aux, encodingQuery, ops, info, customizer); } AdhocProject(FileObject dir, ProjectState stat...
@Test public void testGetLookup() { assertNotNull(project.getLookup().lookup(Project.class)); assertNotNull(project.getLookup().lookup(AdhocProject.class)); assertNotNull(project.getLookup().lookup(ProjectInformation.class)); assertNotNull(project.getLookup().lookup(FileOwnerQueryImplementation.class)); assertNotNull(p...
AdhocProject implements Project, FileOwnerQueryImplementation, ProjectConfiguration, ProjectActionPerformer, ActionProvider, LogicalViewProvider { @Override public String getDisplayName() { return info.getDisplayName(); } AdhocProject(FileObject dir, ProjectState state); @Override FileObject getProjectD...
@Test public void testGetDisplayName() { assertEquals(name, project.getDisplayName()); }
AdhocProject implements Project, FileOwnerQueryImplementation, ProjectConfiguration, ProjectActionPerformer, ActionProvider, LogicalViewProvider { public Charset getEncoding() { try { Preferences p = preferences(false); if (p != null) { String name = p.get("charset", "UTF-8"); return Charset.forName(nam...
@Test public void testGetEncoding() { Charset ascii = Charset.forName("US-ASCII"); Charset utf8 = Charset.forName("UTF-8"); assertEquals(utf8, project.getEncoding()); project.setEncoding(ascii); assertEquals(ascii, project.getEncoding()); }
AdhocProject implements Project, FileOwnerQueryImplementation, ProjectConfiguration, ProjectActionPerformer, ActionProvider, LogicalViewProvider { public List<Favorite> favorites() { List<Favorite> favorites = new ArrayList<>(); try { Preferences forProject = preferences(false); if (forProject != null) ...
@Test public void testFavorites() { java.util.List<Favorite> favs = new ArrayList<>(); char[] chars = new char[]{'d', 'c', 'b', 'a'}; int ix = 1; for (char c : chars) { favs.add(new Favorite(ix *= 10, "foo/" + c)); } project.saveFavorites(favs); java.util.List<Favorite> nue = project.favorites(); assertEquals(new HashS...
AdhocProject implements Project, FileOwnerQueryImplementation, ProjectConfiguration, ProjectActionPerformer, ActionProvider, LogicalViewProvider { @Override public Node findPath(Node node, Object o) { AdhocProjectNode view = logicalView == null ? null : logicalView.get(); if (view != null) { view.findPa...
@Test public void testFindPath() { AdhocProjectNode pn = (AdhocProjectNode) project.createLogicalView(); assertNotNull(pn); Node[] nn = pn.getChildren().getNodes(true); assertNotNull(nn); assertEquals(3, nn.length); assertEquals("Favorites", nn[0].getName()); assertEquals("byType", nn[1].getName()); assertEquals("Sourc...
UserController { @GetMapping("/{userId}") public UserDto getUser(@PathVariable long userId) throws ApplicationException { User user = userService.getUser(userId); return userMapper.toUserDto(user); } UserController(UserMapper userMapper, UserService userService); @GetMapping("/{userId}") UserDto getUser(@PathVariable l...
@Test public void testGetUser() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/users/1").contentType(APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("id", Matchers.is(1))) .andExpect(MockMvcResultMatchers.jsonPath("screenName", Matchers.is(...
IdentityGenerator { public static long generate() { return generate(DEFAULT_SHARD_ID); } private IdentityGenerator(); static Instant extractInstant(long id); static byte extractShardId(long id); static long generate(); static long generate(byte shardId); static final byte DEFAULT_SHARD_ID; static final Instant EPOCH; ...
@Test @Ignore public void testCollision() throws Exception { ExecutorService executorService = Executors.newFixedThreadPool(100); final int NUM_IDS = 1_000_000; final ConcurrentMap<Long, AtomicInteger> collisionMap = new ConcurrentHashMap<Long, AtomicInteger>(NUM_IDS); for (int i = 0; i < NUM_IDS; i++) { executorServic...
IdentityGenerator { static long doGenerate(byte shardId, long time, int serial) { return (shardId & 0x7fL) << 56 | (time & 0xffffffffffL) << 16 | (serial & 0xffff); } private IdentityGenerator(); static Instant extractInstant(long id); static byte extractShardId(long id); static long generate(); static long generate(b...
@Test public void testDoGenerate_withSerial() { long id = IdentityGenerator.doGenerate((byte) 0, 0L, 1); assertEquals(1L, id); } @Test public void testDoGenerate_withShardId() { long id = IdentityGenerator.doGenerate((byte) 1, 0L, 0); assertEquals((long) 1L << 56, id); } @Test public void testDoGenerate_withTime() { lo...
IdentityGenerator { public static byte extractShardId(long id) { return (byte) ((id >>> 56) & 0x7fL); } private IdentityGenerator(); static Instant extractInstant(long id); static byte extractShardId(long id); static long generate(); static long generate(byte shardId); static final byte DEFAULT_SHARD_ID; static final ...
@Test public void testExtractShardId() { long id = IdentityGenerator.doGenerate(SHARD_ID, TIME_DIFF, 10); byte shardId = IdentityGenerator.extractShardId(id); assertEquals(SHARD_ID, shardId); }
IdentityGenerator { public static Instant extractInstant(long id) { long time = (id & 0xffffffffff0000L) >>> 16; return EPOCH.plusMillis(time); } private IdentityGenerator(); static Instant extractInstant(long id); static byte extractShardId(long id); static long generate(); static long generate(byte shardId); static ...
@Test public void testExtractInstant() { long id = IdentityGenerator.doGenerate(SHARD_ID, TIME_DIFF, 10); Instant instant = IdentityGenerator.extractInstant(id); assertEquals(INSTANT.getEpochSecond(), instant.getEpochSecond()); }
SceneStack implements Iterable<Scene> { boolean isEmpty() { return stack.isEmpty(); } SceneStack(@NonNull Callback callback); @Override Iterator<Scene> iterator(); }
@Test public void testIsEmpty() { assertTrue(stack.isEmpty()); stack.push(new TestScene()); assertFalse(stack.isEmpty()); stack.push(new TestScene()); assertFalse(stack.isEmpty()); stack.pop(); assertFalse(stack.isEmpty()); stack.pop(); assertTrue(stack.isEmpty()); }
SceneStack implements Iterable<Scene> { int size() { return stack.size(); } SceneStack(@NonNull Callback callback); @Override Iterator<Scene> iterator(); }
@Test public void testSize() { Scene scene1 = new TestScene(); Scene scene2 = new TestScene(); Scene scene3 = new TestScene(); assertEquals(0, stack.size()); stack.push(scene1); assertEquals(1, stack.size()); stack.pop(scene1); assertEquals(0, stack.size()); stack.push(scene2); stack.push(scene3); assertEquals(2, stack...
SceneStack implements Iterable<Scene> { @Nullable Scene peek() { return stack.peekFirst(); } SceneStack(@NonNull Callback callback); @Override Iterator<Scene> iterator(); }
@Test public void testPeek() { Scene scene1 = new TestScene(); Scene scene2 = new TestScene(); Scene scene3 = new TestScene(); assertEquals(null, stack.peek()); stack.push(scene1); assertEquals(scene1, stack.peek()); stack.push(scene2); assertEquals(scene2, stack.peek()); stack.push(scene3); assertEquals(scene3, stack....
SceneStack implements Iterable<Scene> { @Nullable Scene tail() { return stack.peekLast(); } SceneStack(@NonNull Callback callback); @Override Iterator<Scene> iterator(); }
@Test public void testTail() { Scene scene1 = new TestScene(); Scene scene2 = new TestScene(); Scene scene3 = new TestScene(); assertEquals(null, stack.tail()); stack.push(scene1); assertEquals(scene1, stack.tail()); stack.push(scene2); assertEquals(scene1, stack.tail()); stack.push(scene3); assertEquals(scene1, stack....
Stage implements Iterable<Scene> { @Nullable public Scene getTopScene() { return stack.peek(); } Stage(Director director); void popTopScene(); void pushScene(@NonNull Scene scene); void replaceTopScene(@NonNull Scene scene); void setRootScene(@NonNull Scene scene); boolean hasCurtainRunning(); void completeRunningCurta...
@Test public void testGetTopScene() { Scene scene1 = new TestScene(); Scene scene2 = new TestScene(); assertNull(stage.getTopScene()); stage.pushScene(scene1); assertEquals(scene1, stage.getTopScene()); stage.pushScene(scene2); assertEquals(scene2, stage.getTopScene()); }
Stage implements Iterable<Scene> { @Nullable public Scene getRootScene() { return stack.tail(); } Stage(Director director); void popTopScene(); void pushScene(@NonNull Scene scene); void replaceTopScene(@NonNull Scene scene); void setRootScene(@NonNull Scene scene); boolean hasCurtainRunning(); void completeRunningCurt...
@Test public void testGetRootScene() { Scene scene1 = new TestScene(); Scene scene2 = new TestScene(); assertNull(stage.getRootScene()); stage.pushScene(scene1); assertEquals(scene1, stage.getRootScene()); stage.pushScene(scene2); assertEquals(scene1, stage.getRootScene()); }
Stage implements Iterable<Scene> { public int getSceneCount() { return stack.size(); } Stage(Director director); void popTopScene(); void pushScene(@NonNull Scene scene); void replaceTopScene(@NonNull Scene scene); void setRootScene(@NonNull Scene scene); boolean hasCurtainRunning(); void completeRunningCurtain(); bool...
@Test public void testGetSceneCount() { Scene scene1 = new TestScene(); Scene scene2 = new TestScene(); assertEquals(0, stage.getSceneCount()); stage.pushScene(scene1); assertEquals(1, stage.getSceneCount()); stage.pushScene(scene2); assertEquals(2, stage.getSceneCount()); stage.popScene(scene1); assertEquals(1, stage....
Scene { public void recreateView() { if (view == null) { return; } boolean resumed = false; boolean started = false; int index = -1; if (lifecycleState.isResumed()) { resumed = true; pause(); } if (lifecycleState.isStarted()) { started = true; stop(); } if (lifecycleState.isViewAttached()) { index = stage.getContainer(...
@Test public void testRecreateView() { stage.start(); stage.resume(); Scene scene1 = new TestScene(); stage.pushScene(scene1); Scene scene2 = new TestScene(); stage.pushScene(scene2); assertEquals(true, scene2.getLifecycleState().isResumed()); int hashCode1 = scene2.getView().hashCode(); scene2.recreateView(); assertEq...
Director implements Iterable<Stage> { @Nullable public Scene findSceneById(int sceneId) { for(int i = 0, n = stageMap.size(); i < n; i++) { Stage stage = stageMap.valueAt(i); Scene result = stage.findSceneById(sceneId); if (result != null) { return result; } } return null; } Director(); @NonNull static Director hire(@N...
@Test public void testFindSceneById() { ViewGroup container1 = new TestContainer(RuntimeEnvironment.application); ViewGroup container2 = new TestContainer(RuntimeEnvironment.application); @IdRes int containerId1 = 1; @IdRes int containerId2 = 2; container1.setId(containerId1); container2.setId(containerId2); Stage stag...
Director implements Iterable<Stage> { @NonNull public Stage direct(@NonNull ViewGroup container) { return direct(container, container.getId()); } Director(); @NonNull static Director hire(@NonNull Activity activity, @Nullable Bundle savedInstanceState); boolean contains(int id); @Nullable Stage get(int id); @NonNull St...
@Test public void testTarget() { ViewGroup container1 = new TestContainer(RuntimeEnvironment.application); ViewGroup container2 = new TestContainer(RuntimeEnvironment.application); @IdRes int containerId1 = 1; @IdRes int containerId2 = 2; container1.setId(containerId1); container2.setId(containerId2); Stage stage1 = di...
SpydraArgument { public static SpydraArgument merge(SpydraArgument first, SpydraArgument second) { if (first == null) { return second; } else if (second == null) { return first; } SpydraArgument merged = new SpydraArgument(); if (second.clientId.isPresent()) { merged.clientId = second.clientId; } else { merged.clientId...
@Test public void testMergeEmptyArguments() { SpydraArgument first = new SpydraArgument(); SpydraArgument second = new SpydraArgument(); SpydraArgument merged = SpydraArgument.merge(first, second); Assert.assertNotNull(merged); }
RunJhsCliParser implements CliParser<RunJhsCommand> { @Override public RunJhsCommand parse(String[] args) { DefaultParser parser = new DefaultParser(); CommandLine cmdLine; cmdLine = CliHelper.tryParse(parser, options, args); return RunJhsCommand.builder() .clientId(cmdLine.getOptionValue(CliConsts.CLIENT_ID_OPTION_NAM...
@Test public void testParseWithoutUser() { RunJhsCommand jhsCmd = PARSER.parse(new String[]{ CliTestHelpers.toStrOpt(CliConsts.CLIENT_ID_OPTION_NAME, DUMMY_CLIENT_ID), CliTestHelpers.toStrOpt(CliConsts.LOG_BUCKET_OPTION_NAME, DUMMY_BUCKET) }); assertEquals(jhsCmd.clientId(), DUMMY_CLIENT_ID); } @Test public void testPa...
DumpHistoryCliParser implements CliParser<DumpHistoryCommand> { @Override public DumpHistoryCommand parse(String[] args) { DefaultParser parser = new DefaultParser(); CommandLine cmdLine; cmdLine = CliHelper.tryParse(parser, options, args); return DumpHistoryCommand.builder() .clientId(cmdLine.getOptionValue(CliConsts....
@Test public void testParse() { DumpHistoryCommand dumpCmd = PARSER.parse(new String[]{ CliTestHelpers.toStrOpt(CliConsts.JOB_ID_OPTION_NAME, DUMMY_APP_ID), CliTestHelpers.toStrOpt(CliConsts.CLIENT_ID_OPTION_NAME, DUMMY_CLIENT_ID), CliTestHelpers.toStrOpt(CliConsts.LOG_BUCKET_OPTION_NAME, DUMMY_BUCKET) }); assertEquals...
HistoryLogUtils { public static Configuration generateHadoopConfig( String clientId, String username, String bucket) { Configuration cfg = new Configuration(false); cfg.addResource(HISTORY_LOG_CONFIG_NAME); cfg.reloadConfiguration(); cfg.set(SPYDRA_HISTORY_CLIENT_ID_PROPERTY, clientId); cfg.set(SPYDRA_HISTORY_USERNAME_...
@Test public void testGenerateHadoopConfig() throws Exception { Configuration cfg = HistoryLogUtils.generateHadoopConfig(DUMMY_CLIENT_ID, DUMMY_USER_NAME, DUMMY_BUCKET); checkPropertySubstitution(this.configWithoutSubstitute, cfg, YarnConfiguration.NM_REMOTE_APP_LOG_DIR, "gs: checkPropertySubstitution(this.configWithou...
HistoryLogUtils { public static Optional<String> findHistoryFilePath( FileSystem fs, String historyDirPrefix, ApplicationId applicationId) throws IOException, URISyntaxException { Path jhistPathPattern = new Path(historyDirPrefix); return findHistoryFilePath( new RemoteIteratorAdaptor<>(fs.listFiles(jhistPathPattern, t...
@Test public void testFindHistoryFilePath() throws Exception { final Iterator<LocatedFileStatus> mockListing = Arrays.asList( mockFileStatus("/foobar.jhist"), mockFileStatus("/barbaz.jhist"), mockFileStatus("/a.log"), mockFileStatus("/" + DUMMY_JHIST_NAME)) .iterator(); Optional<String> jHistFile = HistoryLogUtils.find...
OnPremiseExecutor implements Executor { @VisibleForTesting List<String> getCommand(SpydraArgument arguments) { addBaseCommand(); if (arguments.getSubmit().getOptions().containsKey(OPTION_JAR)) { addArgument(arguments.getSubmit().getOptions().get(OPTION_JAR)); } if (arguments.getSubmit().getOptions().containsKey(OPTION_...
@Test public void testGetCommand() { String jarPath = "jarPath"; List<String> args = new ArrayList<>(); args.add("arg1"); String mainClass = "mainClass"; String[] properties = new String[]{ "propertyName0=propertyValue0", "propertyName1=propertyValue1"}; SpydraArgument arguments = new SpydraArgument(); arguments.getSub...
ClusterPlacement { static ClusterPlacement from(String token) { String[] splits = token.split("-"); if (splits.length != 2) { throw new IllegalArgumentException("Could not parse token: " + token); } try { return new ClusterPlacementBuilder() .clusterNumber(Integer.valueOf(splits[0])) .clusterGeneration(Long.valueOf(spl...
@Test public void testFrom() { ClusterPlacement clusterPlacement = ClusterPlacement.from("10-15"); assertThat(clusterPlacement.clusterNumber(), is(10)); assertThat(clusterPlacement.clusterGeneration(), is(15L)); }
ClusterPlacement { String token() { return String.format("%s-%s", clusterNumber(), clusterGeneration()); } Optional<Cluster> findIn(List<Cluster> clusters); }
@Test public void testToken() { final ClusterPlacement clusterPlacement = new ClusterPlacementBuilder().clusterNumber(10).clusterGeneration(15L).build(); assertThat(clusterPlacement.token(), is("10-15")); }
ClusterPlacement { static List<Cluster> filterClusters( List<Cluster> clusters, List<ClusterPlacement> allPlacements) { Set<String> clusterPlacements = allPlacements.stream() .map(ClusterPlacement::token) .collect(toSet()); return clusters.stream() .filter(cluster -> clusterPlacements.contains(placement(cluster).token(...
@Test public void testFilterClusters() { final List<ClusterPlacement> clusterPlacements = Arrays.asList(new ClusterPlacementBuilder().clusterNumber(0).clusterGeneration(1).build(), new ClusterPlacementBuilder().clusterNumber(1).clusterGeneration(1).build(), new ClusterPlacementBuilder().clusterNumber(2).clusterGenerati...
ClusterPlacement { public Optional<Cluster> findIn(List<Cluster> clusters) { return clusters.stream() .filter(cluster -> this.equals(placement(cluster))) .findFirst(); } Optional<Cluster> findIn(List<Cluster> clusters); }
@Test public void testFindIn() { final ClusterPlacement missingPlacement = new ClusterPlacementBuilder().clusterNumber(0).clusterGeneration(0).build(); final ClusterPlacement existingPlacement = new ClusterPlacementBuilder().clusterNumber(0).clusterGeneration(1).build(); final Cluster cluster1 = new Cluster(); cluster1...
DynamicSubmitter extends Submitter { public boolean releaseCluster(SpydraArgument arguments, DataprocApi dataprocApi) throws IOException { try { waitForHistoryToBeMoved(arguments); } finally { return dataprocApi.deleteCluster(arguments); } } DynamicSubmitter(); DynamicSubmitter(DataprocApi dataprocApi, GcpUtils gcpUti...
@Test public void releaseErrorCluster() throws Exception { List<Cluster> clusters = Arrays.asList(errorCluster(), errorCluster()); SpydraArgument.Pooling pooling = new SpydraArgument.Pooling(); arguments.setPooling(pooling); arguments.setClientId(clientId); arguments.cluster.setName(spydraClusterName); when(dataprocApi...
SubmissionCliParser implements CliParser<SpydraArgument> { public SpydraArgument parse(String[] args) throws IOException { DefaultParser parser = new DefaultParser(); CommandLine cmdLine; cmdLine = CliHelper.tryParse(parser, options, args); SpydraArgument spydraArgument = new SpydraArgument(); if (cmdLine.hasOption(Cli...
@Test public void testMultipleSpydraJson() throws IOException { File jsonFile1 = temporaryFolder.newFile("spydra1.json"); File jsonFile2 = temporaryFolder.newFile("spydra2.json"); JsonHelper.objectMapper().writeValue(jsonFile1, new HashMap<String, Map<String, Map<String, String>>>() {{ put("cluster", singletonMap("opti...
DumpLogsCliParser implements CliParser<DumpLogsCommand> { @Override public DumpLogsCommand parse(String[] args) { DefaultParser parser = new DefaultParser(); CommandLine cmdLine; cmdLine = CliHelper.tryParse(parser, options, args); return DumpLogsCommand.builder() .clientId(cmdLine.getOptionValue(CliConsts.CLIENT_ID_OP...
@Test public void testParse() { DumpLogsCommand dumpCmd = PARSER.parse(new String[]{ CliTestHelpers.toStrOpt(CliConsts.JOB_ID_OPTION_NAME, DUMMY_APP_ID), CliTestHelpers.toStrOpt(CliConsts.CLIENT_ID_OPTION_NAME, DUMMY_CLIENT_ID), CliTestHelpers.toStrOpt(CliConsts.USERNAME_OPTION_NAME, DUMMY_USER), CliTestHelpers.toStrOp...
BookController { @DeleteMapping("/{id}") public void delete(@PathVariable Long id) { System.out.println(id); bookService.delete(id); } @GetMapping // @JsonView(BookListView.class) @ApiOperation("查询图书信息") Page<BookInfo> query(BookCondition condition, Pageable pageable); @GetMapping("/{id}") // @JsonView(BookDetailView....
@Test public void whenDeleteSuccess() throws Exception { mockMvc.perform(delete("/book/1").contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); }
Packer implements Writable, MessageFormatter { @Override public void writeBinary(byte[] binary, int offset, int length) { writeBinaryHeader(length); buffer.put(binary, offset, length); } Packer(Codec codec, ByteBufferConsumer sink, ByteBuffer buffer, boolean manualReset); Packer(Codec codec, ByteBufferConsumer sink, B...
@Test public void testWriteBinary() { final byte[] data = new byte[] {1, 2, 3, 4}; MessageFormatter messageFormatter = new Packer( new ByteBufferConsumer() { @Override public void accept(int messageCount, ByteBuffer buffy) { MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(buffy); try { assertEquals(1, unpacke...
OpenJdkOngoingRecording implements OngoingRecording { @Override public OpenJdkRecordingData snapshot(final Instant start, final Instant end) { if (recording.getState() != RecordingState.RUNNING) { throw new IllegalStateException("Cannot snapshot recording that is not running"); } final Recording snapshot = FlightRecord...
@Test public void testSnapshot() { final OpenJdkRecordingData recordingData = ongoingRecording.snapshot(start, end); assertEquals(TEST_NAME, recordingData.getName()); assertEquals(start, recordingData.getStart()); assertEquals(end, recordingData.getEnd()); assertNotEquals( recording, recordingData.getRecording(), "make...
OpenJdkOngoingRecording implements OngoingRecording { @Override public void close() { recording.close(); } OpenJdkOngoingRecording(final Recording recording); @Override OpenJdkRecordingData stop(); @Override OpenJdkRecordingData snapshot(final Instant start, final Instant end); @Override void close(); }
@Test public void testClose() { ongoingRecording.close(); verify(recording).close(); }
OpenJdkController implements Controller { @Override public OpenJdkOngoingRecording createRecording(final String recordingName) { final Recording recording = new Recording(); recording.setName(recordingName); recording.setSettings(recordingSettings); recording.setMaxSize(RECORDING_MAX_SIZE); recording.setMaxAge(RECORDIN...
@Test public void testCreateContinuousRecording() throws IOException { final Recording recording = controller.createRecording(TEST_NAME).stop().getRecording(); assertEquals(TEST_NAME, recording.getName()); assertEquals( JfpUtils.readNamedJfpResource(OpenJdkController.JFP, OVERRIDES), recording.getSettings()); assertEqu...
OpenJdkRecordingData implements RecordingData { @Override public InputStream getStream() throws IOException { return recording.getStream(start, end); } OpenJdkRecordingData(final Recording recording); OpenJdkRecordingData(final Recording recording, final Instant start, final Instant end); @Override InputStream getStr...
@Test public void testGetStream() throws IOException { assertEquals(stream, recordingData.getStream()); } @Test public void testCustomGetStream() throws IOException { assertEquals(customStream, customRecordingData.getStream()); }
OpenJdkRecordingData implements RecordingData { @Override public void release() { recording.close(); } OpenJdkRecordingData(final Recording recording); OpenJdkRecordingData(final Recording recording, final Instant start, final Instant end); @Override InputStream getStream(); @Override void release(); @Override String...
@Test public void testRelease() { recordingData.release(); verify(recording).close(); }
OpenJdkRecordingData implements RecordingData { @Override public String getName() { return recording.getName(); } OpenJdkRecordingData(final Recording recording); OpenJdkRecordingData(final Recording recording, final Instant start, final Instant end); @Override InputStream getStream(); @Override void release(); @Over...
@Test public void testGetName() { assertEquals(TEST_NAME, recordingData.getName()); }
OpenJdkRecordingData implements RecordingData { @Override public String toString() { return "OpenJdkRecording: " + getName(); } OpenJdkRecordingData(final Recording recording); OpenJdkRecordingData(final Recording recording, final Instant start, final Instant end); @Override InputStream getStream(); @Override void re...
@Test public void testToString() { assertThat(recordingData.toString(), containsString(TEST_NAME)); }
OpenJdkRecordingData implements RecordingData { @Override public Instant getStart() { return start; } OpenJdkRecordingData(final Recording recording); OpenJdkRecordingData(final Recording recording, final Instant start, final Instant end); @Override InputStream getStream(); @Override void release(); @Override String ...
@Test public void testGetStart() { assertEquals(start, recordingData.getStart()); } @Test public void testCustomGetStart() { assertEquals(customStart, customRecordingData.getStart()); }
OpenJdkRecordingData implements RecordingData { @Override public Instant getEnd() { return end; } OpenJdkRecordingData(final Recording recording); OpenJdkRecordingData(final Recording recording, final Instant start, final Instant end); @Override InputStream getStream(); @Override void release(); @Override String getN...
@Test public void testGetEnd() { assertEquals(end, recordingData.getEnd()); } @Test public void testCustomGetEnd() { assertEquals(customEnd, customRecordingData.getEnd()); }
Packer implements Writable, MessageFormatter { @Override public void writeNull() { buffer.put(NULL); } Packer(Codec codec, ByteBufferConsumer sink, ByteBuffer buffer, boolean manualReset); Packer(Codec codec, ByteBufferConsumer sink, ByteBuffer buffer); Packer(ByteBufferConsumer sink, ByteBuffer buffer); Packer(Byte...
@Test public void testWriteNull() { MessageFormatter messageFormatter = new Packer( new ByteBufferConsumer() { @Override public void accept(int messageCount, ByteBuffer buffy) { MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(buffy); try { assertEquals(1, unpacker.unpackArrayHeader()); unpacker.unpackNil(); }...
OpenJdkRecordingData implements RecordingData { Recording getRecording() { return recording; } OpenJdkRecordingData(final Recording recording); OpenJdkRecordingData(final Recording recording, final Instant start, final Instant end); @Override InputStream getStream(); @Override void release(); @Override String getName...
@Test public void getRecording() { assertEquals(recording, recordingData.getRecording()); }
DeadlockEventFactory { final List<? extends Event> collectEvents() { if (!isDeadlockEventEnabled()) { return Collections.emptyList(); } long[] locked = threadMXBean.findDeadlockedThreads(); if (locked == null) { return Collections.emptyList(); } long id = deadlockCounter.getAndIncrement(); List<Event> events = new Arra...
@Test void collectEvents() throws Exception { assertNoDeadlocks(); int deadlocked = setupMonitorDeadlock(); assertDeadlock(true, deadlocked); deadlocked += setupSynchronizableDeadlock(); assertDeadlock(false, deadlocked); assertEquals( 1, disabledDetailsEventFactory.collectEvents().stream() .filter(e -> e instanceof De...
JfpUtils { public static Map<String, String> readNamedJfpResource( final String name, final String overridesFile) throws IOException { final Map<String, String> result; try (final InputStream stream = getNamedResource(name)) { result = readJfpFile(stream); } if (overridesFile != null) { try (final InputStream stream = ...
@Test public void testLoadingContinuousConfig() throws IOException { final Map<String, String> config = JfpUtils.readNamedJfpResource(OpenJdkController.JFP, null); assertEquals("true", config.get(CONFIG_ENTRY)); assertNull(config.get(CONFIG_OVERRIDE_ENTRY)); } @Test public void testLoadingContinuousConfigWithOverride()...
StreamUtils { public static <T> T readStream( final InputStream is, final int expectedSize, final BytesConsumer<T> consumer) throws IOException { final byte[] bytes = new byte[expectedSize]; int remaining = expectedSize; while (remaining > 0) { final int offset = expectedSize - remaining; final int read = is.read(bytes...
@Test public void readStreamNoCompression() throws IOException { final int expectedSize = 1; final byte[] bytes = StreamUtils.readStream(testRecordingStream(), expectedSize, CONSUME_TO_BYTES); assertArrayEquals(testRecordingBytes, bytes); } @Test public void readStreamNoCompressionLargeExpectedSize() throws IOException...
StreamUtils { public static <T> T gzipStream( InputStream is, final int expectedSize, final BytesConsumer<T> consumer) throws IOException { is = ensureMarkSupported(is); if (isCompressed(is)) { return readStream(is, expectedSize, consumer); } else { final FastByteArrayOutputStream baos = new FastByteArrayOutputStream(e...
@Test public void gzipStream() throws IOException { final int expectedSize = 1; final byte[] gzippedBytes = StreamUtils.gzipStream(testRecordingStream(), expectedSize, CONSUME_TO_BYTES); assertArrayEquals(testRecordingBytes, uncompressGzip(gzippedBytes)); } @Test public void gzipStreamLargeExpectedSize() throws IOExcep...
Packer implements Writable, MessageFormatter { @Override public void writeBoolean(boolean value) { buffer.put(value ? TRUE : FALSE); } Packer(Codec codec, ByteBufferConsumer sink, ByteBuffer buffer, boolean manualReset); Packer(Codec codec, ByteBufferConsumer sink, ByteBuffer buffer); Packer(ByteBufferConsumer sink, ...
@Test public void testWriteBoolean() { MessageFormatter messageFormatter = new Packer( new ByteBufferConsumer() { @Override public void accept(int messageCount, ByteBuffer buffy) { MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(buffy); try { assertEquals(1, unpacker.unpackArrayHeader()); assertTrue(unpacker....
StreamUtils { public static <T> T lz4Stream( InputStream is, final int expectedSize, final BytesConsumer<T> consumer) throws IOException { is = ensureMarkSupported(is); if (isCompressed(is)) { return readStream(is, expectedSize, consumer); } else { final FastByteArrayOutputStream baos = new FastByteArrayOutputStream(ex...
@Test public void lz4Stream() throws IOException { final int expectedSize = 1; final byte[] gzippedBytes = StreamUtils.lz4Stream(testRecordingStream(), expectedSize, CONSUME_TO_BYTES); assertArrayEquals(testRecordingBytes, uncompressLz4(gzippedBytes)); } @Test public void lz4StreamLargeExpectedSize() throws IOException...
ProfileUploader { public void upload(final RecordingType type, final RecordingData data) { try { if (canEnqueueMoreRequests()) { makeUploadRequest(type, data); } else { log.warn("Cannot upload profile data: too many enqueued requests!"); } } catch (final IllegalStateException | IOException e) { log.warn("Problem upload...
@Test public void testRequestWithContainerId() throws IOException, InterruptedException { uploader = new ProfileUploader(config, ratelimitedLogger, "container-id"); server.enqueue(new MockResponse().setResponseCode(200)); uploader.upload(RECORDING_TYPE, mockRecordingData(RECORDING_RESOURCE)); final RecordedRequest requ...
ConstantPool { public T get(int index) { return index < 0 ? null : reverseIndexMap.get(index); } ConstantPool(); ConstantPool(int startingIndex); T get(int index); int getOrInsert(T constant); void insert(int ptr, T constant); int size(); }
@Test void getByIndexEmpty() { assertNull(instance.get(-1)); assertNull(instance.get(0)); }
ProfileUploader { OkHttpClient getClient() { return client; } ProfileUploader(final Config config); ProfileUploader( final Config config, final RatelimitedLogger ratelimitedLogger, final String containerId); void upload(final RecordingType type, final RecordingData data); void shutdown(); }
@Test void testOkHttpClientForcesCleartextConnspecWhenNotUsingTLS() { when(config.getFinalProfilingUrl()).thenReturn("http: uploader = new ProfileUploader(config); final List<ConnectionSpec> connectionSpecs = uploader.getClient().connectionSpecs(); assertEquals(connectionSpecs.size(), 1); assertTrue(connectionSpecs.con...
ConstantPool { public void insert(int ptr, T constant) { if (constant == null) { if (ptr != -1) { throw new IllegalArgumentException(); } return; } indexMap.put(constant, ptr); reverseIndexMap.put(ptr, constant); offset = Math.max(offset, ptr + 1); } ConstantPool(); ConstantPool(int startingIndex); T get(int index); ...
@Test void insertInvalid() { assertThrows(IllegalArgumentException.class, () -> instance.insert(1, null)); } @Test void insertNull() { assertDoesNotThrow(() -> instance.insert(-1, null)); }
ProfileUploader { public void shutdown() { okHttpExecutorService.shutdownNow(); try { okHttpExecutorService.awaitTermination(TERMINATION_TIMEOUT, TimeUnit.SECONDS); } catch (final InterruptedException e) { log.warn("Wait for executor shutdown interrupted"); } client.connectionPool().evictAll(); } ProfileUploader(final ...
@Test public void testShutdown() throws IOException, InterruptedException { uploader.shutdown(); final RecordingData recording = mockRecordingData(RECORDING_RESOURCE); uploader.upload(RECORDING_TYPE, recording); assertNull(server.takeRequest(100, TimeUnit.MILLISECONDS), "No more requests"); verify(recording.getStream()...
ProfilingThreadFactory implements ThreadFactory { @Override public Thread newThread(final Runnable r) { final Thread t = new Thread(THREAD_GROUP, r, name); t.setDaemon(true); return t; } ProfilingThreadFactory(final String name); @Override Thread newThread(final Runnable r); }
@Test public void testThreadName() { final Thread thread = factory.newThread(() -> {}); assertEquals("test-name", thread.getName()); }
ControllerFactory { public static Controller createController(final Config config) throws UnsupportedEnvironmentException, ConfigurationException { try { Class.forName("com.oracle.jrockit.jfr.Producer"); throw new UnsupportedEnvironmentException( "Not enabling profiling; it requires Oracle Java 11+."); } catch (final C...
@Test @EnabledOnJre({JAVA_8}) public void testCreateControllerJava8() { final UnsupportedEnvironmentException unsupportedEnvironmentException = assertThrows( UnsupportedEnvironmentException.class, () -> { ControllerFactory.createController(config); }); String expected = "Not enabling profiling; it requires OpenJDK 11+,...
ProfilingSystem { public final void shutdown() { executorService.shutdownNow(); try { executorService.awaitTermination(TERMINATION_TIMEOUT, TimeUnit.SECONDS); } catch (final InterruptedException e) { log.error("Wait for executor shutdown interrupted"); } if (recording != null) { recording.close(); } started = false; } ...
@Test public void testShutdown() throws ConfigurationException { final ProfilingSystem system = new ProfilingSystem( controller, listener, Duration.ofMillis(10), Duration.ZERO, Duration.ofMillis(300), false, pool, threadLocalRandom); startProfilingSystem(system); verify(controller).createRecording(any()); system.shutdo...
ProfilingSystem { final Duration getStartupDelay() { return startupDelay; } ProfilingSystem( final Controller controller, final RecordingDataListener dataListener, final Duration startupDelay, final Duration startupDelayRandomRange, final Duration uploadPeriod, final boolean isStarti...
@Test public void testRandomizedStartupDelay() throws ConfigurationException { final Duration startupDelay = Duration.ofMillis(100); final Duration startupDelayRandomRange = Duration.ofMillis(500); final Duration additionalRandomDelay = Duration.ofMillis(300); when(threadLocalRandom.nextLong(startupDelayRandomRange.toM...
ConstantPool { public int size() { return indexMap.size(); } ConstantPool(); ConstantPool(int startingIndex); T get(int index); int getOrInsert(T constant); void insert(int ptr, T constant); int size(); }
@Test void size() { String value1 = "test1"; String value2 = "test2"; assertEquals(0, instance.size()); instance.insert(0, value1); assertEquals(1, instance.size()); instance.getOrInsert(value1); assertEquals(1, instance.size()); instance.getOrInsert(value2); assertEquals(2, instance.size()); }
AbstractLEB128Writer implements LEB128Writer { static int getPackedIntLen(long data) { if ((data & COMPRESSED_INT_MASK) == 0) { return 1; } data >>= 7; if ((data & COMPRESSED_INT_MASK) == 0) { return 2; } data >>= 7; if ((data & COMPRESSED_INT_MASK) == 0) { return 3; } data >>= 7; if ((data & COMPRESSED_INT_MASK) == 0)...
@Test void testGetPackedIntLen() { assertEquals(1, AbstractLEB128Writer.getPackedIntLen(0)); long val = 1L; for (int i = 1; i < 10; i++) { assertEquals(Math.max(i - 1, 1), AbstractLEB128Writer.getPackedIntLen(val - 1)); assertEquals(i, AbstractLEB128Writer.getPackedIntLen(val)); val = val << 7; } }
OpenJdkOngoingRecording implements OngoingRecording { @Override public OpenJdkRecordingData stop() { if (recording.getState() != RecordingState.RUNNING) { throw new IllegalStateException("Cannot stop recording that is not running"); } recording.stop(); return new OpenJdkRecordingData(recording); } OpenJdkOngoingRecordi...
@Test public void testStop() { assertEquals(recording, ongoingRecording.stop().getRecording()); verify(recording).stop(); } @Test public void testStopOnStopped() { when(recording.getState()).thenReturn(RecordingState.STOPPED); assertThrows( IllegalStateException.class, () -> { ongoingRecording.stop(); }); verify(record...
Java8OptionalConverterFactory extends Converter.Factory { public static Java8OptionalConverterFactory create() { return new Java8OptionalConverterFactory(); } private Java8OptionalConverterFactory(); static Java8OptionalConverterFactory create(); @Override @Nullable Converter<ResponseBody, ?> responseBodyConverter( ...
@Test public void delegates() throws IOException { Object object = new Object(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .addConverterFactory( new Converter.Factory() { @Nullable @Override public Converter<ResponseBody, ?> responseBodyConverter( Type type, Annotation[] annotations, Retrofit...
NetworkBehavior { public void setVariancePercent(int variancePercent) { checkPercentageValidity(variancePercent, "Variance percentage must be between 0 and 100."); this.variancePercent = variancePercent; } private NetworkBehavior(Random random); static NetworkBehavior create(); @SuppressWarnings("ConstantConditions") ...
@Test public void varianceRestrictsRange() { try { behavior.setVariancePercent(-13); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Variance percentage must be between 0 and 100."); } try { behavior.setVariancePercent(174); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessag...
NetworkBehavior { public void setFailurePercent(int failurePercent) { checkPercentageValidity(failurePercent, "Failure percentage must be between 0 and 100."); this.failurePercent = failurePercent; } private NetworkBehavior(Random random); static NetworkBehavior create(); @SuppressWarnings("ConstantConditions") // Gua...
@Test public void failureRestrictsRange() { try { behavior.setFailurePercent(-13); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Failure percentage must be between 0 and 100."); } try { behavior.setFailurePercent(174); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("F...
NetworkBehavior { @SuppressWarnings("ConstantConditions") public void setFailureException(Throwable exception) { if (exception == null) { throw new NullPointerException("exception == null"); } this.failureException = exception; } private NetworkBehavior(Random random); static NetworkBehavior create(); @SuppressWarning...
@Test public void failureExceptionIsNotNull() { try { behavior.setFailureException(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("exception == null"); } }
NetworkBehavior { public void setErrorPercent(int errorPercent) { checkPercentageValidity(errorPercent, "Error percentage must be between 0 and 100."); this.errorPercent = errorPercent; } private NetworkBehavior(Random random); static NetworkBehavior create(); @SuppressWarnings("ConstantConditions") // Guarding API nu...
@Test public void errorRestrictsRange() { try { behavior.setErrorPercent(-13); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Error percentage must be between 0 and 100."); } try { behavior.setErrorPercent(174); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Error per...
NetworkBehavior { @SuppressWarnings("ConstantConditions") public void setErrorFactory(Callable<Response<?>> errorFactory) { if (errorFactory == null) { throw new NullPointerException("errorFactory == null"); } this.errorFactory = errorFactory; } private NetworkBehavior(Random random); static NetworkBehavior create(); ...
@Test public void errorFactoryIsNotNull() { try { behavior.setErrorFactory(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("errorFactory == null"); } }
MockRetrofit { public Retrofit retrofit() { return retrofit; } MockRetrofit(Retrofit retrofit, NetworkBehavior behavior, ExecutorService executor); Retrofit retrofit(); NetworkBehavior networkBehavior(); Executor backgroundExecutor(); @SuppressWarnings("unchecked") // Single-interface proxy creation guarded by paramete...
@Test public void retrofitPropagated() { MockRetrofit mockRetrofit = new MockRetrofit.Builder(retrofit).build(); assertThat(mockRetrofit.retrofit()).isSameAs(retrofit); }
MockRetrofit { public NetworkBehavior networkBehavior() { return behavior; } MockRetrofit(Retrofit retrofit, NetworkBehavior behavior, ExecutorService executor); Retrofit retrofit(); NetworkBehavior networkBehavior(); Executor backgroundExecutor(); @SuppressWarnings("unchecked") // Single-interface proxy creation guard...
@Test public void networkBehaviorNullThrows() { MockRetrofit.Builder builder = new MockRetrofit.Builder(retrofit); try { builder.networkBehavior(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("behavior == null"); } } @Test public void networkBehaviorDefault() { MockRetrofit mockRetrofit = ne...
MockRetrofit { public Executor backgroundExecutor() { return executor; } MockRetrofit(Retrofit retrofit, NetworkBehavior behavior, ExecutorService executor); Retrofit retrofit(); NetworkBehavior networkBehavior(); Executor backgroundExecutor(); @SuppressWarnings("unchecked") // Single-interface proxy creation guarded b...
@Test public void backgroundExecutorNullThrows() { MockRetrofit.Builder builder = new MockRetrofit.Builder(retrofit); try { builder.backgroundExecutor(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("executor == null"); } } @Test public void backgroundExecutorDefault() { MockRetrofit mockRetr...
RxJava3CallAdapterFactory extends CallAdapter.Factory { @Override public @Nullable CallAdapter<?, ?> get( Type returnType, Annotation[] annotations, Retrofit retrofit) { Class<?> rawType = getRawType(returnType); if (rawType == Completable.class) { return new RxJava3CallAdapter( Void.class, scheduler, isAsync, false, t...
@Test public void rawResultTypeThrows() { Type observableType = new TypeToken<Observable<Result>>() {}.getType(); try { factory.get(observableType, NO_ANNOTATIONS, retrofit); fail(); } catch (IllegalStateException e) { assertThat(e) .hasMessage("Result must be parameterized as Result<Foo> or Result<? extends Foo>"); } ...
Calls { public static <T> Call<T> response(@Nullable T successValue) { return new FakeCall<>(Response.success(successValue), null); } private Calls(); static Call<T> defer(Callable<Call<T>> callable); static Call<T> response(@Nullable T successValue); static Call<T> response(Response<T> response); static Call<T> failu...
@Test public void bodyExecute() throws IOException { Call<String> taco = Calls.response("Taco"); assertEquals("Taco", taco.execute().body()); } @Test public void bodyEnqueue() throws IOException { Call<String> taco = Calls.response("Taco"); final AtomicReference<Response<String>> responseRef = new AtomicReference<>(); ...
Calls { public static <T> Call<T> failure(IOException failure) { return new FakeCall<>(null, failure); } private Calls(); static Call<T> defer(Callable<Call<T>> callable); static Call<T> response(@Nullable T successValue); static Call<T> response(Response<T> response); static Call<T> failure(IOException failure); stat...
@Test public void failureExecute() { IOException failure = new IOException("Hey"); Call<Object> taco = Calls.failure(failure); assertFalse(taco.isExecuted()); try { taco.execute(); fail(); } catch (IOException e) { assertSame(failure, e); } assertTrue(taco.isExecuted()); } @Test public void failureExecuteCheckedExcepti...
Result { @SuppressWarnings("ConstantConditions") public static <T> Result<T> response(Response<T> response) { if (response == null) throw new NullPointerException("response == null"); return new Result<>(response, null); } private Result(@Nullable Response<T> response, @Nullable Throwable error); @SuppressWarnings("Co...
@Test public void response() { Response<String> response = Response.success("Hi"); Result<String> result = Result.response(response); assertThat(result.isError()).isFalse(); assertThat(result.error()).isNull(); assertThat(result.response()).isSameAs(response); } @Test public void nullResponseThrows() { try { Result.res...
Calls { public static <T> Call<T> defer(Callable<Call<T>> callable) { return new DeferredCall<>(callable); } private Calls(); static Call<T> defer(Callable<Call<T>> callable); static Call<T> response(@Nullable T successValue); static Call<T> response(Response<T> response); static Call<T> failure(IOException failure); ...
@Test public void deferredThrowExecute() throws IOException { final IOException failure = new IOException("Hey"); Call<Object> failing = Calls.defer( () -> { throw failure; }); try { failing.execute(); fail(); } catch (IOException e) { assertSame(failure, e); } } @Test public void deferredThrowEnqueue() { final IOExcep...
Result { @SuppressWarnings("ConstantConditions") public static <T> Result<T> error(Throwable error) { if (error == null) throw new NullPointerException("error == null"); return new Result<>(null, error); } private Result(@Nullable Response<T> response, @Nullable Throwable error); @SuppressWarnings("ConstantConditions"...
@Test public void error() { Throwable error = new IOException(); Result<Object> result = Result.error(error); assertThat(result.isError()).isTrue(); assertThat(result.error()).isSameAs(error); assertThat(result.response()).isNull(); } @Test public void nullErrorThrows() { try { Result.error(null); fail(); } catch (Null...
RxJava2CallAdapterFactory extends CallAdapter.Factory { @SuppressWarnings("ConstantConditions") public static RxJava2CallAdapterFactory createWithScheduler(Scheduler scheduler) { if (scheduler == null) throw new NullPointerException("scheduler == null"); return new RxJava2CallAdapterFactory(scheduler, false); } private...
@Test public void nullSchedulerThrows() { try { RxJava2CallAdapterFactory.createWithScheduler(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("scheduler == null"); } }
JaxbConverterFactory extends Converter.Factory { public static JaxbConverterFactory create() { return new JaxbConverterFactory(null); } private JaxbConverterFactory(@Nullable JAXBContext context); static JaxbConverterFactory create(); @SuppressWarnings("ConstantConditions") // Guarding API nullability. static JaxbConv...
@Test public void userSuppliedJaxbContext() throws Exception { JAXBContext context = JAXBContext.newInstance(Contact.class); JaxbConverterFactory factory = JaxbConverterFactory.create(context); Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).addConverterFactory(factory).build(); service = retrofit.c...
RxJava2CallAdapterFactory extends CallAdapter.Factory { @Override public @Nullable CallAdapter<?, ?> get( Type returnType, Annotation[] annotations, Retrofit retrofit) { Class<?> rawType = getRawType(returnType); if (rawType == Completable.class) { return new RxJava2CallAdapter( Void.class, scheduler, isAsync, false, t...
@Test public void nonRxJavaTypeReturnsNull() { CallAdapter<?, ?> adapter = factory.get(String.class, NO_ANNOTATIONS, retrofit); assertThat(adapter).isNull(); } @Test public void responseTypes() { Type oBodyClass = new TypeToken<Observable<String>>() {}.getType(); assertThat(factory.get(oBodyClass, NO_ANNOTATIONS, retro...
ScalaCallAdapterFactory extends CallAdapter.Factory { @Override public @Nullable CallAdapter<?, ?> get( Type returnType, Annotation[] annotations, Retrofit retrofit) { if (getRawType(returnType) != Future.class) { return null; } if (!(returnType instanceof ParameterizedType)) { throw new IllegalStateException( "Future ...
@Test public void responseType() { Type bodyClass = new TypeToken<Future<String>>() {}.getType(); assertThat(factory.get(bodyClass, NO_ANNOTATIONS, retrofit).responseType()) .isEqualTo(String.class); Type bodyWildcard = new TypeToken<Future<? extends String>>() {}.getType(); assertThat(factory.get(bodyWildcard, NO_ANNO...
Java8CallAdapterFactory extends CallAdapter.Factory { @Override public @Nullable CallAdapter<?, ?> get( Type returnType, Annotation[] annotations, Retrofit retrofit) { if (getRawType(returnType) != CompletableFuture.class) { return null; } if (!(returnType instanceof ParameterizedType)) { throw new IllegalStateExceptio...
@Test public void responseType() { Type bodyClass = new TypeToken<CompletableFuture<String>>() {}.getType(); assertThat(factory.get(bodyClass, NO_ANNOTATIONS, retrofit).responseType()) .isEqualTo(String.class); Type bodyWildcard = new TypeToken<CompletableFuture<? extends String>>() {}.getType(); assertThat(factory.get...
MoshiConverterFactory extends Converter.Factory { public MoshiConverterFactory asLenient() { return new MoshiConverterFactory(moshi, true, failOnUnknown, serializeNulls); } private MoshiConverterFactory( Moshi moshi, boolean lenient, boolean failOnUnknown, boolean serializeNulls); static MoshiConverterFactory cr...
@Test public void asLenient() throws IOException, InterruptedException { MockResponse malformedResponse = new MockResponse().setBody("{\"theName\":value}"); server.enqueue(malformedResponse); server.enqueue(malformedResponse); Call<AnImplementation> call = service.anImplementation(new AnImplementation("value")); try { ...
RxJavaCallAdapterFactory extends CallAdapter.Factory { @SuppressWarnings("ConstantConditions") public static RxJavaCallAdapterFactory createWithScheduler(Scheduler scheduler) { if (scheduler == null) throw new NullPointerException("scheduler == null"); return new RxJavaCallAdapterFactory(scheduler, false); } private R...
@Test public void nullSchedulerThrows() { try { RxJavaCallAdapterFactory.createWithScheduler(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("scheduler == null"); } }
RxJavaCallAdapterFactory extends CallAdapter.Factory { @Override public @Nullable CallAdapter<?, ?> get( Type returnType, Annotation[] annotations, Retrofit retrofit) { Class<?> rawType = getRawType(returnType); boolean isSingle = rawType == Single.class; boolean isCompletable = rawType == Completable.class; if (rawTyp...
@Test public void nonRxJavaTypeReturnsNull() { CallAdapter<?, ?> adapter = factory.get(String.class, NO_ANNOTATIONS, retrofit); assertThat(adapter).isNull(); } @Test public void responseTypes() { Type oBodyClass = new TypeToken<Observable<String>>() {}.getType(); assertThat(factory.get(oBodyClass, NO_ANNOTATIONS, retro...