method2testcases
stringlengths 118
3.08k
|
---|
### Question:
RefocusClient extends AbstractRemoteClient<RefocusService> { public List<Sample> getSamples(String name) throws UnauthorizedException { Preconditions.checkNotNull(name, "Name should not be null"); return executeAndRetrieveBody(svc().getSample(authorizationHeader(), name), emptyList()); } RefocusClient(EndpointConnector connector); @Override boolean isAuthenticated(); Sample getSample(String key, List<String> fields); List<Sample> getSamples(String name); boolean upsertSamplesBulk(List<Sample> samples); Sample deleteSample(String key); List<Subject> getSubjects(List<String> fields); Subject getSubject(String key, List<String> fields); Subject getSubjectHierarchy(String key, String status); Subject postSubject(Subject subject); Subject patchSubject(Subject subject); Subject putSubject(Subject subject); Subject deleteSubject(String subjectKey); List<Aspect> getAspects(List<String> fields); Aspect getAspect(String key, List<String> fields); Aspect postAspect(Aspect aspect); Aspect patchAspect(Aspect aspect); }### Answer:
@Test public void getSamples() throws Exception { Response<List<Sample>> response = Response.success(Collections.singletonList(sample)); @SuppressWarnings("unchecked") Call<ResponseBody> responseCall = mock(Call.class); doReturn(response).when(responseCall).execute(); doReturn(request).when(responseCall).request(); doReturn(responseCall).when(svc).getSample(any(), anyString()); List<Sample> results = refocus.getSamples("name"); assertThat(results, hasSize(1)); assertThat(results.get(0).name(), is("name")); assertThat(results.get(0).value(), is("value")); assertThat(results.get(0).id(), is("id")); }
|
### Question:
RefocusClient extends AbstractRemoteClient<RefocusService> { public Sample deleteSample(String key) throws UnauthorizedException { Preconditions.checkNotNull(key, "Key should not be null"); return executeAndRetrieveBody(svc().deleteSample(authorizationHeader(), key), null); } RefocusClient(EndpointConnector connector); @Override boolean isAuthenticated(); Sample getSample(String key, List<String> fields); List<Sample> getSamples(String name); boolean upsertSamplesBulk(List<Sample> samples); Sample deleteSample(String key); List<Subject> getSubjects(List<String> fields); Subject getSubject(String key, List<String> fields); Subject getSubjectHierarchy(String key, String status); Subject postSubject(Subject subject); Subject patchSubject(Subject subject); Subject putSubject(Subject subject); Subject deleteSubject(String subjectKey); List<Aspect> getAspects(List<String> fields); Aspect getAspect(String key, List<String> fields); Aspect postAspect(Aspect aspect); Aspect patchAspect(Aspect aspect); }### Answer:
@Test public void deleteSample() throws Exception { Response<Sample> response = Response.success(sample); @SuppressWarnings("unchecked") Call<Sample> responseCall = mock(Call.class); doReturn(response).when(responseCall).execute(); doReturn(request).when(responseCall).request(); doReturn(responseCall).when(svc).deleteSample(any(), anyString()); refocus.deleteSample("id"); verify(svc).deleteSample(AUTHORIZATION_HEADER, "id"); }
|
### Question:
RefocusClient extends AbstractRemoteClient<RefocusService> { public Subject getSubjectHierarchy(String key, String status) throws UnauthorizedException { Preconditions.checkNotNull(key, "Key should not be null"); return executeAndRetrieveBody(svc().getSubjectHierarchy(authorizationHeader(), key, status), null); } RefocusClient(EndpointConnector connector); @Override boolean isAuthenticated(); Sample getSample(String key, List<String> fields); List<Sample> getSamples(String name); boolean upsertSamplesBulk(List<Sample> samples); Sample deleteSample(String key); List<Subject> getSubjects(List<String> fields); Subject getSubject(String key, List<String> fields); Subject getSubjectHierarchy(String key, String status); Subject postSubject(Subject subject); Subject patchSubject(Subject subject); Subject putSubject(Subject subject); Subject deleteSubject(String subjectKey); List<Aspect> getAspects(List<String> fields); Aspect getAspect(String key, List<String> fields); Aspect postAspect(Aspect aspect); Aspect patchAspect(Aspect aspect); }### Answer:
@Test public void getSubjectHierarchy() throws Exception { Response<Subject> response = Response.success(subject); @SuppressWarnings("unchecked") Call<Subject> responseCall = mock(Call.class); doReturn(response).when(responseCall).execute(); doReturn(request).when(responseCall).request(); doReturn(responseCall).when(svc).getSubjectHierarchy(any(), anyString(), anyString()); Subject result = refocus.getSubjectHierarchy("name", "OK"); assertThat(result, is(not(nullValue()))); assertThat(result.name(), equalTo("name")); assertThat(result.id(), is("id")); }
|
### Question:
RefocusClient extends AbstractRemoteClient<RefocusService> { public Subject deleteSubject(String subjectKey) throws UnauthorizedException { Preconditions.checkNotNull(subjectKey, "Subject key (ID or path) should not be null"); return executeAndRetrieveBody(svc().deleteSubject(authorizationHeader(), subjectKey), null); } RefocusClient(EndpointConnector connector); @Override boolean isAuthenticated(); Sample getSample(String key, List<String> fields); List<Sample> getSamples(String name); boolean upsertSamplesBulk(List<Sample> samples); Sample deleteSample(String key); List<Subject> getSubjects(List<String> fields); Subject getSubject(String key, List<String> fields); Subject getSubjectHierarchy(String key, String status); Subject postSubject(Subject subject); Subject patchSubject(Subject subject); Subject putSubject(Subject subject); Subject deleteSubject(String subjectKey); List<Aspect> getAspects(List<String> fields); Aspect getAspect(String key, List<String> fields); Aspect postAspect(Aspect aspect); Aspect patchAspect(Aspect aspect); }### Answer:
@Test public void deleteSubject() throws Exception { Response<Subject> response = Response.success(subject); @SuppressWarnings("unchecked") Call<Subject> responseCall = mock(Call.class); doReturn(response).when(responseCall).execute(); doReturn(request).when(responseCall).request(); doReturn(responseCall).when(svc).deleteSubject(any(), any()); Subject result = refocus.deleteSubject("key"); assertThat(result, is(not(nullValue()))); assertThat(result.name(), equalTo("name")); assertThat(result.isPublished(), equalTo(true)); }
@Test(expectedExceptions = NullPointerException.class) public void deleteSubjectFailNPE() throws Exception { refocus.deleteSubject(null); }
|
### Question:
FileMemoryProvider implements ReadableMemoryProvider, WritableMemoryProvider { @Override public SeekableByteChannel openWrite(int pid) throws ProcessOpenException { Path memFile = createPathToProcessMemoryFile(pid); try { return Files.newByteChannel(memFile, StandardOpenOption.WRITE); } catch (IOException ex) { String message = String.format( "Failed to open process %d for writing! See getCause()!", pid ); throw new ProcessOpenException(message, ex); } } FileMemoryProvider(Path procRoot); @Override SeekableByteChannel openRead(int pid); @Override SeekableByteChannel openWrite(int pid); }### Answer:
@Test public void writesDataCorrectlyToCorrectFile() throws IOException { Integer pid = 10001; Path memFile = procRoot.resolve(pid + "").resolve("mem"); assertTrue(Files.notExists(memFile)); Files.createDirectories(memFile.getParent()); Files.createFile(memFile); byte[] bytesToWrite = TestUtils.generateRandomBytes(2048); SeekableByteChannel writeChannel = provider.openWrite(pid); writeChannel.write(ByteBuffer.wrap(bytesToWrite)); byte[] writtenBytes = Files.readAllBytes(memFile); assertArrayEquals(bytesToWrite, writtenBytes); }
@Test(expected = ProcessOpenException.class) public void openWriteThrowsIfProcRootDoesntExist() throws IOException { assertFalse(Files.exists(procRoot)); provider.openWrite(123); }
@Test(expected = ProcessOpenException.class) public void openWriteThrowsIfProcessDoesntExist() throws IOException { Files.createDirectories(procRoot); Integer pid = 3551; assertFalse(Files.exists(procRoot.resolve(pid + ""))); provider.openWrite(pid); }
|
### Question:
MemoryWriterImpl implements MemoryWriter { @Override public void writeFloat(NativeProcess process, int offset, float value) throws MemoryAccessException { ByteBuffer buffer = createLEBuffer(TypeSize.FLOAT.getSize()); buffer.putFloat(value); writer.write(process, offset, buffer.array()); } MemoryWriterImpl(RawMemoryWriter writer); @Override void writeBoolean(NativeProcess process, int offset, boolean value); @Override void writeByte(NativeProcess process, int offset, byte value); @Override void writeCharUTF8(NativeProcess process, int offset, char value); @Override void writeCharUTF16LE(NativeProcess process, int offset, char value); @Override void writeShort(NativeProcess process, int offset, short value); @Override void writeInt(NativeProcess process, int offset, int value); @Override void writeFloat(NativeProcess process, int offset, float value); @Override void writeLong(NativeProcess process, int offset, long value); @Override void writeDouble(NativeProcess process, int offset, double value); @Override void writeStringUTF8(NativeProcess process, int offset, String value); @Override void writeStringUTF16LE(NativeProcess process, int offset, String value); @Override void write(NativeProcess process, int offset, byte[] values); }### Answer:
@Test public void writeFloatWritesCorrectly() { writer.writeFloat(process, 0, 5123.412f); byte[] expected = {0x4C, 0x1B, (byte) 0xA0, 0x45}; assertArrayEquals(expected, rawByteWriter.getBytes()); }
@Test public void writeFloatWritesZeroCorrectly() { writer.writeFloat(process, 0, 0f); byte[] expected = {0, 0, 0, 0}; assertArrayEquals(expected, rawByteWriter.getBytes()); }
@Test public void writeFloatWritesToCorrectOffset() { final int targetOffset = 0xBADF00D; rawWriter = (p, offset, b) -> { assertEquals(targetOffset, offset); }; writer.writeFloat(process, targetOffset, 1234f); }
|
### Question:
NativeProcessImpl implements NativeProcess { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NativeProcessImpl process = (NativeProcessImpl) o; return pid == process.pid && Objects.equals(description, process.description) && Objects.equals(owner, process.owner); } NativeProcessImpl(); NativeProcessImpl(int pid, String description, String owner); @Override int getPid(); @Override void setPid(int pid); @Override String getDescription(); @Override void setDescription(String description); @Override String getOwner(); @Override void setOwner(String owner); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void equalsFindsSameObjectsEqual() { process = new NativeProcessImpl(123, "ayy", "lmao"); assertTrue(process.equals(process)); }
@Test public void equalsFindsNullNotEqual() { process = new NativeProcessImpl(321, "yea", "boiiiiiiiiiii"); assertFalse(process.equals(null)); }
@Test public void equalsFindsProcsWithSamePropertyValuesEqual() { NativeProcessImpl a = new NativeProcessImpl(123, "yuss", "boii"); NativeProcessImpl b = new NativeProcessImpl(123, "yuss", "boii"); assertTrue(a.equals(b)); assertTrue(b.equals(a)); }
|
### Question:
NativeProcessImpl implements NativeProcess { @Override public int hashCode() { return Objects.hash(pid, description, owner); } NativeProcessImpl(); NativeProcessImpl(int pid, String description, String owner); @Override int getPid(); @Override void setPid(int pid); @Override String getDescription(); @Override void setDescription(String description); @Override String getOwner(); @Override void setOwner(String owner); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void hashCodeIsSameForSameObject() { NativeProcessImpl a = new NativeProcessImpl(123, "yuss", "boii"); assertEquals(a.hashCode(), a.hashCode()); }
@Test public void hashCodeIsSameForObjectsWithSamePropertyValues() { NativeProcessImpl a = new NativeProcessImpl(123, "yuss", "boii"); NativeProcessImpl b = new NativeProcessImpl(123, "yuss", "boii"); assertEquals(a.hashCode(), b.hashCode()); }
@Test public void hashCodeDiffersWhenPidDiffers() { NativeProcessImpl a = new NativeProcessImpl(6712, "yuss", "boii"); NativeProcessImpl b = new NativeProcessImpl(8233, "yuss", "boii"); assertNotEquals(a.hashCode(), b.hashCode()); }
@Test public void hashCodeDiffersWhenOwnerDiffers() { NativeProcessImpl a = new NativeProcessImpl(6712, "yuss", "owner not home"); NativeProcessImpl b = new NativeProcessImpl(6712, "yuss", "boii"); assertNotEquals(a.hashCode(), b.hashCode()); }
@Test public void hashCodeDiffersWhenDescriptionDiffers() { NativeProcessImpl a = new NativeProcessImpl(6712, "doge", "boii"); NativeProcessImpl b = new NativeProcessImpl(6712, "woof woof", "boii"); assertNotEquals(a.hashCode(), b.hashCode()); }
|
### Question:
NativeProcessImpl implements NativeProcess { @Override public String toString() { return String.format("{ PID: %d, owner: %s, description: %s }", pid, owner, description ); } NativeProcessImpl(); NativeProcessImpl(int pid, String description, String owner); @Override int getPid(); @Override void setPid(int pid); @Override String getDescription(); @Override void setDescription(String description); @Override String getOwner(); @Override void setOwner(String owner); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void toStringContainsRightPid() { NativeProcessImpl proc1 = new NativeProcessImpl(1234, "ayy", "lmao"); NativeProcessImpl proc2 = new NativeProcessImpl(29999, "ayy", "lmao"); assertTrue(proc1.toString().contains("1234")); assertTrue(proc2.toString().contains("29999")); }
@Test public void toStringContainsRightDescription() { NativeProcessImpl proc1 = new NativeProcessImpl(1234, "ayy", "lmao"); NativeProcessImpl proc2 = new NativeProcessImpl(1234, "toopppppp kkeeekkkk", "lmao"); assertTrue(proc1.toString().contains("ayy")); assertTrue(proc2.toString().contains("toopppppp kkeeekkkk")); }
@Test public void toStringContainsRightOwner() { NativeProcessImpl proc1 = new NativeProcessImpl(1234, "ayy", "SYSTEM"); NativeProcessImpl proc2 = new NativeProcessImpl(1234, "toaster", "Joona"); assertTrue(proc1.toString().contains("SYSTEM")); assertTrue(proc2.toString().contains("Joona")); }
|
### Question:
MainPresenter implements Presenter, MainCallbacks { @Override public void initialize() { view.attach(this); } MainPresenter(MainView view, MainModel model); @Override void initialize(); @Override void newActiveProcessSelected(); }### Answer:
@Test public void initializeAttachesPresenterToView() { presenter.initialize(); verify(view).attach(presenter); }
|
### Question:
MainPresenter implements Presenter, MainCallbacks { @Override public void newActiveProcessSelected() { NativeProcess newProc = view.getActiveProcess(); model.setActiveProcess(newProc); } MainPresenter(MainView view, MainModel model); @Override void initialize(); @Override void newActiveProcessSelected(); }### Answer:
@Test public void newActiveProcessSelectedUpdatesModel() { NativeProcess newProcess = new NativeProcessImpl(123, "ayy", "lmao"); given(view.getActiveProcess()).willReturn(newProcess); model.setActiveProcess(null); presenter.newActiveProcessSelected(); assertEquals(newProcess, model.getActiveProcess()); }
|
### Question:
ProcessListPresenter implements Presenter, ProcessListCallbacks { @Override public void updateRequested() { view.setProcessList(model.getProcesses()); } ProcessListPresenter(ProcessListView view, ProcessListModel model); @Override void processChosen(); @Override void updateRequested(); @Override void initialize(); void addProcessChosenListener(ProcessChosenEventListener callback); }### Answer:
@Test public void updateRequestedUpdatesProcessesInViewWithEmptyList() { given(model.getProcesses()).willReturn(new ArrayList<>()); presenter.updateRequested(); verify(view).setProcessList(model.getProcesses()); }
@Test public void updateRequestedUpdatesProcessesInViewWithNonEmptyList() { List<NativeProcess> procs = new ArrayList<>(); procs.add(new NativeProcessImpl(123, "123", "123")); procs.add(new NativeProcessImpl(555, "5555", "555")); procs.add(new NativeProcessImpl(521, "1235", "999")); given(model.getProcesses()).willReturn(procs); presenter.updateRequested(); verify(view).setProcessList(model.getProcesses()); }
|
### Question:
ProcessListPresenter implements Presenter, ProcessListCallbacks { @Override public void initialize() { view.attach(this); } ProcessListPresenter(ProcessListView view, ProcessListModel model); @Override void processChosen(); @Override void updateRequested(); @Override void initialize(); void addProcessChosenListener(ProcessChosenEventListener callback); }### Answer:
@Test public void initializeAttachesPresenterToView() { presenter.initialize(); verify(view).attach(presenter); }
|
### Question:
ProcessListPresenter implements Presenter, ProcessListCallbacks { @Override public void processChosen() { view.getChosenProcess() .ifPresent(proc -> processChosenCallbacks.forEach(c -> c.processChosen(proc))); } ProcessListPresenter(ProcessListView view, ProcessListModel model); @Override void processChosen(); @Override void updateRequested(); @Override void initialize(); void addProcessChosenListener(ProcessChosenEventListener callback); }### Answer:
@Test public void processChosenDoesntThrowIfViewReturnsEmptyAndNoListenersRegistered() { given(view.getChosenProcess()).willReturn(Optional.empty()); presenter.processChosen(); }
|
### Question:
ProcessListPresenter implements Presenter, ProcessListCallbacks { public void addProcessChosenListener(ProcessChosenEventListener callback) { if (callback == null) { throw new IllegalArgumentException("Callback cannot be null!"); } processChosenCallbacks.add(callback); } ProcessListPresenter(ProcessListView view, ProcessListModel model); @Override void processChosen(); @Override void updateRequested(); @Override void initialize(); void addProcessChosenListener(ProcessChosenEventListener callback); }### Answer:
@Test(expected = IllegalArgumentException.class) public void addProcessChosenListenerThrowsWhenNullArgPassed() { presenter.addProcessChosenListener(null); }
|
### Question:
WindowsProcessDescriptionGetter implements ProcessDescriptionGetter { @Override public Optional<String> get(ProcessHandle processHandle) { Objects.requireNonNull(processHandle, "processHandle cannot be null!"); return getProcessImageName(processHandle.getNativeHandle()); } WindowsProcessDescriptionGetter(QueryFullProcessImageName winapi); @Override Optional<String> get(ProcessHandle processHandle); }### Answer:
@Test(expected = NullPointerException.class) public void getThrowsWhenPassedNullHandle() { getter.get(null); }
@Test public void getReturnsEmptyIfKernelQueryFails() { nameQuerier = (a, b, c, d) -> false; Optional<String> result = getter.get(handle); assertFalse(result.isPresent()); }
@Test public void getReturnsEmptyStringIfKernelSaysItWroteZeroBytes() { nameQuerier = (procHandle, flags, exeName, bufSize) -> { char[] name = "Image name that isn not empty.exe".toCharArray(); System.arraycopy(name, 0, exeName, 0, name.length); bufSize.setValue(0); return true; }; Optional<String> result = getter.get(handle); assertEquals(0, result.get().length()); }
@Test public void getReturnsCorrectlyTrimmedString() { final String description = "toasters.exe"; final int howManyBytesWeClaimToHaveCopied = description.length() - 1; final String expected = description.substring(0, howManyBytesWeClaimToHaveCopied); nameQuerier = (procHandle, flags, exeName, bufSize) -> { char[] name = description.toCharArray(); System.arraycopy(name, 0, exeName, 0, howManyBytesWeClaimToHaveCopied); bufSize.setValue(howManyBytesWeClaimToHaveCopied); return true; }; Optional<String> result = getter.get(handle); assertEquals(expected, result.get()); }
|
### Question:
FileMemoryProvider implements ReadableMemoryProvider, WritableMemoryProvider { @Override public SeekableByteChannel openRead(int pid) throws ProcessOpenException { Path memFile = createPathToProcessMemoryFile(pid); try { return Files.newByteChannel(memFile, StandardOpenOption.READ); } catch (IOException ex) { String message = String.format( "Failed to open process %d for reading! See getCause()!", pid ); throw new ProcessOpenException(message, ex); } } FileMemoryProvider(Path procRoot); @Override SeekableByteChannel openRead(int pid); @Override SeekableByteChannel openWrite(int pid); }### Answer:
@Test(expected = ProcessOpenException.class) public void openReadThrowsIfProcRootDoesntExist() throws IOException { assertFalse(Files.exists(procRoot)); provider.openRead(123); }
@Test(expected = ProcessOpenException.class) public void openReadThrowsIfProcessDoesntExist() throws IOException { Files.createDirectories(procRoot); Integer pid = 3551; assertFalse(Files.exists(procRoot.resolve(pid + ""))); provider.openRead(pid); }
@Test public void readsCorrectDataFromCorrectFile() throws IOException { Integer pid = 5567; Path memFile = procRoot.resolve(pid + "").resolve("mem"); byte[] inputData = TestUtils.generateRandomBytes(200); assertTrue(Files.notExists(memFile)); Files.createDirectories(memFile.getParent()); Files.write(memFile, inputData); SeekableByteChannel stream = provider.openRead(pid); ByteBuffer readBuffer = ByteBuffer.allocate(inputData.length); int bytesRead = stream.read(readBuffer); assertEquals(inputData.length, bytesRead); assertArrayEquals(inputData, readBuffer.array()); }
|
### Question:
CamelToPascalCaseFunctionMapper implements FunctionMapper { @Override public String getFunctionName(NativeLibrary nativeLibrary, Method method) { return capitalizeFirstLetter(method.getName()); } @Override String getFunctionName(NativeLibrary nativeLibrary, Method method); }### Answer:
@Test public void capitalizesOneCharacterName() throws NoSuchMethodException { Method method = getClass().getDeclaredMethod("a"); String mappedName = mapper.getFunctionName(null, method); assertEquals("A", mappedName); }
@Test public void capitalizesLongerName() throws NoSuchMethodException { Method method = getClass().getDeclaredMethod("longerMethodNameW"); String mappedName = mapper.getFunctionName(null, method); assertEquals("LongerMethodNameW", mappedName); }
|
### Question:
EsDailySnapshotStore extends EsStore implements DailySnapshotStore { @Override public EsDailySnapshotInstance getInstanceById(String instanceId) throws Exception { SearchResponse response = this.retrieveByField("_id", instanceId, EsDailySnapshotInstance.class); if (response.getHits().totalHits() > 0) { String str = response.getHits().getAt(0).getSourceAsString(); EsDailySnapshotInstance inst = essnapshotinstanceMapper.readValue(str, EsDailySnapshotInstance.class); inst.setId(response.getHits().getAt(0).getId()); inst.setVersion(response.getHits().getAt(0).getVersion()); return inst; } return null; } EsDailySnapshotStore(DateTime day); @Override String getIndexName(); @Override String getDocTypeName(); @Override EsDailySnapshotInstance getInstanceById(String instanceId); @Override long updateOrInsert(EsDailySnapshotInstance instance); @Override long update(EsDailySnapshotInstance instance); @Override Iterator<EsDailySnapshotInstance> getSnapshotInstances(); @Override void bulkInsert(List<EsDailySnapshotInstance> instances); @Override void bulkUpdate(List<EsDailySnapshotInstance> instances); }### Answer:
@Test @Ignore public void getInstanceById() throws Exception { EsDailySnapshotStoreFactory factory = new EsDailySnapshotStoreFactory(); EsDailySnapshotStore store = (EsDailySnapshotStore) factory.getDailyStore(DateTime.parse("2016-07-14")); EsDailySnapshotInstance inst = store.getInstanceById("i-9909451f"); Assert.assertEquals("i-9909451f", inst.getId()); Assert.assertEquals("Growth", inst.getUsageTag()[0]); inst = store.getInstanceById("i-999c8b05"); Assert.assertEquals("SRE", inst.getSysTag()[0]); Assert.assertEquals("vpc-app-production", inst.getSecurityGroups().get(0)); }
|
### Question:
EsDailySnapshotStore extends EsStore implements DailySnapshotStore { @Override public long updateOrInsert(EsDailySnapshotInstance instance) throws Exception { byte[] doc = essnapshotinstanceMapper.writeValueAsBytes(instance); UpdateResponse response = this.updateOrInsert(instance.getId(), doc, doc); return response.getVersion(); } EsDailySnapshotStore(DateTime day); @Override String getIndexName(); @Override String getDocTypeName(); @Override EsDailySnapshotInstance getInstanceById(String instanceId); @Override long updateOrInsert(EsDailySnapshotInstance instance); @Override long update(EsDailySnapshotInstance instance); @Override Iterator<EsDailySnapshotInstance> getSnapshotInstances(); @Override void bulkInsert(List<EsDailySnapshotInstance> instances); @Override void bulkUpdate(List<EsDailySnapshotInstance> instances); }### Answer:
@Test @Ignore public void updateOrInsert() throws Exception { EsDailySnapshotStoreFactory factory = new EsDailySnapshotStoreFactory(); EsDailySnapshotStore store = (EsDailySnapshotStore) factory.getDailyStore(DateTime.parse("2016-07-14")); EsDailySnapshotInstance inst = new EsDailySnapshotInstance(); inst.setId("i-123456789"); inst.setName("test123"); inst.setLaunchTime(DateTime.now().toDate()); inst.setServiceMappings(new String[]{"mapping"}); store.updateOrInsert(inst); }
|
### Question:
EsDailySnapshotInstance implements EsDocument { public static final Date roundToSeconds(Date dt) { if (dt != null) { return new Date(dt.getTime() / 1000 * 1000); } return dt; } EsDailySnapshotInstance(); @JsonCreator EsDailySnapshotInstance(@JsonProperty("config") EsInstanceConfig config); EsDailySnapshotInstance(PinterestEsInstance esInstance); static final Date roundToSeconds(Date dt); static final String getStringOfPeriod(Date begin, Date end); String getRegion(); void setRegion(String region); String getLocation(); void setLocation(String location); String getNodePool(); void setNodePool(String nodePool); String getState(); void setState(String state); String getDeployment(); void setDeployment(String deployment); Date getLaunchTime(); void setLaunchTime(Date launchTime); String[] getServiceMappings(); void setServiceMappings(String[] serviceMappings); String[] getServiceTag(); void setServiceTag(String[] serviceTag); String[] getSysTag(); void setSysTag(String[] sysTag); String[] getUsageTag(); void setUsageTag(String[] usageTag); List<String> getSecurityGroups(); void setSecurityGroups(List<String> securityGroups); String getLifecycle(); void setLifecycle(String lifecycle); String getType(); void setType(String type); String getName(); void setName(String name); Date getTerminateTime(); void setTerminateTime(Date terminateTime); String getRunTime(); void setRunTime(String runTime); String getId(); void setId(String id); long getVersion(); void setVersion(long version); @JsonProperty("config") void setConfig(Map<String, Object> foo); Map<String, Object[]> findDiff(EsDailySnapshotInstance inst); }### Answer:
@Test public void roundToSeconds() throws Exception { DateTime d = new DateTime(2016, 7, 7, 10, 11, 23, 123); Date d2 = EsDailySnapshotInstance.roundToSeconds(d.toDate()); Assert.assertEquals(d2.getTime(), d.getMillis() - 123); }
|
### Question:
DailySnapshot { @GET @Path("/dailysnapshot/{day}") public Response getDailySnapshot(@PathParam("day") @NotNull String day) { OperationStats opStats = new OperationStats("cmdb_api", "get_dailysnapshot", new HashMap<>()); Map<String, String> tags = new HashMap<>(); try { DateTime time = DateTime.parse(day, DateTimeFormat.forPattern("yyyy-MM-dd")); DailySnapshotStore dailySnapshot = factory.getDailyStore(time); Iterator<EsDailySnapshotInstance> iter = dailySnapshot.getSnapshotInstances(); List<EsDailySnapshotInstance> ret = IteratorUtils.toList(iter); logger.info("Success: getDailySnapshot - {}", day); return Response.status(Response.Status.OK) .type(MediaType.APPLICATION_JSON) .entity(ret) .build(); } catch (Exception e) { return Utils.responseException(e, logger, opStats, tags); } } @GET @Path("/dailysnapshot/{day}") Response getDailySnapshot(@PathParam("day")
@NotNull String day); }### Answer:
@Test @Ignore public void getDailySnapshot() throws Exception { DailySnapshot snapshot = new DailySnapshot(); Response resp = snapshot.getDailySnapshot("2016-12-12"); Assert.assertNotNull(resp); }
|
### Question:
ValueField implements Field { public void addDataPoint(Measurement measurement, long value) throws IOException { ValueWriter timeseriesBucket = getOrCreateValueWriter(measurement); try { timeseriesBucket.add(value); } catch (RollOverException e) { addDataPoint(measurement, value); } catch (NullPointerException e) { logger.log(Level.SEVERE, "\n\nNPE occurred for add datapoint operation\n\n", e); } } ValueField(Measurement measurement, LinkedByteString fieldId, int tsBucket, Map<String, String> conf); void loadBucketMap(Measurement measurement, List<BufferObject> bufferEntries); FieldReaderIterator queryReader(Predicate predicate, Lock readLock); void addDataPoint(Measurement measurement, long value); List<ValueWriter> getRawWriterList(); LinkedByteString getFieldId(); void setFieldId(LinkedByteString fieldId); @Override String toString(); void close(); @SafeVarargs final List<Writer> compact(Measurement measurement, Lock writeLock,
Consumer<List<? extends Writer>>... functions); void replaceFirstBuckets(Measurement measurement, List<byte[]> bufList); @Override int getWriterCount(); @Override List<? extends Writer> getWriters(); static double compactionRatio; static Class<ValueWriter> compressionClass; static Class<ValueWriter> compactionClass; }### Answer:
@Test public void testExpandBufferError() throws IOException { measurement = new MockMeasurement(149, 100); Field field = new ValueField(measurement, fieldId, 121213, new HashMap<>()); try { for (double i = 100; i > 0; i--) { long v = Double.doubleToLongBits(3.1417 * i % 7); field.addDataPoint(measurement, v); } } catch (Exception e) { e.printStackTrace(); fail("No exception must be thrown"); } }
|
### Question:
TimeUtils { public static int getTimeBucket(TimeUnit unit, long timestamp, int bucketSizeInSeconds) throws IllegalArgumentException { int ts = timeToSeconds(unit, timestamp); return getWindowFlooredNaturalTime(ts, bucketSizeInSeconds); } private TimeUtils(); static int getTimeBucket(TimeUnit unit, long timestamp, int bucketSizeInSeconds); static int getWindowFlooredBinaryTime(TimeUnit unit, long timestamp, int windowSizeInSeconds); static int timeToSeconds(TimeUnit unit, long time); static int timeToMilliSeconds(TimeUnit unit, long time); static long timeToNanoSeconds(TimeUnit unit, long time); static int getWindowFlooredNaturalTime(int timeInSeconds, int bucketInSeconds); static long getTimeFromBucketString(String hexTimeInSeconds); static long getTimeFromBucketString(int timeInSeconds); }### Answer:
@Test public void testGetTimeBucket() { long timestamp = System.currentTimeMillis(); int timeBucket = TimeUtils.getTimeBucket(TimeUnit.MILLISECONDS, timestamp, 3600); assertEquals(((timestamp / 1000) / 3600) * 3600, timeBucket); }
|
### Question:
TimeUtils { public static int timeToSeconds(TimeUnit unit, long time) { int ts; switch (unit) { case NANOSECONDS: ts = (int) (time / (1000 * 1000 * 1000)); break; case MICROSECONDS: ts = (int) (time / (1000 * 1000)); break; case MILLISECONDS: ts = (int) (time / 1000); break; case SECONDS: ts = (int) time; break; case MINUTES: ts = (int) (time * 60); break; case HOURS: ts = (int) (time * 3600); break; case DAYS: ts = (int) (time * 3600 * 24); break; default: throw ARGUMENT_EXCEPTION; } return ts; } private TimeUtils(); static int getTimeBucket(TimeUnit unit, long timestamp, int bucketSizeInSeconds); static int getWindowFlooredBinaryTime(TimeUnit unit, long timestamp, int windowSizeInSeconds); static int timeToSeconds(TimeUnit unit, long time); static int timeToMilliSeconds(TimeUnit unit, long time); static long timeToNanoSeconds(TimeUnit unit, long time); static int getWindowFlooredNaturalTime(int timeInSeconds, int bucketInSeconds); static long getTimeFromBucketString(String hexTimeInSeconds); static long getTimeFromBucketString(int timeInSeconds); }### Answer:
@Test public void testTimeToSeconds() { long time = System.currentTimeMillis() / 1000 / 3600; int timeToSeconds = TimeUtils.timeToSeconds(TimeUnit.HOURS, time); assertEquals(time * 3600, timeToSeconds); time = System.currentTimeMillis() * 1000 * 1000; timeToSeconds = TimeUtils.timeToSeconds(TimeUnit.NANOSECONDS, time); assertEquals(time / 1000 / 1000 / 1000, timeToSeconds); }
|
### Question:
TimeUtils { public static long timeToNanoSeconds(TimeUnit unit, long time) { long ts; switch (unit) { case NANOSECONDS: ts = time; break; case MICROSECONDS: ts = ((long) time * (1000)); break; case MILLISECONDS: ts = (((long) time) * 1000 * 1000); break; case SECONDS: ts = (((long) time) * (1000 * 1000 * 1000)); break; default: throw ARGUMENT_EXCEPTION; } return ts; } private TimeUtils(); static int getTimeBucket(TimeUnit unit, long timestamp, int bucketSizeInSeconds); static int getWindowFlooredBinaryTime(TimeUnit unit, long timestamp, int windowSizeInSeconds); static int timeToSeconds(TimeUnit unit, long time); static int timeToMilliSeconds(TimeUnit unit, long time); static long timeToNanoSeconds(TimeUnit unit, long time); static int getWindowFlooredNaturalTime(int timeInSeconds, int bucketInSeconds); static long getTimeFromBucketString(String hexTimeInSeconds); static long getTimeFromBucketString(int timeInSeconds); }### Answer:
@Test public void testTimeToNanoSeconds() { long time = System.currentTimeMillis(); long timeToNano = TimeUtils.timeToNanoSeconds(TimeUnit.MILLISECONDS, time); assertEquals(time * 1000 * 1000, timeToNano); time = System.currentTimeMillis() * 1000 * 1000; timeToNano = TimeUtils.timeToNanoSeconds(TimeUnit.NANOSECONDS, time); assertEquals(time, timeToNano); }
|
### Question:
TimeUtils { public static int getWindowFlooredNaturalTime(int timeInSeconds, int bucketInSeconds) { return ((timeInSeconds / bucketInSeconds) * bucketInSeconds); } private TimeUtils(); static int getTimeBucket(TimeUnit unit, long timestamp, int bucketSizeInSeconds); static int getWindowFlooredBinaryTime(TimeUnit unit, long timestamp, int windowSizeInSeconds); static int timeToSeconds(TimeUnit unit, long time); static int timeToMilliSeconds(TimeUnit unit, long time); static long timeToNanoSeconds(TimeUnit unit, long time); static int getWindowFlooredNaturalTime(int timeInSeconds, int bucketInSeconds); static long getTimeFromBucketString(String hexTimeInSeconds); static long getTimeFromBucketString(int timeInSeconds); }### Answer:
@Test public void testFlooredNaturalTime() { int time = (int) (System.currentTimeMillis() / 1000); int windowFlooredNaturalTime = TimeUtils.getWindowFlooredNaturalTime(time, 3600); assertEquals((time / 3600) * 3600, windowFlooredNaturalTime); }
|
### Question:
MiscUtils { public static String tagToString(List<String> tags) { StringBuilder builder = new StringBuilder(); for (String tag : tags) { builder.append("/"); builder.append(tag); } return builder.toString(); } private MiscUtils(); static long bucketCounter(Series series); static String[] splitAndNormalizeString(String input); static List<String> readAllLines(File file); static DataPoint buildDataPoint(long timestamp, long value); static DataPoint buildDataPoint(long timestamp, double value); static void ls(File file); static boolean delete(File file); static String tagsToString(List<Tag> tags); static String tagToString(List<String> tags); static TagFilter buildTagFilter(String tagFilter); static SimpleTagFilter buildSimpleFilter(String item); static FunctionIteratorFactory createIteratorChain(String[] parts, int startIndex); static Function createFunctionChain(String[] parts, int startIndex); static TargetSeries extractTargetFromQuery(String query); static Point buildDP(String dbName, String measurementName, List<String> valueFieldName, List<Tag> tags,
long timestamp, List<Long> value, List<Boolean> fp); static String printBuffer(ByteBuffer buffer, int counter); static void writeStringToBuffer(String str, ByteBuffer buf); static void writeByteStringToBuffer(byte[] str, ByteBuffer buf); static ByteString getByteStringFromBuffer(ByteBuffer buf); static String getStringFromBuffer(ByteBuffer buf); static Point buildDataPoint(String dbName, String measurementName, List<String> valueFieldName,
List<Tag> taglist, long timestamp, List<Long> values, List<Boolean> fp); static Point buildDataPoint(String dbName, String measurementName, String valueFieldName, List<Tag> taglist,
long timestamp, long value); static Point buildDataPoint(String dbName, String measurementName, String valueFieldName, List<Tag> taglist,
long timestamp, double value); static int tagHashCode(List<Tag> tags); }### Answer:
@Test public void testTagToString() { String tagString = MiscUtils.tagToString(Arrays.asList("test", "test2")); assertEquals("/test/test2", tagString); }
|
### Question:
ByteUtils { public static List<String> jsonArrayToStringList(JsonArray array) { List<String> ary = new ArrayList<>(); for (JsonElement jsonElement : array) { ary.add(jsonElement.getAsString()); } return ary; } static byte[] md5(byte[] data); static byte[] sha1(byte[] data); static byte[] intToByteMSB(int in); static int bytesToIntMSB(byte[] bytes); static byte[] shortToByteMSB(short in); static byte[] stringToBytes(String input); static String byteAryToAscii(byte[] in); static List<String> jsonArrayToStringList(JsonArray array); static final Charset DEF_CHARSET; }### Answer:
@Test public void testJsonArrayToList() { JsonArray ary = new JsonArray(); ary.add("test"); ary.add("test1"); ary.add("test2"); List<String> list = ByteUtils.jsonArrayToStringList(ary); assertEquals("test", list.get(0)); assertEquals("test1", list.get(1)); assertEquals("test2", list.get(2)); }
|
### Question:
ByteUtils { public static String byteAryToAscii(byte[] in) { return new String(in, DEF_CHARSET); } static byte[] md5(byte[] data); static byte[] sha1(byte[] data); static byte[] intToByteMSB(int in); static int bytesToIntMSB(byte[] bytes); static byte[] shortToByteMSB(short in); static byte[] stringToBytes(String input); static String byteAryToAscii(byte[] in); static List<String> jsonArrayToStringList(JsonArray array); static final Charset DEF_CHARSET; }### Answer:
@Test public void testByteAryToAscii() { int time = 1380327876; System.out.println("time:" + new Date((long) time * 1000)); time = Integer.MAX_VALUE - time; System.out.println("inverted time:" + time); System.out.println("inverted time:" + new Date((long) time * 1000)); System.out.println("inverted time:" + ByteUtils.byteAryToAscii(ByteUtils.intToByteMSB(time))); System.out.println("max time:" + new Date((long) Integer.MAX_VALUE * 1000)); System.out.println("max time:" + ByteUtils.byteAryToAscii(ByteUtils.intToByteMSB(Integer.MAX_VALUE))); }
|
### Question:
MathUtils { public static double mean(double[] a) { double avg = 0; for (int i = 0; i < a.length; i++) { avg += a[i]; } avg = avg / a.length; return avg; } static double ppmcc(double[] a, double[] b); static double mean(double[] a); static long mean(long[] a); static double covariance(double[] a, double amean, double[] b, double bmean); static long standardDeviation(long[] a, long avg); static double standardDeviation(double[] a, double avg); static double[] ppmcc(double[][] ary, int baseIndex); }### Answer:
@Test public void testMean() { double[] a = new double[] { 2, 3, 4, 5, 6 }; double mean = MathUtils.mean(a); Mean cmean = new Mean(); assertEquals(cmean.evaluate(a), mean, 0.0001); }
|
### Question:
MathUtils { public static double covariance(double[] a, double amean, double[] b, double bmean) { double t = 0; for (int i = 0; i < a.length; i++) { t += (a[i] - amean) * (b[i] - bmean); } return t / a.length; } static double ppmcc(double[] a, double[] b); static double mean(double[] a); static long mean(long[] a); static double covariance(double[] a, double amean, double[] b, double bmean); static long standardDeviation(long[] a, long avg); static double standardDeviation(double[] a, double avg); static double[] ppmcc(double[][] ary, int baseIndex); }### Answer:
@Test public void testCovariance() { double[] a = new double[] { 2, 3, 4, 5, 6 }; double[] b = new double[] { 2.2, 33.2, 44.4, 55.5, 66.6 }; Covariance cov = new Covariance(); double covariance = cov.covariance(a, b, false); double amean = MathUtils.mean(a); double bmean = MathUtils.mean(b); assertEquals(covariance, MathUtils.covariance(a, amean, b, bmean), 0.001); }
|
### Question:
RangeSplitUtil { public static long[] doLongSplit(long left, long right, int expectSliceNumber) { BigInteger[] result = doBigIntegerSplit(BigInteger.valueOf(left), BigInteger.valueOf(right), expectSliceNumber); long[] returnResult = new long[result.length]; for (int i = 0, len = result.length; i < len; i++) { returnResult[i] = result[i].longValue(); } return returnResult; } static String[] doAsciiStringSplit(String left, String right, int expectSliceNumber); static long[] doLongSplit(long left, long right, int expectSliceNumber); static BigInteger[] doBigIntegerSplit(BigInteger left, BigInteger right, int expectSliceNumber); static BigInteger stringToBigInteger(String aString, int radix); static Pair<Character, Character> getMinAndMaxCharacter(String aString); }### Answer:
@Test public void testLong_00() { long count = 0; long left = 0; long right = count - 1; int expectSliceNumber = 3; long[] result = RangeSplitUtil.doLongSplit(left, right, expectSliceNumber); result[result.length - 1]++; for (int i = 0; i < result.length - 1; i++) { System.out.println("start:" + result[i] + " count:" + (result[i + 1] - result[i])); } System.out.println(Arrays.toString(result)); }
@Test public void testLong_01() { long count = 8; long left = 0; long right = count - 1; int expectSliceNumber = 3; long[] result = RangeSplitUtil.doLongSplit(left, right, expectSliceNumber); result[result.length - 1]++; for (int i = 0; i < result.length - 1; i++) { System.out.println("start:" + result[i] + " count:" + (result[i + 1] - result[i])); } Assert.assertTrue(result.length - 1 == expectSliceNumber); System.out.println(Arrays.toString(result)); }
|
### Question:
RangeSplitUtil { public static Pair<Character, Character> getMinAndMaxCharacter(String aString) { if (!isPureAscii(aString)) { throw new IllegalArgumentException(String.format("根据字符串进行切分时仅支持 ASCII 字符串,而字符串:[%s]非 ASCII 字符串.", aString)); } char min = aString.charAt(0); char max = min; char temp; for (int i = 1, len = aString.length(); i < len; i++) { temp = aString.charAt(i); min = min < temp ? min : temp; max = max > temp ? max : temp; } return new ImmutablePair<Character, Character>(min, max); } static String[] doAsciiStringSplit(String left, String right, int expectSliceNumber); static long[] doLongSplit(long left, long right, int expectSliceNumber); static BigInteger[] doBigIntegerSplit(BigInteger left, BigInteger right, int expectSliceNumber); static BigInteger stringToBigInteger(String aString, int radix); static Pair<Character, Character> getMinAndMaxCharacter(String aString); }### Answer:
@Test public void testGetMinAndMaxCharacter() { Pair<Character, Character> result = RangeSplitUtil.getMinAndMaxCharacter("abc%^&"); Assert.assertEquals('%', result.getLeft().charValue()); Assert.assertEquals('c', result.getRight().charValue()); result = RangeSplitUtil.getMinAndMaxCharacter("\tAabcZx"); Assert.assertEquals('\t', result.getLeft().charValue()); Assert.assertEquals('x', result.getRight().charValue()); }
|
### Question:
ListUtil { public static List<String> valueToLowerCase(List<String> aList) { if (null == aList || aList.isEmpty()) { throw new IllegalArgumentException("您提供的作业配置有误, List不能为空."); } List<String> result = new ArrayList<String>(aList.size()); for (String oneValue : aList) { result.add(null != oneValue ? oneValue.toLowerCase() : null); } return result; } static boolean checkIfValueDuplicate(List<String> aList,
boolean caseSensitive); static void makeSureNoValueDuplicate(List<String> aList,
boolean caseSensitive); static boolean checkIfBInA(List<String> aList, List<String> bList,
boolean caseSensitive); static void makeSureBInA(List<String> aList, List<String> bList,
boolean caseSensitive); static boolean checkIfValueSame(List<Boolean> aList); static List<String> valueToLowerCase(List<String> aList); }### Answer:
@Test public void testValueToLowerCase() { List<String> list = new ArrayList<String>(aList); for (int i = 0, len = list.size(); i < len; i++) { list.set(i, list.get(i).toLowerCase()); } Assert.assertArrayEquals(list.toArray(), ListUtil.valueToLowerCase(list).toArray()); }
|
### Question:
ListUtil { public static boolean checkIfValueSame(List<Boolean> aList) { if (null == aList || aList.isEmpty()) { throw new IllegalArgumentException("您提供的作业配置有误, List不能为空."); } if (1 == aList.size()) { return true; } else { Boolean firstValue = aList.get(0); for (int i = 1, len = aList.size(); i < len; i++) { if (firstValue.booleanValue() != aList.get(i).booleanValue()) { return false; } } return true; } } static boolean checkIfValueDuplicate(List<String> aList,
boolean caseSensitive); static void makeSureNoValueDuplicate(List<String> aList,
boolean caseSensitive); static boolean checkIfBInA(List<String> aList, List<String> bList,
boolean caseSensitive); static void makeSureBInA(List<String> aList, List<String> bList,
boolean caseSensitive); static boolean checkIfValueSame(List<Boolean> aList); static List<String> valueToLowerCase(List<String> aList); }### Answer:
@Test public void testCheckIfValueSame() { List<Boolean> boolList = new ArrayList<Boolean>(); boolList.add(true); boolList.add(true); boolList.add(true); Assert.assertTrue(boolList + " all value same.", ListUtil.checkIfValueSame(boolList)); boolList.add(false); Assert.assertTrue(boolList + "not all value same.", ListUtil.checkIfValueSame(boolList) == false); }
|
### Question:
ListUtil { public static boolean checkIfBInA(List<String> aList, List<String> bList, boolean caseSensitive) { if (null == aList || aList.isEmpty() || null == bList || bList.isEmpty()) { throw new IllegalArgumentException("您提供的作业配置有误, List不能为空."); } try { makeSureBInA(aList, bList, caseSensitive); } catch (Exception e) { return false; } return true; } static boolean checkIfValueDuplicate(List<String> aList,
boolean caseSensitive); static void makeSureNoValueDuplicate(List<String> aList,
boolean caseSensitive); static boolean checkIfBInA(List<String> aList, List<String> bList,
boolean caseSensitive); static void makeSureBInA(List<String> aList, List<String> bList,
boolean caseSensitive); static boolean checkIfValueSame(List<Boolean> aList); static List<String> valueToLowerCase(List<String> aList); }### Answer:
@Test public void testCheckIfBInA() { List<String> bList = new ArrayList<String>(aList); bList.set(0, bList.get(0) + "_hello"); Assert.assertTrue(bList + " not all in " + aList, ListUtil.checkIfBInA(aList, bList, false) == false); Assert.assertTrue(bList + " not all in " + aList, ListUtil.checkIfBInA(aList, bList, true) == false); bList = new ArrayList<String>(aList); bList.set(0, bList.get(0).toUpperCase()); Assert.assertTrue(bList + " all in " + aList, ListUtil.checkIfBInA(aList, bList, false)); bList = new ArrayList<String>(aList); bList.set(0, bList.get(0).toUpperCase()); Assert.assertTrue(bList + " not all in " + aList, ListUtil.checkIfBInA(aList, bList, true) == false); }
|
### Question:
BoolColumn extends Column { @Override public Boolean asBoolean() { if (null == super.getRawData()) { return null; } return (Boolean) super.getRawData(); } BoolColumn(Boolean bool); BoolColumn(final String data); BoolColumn(); @Override Boolean asBoolean(); @Override Long asLong(); @Override Double asDouble(); @Override String asString(); @Override BigInteger asBigInteger(); @Override BigDecimal asBigDecimal(); @Override Date asDate(); @Override byte[] asBytes(); }### Answer:
@Test public void test_nullReference() { Boolean b = null; BoolColumn boolColumn = new BoolColumn(b); Assert.assertTrue(boolColumn.asBoolean() == null); }
|
### Question:
StringColumn extends Column { @Override public BigDecimal asBigDecimal() { if (null == this.getRawData()) { return null; } this.validateDoubleSpecific((String) this.getRawData()); try { return new BigDecimal(this.asString()); } catch (Exception e) { throw DataXException.asDataXException( CommonErrorCode.CONVERT_NOT_SUPPORT, String.format( "String [\"%s\"] 不能转为BigDecimal .", this.asString())); } } StringColumn(); StringColumn(final String rawData); @Override String asString(); @Override BigInteger asBigInteger(); @Override Long asLong(); @Override BigDecimal asBigDecimal(); @Override Double asDouble(); @Override Boolean asBoolean(); @Override Date asDate(); @Override byte[] asBytes(); }### Answer:
@Test public void testEmptyString() { StringColumn column = new StringColumn(""); try { BigDecimal num = column.asBigDecimal(); } catch(Exception e) { Assert.assertTrue(e.getMessage().contains("String [\"\"] 不能转为BigDecimal")); } }
|
### Question:
GeneratedAnnotationPolicy implements AnnotationPolicy { @Override public void apply(@Nonnull TypeSpec.Builder builder) { builder.addAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", klass.getCanonicalName()) .build()); } GeneratedAnnotationPolicy(@Nonnull Class<?> klass); @Override void apply(@Nonnull TypeSpec.Builder builder); }### Answer:
@Test public void applyShouldAddGeneratedAnnotation() throws Exception { final TypeSpec.Builder builder = TypeSpec.classBuilder("Test"); underTest.apply(builder); assertThat(builder.build()) .hasName("Test") .hasAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", this.getClass().getCanonicalName()) .build()); }
|
### Question:
ClassPrefixValidator implements InputValidatorEx { @Override public boolean canClose(@Nullable String prefix) { if (Strings.isNullOrEmpty(prefix)) { return true; } if (!nameHelper.isIdentifier(prefix)) { return false; } final char first = prefix.charAt(0); return StringUtil.isJavaIdentifierStart(first); } @Inject ClassPrefixValidator(@NotNull Json2JavaBundle bundle, @NotNull PsiNameHelper nameHelper); @Nullable @Override String getErrorText(@Nullable String prefix); @Override boolean checkInput(@Nullable String prefix); @Override boolean canClose(@Nullable String prefix); }### Answer:
@Test public void canCloseShouldReturnTrueWhenNull() throws Exception { final boolean actual = underTest.canClose(null); assertThat(actual) .overridingErrorMessage("Expected value returned by canClose is true, but was false") .isTrue(); }
@Test public void canCloseShouldReturnTrueWhenValid() throws Exception { final boolean actual = underTest.canClose("Foo"); assertThat(actual) .overridingErrorMessage("Expected value returned by canClose is true, but was false") .isTrue(); }
@Test public void canCloseShouldReturnFalseWhenReserved() throws Exception { final boolean actual = underTest.canClose("private"); assertThat(actual) .overridingErrorMessage("Expected value returned by canClose is false, but was true") .isFalse(); }
@Test public void canCloseShouldReturnFalseWhenInvalid() throws Exception { final boolean actual = underTest.canClose("^invalid"); assertThat(actual) .overridingErrorMessage("Expected value returned by canClose is false, but was true") .isFalse(); }
|
### Question:
ClassSuffixValidator implements InputValidatorEx { @Nullable @Override public String getErrorText(@Nullable String suffix) { if (canClose(suffix)) { return null; } return bundle.message("error.message.validator.class.suffix", suffix); } @Inject ClassSuffixValidator(@NotNull Json2JavaBundle bundle, @NotNull PsiNameHelper nameHelper); @Nullable @Override String getErrorText(@Nullable String suffix); @Override boolean checkInput(@Nullable String suffix); @Override boolean canClose(@Nullable String suffix); }### Answer:
@Test public void getErrorTextShouldReturnNullWhenValid() throws Exception { final String actual = underTest.getErrorText("Foo"); assertThat(actual) .overridingErrorMessage("Expected value returned by getErrorText is null, but was <%s>", actual) .isNull(); }
@Test public void getErrorTextShouldReturnTextWhenInvalid() throws Exception { final String actual = underTest.getErrorText("^Foo"); assertThat(actual) .overridingErrorMessage("Expected value returned by getErrorText is null, but was <%s>", actual) .isNotEmpty(); }
|
### Question:
ClassSuffixValidator implements InputValidatorEx { @Override public boolean checkInput(@Nullable String suffix) { return true; } @Inject ClassSuffixValidator(@NotNull Json2JavaBundle bundle, @NotNull PsiNameHelper nameHelper); @Nullable @Override String getErrorText(@Nullable String suffix); @Override boolean checkInput(@Nullable String suffix); @Override boolean canClose(@Nullable String suffix); }### Answer:
@Test public void checkInputShouldAlwaysReturnTrue() throws Exception { final boolean actual = underTest.checkInput("foo"); assertThat(actual) .overridingErrorMessage("Expected value returned by checkInput is true, but was false") .isTrue(); }
|
### Question:
ClassSuffixValidator implements InputValidatorEx { @Override public boolean canClose(@Nullable String suffix) { if (Strings.isNullOrEmpty(suffix)) { return true; } return nameHelper.isIdentifier(suffix); } @Inject ClassSuffixValidator(@NotNull Json2JavaBundle bundle, @NotNull PsiNameHelper nameHelper); @Nullable @Override String getErrorText(@Nullable String suffix); @Override boolean checkInput(@Nullable String suffix); @Override boolean canClose(@Nullable String suffix); }### Answer:
@Test public void canCloseShouldReturnTrueWhenNull() throws Exception { final boolean actual = underTest.canClose(null); assertThat(actual) .overridingErrorMessage("Expected value returned by canClose is true, but was false") .isTrue(); }
@Test public void canCloseShouldReturnTrueWhenValid() throws Exception { final boolean actual = underTest.canClose("Foo"); assertThat(actual) .overridingErrorMessage("Expected value returned by canClose is true, but was false") .isTrue(); }
@Test public void canCloseShouldReturnFalseWhenReserved() throws Exception { final boolean actual = underTest.canClose("private"); assertThat(actual) .overridingErrorMessage("Expected value returned by canClose is false, but was true") .isFalse(); }
@Test public void canCloseShouldReturnFalseWhenInvalid() throws Exception { final boolean actual = underTest.canClose("+-/*"); assertThat(actual) .overridingErrorMessage("Expected value returned by canClose is false, but was true") .isFalse(); }
|
### Question:
NullValidator implements InputValidator { @Override public boolean checkInput(@Nullable String text) { return false; } @Override boolean checkInput(@Nullable String text); @Override boolean canClose(@Nullable String text); }### Answer:
@Test public void checkInputShouldAlwaysReturnFalse() throws Exception { final boolean actual = underTest.checkInput("text"); assertThat(actual) .overridingErrorMessage("Expected value returned by checkInput is false but was true") .isFalse(); }
|
### Question:
NullValidator implements InputValidator { @Override public boolean canClose(@Nullable String text) { return false; } @Override boolean checkInput(@Nullable String text); @Override boolean canClose(@Nullable String text); }### Answer:
@Test public void canCloseShouldAlwaysReturnFalse() throws Exception { final boolean actual = underTest.canClose("text"); assertThat(actual) .overridingErrorMessage("Expected value returned by canClose is false but was true") .isFalse(); }
|
### Question:
NameValidator implements InputValidatorEx { @Nullable @Override public String getErrorText(@Nullable String name) { if (nameHelper.isQualifiedName(name)) { return null; } return bundle.message("error.message.validator.name.invalid"); } @Inject NameValidator(@Nonnull Json2JavaBundle bundle, @Nonnull PsiNameHelper nameHelper); @Nullable @Override String getErrorText(@Nullable String name); @Override boolean checkInput(@Nullable String name); @Override @SuppressWarnings("RedundantIfStatement") boolean canClose(@Nullable String name); }### Answer:
@Test @SuppressWarnings("ResultOfMethodCallIgnored") public void getErrorTextShouldReturnTextWhenNameIsInvalid() throws Exception { final String actual = underTest.getErrorText("private"); assertThat(actual) .overridingErrorMessage("Expected value returned by getErrorText is not empty, but was <%s>", actual) .isNotEmpty(); verify(bundle).message(eq("error.message.validator.name.invalid")); }
@Test public void getErrorTextShouldReturnNullWhenNameIsValid() throws Exception { final String actual = underTest.getErrorText("Test"); assertThat(actual) .overridingErrorMessage("Expected value returned by getErrorText is null, but was <%s>", actual) .isNull(); }
|
### Question:
NameValidator implements InputValidatorEx { @Override public boolean checkInput(@Nullable String name) { return true; } @Inject NameValidator(@Nonnull Json2JavaBundle bundle, @Nonnull PsiNameHelper nameHelper); @Nullable @Override String getErrorText(@Nullable String name); @Override boolean checkInput(@Nullable String name); @Override @SuppressWarnings("RedundantIfStatement") boolean canClose(@Nullable String name); }### Answer:
@Test public void checkInputShouldAlwaysReturnTrue() throws Exception { final boolean actual = underTest.checkInput("test"); assertThat(actual) .overridingErrorMessage("Expected value returned by checkInput is true, but was false") .isTrue(); }
|
### Question:
NameValidator implements InputValidatorEx { @Override @SuppressWarnings("RedundantIfStatement") public boolean canClose(@Nullable String name) { return nameHelper.isQualifiedName(name); } @Inject NameValidator(@Nonnull Json2JavaBundle bundle, @Nonnull PsiNameHelper nameHelper); @Nullable @Override String getErrorText(@Nullable String name); @Override boolean checkInput(@Nullable String name); @Override @SuppressWarnings("RedundantIfStatement") boolean canClose(@Nullable String name); }### Answer:
@Test public void canCloseShouldReturnTrueWhenNameIsValid() throws Exception { final boolean actual = underTest.canClose("Test"); assertThat(actual) .overridingErrorMessage("Expected value returned by canClose is true, but was false") .isTrue(); }
@Test public void canCloseShouldReturnFalseWhenNameIsInvalid() throws Exception { final boolean actual = underTest.canClose("private"); assertThat(actual) .overridingErrorMessage("Expected value returned by canClose is false, but was true") .isFalse(); }
|
### Question:
JsonArray extends JsonValue { @Nonnull @Override public TypeName getType() { return ParameterizedTypeName.get(List.class, Object.class); } JsonArray(@Nonnull List<Object> value); @Nonnull @Override TypeName getType(); @Nonnull @Override List<Object> getValue(); @Nonnull @CheckReturnValue Stream<JsonValue> stream(); }### Answer:
@Test public void getType() throws Exception { final TypeName actual = underTest.getType(); assertThat(actual) .isEqualTo(ParameterizedTypeName.get(List.class, Object.class)); }
|
### Question:
JsonArray extends JsonValue { @Nonnull @Override public List<Object> getValue() { return ImmutableList.copyOf(value); } JsonArray(@Nonnull List<Object> value); @Nonnull @Override TypeName getType(); @Nonnull @Override List<Object> getValue(); @Nonnull @CheckReturnValue Stream<JsonValue> stream(); }### Answer:
@Test public void getValues() throws Exception { final List<Object> actual = underTest.getValue(); assertThat(actual) .hasSize(4) .containsOnlyOnce("foo", "bar", "baz", "qux"); }
|
### Question:
JsonArray extends JsonValue { @Nonnull @CheckReturnValue public Stream<JsonValue> stream() { return value.stream().map(JsonValue::wrap); } JsonArray(@Nonnull List<Object> value); @Nonnull @Override TypeName getType(); @Nonnull @Override List<Object> getValue(); @Nonnull @CheckReturnValue Stream<JsonValue> stream(); }### Answer:
@Test public void stream() throws Exception { final Stream<JsonValue> actual = underTest.stream(); assertThat(actual) .hasSize(4) .doesNotContainNull(); }
|
### Question:
JsonNumber extends JsonValue { @Nonnull @Override public TypeName getType() { return TypeName.get(type); } JsonNumber(@Nonnull Type type, @Nonnull Number value); @Nonnull @Override TypeName getType(); @Nonnull @Override Number getValue(); }### Answer:
@Test public void getType() throws Exception { final TypeName actual = underTest.getType(); assertThat(actual) .isEqualTo(TypeName.INT); }
|
### Question:
SuppressWarningsAnnotationPolicy implements AnnotationPolicy { @Override public void apply(@Nonnull TypeSpec.Builder builder) { builder.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class) .addMember("value", "$S", value) .build()); } SuppressWarningsAnnotationPolicy(@Nonnull String value); @Override void apply(@Nonnull TypeSpec.Builder builder); }### Answer:
@Test public void applyShouldAddGeneratedAnnotation() throws Exception { final TypeSpec.Builder builder = TypeSpec.classBuilder("Test"); underTest.apply(builder); assertThat(builder.build()) .hasName("Test") .hasAnnotation(AnnotationSpec.builder(SuppressWarnings.class) .addMember("value", "$S", "all") .build()); }
|
### Question:
JsonNumber extends JsonValue { @Nonnull @Override public Number getValue() { return value; } JsonNumber(@Nonnull Type type, @Nonnull Number value); @Nonnull @Override TypeName getType(); @Nonnull @Override Number getValue(); }### Answer:
@Test public void getValue() throws Exception { final Number actual = underTest.getValue(); assertThat(actual) .isInstanceOf(Integer.class) .isEqualTo(42); }
|
### Question:
JsonObject extends JsonValue { @Nonnull @Override public TypeName getType() { return ParameterizedTypeName.get(Map.class, String.class, Object.class); } JsonObject(@Nonnull Map<String, Object> value); @Nonnull @Override TypeName getType(); @Nonnull @Override Map<String, Object> getValue(); @Nonnull @CheckReturnValue Stream<Map.Entry<String, JsonValue>> stream(); }### Answer:
@Test public void getType() throws Exception { final TypeName actual = underTest.getType(); assertThat(actual) .isEqualTo(ParameterizedTypeName.get(Map.class, String.class, Object.class)); }
|
### Question:
JsonObject extends JsonValue { @Nonnull @Override public Map<String, Object> getValue() { return ImmutableMap.copyOf(value); } JsonObject(@Nonnull Map<String, Object> value); @Nonnull @Override TypeName getType(); @Nonnull @Override Map<String, Object> getValue(); @Nonnull @CheckReturnValue Stream<Map.Entry<String, JsonValue>> stream(); }### Answer:
@Test public void getValue() throws Exception { final Map<String, Object> actual = underTest.getValue(); assertThat(actual) .hasSize(2) .containsEntry("foo", 42) .containsEntry("bar", 32); }
|
### Question:
JsonObject extends JsonValue { @Nonnull @CheckReturnValue public Stream<Map.Entry<String, JsonValue>> stream() { return value.entrySet() .stream() .map(entry -> { final String name = entry.getKey(); final Object value = entry.getValue(); return new HashMap.SimpleImmutableEntry<>(name, wrap(value)); }); } JsonObject(@Nonnull Map<String, Object> value); @Nonnull @Override TypeName getType(); @Nonnull @Override Map<String, Object> getValue(); @Nonnull @CheckReturnValue Stream<Map.Entry<String, JsonValue>> stream(); }### Answer:
@Test public void stream() throws Exception { final Stream<Map.Entry<String, JsonValue>> actual = underTest.stream(); assertThat(actual) .hasSize(2) .doesNotContainNull(); }
|
### Question:
JsonString extends JsonValue { @Nonnull @Override public TypeName getType() { return ClassName.get(String.class); } JsonString(@Nonnull String value); @Nonnull @Override TypeName getType(); @Nonnull @Override String getValue(); }### Answer:
@Test public void getType() throws Exception { final TypeName actual = underTest.getType(); assertThat(actual) .isEqualTo(ClassName.get(String.class)); }
|
### Question:
JsonString extends JsonValue { @Nonnull @Override public String getValue() { return value; } JsonString(@Nonnull String value); @Nonnull @Override TypeName getType(); @Nonnull @Override String getValue(); }### Answer:
@Test public void getValue() throws Exception { final String actual = underTest.getValue(); assertThat(actual) .isEqualTo("foo"); }
|
### Question:
JsonBoolean extends JsonValue { @Nonnull @Override public TypeName getType() { return TypeName.BOOLEAN; } JsonBoolean(boolean value); @Nonnull @Override TypeName getType(); @Nonnull @Override Boolean getValue(); }### Answer:
@Test public void getType() throws Exception { final TypeName actual = underTest.getType(); assertThat(actual) .isEqualTo(TypeName.BOOLEAN); }
|
### Question:
JsonBoolean extends JsonValue { @Nonnull @Override public Boolean getValue() { return value; } JsonBoolean(boolean value); @Nonnull @Override TypeName getType(); @Nonnull @Override Boolean getValue(); }### Answer:
@Test public void getValue() throws Exception { final Boolean actual = underTest.getValue(); assertThat(actual) .isNotNull() .isTrue(); }
|
### Question:
JavaBuilderImpl implements JavaBuilder { @Nonnull @Override public String build(@Nonnull String packageName, @Nonnull TypeSpec typeSpec) throws JavaBuildException { return JavaFile.builder(packageName, typeSpec) .indent(INDENT) .skipJavaLangImports(true) .build() .toString(); } @Nonnull @Override String build(@Nonnull String packageName, @Nonnull TypeSpec typeSpec); }### Answer:
@Test public void buildShouldReturnJavaCode() throws Exception { final TypeSpec typeSpec = TypeSpec.classBuilder("Test") .addModifiers(Modifier.PUBLIC) .build(); final String actual = underTest.build("io.t28.example", typeSpec); assertThat(actual) .isEqualTo("package io.t28.example;\n\npublic class Test {\n}\n"); }
|
### Question:
JsonNull extends JsonValue { @Nonnull @Override public TypeName getType() { return TypeName.OBJECT; } @Nonnull @Override TypeName getType(); @Nullable @Override Object getValue(); }### Answer:
@Test public void getType() throws Exception { final TypeName actual = underTest.getType(); assertThat(actual) .isEqualTo(TypeName.OBJECT); }
|
### Question:
MoshiClassBuilder extends ClassBuilder { @Nonnull @Override protected List<FieldSpec> buildFields() { return getProperties().entrySet().stream().map(property -> { final String name = property.getKey(); final TypeName type = property.getValue(); final String fieldName = fieldNamePolicy.convert(name, type); return FieldSpec.builder(type, fieldName) .addModifiers(Modifier.PRIVATE, Modifier.FINAL) .addAnnotation(AnnotationSpec.builder(Json.class) .addMember("name", "$S", name) .build()) .build(); }).collect(Collectors.toList()); } MoshiClassBuilder(@Nonnull NamePolicy fieldNamePolicy,
@Nonnull NamePolicy methodNamePolicy,
@Nonnull NamePolicy parameterNamePolicy); }### Answer:
@Test public void buildFields() throws Exception { underTest.addProperty("foo", TypeName.INT) .addProperty("bar", TypeName.OBJECT) .addProperty("baz", TypeName.BOOLEAN); final List<FieldSpec> actual = underTest.buildFields(); assertThat(actual) .hasSize(3) .doesNotContainNull(); assertThat(actual.get(0)) .hasType(TypeName.INT) .hasName("foo") .isPrivate() .isFinal() .hasNoInitializer() .hasAnnotation(AnnotationSpec.builder(Json.class) .addMember("name", "$S", "foo") .build()); assertThat(actual.get(1)) .hasType(TypeName.OBJECT) .hasName("bar") .isPrivate() .isFinal() .hasNoInitializer() .hasAnnotation(AnnotationSpec.builder(Json.class) .addMember("name", "$S", "bar") .build()); assertThat(actual.get(2)) .hasType(TypeName.BOOLEAN) .hasName("baz") .isPrivate() .isFinal() .hasNoInitializer() .hasAnnotation(AnnotationSpec.builder(Json.class) .addMember("name", "$S", "baz") .build()); }
|
### Question:
GsonClassBuilder extends ClassBuilder { @Nonnull @Override protected List<FieldSpec> buildFields() { return getProperties() .entrySet() .stream() .map(property -> { final String name = property.getKey(); final TypeName type = property.getValue(); final String fieldName = fieldNamePolicy.convert(name, type); return FieldSpec.builder(type, fieldName) .addModifiers(Modifier.PRIVATE, Modifier.FINAL) .addAnnotation(AnnotationSpec.builder(SerializedName.class) .addMember("value", "$S", name) .build()) .build(); }) .collect(Collectors.toList()); } GsonClassBuilder(@Nonnull NamePolicy fieldNamePolicy,
@Nonnull NamePolicy methodNamePolicy,
@Nonnull NamePolicy parameterNamePolicy); }### Answer:
@Test public void buildFields() throws Exception { underTest.addProperty("foo", TypeName.INT) .addProperty("bar", TypeName.OBJECT) .addProperty("baz", TypeName.BOOLEAN); final List<FieldSpec> actual = underTest.buildFields(); assertThat(actual) .hasSize(3) .doesNotContainNull(); assertThat(actual.get(0)) .hasType(TypeName.INT) .hasName("foo") .isPrivate() .isFinal() .hasNoInitializer() .hasAnnotation(AnnotationSpec.builder(SerializedName.class) .addMember("value", "$S", "foo") .build()); assertThat(actual.get(1)) .hasType(TypeName.OBJECT) .hasName("bar") .isPrivate() .isFinal() .hasNoInitializer() .hasAnnotation(AnnotationSpec.builder(SerializedName.class) .addMember("value", "$S", "bar") .build()); assertThat(actual.get(2)) .hasType(TypeName.BOOLEAN) .hasName("baz") .isPrivate() .isFinal() .hasNoInitializer() .hasAnnotation(AnnotationSpec.builder(SerializedName.class) .addMember("value", "$S", "baz") .build()); }
|
### Question:
JsonNull extends JsonValue { @Nullable @Override public Object getValue() { return null; } @Nonnull @Override TypeName getType(); @Nullable @Override Object getValue(); }### Answer:
@Test public void getValue() throws Exception { final Object actual = underTest.getValue(); assertThat(actual) .isNull(); }
|
### Question:
ModelClassBuilder extends ClassBuilder { @Nonnull @Override protected List<FieldSpec> buildFields() { return getProperties() .entrySet() .stream() .map(property -> { final String name = property.getKey(); final TypeName type = property.getValue(); final String fieldName = fieldNamePolicy.convert(name, type); return FieldSpec.builder(type, fieldName) .addModifiers(Modifier.PRIVATE, Modifier.FINAL) .build(); }) .collect(Collectors.toList()); } ModelClassBuilder(@Nonnull NamePolicy fieldNameStrategy,
@Nonnull NamePolicy methodNameStrategy,
@Nonnull NamePolicy parameterNameStrategy); }### Answer:
@Test public void buildFields() throws Exception { underTest.addProperty("foo", TypeName.INT) .addProperty("bar", TypeName.OBJECT) .addProperty("baz", TypeName.BOOLEAN); final List<FieldSpec> actual = underTest.buildFields(); assertThat(actual) .hasSize(3) .doesNotContainNull(); assertThat(actual.get(0)) .hasType(TypeName.INT) .hasName("foo") .hasNoJavadoc() .hasNoAnnotation() .hasModifier(Modifier.PRIVATE, Modifier.FINAL) .hasNoInitializer(); assertThat(actual.get(1)) .hasType(TypeName.OBJECT) .hasName("bar") .hasNoJavadoc() .hasNoAnnotation() .hasModifier(Modifier.PRIVATE, Modifier.FINAL) .hasNoInitializer(); assertThat(actual.get(2)) .hasType(TypeName.BOOLEAN) .hasName("baz") .hasNoJavadoc() .hasNoAnnotation() .hasModifier(Modifier.PRIVATE, Modifier.FINAL) .hasNoInitializer(); }
|
### Question:
JacksonClassBuilder extends ClassBuilder { @Nonnull @Override protected List<FieldSpec> buildFields() { return getProperties().entrySet() .stream() .map(property -> { final String name = property.getKey(); final TypeName type = property.getValue(); final String fieldName = fieldNamePolicy.convert(name, type); return FieldSpec.builder(type, fieldName) .addModifiers(Modifier.PRIVATE, Modifier.FINAL) .build(); }) .collect(Collectors.toList()); } JacksonClassBuilder(@Nonnull NamePolicy fieldNamePolicy,
@Nonnull NamePolicy methodNamePolicy,
@Nonnull NamePolicy parameterNamePolicy); }### Answer:
@Test public void buildFields() throws Exception { underTest.addProperty("foo", TypeName.INT) .addProperty("bar", TypeName.OBJECT) .addProperty("baz", TypeName.BOOLEAN); final List<FieldSpec> actual = underTest.buildFields(); assertThat(actual) .hasSize(3) .doesNotContainNull(); assertThat(actual.get(0)) .hasType(TypeName.INT) .hasName("foo") .isPrivate() .isFinal() .hasNoInitializer() .hasNoAnnotation(); assertThat(actual.get(1)) .hasType(TypeName.OBJECT) .hasName("bar") .isPrivate() .isFinal() .hasNoInitializer() .hasNoAnnotation(); assertThat(actual.get(2)) .hasType(TypeName.BOOLEAN) .hasName("baz") .isPrivate() .isFinal() .hasNoInitializer() .hasNoAnnotation(); }
|
### Question:
PsiTypeConverter implements Function<TypeName, PsiType> { @Nonnull @CheckReturnValue @Override public PsiType apply(@Nonnull TypeName typeName) { return Stream.of(PrimitiveType.values()) .filter(primitiveType -> primitiveType.isSameAs(typeName)) .map(PrimitiveType::psiType) .findFirst() .orElseGet(() -> PsiType.getJavaLangObject(psiManager, GlobalSearchScope.EMPTY_SCOPE)); } @Inject PsiTypeConverter(@Nonnull PsiManager psiManager); @Nonnull @CheckReturnValue @Override PsiType apply(@Nonnull TypeName typeName); }### Answer:
@Test public void apply() throws Exception { final PsiType actual = underTest.apply(typeName); assertThat(actual) .isEqualTo(expected); }
|
### Question:
Extensions { @Nonnull @CheckReturnValue public static String remove(@Nonnull String fileName, @Nonnull FileType fileType) { final String extension = fileType.getDefaultExtension(); if (fileName.endsWith(DELIMITER + extension)) { return fileName.substring(0, fileName.length() - (extension.length() + 1)); } return fileName; } private Extensions(); @Nonnull @CheckReturnValue static String remove(@Nonnull String fileName, @Nonnull FileType fileType); @Nonnull @CheckReturnValue static String append(@Nonnull String fileName, @Nonnull FileType fileType); }### Answer:
@Test public void removeShouldRemoveExtension() throws Exception { final String actual = Extensions.remove("foo.java", JavaFileType.INSTANCE); assertThat(actual) .isEqualTo("foo"); }
@Test public void removeShouldNotRemoveExtensionWhenNotMatch() throws Exception { final String actual = Extensions.remove("foo.java.tmp", JavaFileType.INSTANCE); assertThat(actual) .isEqualTo("foo.java.tmp"); }
@Test public void removeShouldReturnFileNameWhenExtensionDoesNotExist() throws Exception { final String actual = Extensions.remove("foo", JavaFileType.INSTANCE); assertThat(actual) .isEqualTo("foo"); }
|
### Question:
Extensions { @Nonnull @CheckReturnValue public static String append(@Nonnull String fileName, @Nonnull FileType fileType) { final String extension = fileType.getDefaultExtension(); if (fileName.endsWith(DELIMITER + extension)) { return fileName; } return fileName + DELIMITER + extension; } private Extensions(); @Nonnull @CheckReturnValue static String remove(@Nonnull String fileName, @Nonnull FileType fileType); @Nonnull @CheckReturnValue static String append(@Nonnull String fileName, @Nonnull FileType fileType); }### Answer:
@Test public void appendShouldAppendExtension() throws Exception { final String actual = Extensions.append("foo", JavaFileType.INSTANCE); assertThat(actual) .isEqualTo("foo.java"); }
@Test public void appendShouldNotAppendExtensionWhenExtensionExists() throws Exception { final String actual = Extensions.append("foo.java", JavaFileType.INSTANCE); assertThat(actual) .isEqualTo("foo.java"); }
@Test public void appendShouldAppendExtensionWhenAnotherExtensionExists() throws Exception { final String actual = Extensions.append("foo.tmp", JavaFileType.INSTANCE); assertThat(actual) .isEqualTo("foo.tmp.java"); }
|
### Question:
Formatter { @NotNull @CheckReturnValue public String format(@Nonnull String text) { final String name = Extensions.append(NAME, fileType); final PsiFile file = fileFactory.createFileFromText(name, fileType, text); final CodeStyleManager styleManager = CodeStyleManager.getInstance(file.getProject()); styleManager.reformat(file); return file.getText(); } Formatter(@Nonnull PsiFileFactory fileFactory, @Nonnull FileType fileType); @NotNull @CheckReturnValue String format(@Nonnull String text); }### Answer:
@Test public void formatShouldReformatText() throws Exception { getApplication().invokeAndWait(() -> { final Formatter underTest = new Formatter(fileFactory, JsonFileType.INSTANCE); final String actual = underTest.format("{\"key\":\"value\",\"array\":[\"foo\",\"bar\"]}"); assertThat(actual) .isEqualTo("{\n \"key\": \"value\",\n \"array\": [\n \"foo\",\n \"bar\"\n ]\n}"); }); }
|
### Question:
FieldNamePolicy implements NamePolicy { @Nonnull @Override public String convert(@Nonnull String name, @Nonnull TypeName type) { final String propertyName = DefaultNamePolicy.format(name, CaseFormat.LOWER_CAMEL); final String fieldName = codeStyleManager.propertyNameToVariableName(propertyName, VariableKind.FIELD); if (Strings.isNullOrEmpty(fieldName)) { throw new IllegalArgumentException("Cannot convert '" + name + "' to a field name"); } return fieldName; } @Inject FieldNamePolicy(@Nonnull JavaCodeStyleManager codeStyleManager); @Nonnull @Override String convert(@Nonnull String name, @Nonnull TypeName type); }### Answer:
@Test public void convertShouldReturnLowerCamelText() throws Exception { final String actual = underTest.convert("Foo", TypeName.OBJECT); assertThat(actual) .isEqualTo("foo"); }
@Test public void convertShouldReturnTextWithPrefixWhenReserved() throws Exception { final String actual = underTest.convert("Private", TypeName.OBJECT); assertThat(actual) .isEqualTo("aPrivate"); }
@Test public void convertShouldRemoveInvalidCharacter() throws Exception { final String actual = underTest.convert("1nva|id", TypeName.OBJECT); assertThat(actual) .isEqualTo("a1nvaid"); }
@Test @SuppressWarnings("ResultOfMethodCallIgnored") public void convertShouldThrowExceptionWhenInvalidName() throws Exception { assertThatThrownBy(() -> { underTest.convert("+-*/", TypeName.OBJECT); }).isInstanceOf(IllegalArgumentException.class); }
|
### Question:
MethodNamePolicy implements NamePolicy { @Nonnull @Override public String convert(@Nonnull String name, @Nonnull TypeName type) { final String variableName = DefaultNamePolicy.format(name, CaseFormat.UPPER_CAMEL); if (Strings.isNullOrEmpty(variableName)) { throw new IllegalArgumentException("Cannot convert '" + name + "' to a method name"); } try { final PsiType psiType = typeConverter.apply(type); return GenerateMembersUtil.suggestGetterName(variableName, psiType, project); } catch (IncorrectOperationException e) { throw new IllegalArgumentException("Cannot convert '" + name + "' to a method name", e); } } @Inject MethodNamePolicy(@Nonnull Project project, @Nonnull PsiTypeConverter typeConverter); @Nonnull @Override String convert(@Nonnull String name, @Nonnull TypeName type); }### Answer:
@Test public void convertShouldReturnLowerCamelTextWithPrefix() throws Exception { application.invokeAndWait(() -> { final String actual = underTest.convert("Foo_Bar", TypeName.OBJECT); assertThat(actual) .isEqualTo("getFooBar"); }); }
@Test public void convertShouldReturnWithPrefixWhenBoolean() throws Exception { application.invokeAndWait(() -> { final String actual = underTest.convert("Foo_Bar", TypeName.BOOLEAN); assertThat(actual) .isEqualTo("isFooBar"); }); }
@Test public void convertShouldRemoveInvalidCharacters() throws Exception { application.invokeAndWait(() -> { final String actual = underTest.convert("", TypeName.OBJECT); assertThat(actual) .isEqualTo("getFooBar"); }); }
@Test @SuppressWarnings("ResultOfMethodCallIgnored") public void convertShouldThrowExceptionWhenInvalidName() throws Exception { application.invokeAndWait(() -> { assertThatThrownBy(() -> { underTest.convert("+-*/", TypeName.OBJECT); }).isInstanceOf(IllegalArgumentException.class); }); }
|
### Question:
ParameterNamePolicy implements NamePolicy { @Nonnull @Override public String convert(@Nonnull String name, @Nonnull TypeName type) { final String propertyName = DefaultNamePolicy.format(name, CaseFormat.LOWER_CAMEL); final String parameterName = codeStyleManager.propertyNameToVariableName(propertyName, VariableKind.PARAMETER); if (Strings.isNullOrEmpty(parameterName)) { throw new IllegalArgumentException("Cannot convert '" + name + "' to a parameter name"); } return parameterName; } @Inject ParameterNamePolicy(@Nonnull JavaCodeStyleManager codeStyleManager); @Nonnull @Override String convert(@Nonnull String name, @Nonnull TypeName type); }### Answer:
@Test public void convertShouldReturnLowerCamelText() throws Exception { final String actual = underTest.convert("Foo", TypeName.OBJECT); assertThat(actual) .isEqualTo("foo"); }
@Test public void convertShouldAppendPrefixWhenReserved() throws Exception { final String actual = underTest.convert("Class", TypeName.OBJECT); assertThat(actual) .isEqualTo("aClass"); }
@Test @SuppressWarnings("ResultOfMethodCallIgnored") public void convertShouldThrowExceptionWhenInvalidText() throws Exception { assertThatThrownBy(() -> { underTest.convert("+", TypeName.OBJECT); }).isInstanceOf(IllegalArgumentException.class); }
|
### Question:
ClassNamePolicy implements NamePolicy { @Nonnull @Override public String convert(@Nonnull String name, @Nonnull TypeName type) { final StringBuilder builder = new StringBuilder(); builder.append(prefix) .append(DefaultNamePolicy.CLASS.convert(name, type)) .append(suffix); final String className = builder.toString(); if (!nameHelper.isQualifiedName(className)) { throw new IllegalArgumentException("Cannot convert '" + name + "' to class name"); } return className; } @Inject ClassNamePolicy(@Nonnull PsiNameHelper nameHelper, @Nonnull String prefix, @Nonnull String suffix); @Nonnull @Override String convert(@Nonnull String name, @Nonnull TypeName type); }### Answer:
@Test public void convertShouldReturnUpperCamelText() throws Exception { final ClassNamePolicy underTest = new ClassNamePolicy(nameHelper, "", ""); final String actual = underTest.convert("foo_bar", TypeName.OBJECT); assertThat(actual) .isEqualTo("FooBar"); }
@Test public void convertShouldReturnTextWithPrefix() throws Exception { final ClassNamePolicy underTest = new ClassNamePolicy(nameHelper, "Baz", ""); final String actual = underTest.convert("foo_bar", TypeName.OBJECT); assertThat(actual) .isEqualTo("BazFooBar"); }
@Test public void convertShouldReturnTextWithSuffix() throws Exception { final ClassNamePolicy underTest = new ClassNamePolicy(nameHelper, "", "Baz"); final String actual = underTest.convert("foo_bar", TypeName.OBJECT); assertThat(actual) .isEqualTo("FooBarBaz"); }
@Test @SuppressWarnings("ResultOfMethodCallIgnored") public void convertShouldThrowExceptionWhenUnQualifiedName() throws Exception { assertThatThrownBy(() -> { final ClassNamePolicy underTest = new ClassNamePolicy(nameHelper, "", ""); underTest.convert("+1", TypeName.OBJECT); }).isInstanceOf(IllegalArgumentException.class); }
|
### Question:
SettingsPanel implements Disposable, ActionListener, DocumentListener { @Override public void dispose() { Collections.list(styleGroup.getElements()).forEach(button -> button.removeActionListener(this)); classNamePrefixField.getDocument().removeDocumentListener(this); classNameSuffixField.getDocument().removeDocumentListener(this); generatedAnnotationCheckBox.removeActionListener(this); suppressWarningsAnnotationCheckBox.removeActionListener(this); if (previewEditor == null || previewEditor.isDisposed()) { return; } EditorFactory.getInstance().releaseEditor(previewEditor); } SettingsPanel(); @Override void dispose(); @Override void actionPerformed(@Nonnull ActionEvent event); @Override void insertUpdate(@Nonnull DocumentEvent event); @Override void removeUpdate(@Nonnull DocumentEvent event); @Override void changedUpdate(@Nonnull DocumentEvent event); @Nonnull @CheckReturnValue JComponent getComponent(); @Nonnull @CheckReturnValue Style getStyle(); void setStyle(@Nonnull Style style); @Nonnull @CheckReturnValue String getClassNamePrefix(); void setClassNamePrefix(@Nonnull String prefix); @Nonnull @CheckReturnValue String getClassNameSuffix(); void setClassNameSuffix(@Nonnull String suffix); @CheckReturnValue boolean isGeneratedAnnotationEnabled(); void setGeneratedAnnotationEnabled(boolean enabled); @CheckReturnValue boolean isSuppressWarningsAnnotationEnabled(); void setSuppressWarningsAnnotationEnabled(boolean enabled); void setPreviewText(@Nonnull String text); }### Answer:
@Test public void disposeShouldReleaseEditor() throws Exception { application.invokeAndWait(() -> underTest.dispose()); final Editor[] actual = EditorFactory.getInstance().getAllEditors(); assertThat(actual) .isEmpty(); }
|
### Question:
SettingsPanel implements Disposable, ActionListener, DocumentListener { @Nonnull @CheckReturnValue public Style getStyle() { final ButtonModel selected = styleGroup.getSelection(); return getStyleButtonStream() .filter(button -> { final ButtonModel model = button.getModel(); return model.equals(selected); }) .map(button -> { final String name = button.getText(); return Style.fromName(name, Style.NONE); }) .findFirst() .orElse(Style.NONE); } SettingsPanel(); @Override void dispose(); @Override void actionPerformed(@Nonnull ActionEvent event); @Override void insertUpdate(@Nonnull DocumentEvent event); @Override void removeUpdate(@Nonnull DocumentEvent event); @Override void changedUpdate(@Nonnull DocumentEvent event); @Nonnull @CheckReturnValue JComponent getComponent(); @Nonnull @CheckReturnValue Style getStyle(); void setStyle(@Nonnull Style style); @Nonnull @CheckReturnValue String getClassNamePrefix(); void setClassNamePrefix(@Nonnull String prefix); @Nonnull @CheckReturnValue String getClassNameSuffix(); void setClassNameSuffix(@Nonnull String suffix); @CheckReturnValue boolean isGeneratedAnnotationEnabled(); void setGeneratedAnnotationEnabled(boolean enabled); @CheckReturnValue boolean isSuppressWarningsAnnotationEnabled(); void setSuppressWarningsAnnotationEnabled(boolean enabled); void setPreviewText(@Nonnull String text); }### Answer:
@Test public void getStyleShouldReturnNoneByDefault() throws Exception { final Style actual = underTest.getStyle(); assertThat(actual).isEqualTo(Style.NONE); }
@Test public void getStyleShouldReturnSelectedStyle() throws Exception { final JRadioButtonFixture fixture = findRadioButtonByName("settings.name.style.gson"); fixture.requireEnabled(); fixture.requireNotSelected(); fixture.target().setSelected(true); final Style actual = underTest.getStyle(); assertThat(actual) .overridingErrorMessage("Expected style to be <%s> but was <%s>", Style.GSON, actual) .isEqualTo(Style.GSON); }
|
### Question:
SettingsPanel implements Disposable, ActionListener, DocumentListener { public void setStyle(@Nonnull Style style) { getStyleButtonStream().forEach(button -> { final String text = button.getText(); button.setSelected(style.name().equalsIgnoreCase(text)); }); } SettingsPanel(); @Override void dispose(); @Override void actionPerformed(@Nonnull ActionEvent event); @Override void insertUpdate(@Nonnull DocumentEvent event); @Override void removeUpdate(@Nonnull DocumentEvent event); @Override void changedUpdate(@Nonnull DocumentEvent event); @Nonnull @CheckReturnValue JComponent getComponent(); @Nonnull @CheckReturnValue Style getStyle(); void setStyle(@Nonnull Style style); @Nonnull @CheckReturnValue String getClassNamePrefix(); void setClassNamePrefix(@Nonnull String prefix); @Nonnull @CheckReturnValue String getClassNameSuffix(); void setClassNameSuffix(@Nonnull String suffix); @CheckReturnValue boolean isGeneratedAnnotationEnabled(); void setGeneratedAnnotationEnabled(boolean enabled); @CheckReturnValue boolean isSuppressWarningsAnnotationEnabled(); void setSuppressWarningsAnnotationEnabled(boolean enabled); void setPreviewText(@Nonnull String text); }### Answer:
@Test public void setStyleShouldSelectButton() throws Exception { final JRadioButtonFixture fixture = findRadioButtonByName("settings.name.style.moshi"); fixture.requireEnabled(); fixture.requireNotSelected(); underTest.setStyle(Style.MOSHI); final JRadioButton radioButton = fixture.target(); assertThat(radioButton.isSelected()).isTrue(); }
|
### Question:
SettingsPanel implements Disposable, ActionListener, DocumentListener { @Nonnull @CheckReturnValue public String getClassNamePrefix() { return classNamePrefixField.getText().trim(); } SettingsPanel(); @Override void dispose(); @Override void actionPerformed(@Nonnull ActionEvent event); @Override void insertUpdate(@Nonnull DocumentEvent event); @Override void removeUpdate(@Nonnull DocumentEvent event); @Override void changedUpdate(@Nonnull DocumentEvent event); @Nonnull @CheckReturnValue JComponent getComponent(); @Nonnull @CheckReturnValue Style getStyle(); void setStyle(@Nonnull Style style); @Nonnull @CheckReturnValue String getClassNamePrefix(); void setClassNamePrefix(@Nonnull String prefix); @Nonnull @CheckReturnValue String getClassNameSuffix(); void setClassNameSuffix(@Nonnull String suffix); @CheckReturnValue boolean isGeneratedAnnotationEnabled(); void setGeneratedAnnotationEnabled(boolean enabled); @CheckReturnValue boolean isSuppressWarningsAnnotationEnabled(); void setSuppressWarningsAnnotationEnabled(boolean enabled); void setPreviewText(@Nonnull String text); }### Answer:
@Test public void getClassNamePrefixShouldReturnEmptyTextByDefault() throws Exception { final JTextComponentFixture fixture = findTextFieldByName("settings.name.class.prefix"); fixture.requireEnabled(); fixture.requireEmpty(); final String actual = underTest.getClassNamePrefix(); assertThat(actual) .overridingErrorMessage("Expected prefix to be empty but was <%s>", actual) .isEmpty(); }
@Test public void getClassNamePrefixShouldReturnText() throws Exception { final JTextComponentFixture fixture = findTextFieldByName("settings.name.class.prefix"); fixture.requireEnabled(); fixture.requireEmpty(); fixture.target().setText("Foo"); final String actual = underTest.getClassNamePrefix(); assertThat(actual) .overridingErrorMessage("Expected prefix to be <%s> but was <%s>", "Foo", actual) .isEqualTo("Foo"); }
|
### Question:
SettingsPanel implements Disposable, ActionListener, DocumentListener { public void setClassNamePrefix(@Nonnull String prefix) { classNamePrefixField.setText(prefix); } SettingsPanel(); @Override void dispose(); @Override void actionPerformed(@Nonnull ActionEvent event); @Override void insertUpdate(@Nonnull DocumentEvent event); @Override void removeUpdate(@Nonnull DocumentEvent event); @Override void changedUpdate(@Nonnull DocumentEvent event); @Nonnull @CheckReturnValue JComponent getComponent(); @Nonnull @CheckReturnValue Style getStyle(); void setStyle(@Nonnull Style style); @Nonnull @CheckReturnValue String getClassNamePrefix(); void setClassNamePrefix(@Nonnull String prefix); @Nonnull @CheckReturnValue String getClassNameSuffix(); void setClassNameSuffix(@Nonnull String suffix); @CheckReturnValue boolean isGeneratedAnnotationEnabled(); void setGeneratedAnnotationEnabled(boolean enabled); @CheckReturnValue boolean isSuppressWarningsAnnotationEnabled(); void setSuppressWarningsAnnotationEnabled(boolean enabled); void setPreviewText(@Nonnull String text); }### Answer:
@Test public void setClassNamePrefixShouldSetText() throws Exception { final JTextComponentFixture fixture = findTextFieldByName("settings.name.class.prefix"); fixture.requireEnabled(); fixture.requireEmpty(); underTest.setClassNamePrefix("Foo"); final String actual = fixture.text(); assertThat(actual) .overridingErrorMessage("Expected prefix to be <%s> but was <%s>", "Foo", actual) .isEqualTo("Foo"); }
|
### Question:
SettingsPanel implements Disposable, ActionListener, DocumentListener { @Nonnull @CheckReturnValue public String getClassNameSuffix() { return classNameSuffixField.getText().trim(); } SettingsPanel(); @Override void dispose(); @Override void actionPerformed(@Nonnull ActionEvent event); @Override void insertUpdate(@Nonnull DocumentEvent event); @Override void removeUpdate(@Nonnull DocumentEvent event); @Override void changedUpdate(@Nonnull DocumentEvent event); @Nonnull @CheckReturnValue JComponent getComponent(); @Nonnull @CheckReturnValue Style getStyle(); void setStyle(@Nonnull Style style); @Nonnull @CheckReturnValue String getClassNamePrefix(); void setClassNamePrefix(@Nonnull String prefix); @Nonnull @CheckReturnValue String getClassNameSuffix(); void setClassNameSuffix(@Nonnull String suffix); @CheckReturnValue boolean isGeneratedAnnotationEnabled(); void setGeneratedAnnotationEnabled(boolean enabled); @CheckReturnValue boolean isSuppressWarningsAnnotationEnabled(); void setSuppressWarningsAnnotationEnabled(boolean enabled); void setPreviewText(@Nonnull String text); }### Answer:
@Test public void getClassNameSuffixShouldReturnEmptyTextByDefault() throws Exception { final JTextComponentFixture fixture = findTextFieldByName("settings.name.class.suffix"); fixture.requireEnabled(); fixture.requireEmpty(); final String actual = underTest.getClassNameSuffix(); assertThat(actual) .overridingErrorMessage("Expected suffix to be empty but was <%s>", actual) .isEmpty(); }
@Test public void getClassNameSuffixShouldReturnText() throws Exception { final JTextComponentFixture fixture = findTextFieldByName("settings.name.class.suffix"); fixture.requireEnabled(); fixture.requireEmpty(); fixture.target().setText("Bar"); final String actual = underTest.getClassNameSuffix(); assertThat(actual) .overridingErrorMessage("Expected suffix to be <%s> but was <%s>", "Bar", actual) .isEqualTo("Bar"); }
|
### Question:
SettingsPanel implements Disposable, ActionListener, DocumentListener { public void setClassNameSuffix(@Nonnull String suffix) { classNameSuffixField.setText(suffix); } SettingsPanel(); @Override void dispose(); @Override void actionPerformed(@Nonnull ActionEvent event); @Override void insertUpdate(@Nonnull DocumentEvent event); @Override void removeUpdate(@Nonnull DocumentEvent event); @Override void changedUpdate(@Nonnull DocumentEvent event); @Nonnull @CheckReturnValue JComponent getComponent(); @Nonnull @CheckReturnValue Style getStyle(); void setStyle(@Nonnull Style style); @Nonnull @CheckReturnValue String getClassNamePrefix(); void setClassNamePrefix(@Nonnull String prefix); @Nonnull @CheckReturnValue String getClassNameSuffix(); void setClassNameSuffix(@Nonnull String suffix); @CheckReturnValue boolean isGeneratedAnnotationEnabled(); void setGeneratedAnnotationEnabled(boolean enabled); @CheckReturnValue boolean isSuppressWarningsAnnotationEnabled(); void setSuppressWarningsAnnotationEnabled(boolean enabled); void setPreviewText(@Nonnull String text); }### Answer:
@Test public void setClassNameSuffixShouldSetText() throws Exception { final JTextComponentFixture fixture = findTextFieldByName("settings.name.class.suffix"); fixture.requireEnabled(); fixture.requireEmpty(); underTest.setClassNameSuffix("Bar"); final String actual = fixture.target().getText(); assertThat(actual) .overridingErrorMessage("Expected suffix to be <%s> but was <%s>", "Foo", actual) .isEqualTo("Bar"); }
|
### Question:
JsonValidator implements InputValidatorEx { @Override public boolean checkInput(@Nullable String json) { return true; } @Inject JsonValidator(@Nonnull Json2JavaBundle bundle, @Nonnull JsonParser parser); @Nullable @Override String getErrorText(@Nullable String json); @Override boolean checkInput(@Nullable String json); @Override @SuppressWarnings("SimplifiableIfStatement") boolean canClose(@Nullable String json); }### Answer:
@Test public void checkInputShouldAlwaysReturnTrue() throws Exception { final boolean actual = underTest.checkInput("test"); assertThat(actual) .overridingErrorMessage("Expected value returned by checkInput is true, but was false") .isTrue(); }
|
### Question:
JsonValidator implements InputValidatorEx { @Override @SuppressWarnings("SimplifiableIfStatement") public boolean canClose(@Nullable String json) { if (Strings.isNullOrEmpty(json)) { return false; } try { final JsonElement root = parser.parse(json); return !root.isJsonNull() && !root.isJsonPrimitive(); } catch (JsonParseException e) { return false; } } @Inject JsonValidator(@Nonnull Json2JavaBundle bundle, @Nonnull JsonParser parser); @Nullable @Override String getErrorText(@Nullable String json); @Override boolean checkInput(@Nullable String json); @Override @SuppressWarnings("SimplifiableIfStatement") boolean canClose(@Nullable String json); }### Answer:
@Test public void canCloseShouldReturnFalseWhenJsonIsEmpty() throws Exception { final boolean actual = underTest.canClose(""); assertThat(actual) .overridingErrorMessage("Expected value returned by canClose is false, but was true") .isFalse(); }
@Test public void canCloseShouldReturnFalseWhenJsonIsPrimitive() throws Exception { final boolean actual = underTest.canClose("1000"); assertThat(actual) .overridingErrorMessage("Expected value returned by canClose is false, but was true") .isFalse(); }
@Test public void canCloseShouldReturnFalseWhenJsonIsInvalid() throws Exception { final boolean actual = underTest.canClose("{{}}"); assertThat(actual) .overridingErrorMessage("Expected value returned by canClose is false, but was true") .isFalse(); }
@Test public void canCloseShouldReturnTrueWhenJsonIsValid() throws Exception { final boolean actual = underTest.canClose("{}"); assertThat(actual) .overridingErrorMessage("Expected value returned by canClose is true, but was false") .isTrue(); }
|
### Question:
ClassPrefixValidator implements InputValidatorEx { @Nullable @Override public String getErrorText(@Nullable String prefix) { if (canClose(prefix)) { return null; } return bundle.message("error.message.validator.class.prefix", prefix); } @Inject ClassPrefixValidator(@NotNull Json2JavaBundle bundle, @NotNull PsiNameHelper nameHelper); @Nullable @Override String getErrorText(@Nullable String prefix); @Override boolean checkInput(@Nullable String prefix); @Override boolean canClose(@Nullable String prefix); }### Answer:
@Test public void getErrorTextShouldReturnNullWhenValid() throws Exception { final String actual = underTest.getErrorText("Foo"); assertThat(actual) .overridingErrorMessage("Expected value returned by getErrorText is null, but was <%s>", actual) .isNull(); }
@Test public void getErrorTextShouldReturnTextWhenInvalid() throws Exception { final String actual = underTest.getErrorText("^Foo"); assertThat(actual) .overridingErrorMessage("Expected value returned by getErrorText is null, but was <%s>", actual) .isNotEmpty(); }
|
### Question:
ClassPrefixValidator implements InputValidatorEx { @Override public boolean checkInput(@Nullable String prefix) { return true; } @Inject ClassPrefixValidator(@NotNull Json2JavaBundle bundle, @NotNull PsiNameHelper nameHelper); @Nullable @Override String getErrorText(@Nullable String prefix); @Override boolean checkInput(@Nullable String prefix); @Override boolean canClose(@Nullable String prefix); }### Answer:
@Test public void checkInputShouldAlwaysReturnTrue() throws Exception { final boolean actual = underTest.checkInput("foo"); assertThat(actual) .overridingErrorMessage("Expected value returned by checkInput is true, but was false") .isTrue(); }
|
### Question:
StringUtils { public static boolean hasText(final String text) { if (text != null && !"".equals(text.trim())) { return true; } return false; } private StringUtils(); static StringUtils getInstance(); static boolean hasText(final String text); static boolean hasBytes(final byte[] data); }### Answer:
@Test public void testHasText_true() { String text = "data"; boolean status = StringUtils.hasText(text); Assert.assertTrue(status); }
@Test public void testHasText_false() { String text = ""; boolean status = StringUtils.hasText(text); Assert.assertFalse(status); }
@Test public void testHasText_null() { boolean status = StringUtils.hasText(null); Assert.assertFalse(status); }
|
### Question:
WebhooksService { public boolean verifyPayload(String intuitSignature, String payload) { try { SecretKeySpec secretKey = new SecretKeySpec(getVerifierKey().getBytes("UTF-8"), ALGORITHM); Mac mac = Mac.getInstance(ALGORITHM); mac.init(secretKey); String hash = DatatypeConverter.printBase64Binary(mac.doFinal(payload.getBytes())); return hash.equals(intuitSignature); } catch (NoSuchAlgorithmException e) { LOG.error("NoSuchAlgorithmException while validating payload", e); return false; } catch (UnsupportedEncodingException e) { LOG.error("UnsupportedEncodingException while validating payload", e); return false; } catch (InvalidKeyException e) { LOG.error("InvalidKeyException validating payload", e); return false; } } boolean verifyPayload(String intuitSignature, String payload); WebhooksEvent getWebhooksEvent(String payload); }### Answer:
@Test public void testVerifyPayload() throws FMSException { boolean result = webhooksService.verifyPayload("1234", payload); Assert.assertFalse(result); result = webhooksService.verifyPayload(intuitSignature, payload); Assert.assertTrue(result); }
|
### Question:
SerializeInterceptor implements Interceptor { protected String getSerializationRequestFormat() { return Config.getProperty(Config.SERIALIZATION_REQUEST_FORMAT); } @Override void execute(IntuitMessage intuitMessage); }### Answer:
@Test(description = "Serialization request format returned should be of " + "the form: message.request.serialization") public void getSerializationRequestFormat() { assertTrue(serializeInterceptor .getSerializationRequestFormat() .equalsIgnoreCase(Config.getProperty(SERIALIZATION_REQUEST_FORMAT))); }
|
### Question:
WebhooksService { public WebhooksEvent getWebhooksEvent(String payload) { if (!StringUtils.hasText(payload)) { return null; } try { ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(payload, WebhooksEvent.class); } catch (JsonParseException e) { LOG.error("Error while parsing payload", e); return null; } catch (JsonMappingException e) { LOG.error("Error while mapping payload", e); return null; } catch (IOException e) { LOG.error("IO exception while parsing payload", e); return null; } } boolean verifyPayload(String intuitSignature, String payload); WebhooksEvent getWebhooksEvent(String payload); }### Answer:
@Test public void testGetWebhooksEvent() throws FMSException { WebhooksEvent webhooksEvent = webhooksService.getWebhooksEvent(payload); Assert.assertNotNull(webhooksEvent); Assert.assertEquals(webhooksEvent.getEventNotifications().size(), 1); }
|
### Question:
DeflateCompressor implements ICompressor { public byte[] compress(final String data, byte[] uploadFile) throws CompressionException { if (!StringUtils.hasText(data)) { return null; } ByteArrayOutputStream baos = null; OutputStream deflater = null; byte[] compressedData = null; try { baos = new ByteArrayOutputStream(); deflater = new DeflaterOutputStream(baos); deflater.write(data.getBytes()); if (uploadFile != null) { deflater.write(uploadFile); } deflater.close(); compressedData = baos.toByteArray(); return compressedData; } catch (IOException ioe) { throw new CompressionException("IOException while compress the data using Deflate compression.", ioe); } finally { if (baos != null) { try { baos.close(); } catch (IOException e) { LOG.error("Unable to close ByteArrayOutputStream."); } } } } byte[] compress(final String data, byte[] uploadFile); OutputStream decompress(final InputStream in); }### Answer:
@Test public void testCompress() throws CompressionException { String data = "Hello World!"; DeflateCompressor compressor = new DeflateCompressor(); byte[] compressed = compressor.compress(data, null); Assert.assertNotEquals(data, compressed, "DeflateCompressor : given data did not compress."); }
@Test public void testCompress_null() throws CompressionException { String data = null; DeflateCompressor compressor = new DeflateCompressor(); byte[] compressed = compressor.compress(data, null); Assert.assertNull(compressed); }
|
### Question:
DeflateCompressor implements ICompressor { public OutputStream decompress(final InputStream in) throws CompressionException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { InputStream inflater = new InflaterInputStream(in); byte[] bbuf = new byte[LENGTH_256]; while (true) { int r = inflater.read(bbuf); if (r < 0) { break; } baos.write(bbuf, 0, r); } return baos; } catch (IOException ioe) { throw new CompressionException("IOException while decompress the data using Deflate compression.", ioe); } finally { if (baos != null) { try { baos.close(); } catch (IOException e) { LOG.error("Unable to close ByteArrayOutputStream."); } } } } byte[] compress(final String data, byte[] uploadFile); OutputStream decompress(final InputStream in); }### Answer:
@Test public void testDecompress() throws CompressionException { String data = "Hello World!"; DeflateCompressor compressor = new DeflateCompressor(); byte[] compressed = compressor.compress(data, null); String decompressed = new String(((ByteArrayOutputStream)compressor.decompress(new ByteArrayInputStream(compressed))).toByteArray()); Assert.assertEquals(data, decompressed, "DeflateCompressor : given data did not decompress."); }
@Test public void testDecompress_invalid() { boolean isException = false; String data = "data"; try { DeflateCompressor compressor = new DeflateCompressor(); compressor.decompress(new ByteArrayInputStream(data.getBytes())); } catch (CompressionException e) { isException = true; } Assert.assertTrue(isException); }
|
### Question:
CompressorFactory { public static ICompressor getCompressor(final String compressFormat) throws CompressionException { ICompressor compressor = null; if (isValidCompressFormat(compressFormat)) { if (compressFormat.equalsIgnoreCase(GZIP_COMPRESS_FORMAT)) { compressor = new GZIPCompressor(); } else if (compressFormat.equalsIgnoreCase(DEFLATE_COMPRESS_FORMAT)) { compressor = new DeflateCompressor(); } } return compressor; } private CompressorFactory(); static CompressorFactory getInstance(); static ICompressor getCompressor(final String compressFormat); static boolean isValidCompressFormat(final String compressFormat); static final String GZIP_COMPRESS_FORMAT; static final String DEFLATE_COMPRESS_FORMAT; }### Answer:
@Test public void testGetCompressor_gzip() throws CompressionException { ICompressor compressor = CompressorFactory.getCompressor("gzip"); Assert.assertTrue(compressor instanceof GZIPCompressor, "Object compressor is not instance of GZIPCompressor"); }
@Test public void testGetCompressor_deflate() throws CompressionException { ICompressor compressor = CompressorFactory.getCompressor("deflate"); Assert.assertTrue(compressor instanceof DeflateCompressor, "Object compressor is not instance of DeflateCompressor"); }
@Test public void testGetCompressor_others() { boolean isException = false; try { CompressorFactory.getCompressor("others"); } catch (CompressionException e) { isException = true; } Assert.assertTrue(isException); }
@Test public void testGetCompressor_null() { boolean isException = false; try { CompressorFactory.getCompressor(null); } catch (CompressionException e) { isException = true; } Assert.assertTrue(isException); }
|
### Question:
CompressorFactory { public static boolean isValidCompressFormat(final String compressFormat) throws CompressionException { if (!StringUtils.hasText(compressFormat)) { throw new CompressionException("Compress format is either null or empty!"); } else if (compressFormat.equalsIgnoreCase(GZIP_COMPRESS_FORMAT) || compressFormat.equalsIgnoreCase(DEFLATE_COMPRESS_FORMAT)) { return true; } else { throw new CompressionException("There is no compression technique for the given compress format : " + compressFormat); } } private CompressorFactory(); static CompressorFactory getInstance(); static ICompressor getCompressor(final String compressFormat); static boolean isValidCompressFormat(final String compressFormat); static final String GZIP_COMPRESS_FORMAT; static final String DEFLATE_COMPRESS_FORMAT; }### Answer:
@Test public void testIsValidCompressFormat_gzip() throws CompressionException { boolean isValid = CompressorFactory.isValidCompressFormat("gzip"); Assert.assertTrue(isValid); }
@Test public void testIsValidCompressFormat_deflate() throws CompressionException { boolean isValid = CompressorFactory.isValidCompressFormat("deflate"); Assert.assertTrue(isValid); }
@Test public void testIsValidCompressFormat_others() { boolean isValid = true; try { isValid = CompressorFactory.isValidCompressFormat("others"); } catch (CompressionException e) { isValid = false; } Assert.assertFalse(isValid); }
@Test public void testIsValidCompressFormat_null() { boolean isValid = true; try { isValid = CompressorFactory.isValidCompressFormat(null); } catch (CompressionException e) { isValid = false; } Assert.assertFalse(isValid); }
|
### Question:
CompressorFactory { private CompressorFactory() { } private CompressorFactory(); static CompressorFactory getInstance(); static ICompressor getCompressor(final String compressFormat); static boolean isValidCompressFormat(final String compressFormat); static final String GZIP_COMPRESS_FORMAT; static final String DEFLATE_COMPRESS_FORMAT; }### Answer:
@Test public void testCompressorFactory() { CompressorFactory factory = CompressorFactory.getInstance(); Assert.assertNotNull(factory); }
|
### Question:
GZIPCompressor implements ICompressor { public byte[] compress(final String data, byte[] uploadFile) throws CompressionException { if (!StringUtils.hasText(data)) { return null; } ByteArrayOutputStream baos = null; OutputStream gzout = null; byte[] compressedData = null; try { baos = new ByteArrayOutputStream(); gzout = new GZIPOutputStream(baos); gzout.write(data.getBytes(StandardCharsets.UTF_8)); if (uploadFile != null) { gzout.write(uploadFile); } gzout.close(); compressedData = baos.toByteArray(); return compressedData; } catch (IOException ioe) { LOG.error("IOException while compress the data using GZIP compression.", ioe); throw new CompressionException(ioe); } finally { if (baos != null) { try { baos.close(); } catch (IOException e) { LOG.error("Unable to close ByteArrayOutputStream."); } } } } byte[] compress(final String data, byte[] uploadFile); OutputStream decompress(final InputStream in); }### Answer:
@Test public void testCompress() { String data = "Hello World!"; try { GZIPCompressor compressor = new GZIPCompressor(); byte[] compressed = compressor.compress(data, null); Assert.assertNotEquals(data, compressed, "GZIPCompressor : given data did not compress."); } catch (CompressionException e) { e.printStackTrace(); } }
@Test public void testCompress_null() { String data = null; try { GZIPCompressor compressor = new GZIPCompressor(); byte[] compressed = compressor.compress(data, null); Assert.assertEquals(compressed, null); } catch (CompressionException e) { e.printStackTrace(); } }
|
### Question:
GZIPCompressor implements ICompressor { public OutputStream decompress(final InputStream in) throws CompressionException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { InputStream inflater = new GZIPInputStream(in); byte[] bbuf = new byte[LENGTH_256]; while (true) { int r = inflater.read(bbuf); if (r < 0) { break; } baos.write(bbuf, 0, r); } return baos; } catch (IOException ioe) { LOG.error("IOException while decompress the data using GZIP compression.", ioe); throw new CompressionException(ioe); } finally { if (baos != null) { try { baos.close(); } catch (IOException e) { LOG.error("Unable to close ByteArrayOutputStream."); } } } } byte[] compress(final String data, byte[] uploadFile); OutputStream decompress(final InputStream in); }### Answer:
@Test public void testDecompress() { String data = "Hello World!"; try { GZIPCompressor compressor = new GZIPCompressor(); byte[] compressed = compressor.compress(data, null); LOG.debug(compressed.toString()); String decompressed = new String(((ByteArrayOutputStream)compressor.decompress(new ByteArrayInputStream(compressed))).toByteArray()); Assert.assertEquals(data, decompressed, "GZIPCompressor : given data did not decompress."); } catch (CompressionException e) { e.printStackTrace(); } }
@Test public void testDecompress_invalid() { boolean isException = false; String data = "data"; try { GZIPCompressor compressor = new GZIPCompressor(); compressor.decompress(new ByteArrayInputStream(data.getBytes())); } catch (CompressionException e) { isException = true; } Assert.assertTrue(isException); }
|
### Question:
PaymentContext extends Entity { @Override public String toString() { return ReflectionToStringBuilder.toString(this); } PaymentContext(); private PaymentContext(Builder builder); BigDecimal getTax(); void setTax(BigDecimal tax); DeviceInfo getDeviceInfo(); void setDeviceInfo(DeviceInfo deviceInfo); Boolean getRecurring(); void setRecurring(Boolean recurring); String getMobile(); void setMobile(String mobile); String getIsEcommerce(); void setIsEcommerce(String isEcommerce); Lodging getLodging(); void setLodging(Lodging lodging); Restaurant getRestaurant(); void setRestaurant(Restaurant restaurant); @Override String toString(); }### Answer:
@Test public void testToString() { String expectedResult = ReflectionToStringBuilder.toString(paymentContext); String actualResult = paymentContext.toString(); Assert.assertTrue(actualResult.contains(expectedResult)); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.