method2testcases
stringlengths
118
3.08k
### Question: Castle { static boolean isUrlWhiteListed(String urlString) { try { URL url = new URL(urlString); String baseUrl = url.getProtocol() + ": if (Castle.configuration().baseURLWhiteList() != null && !Castle.configuration().baseURLWhiteList().isEmpty()) { if (Castle.configuration().baseURLWhiteList().contains(baseUrl)) { return true; } } } catch (MalformedURLException e) { e.printStackTrace(); } return false; } private Castle(Application application, CastleConfiguration castleConfiguration); static void configure(Application application, CastleConfiguration configuration); static void configure(Application application, String publishableKey); static void configure(Application application, String publishableKey, CastleConfiguration configuration); static void configure(Application application); static void identify(String userId); static void identify(String userId, Map<String, String> traits); static String userId(); static void reset(); static void screen(String name); static void screen(Activity activity); static void secure(String signature); static boolean secureModeEnabled(); static String publishableKey(); static boolean debugLoggingEnabled(); static String baseUrl(); static String clientId(); static String userSignature(); static void userSignature(String signature); static CastleConfiguration configuration(); static void flush(); static boolean flushIfNeeded(String url); static Map<String, String> headers(String url); static CastleInterceptor castleInterceptor(); static int queueSize(); static void destroy(Application application); static String userAgent(); static io.castle.android.api.model.Context createContext(); static final String clientIdHeaderName; }### Answer: @Test public void testWhiteList() { Assert.assertFalse(Castle.isUrlWhiteListed("invalid url")); }
### Question: Solve { Solve() { } Solve(); int solve(int dimension, int[][] gridCopy); static int[] rc2box(int i, int j); }### Answer: @Test public void testInvalidGrid() { Solve grid1 = new Solve(); int[][] grid = { { 4, 8, 3, 7, 6, 9, 2, 1, 5 }, { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 2, 3, 4, 5, 6, 7, 8, 0 } }; assertEquals(0, grid1.solve(9, grid)); } @Test public void testGameGrid() { Solve grid1 = new Solve(); GameGrid grid = new GameGrid(9); assertTrue(0< grid1.solve(9, grid.grid)); }
### Question: MatrixController { @RequestMapping(path = "/find/{petId}", method = RequestMethod.GET) @ResponseBody public String find(@PathVariable String petId, @MatrixVariable int q) { logger.info("petId:{},q:{}",petId,q); return petId + q; } @RequestMapping(path = "/find/{petId}", method = RequestMethod.GET) @ResponseBody String find(@PathVariable String petId, @MatrixVariable int q); @RequestMapping(path = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET) @ResponseBody String find1( @MatrixVariable(name="q", pathVar="ownerId") int q1, @MatrixVariable(name="q", pathVar="petId") int q2); }### Answer: @Test public void find() throws Exception { this.mockMvc.perform(get("/matrix/find/42;q=11;r=22")) .andExpect(status().isOk()) .andExpect(content().string("4211")); }
### Question: MatrixController { @RequestMapping(path = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET) @ResponseBody public String find1( @MatrixVariable(name="q", pathVar="ownerId") int q1, @MatrixVariable(name="q", pathVar="petId") int q2) { return String.valueOf(q1+q2); } @RequestMapping(path = "/find/{petId}", method = RequestMethod.GET) @ResponseBody String find(@PathVariable String petId, @MatrixVariable int q); @RequestMapping(path = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET) @ResponseBody String find1( @MatrixVariable(name="q", pathVar="ownerId") int q1, @MatrixVariable(name="q", pathVar="petId") int q2); }### Answer: @Test public void find1() throws Exception { this.mockMvc.perform(get("/matrix/owners/42;q=11/pets/11;q=22")) .andExpect(status().isOk()) .andExpect(content().string("33")); }
### Question: JsonController { @RequestMapping(path = "/get",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User get(){ return new User(20,"李四","F"); } @RequestMapping(path = "/get",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post/{name}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User post(@PathVariable String name, Model model); }### Answer: @Test public void getUser() throws Exception { logger.info("JsonControllerTest getUser is running"); this.mockMvc.perform(get("/json/get").accept(MediaType.parseMediaType("application/json;charset=UTF-8"))) .andExpect(status().isOk()).andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("$.name").value("李四")); }
### Question: JsonController { @RequestMapping(path = "/post/{name}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User post(@PathVariable String name, Model model){ logger.info("name : {}",name); return new User(20,name,"男"); } @RequestMapping(path = "/get",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post/{name}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User post(@PathVariable String name, Model model); }### Answer: @Test public void postUser() throws Exception { logger.info("JsonControllerTest postUser is running"); this.mockMvc.perform(post("/json/post/haha").accept(MediaType.parseMediaType("application/json;charset=UTF-8"))) .andExpect(status().isOk()).andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("$.name").value("haha")); }
### Question: XmlController { @RequestMapping(path = "/get",method = RequestMethod.GET,produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody public User get(){ return new User(21,"张三","男"); } @RequestMapping(path = "/get",method = RequestMethod.GET,produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post(@RequestBody User user); @RequestMapping(path = "/post1",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post1(@RequestBody User user); @RequestMapping(path = "/postHouse",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody House postHouse(@RequestBody House house); }### Answer: @Test public void getUser() throws Exception { logger.info("XmlControllerTest getUser is running"); this.mockMvc.perform(get("/xml/get")).andExpect(status().isOk()).andExpect(content().contentType ("application/xml")).andExpect(xpath("/user/name", new HashMap<String, String>()).string("张三")); }
### Question: XmlController { @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody public User post(@RequestBody User user){ logger.info(user.toString()); return user; } @RequestMapping(path = "/get",method = RequestMethod.GET,produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post(@RequestBody User user); @RequestMapping(path = "/post1",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post1(@RequestBody User user); @RequestMapping(path = "/postHouse",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody House postHouse(@RequestBody House house); }### Answer: @Test public void postUser() throws Exception { logger.info("XmlControllerTest postUser is running"); User user = new User(10, "王五", "男"); String content = JaxbUtils.toXml(user); logger.info("content:{}", content); this.mockMvc.perform(post("/xml/post").contentType(MediaType.APPLICATION_XML_VALUE).content(content)) .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_XML_VALUE)).andExpect(xpath ("/user/sex", new HashMap<String, String>()).string("男")); }
### Question: XmlController { @RequestMapping(path = "/postHouse",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody public House postHouse(@RequestBody House house){ logger.info(house.toString()); return house; } @RequestMapping(path = "/get",method = RequestMethod.GET,produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post(@RequestBody User user); @RequestMapping(path = "/post1",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post1(@RequestBody User user); @RequestMapping(path = "/postHouse",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody House postHouse(@RequestBody House house); }### Answer: @Test public void postHouse() throws Exception { logger.info("XmlControllerTest postHouse is running"); User user = new User(30, "王五", "男"); House house = new House(user,"南京"); String content = JaxbUtils.toXml(house); logger.info("content:{}", content); this.mockMvc.perform(post("/xml/postHouse").contentType(MediaType.APPLICATION_XML_VALUE).content(content)) .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_XML_VALUE)).andExpect(xpath ("/house/user/sex", new HashMap<String, String>()).string("男")); }
### Question: ValidController { @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User post(@RequestBody @Valid User user){ return user; } @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User post(@RequestBody @Valid User user); }### Answer: @Test public void postTest() throws Exception { User user = new User(50, "王五", "男"); String content = JSON.toJSONString(user); logger.info("content:{}", content); this.mockMvc.perform(post("/valid/post").contentType(MediaType.APPLICATION_JSON_UTF8_VALUE).content(content)) .andExpect(content().string("4211")); }
### Question: ModelRef { static public boolean validateId(String id){ return (id != null) && (id).matches(REGEX_ID); } ModelRef(ModelRef modelRef); ModelRef(Principal owner, String id); @Override int hashCode(); @Override boolean equals(Object object); Principal getOwner(); String getId(); static boolean validateId(String id); static final String PATH_VALUE_ID; }### Answer: @Test public void validateId(){ assertTrue(ModelRef.validateId("com.mycompany.Test")); assertTrue(ModelRef.validateId("Test_v1")); assertTrue(ModelRef.validateId("Test_v1.0")); assertFalse(ModelRef.validateId(".")); assertFalse(ModelRef.validateId("-Test")); }
### Question: CsvUtil { static public CsvPreference getFormat(String delimiterChar, String quoteChar){ char delimiter = ','; char quote = '\"'; if(delimiterChar != null){ delimiterChar = decodeDelimiter(delimiterChar); if(delimiterChar.length() != 1){ throw new IllegalArgumentException("Invalid CSV delimiter character: \"" + delimiterChar + "\""); } delimiter = delimiterChar.charAt(0); } if(quoteChar != null){ quoteChar = decodeQuote(quoteChar); if(quoteChar.length() != 1){ throw new IllegalArgumentException("Invalid CSV quote character: \"" + quoteChar + "\""); } quote = quoteChar.charAt(0); } CsvPreference format = createFormat(delimiter, quote); return format; } private CsvUtil(); static CsvPreference getFormat(String delimiterChar, String quoteChar); static CsvPreference getFormat(BufferedReader reader); static CsvPreference createFormat(char delimiterChar, char quoteChar); static TableEvaluationRequest readTable(BufferedReader reader, CsvPreference format); static void writeTable(TableEvaluationResponse tableResponse, BufferedWriter writer, CsvPreference format); }### Answer: @Test public void getFormat() throws IOException { CsvPreference first; CsvPreference second; String csv = "1\tone\n" + "2\ttwo\n" + "3\tthree"; try(BufferedReader reader = new BufferedReader(new StringReader(csv))){ first = CsvUtil.getFormat(reader); second = CsvUtil.getFormat(reader); } assertNotSame(first.getEncoder(), second.getEncoder()); }
### Question: WebApplicationExceptionMapper implements ExceptionMapper<WebApplicationException> { @Override public Response toResponse(WebApplicationException exception){ Response response = exception.getResponse(); Throwable throwable = exception; Map<Throwable, Throwable> throwableMap = new IdentityHashMap<>(); while(true){ Throwable cause = throwable.getCause(); throwableMap.put(throwable, cause); if((cause == null) || throwableMap.containsKey(cause)){ break; } throwable = cause; } String message = throwable.getMessage(); if((message == null) || ("").equals(message)){ Response.Status status = (Response.Status)response.getStatusInfo(); message = status.getReasonPhrase(); } if(message.startsWith("HTTP ")){ message = message.replaceFirst("^HTTP (\\d)+ ", ""); } SimpleResponse entity = new SimpleResponse(); entity.setMessage(message); return (Response.fromResponse(response).entity(entity).type(MediaType.APPLICATION_JSON)).build(); } @Override Response toResponse(WebApplicationException exception); }### Answer: @Test public void toResponse(){ assertEquals("Not Found", getMessage(new NotFoundException())); assertEquals("Resource \"id\" not found", getMessage(new NotFoundException("Resource \"id\" not found"))); assertEquals("Bad Request", getMessage(new BadRequestException(new IllegalArgumentException()))); assertEquals("Bad \"id\" value", getMessage(new BadRequestException(new IllegalArgumentException("Bad \"id\" value")))); assertEquals("Bad Request", getMessage(new BadRequestException(new UnmarshalException(new IOException())))); assertEquals("Resource \"id\" is incomplete", getMessage(new BadRequestException(new UnmarshalException(new EOFException("Resource \"id\" is incomplete"))))); UnmarshalException selfRefException = new UnmarshalException((Throwable)null); selfRefException.setLinkedException(new UnmarshalException(selfRefException)); assertEquals("Bad Request", getMessage(new BadRequestException(selfRefException))); }
### Question: Delegating { public static <T> DelegatingWith<T> proxy(Class<T> type) { return new DelegatingWith<T>(new Delegating<T>(type)); } private Delegating(Class<T> type); static DelegatingWith<T> proxy(Class<T> type); }### Answer: @Test public void shouldSupportIndirectRecursion() { Faculty fac = new Faculty() { public int calc(int i, Faculty fac) { return i == 1 ? 1 : i * fac.calc(i - 1, fac); } }; Faculty proxy = Delegating.proxy(Faculty.class).with(fac).build(getFactory()); assertEquals(120, fac.calc(5, fac)); assertEquals(120, proxy.calc(5, proxy)); }
### Question: Echoing { public static <T> EchoingWithOrTo<T> proxy(final Class<T> type) { return new EchoingWithOrTo<T>(new Echoing<T>(type)); } private Echoing(final Class<T> type); static EchoingWithOrTo<T> proxy(final Class<T> type); }### Answer: @Test public void shouldEchoMethodNameAndArgs() throws Exception { Writer out = new StringWriter(); Simple foo = Echoing.proxy(Simple.class).to(new PrintWriter(out)).build(getFactory()); foo.doSomething(); assertContains("Simple.doSomething()", out); } @Test public void shouldDelegateCalls() throws Exception { Writer out = new StringWriter(); Simple foo = Echoing.proxy(Simple.class).with(simpleMock).to(new PrintWriter(out)).build(getFactory()); foo.doSomething(); verify(simpleMock).doSomething(); } @Test public void shouldRecursivelyReturnEchoProxiesForInterfaces() throws Exception { Inner innerMock = mock(Inner.class); Outer outerMock = mock(Outer.class); StringWriter out = new StringWriter(); Outer outer = Echoing.proxy(Outer.class).with(outerMock).to(new PrintWriter(out)).build(getFactory()); when(outerMock.getInner()).thenReturn(innerMock); when(innerMock.getName()).thenReturn("inner"); String result = outer.getInner().getName(); assertEquals("inner", result); assertContains("Outer.getInner()", out); assertContains("Inner.getName()", out); verify(outerMock).getInner(); verify(innerMock).getName(); } @Test public void shouldRecursivelyReturnEchoProxiesEvenForMissingImplementations() throws Exception { StringWriter out = new StringWriter(); Outer outer = Echoing.proxy(Outer.class).to(new PrintWriter(out)).build(getFactory()); outer.getInner().getName(); assertContains("Outer.getInner()", out); assertContains("Inner.getName()", out); }
### Question: CglibProxyFactory extends AbstractProxyFactory { public boolean canProxy(final Class<?> type) { return !Modifier.isFinal(type.getModifiers()); } CglibProxyFactory(); CglibProxyFactory(boolean interceptDuringConstruction); T createProxy(final Invoker invoker, final Class<?>... types); boolean canProxy(final Class<?> type); boolean isProxyClass(final Class<?> type); }### Answer: @Test public void shouldDenyProxyGenerationForFinalClasses() throws Exception { ProxyFactory factory = new CglibProxyFactory(); assertFalse(factory.canProxy(String.class)); }
### Question: ReflectionUtils { public static Set<Class<?>> getAllInterfaces(Object... objects) { final Set<Class<?>> interfaces = new HashSet<Class<?>>(); for (Object object : objects) { if (object != null) { getInterfaces(object.getClass(), interfaces); } } interfaces.remove(InvokerReference.class); return interfaces; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject( final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; }### Answer: @Test public void allInterfacesOfListShouldBeFound() { Set<Class<?>> interfaces = ReflectionUtils.getAllInterfaces(BeanContextServices.class); assertTrue(interfaces.contains(BeanContextServices.class)); assertTrue(interfaces.contains(BeanContext.class)); assertTrue(interfaces.contains(Collection.class)); assertTrue(interfaces.contains(BeanContextServicesListener.class)); assertTrue(interfaces.contains(EventListener.class)); }
### Question: ReflectionUtils { public static void writeMethod(final ObjectOutputStream out, final Method method) throws IOException { out.writeObject(method.getDeclaringClass()); out.writeObject(method.getName()); out.writeObject(method.getParameterTypes()); } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject( final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; }### Answer: @Test public void methodCanBeSerialized() throws IOException, ClassNotFoundException { ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(); ObjectOutputStream outStream = new ObjectOutputStream(outBuffer); ReflectionUtils.writeMethod(outStream, ReflectionUtils.equals); outStream.close(); ByteArrayInputStream inBuffer = new ByteArrayInputStream(outBuffer.toByteArray()); ObjectInputStream inStream = new ObjectInputStream(inBuffer); assertSame(Object.class, inStream.readObject()); assertEquals("equals", inStream.readObject()); assertTrue(Arrays.equals(new Class[]{Object.class}, (Object[]) inStream.readObject())); inStream.close(); }
### Question: Future { public static <T> FutureWith<T> proxy(Class<T> primaryType) { Future<T> future = new Future<T>(new Class<?>[]{primaryType}); return new FutureWith<T>(future); } private Future(Class<?>[] types); static FutureWith<T> proxy(Class<T> primaryType); static FutureWith<T> proxy(Class<T> primaryType, Class<?>... types); static FutureBuild<T> proxy(T target); }### Answer: @Test public void shouldReturnNullObjectAsIntermediateResultAndSwapWhenMethodCompletesWithCast() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Service slowService = new SlowService(latch); Service fastService = Future.proxy(slowService).build(getFactory()); List<String> stuff = fastService.getList(); assertTrue(stuff.isEmpty()); latch.countDown(); Thread.sleep(100); assertEquals(1, stuff.size()); assertEquals("yo", stuff.get(0)); } @Test public void shouldReturnNullObjectAsIntermediateResultAndSwapWhenMethodCompletesWithGenerics() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Service slowService = new SlowService(latch); Service fastService = Future.proxy(Service.class).with(slowService).build(getFactory()); List<String> stuff = fastService.getList(); assertTrue(stuff.isEmpty()); latch.countDown(); Thread.sleep(100); assertEquals(1, stuff.size()); assertEquals("yo", stuff.get(0)); } @Test public void shouldHandleVoidMethodsWithCast() { CountDownLatch latch = new CountDownLatch(1); Service slowService = new SlowService(latch); Service fastService = Future.proxy(slowService).build(getFactory()); fastService.methodReturnsVoid(); } @Test public void shouldHandleVoidMethodsWithGenerics() { CountDownLatch latch = new CountDownLatch(1); Service slowService = new SlowService(latch); Service fastService = Future.proxy(Service.class).with(slowService).build(getFactory()); fastService.methodReturnsVoid(); }
### Question: RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected RRestoreBlobData createRestoreData(final RestoreBlobData restoreBlobData) { checkState(!isEmpty(restoreBlobData.getBlobName()), "Blob name cannot be empty"); return new RRestoreBlobData(restoreBlobData); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess, final RepositoryManager repositoryManager, final BlobStoreManager blobStoreManager, final DryRunPrefix dryRunPrefix); }### Answer: @Test public void testBlobDataIsCreated() { assertThat(restoreBlobStrategy.createRestoreData(restoreBlobData).getBlobData(), is(restoreBlobData)); } @Test(expected = IllegalStateException.class) public void testIfBlobDataNameIsEmptyExceptionIsThrown() { when(rRestoreBlobData.getBlobData().getBlobName()).thenReturn(""); restoreBlobStrategy.createRestoreData(restoreBlobData); }
### Question: RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Nonnull @Override protected List<HashAlgorithm> getHashAlgorithms() { return ImmutableList.of(SHA1); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess, final RepositoryManager repositoryManager, final BlobStoreManager blobStoreManager, final DryRunPrefix dryRunPrefix); }### Answer: @Test public void testCorrectHashAlgorithmsAreSupported() { assertThat(restoreBlobStrategy.getHashAlgorithms(), containsInAnyOrder(SHA1)); }
### Question: RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected String getAssetPath(@Nonnull final RRestoreBlobData rRestoreBlobData) { return rRestoreBlobData.getBlobData().getBlobName(); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess, final RepositoryManager repositoryManager, final BlobStoreManager blobStoreManager, final DryRunPrefix dryRunPrefix); }### Answer: @Test public void testAppropriatePathIsReturned() { assertThat(restoreBlobStrategy.getAssetPath(rRestoreBlobData), is(ARCHIVE_PATH)); }
### Question: RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected boolean assetExists(@Nonnull final RRestoreBlobData rRestoreBlobData) { RRestoreFacet facet = getRestoreFacet(rRestoreBlobData); return facet.assetExists(getAssetPath(rRestoreBlobData)); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess, final RepositoryManager repositoryManager, final BlobStoreManager blobStoreManager, final DryRunPrefix dryRunPrefix); }### Answer: @Test public void testPackageIsRestored() throws Exception { restoreBlobStrategy.restore(properties, blob, TEST_BLOB_STORE_NAME, false); verify(rRestoreFacet).assetExists(ARCHIVE_PATH); verify(rRestoreFacet).restore(any(AssetBlob.class), eq(ARCHIVE_PATH)); verifyNoMoreInteractions(rRestoreFacet); }
### Question: RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected boolean componentRequired(final RRestoreBlobData data) { RRestoreFacet facet = getRestoreFacet(data); final String path = data.getBlobData().getBlobName(); return facet.componentRequired(path); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess, final RepositoryManager repositoryManager, final BlobStoreManager blobStoreManager, final DryRunPrefix dryRunPrefix); }### Answer: @Test public void testComponentIsRequiredForGz() { boolean expected = true; when(rRestoreFacet.componentRequired(ARCHIVE_PATH)).thenReturn(expected); assertThat(restoreBlobStrategy.componentRequired(rRestoreBlobData), is(expected)); verify(rRestoreFacet).componentRequired(ARCHIVE_PATH); verifyNoMoreInteractions(rRestoreFacet); }
### Question: RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected Query getComponentQuery(final RRestoreBlobData data) throws IOException { RRestoreFacet facet = getRestoreFacet(data); RestoreBlobData blobData = data.getBlobData(); Map<String, String> attributes; try (InputStream inputStream = blobData.getBlob().getInputStream()) { attributes = facet.extractComponentAttributesFromArchive(blobData.getBlobName(), inputStream); } return facet.getComponentQuery(attributes); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess, final RepositoryManager repositoryManager, final BlobStoreManager blobStoreManager, final DryRunPrefix dryRunPrefix); }### Answer: @Test public void testComponentQuery() throws IOException { restoreBlobStrategy.getComponentQuery(rRestoreBlobData); verify(rRestoreFacet, times(1)).getComponentQuery(anyMapOf(String.class, String.class)); }
### Question: XssSanitizerService { public String sanitize(String html) { return policyFactory.sanitize( html, xssHtmlChangeListener, "ip='"+ getIpAddressFromRequestContext()+"'" ); } String sanitize(String html); }### Answer: @Test public void test() throws Exception { String unsafe = "<a href='javascript:alert('XSS')'>часто</a> используемый в печати и вэб-дизайне"; String safe = xssSanitizerService.sanitize(unsafe); Assertions.assertEquals("часто используемый в печати и вэб-дизайне", safe); } @Test public void testNoClosed() throws Exception { String unsafe = "<a href='javascript:alert('XSS')'>часто используемый в печати и вэб-дизайне"; String safe = xssSanitizerService.sanitize(unsafe); Assertions.assertEquals("часто используемый в печати и вэб-дизайне", safe); }
### Question: PostConverter { public static String getYouTubeVideoId(String iframeSrcUrl) { UriComponents build = UriComponentsBuilder.fromHttpUrl(iframeSrcUrl).build(); List<String> pathSegments = build.getPathSegments(); return pathSegments.get(pathSegments.size() - 1); } PostDTOWithAuthorization convertToDto(Post saved, UserAccountDetailsDTO userAccount); Post convertToPost(PostDTO postDTO, Post forUpdate); static String getYouTubeVideoId(String iframeSrcUrl); IndexPost toElasticsearchPost(com.github.nkonev.blog.entity.jdbc.Post jpaPost); static void cleanTags(PostDTO postDTO); static String cleanHtmlTags(String html); PostDTO convertToPostDTO(Post post); }### Answer: @Test public void testGetYouTubeId() { String youtubeVideoId = PostConverter.getYouTubeVideoId("https: Assertions.assertEquals("eoDsxos6xhM", youtubeVideoId); }
### Question: Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }### Answer: @Test public void replaceSlashes07() { assertEquals("Replaced", "/foo/bar/car/", Path.replaceSlashes("/foo } @Test public void replaceSlashesWithNull() { assertEquals("Replaced", null, Path.replaceSlashes(null)); } @Test public void replaceSlashes01() { assertEquals("Replaced", "/foo/bar/", Path.replaceSlashes("/foo/bar/")); } @Test public void replaceSlashes02() { assertEquals("Replaced", "/", Path.replaceSlashes("/")); } @Test public void replaceSlashes03() { assertEquals("Replaced", "/", Path.replaceSlashes(" } @Test public void replaceSlashes04() { assertEquals("Replaced", "/foo/bar", Path.replaceSlashes(" } @Test public void replaceSlashes05() { assertEquals("Replaced", "foo/bar/", Path.replaceSlashes("foo/bar } @Test public void replaceSlashes06() { assertEquals("Replaced", "foo/bar", Path.replaceSlashes("foo }
### Question: Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }### Answer: @Test public void normalizeResourcePathSlash01() { assertEquals("Normalized", "/", Path.normalizeResourcePath("/")); } @Test public void normalizeResourcePathSlash02() { assertEquals("Normalized", "/", Path.normalizeResourcePath(" /")); } @Test public void normalizeResourcePathSlash03() { assertEquals("Normalized", "/", Path.normalizeResourcePath(" / ")); } @Test public void normalizeResourcePathSlash04() { assertEquals("Normalized", "/", Path.normalizeResourcePath("/ ")); }
### Question: WebAppParser { protected WebAppType parseWebXml(URL url) { try { XMLReader reader = XMLReaderFactory.createXMLReader(); NamespaceFilter inFilter = new NamespaceFilter("http: inFilter.setParent(reader); JAXBContext context = JAXBContext.newInstance(WebAppType.class); Unmarshaller unmarshaller = context.createUnmarshaller(); SAXSource source = new SAXSource(inFilter, new InputSource(url.openStream())); return unmarshaller.unmarshal(source, WebAppType.class).getValue(); } catch (JAXBException | IOException | SAXException exc) { LOG.error("error parsing web.xml", exc); } return null; } WebAppParser(ServiceTracker<PackageAdmin, PackageAdmin> packageAdmin); void parse(final Bundle bundle, WebApp webApp); static Boolean canSeeClass(Bundle bundle, Class<?> clazz); }### Answer: @SuppressWarnings("deprecation") @Test public void testParseWebXml() throws Exception { WebAppParser parser = new WebAppParser(null); File file = new File("src/test/resources/web.xml"); assertTrue(file.exists()); WebAppType parseWebXml = parser.parseWebXml(file.toURL()); assertNotNull(parseWebXml); List<JAXBElement<?>> list = parseWebXml.getModuleNameOrDescriptionAndDisplayName(); for (JAXBElement<?> jaxbElement : list) { Object value = jaxbElement.getValue(); if (value instanceof SessionConfigType) { SessionConfigType sessionConfig = (SessionConfigType) value; BigInteger value2 = sessionConfig.getSessionTimeout().getValue(); assertThat(value2.intValue(), is(30)); } } }
### Question: DeployerUtils { public static String[] extractNameVersionType(String url) { Matcher m = ARTIFACT_MATCHER.matcher(url); if (!m.matches()) { return new String[]{url.split("\\.")[0], DEFAULT_VERSION}; } else { StringBuilder v = new StringBuilder(); String d1 = m.group(1); String d2 = m.group(2); String d3 = m.group(3); String d4 = m.group(4); String d5 = m.group(5); String d6 = m.group(6); if (d2 != null) { v.append(d2); if (d3 != null) { v.append('.'); v.append(d3); if (d4 != null) { v.append('.'); v.append(d4); if (d5 != null) { v.append("."); cleanupModifier(v, d5); } } else if (d5 != null) { v.append(".0."); cleanupModifier(v, d5); } } else if (d5 != null) { v.append(".0.0."); cleanupModifier(v, d5); } } return new String[]{d1, v.toString(), d6}; } } private DeployerUtils(); static String[] extractNameVersionType(String url); }### Answer: @Test public void testExtractNameVersionType() { String[] nameVersion; nameVersion = DeployerUtils.extractNameVersionType("test-1.0.0.war"); assertEquals("test", nameVersion[0]); assertEquals("1.0.0", nameVersion[1]); nameVersion = DeployerUtils.extractNameVersionType("test.war"); assertEquals("test", nameVersion[0]); assertEquals("0.0.0", nameVersion[1]); }
### Question: HttpServiceFactoryImpl implements ServiceFactory<HttpService> { @Override public HttpService getService(final Bundle bundle, final ServiceRegistration<HttpService> serviceRegistration) { LOG.info("Binding bundle: [" + bundle + "] to http service"); return createService(bundle); } @Override HttpService getService(final Bundle bundle, final ServiceRegistration<HttpService> serviceRegistration); @Override void ungetService(final Bundle bundle, final ServiceRegistration<HttpService> serviceRegistration, final HttpService httpService); }### Answer: @Test public void checkGetServiceFlow() { replay(bundle, serviceRegistration, httpService); Object result = underTest.getService(bundle, serviceRegistration); assertNotNull("expect not null", result); verify(bundle, serviceRegistration, httpService); }
### Question: HttpServiceFactoryImpl implements ServiceFactory<HttpService> { @Override public void ungetService(final Bundle bundle, final ServiceRegistration<HttpService> serviceRegistration, final HttpService httpService) { LOG.info("Unbinding bundle: [" + bundle + "]"); ((StoppableHttpService) httpService).stop(); } @Override HttpService getService(final Bundle bundle, final ServiceRegistration<HttpService> serviceRegistration); @Override void ungetService(final Bundle bundle, final ServiceRegistration<HttpService> serviceRegistration, final HttpService httpService); }### Answer: @Test public void checkUngetServiceFlow() { httpService.stop(); replay(bundle, serviceRegistration, httpService); underTest.ungetService(bundle, serviceRegistration, httpService); verify(bundle, serviceRegistration, httpService); }
### Question: DefaultHttpContext implements WebContainerContext { @Override public boolean handleSecurity(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws IOException { return true; } DefaultHttpContext(final Bundle bundle, String contextID); @Override boolean handleSecurity(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse); @Override URL getResource(final String name); @Override String getMimeType(String name); @Override Set<String> getResourcePaths(final String name); @Override String getContextId(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void handleSecurity() throws IOException { assertTrue(contextUnderTest.handleSecurity(null, null)); }
### Question: DefaultHttpContext implements WebContainerContext { @Override public String getMimeType(String name) { return null; } DefaultHttpContext(final Bundle bundle, String contextID); @Override boolean handleSecurity(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse); @Override URL getResource(final String name); @Override String getMimeType(String name); @Override Set<String> getResourcePaths(final String name); @Override String getContextId(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void getMimeType() { assertEquals(null, contextUnderTest.getMimeType(null)); }
### Question: DefaultHttpContext implements WebContainerContext { @Override public URL getResource(final String name) { final String normalizedname = Path.normalizeResourcePath(name); LOG.debug("Searching bundle [" + bundle + "] for resource [" + normalizedname + "]"); return bundle.getResource(normalizedname); } DefaultHttpContext(final Bundle bundle, String contextID); @Override boolean handleSecurity(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse); @Override URL getResource(final String name); @Override String getMimeType(String name); @Override Set<String> getResourcePaths(final String name); @Override String getContextId(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void getResource() throws MalformedURLException { URL url = new URL("file: expect(bundle.getResource("test")).andReturn(url); replay(bundle); contextUnderTest.getResource("test"); verify(bundle); }
### Question: Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }### Answer: @Test public void replaceSlashesWithNull() { assertEquals("Replaced", null, Path.replaceSlashes(null)); } @Test public void replaceSlashes01() { assertEquals("Replaced", "/foo/bar/", Path.replaceSlashes("/foo/bar/")); } @Test public void replaceSlashes02() { assertEquals("Replaced", "/", Path.replaceSlashes("/")); } @Test public void replaceSlashes03() { assertEquals("Replaced", "/", Path.replaceSlashes(" } @Test public void replaceSlashes04() { assertEquals("Replaced", "/foo/bar", Path.replaceSlashes(" } @Test public void replaceSlashes05() { assertEquals("Replaced", "foo/bar/", Path.replaceSlashes("foo/bar } @Test public void replaceSlashes06() { assertEquals("Replaced", "foo/bar", Path.replaceSlashes("foo } @Test public void replaceSlashes07() { assertEquals("Replaced", "/foo/bar/car/", Path.replaceSlashes("/foo }
### Question: Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }### Answer: @Test public void normalizeResourcePathSlash01() { assertEquals("Normalized", "/", Path.normalizeResourcePath("/")); } @Test public void normalizeResourcePathSlash02() { assertEquals("Normalized", "/", Path.normalizeResourcePath(" /")); } @Test public void normalizeResourcePathSlash03() { assertEquals("Normalized", "/", Path.normalizeResourcePath(" / ")); } @Test public void normalizeResourcePathSlash04() { assertEquals("Normalized", "/", Path.normalizeResourcePath("/ ")); }
### Question: FileTools { public static boolean createBlankProject(String path, String projectName) { boolean result = true; result &= createDirectory(path + File.separator + projectName); result &= createAssetDirectories(path + File.separator + projectName); return result; } static String getJreDirectory(); static String getBuildsDirectory(); static String getProjectsDirectory(); static String getExecutionPath(Class clazz); static boolean createBlankProject(String path, String projectName); static Project createProjectFromTemplate(String path, String projectName, String template); static boolean createAssetDirectories(String path); static File doChoosePath(); static File doChooseFile(String extension, String directory, String type); static void saveAsset(AbstractAsset asset); }### Answer: @Test public void testCreateDirectoryStructure() { System.out.println("createDirectoryStructure"); String path = System.getProperty("user.home"); String project = "Test"; boolean expResult = true; boolean result = FileTools.createBlankProject(path, project); assertEquals(expResult, result); }
### Question: FileTools { public static File doChoosePath() { JFileChooser fileChooser = new JFileChooser(System.getProperty("user.home")); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (fileChooser.showOpenDialog(MainWindow.getInstance()) == JFileChooser.APPROVE_OPTION) { return fileChooser.getCurrentDirectory(); } return null; } static String getJreDirectory(); static String getBuildsDirectory(); static String getProjectsDirectory(); static String getExecutionPath(Class clazz); static boolean createBlankProject(String path, String projectName); static Project createProjectFromTemplate(String path, String projectName, String template); static boolean createAssetDirectories(String path); static File doChoosePath(); static File doChooseFile(String extension, String directory, String type); static void saveAsset(AbstractAsset asset); }### Answer: @Test @Ignore public void testDoChoosePath() { System.out.println("doChoosePath"); File expResult = null; File result = FileTools.doChoosePath(); assertEquals(expResult, result); fail("The test case is a prototype."); }
### Question: FileTools { public static File doChooseFile(String extension, String directory, String type) { if (MainWindow.getInstance().getActiveProject() != null) { File projectPath = new File(System.getProperty("project.path") + File.separator + directory); if (projectPath.exists()) { JFileChooser fileChooser = new JFileChooser(new SingleRootFileSystemView(projectPath)); fileChooser.setAcceptAllFileFilterUsed(false); FileNameExtensionFilter filter = new FileNameExtensionFilter(type, extension); fileChooser.setFileFilter(filter); if (fileChooser.showOpenDialog(MainWindow.getInstance()) == JFileChooser.APPROVE_OPTION) { return fileChooser.getSelectedFile(); } } } return null; } static String getJreDirectory(); static String getBuildsDirectory(); static String getProjectsDirectory(); static String getExecutionPath(Class clazz); static boolean createBlankProject(String path, String projectName); static Project createProjectFromTemplate(String path, String projectName, String template); static boolean createAssetDirectories(String path); static File doChoosePath(); static File doChooseFile(String extension, String directory, String type); static void saveAsset(AbstractAsset asset); }### Answer: @Test @Ignore public void testDoChooseFile() { System.out.println("doChooseFile"); String extension = ""; String directory = ""; String type = ""; File expResult = null; File result = FileTools.doChooseFile(extension, directory, type); assertEquals(expResult, result); fail("The test case is a prototype."); }
### Question: JSONCPARepository implements CPARepository { public boolean isValidPartnerAgreement(final Map<String, Object> fields) { PartnerAgreement agreement = (PartnerAgreement) fields.get(EbmsConstants.CPA); return agreement != null; } void init(); @Override List<PartnerAgreement> getPartnerAgreements(); @Override List<PartnerAgreement> getActivePartnerAgreements(); @Override PartnerAgreement findByCPAId(String cpaId); @Override PartnerAgreement findByServiceAndAction(final String service, final String action); @Override PartnerAgreement findByMessage(Document message, String ebmsVersion); boolean isValidPartnerAgreement(final Map<String, Object> fields); File getCpaJsonFile(); void setCpaJsonFile(File cpaJsonFile); }### Answer: @Test public void testIsValidPartnerAgreement() throws IOException { JSONCPARepository repository = new JSONCPARepository(); repository.setCpaJsonFile(fileFromClasspath("agreementWithServices.json")); repository.init(); Map<String,Object> fields = new ImmutableMap.Builder<String, Object>() .put(EbmsConstants.CPA, repository.getActivePartnerAgreements().get(0)) .build(); assertThat(repository.isValidPartnerAgreement(fields),is(true)); Map<String,Object> fields2 = new ImmutableMap.Builder<String, Object>() .put(EbmsConstants.MESSAGE_SERVICE, "service2") .put(EbmsConstants.MESSAGE_ACTION,"action1") .build(); assertThat(repository.isValidPartnerAgreement(fields2),is(false)); }
### Question: FileMessageStore implements MessageStore { @Override public Message findByMessageId(final String messageId, String messageDirection) { return new DefaultMessage(messageId); } @Override void store(@Body InputStream input, Exchange exchange); @Override void storeMessage(Exchange exchange); @Override Message findByMessageId(final String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection,String status); @Override void updateMessage(final String messageId, String messageDirection, MessageStatusType status, String statusDescription); String getBaseDir(); void setBaseDir(String baseDir); String getFileNameExpression(); void setFileNameExpression(String fileNameExpression); @Override String toString(); }### Answer: @Test public void testFileMessageStore() throws IOException { Exchange request = new DefaultExchange(context()); request.getIn().setHeader(EbmsConstants.EBMS_VERSION,EbmsConstants.EBMS_V3); request.getIn().setHeader(EbmsConstants.MESSAGE_ID,"testMessageID"); request.getIn().setBody(new ByteArrayInputStream("test".getBytes())); Exchange response = context().createProducerTemplate().send(MessageStore.DEFAULT_MESSAGE_STORE_ENDPOINT,request); String msgId = response.getIn().getHeader(MessageStore.JENTRATA_MESSAGE_ID, String.class); assertThat(msgId,equalTo("testMessageID")); assertThat(messageStore.findByMessageId(msgId,EbmsConstants.MESSAGE_DIRECTION_INBOUND).getMessageId(),equalTo(msgId)); }
### Question: FileMessageStore implements MessageStore { @Override public InputStream findPayloadById(String messageId) { try { return new FileInputStream(getFilename(messageId)); } catch (FileNotFoundException e) { return null; } } @Override void store(@Body InputStream input, Exchange exchange); @Override void storeMessage(Exchange exchange); @Override Message findByMessageId(final String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection,String status); @Override void updateMessage(final String messageId, String messageDirection, MessageStatusType status, String statusDescription); String getBaseDir(); void setBaseDir(String baseDir); String getFileNameExpression(); void setFileNameExpression(String fileNameExpression); @Override String toString(); }### Answer: @Test public void testFindPayloadById() throws Exception { testFileMessageStore(); InputStream stream = messageStore.findPayloadById("testMessageID"); assertThat(IOUtils.toString(stream),equalTo("test")); }
### Question: JDBCMessageStore implements MessageStore { @Override public void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription) { repositoryManager.updateMessage(messageId,messageDirection,status,statusDescription); } void init(); @Override void store(InputStream message, Exchange exchange); void storeMessage(Exchange exchange); @Override void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription); @Override Message findByMessageId(String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection, String status); RepositoryManager getRepositoryManager(); void setRepositoryManager(RepositoryManager repositoryManager); boolean isCreateTables(); void setCreateTables(boolean createTables); UUIDGenerator getUuidGenerator(); void setUuidGenerator(UUIDGenerator uuidGenerator); }### Answer: @Test public void testUpdateStoreMimeMessage() throws Exception { File body = fileFromClasspath("simple-as4-receipt.xml"); String contentType = "Multipart/Related; boundary=\"----=_Part_7_10584188.1123489648993\"; type=\"application/soap+xml\"; start=\"<[email protected]>\""; String messageId = "testMimeMessage1"; assertStoredMessage(messageId, contentType, body, MessageType.USER_MESSAGE); messageStore.updateMessage(messageId, EbmsConstants.MESSAGE_DIRECTION_INBOUND, MessageStatusType.RECEIVED,"Message Received"); try(Connection conn = dataSource.getConnection()) { try (PreparedStatement st = conn.prepareStatement("select * from message where message_id = ?")) { st.setString(1,messageId); ResultSet resultSet = st.executeQuery(); assertThat(resultSet.next(),is(true)); assertThat(resultSet.getString("status"),equalTo("RECEIVED")); assertThat(resultSet.getString("status_description"),equalTo("Message Received")); } } }
### Question: JDBCMessageStore implements MessageStore { @Override public Message findByMessageId(String messageId, String messageDirection) { Map<String,Object> fields = new HashMap<>(); fields.put("message_id",messageId); fields.put("message_box",messageDirection); List<Message> messages = repositoryManager.selectMessageBy(fields); if(messages.size() > 0) { return messages.get(0); } return null; } void init(); @Override void store(InputStream message, Exchange exchange); void storeMessage(Exchange exchange); @Override void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription); @Override Message findByMessageId(String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection, String status); RepositoryManager getRepositoryManager(); void setRepositoryManager(RepositoryManager repositoryManager); boolean isCreateTables(); void setCreateTables(boolean createTables); UUIDGenerator getUuidGenerator(); void setUuidGenerator(UUIDGenerator uuidGenerator); }### Answer: @Test public void testFindByMessageId() throws Exception { String contentType = "application/soap+xml"; File body = fileFromClasspath("simple-as4-receipt.xml"); String messageId = "testSoapMessage1"; assertStoredMessage(messageId, contentType, body, MessageType.SIGNAL_MESSAGE_WITH_USER_MESSAGE); messageStore.updateMessage(messageId, EbmsConstants.MESSAGE_DIRECTION_INBOUND, MessageStatusType.RECEIVED,"Message Received"); Message message = messageStore.findByMessageId("testSoapMessage1",EbmsConstants.MESSAGE_DIRECTION_INBOUND); assertThat(message,notNullValue()); assertThat(message.getMessageId(),equalTo("testSoapMessage1")); assertThat(message.getStatus(),equalTo(MessageStatusType.RECEIVED)); assertThat(message.getStatusDescription(),equalTo("Message Received")); }
### Question: JDBCMessageStore implements MessageStore { @Override public InputStream findPayloadById(String messageId) { InputStream payload = repositoryManager.selectRepositoryBy("message_id",messageId); return payload; } void init(); @Override void store(InputStream message, Exchange exchange); void storeMessage(Exchange exchange); @Override void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription); @Override Message findByMessageId(String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection, String status); RepositoryManager getRepositoryManager(); void setRepositoryManager(RepositoryManager repositoryManager); boolean isCreateTables(); void setCreateTables(boolean createTables); UUIDGenerator getUuidGenerator(); void setUuidGenerator(UUIDGenerator uuidGenerator); }### Answer: @Test public void testFindPayloadById() throws Exception { testFindByMessageId(); InputStream stream = messageStore.findPayloadById("testSoapMessage1"); assertThat(stream,notNullValue()); assertThat(IOUtils.toString(stream),equalTo(IOUtils.toString(new FileInputStream(fileFromClasspath("simple-as4-receipt.xml"))))); }
### Question: JDBCMessageStore implements MessageStore { @Override public List<Message> findByMessageStatus(String messageDirection, String status) { Map<String,Object> fields = new HashMap<>(); fields.put("status",status); fields.put("message_box",messageDirection); fields.put("orderByDesc","time_stamp"); fields.put("maxResults",100); List<Message> messages = repositoryManager.selectMessageBy(fields); return messages; } void init(); @Override void store(InputStream message, Exchange exchange); void storeMessage(Exchange exchange); @Override void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription); @Override Message findByMessageId(String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection, String status); RepositoryManager getRepositoryManager(); void setRepositoryManager(RepositoryManager repositoryManager); boolean isCreateTables(); void setCreateTables(boolean createTables); UUIDGenerator getUuidGenerator(); void setUuidGenerator(UUIDGenerator uuidGenerator); }### Answer: @Test public void testFindMessageByStatus() throws Exception { testFindByMessageId(); List<Message> messages = messageStore.findByMessageStatus(EbmsConstants.MESSAGE_DIRECTION_INBOUND,MessageStatusType.RECEIVED.name()); assertThat(messages,notNullValue()); assertThat(messages,hasSize(1)); Message message = messages.get(0); assertThat(message,notNullValue()); assertThat(message.getMessageId(),equalTo("testSoapMessage1")); assertThat(message.getStatus(),equalTo(MessageStatusType.RECEIVED)); assertThat(message.getStatusDescription(),equalTo("Message Received")); }
### Question: AvailableSegment extends Segment implements Serializable { public ITEM get(int position) { if (items == null) { return null; } if (covered(position)) { int index = position - getFrom(); return index < items.size() ? items.get(index) : null; } return null; } AvailableSegment(UncoveringDataModel<?> model, int page); int getMaxIndex(); ITEM get(int position); boolean covered(int position); void dataProvided(List<ITEM> items); void dataProvided(List<ITEM> items, int maxIndex); List<ITEM> getData(); String toString(); }### Answer: @Test public void testGet() { AvailableSegment<TestItem> a = new AvailableSegment<>(model, 2); assertEquals(20, a.getFrom()); assertEquals(30, a.getTo()); assertEquals(2, a.getPage()); a.dataProvided(TestItem.range(20, 30)); assertEquals("p.20", a.get(20).toString()); assertEquals("p.29", a.get(29).toString()); assertNull(a.get(19)); assertNull(a.get(30)); }
### Question: AvailableSegment extends Segment implements Serializable { public boolean covered(int position) { return model.getPage(position) == page; } AvailableSegment(UncoveringDataModel<?> model, int page); int getMaxIndex(); ITEM get(int position); boolean covered(int position); void dataProvided(List<ITEM> items); void dataProvided(List<ITEM> items, int maxIndex); List<ITEM> getData(); String toString(); }### Answer: @Test public void testCovered() { AvailableSegment<TestItem> a = new AvailableSegment<>(model, 2); when(model.getPage(anyInt())).thenReturn(2); assertTrue(a.covered(0)); when(model.getPage(anyInt())).thenReturn(1); assertFalse(a.covered(0)); }
### Question: AvailableSegment extends Segment implements Serializable { public void dataProvided(List<ITEM> items) { if (items == null) { dataProvided(items, 0); } else { dataProvided(items, getFrom() + items.size()); } } AvailableSegment(UncoveringDataModel<?> model, int page); int getMaxIndex(); ITEM get(int position); boolean covered(int position); void dataProvided(List<ITEM> items); void dataProvided(List<ITEM> items, int maxIndex); List<ITEM> getData(); String toString(); }### Answer: @Test public void testDataProvided() { AvailableSegment<TestItem> a = new AvailableSegment<>(model, 2); assertNull(a.get(20)); assertNull(a.get(29)); assertNull(a.get(19)); assertNull(a.get(30)); assertEquals(0, a.getMaxIndex()); a.dataProvided(TestItem.range(20, 29)); assertEquals("p.20", a.get(20).toString()); assertEquals("p.28", a.get(28).toString()); assertNull(a.get(19)); assertNull(a.get(29)); assertNull(a.get(30)); assertEquals(29, a.getMaxIndex()); a.dataProvided(TestItem.range(20, 30)); assertEquals(30, a.getMaxIndex()); assertEquals("p.29", a.get(29).toString()); a.dataProvided(null); assertNull(a.get(20)); assertNull(a.get(29)); assertNull(a.get(19)); assertNull(a.get(30)); assertEquals(0, a.getMaxIndex()); }
### Question: Segment implements Serializable { public Segment(UncoveringDataModel<ITEM> model, int page) { this.model = model; this.page = page; } Segment(UncoveringDataModel<ITEM> model, int page); int getFrom(); int getTo(); int getPage(); @Override boolean equals(Object o); void setModel(UncoveringDataModel<ITEM> model); @Override int hashCode(); String toString(); }### Answer: @Test public void testSegment() { UncoveringDataModel<TestItem> model = mock(UncoveringDataModel.class); when(model.getPageSize()).thenReturn(10); Segment s = new Segment(model, 20); assertEquals(200, s.getFrom()); assertEquals(210, s.getTo()); assertEquals(20, s.getPage()); }
### Question: WeatherService { public Observable<ThreeHoursForecastWeather> getForecastWeather(double longitude, double latitude) { return api.getForecastWeather(longitude, latitude) .subscribeOn(scheduler) .take(1); } @Inject WeatherService(WeatherApi api, @RxScheduler(NETWORK) Scheduler scheduler, ImageRequestManager imageRequestManager); Observable<Bitmap> loadIcon(String icon); Observable<TomorrowWeather> getTomorrowWeather(double longitude, double latitude); Observable<ThreeHoursForecastWeather> getForecastWeather(double longitude, double latitude); Observable<TodayWeather> getCurrentWeather(double longitude, double latitude); }### Answer: @Test public void shouldLoadForecastWeather() throws ParseException, IOException { final ThreeHoursForecastWeather item = Fakes.fakeResponse(Responses.JSON.THREE_HOUR_FORECAST); doReturn(Observable.just(item)) .when(weatherApi).getForecastWeather(anyDouble(), anyDouble()); TestObserver<ThreeHoursForecastWeather> testObserver = new TestObserver<>(); weatherService.getForecastWeather(1.0, 1.0).subscribe(testObserver); testObserver.assertSubscribed().assertNoErrors().assertComplete().assertValue(item); }
### Question: SearchService { public Observable<SearchModel> searchByCity(String city) { lastCity = city; return api.searchWeather(city).subscribeOn(this.scheduler); } @Inject SearchService(WeatherApi api, @RxScheduler(NETWORK) Scheduler scheduler); Observable<SearchModel> searchByCity(String city); String getLastSearch(); }### Answer: @Test public void searchApiFunctionIsCalled() { final TestObserver<SearchModel> observer = new TestObserver<>(); searchService.searchByCity(CITY).subscribe(observer); verify(weatherApi).searchWeather(CITY); observer.assertSubscribed() .assertNoErrors() .assertComplete() .assertValue(item); }
### Question: TomorrowWeatherViewModel extends WeatherViewModel { public void loadForecastWeatherDataForTomorrow() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(this::handleForecastDataResult, this::showError); } } @Inject @Replaceable TomorrowWeatherViewModel(NavigationController navigation, @RxObservable(PAGE) Observable<Integer> pageChangeObservable, PermissionService permissionService, LocationService locationService, WeatherService weatherService, TomorrowWeatherResponseFilter weatherParser, @RxScheduler(MAIN) Scheduler androidScheduler); void loadForecastWeatherDataForTomorrow(); }### Answer: @Test public void shouldNotLoadForecastsIfNoLocationIsPresent() { when(locationService.lastLocation()).thenReturn(null); vm.onViewAttached(); vm.loadForecastWeatherDataForTomorrow(); verifyZeroInteractions(weatherService); } @Test public void shouldLoadForecastsIfLocationIsPresent() throws ParseException, IOException { double longitude = 1.0; double latitude = 1.0; final Location location = mockLocation(mock(Location.class), 1.0, 1.0); when(locationService.lastLocation()).thenReturn(location); String expectedResult = Responses.createExpectedFilteredResult(); when(weatherParser.parse(any(ThreeHoursForecastWeather.class))).thenReturn(expectedResult); when(weatherService.getForecastWeather(longitude, latitude)) .thenReturn(Observable.just(fakeResponse(Responses.JSON.THREE_HOUR_FORECAST))); vm.loadForecastWeatherDataForTomorrow(); verify(navigation).toForecastActivity(expectedResult); }
### Question: TodayWeatherViewModel extends WeatherViewModel { public void loadForecastWeatherDataForToday() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(forecastData -> { dispatchRequestFinished(); navigateToForecastActivity(forecastData); }, this::showError); } } @Inject @Replaceable TodayWeatherViewModel(NavigationController navigation, @RxObservable(PAGE) Observable<Integer> pageChangeObservable, PermissionService permissionService, LocationService locationService, WeatherService weatherService, TodayWeatherResponseFilter weatherParser, @RxScheduler(MAIN) Scheduler androidScheduler); void loadForecastWeatherDataForToday(); }### Answer: @Test public void shouldNotLoadForecastsIfNoLocationIsPresent() { when(locationService.lastLocation()).thenReturn(null); vm.onViewAttached(); vm.loadForecastWeatherDataForToday(); verifyZeroInteractions(weatherService); } @Test public void shouldLoadForecastsIfLocationIsPresent() throws ParseException, IOException { double longitude = 1.0; double latitude = 1.0; final Location location = mockLocation(mock(Location.class), 1.0, 1.0); when(locationService.lastLocation()).thenReturn(location); String expectedResult = Responses.createExpectedFilteredResult(); when(weatherParser.parse(any(ThreeHoursForecastWeather.class))).thenReturn(expectedResult); when(weatherService.getForecastWeather(longitude, latitude)) .thenReturn(Observable.just(fakeResponse(Responses.JSON.THREE_HOUR_FORECAST))); vm.loadForecastWeatherDataForToday(); verify(navigation).toForecastActivity(expectedResult); }
### Question: CounterWithProgress extends ObservableImp { @SuppressLint("StaticFieldLeak") public void increaseBy20(){ logger.i(TAG, "increaseBy20()"); isBusy = true; notifyObservers(); new Async<Void, Integer, Integer>(workMode) { @Override protected Integer doInBackground(Void... voids) { int totalIncrease = 0; for (int ii=0; ii<20; ii++) { synchronized (this) { try { wait(workMode == WorkMode.SYNCHRONOUS ? 1 : 100); } catch (InterruptedException e) { } } publishProgressTask(++totalIncrease); } return totalIncrease; } @Override protected void onProgressUpdate(Integer... values) { logger.i(TAG, "-tick-"); progress = values[0]; notifyObservers(); } @Override protected void onPostExecute(Integer result) { logger.i(TAG, "done"); count = count + result; isBusy = false; progress = 0; notifyObservers(); } }.executeTask((Void)null); } CounterWithProgress(WorkMode workMode, Logger logger); @SuppressLint("StaticFieldLeak") void increaseBy20(); boolean isBusy(); int getCount(); int getProgress(); static final String TAG; }### Answer: @Test public void observersNotifiedAtLeastOnce() throws Exception { CounterWithProgress counterWithProgress = new CounterWithProgress(WorkMode.SYNCHRONOUS, logger); Observer mockObserver = mock(Observer.class); counterWithProgress.addObserver(mockObserver); counterWithProgress.increaseBy20(); verify(mockObserver, atLeastOnce()).somethingChanged(); }
### Question: CounterWithLambdas extends ObservableImp { public void increaseBy20(){ logger.i(TAG, "increaseBy20()"); isBusy = true; notifyObservers(); new AsyncBuilder<Void, Integer>(workMode) .doInBackground(input -> CounterWithLambdas.this.doStuffInBackground(input)) .onPostExecute(result -> CounterWithLambdas.this.doThingsWithTheResult(result)) .execute((Void) null); } CounterWithLambdas(WorkMode workMode, Logger logger); void increaseBy20(); boolean isBusy(); int getCount(); static final String TAG; }### Answer: @Test public void observersNotifiedAtLeastOnce() throws Exception { CounterWithLambdas counterWithLambdas = new CounterWithLambdas(WorkMode.SYNCHRONOUS, logger); Observer mockObserver = mock(Observer.class); counterWithLambdas.addObserver(mockObserver); counterWithLambdas.increaseBy20(); verify(mockObserver, atLeastOnce()).somethingChanged(); }
### Question: PlaylistAdvancedModel extends ObservableImp implements Updateable { public void addNewTrack() { logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); @Override UpdateSpec getAndClearLatestUpdateSpec(long maxAgeMs); }### Answer: @Test public void addNewTrack() throws Exception { PlaylistAdvancedModel playlistAdvancedModel = new PlaylistAdvancedModel(mockSystemTimeWrapper, WorkMode.SYNCHRONOUS, logger); playlistAdvancedModel.addNewTrack(); Assert.assertEquals(1, playlistAdvancedModel.getTrackListSize()); Assert.assertEquals(1, playlistAdvancedModel.getTrack(0).getNumberOfPlaysRequested()); } @Test public void observersNotifiedAtLeastOnceForAddTrack() throws Exception { PlaylistAdvancedModel playlistAdvancedModel = new PlaylistAdvancedModel(mockSystemTimeWrapper, WorkMode.SYNCHRONOUS, logger); Observer mockObserver = mock(Observer.class); playlistAdvancedModel.addObserver(mockObserver); playlistAdvancedModel.addNewTrack(); verify(mockObserver, atLeastOnce()).somethingChanged(); }
### Question: PlaylistAdvancedModel extends ObservableImp implements Updateable { public void removeTrack(int index) { logger.i(TAG, "removeTrack() " + index); checkIndex(index); trackList.remove(index); notifyObservers(); } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); @Override UpdateSpec getAndClearLatestUpdateSpec(long maxAgeMs); }### Answer: @Test public void removeTrack() throws Exception { PlaylistAdvancedModel playlistAdvancedModel = new PlaylistAdvancedModel(mockSystemTimeWrapper, WorkMode.SYNCHRONOUS, logger); playlistAdvancedModel.addNewTrack(); playlistAdvancedModel.removeTrack(0); Assert.assertEquals(0, playlistAdvancedModel.getTrackListSize()); }
### Question: PlaylistAdvancedModel extends ObservableImp implements Updateable { public void add5NewTracks() { logger.i(TAG, "add5NewTracks()"); List<Track> newTracks = new ArrayList<>(); for (int ii=0; ii<5; ii++){ newTracks.add(new Track(generateRandomColourResource())); } trackList.addAll(0, newTracks); notifyObservers(); } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); @Override UpdateSpec getAndClearLatestUpdateSpec(long maxAgeMs); }### Answer: @Test public void add5NewTracks() throws Exception { PlaylistAdvancedModel playlistAdvancedModel = new PlaylistAdvancedModel(mockSystemTimeWrapper, WorkMode.SYNCHRONOUS, logger); playlistAdvancedModel.add5NewTracks(); Assert.assertEquals(5, playlistAdvancedModel.getTrackListSize()); Assert.assertEquals(1, playlistAdvancedModel.getTrack(4).getNumberOfPlaysRequested()); }
### Question: PlaylistAdvancedModel extends ObservableImp implements Updateable { public void remove5Tracks() { logger.i(TAG, "remove5Tracks()"); if (getTrackListSize()>4){ trackList.removeRange(0, 5); notifyObservers(); } } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); @Override UpdateSpec getAndClearLatestUpdateSpec(long maxAgeMs); }### Answer: @Test public void remove5Tracks() throws Exception { PlaylistAdvancedModel playlistAdvancedModel = new PlaylistAdvancedModel(mockSystemTimeWrapper, WorkMode.SYNCHRONOUS, logger); playlistAdvancedModel.add5NewTracks(); playlistAdvancedModel.remove5Tracks(); Assert.assertEquals(0, playlistAdvancedModel.getTrackListSize()); }
### Question: PlaylistAdvancedModel extends ObservableImp implements Updateable { public void removeAllTracks() { logger.i(TAG, "removeAllTracks()"); trackList.clear(); notifyObservers(); } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); @Override UpdateSpec getAndClearLatestUpdateSpec(long maxAgeMs); }### Answer: @Test public void removeAllTracks() throws Exception { PlaylistAdvancedModel playlistAdvancedModel = new PlaylistAdvancedModel(mockSystemTimeWrapper, WorkMode.SYNCHRONOUS, logger); playlistAdvancedModel.add5NewTracks(); playlistAdvancedModel.addNewTrack(); playlistAdvancedModel.addNewTrack(); playlistAdvancedModel.removeAllTracks(); Assert.assertEquals(0, playlistAdvancedModel.getTrackListSize()); }
### Question: PlaylistSimpleModel extends ObservableImp { public int getTrackListSize(){ return trackList.size(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); }### Answer: @Test public void initialConditions() throws Exception { PlaylistSimpleModel playlistSimpleModel = new PlaylistSimpleModel(WorkMode.SYNCHRONOUS, logger); Assert.assertEquals(0, playlistSimpleModel.getTrackListSize()); Assert.assertEquals(false, playlistSimpleModel.hasObservers()); }
### Question: PlaylistSimpleModel extends ObservableImp { public void addNewTrack(){ logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); }### Answer: @Test public void addNewTrack() throws Exception { PlaylistSimpleModel playlistSimpleModel = new PlaylistSimpleModel(WorkMode.SYNCHRONOUS, logger); playlistSimpleModel.addNewTrack(); Assert.assertEquals(1, playlistSimpleModel.getTrackListSize()); Assert.assertEquals(1, playlistSimpleModel.getTrack(0).getNumberOfPlaysRequested()); } @Test public void observersNotifiedAtLeastOnceForAddTrack() throws Exception { PlaylistSimpleModel playlistSimpleModel = new PlaylistSimpleModel(WorkMode.SYNCHRONOUS, logger); Observer mockObserver = mock(Observer.class); playlistSimpleModel.addObserver(mockObserver); playlistSimpleModel.addNewTrack(); verify(mockObserver, atLeastOnce()).somethingChanged(); }
### Question: PlaylistSimpleModel extends ObservableImp { public void removeTrack(int index){ logger.i(TAG, "removeTrack() "+index); checkIndex(index); trackList.remove(index); notifyObservers(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); }### Answer: @Test public void removeTrack() throws Exception { PlaylistSimpleModel playlistSimpleModel = new PlaylistSimpleModel(WorkMode.SYNCHRONOUS, logger); playlistSimpleModel.addNewTrack(); playlistSimpleModel.removeTrack(0); Assert.assertEquals(0, playlistSimpleModel.getTrackListSize()); }
### Question: PlaylistSimpleModel extends ObservableImp { public void add5NewTracks() { logger.i(TAG, "add5NewTracks()"); List<Track> newTracks = new ArrayList<>(); for (int ii=0; ii<5; ii++){ newTracks.add(new Track(generateRandomColourResource())); } trackList.addAll(0, newTracks); notifyObservers(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); }### Answer: @Test public void add5NewTracks() throws Exception { PlaylistSimpleModel playlistSimpleModel = new PlaylistSimpleModel(WorkMode.SYNCHRONOUS, logger); playlistSimpleModel.add5NewTracks(); Assert.assertEquals(5, playlistSimpleModel.getTrackListSize()); Assert.assertEquals(1, playlistSimpleModel.getTrack(4).getNumberOfPlaysRequested()); }
### Question: PlaylistSimpleModel extends ObservableImp { public void remove5Tracks() { logger.i(TAG, "remove5Tracks()"); if (getTrackListSize()>4){ trackList.subList(0, 5).clear(); notifyObservers(); } } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); }### Answer: @Test public void remove5Tracks() throws Exception { PlaylistSimpleModel playlistSimpleModel = new PlaylistSimpleModel(WorkMode.SYNCHRONOUS, logger); playlistSimpleModel.add5NewTracks(); playlistSimpleModel.remove5Tracks(); Assert.assertEquals(0, playlistSimpleModel.getTrackListSize()); }
### Question: PlaylistSimpleModel extends ObservableImp { public void removeAllTracks() { logger.i(TAG, "removeAllTracks()"); trackList.clear(); notifyObservers(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); }### Answer: @Test public void removeAllTracks() throws Exception { PlaylistSimpleModel playlistSimpleModel = new PlaylistSimpleModel(WorkMode.SYNCHRONOUS, logger); playlistSimpleModel.add5NewTracks(); playlistSimpleModel.addNewTrack(); playlistSimpleModel.addNewTrack(); playlistSimpleModel.removeAllTracks(); Assert.assertEquals(0, playlistSimpleModel.getTrackListSize()); }
### Question: Wallet extends ObservableImp { public void increaseMobileWallet() { if (canIncrease()) { mobileWalletDollars++; logger.i(TAG, "Increasing mobile wallet to:" + mobileWalletDollars); notifyObservers(); } } Wallet(Logger logger); void increaseMobileWallet(); void decreaseMobileWallet(); int getMobileWalletAmount(); int getSavingsWalletAmount(); boolean canIncrease(); boolean canDecrease(); final int totalDollarsAvailable; }### Answer: @Test public void increaseMobileWallet() throws Exception { Wallet wallet = new Wallet(logger); wallet.increaseMobileWallet(); Assert.assertEquals(true, wallet.canIncrease()); Assert.assertEquals(true, wallet.canDecrease()); Assert.assertEquals(wallet.totalDollarsAvailable - 1, wallet.getSavingsWalletAmount()); Assert.assertEquals(1, wallet.getMobileWalletAmount()); } @Test public void observersNotifiedAtLeastOnceForIncrease() throws Exception { Wallet wallet = new Wallet(logger); Observer mockObserver = mock(Observer.class); wallet.addObserver(mockObserver); wallet.increaseMobileWallet(); verify(mockObserver, atLeastOnce()).somethingChanged(); }
### Question: Wallet extends ObservableImp { public void decreaseMobileWallet(){ if (canDecrease()) { mobileWalletDollars--; logger.i(TAG, "Decreasing mobile wallet to:" + mobileWalletDollars); notifyObservers(); } } Wallet(Logger logger); void increaseMobileWallet(); void decreaseMobileWallet(); int getMobileWalletAmount(); int getSavingsWalletAmount(); boolean canIncrease(); boolean canDecrease(); final int totalDollarsAvailable; }### Answer: @Test public void decreaseMobileWallet() throws Exception { Wallet wallet = new Wallet(logger); wallet.increaseMobileWallet(); Assert.assertEquals(1, wallet.getMobileWalletAmount()); wallet.decreaseMobileWallet(); Assert.assertEquals(true, wallet.canIncrease()); Assert.assertEquals(false, wallet.canDecrease()); Assert.assertEquals(wallet.totalDollarsAvailable, wallet.getSavingsWalletAmount()); Assert.assertEquals(0, wallet.getMobileWalletAmount()); }
### Question: AmazonWebServiceClient { protected Signer getSigner() { return signer; } protected AmazonWebServiceClient( final ClientConfiguration clientConfiguration); @Deprecated protected AmazonWebServiceClient( final ClientConfiguration clientConfiguration, final RequestMetricCollector requestMetricCollector); protected AmazonWebServiceClient( final ClientConfiguration clientConfiguration, final HttpClient httpClient); @Deprecated protected AmazonWebServiceClient( final ClientConfiguration clientConfiguration, final HttpClient httpClient, final RequestMetricCollector requestMetricCollector); void setEndpoint(final String endpoint); String getEndpoint(); String getEndpointPrefix(); @Deprecated @SuppressWarnings("checkstyle:hiddenfield") void setEndpoint(final String endpoint, final String serviceName, final String regionId); @SuppressWarnings("checkstyle:hiddenfield") Signer getSignerByURI(final URI uri); @SuppressWarnings("checkstyle:hiddenfield") void setRegion(final Region region); @Deprecated @SuppressWarnings("checkstyle:hiddenfield") void setConfiguration(final ClientConfiguration clientConfiguration); void shutdown(); @Deprecated void addRequestHandler(final RequestHandler requestHandler); void addRequestHandler(final RequestHandler2 requestHandler2); @Deprecated void removeRequestHandler(final RequestHandler requestHandler); void removeRequestHandler(final RequestHandler2 requestHandler2); void setTimeOffset(final int timeOffset); @SuppressWarnings("checkstyle:hiddenfield") AmazonWebServiceClient withTimeOffset(final int timeOffset); int getTimeOffset(); @Deprecated RequestMetricCollector getRequestMetricsCollector(); String getServiceName(); @SuppressWarnings("checkstyle:hiddenfield") final void setServiceNameIntern(final String serviceName); final String getSignerRegionOverride(); @SuppressWarnings("checkstyle:hiddenfield") final void setSignerRegionOverride(final String signerRegionOverride); static final boolean LOGGING_AWS_REQUEST_METRIC; }### Answer: @Test public void testOverrideSigner() { final ClientConfiguration config = new ClientConfiguration(); config.setSignerOverride("QueryStringSignerType"); final AmazonTestClient client = new AmazonTestClient(config); Assert.assertTrue(client.getSigner() instanceof QueryStringSigner); }
### Question: ClientConnectionRequestFactory { static ClientConnectionRequest wrap(ClientConnectionRequest orig) { if (orig instanceof Wrapped) throw new IllegalArgumentException(); return (ClientConnectionRequest) Proxy.newProxyInstance( ClientConnectionRequestFactory.class.getClassLoader(), INTERFACES, new Handler(orig)); } }### Answer: @Test public void wrapOnce() { ClientConnectionRequest wrapped = ClientConnectionRequestFactory.wrap(noop); assertTrue(wrapped instanceof Wrapped); } @Test(expected = IllegalArgumentException.class) public void wrapTwice() { ClientConnectionRequest wrapped = ClientConnectionRequestFactory.wrap(noop); ClientConnectionRequestFactory.wrap(wrapped); }
### Question: ClientConnectionManagerFactory { public static ClientConnectionManager wrap(ClientConnectionManager orig) { if (orig instanceof Wrapped) throw new IllegalArgumentException(); final Class<?>[] interfaces = new Class<?>[] { ClientConnectionManager.class, Wrapped.class }; return (ClientConnectionManager) Proxy.newProxyInstance( ClientConnectionManagerFactory.class.getClassLoader(), interfaces, new Handler(orig)); } static ClientConnectionManager wrap(ClientConnectionManager orig); }### Answer: @Test public void wrapOnce() { ClientConnectionManager wrapped = ClientConnectionManagerFactory.wrap(noop); assertTrue(wrapped instanceof Wrapped); } @Test(expected = IllegalArgumentException.class) public void wrapTwice() { ClientConnectionManager wrapped = ClientConnectionManagerFactory.wrap(noop); ClientConnectionManagerFactory.wrap(wrapped); }
### Question: JsonUtils { public static String mapToString(Map<String, String> map) { if (map == null || map.isEmpty()) { return "{}"; } try { StringWriter out = new StringWriter(); AwsJsonWriter writer = getJsonWriter(out); writer.beginObject(); for (Map.Entry<String, String> entry : map.entrySet()) { writer.name(entry.getKey()).value(entry.getValue()); } writer.endObject(); writer.close(); return out.toString(); } catch (IOException e) { throw new AmazonClientException("Unable to serialize to JSON String.", e); } } static void setJsonEngine(JsonEngine jsonEngine); static AwsJsonReader getJsonReader(Reader in); static AwsJsonWriter getJsonWriter(Writer out); @SuppressWarnings("unchecked") static Map<String, String> jsonToMap(Reader in); @SuppressWarnings("unchecked") static Map<String, String> jsonToMap(String json); static String mapToString(Map<String, String> map); }### Answer: @Test public void testEmptyMapToJson() { Map<String, String> source = new HashMap<String, String>(); assertEquals("empty map", "{}", JsonUtils.mapToString(source)); }
### Question: JsonUtils { public static AwsJsonWriter getJsonWriter(Writer out) { if (factory == null) { throw new IllegalStateException("Json engine is unavailable."); } return factory.getJsonWriter(out); } static void setJsonEngine(JsonEngine jsonEngine); static AwsJsonReader getJsonReader(Reader in); static AwsJsonWriter getJsonWriter(Writer out); @SuppressWarnings("unchecked") static Map<String, String> jsonToMap(Reader in); @SuppressWarnings("unchecked") static Map<String, String> jsonToMap(String json); static String mapToString(Map<String, String> map); }### Answer: @Test public void testJsonWriter() throws IOException { StringWriter out = new StringWriter(); AwsJsonWriter writer = JsonUtils.getJsonWriter(out); writer.beginObject() .name("string").value("string") .name("long").value(123) .name("double").value(123.45) .name("null").value() .name("true").value(true) .name("false").value(false) .name("encoding").value("Chloë") .name("array").beginArray() .value("string").value(123).value(123.45).value().value(true).value(false) .endArray() .name("object").beginObject().endObject() .endObject().close(); String json = out.toString(); assertEquals("same json", JSON_STRING, json); }
### Question: PeriodicRateGenerator implements RateGenerator { @Override public double getRate(long time) { double valueInPeriod = normalizeValue(time); double result = rateFunction(valueInPeriod); LOGGER.trace("rateFunction returned: {} for value: {}", result, valueInPeriod); return result < 0 ? 0d : result; } PeriodicRateGenerator(long periodInSeconds); @Override double getRate(long time); }### Answer: @Test public void rate_should_return_1_when_period_is_100_and_time_is_201() { ConcretePeriodicRateGenerator periodicRateGenerator = new ConcretePeriodicRateGenerator(100); double rate = periodicRateGenerator.getRate(TimeUnit.SECONDS.toNanos(201)); Assert.assertEquals(1d, rate, DELTA); } @Test public void rate_should_return_0_when_period_is_50_and_time_is_150() { ConcretePeriodicRateGenerator periodicRateGenerator = new ConcretePeriodicRateGenerator(50); double rate = periodicRateGenerator.getRate(TimeUnit.SECONDS.toNanos(150)); Assert.assertEquals(0d, rate, DELTA); } @Test public void rate_should_return_60_when_period_is_10_and_time_is_16() { ConcretePeriodicRateGenerator periodicRateGenerator = new ConcretePeriodicRateGenerator(10); double rate = periodicRateGenerator.getRate(TimeUnit.SECONDS.toNanos(16)); Assert.assertEquals(60d, rate, DELTA); } @Test public void rate_should_return_99_when_period_is_100_and_time_is_399() { ConcretePeriodicRateGenerator periodicRateGenerator = new ConcretePeriodicRateGenerator(100); double rate = periodicRateGenerator.getRate(TimeUnit.SECONDS.toNanos(399)); Assert.assertEquals(99d, rate, DELTA); }
### Question: LoadGenerator { public void run() { try { checkState(); LOGGER.info("Load generator started."); long beginning = System.nanoTime(); long previous = beginning; infiniteWhile: while (true) { if (terminate.get()) { LOGGER.info("Termination signal detected. Terminating load generator..."); break; } long now = System.nanoTime(); long fromBeginning = now - beginning; long elapsed = now - previous; double rate = rateGenerator.getRate(fromBeginning); long normalizedRate = normalizeRate(elapsed, rate); if (normalizedRate > 0) { previous += calculateConsumedTime(normalizedRate, rate); } for (int i = 0; i < normalizedRate; i++) { if (!dataSource.hasNext(fromBeginning)) { LOGGER.info("Reached end of data source. Terminating load generator..."); terminate.set(true); break infiniteWhile; } T data = dataSource.getNext(fromBeginning); worker.accept(data); } } LOGGER.info("Load generator terminated."); } catch (Exception e) { LOGGER.error("Terminating load generator due to error. Error: ", e); } } LoadGenerator(DataSource<T> dataSource, RateGenerator rateGenerator, Consumer<T> worker); void run(); void terminate(); }### Answer: @Test(timeout = DEFAULT_TEST_TIMEOUT) public void loadGenerator_should_be_terminated_when_dataSource_has_no_next_element() { LoadGenerator<Integer> loadGenerator = new LoadGenerator<>(new DataSource<Integer>() { @Override public boolean hasNext(long time) { return false; } @Override public Integer getNext(long time) { return 123; } }, new ConstantRateGenerator(1000), (x) -> { }); loadGenerator.run(); }
### Question: LinkedEvictingBlockingQueue { public T take() throws InterruptedException { final ReentrantLock lock = this.lock; lock.lock(); try { T x; while ((x = unlinkFromHead()) == null) notEmpty.await(); return x; } finally { lock.unlock(); } } LinkedEvictingBlockingQueue(); LinkedEvictingBlockingQueue(boolean dropFromHead); LinkedEvictingBlockingQueue(boolean dropFromHead, int capacity); T put(T e); T take(); int size(); }### Answer: @Test(timeout = 2000) public void should_not_take_value_from_queue_when_value_is_not_put() throws InterruptedException { LinkedEvictingBlockingQueue<Integer> queue = new LinkedEvictingBlockingQueue<>(); Thread takeFromQueueThread = newStartedThread(() -> { try { queue.take(); } catch (InterruptedException e) { } }); Thread.sleep(1000); Assert.assertTrue(takeFromQueueThread.isAlive()); takeFromQueueThread.interrupt(); }
### Question: Balance { public Balance exchangeId(String exchangeId) { this.exchangeId = exchangeId; return this; } Balance exchangeId(String exchangeId); @javax.annotation.Nullable @ApiModelProperty(example = "KRAKEN", value = "Exchange identifier used to identify the routing destination.") String getExchangeId(); void setExchangeId(String exchangeId); Balance data(List<BalanceData> data); Balance addDataItem(BalanceData dataItem); @javax.annotation.Nullable @ApiModelProperty(value = "") List<BalanceData> getData(); void setData(List<BalanceData> data); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_EXCHANGE_ID; static final String SERIALIZED_NAME_DATA; }### Answer: @Test public void exchangeIdTest() { }
### Question: ValidationError { public ValidationError errors(String errors) { this.errors = errors; return this; } ValidationError type(String type); @javax.annotation.Nullable @ApiModelProperty(example = "https://tools.ietf.org/html/rfc7231#section-6.5.1", value = "") String getType(); void setType(String type); ValidationError title(String title); @javax.annotation.Nullable @ApiModelProperty(example = "One or more validation errors occurred.", value = "") String getTitle(); void setTitle(String title); ValidationError status(BigDecimal status); @javax.annotation.Nullable @ApiModelProperty(example = "400", value = "") BigDecimal getStatus(); void setStatus(BigDecimal status); ValidationError traceId(String traceId); @javax.annotation.Nullable @ApiModelProperty(example = "d200e8b5-4271a5461ce5342f", value = "") String getTraceId(); void setTraceId(String traceId); ValidationError errors(String errors); @javax.annotation.Nullable @ApiModelProperty(value = "") String getErrors(); void setErrors(String errors); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_TYPE; static final String SERIALIZED_NAME_TITLE; static final String SERIALIZED_NAME_STATUS; static final String SERIALIZED_NAME_TRACE_ID; static final String SERIALIZED_NAME_ERRORS; }### Answer: @Test public void errorsTest() { }
### Question: Balance { public Balance data(List<BalanceData> data) { this.data = data; return this; } Balance exchangeId(String exchangeId); @javax.annotation.Nullable @ApiModelProperty(example = "KRAKEN", value = "Exchange identifier used to identify the routing destination.") String getExchangeId(); void setExchangeId(String exchangeId); Balance data(List<BalanceData> data); Balance addDataItem(BalanceData dataItem); @javax.annotation.Nullable @ApiModelProperty(value = "") List<BalanceData> getData(); void setData(List<BalanceData> data); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_EXCHANGE_ID; static final String SERIALIZED_NAME_DATA; }### Answer: @Test public void dataTest() { }
### Question: OrderCancelAllRequest { public OrderCancelAllRequest exchangeId(String exchangeId) { this.exchangeId = exchangeId; return this; } OrderCancelAllRequest exchangeId(String exchangeId); @ApiModelProperty(example = "KRAKEN", required = true, value = "Identifier of the exchange from which active orders should be canceled.") String getExchangeId(); void setExchangeId(String exchangeId); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_EXCHANGE_ID; }### Answer: @Test public void exchangeIdTest() { }
### Question: Fills { public Fills time(LocalDate time) { this.time = time; return this; } Fills time(LocalDate time); @javax.annotation.Nullable @ApiModelProperty(example = "2020-01-01T10:45:20.1677709Z", value = "Execution time.") LocalDate getTime(); void setTime(LocalDate time); Fills price(BigDecimal price); @javax.annotation.Nullable @ApiModelProperty(example = "10799.2", value = "Execution price.") BigDecimal getPrice(); void setPrice(BigDecimal price); Fills amount(BigDecimal amount); @javax.annotation.Nullable @ApiModelProperty(example = "0.002", value = "Executed quantity.") BigDecimal getAmount(); void setAmount(BigDecimal amount); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_TIME; static final String SERIALIZED_NAME_PRICE; static final String SERIALIZED_NAME_AMOUNT; }### Answer: @Test public void timeTest() { }
### Question: Fills { public Fills price(BigDecimal price) { this.price = price; return this; } Fills time(LocalDate time); @javax.annotation.Nullable @ApiModelProperty(example = "2020-01-01T10:45:20.1677709Z", value = "Execution time.") LocalDate getTime(); void setTime(LocalDate time); Fills price(BigDecimal price); @javax.annotation.Nullable @ApiModelProperty(example = "10799.2", value = "Execution price.") BigDecimal getPrice(); void setPrice(BigDecimal price); Fills amount(BigDecimal amount); @javax.annotation.Nullable @ApiModelProperty(example = "0.002", value = "Executed quantity.") BigDecimal getAmount(); void setAmount(BigDecimal amount); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_TIME; static final String SERIALIZED_NAME_PRICE; static final String SERIALIZED_NAME_AMOUNT; }### Answer: @Test public void priceTest() { }
### Question: Fills { public Fills amount(BigDecimal amount) { this.amount = amount; return this; } Fills time(LocalDate time); @javax.annotation.Nullable @ApiModelProperty(example = "2020-01-01T10:45:20.1677709Z", value = "Execution time.") LocalDate getTime(); void setTime(LocalDate time); Fills price(BigDecimal price); @javax.annotation.Nullable @ApiModelProperty(example = "10799.2", value = "Execution price.") BigDecimal getPrice(); void setPrice(BigDecimal price); Fills amount(BigDecimal amount); @javax.annotation.Nullable @ApiModelProperty(example = "0.002", value = "Executed quantity.") BigDecimal getAmount(); void setAmount(BigDecimal amount); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_TIME; static final String SERIALIZED_NAME_PRICE; static final String SERIALIZED_NAME_AMOUNT; }### Answer: @Test public void amountTest() { }
### Question: OrderCancelSingleRequest { public OrderCancelSingleRequest exchangeId(String exchangeId) { this.exchangeId = exchangeId; return this; } OrderCancelSingleRequest exchangeId(String exchangeId); @ApiModelProperty(example = "KRAKEN", required = true, value = "Exchange identifier used to identify the routing destination.") String getExchangeId(); void setExchangeId(String exchangeId); OrderCancelSingleRequest exchangeOrderId(String exchangeOrderId); @javax.annotation.Nullable @ApiModelProperty(example = "3456456754", value = "Unique identifier of the order assigned by the exchange or executing system. One of the properties (`exchange_order_id`, `client_order_id`) is required to identify the new order.") String getExchangeOrderId(); void setExchangeOrderId(String exchangeOrderId); OrderCancelSingleRequest clientOrderId(String clientOrderId); @javax.annotation.Nullable @ApiModelProperty(example = "6ab36bc1-344d-432e-ac6d-0bf44ee64c2b", value = "The unique identifier of the order assigned by the client. One of the properties (`exchange_order_id`, `client_order_id`) is required to identify the new order.") String getClientOrderId(); void setClientOrderId(String clientOrderId); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_EXCHANGE_ID; static final String SERIALIZED_NAME_EXCHANGE_ORDER_ID; static final String SERIALIZED_NAME_CLIENT_ORDER_ID; }### Answer: @Test public void exchangeIdTest() { }
### Question: OrderCancelSingleRequest { public OrderCancelSingleRequest exchangeOrderId(String exchangeOrderId) { this.exchangeOrderId = exchangeOrderId; return this; } OrderCancelSingleRequest exchangeId(String exchangeId); @ApiModelProperty(example = "KRAKEN", required = true, value = "Exchange identifier used to identify the routing destination.") String getExchangeId(); void setExchangeId(String exchangeId); OrderCancelSingleRequest exchangeOrderId(String exchangeOrderId); @javax.annotation.Nullable @ApiModelProperty(example = "3456456754", value = "Unique identifier of the order assigned by the exchange or executing system. One of the properties (`exchange_order_id`, `client_order_id`) is required to identify the new order.") String getExchangeOrderId(); void setExchangeOrderId(String exchangeOrderId); OrderCancelSingleRequest clientOrderId(String clientOrderId); @javax.annotation.Nullable @ApiModelProperty(example = "6ab36bc1-344d-432e-ac6d-0bf44ee64c2b", value = "The unique identifier of the order assigned by the client. One of the properties (`exchange_order_id`, `client_order_id`) is required to identify the new order.") String getClientOrderId(); void setClientOrderId(String clientOrderId); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_EXCHANGE_ID; static final String SERIALIZED_NAME_EXCHANGE_ORDER_ID; static final String SERIALIZED_NAME_CLIENT_ORDER_ID; }### Answer: @Test public void exchangeOrderIdTest() { }
### Question: OrderCancelSingleRequest { public OrderCancelSingleRequest clientOrderId(String clientOrderId) { this.clientOrderId = clientOrderId; return this; } OrderCancelSingleRequest exchangeId(String exchangeId); @ApiModelProperty(example = "KRAKEN", required = true, value = "Exchange identifier used to identify the routing destination.") String getExchangeId(); void setExchangeId(String exchangeId); OrderCancelSingleRequest exchangeOrderId(String exchangeOrderId); @javax.annotation.Nullable @ApiModelProperty(example = "3456456754", value = "Unique identifier of the order assigned by the exchange or executing system. One of the properties (`exchange_order_id`, `client_order_id`) is required to identify the new order.") String getExchangeOrderId(); void setExchangeOrderId(String exchangeOrderId); OrderCancelSingleRequest clientOrderId(String clientOrderId); @javax.annotation.Nullable @ApiModelProperty(example = "6ab36bc1-344d-432e-ac6d-0bf44ee64c2b", value = "The unique identifier of the order assigned by the client. One of the properties (`exchange_order_id`, `client_order_id`) is required to identify the new order.") String getClientOrderId(); void setClientOrderId(String clientOrderId); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_EXCHANGE_ID; static final String SERIALIZED_NAME_EXCHANGE_ORDER_ID; static final String SERIALIZED_NAME_CLIENT_ORDER_ID; }### Answer: @Test public void clientOrderIdTest() { }
### Question: Message { public Message message(String message) { this.message = message; return this; } Message type(String type); @javax.annotation.Nullable @ApiModelProperty(example = "message", value = "Type of message.") String getType(); void setType(String type); Message severity(Severity severity); @javax.annotation.Nullable @ApiModelProperty(value = "") Severity getSeverity(); void setSeverity(Severity severity); Message exchangeId(String exchangeId); @javax.annotation.Nullable @ApiModelProperty(example = "KRAKEN", value = "If the message related to exchange, then the identifier of the exchange will be provided.") String getExchangeId(); void setExchangeId(String exchangeId); Message message(String message); @javax.annotation.Nullable @ApiModelProperty(example = "Ok", value = "Message text.") String getMessage(); void setMessage(String message); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_TYPE; static final String SERIALIZED_NAME_SEVERITY; static final String SERIALIZED_NAME_EXCHANGE_ID; static final String SERIALIZED_NAME_MESSAGE; }### Answer: @Test public void testMessage() { } @Test public void messageTest() { }
### Question: Message { public Message type(String type) { this.type = type; return this; } Message type(String type); @javax.annotation.Nullable @ApiModelProperty(example = "message", value = "Type of message.") String getType(); void setType(String type); Message severity(Severity severity); @javax.annotation.Nullable @ApiModelProperty(value = "") Severity getSeverity(); void setSeverity(Severity severity); Message exchangeId(String exchangeId); @javax.annotation.Nullable @ApiModelProperty(example = "KRAKEN", value = "If the message related to exchange, then the identifier of the exchange will be provided.") String getExchangeId(); void setExchangeId(String exchangeId); Message message(String message); @javax.annotation.Nullable @ApiModelProperty(example = "Ok", value = "Message text.") String getMessage(); void setMessage(String message); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_TYPE; static final String SERIALIZED_NAME_SEVERITY; static final String SERIALIZED_NAME_EXCHANGE_ID; static final String SERIALIZED_NAME_MESSAGE; }### Answer: @Test public void typeTest() { }
### Question: Message { public Message severity(Severity severity) { this.severity = severity; return this; } Message type(String type); @javax.annotation.Nullable @ApiModelProperty(example = "message", value = "Type of message.") String getType(); void setType(String type); Message severity(Severity severity); @javax.annotation.Nullable @ApiModelProperty(value = "") Severity getSeverity(); void setSeverity(Severity severity); Message exchangeId(String exchangeId); @javax.annotation.Nullable @ApiModelProperty(example = "KRAKEN", value = "If the message related to exchange, then the identifier of the exchange will be provided.") String getExchangeId(); void setExchangeId(String exchangeId); Message message(String message); @javax.annotation.Nullable @ApiModelProperty(example = "Ok", value = "Message text.") String getMessage(); void setMessage(String message); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_TYPE; static final String SERIALIZED_NAME_SEVERITY; static final String SERIALIZED_NAME_EXCHANGE_ID; static final String SERIALIZED_NAME_MESSAGE; }### Answer: @Test public void severityTest() { }
### Question: Message { public Message exchangeId(String exchangeId) { this.exchangeId = exchangeId; return this; } Message type(String type); @javax.annotation.Nullable @ApiModelProperty(example = "message", value = "Type of message.") String getType(); void setType(String type); Message severity(Severity severity); @javax.annotation.Nullable @ApiModelProperty(value = "") Severity getSeverity(); void setSeverity(Severity severity); Message exchangeId(String exchangeId); @javax.annotation.Nullable @ApiModelProperty(example = "KRAKEN", value = "If the message related to exchange, then the identifier of the exchange will be provided.") String getExchangeId(); void setExchangeId(String exchangeId); Message message(String message); @javax.annotation.Nullable @ApiModelProperty(example = "Ok", value = "Message text.") String getMessage(); void setMessage(String message); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_TYPE; static final String SERIALIZED_NAME_SEVERITY; static final String SERIALIZED_NAME_EXCHANGE_ID; static final String SERIALIZED_NAME_MESSAGE; }### Answer: @Test public void exchangeIdTest() { }
### Question: ValidationError { public ValidationError type(String type) { this.type = type; return this; } ValidationError type(String type); @javax.annotation.Nullable @ApiModelProperty(example = "https://tools.ietf.org/html/rfc7231#section-6.5.1", value = "") String getType(); void setType(String type); ValidationError title(String title); @javax.annotation.Nullable @ApiModelProperty(example = "One or more validation errors occurred.", value = "") String getTitle(); void setTitle(String title); ValidationError status(BigDecimal status); @javax.annotation.Nullable @ApiModelProperty(example = "400", value = "") BigDecimal getStatus(); void setStatus(BigDecimal status); ValidationError traceId(String traceId); @javax.annotation.Nullable @ApiModelProperty(example = "d200e8b5-4271a5461ce5342f", value = "") String getTraceId(); void setTraceId(String traceId); ValidationError errors(String errors); @javax.annotation.Nullable @ApiModelProperty(value = "") String getErrors(); void setErrors(String errors); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_TYPE; static final String SERIALIZED_NAME_TITLE; static final String SERIALIZED_NAME_STATUS; static final String SERIALIZED_NAME_TRACE_ID; static final String SERIALIZED_NAME_ERRORS; }### Answer: @Test public void typeTest() { }
### Question: Position { public Position exchangeId(String exchangeId) { this.exchangeId = exchangeId; return this; } Position exchangeId(String exchangeId); @javax.annotation.Nullable @ApiModelProperty(example = "KRAKEN", value = "Exchange identifier used to identify the routing destination.") String getExchangeId(); void setExchangeId(String exchangeId); Position data(List<PositionData> data); Position addDataItem(PositionData dataItem); @javax.annotation.Nullable @ApiModelProperty(value = "") List<PositionData> getData(); void setData(List<PositionData> data); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_EXCHANGE_ID; static final String SERIALIZED_NAME_DATA; }### Answer: @Test public void exchangeIdTest() { }
### Question: Position { public Position data(List<PositionData> data) { this.data = data; return this; } Position exchangeId(String exchangeId); @javax.annotation.Nullable @ApiModelProperty(example = "KRAKEN", value = "Exchange identifier used to identify the routing destination.") String getExchangeId(); void setExchangeId(String exchangeId); Position data(List<PositionData> data); Position addDataItem(PositionData dataItem); @javax.annotation.Nullable @ApiModelProperty(value = "") List<PositionData> getData(); void setData(List<PositionData> data); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_EXCHANGE_ID; static final String SERIALIZED_NAME_DATA; }### Answer: @Test public void dataTest() { }
### Question: ValidationError { public ValidationError title(String title) { this.title = title; return this; } ValidationError type(String type); @javax.annotation.Nullable @ApiModelProperty(example = "https://tools.ietf.org/html/rfc7231#section-6.5.1", value = "") String getType(); void setType(String type); ValidationError title(String title); @javax.annotation.Nullable @ApiModelProperty(example = "One or more validation errors occurred.", value = "") String getTitle(); void setTitle(String title); ValidationError status(BigDecimal status); @javax.annotation.Nullable @ApiModelProperty(example = "400", value = "") BigDecimal getStatus(); void setStatus(BigDecimal status); ValidationError traceId(String traceId); @javax.annotation.Nullable @ApiModelProperty(example = "d200e8b5-4271a5461ce5342f", value = "") String getTraceId(); void setTraceId(String traceId); ValidationError errors(String errors); @javax.annotation.Nullable @ApiModelProperty(value = "") String getErrors(); void setErrors(String errors); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_TYPE; static final String SERIALIZED_NAME_TITLE; static final String SERIALIZED_NAME_STATUS; static final String SERIALIZED_NAME_TRACE_ID; static final String SERIALIZED_NAME_ERRORS; }### Answer: @Test public void titleTest() { }
### Question: BalancesApi { public List<Balance> v1BalancesGet(String exchangeId) throws ApiException { ApiResponse<List<Balance>> localVarResp = v1BalancesGetWithHttpInfo(exchangeId); return localVarResp.getData(); } BalancesApi(); BalancesApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); okhttp3.Call v1BalancesGetCall(String exchangeId, final ApiCallback _callback); List<Balance> v1BalancesGet(String exchangeId); ApiResponse<List<Balance>> v1BalancesGetWithHttpInfo(String exchangeId); okhttp3.Call v1BalancesGetAsync(String exchangeId, final ApiCallback<List<Balance>> _callback); }### Answer: @Test public void v1BalancesGetTest() throws ApiException { String exchangeId = null; List<Balance> response = api.v1BalancesGet(exchangeId); }
### Question: PositionsApi { public List<Position> v1PositionsGet(String exchangeId) throws ApiException { ApiResponse<List<Position>> localVarResp = v1PositionsGetWithHttpInfo(exchangeId); return localVarResp.getData(); } PositionsApi(); PositionsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); okhttp3.Call v1PositionsGetCall(String exchangeId, final ApiCallback _callback); List<Position> v1PositionsGet(String exchangeId); ApiResponse<List<Position>> v1PositionsGetWithHttpInfo(String exchangeId); okhttp3.Call v1PositionsGetAsync(String exchangeId, final ApiCallback<List<Position>> _callback); }### Answer: @Test public void v1PositionsGetTest() throws ApiException { String exchangeId = null; List<Position> response = api.v1PositionsGet(exchangeId); }
### Question: ValidationError { public ValidationError status(BigDecimal status) { this.status = status; return this; } ValidationError type(String type); @javax.annotation.Nullable @ApiModelProperty(example = "https://tools.ietf.org/html/rfc7231#section-6.5.1", value = "") String getType(); void setType(String type); ValidationError title(String title); @javax.annotation.Nullable @ApiModelProperty(example = "One or more validation errors occurred.", value = "") String getTitle(); void setTitle(String title); ValidationError status(BigDecimal status); @javax.annotation.Nullable @ApiModelProperty(example = "400", value = "") BigDecimal getStatus(); void setStatus(BigDecimal status); ValidationError traceId(String traceId); @javax.annotation.Nullable @ApiModelProperty(example = "d200e8b5-4271a5461ce5342f", value = "") String getTraceId(); void setTraceId(String traceId); ValidationError errors(String errors); @javax.annotation.Nullable @ApiModelProperty(value = "") String getErrors(); void setErrors(String errors); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_TYPE; static final String SERIALIZED_NAME_TITLE; static final String SERIALIZED_NAME_STATUS; static final String SERIALIZED_NAME_TRACE_ID; static final String SERIALIZED_NAME_ERRORS; }### Answer: @Test public void statusTest() { }