method2testcases
stringlengths 118
6.63k
|
---|
### Question:
SpringModelAdjuster implements ModelAdjuster { @Override public @Nullable Object adjust(@Nullable final Object obj) { if (obj instanceof Model) { final Model model = (Model) obj; return model.asMap().get("model"); } if (obj instanceof Map) { final Map map = (Map) obj; return map.get("model"); } return obj; } @Override @Nullable Object adjust(@Nullable final Object obj); void setModelKey(final String modelKey); String getModelKey(); }### Answer:
@Test public void adjustMap() throws Exception { final Object modelObject = new Object(); final Map<String,Object> map = new HashMap(); map.put("model", modelObject); Assert.assertEquals("should return modelObject", modelObject, springModelAdjuster.adjust(map)); }
@Test public void adjustMapFail() throws Exception { final Object modelObject = new Object(); final Map<String,Object> map = new HashMap(); map.put("model2", modelObject); Assert.assertNull("should return null", springModelAdjuster.adjust(map)); }
@Test public void adjustSpringModel() throws Exception { final Object modelObject = new Object(); final Model model = new ExtendedModelMap(); model.addAttribute("model", modelObject); Assert.assertEquals("should return modelObject", modelObject, springModelAdjuster.adjust(model)); }
@Test public void adjustPassThrough() throws Exception { final Object modelObject = new Object(); Assert.assertEquals("should return modelObject", modelObject, springModelAdjuster.adjust(modelObject)); } |
### Question:
DefaultToSoyDataConverter implements ToSoyDataConverter { @Override public Optional<SoyMapData> toSoyMap(final Object model) throws Exception { if (model == null) { return Optional.absent(); } return Optional.fromNullable(objectToSoyDataMap(model)); } DefaultToSoyDataConverter(); void setIgnorablePropertiesMatcher(
Matcher<PropertyDescriptor> ignorablePropertiesMatcher); @Override Optional<SoyMapData> toSoyMap(final Object model); }### Answer:
@Test public void testToSoyMapWhenNoModel() throws Exception { Optional<SoyMapData> soyData = objectToSoyDataConverter.toSoyMap(null); assertFalse(soyData.isPresent()); }
@Test public void testToSoyMapWhenModelIsPresent() throws Exception { Map<String, String> model = new HashMap<String, String>(); model.put(key, keyValue); Optional<SoyMapData> soyData = objectToSoyDataConverter.toSoyMap(model); assertTrue(soyData.isPresent()); SoyMapData data = soyData.get(); assertEquals(keyValue, data.get(key).stringValue()); } |
### Question:
SoyAjaxController { private ResponseEntity<String> compileJs(final String[] templateFileNames, final String hash, final boolean disableProcessors, final HttpServletRequest request, final String locale ) throws IOException { Preconditions.checkNotNull(templateFilesResolver, "templateFilesResolver cannot be null"); if (isHotReloadModeOff()) { final Optional<String> template = extractAndCombineAll(hash, templateFileNames); if (template.isPresent()) { return prepareResponseFor(template.get(), disableProcessors); } } try { final Map<URL,String> compiledTemplates = compileTemplates(templateFileNames, request, locale); final Optional<String> allCompiledTemplates = concatCompiledTemplates(compiledTemplates); if (!allCompiledTemplates.isPresent()) { throw notFound("Template file(s) could not be resolved."); } if (isHotReloadModeOff()) { synchronized (cachedJsTemplates) { Map<String, String> map = cachedJsTemplates.getIfPresent(hash); if (map == null) { map = new ConcurrentHashMap<String, String>(); } else { map.put(PathUtils.arrayToPath(templateFileNames), allCompiledTemplates.get()); } this.cachedJsTemplates.put(hash, map); } } return prepareResponseFor(allCompiledTemplates.get(), disableProcessors); } catch (final SecurityException ex) { return new ResponseEntity<String>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (final HttpClientErrorException ex) { return new ResponseEntity<String>(ex.getMessage(), ex.getStatusCode()); } } SoyAjaxController(); @PostConstruct void init(); @RequestMapping(value="/soy/compileJs", method=GET) ResponseEntity<String> compile(@RequestParam(required = false, value="hash", defaultValue = "") final String hash,
@RequestParam(required = true, value = "file") final String[] templateFileNames,
@RequestParam(required = false, value = "locale") String locale,
@RequestParam(required = false, value = "disableProcessors", defaultValue = "false") String disableProcessors,
final HttpServletRequest request); void setCacheControl(final String cacheControl); void setTemplateFilesResolver(final TemplateFilesResolver templateFilesResolver); void setTofuCompiler(final TofuCompiler tofuCompiler); void setSoyMsgBundleResolver(final SoyMsgBundleResolver soyMsgBundleResolver); void setLocaleProvider(final LocaleProvider localeProvider); void setHotReloadMode(final boolean hotReloadMode); void setEncoding(final String encoding); void setExpiresHeaders(final String expiresHeaders); void setOutputProcessors(List<OutputProcessor> outputProcessors); void setAuthManager(AuthManager authManager); void setCacheMaxSize(int cacheMaxSize); void setExpireAfterWrite(int expireAfterWrite); void setExpireAfterWriteUnit(String expireAfterWriteUnit); }### Answer:
@Test public void testCompileJs() throws Exception { final String templateName = "templates/template1.soy"; final String jsData = "jsData"; final HttpServletRequest request = mock(HttpServletRequest.class); when(localeProvider.resolveLocale(request)).thenReturn(Optional.<Locale>absent()); when(soyMsgBundleResolver.resolve(any(Optional.class))).thenReturn(Optional.<SoyMsgBundle>absent()); final URL url1 = getClass().getClassLoader().getResource(templateName); when(templateFilesResolver.resolve(templateName)).thenReturn(Optional.of(url1)); when(tofuCompiler.compileToJsSrc(url1, null)).thenReturn(Optional.of(jsData)); final ResponseEntity<String> responseEntity = soyAjaxController.compile("", new String[]{templateName}, null, "true", request); Assert.assertEquals("data should be equal", jsData, responseEntity.getBody()); Assert.assertTrue("http status should be equal", (responseEntity.getStatusCode() == HttpStatus.OK)); } |
### Question:
DefaultToSoyDataConverter implements ToSoyDataConverter { @SuppressWarnings("unchecked") protected Map<String, ?> toSoyCompatibleMap(final Object obj) throws Exception { Object ret = toSoyCompatibleObjects(obj); if (!(ret instanceof Map)) { throw new IllegalArgumentException("Input should be a Map or POJO."); } return (Map<String, ?>) ret; } DefaultToSoyDataConverter(); void setIgnorablePropertiesMatcher(
Matcher<PropertyDescriptor> ignorablePropertiesMatcher); @Override Optional<SoyMapData> toSoyMap(final Object model); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testToSoyCompatibleMapWhenNotMap() throws Exception { String test = "won't work"; objectToSoyDataConverter.toSoyCompatibleMap(test); } |
### Question:
DefaultToSoyDataConverter implements ToSoyDataConverter { protected Object toSoyCompatibleObjects(Object obj) throws Exception { if (obj == null) { return obj; } if (Primitives.isWrapperType(obj.getClass()) || obj instanceof String) { return obj; } if(obj.getClass().isEnum()) { return ((Enum)obj).name(); } if (obj instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) obj; Map<String, Object> newMap = new HashMap<String, Object>(map.size()); for (String key : map.keySet()) { newMap.put(key, toSoyCompatibleObjects(map.get(key))); } return newMap; } if (obj instanceof Iterable<?>) { List<Object> list = Lists.newArrayList(); for (Object subValue : ((Iterable<?>) obj)) { list.add(toSoyCompatibleObjects(subValue)); } return list; } if (obj instanceof Callable) { final Callable<?> callable = (Callable<?>) obj; return toSoyCompatibleObjects(callable.call()); } if (obj.getClass().isArray()) { return obj; } @SuppressWarnings("unchecked") Map<String, Object> pojoMap = (Map<String, Object>) pojoToMap(obj); Map<String, Object> newMap = new HashMap<String, Object>(pojoMap.size()); for (String key : pojoMap.keySet()) { newMap.put(key, toSoyCompatibleObjects(pojoMap.get(key))); } return newMap; } DefaultToSoyDataConverter(); void setIgnorablePropertiesMatcher(
Matcher<PropertyDescriptor> ignorablePropertiesMatcher); @Override Optional<SoyMapData> toSoyMap(final Object model); }### Answer:
@Test public void testToSoyCompatibleObjectsWhenObjectIsNull() throws Exception { Object testObject = objectToSoyDataConverter .toSoyCompatibleObjects(null); assertNull(testObject); }
@Test public void testToSoyCompatibleObjectsWhenObjectIsString() throws Exception { String testInput = "test"; Object testObject = objectToSoyDataConverter .toSoyCompatibleObjects(testInput); assertEquals("test", testObject.toString()); }
@Test public void testToSoyCompatibleObjectsWhenObjectIsEnum() throws Exception { MyEnum testInput = MyEnum.A; Object testObject = objectToSoyDataConverter .toSoyCompatibleObjects(testInput); assertEquals("A", testObject.toString()); }
@Test public void testToSoyCompatibleObjectsWhenObjectIsWrapperType() throws Exception { Integer testInput = 42; Object testObject = objectToSoyDataConverter .toSoyCompatibleObjects(testInput); assertTrue(testObject instanceof Integer); assertEquals(testInput, (Integer) testObject); }
@Test public void testToSoyCompatibleObjectsWhenObjectIsIterable() throws Exception { List<String> testInput = new ArrayList<String>(); testInput.add("test"); Object testObject = objectToSoyDataConverter .toSoyCompatibleObjects(testInput); assertTrue(testObject instanceof Iterable<?>); @SuppressWarnings("unchecked") List<String> actual = (List<String>) testObject; assertEquals(1, actual.size()); assertEquals("test", actual.get(0)); }
@Test public void testToSoyCompatibleObjectsWhenObjectIsArray() throws Exception { String[] testInput = new String[] { "test" }; Object testObject = objectToSoyDataConverter .toSoyCompatibleObjects(testInput); assertTrue(testObject.getClass().isArray()); String[] actual = (String[]) testObject; assertEquals(1, actual.length); assertEquals("test", actual[0]); }
@SuppressWarnings("unchecked") @Test public void testToSoyCompatibleObjectsWhenObjectIsPojo() throws Exception { PojoTest testInput = new PojoTest(); Object testObject = objectToSoyDataConverter .toSoyCompatibleObjects(testInput); assertTrue(testObject instanceof Map); assertEquals("test", ((Map<String, String>) testObject).get("name")); }
@Test public void testObjectToSoyDataMapWhenObjectIsCallable() throws Exception { Callable<String> testInput = new Callable<String>() { @Override public String call() throws Exception { return "test"; } }; Object testObject = objectToSoyDataConverter .toSoyCompatibleObjects(testInput); assertEquals("test", testObject.toString()); } |
### Question:
DefaultToSoyDataConverter implements ToSoyDataConverter { protected SoyMapData objectToSoyDataMap(Object obj) throws Exception { if (obj == null) { return new SoyMapData(); } if (obj instanceof SoyMapData) { return (SoyMapData) obj; } return new SoyMapData(toSoyCompatibleMap(obj)); } DefaultToSoyDataConverter(); void setIgnorablePropertiesMatcher(
Matcher<PropertyDescriptor> ignorablePropertiesMatcher); @Override Optional<SoyMapData> toSoyMap(final Object model); }### Answer:
@Test public void testObjectToSoyDataMapWhenObjectIsNull() throws Exception { SoyMapData testObject = objectToSoyDataConverter .objectToSoyDataMap(null); assertTrue(testObject instanceof SoyMapData); }
@Test public void testObjectToSoyDataMapWhenObjectIsSoyMapData() throws Exception { SoyMapData testInput = new SoyMapData(); testInput.putSingle(key, SoyData.createFromExistingData(keyValue)); SoyMapData testObject = objectToSoyDataConverter .objectToSoyDataMap(testInput); assertTrue(testObject instanceof SoyMapData); assertEquals(keyValue, ((SoyMapData) testObject).get(key).stringValue()); }
@Test public void testObjectToSoyDataMapWhenObjectIsMap() throws Exception { Map<String, String> testInput = new HashMap<String, String>(); testInput.put(key, keyValue); SoyMapData testObject = objectToSoyDataConverter .objectToSoyDataMap(testInput); assertTrue(testObject instanceof SoyMapData); assertEquals(keyValue, ((SoyMapData) testObject).get(key).stringValue()); } |
### Question:
SoyAjaxController { @RequestMapping(value="/soy/compileJs", method=GET) public ResponseEntity<String> compile(@RequestParam(required = false, value="hash", defaultValue = "") final String hash, @RequestParam(required = true, value = "file") final String[] templateFileNames, @RequestParam(required = false, value = "locale") String locale, @RequestParam(required = false, value = "disableProcessors", defaultValue = "false") String disableProcessors, final HttpServletRequest request) throws IOException { return compileJs(templateFileNames, hash, new Boolean(disableProcessors).booleanValue(), request, locale); } SoyAjaxController(); @PostConstruct void init(); @RequestMapping(value="/soy/compileJs", method=GET) ResponseEntity<String> compile(@RequestParam(required = false, value="hash", defaultValue = "") final String hash,
@RequestParam(required = true, value = "file") final String[] templateFileNames,
@RequestParam(required = false, value = "locale") String locale,
@RequestParam(required = false, value = "disableProcessors", defaultValue = "false") String disableProcessors,
final HttpServletRequest request); void setCacheControl(final String cacheControl); void setTemplateFilesResolver(final TemplateFilesResolver templateFilesResolver); void setTofuCompiler(final TofuCompiler tofuCompiler); void setSoyMsgBundleResolver(final SoyMsgBundleResolver soyMsgBundleResolver); void setLocaleProvider(final LocaleProvider localeProvider); void setHotReloadMode(final boolean hotReloadMode); void setEncoding(final String encoding); void setExpiresHeaders(final String expiresHeaders); void setOutputProcessors(List<OutputProcessor> outputProcessors); void setAuthManager(AuthManager authManager); void setCacheMaxSize(int cacheMaxSize); void setExpireAfterWrite(int expireAfterWrite); void setExpireAfterWriteUnit(String expireAfterWriteUnit); }### Answer:
@Test @Ignore public void testCompileJs2() throws Exception { final String templateName1 = "templates/template1.soy"; final String templateName2 = "templates/template2.soy"; final String jsData1 = "jsData1"; final String jsData2 = "jsData2"; final HttpServletRequest request = mock(HttpServletRequest.class); when(localeProvider.resolveLocale(request)).thenReturn(Optional.<Locale>absent()); when(soyMsgBundleResolver.resolve(any(Optional.class))).thenReturn(Optional.<SoyMsgBundle>absent()); final URL url1 = getClass().getClassLoader().getResource(templateName1); final URL url2 = getClass().getClassLoader().getResource(templateName2); when(templateFilesResolver.resolve(templateName1)).thenReturn(Optional.of(url1)); when(templateFilesResolver.resolve(templateName2)).thenReturn(Optional.of(url2)); when(tofuCompiler.compileToJsSrc(url1, null)).thenReturn(Optional.of(jsData1)); when(tofuCompiler.compileToJsSrc(url2, null)).thenReturn(Optional.of(jsData2)); final ResponseEntity<String> responseEntity = soyAjaxController.compile("", new String[]{templateName1, templateName2}, null, "true", request); Assert.assertEquals("data should be equal", jsData1 + jsData2, responseEntity.getBody()); Assert.assertTrue("http status should be equal", (responseEntity.getStatusCode() == HttpStatus.OK)); } |
### Question:
EmptyLocaleProvider implements LocaleProvider { @Override public Optional<Locale> resolveLocale(final HttpServletRequest request) { return Optional.absent(); } @Override Optional<Locale> resolveLocale(final HttpServletRequest request); }### Answer:
@Test public void testShouldNotReturnNull() throws Exception { Assert.assertNotNull(emptyLocaleProvider.resolveLocale(null)); }
@Test public void testDefaultAbsent() throws Exception { Assert.assertFalse("locale should be absent", emptyLocaleProvider.resolveLocale(null).isPresent()); } |
### Question:
DefaultLocaleProvider implements LocaleProvider { @Override public Optional<Locale> resolveLocale(final HttpServletRequest request) { return Optional.fromNullable(locale); } DefaultLocaleProvider(Locale locale); DefaultLocaleProvider(); @Override Optional<Locale> resolveLocale(final HttpServletRequest request); void setLocale(final Locale locale); }### Answer:
@Test public void testShouldNotReturnNull() throws Exception { Assert.assertTrue("should return value", defaultLocaleProvider.resolveLocale(null).isPresent()); }
@Test public void shouldReturnUsDefault() throws Exception { Assert.assertEquals("should return absent", Locale.US, defaultLocaleProvider.resolveLocale(request).get()); } |
### Question:
AcceptHeaderLocaleProvider implements LocaleProvider { public Optional<Locale> resolveLocale(final HttpServletRequest request) { return Optional.fromNullable(request.getLocale()); } Optional<Locale> resolveLocale(final HttpServletRequest request); }### Answer:
@Test public void shouldThrowNPE() throws Exception { try { acceptHeaderLocaleProvider.resolveLocale(null); fail("npe should be thrown"); } catch (Exception ex) { } }
@Test public void shouldReturnLocale() throws Exception { when(request.getLocale()).thenReturn(Locale.GERMAN); final Optional<Locale> localeOptional = acceptHeaderLocaleProvider.resolveLocale(request); Assert.assertTrue("locale should be present", localeOptional.isPresent()); Assert.assertEquals("locale should be German", Locale.GERMAN, localeOptional.get()); } |
### Question:
DefaultTemplateRenderer implements TemplateRenderer { public boolean isHotReloadMode() { return hotReloadMode; } @Override void render(final RenderRequest renderRequest); void setToSoyDataConverter(final ToSoyDataConverter toSoyDataConverter); void setHotReloadMode(boolean hotReloadMode); boolean isHotReloadMode(); boolean isHotReloadModeOff(); }### Answer:
@Test public void testDefaultDebug() throws Exception { Assert.assertFalse("debug is off by default", defaultTemplateRenderer.isHotReloadMode()); } |
### Question:
ConfigurableAuthManager implements AuthManager { @Override public boolean isAllowed(final String url) { return allowedTemplates.contains(url); } ConfigurableAuthManager(List<String> allowedTemplates); ConfigurableAuthManager(); void setAllowedTemplates(final List<String> allowedTemplates); @Override boolean isAllowed(final String url); }### Answer:
@Test public void testDefault() throws Exception { Assert.assertFalse("should not allow by default", configurableAuthManager.isAllowed("template")); } |
### Question:
DefaultTemplateRenderer implements TemplateRenderer { @Override public void render(final RenderRequest renderRequest) throws Exception { if (!renderRequest.getCompiledTemplates().isPresent()) { logger.warn("compiled templates are not present, nothing to render!"); return; } final SoyTofu compiledTemplates = renderRequest.getCompiledTemplates().get(); final String templateName = renderRequest.getTemplateName(); final SoyTofu.Renderer renderer = compiledTemplates.newRenderer(templateName); final Optional<SoyMapData> soyModel = toSoyDataConverter.toSoyMap(renderRequest.getModel()); setupRenderer(renderer, renderRequest, soyModel); writeResponse(renderer, renderRequest); } @Override void render(final RenderRequest renderRequest); void setToSoyDataConverter(final ToSoyDataConverter toSoyDataConverter); void setHotReloadMode(boolean hotReloadMode); boolean isHotReloadMode(); boolean isHotReloadModeOff(); }### Answer:
@Test public void testThrowsNPE() throws Exception { try { defaultTemplateRenderer.render(null); fail("should throw NPE"); } catch (NullPointerException ex) { } }
@Test public void testDontRenderWithoutCompiledTemplates() throws Exception { final RenderRequest renderRequest = mock(RenderRequest.class); final HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); when(renderRequest.getCompiledTemplates()).thenReturn(Optional.<SoyTofu>absent()); when(renderRequest.getResponse()).thenReturn(httpServletResponse); defaultTemplateRenderer.render(renderRequest); Mockito.verifyZeroInteractions(httpServletResponse); }
@Test public void testRenderWithoutAnyDataWithoutDebug() throws Exception { final Object domainMock = new Object(); final RenderRequest renderRequest = mock(RenderRequest.class); final SoyTofu soyTofu = mock(SoyTofu.class); final PrintWriter printWriter = mock(PrintWriter.class); final HttpServletResponse response = mock(HttpServletResponse.class); final HttpServletRequest request = mock(HttpServletRequest.class); final String templateName = "soy.example.clientWords"; final SoyTofu.Renderer renderer = mock(SoyTofu.Renderer.class); final SoyMapData modelData = new SoyMapData(); final SoyView soyView = mock(SoyView.class); when(renderRequest.getCompiledTemplates()).thenReturn(Optional.of(soyTofu)); when(toSoyDataConverter.toSoyMap(domainMock)).thenReturn(Optional.<SoyMapData>absent()); when(renderRequest.getModel()).thenReturn(domainMock); when(renderRequest.getRequest()).thenReturn(request); when(renderRequest.getResponse()).thenReturn(response); when(renderRequest.getTemplateName()).thenReturn(templateName); when(soyTofu.newRenderer(templateName)).thenReturn(renderer); when(renderRequest.getGlobalRuntimeModel()).thenReturn(Optional.<SoyMapData>absent()); when(renderRequest.getSoyMsgBundle()).thenReturn(Optional.<SoyMsgBundle>absent()); when(renderRequest.getSoyView()).thenReturn(soyView); when(response.getWriter()).thenReturn(printWriter); defaultTemplateRenderer.render(renderRequest); Mockito.verify(renderer, never()).setDontAddToCache(anyBoolean()); Mockito.verify(renderer, never()).setData(modelData); Mockito.verify(renderer, never()).setIjData(any(SoyMapData.class)); Mockito.verify(renderer, never()).setMsgBundle(any(SoyMsgBundle.class)); Mockito.verify(renderer).render(); Mockito.verify(printWriter).write(anyString()); Mockito.verify(printWriter).flush(); Mockito.verify(response).flushBuffer(); } |
### Question:
EmptyTemplateRenderer implements TemplateRenderer { @Override public void render(final RenderRequest renderRequest) throws Exception { } @Override void render(final RenderRequest renderRequest); }### Answer:
@Test public void testName() throws Exception { emptyTemplateRenderer.render(renderRequest); Mockito.verifyZeroInteractions(renderRequest); } |
### Question:
DefaultContentNegotiator implements ContentNegotiator { @Override public List<String> contentTypes() { List<String> contentTypes = null; final HttpServletRequest request = getHttpRequest(); if (favorParameterOverAcceptHeader) { contentTypes = getFavoredParameterValueAsList(request); } else { contentTypes = getAcceptHeaderValues(request); } if (isEmpty(contentTypes)) { logger.debug("Setting content types to default: {}.", DEFAULT_SUPPORTED_CONTENT_TYPES); contentTypes = DEFAULT_SUPPORTED_CONTENT_TYPES; } return unmodifiableList(contentTypes); } DefaultContentNegotiator(); List<String> getSupportedContentTypes(); void setSupportedContentTypes(final List<String> supportedContentTypes); boolean isFavorParameterOverAcceptHeader(); void setFavorParameterOverAcceptHeader(final boolean favorParameterOverAcceptHeader); String getFavoredParameterName(); void setFavoredParameterName(final String parameterName); Comparator<List<String>> getContentTypeComparator(); void setContentTypeComparator(final Comparator<List<String>> contentTypeComparator); @Override boolean isSupportedContentTypes(final List<String> contentTypes); @Override List<String> contentTypes(); static final String DEFAULT_FAVORED_PARAMETER_NAME; static final List<String> DEFAULT_SUPPORTED_CONTENT_TYPES; static final String ACCEPT_HEADER; }### Answer:
@Test public void testContentTypesWhenAcceptHeader() { when(req.getParameter(DEFAULT_FAVORED_PARAMETER_NAME)).thenReturn("text/html"); when(req.getHeaders(ACCEPT_HEADER)).thenReturn(enumeration(asList("text/html", "text/plain"))); assertEquals(asList("text/html", "text/plain"), contentNegotiator.contentTypes()); }
@Test public void testContentTypesWhenNeedsSplit() { when(req.getHeaders(ACCEPT_HEADER)).thenReturn( enumeration(asList("text/html,application/xhtml+xml,application/xml;q=0.9"))); assertEquals(asList("text/html", "application/xhtml+xml", "application/xml;q=0.9"), contentNegotiator.contentTypes()); }
@Test public void testContentTypesWhenNeedsSplitWithWhitespace() { when(req.getHeaders(ACCEPT_HEADER)).thenReturn( enumeration(asList("text/html, application/xhtml+xml, application/xml;q=0.9"))); assertEquals(asList("text/html", "application/xhtml+xml", "application/xml;q=0.9"), contentNegotiator.contentTypes()); } |
### Question:
DefaultTofuCompiler implements TofuCompiler { public boolean isHotReloadMode() { return hotReloadMode; } @Override SoyTofu compile(@Nullable final Collection<URL> urls); @Override final Optional<String> compileToJsSrc(@Nullable final URL url, @Nullable final SoyMsgBundle soyMsgBundle); @Override Collection<String> compileToJsSrc(Collection<URL> templates, @Nullable SoyMsgBundle soyMsgBundle); void setHotReloadMode(final boolean hotReloadMode); void setCompileTimeGlobalModelResolver(final CompileTimeGlobalModelResolver compileTimeGlobalModelResolver); void setSoyJsSrcOptions(final SoyJsSrcOptions soyJsSrcOptions); boolean isHotReloadMode(); boolean isHotReloadModeOff(); SoyJsSrcOptions getSoyJsSrcOptions(); SoyTofuOptions getSoyTofuOptions(); void setSoyTofuOptions(SoyTofuOptions soyTofuOptions); }### Answer:
@Test public void debugDefault() throws Exception { Assert.assertFalse("debug should be off", defaultTofuCompiler.isHotReloadMode()); } |
### Question:
DefaultTofuCompiler implements TofuCompiler { public SoyJsSrcOptions getSoyJsSrcOptions() { return soyJsSrcOptions; } @Override SoyTofu compile(@Nullable final Collection<URL> urls); @Override final Optional<String> compileToJsSrc(@Nullable final URL url, @Nullable final SoyMsgBundle soyMsgBundle); @Override Collection<String> compileToJsSrc(Collection<URL> templates, @Nullable SoyMsgBundle soyMsgBundle); void setHotReloadMode(final boolean hotReloadMode); void setCompileTimeGlobalModelResolver(final CompileTimeGlobalModelResolver compileTimeGlobalModelResolver); void setSoyJsSrcOptions(final SoyJsSrcOptions soyJsSrcOptions); boolean isHotReloadMode(); boolean isHotReloadModeOff(); SoyJsSrcOptions getSoyJsSrcOptions(); SoyTofuOptions getSoyTofuOptions(); void setSoyTofuOptions(SoyTofuOptions soyTofuOptions); }### Answer:
@Test public void testSoyJsSrcOptionsNotNull() throws Exception { Assert.assertNotNull(defaultTofuCompiler.getSoyJsSrcOptions()); } |
### Question:
DefaultTofuCompiler implements TofuCompiler { @Override public SoyTofu compile(@Nullable final Collection<URL> urls) throws IOException { Preconditions.checkNotNull("compileTimeGlobalModelResolver", compileTimeGlobalModelResolver); if (urls == null || urls.isEmpty()) { throw new IOException("Unable to compile, no urls found"); } logger.debug("SoyTofu compilation of templates:" + urls.size()); final long time1 = System.currentTimeMillis(); final SoyFileSet.Builder sfsBuilder = new SoyFileSet.Builder(); for (final URL url : urls) { sfsBuilder.add(url); } addCompileTimeGlobalModel(sfsBuilder); final SoyFileSet soyFileSet = sfsBuilder.build(); final SoyTofuOptions soyTofuOptions = createSoyTofuOptions(); final SoyTofu soyTofu = soyFileSet.compileToTofu(soyTofuOptions); final long time2 = System.currentTimeMillis(); logger.debug("SoyTofu compilation complete." + (time2 - time1) + " ms"); return soyTofu; } @Override SoyTofu compile(@Nullable final Collection<URL> urls); @Override final Optional<String> compileToJsSrc(@Nullable final URL url, @Nullable final SoyMsgBundle soyMsgBundle); @Override Collection<String> compileToJsSrc(Collection<URL> templates, @Nullable SoyMsgBundle soyMsgBundle); void setHotReloadMode(final boolean hotReloadMode); void setCompileTimeGlobalModelResolver(final CompileTimeGlobalModelResolver compileTimeGlobalModelResolver); void setSoyJsSrcOptions(final SoyJsSrcOptions soyJsSrcOptions); boolean isHotReloadMode(); boolean isHotReloadModeOff(); SoyJsSrcOptions getSoyJsSrcOptions(); SoyTofuOptions getSoyTofuOptions(); void setSoyTofuOptions(SoyTofuOptions soyTofuOptions); }### Answer:
@Test public void testCompileSoyToBinaryWithEmptyCompileTimeModel() throws Exception { when(compileTimeGlobalModelResolver.resolveData()).thenReturn(Optional.<SoyMapData>absent()); final URL template1 = getClass().getClassLoader().getResource("templates/template1.soy"); final SoyTofu tofu = defaultTofuCompiler.compile(Lists.newArrayList(template1)); Assert.assertNotNull(tofu); }
@Test public void testCompileSoyToJsWithCompileTimeModel() throws Exception { final SoyMapData soyMapData = new SoyMapData(); soyMapData.put("test1", "test2"); when(compileTimeGlobalModelResolver.resolveData()).thenReturn(Optional.of(soyMapData)); final URL template1 = getClass().getClassLoader().getResource("templates/template1.soy"); final SoyTofu tofu = defaultTofuCompiler.compile(Lists.newArrayList(template1)); Assert.assertNotNull("tofu object should not be null", tofu); } |
### Question:
PermissableAuthManager implements AuthManager { @Override public boolean isAllowed(String url) { return true; } @Override boolean isAllowed(String url); }### Answer:
@Test public void testDefault() throws Exception { Assert.assertTrue("should allow all", permissableAuthManager.isAllowed("template")); } |
### Question:
CookieDataResolver implements RuntimeDataResolver { @Override public void resolveData(final HttpServletRequest request, final HttpServletResponse response, final Map<String, ? extends Object> model, final SoyMapData root) { if (request.getCookies() == null) { logger.debug("no cookies!"); return; } for (final Cookie cookie : request.getCookies()) { if (StringUtils.hasLength(cookie.getName())) { final String keyPrefix = prefix + cookie.getName(); root.put(keyPrefix + ".name", cookie.getName()); if (StringUtils.hasLength(cookie.getValue())) { root.put(keyPrefix + ".value", cookie.getValue()); } if (StringUtils.hasLength(cookie.getComment())) { root.put(keyPrefix + ".comment", cookie.getComment()); } if (StringUtils.hasLength(cookie.getDomain())) { root.put(keyPrefix + ".domain", cookie.getDomain()); } root.put(keyPrefix + ".maxAge", cookie.getMaxAge()); if (StringUtils.hasLength(cookie.getPath())) { root.put(keyPrefix + ".path", cookie.getPath()); } root.put(keyPrefix + ".version", cookie.getVersion()); root.put(keyPrefix + ".secure", cookie.getSecure()); } } } @Override void resolveData(final HttpServletRequest request, final HttpServletResponse response, final Map<String, ? extends Object> model, final SoyMapData root); String getPrefix(); void setPrefix(String prefix); }### Answer:
@Test public void testBindCookies() throws Exception { final SoyMapData soyMapData = new SoyMapData(); final HttpServletRequest request = mock(HttpServletRequest.class); final HttpServletResponse response = mock(HttpServletResponse.class); final Enumeration e = mock(Enumeration.class); when(e.hasMoreElements()).thenReturn(false); when(request.getParameterNames()).thenReturn(e); when(request.getHeaderNames()).thenReturn(e); when(request.getCookies()).thenReturn(new Cookie[]{new Cookie("name1", "value1"), new Cookie("name2", "value2")}); cookieResolver.resolveData(request, response, null, soyMapData); Assert.assertEquals("should not be value1", "value1", soyMapData.get("_request.cookie.name1.value").stringValue()); Assert.assertEquals("should not be value2", "value2", soyMapData.get("_request.cookie.name2.value").stringValue()); Assert.assertEquals("should not be name1", "name1", soyMapData.get("_request.cookie.name1.name").stringValue()); Assert.assertEquals("should not be name2", "name2", soyMapData.get("_request.cookie.name2.name").stringValue()); } |
### Question:
RequestParametersDataResolver implements RuntimeDataResolver { @Override public void resolveData(final HttpServletRequest request, final HttpServletResponse response, final Map<String, ? extends Object> model, final SoyMapData root) { for (final Enumeration e = request.getParameterNames(); e.hasMoreElements();) { final String paramName = (String) e.nextElement(); final String parameter = request.getParameter(paramName); if (parameter != null) { root.put("_request.parameter." + paramName, parameter); } } } @Override void resolveData(final HttpServletRequest request, final HttpServletResponse response, final Map<String, ? extends Object> model, final SoyMapData root); String getPrefix(); void setPrefix(String prefix); }### Answer:
@Test public void resolveRequestParameters() throws Exception { final SoyMapData soyMapData = new SoyMapData(); final Vector<String> names = new Vector<String>(); names.add("name1"); names.add("name2"); final Vector<String> values = new Vector<String>(); values.add("value1"); values.add("value2"); final HttpServletRequest request = mock(HttpServletRequest.class); final HttpServletResponse response = mock(HttpServletResponse.class); final Enumeration e = mock(Enumeration.class); when(e.hasMoreElements()).thenReturn(false); when(request.getParameterNames()).thenReturn(names.elements()); when(request.getHeaderNames()).thenReturn(e); when(request.getParameter("name1")).thenReturn(values.get(0)); when(request.getParameter("name2")).thenReturn(values.get(1)); when(request.getCookies()).thenReturn(new Cookie[]{}); requestParametersResolver.resolveData(request, response, null, soyMapData); Assert.assertEquals("should not be value1", "value1", soyMapData.get("_request.parameter.name1").stringValue()); Assert.assertEquals("should not be value2", "value2", soyMapData.get("_request.parameter.name2").stringValue()); } |
### Question:
RequestHeadersDataResolver implements RuntimeDataResolver { @Override public void resolveData(final HttpServletRequest request, final HttpServletResponse response, Map<String, ? extends Object> model, final SoyMapData root) { for (final Enumeration e = request.getHeaderNames(); e.hasMoreElements();) { final String headerName = (String) e.nextElement(); final String requestHeader = request.getHeader(headerName); if (requestHeader != null) { root.put(prefix + headerName, requestHeader); } } } @Override void resolveData(final HttpServletRequest request, final HttpServletResponse response, Map<String, ? extends Object> model, final SoyMapData root); void setPrefix(String prefix); String getPrefix(); }### Answer:
@Test public void testResolverHeaders() throws Exception { final SoyMapData soyMapData = new SoyMapData(); final Vector<String> names = new Vector<String>(); names.add("name1"); names.add("name2"); final Vector<String> values = new Vector<String>(); values.add("value1"); values.add("value2"); final HttpServletRequest request = mock(HttpServletRequest.class); final HttpServletResponse response = mock(HttpServletResponse.class); final Enumeration e = mock(Enumeration.class); when(e.hasMoreElements()).thenReturn(false); when(request.getParameterNames()).thenReturn(e); when(request.getHeaderNames()).thenReturn(names.elements()); when(request.getHeader("name1")).thenReturn(values.get(0)); when(request.getHeader("name2")).thenReturn(values.get(1)); when(request.getCookies()).thenReturn(new Cookie[]{}); requestHeadersResolver.resolveData(request, response, Maps.<String, Object>newHashMap(), soyMapData); Assert.assertEquals("should not be value1", "value1", soyMapData.get("_request.header.name1").stringValue()); Assert.assertEquals("should not be value2", "value2", soyMapData.get("_request.header.name2").stringValue()); } |
### Question:
EmptyCompileTimeGlobalModelResolver implements CompileTimeGlobalModelResolver { public Optional<SoyMapData> resolveData() { return Optional.absent(); } Optional<SoyMapData> resolveData(); }### Answer:
@Test public void notNull() throws Exception { Assert.assertNotNull("not null", defaultCompileTimeGlobalModelResolver.resolveData()); }
@Test public void absent() throws Exception { Assert.assertFalse("should be absent", defaultCompileTimeGlobalModelResolver.resolveData().isPresent()); } |
### Question:
DefaultCompileTimeGlobalModelResolver implements CompileTimeGlobalModelResolver { @Override public Optional<SoyMapData> resolveData() { if (data == null || data.isEmpty()) { return Optional.absent(); } return Optional.of(new SoyMapData(data)); } @Override Optional<SoyMapData> resolveData(); void setData(final Map data); void setProperties(final Properties properties); }### Answer:
@Test public void defaultNotNull() throws Exception { Assert.assertNotNull("by default not null", defaultCompileTimeGlobalModelResolver.resolveData()); }
@Test public void defaultAbsent() throws Exception { Assert.assertFalse("by default there is no data - returns absent", defaultCompileTimeGlobalModelResolver.resolveData().isPresent()); } |
### Question:
MD5HashFileGenerator implements HashFileGenerator, InitializingBean { public boolean isHotReloadMode() { return hotReloadMode; } void afterPropertiesSet(); @Override Optional<String> hash(final Optional<URL> url); @Override Optional<String> hashMulti(final Collection<URL> urls); static String getMD5Checksum(final InputStream is); void setHotReloadMode(boolean hotReloadMode); void setCacheMaxSize(int cacheMaxSize); void setExpireAfterWrite(int expireAfterWrite); void setExpireAfterWriteUnit(String expireAfterWriteUnit); boolean isHotReloadMode(); int getCacheMaxSize(); int getExpireAfterWrite(); String getExpireAfterWriteUnit(); }### Answer:
@Test public void testDebugByDefault() throws Exception { Assert.assertFalse("debug should be off by default", hashFileGenerator.isHotReloadMode()); } |
### Question:
DefaultCompileTimeGlobalModelResolver implements CompileTimeGlobalModelResolver { public void setProperties(final Properties properties) { data = new HashMap(); for (final String propertyName : properties.stringPropertyNames()) { data.put(propertyName, properties.getProperty(propertyName)); } } @Override Optional<SoyMapData> resolveData(); void setData(final Map data); void setProperties(final Properties properties); }### Answer:
@Test public void setProperties() throws Exception { final Properties properties = new Properties(); properties.setProperty("key1", "value1"); properties.setProperty("key2", "value2"); properties.setProperty("key3", "value3"); defaultCompileTimeGlobalModelResolver.setProperties(properties); Assert.assertEquals("after setting data - returns value1", "value1", defaultCompileTimeGlobalModelResolver.resolveData().get().get("key1").stringValue()); Assert.assertEquals("after setting data - returns value2", "value2", defaultCompileTimeGlobalModelResolver.resolveData().get().get("key2").stringValue()); Assert.assertEquals("after setting data - returns value3", "value3", defaultCompileTimeGlobalModelResolver.resolveData().get().get("key3").stringValue()); } |
### Question:
ClasspathTemplateFilesResolver implements TemplateFilesResolver, InitializingBean { public boolean isHotReloadMode() { return hotReloadMode; } @Override void afterPropertiesSet(); @Override Collection<URL> resolve(); @Override Optional<URL> resolve(final @Nullable String templateFileName); void setTemplatesLocation(String templatesLocation); void setRecursive(boolean recursive); void setHotReloadMode(boolean hotReloadMode); String getTemplatesLocation(); boolean isRecursive(); boolean isHotReloadMode(); String getFilesExtension(); void setFilesExtension(String filesExtension); }### Answer:
@Test public void defaultDebugFlag() throws Exception { Assert.assertFalse("debug flag should be off", templateFilesResolver.isHotReloadMode()); } |
### Question:
ClasspathTemplateFilesResolver implements TemplateFilesResolver, InitializingBean { public boolean isRecursive() { return recursive; } @Override void afterPropertiesSet(); @Override Collection<URL> resolve(); @Override Optional<URL> resolve(final @Nullable String templateFileName); void setTemplatesLocation(String templatesLocation); void setRecursive(boolean recursive); void setHotReloadMode(boolean hotReloadMode); String getTemplatesLocation(); boolean isRecursive(); boolean isHotReloadMode(); String getFilesExtension(); void setFilesExtension(String filesExtension); }### Answer:
@Test public void defaultRecursive() throws Exception { Assert.assertTrue("recursive template file resolution should be on", templateFilesResolver.isRecursive()); } |
### Question:
ClasspathTemplateFilesResolver implements TemplateFilesResolver, InitializingBean { public void setRecursive(boolean recursive) { this.recursive = recursive; } @Override void afterPropertiesSet(); @Override Collection<URL> resolve(); @Override Optional<URL> resolve(final @Nullable String templateFileName); void setTemplatesLocation(String templatesLocation); void setRecursive(boolean recursive); void setHotReloadMode(boolean hotReloadMode); String getTemplatesLocation(); boolean isRecursive(); boolean isHotReloadMode(); String getFilesExtension(); void setFilesExtension(String filesExtension); }### Answer:
@Test public void setRecursive() throws Exception { templateFilesResolver.setRecursive(false); Assert.assertFalse("recursive template file resolution should be off", templateFilesResolver.isRecursive()); } |
### Question:
ClasspathTemplateFilesResolver implements TemplateFilesResolver, InitializingBean { public String getTemplatesLocation() { return templatesLocation; } @Override void afterPropertiesSet(); @Override Collection<URL> resolve(); @Override Optional<URL> resolve(final @Nullable String templateFileName); void setTemplatesLocation(String templatesLocation); void setRecursive(boolean recursive); void setHotReloadMode(boolean hotReloadMode); String getTemplatesLocation(); boolean isRecursive(); boolean isHotReloadMode(); String getFilesExtension(); void setFilesExtension(String filesExtension); }### Answer:
@Test public void defaultTemplateLocation() throws Exception { Assert.assertNull("template file location should be null", new DefaultTemplateFilesResolver().getTemplatesLocation()); } |
### Question:
ClasspathTemplateFilesResolver implements TemplateFilesResolver, InitializingBean { @Override public Collection<URL> resolve() throws IOException { Preconditions.checkNotNull(templatesLocation, "templatesLocation cannot be null!"); return Collections.unmodifiableCollection(handleResolution()); } @Override void afterPropertiesSet(); @Override Collection<URL> resolve(); @Override Optional<URL> resolve(final @Nullable String templateFileName); void setTemplatesLocation(String templatesLocation); void setRecursive(boolean recursive); void setHotReloadMode(boolean hotReloadMode); String getTemplatesLocation(); boolean isRecursive(); boolean isHotReloadMode(); String getFilesExtension(); void setFilesExtension(String filesExtension); }### Answer:
@Test public void resolveDebugOffRecursiveOn() throws Exception { final Collection<URL> urls = templateFilesResolver.resolve(); Assert.assertEquals("should resolve urls", 5, urls.size()); Set<String> names = nab_template_names(urls); for (final String s : new String[] {"template1", "template2", "template3", "sub/template4", "sub/template5"}) { Assert.assertTrue(s + " must be in the set of resolved templates.", names.contains("templates/" + s + ".soy")); } }
@Test public void resolveWithFullTemplateNameDebugOff() throws Exception { final Optional<URL> url = templateFilesResolver.resolve("templates/template1"); Assert.assertTrue("should be present", url.isPresent()); Assert.assertTrue("template1Url file should end with template1.soy", url.get().getFile().endsWith("template1.soy")); }
@Test public void resolveWithTemplateNameDebugOff() throws Exception { final Optional<URL> url = templateFilesResolver.resolve("template1"); Assert.assertTrue("should be present", url.isPresent()); Assert.assertTrue("template1Url file should end with template1.soy", url.get().getFile().endsWith("template1.soy")); }
@Test public void resolveWithFullTemplateNameExtDebugOff() throws Exception { final Optional<URL> url = templateFilesResolver.resolve("templates/template1.soy"); Assert.assertTrue("should be present", url.isPresent()); Assert.assertTrue("template1Url file should end with template1.soy", url.get().getFile().endsWith("template1.soy")); }
@Test public void resolveWithTemplateNameExtDebugOff() throws Exception { final Optional<URL> url = templateFilesResolver.resolve("template1.soy"); Assert.assertTrue("should be present", url.isPresent()); Assert.assertTrue("template1Url file should end with template1.soy", url.get().getFile().endsWith("template1.soy")); }
@Test public void resolveWithFullTemplateNameExtDebugOffShouldNotWork() throws Exception { final Optional<URL> url = templateFilesResolver.resolve("tmpl/template1.soy"); Assert.assertFalse("should be absent", url.isPresent()); }
@Test public void cacheDisabledByDefault() throws Exception { templateFilesResolver.resolve("template1"); Assert.assertFalse("cache should not be empty", templateFilesResolver.cachedFiles.isEmpty()); }
@Test public void cacheEnabledWithDebugOff() throws Exception { templateFilesResolver.resolve("template1"); Assert.assertFalse("cache should not be empty", templateFilesResolver.cachedFiles.isEmpty()); Assert.assertEquals("number of items in cache should be equal", 5, templateFilesResolver.cachedFiles.size()); } |
### Question:
MD5HashFileGenerator implements HashFileGenerator, InitializingBean { public String getExpireAfterWriteUnit() { return expireAfterWriteUnit; } void afterPropertiesSet(); @Override Optional<String> hash(final Optional<URL> url); @Override Optional<String> hashMulti(final Collection<URL> urls); static String getMD5Checksum(final InputStream is); void setHotReloadMode(boolean hotReloadMode); void setCacheMaxSize(int cacheMaxSize); void setExpireAfterWrite(int expireAfterWrite); void setExpireAfterWriteUnit(String expireAfterWriteUnit); boolean isHotReloadMode(); int getCacheMaxSize(); int getExpireAfterWrite(); String getExpireAfterWriteUnit(); }### Answer:
@Test public void testDefaultWriteExpireUnit() throws Exception { Assert.assertEquals("default write expire unit should be", "DAYS", hashFileGenerator.getExpireAfterWriteUnit()); } |
### Question:
DefaultTemplateFilesResolver implements TemplateFilesResolver, ServletContextAware, InitializingBean { public boolean isHotReloadMode() { return hotReloadMode; } DefaultTemplateFilesResolver(); @Override void afterPropertiesSet(); @Override Collection<URL> resolve(); @Override Optional<URL> resolve(final @Nullable String templateFileName); void setTemplatesLocation(Resource templatesLocation); void setRecursive(boolean recursive); void setHotReloadMode(boolean hotReloadMode); Resource getTemplatesLocation(); boolean isRecursive(); boolean isHotReloadMode(); String getFilesExtension(); void setFilesExtension(String filesExtension); @Override void setServletContext(ServletContext servletContext); }### Answer:
@Test public void defaultDebugFlag() throws Exception { Assert.assertFalse("debug flag should be off", defaultTemplateFilesResolver.isHotReloadMode()); } |
### Question:
DefaultTemplateFilesResolver implements TemplateFilesResolver, ServletContextAware, InitializingBean { public boolean isRecursive() { return recursive; } DefaultTemplateFilesResolver(); @Override void afterPropertiesSet(); @Override Collection<URL> resolve(); @Override Optional<URL> resolve(final @Nullable String templateFileName); void setTemplatesLocation(Resource templatesLocation); void setRecursive(boolean recursive); void setHotReloadMode(boolean hotReloadMode); Resource getTemplatesLocation(); boolean isRecursive(); boolean isHotReloadMode(); String getFilesExtension(); void setFilesExtension(String filesExtension); @Override void setServletContext(ServletContext servletContext); }### Answer:
@Test public void defaultRecursive() throws Exception { Assert.assertTrue("recursive template file resolution should be on", defaultTemplateFilesResolver.isRecursive()); } |
### Question:
DefaultTemplateFilesResolver implements TemplateFilesResolver, ServletContextAware, InitializingBean { public void setRecursive(boolean recursive) { this.recursive = recursive; } DefaultTemplateFilesResolver(); @Override void afterPropertiesSet(); @Override Collection<URL> resolve(); @Override Optional<URL> resolve(final @Nullable String templateFileName); void setTemplatesLocation(Resource templatesLocation); void setRecursive(boolean recursive); void setHotReloadMode(boolean hotReloadMode); Resource getTemplatesLocation(); boolean isRecursive(); boolean isHotReloadMode(); String getFilesExtension(); void setFilesExtension(String filesExtension); @Override void setServletContext(ServletContext servletContext); }### Answer:
@Test public void setRecursive() throws Exception { defaultTemplateFilesResolver.setRecursive(false); Assert.assertFalse("recursive template file resolution should be off", defaultTemplateFilesResolver.isRecursive()); } |
### Question:
DefaultTemplateFilesResolver implements TemplateFilesResolver, ServletContextAware, InitializingBean { public Resource getTemplatesLocation() { return templatesLocation; } DefaultTemplateFilesResolver(); @Override void afterPropertiesSet(); @Override Collection<URL> resolve(); @Override Optional<URL> resolve(final @Nullable String templateFileName); void setTemplatesLocation(Resource templatesLocation); void setRecursive(boolean recursive); void setHotReloadMode(boolean hotReloadMode); Resource getTemplatesLocation(); boolean isRecursive(); boolean isHotReloadMode(); String getFilesExtension(); void setFilesExtension(String filesExtension); @Override void setServletContext(ServletContext servletContext); }### Answer:
@Test public void defaultTemplateLocation() throws Exception { Assert.assertNull("template file location should be null", defaultTemplateFilesResolver.getTemplatesLocation()); } |
### Question:
EmptyTemplateFilesResolver implements TemplateFilesResolver { @Override public Collection<URL> resolve() throws IOException { return Collections.emptyList(); } @Override Collection<URL> resolve(); @Override Optional<URL> resolve(final String templateName); }### Answer:
@Test public void nonNull() throws Exception { Assert.assertNotNull("should not be null", emptyTemplateFilesResolver.resolve()); }
@Test public void testResolveMany() throws Exception { Assert.assertTrue("should be empty", emptyTemplateFilesResolver.resolve().isEmpty()); }
@Test public void testResolveOne() throws Exception { Assert.assertFalse("should be absent", emptyTemplateFilesResolver.resolve("template").isPresent()); } |
### Question:
MD5HashFileGenerator implements HashFileGenerator, InitializingBean { public int getExpireAfterWrite() { return expireAfterWrite; } void afterPropertiesSet(); @Override Optional<String> hash(final Optional<URL> url); @Override Optional<String> hashMulti(final Collection<URL> urls); static String getMD5Checksum(final InputStream is); void setHotReloadMode(boolean hotReloadMode); void setCacheMaxSize(int cacheMaxSize); void setExpireAfterWrite(int expireAfterWrite); void setExpireAfterWriteUnit(String expireAfterWriteUnit); boolean isHotReloadMode(); int getCacheMaxSize(); int getExpireAfterWrite(); String getExpireAfterWriteUnit(); }### Answer:
@Test public void testDefaultExpireTime() throws Exception { Assert.assertEquals("default expire in days is 1 day", 1, hashFileGenerator.getExpireAfterWrite()); } |
### Question:
DefaultSoyMsgBundleResolver implements SoyMsgBundleResolver { public boolean isHotReloadMode() { return hotReloadMode; } Optional<SoyMsgBundle> resolve(final Optional<Locale> locale); void setMessagesPath(final String messagesPath); void setHotReloadMode(final boolean hotReloadMode); void setFallbackToEnglish(boolean fallbackToEnglish); String getMessagesPath(); boolean isHotReloadMode(); boolean isFallbackToEnglish(); }### Answer:
@Test public void defaultDebug() throws Exception { Assert.assertFalse("debug should be off", defaultSoyMsgBundleResolver.isHotReloadMode()); } |
### Question:
DefaultSoyMsgBundleResolver implements SoyMsgBundleResolver { public String getMessagesPath() { return messagesPath; } Optional<SoyMsgBundle> resolve(final Optional<Locale> locale); void setMessagesPath(final String messagesPath); void setHotReloadMode(final boolean hotReloadMode); void setFallbackToEnglish(boolean fallbackToEnglish); String getMessagesPath(); boolean isHotReloadMode(); boolean isFallbackToEnglish(); }### Answer:
@Test public void defaultMessagesPath() throws Exception { Assert.assertEquals("default messages path", "messages", defaultSoyMsgBundleResolver.getMessagesPath()); } |
### Question:
DefaultSoyMsgBundleResolver implements SoyMsgBundleResolver { public boolean isFallbackToEnglish() { return fallbackToEnglish; } Optional<SoyMsgBundle> resolve(final Optional<Locale> locale); void setMessagesPath(final String messagesPath); void setHotReloadMode(final boolean hotReloadMode); void setFallbackToEnglish(boolean fallbackToEnglish); String getMessagesPath(); boolean isHotReloadMode(); boolean isFallbackToEnglish(); }### Answer:
@Test public void defaultFallbackToEnglish() throws Exception { Assert.assertTrue("fallBack to English should be on", defaultSoyMsgBundleResolver.isFallbackToEnglish()); } |
### Question:
DefaultSoyMsgBundleResolver implements SoyMsgBundleResolver { public Optional<SoyMsgBundle> resolve(final Optional<Locale> locale) throws IOException { if (!locale.isPresent()) { return Optional.absent(); } synchronized (msgBundles) { SoyMsgBundle soyMsgBundle = null; if (isHotReloadModeOff()) { soyMsgBundle = msgBundles.get(locale.get()); } if (soyMsgBundle == null) { soyMsgBundle = createSoyMsgBundle(locale.get()); if (soyMsgBundle == null) { soyMsgBundle = createSoyMsgBundle(new Locale(locale.get().getLanguage())); } if (soyMsgBundle == null && fallbackToEnglish) { soyMsgBundle = createSoyMsgBundle(Locale.ENGLISH); } if (soyMsgBundle == null) { return Optional.absent(); } if (isHotReloadModeOff()) { msgBundles.put(locale.get(), soyMsgBundle); } } return Optional.fromNullable(soyMsgBundle); } } Optional<SoyMsgBundle> resolve(final Optional<Locale> locale); void setMessagesPath(final String messagesPath); void setHotReloadMode(final boolean hotReloadMode); void setFallbackToEnglish(boolean fallbackToEnglish); String getMessagesPath(); boolean isHotReloadMode(); boolean isFallbackToEnglish(); }### Answer:
@Test public void resolveWithNoLocale() throws Exception { Assert.assertFalse("value should be absent", defaultSoyMsgBundleResolver.resolve(Optional.<Locale>absent()).isPresent()); }
@Test public void resolveDefaultMessagePathValuePresent() throws Exception { final Optional<SoyMsgBundle> soyMsgBundleOptional = defaultSoyMsgBundleResolver.resolve(Optional.of(Locale.ENGLISH)); Assert.assertTrue("value should be present", soyMsgBundleOptional.isPresent()); }
@Test public void resolveDefaultMessagePathNotNull() throws Exception { final Optional<SoyMsgBundle> soyMsgBundleOptional = defaultSoyMsgBundleResolver.resolve(Optional.of(Locale.ENGLISH)); Assert.assertNotNull("value should be present", soyMsgBundleOptional.get()); } |
### Question:
EmptySoyMsgBundleResolver implements SoyMsgBundleResolver { @Override public Optional<SoyMsgBundle> resolve(final Optional<Locale> locale) throws IOException { return Optional.absent(); } @Override Optional<SoyMsgBundle> resolve(final Optional<Locale> locale); }### Answer:
@Test public void defaultNull() throws Exception { Assert.assertFalse(emptySoyMsgBundleResolver.resolve(null).isPresent()); }
@Test public void defaultAbsent() throws Exception { Assert.assertFalse(emptySoyMsgBundleResolver.resolve(Optional.<Locale>absent()).isPresent()); }
@Test public void localePassedIn() throws Exception { Assert.assertFalse(emptySoyMsgBundleResolver.resolve(Optional.of(Locale.GERMANY)).isPresent()); } |
### Question:
MD5HashFileGenerator implements HashFileGenerator, InitializingBean { public int getCacheMaxSize() { return cacheMaxSize; } void afterPropertiesSet(); @Override Optional<String> hash(final Optional<URL> url); @Override Optional<String> hashMulti(final Collection<URL> urls); static String getMD5Checksum(final InputStream is); void setHotReloadMode(boolean hotReloadMode); void setCacheMaxSize(int cacheMaxSize); void setExpireAfterWrite(int expireAfterWrite); void setExpireAfterWriteUnit(String expireAfterWriteUnit); boolean isHotReloadMode(); int getCacheMaxSize(); int getExpireAfterWrite(); String getExpireAfterWriteUnit(); }### Answer:
@Test public void testDefaultMaxEntries() throws Exception { Assert.assertEquals("default cache size is 10000", 10000, hashFileGenerator.getCacheMaxSize()); } |
### Question:
Value implements Cloneable { @Nonnull public final T get() { return value; } protected Value(@Nonnull final T value); @Nonnull abstract Class<T> type(); @Nonnull final T get(); @Nonnull final W map(
@Nonnull final Function<? super T, ? extends W> mapper); @SuppressWarnings({"CloneDoesntCallSuperClone", "unchecked"}) @Override final V clone(); @Override final String toString(); }### Answer:
@Test public void shouldInternStringValues() { final String value = new String(new char[]{'a', 'b'}); assertThat(StringTestyValue.of(value).get(), is( sameInstance(StringTestyValue.of("ab").get()))); } |
### Question:
XProperties extends OrderedProperties { @Nullable @Override public String getProperty(final String key) { final String value = super.getProperty(key); if (null == value) return null; return substitutor.replace(value); } XProperties(); XProperties(@Nonnull final Map<String, String> initial); @Nonnull static XProperties from(@Nonnull @NonNull final String absolutePath); void register(@Nonnull final String prefix,
@Nonnull final Conversion<?, ? extends Exception> factory); @Override synchronized void load(@Nonnull final Reader reader); @Override synchronized void load(final InputStream inStream); @Nullable @Override String getProperty(final String key); @Nullable @Override synchronized Object get(final Object key); @Nullable T getObject(@Nonnull final String key); @Nullable @SuppressWarnings("unchecked") T getObjectOrDefault(@Nonnull final String key,
@Nullable final T defaultValue); }### Answer:
@Test public void shouldReplaceEnvironmentVariables() { xprops.setProperty("bar", isWindows() ? "${USERNAME}" : "${USER}"); assertThat(xprops.getProperty("bar"), is(not(nullValue()))); }
@Test public void shouldThrowOnMissingReplacement() { thrown.expect(MissingPropertyException.class); thrown.expectMessage(containsString("no-such-value")); xprops.setProperty("missing", "${no-such-value}"); xprops.getProperty("missing"); }
@Test public void shouldReplaceGetProperty() { xprops.setProperty("foo", "found"); xprops.setProperty("bar", "${foo}"); assertThat(xprops.getProperty("bar"), is(equalTo("found"))); }
@Test public void shouldReplaceGetPropertyFromSystemProperties() { try { System.setProperty("foo", "found"); xprops.setProperty("bar", "${foo}"); assertThat(xprops.getProperty("bar"), is(equalTo("found"))); } finally { System.clearProperty("foo"); } }
@Test public void shouldReplaceGetPropertyFromEnvironment() { new MockUp<System>() { @Mock(invocations = 1) public String getenv(final String key) { return "found"; } }; xprops.setProperty("bar", "${foo}"); assertThat(xprops.getProperty("bar"), is(equalTo("found"))); }
@Test public void shouldReplaceRepeatedGetProperty() { xprops.setProperty("baz", "found"); xprops.setProperty("foo", "${baz}"); xprops.setProperty("bar", "${foo}"); assertThat(xprops.getProperty("bar"), is(equalTo("found"))); }
@Test public void shouldReplaceNestedGetProperty() { xprops.setProperty("baz", "found"); xprops.setProperty("foo", "baz"); xprops.setProperty("bar", "${${foo}}"); assertThat(xprops.getProperty("bar"), is(equalTo("found"))); }
@Test public void shouldReplaceSystemProperty() { xprops.setProperty("bar", "${user.name}"); assertThat(xprops.getProperty("bar"), is(not(nullValue()))); } |
### Question:
XProperties extends OrderedProperties { @Nullable public <T> T getObject(@Nonnull final String key) { return getObjectOrDefault(key, null); } XProperties(); XProperties(@Nonnull final Map<String, String> initial); @Nonnull static XProperties from(@Nonnull @NonNull final String absolutePath); void register(@Nonnull final String prefix,
@Nonnull final Conversion<?, ? extends Exception> factory); @Override synchronized void load(@Nonnull final Reader reader); @Override synchronized void load(final InputStream inStream); @Nullable @Override String getProperty(final String key); @Nullable @Override synchronized Object get(final Object key); @Nullable T getObject(@Nonnull final String key); @Nullable @SuppressWarnings("unchecked") T getObjectOrDefault(@Nonnull final String key,
@Nullable final T defaultValue); }### Answer:
@Test public void shouldThrowWhenWronglyKeyAssignedToNonString() { thrown.expect(ClassCastException.class); thrown.expectMessage(containsString(Integer.class.getName())); xprops.setProperty("bar", ""); final Integer ignored = xprops.getObject("bar"); }
@Test public void shouldGetInt() { xprops.setProperty("bar", "3"); assertThat(xprops.getObject("int:bar"), is(equalTo(3))); }
@Test public void shouldGetIntegerExplicit() { xprops.setProperty("bar", "3"); assertThat(xprops.getObject("java.math.BigInteger:bar"), is(equalTo(new BigInteger("3")))); }
@Test public void shouldGetIntegerAliased() { xprops.setProperty("bar", "3"); assertThat(xprops.getObject("integer:bar"), is(equalTo(new BigInteger("3")))); }
@Test public void shouldGetDecimal() { xprops.setProperty("bar", "3"); assertThat(xprops.getObject("decimal:bar"), is(equalTo(new BigDecimal("3")))); }
@Test public void shouldGetResources() { xprops.setProperty("bar", format("classpath*:%sincluded*.properties", firstPathComponent(pathPrefix))); final List<Resource> resources = xprops.getObject("resource*:bar"); assertThat(resources.size(), is(equalTo(2))); assertThat(resources, tests( "contains resource filename ending with 'included" + ".properties'", r -> r.stream(). map(Resource::getFilename). filter(f -> f.endsWith("included.properties")). findFirst(). isPresent())); assertThat(resources, tests( "contains resource filename ending with 'included2.properties'", r -> r.stream(). map(Resource::getFilename). filter(f -> f.endsWith("included2.properties")). findFirst(). isPresent())); }
@Test public void shouldGetAddress() { xprops.setProperty("bar", "[2001:db8::1]:80"); final InetSocketAddress address = xprops.getObject("address:bar"); assertThat(address.getHostString(), is(equalTo("2001:db8::1"))); assertThat(address.getPort(), is(equalTo(80))); }
@Test public void shouldThrowForBadAddress() { thrown.expect(FailedConversionException.class); thrown.expectMessage(containsString("address:bar")); thrown.expectMessage(containsString("-@-")); xprops.setProperty("bar", "-@-"); xprops.getObject("address:bar"); } |
### Question:
XProperties extends OrderedProperties { @Nonnull public static XProperties from(@Nonnull @NonNull final String absolutePath) throws IOException { final Resource resource = new PathMatchingResourcePatternResolver() .getResource(absolutePath); try (final InputStream in = resource.getInputStream()) { final XProperties xprops = new XProperties(); xprops.included.add(resource.getURI()); xprops.load(in); return xprops; } } XProperties(); XProperties(@Nonnull final Map<String, String> initial); @Nonnull static XProperties from(@Nonnull @NonNull final String absolutePath); void register(@Nonnull final String prefix,
@Nonnull final Conversion<?, ? extends Exception> factory); @Override synchronized void load(@Nonnull final Reader reader); @Override synchronized void load(final InputStream inStream); @Nullable @Override String getProperty(final String key); @Nullable @Override synchronized Object get(final Object key); @Nullable T getObject(@Nonnull final String key); @Nullable @SuppressWarnings("unchecked") T getObjectOrDefault(@Nonnull final String key,
@Nullable final T defaultValue); }### Answer:
@Test public void shouldNoticeRecursiveInclude() throws IOException { thrown.expect(RecursiveIncludeException.class); thrown.expectMessage(containsString(format("%s/tweedle-dee.properties", pathPrefix))); XProperties.from(format("%s/tweedle-dee.properties", pathPrefix)); } |
### Question:
StackTraceFocuser implements Function<E, E> { @Nonnull public static <E extends Throwable> StackTraceFocuser<E> ignoreJavaClasses() { return ignoreClassNames(defaultClassNameIgnores); } StackTraceFocuser(@Nonnull final Iterable<Predicate<StackTraceElement>> ignores); @SafeVarargs StackTraceFocuser(@Nonnull final Predicate<StackTraceElement> first,
final Predicate<StackTraceElement>... rest); @Nonnull static StackTraceFocuser<E> ignoreClassNames(
@Nonnull final List<Pattern> classNameIgnores); @Nonnull static StackTraceFocuser<E> ignoreJavaClasses(); @Override E apply(final E e); @Nonnull static Predicate<StackTraceElement> ignoreClassName(@Nonnull final Pattern className); @Nonnull static Predicate<StackTraceElement> ignoreMethodName(@Nonnull final Pattern methodName); @Nonnull static Predicate<StackTraceElement> ignoreFileName(@Nonnull final Pattern fileName); @Nonnull static Predicate<StackTraceElement> ignoreLineNumber(@Nonnull final Pattern lineNumber); }### Answer:
@Test public void shouldIgnoreJavaClasses() { final Throwable x = new Throwable(); final StackTraceElement nonJava = new StackTraceElement("lotro.Bilbo", "smokes", "Bilbo.java", 5); x.setStackTrace(new StackTraceElement[]{ new StackTraceElement("java.lang.Frodo", "lives", "Frodo.java", 3), nonJava}); assertFramesRemaining(x, ignoreJavaClasses(), nonJava); }
@Test public void shouldIgnoreJavaxClasses() { final Throwable x = new Throwable(); final StackTraceElement nonJavax = new StackTraceElement("lotro.Bilbo", "smokes", "Bilbo.java", 5); x.setStackTrace(new StackTraceElement[]{ new StackTraceElement("javax.lang.Frodo", "lives", "Frodo.java", 3), nonJavax}); assertFramesRemaining(x, ignoreJavaClasses(), nonJavax); }
@Test public void shouldIgnoreSunClasses() { final Throwable x = new Throwable(); final StackTraceElement nonSun = new StackTraceElement("lotro.Bilbo", "smokes", "Bilbo.java", 5); x.setStackTrace(new StackTraceElement[]{ new StackTraceElement("sun.Frodo", "lives", "Frodo.java", 3), nonSun}); assertFramesRemaining(x, ignoreJavaClasses(), nonSun); }
@Test public void shouldIgnoreComSunClasses() { final Throwable x = new Throwable(); final StackTraceElement nonComSun = new StackTraceElement("lotro.Bilbo", "smokes", "Bilbo.java", 5); x.setStackTrace(new StackTraceElement[]{ new StackTraceElement("com.sun.Frodo", "lives", "Frodo.java", 3), nonComSun}); assertFramesRemaining(x, ignoreJavaClasses(), nonComSun); } |
### Question:
StackTraceFocuser implements Function<E, E> { @Nonnull public static Predicate<StackTraceElement> ignoreClassName(@Nonnull final Pattern className) { return frame -> className.matcher(frame.getClassName()).find(); } StackTraceFocuser(@Nonnull final Iterable<Predicate<StackTraceElement>> ignores); @SafeVarargs StackTraceFocuser(@Nonnull final Predicate<StackTraceElement> first,
final Predicate<StackTraceElement>... rest); @Nonnull static StackTraceFocuser<E> ignoreClassNames(
@Nonnull final List<Pattern> classNameIgnores); @Nonnull static StackTraceFocuser<E> ignoreJavaClasses(); @Override E apply(final E e); @Nonnull static Predicate<StackTraceElement> ignoreClassName(@Nonnull final Pattern className); @Nonnull static Predicate<StackTraceElement> ignoreMethodName(@Nonnull final Pattern methodName); @Nonnull static Predicate<StackTraceElement> ignoreFileName(@Nonnull final Pattern fileName); @Nonnull static Predicate<StackTraceElement> ignoreLineNumber(@Nonnull final Pattern lineNumber); }### Answer:
@Test public void shouldIgnoreWithCustomClassName() { final Throwable x = new Throwable(); final StackTraceElement nonWindfola = new StackTraceElement("lotro.Bilbo", "smokes", "Bilbo.java", 5); x.setStackTrace(new StackTraceElement[]{ new StackTraceElement("windfola.Frodo", "lives", "Frodo.java", 3), nonWindfola}); assertFramesRemaining(x, new StackTraceFocuser<>(ignoreClassName(compile("^windfola\\."))), nonWindfola); } |
### Question:
StackTraceFocuser implements Function<E, E> { @Nonnull public static Predicate<StackTraceElement> ignoreMethodName(@Nonnull final Pattern methodName) { return frame -> methodName.matcher(frame.getMethodName()).find(); } StackTraceFocuser(@Nonnull final Iterable<Predicate<StackTraceElement>> ignores); @SafeVarargs StackTraceFocuser(@Nonnull final Predicate<StackTraceElement> first,
final Predicate<StackTraceElement>... rest); @Nonnull static StackTraceFocuser<E> ignoreClassNames(
@Nonnull final List<Pattern> classNameIgnores); @Nonnull static StackTraceFocuser<E> ignoreJavaClasses(); @Override E apply(final E e); @Nonnull static Predicate<StackTraceElement> ignoreClassName(@Nonnull final Pattern className); @Nonnull static Predicate<StackTraceElement> ignoreMethodName(@Nonnull final Pattern methodName); @Nonnull static Predicate<StackTraceElement> ignoreFileName(@Nonnull final Pattern fileName); @Nonnull static Predicate<StackTraceElement> ignoreLineNumber(@Nonnull final Pattern lineNumber); }### Answer:
@Test public void shouldIgnoreWithCustomMethodName() { final Throwable x = new Throwable(); final StackTraceElement nonLives = new StackTraceElement("lotro.Bilbo", "smokes", "Bilbo.java", 5); x.setStackTrace(new StackTraceElement[]{ new StackTraceElement("windfola.Frodo", "lives", "Frodo.java", 3), nonLives}); assertFramesRemaining(x, new StackTraceFocuser<>(ignoreMethodName(compile("lives"))), nonLives); } |
### Question:
StackTraceFocuser implements Function<E, E> { @Nonnull public static Predicate<StackTraceElement> ignoreFileName(@Nonnull final Pattern fileName) { return frame -> fileName.matcher(frame.getFileName()).find(); } StackTraceFocuser(@Nonnull final Iterable<Predicate<StackTraceElement>> ignores); @SafeVarargs StackTraceFocuser(@Nonnull final Predicate<StackTraceElement> first,
final Predicate<StackTraceElement>... rest); @Nonnull static StackTraceFocuser<E> ignoreClassNames(
@Nonnull final List<Pattern> classNameIgnores); @Nonnull static StackTraceFocuser<E> ignoreJavaClasses(); @Override E apply(final E e); @Nonnull static Predicate<StackTraceElement> ignoreClassName(@Nonnull final Pattern className); @Nonnull static Predicate<StackTraceElement> ignoreMethodName(@Nonnull final Pattern methodName); @Nonnull static Predicate<StackTraceElement> ignoreFileName(@Nonnull final Pattern fileName); @Nonnull static Predicate<StackTraceElement> ignoreLineNumber(@Nonnull final Pattern lineNumber); }### Answer:
@Test public void shouldIgnoreWithCustomFileName() { final Throwable x = new Throwable(); final StackTraceElement nonFrodo = new StackTraceElement("lotro.Bilbo", "smokes", "Bilbo.java", 5); x.setStackTrace(new StackTraceElement[]{ new StackTraceElement("windfola.Frodo", "lives", "Frodo.java", 3), nonFrodo}); assertFramesRemaining(x, new StackTraceFocuser<>(ignoreFileName(compile("Frodo\\.java"))), nonFrodo); } |
### Question:
StackTraceFocuser implements Function<E, E> { @Nonnull public static Predicate<StackTraceElement> ignoreLineNumber(@Nonnull final Pattern lineNumber) { return frame -> lineNumber.matcher(String.valueOf(frame.getLineNumber())).find(); } StackTraceFocuser(@Nonnull final Iterable<Predicate<StackTraceElement>> ignores); @SafeVarargs StackTraceFocuser(@Nonnull final Predicate<StackTraceElement> first,
final Predicate<StackTraceElement>... rest); @Nonnull static StackTraceFocuser<E> ignoreClassNames(
@Nonnull final List<Pattern> classNameIgnores); @Nonnull static StackTraceFocuser<E> ignoreJavaClasses(); @Override E apply(final E e); @Nonnull static Predicate<StackTraceElement> ignoreClassName(@Nonnull final Pattern className); @Nonnull static Predicate<StackTraceElement> ignoreMethodName(@Nonnull final Pattern methodName); @Nonnull static Predicate<StackTraceElement> ignoreFileName(@Nonnull final Pattern fileName); @Nonnull static Predicate<StackTraceElement> ignoreLineNumber(@Nonnull final Pattern lineNumber); }### Answer:
@Test public void shouldIgnoreWithCustomLineNumber() { final Throwable x = new Throwable(); final StackTraceElement nonThree = new StackTraceElement("lotro.Bilbo", "smokes", "Bilbo.java", 5); x.setStackTrace(new StackTraceElement[]{ new StackTraceElement("windfola.Frodo", "lives", "Frodo.java", 3), nonThree}); assertFramesRemaining(x, new StackTraceFocuser<>(ignoreLineNumber(compile("3"))), nonThree); } |
### Question:
LinkedIterable implements Iterable<T> { @Nonnull public static <T> Iterable<T> over(@Nullable final T head, @Nonnull final Predicate<T> terminate, @Nonnull final Function<T, T> traverse) { return new LinkedIterable<>(head, terminate, traverse); } private LinkedIterable(final T head, final Predicate<T> terminate,
final Function<T, T> traverse); @Nonnull static Iterable<T> over(@Nullable final T head,
@Nonnull final Predicate<T> terminate, @Nonnull final Function<T, T> traverse); @Nonnull static Iterable<T> over(@Nonnull final Predicate<T> terminate,
@Nonnull final Function<T, T> traverse); @Override Iterator<T> iterator(); @Override Spliterator<T> spliterator(); static final int SPLITERATOR_CHARACTERISTICS; }### Answer:
@Test public void shouldHaveNone() { assertThat(over(Objects::isNull, identity()), is(emptyIterable())); }
@Test public void shouldHaveOne() { assertThat(over(this, Objects::isNull, t -> null), is(contains(this))); }
@Test public void shouldHaveMany() { final Predicate<Integer> terminate = t -> 3 == t; final Function<Integer, Integer> traverse = t -> t + 1; assertThat(over(0, terminate, traverse), contains(0, 1, 2)); } |
### Question:
XProperties extends OrderedProperties { @Override public synchronized void load(@Nonnull final Reader reader) throws IOException { final ResourcePatternResolver loader = new PathMatchingResourcePatternResolver(); try (final CharArrayWriter writer = new CharArrayWriter()) { try (final BufferedReader lines = new BufferedReader(reader)) { for (String line = lines.readLine(); null != line; line = lines.readLine()) { writer.append(line).append('\n'); final Matcher matcher = include.matcher(line); if (matcher.matches()) for (final String x : comma .split(substitutor.replace(matcher.group(1)))) for (final Resource resource : loader .getResources(x)) { final URI uri = resource.getURI(); if (!included.add(uri)) throw new RecursiveIncludeException(uri, included); try (final InputStream in = resource .getInputStream()) { load(in); } } } } super.load(new CharArrayReader(writer.toCharArray())); } included.clear(); } XProperties(); XProperties(@Nonnull final Map<String, String> initial); @Nonnull static XProperties from(@Nonnull @NonNull final String absolutePath); void register(@Nonnull final String prefix,
@Nonnull final Conversion<?, ? extends Exception> factory); @Override synchronized void load(@Nonnull final Reader reader); @Override synchronized void load(final InputStream inStream); @Nullable @Override String getProperty(final String key); @Nullable @Override synchronized Object get(final Object key); @Nullable T getObject(@Nonnull final String key); @Nullable @SuppressWarnings("unchecked") T getObjectOrDefault(@Nonnull final String key,
@Nullable final T defaultValue); }### Answer:
@Test public void shouldThrowOnBadInclude() throws IOException { thrown.expect(FileNotFoundException.class); thrown.expectMessage(containsString("no-such-location")); xprops.load(new StringReader("#include no-such-location")); } |
### Question:
Converter { @Nonnull public <T> T convert(@Nonnull final Class<T> type, @Nonnull final String value) throws Exception { return convert(TypeToken.of(wrap(type)), value); } void register(@Nonnull final Class<T> type, @Nonnull final Conversion<T, ?> factory); void register(@Nonnull final TypeToken<T> type,
@Nonnull final Conversion<T, ?> factory); void registerDate(@Nonnull final String pattern); @Nonnull T convert(@Nonnull final Class<T> type, @Nonnull final String value); @SuppressWarnings("unchecked") @Nonnull T convert(@Nonnull final TypeToken<T> type, @Nonnull final String value); @Nonnull Set<TypeToken<?>> registered(); }### Answer:
@Test public void shouldConvertString() throws Exception { assertThat("bob", is(equalTo(converter.convert(String.class, "bob")))); }
@Test public void shouldConvertRegistered() throws Exception { assertThat(Paths.get("/dev/null"), is(equalTo(converter.convert(Path.class, "/dev/null")))); }
@Test public void shouldConvertWithValueOf() throws Exception { assertThat(3, is(equalTo(converter.convert(Integer.class, "3")))); }
@Test public void shouldConvertWithOf() throws Exception { assertThat(UTC, is(equalTo(converter.convert(ZoneOffset.class, "Z")))); }
@Test public void shouldConvertWithNew() throws Exception { assertThat(new File("/dev/null"), is(equalTo(converter.convert(File.class, "/dev/null")))); }
@Test public void shouldConvertToResourceList() throws Exception { final String path = format("classpath:/%s.class", getClass().getName().replace('.', '/')); final List<Resource> resources = asList( new PathMatchingResourcePatternResolver().getResources(path)); assertThat(resources, is(equalTo(converter.convert(new TypeToken<List<Resource>>() { }, path)))); }
@Test(expected = UnsupportedConversion.class) public void shouldThrowWhenUnsupported() throws Exception { converter.convert(Package.class, getClass().getPackage().getName()); } |
### Question:
Converter { public <T> void register(@Nonnull final Class<T> type, @Nonnull final Conversion<T, ?> factory) throws DuplicateConversion { register(TypeToken.of(type), factory); } void register(@Nonnull final Class<T> type, @Nonnull final Conversion<T, ?> factory); void register(@Nonnull final TypeToken<T> type,
@Nonnull final Conversion<T, ?> factory); void registerDate(@Nonnull final String pattern); @Nonnull T convert(@Nonnull final Class<T> type, @Nonnull final String value); @SuppressWarnings("unchecked") @Nonnull T convert(@Nonnull final TypeToken<T> type, @Nonnull final String value); @Nonnull Set<TypeToken<?>> registered(); }### Answer:
@Test(expected = DuplicateConversion.class) public void shouldThrowWhenDuplicate() { converter.register(Path.class, Paths::get); } |
### Question:
XProperties extends OrderedProperties { @Nullable @Override public synchronized Object get(final Object key) { final Object value = super.get(key); if (null == value || !(value instanceof String)) return value; return substitutor.replace((String) value); } XProperties(); XProperties(@Nonnull final Map<String, String> initial); @Nonnull static XProperties from(@Nonnull @NonNull final String absolutePath); void register(@Nonnull final String prefix,
@Nonnull final Conversion<?, ? extends Exception> factory); @Override synchronized void load(@Nonnull final Reader reader); @Override synchronized void load(final InputStream inStream); @Nullable @Override String getProperty(final String key); @Nullable @Override synchronized Object get(final Object key); @Nullable T getObject(@Nonnull final String key); @Nullable @SuppressWarnings("unchecked") T getObjectOrDefault(@Nonnull final String key,
@Nullable final T defaultValue); }### Answer:
@Test public void shouldReplaceGet() { xprops.setProperty("foo", "found"); xprops.setProperty("bar", "${foo}"); assertThat(xprops.get("bar"), is(equalTo((Object) "found"))); } |
### Question:
SPAlgorithms { public static List<Path> kShortestPaths(Graph g, Node origin, Node destination, Integer K) throws Exception{ List<Path> A = new LinkedList<Path>(); PriorityQueue<Path> B = new PriorityQueue<Path>(); A.add(SPAlgorithms.dijkstra(g, origin,destination)); if (A.get(0) == null) throw new Exception(); for (Integer k = 1; k < K; k++) { for (Integer i = 0; i < A.get(k-1).size(); i++) { Graph gprime = new Graph(g); Node spurNode = A.get(k-1).node(i); Path rootPath = A.get(k-1).subPath(0,i); for (Path p : A) { if (rootPath.equals(p.subPath(0,i))){ gprime.remove(p.get(i)); } } for (Node rootPathNode : rootPath.nodes()) { if (!rootPathNode.equals(spurNode)){ gprime.remove(rootPathNode); } } Path spurPath = SPAlgorithms.dijkstra(gprime, spurNode, destination); if (spurPath != null) { rootPath.append(spurPath); B.add(rootPath); } } if (B.isEmpty()) break; A.add(B.poll()); } return A; } static Path dijkstra(Graph g, Node origin, Node destination); static List<Path> kShortestPaths(Graph g, Node origin, Node destination, Integer K); }### Answer:
@Test void braessTestFixed() { List<Path> shortPath = null; try { shortPath = SPAlgorithms.kShortestPaths(graph, A, D,3); } catch (Exception e) { fail(e); } Path abd = new Path(); abd.add(AB); abd.add(BD); Path acd = new Path(); acd.add(AC); acd.add(CD); Path abcd = new Path(); abcd.add(AB); abcd.add(BC); abcd.add(CD); LinkedList<Path> p = new LinkedList<Path>(); p.add(abcd); p.add(acd); p.add(abd); if (shortPath == null || !(shortPath.equals(p))) fail("K Short Path returned "+shortPath.toString()); assertTrue(shortPath != null && shortPath.equals(p)); assertEquals(shortPath,p); } |
### Question:
Gateway3DSecureActivity extends AppCompatActivity { String getExtraTitle() { Bundle extras = getIntent().getExtras(); if (extras != null) { return extras.getString(EXTRA_TITLE); } return null; } static final String EXTRA_HTML; static final String EXTRA_TITLE; static final String EXTRA_ACS_RESULT; }### Answer:
@Test public void testGetExtraTitleReturnsNullIfMissing() { Intent testIntent = new Intent(); doReturn(testIntent).when(activity).getIntent(); String title = activity.getExtraTitle(); assertNull(title); }
@Test public void testGetExtraTitleReturnsValueIfExists() { String expectedTitle = "My Title"; Intent testIntent = new Intent(); testIntent.putExtra(Gateway3DSecureActivity.EXTRA_TITLE, expectedTitle); doReturn(testIntent).when(activity).getIntent(); String title = activity.getExtraTitle(); assertEquals(expectedTitle, title); } |
### Question:
GatewayMap extends LinkedHashMap<String, Object> { @Override public Object get(Object keyPath) { String[] keys = ((String) keyPath).split("\\."); if (keys.length <= 1) { Matcher m = arrayIndexPattern.matcher(keys[0]); if (!m.matches()) { return super.get(keys[0]); } else { String key = m.group(1); Object o = super.get(key); if (!(o instanceof List)) { throw new IllegalArgumentException("Property '" + key + "' is not an array"); } List<Map<String, Object>> l = (List<Map<String, Object>>) o; Integer index = l.size() - 1; if (!"".equals(m.group(2))) { index = Integer.parseInt(m.group(2)); } return l.get(index); } } Map<String, Object> map = findLastMapInKeyPath((String) keyPath); return map.get(keys[keys.length - 1]); } GatewayMap(int initialCapacity, float loadFactor); GatewayMap(int initialCapacity); GatewayMap(); GatewayMap(Map<String, Object> map); GatewayMap(String jsonMapString); GatewayMap(String keyPath, Object value); @Override Object put(String keyPath, Object value); GatewayMap set(String keyPath, Object value); @Override Object get(Object keyPath); @Override boolean containsKey(Object keyPath); @Override Object remove(Object keyPath); static Map<String, Object> normalize(Map<String, Object> m); }### Answer:
@Test public void testJsonConstructorWithMap() { String json = "{\n" + " \"k1\":\"v1\",\n" + " \"k2\":{\n" + " \"k21\": \"v21\",\n" + " \"k22\": \"v22\",\n" + " \"k23\" : {\n" + " \"k231\": \"v231\"\n" + " }\n" + " }\n" + " }"; GatewayMap map = new GatewayMap(json); assertEquals(map.get("k1"), "v1"); assert map.get("k2") instanceof Map; assertEquals(map.get("k2.k21"), "v21"); assertEquals(map.get("k2.k22"), "v22"); assert map.get("k2.k23") instanceof Map; assertEquals(map.get("k2.k23.k231"), "v231"); }
@Test public void keyValueConstructorAddsKey() { assertEquals(new GatewayMap("k1", "v1").get("k1"), "v1"); assertEquals(new GatewayMap("k1.k2", "v12").get("k1.k2"), "v12"); } |
### Question:
Gateway { public Gateway setMerchantId(String merchantId) { if (merchantId == null) { throw new IllegalArgumentException("Merchant ID may not be null"); } this.merchantId = merchantId; return this; } Gateway(); String getMerchantId(); Gateway setMerchantId(String merchantId); Region getRegion(); Gateway setRegion(Region region); void updateSession(String sessionId, String apiVersion, GatewayMap payload, GatewayCallback callback); Single<GatewayMap> updateSession(String sessionId, String apiVersion, GatewayMap payload); static void start3DSecureActivity(Activity activity, String html); static void start3DSecureActivity(Activity activity, String html, String title); static boolean handle3DSecureResult(int requestCode, int resultCode, Intent data, Gateway3DSecureCallback callback); static void requestGooglePayData(PaymentsClient paymentsClient, PaymentDataRequest request, Activity activity); static boolean handleGooglePayResult(int requestCode, int resultCode, Intent data, GatewayGooglePayCallback callback); }### Answer:
@Test public void testSetMerchantIdThrowsExceptionIfNull() throws Exception { try { gateway.setMerchantId(null); fail("Null merchant ID should throw illegal argument exception"); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } }
@Test public void setMerchantIdWorksAsExpected() throws Exception { gateway.setMerchantId("MERCHANT_ID"); assertEquals(gateway.merchantId, "MERCHANT_ID"); } |
### Question:
Gateway { public Gateway setRegion(Region region) { if (region == null) { throw new IllegalArgumentException("Region may not be null"); } this.region = region; return this; } Gateway(); String getMerchantId(); Gateway setMerchantId(String merchantId); Region getRegion(); Gateway setRegion(Region region); void updateSession(String sessionId, String apiVersion, GatewayMap payload, GatewayCallback callback); Single<GatewayMap> updateSession(String sessionId, String apiVersion, GatewayMap payload); static void start3DSecureActivity(Activity activity, String html); static void start3DSecureActivity(Activity activity, String html, String title); static boolean handle3DSecureResult(int requestCode, int resultCode, Intent data, Gateway3DSecureCallback callback); static void requestGooglePayData(PaymentsClient paymentsClient, PaymentDataRequest request, Activity activity); static boolean handleGooglePayResult(int requestCode, int resultCode, Intent data, GatewayGooglePayCallback callback); }### Answer:
@Test public void testSetRegionThrowsExceptionIfNull() throws Exception { try { gateway.setRegion(null); fail("Null region should throw illegal argument exception"); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } }
@Test public void testSetRegionWorksAsIntended() throws Exception { gateway.setRegion(Gateway.Region.ASIA_PACIFIC); assertEquals(Gateway.Region.ASIA_PACIFIC, gateway.region); } |
### Question:
Gateway { public static void start3DSecureActivity(Activity activity, String html) { start3DSecureActivity(activity, html, null); } Gateway(); String getMerchantId(); Gateway setMerchantId(String merchantId); Region getRegion(); Gateway setRegion(Region region); void updateSession(String sessionId, String apiVersion, GatewayMap payload, GatewayCallback callback); Single<GatewayMap> updateSession(String sessionId, String apiVersion, GatewayMap payload); static void start3DSecureActivity(Activity activity, String html); static void start3DSecureActivity(Activity activity, String html, String title); static boolean handle3DSecureResult(int requestCode, int resultCode, Intent data, Gateway3DSecureCallback callback); static void requestGooglePayData(PaymentsClient paymentsClient, PaymentDataRequest request, Activity activity); static boolean handleGooglePayResult(int requestCode, int resultCode, Intent data, GatewayGooglePayCallback callback); }### Answer:
@Test public void testStart3DSecureActivitySkipsTitleIfNull() { Activity activity = mock(Activity.class); Intent intent = new Intent(); String testHtml = "html"; Gateway.start3DSecureActivity(activity, testHtml, null, intent); verify(activity).startActivityForResult(intent, Gateway.REQUEST_3D_SECURE); assertTrue(intent.hasExtra(Gateway3DSecureActivity.EXTRA_HTML)); assertFalse(intent.hasExtra(Gateway3DSecureActivity.EXTRA_TITLE)); assertEquals(testHtml, intent.getStringExtra(Gateway3DSecureActivity.EXTRA_HTML)); }
@Test public void testStart3DSecureActivityWorksAsExpected() { Activity activity = mock(Activity.class); Intent intent = new Intent(); String testHtml = "html"; String testTitle = "title"; Gateway.start3DSecureActivity(activity, testHtml, testTitle, intent); verify(activity).startActivityForResult(intent, Gateway.REQUEST_3D_SECURE); assertTrue(intent.hasExtra(Gateway3DSecureActivity.EXTRA_HTML)); assertTrue(intent.hasExtra(Gateway3DSecureActivity.EXTRA_TITLE)); assertEquals(testHtml, intent.getStringExtra(Gateway3DSecureActivity.EXTRA_HTML)); assertEquals(testTitle, intent.getStringExtra(Gateway3DSecureActivity.EXTRA_TITLE)); } |
### Question:
Gateway { public static boolean handle3DSecureResult(int requestCode, int resultCode, Intent data, Gateway3DSecureCallback callback) { if (callback == null) { return false; } if (requestCode == REQUEST_3D_SECURE) { if (resultCode == Activity.RESULT_OK) { String acsResultJson = data.getStringExtra(Gateway3DSecureActivity.EXTRA_ACS_RESULT); GatewayMap acsResult = new GatewayMap(acsResultJson); callback.on3DSecureComplete(acsResult); } else { callback.on3DSecureCancel(); } return true; } return false; } Gateway(); String getMerchantId(); Gateway setMerchantId(String merchantId); Region getRegion(); Gateway setRegion(Region region); void updateSession(String sessionId, String apiVersion, GatewayMap payload, GatewayCallback callback); Single<GatewayMap> updateSession(String sessionId, String apiVersion, GatewayMap payload); static void start3DSecureActivity(Activity activity, String html); static void start3DSecureActivity(Activity activity, String html, String title); static boolean handle3DSecureResult(int requestCode, int resultCode, Intent data, Gateway3DSecureCallback callback); static void requestGooglePayData(PaymentsClient paymentsClient, PaymentDataRequest request, Activity activity); static boolean handleGooglePayResult(int requestCode, int resultCode, Intent data, GatewayGooglePayCallback callback); }### Answer:
@Test public void testHandle3DSecureResultReturnsFalseWithNullCallback() { assertFalse(Gateway.handle3DSecureResult(0, 0, null, null)); }
@Test public void testHandle3DSSecureResultReturnsFalseIfInvalidRequestCode() { int invalidRequestCode = 10; Gateway3DSecureCallback callback = mock(Gateway3DSecureCallback.class); assertFalse(Gateway.handle3DSecureResult(invalidRequestCode, 0, null, callback)); }
@Test public void testHandle3DSecureResultCallsCancelIfResultNotOk() { int validRequestCode = Gateway.REQUEST_3D_SECURE; int resultCode = Activity.RESULT_CANCELED; Gateway3DSecureCallback callback = mock(Gateway3DSecureCallback.class); boolean result = Gateway.handle3DSecureResult(validRequestCode, resultCode, null, callback); assertTrue(result); verify(callback).on3DSecureCancel(); }
@Test public void testHandle3DSecureResultCallsCompleteIfResultOK() { int validRequestCode = Gateway.REQUEST_3D_SECURE; int resultCode = Activity.RESULT_OK; Intent data = mock(Intent.class); String acsResultJson = "{\"foo\":\"bar\"}"; Gateway3DSecureCallback callback = spy(new Gateway3DSecureCallback() { @Override public void on3DSecureComplete(GatewayMap response) { assertNotNull(response); assertTrue(response.containsKey("foo")); assertEquals("bar", response.get("foo")); } @Override public void on3DSecureCancel() { fail("Should never have called cancel"); } }); doReturn(acsResultJson).when(data).getStringExtra(Gateway3DSecureActivity.EXTRA_ACS_RESULT); boolean result = Gateway.handle3DSecureResult(validRequestCode, resultCode, data, callback); assertTrue(result); verify(callback).on3DSecureComplete(any()); } |
### Question:
Gateway { public static boolean handleGooglePayResult(int requestCode, int resultCode, Intent data, GatewayGooglePayCallback callback) { if (callback == null) { return false; } if (requestCode == REQUEST_GOOGLE_PAY_LOAD_PAYMENT_DATA) { if (resultCode == Activity.RESULT_OK) { try { PaymentData paymentData = PaymentData.getFromIntent(data); JSONObject json = new JSONObject(paymentData.toJson()); callback.onReceivedPaymentData(json); } catch (Exception e) { callback.onGooglePayError(Status.RESULT_INTERNAL_ERROR); } } else if (resultCode == Activity.RESULT_CANCELED) { callback.onGooglePayCancelled(); } else if (resultCode == AutoResolveHelper.RESULT_ERROR) { Status status = AutoResolveHelper.getStatusFromIntent(data); callback.onGooglePayError(status); } return true; } return false; } Gateway(); String getMerchantId(); Gateway setMerchantId(String merchantId); Region getRegion(); Gateway setRegion(Region region); void updateSession(String sessionId, String apiVersion, GatewayMap payload, GatewayCallback callback); Single<GatewayMap> updateSession(String sessionId, String apiVersion, GatewayMap payload); static void start3DSecureActivity(Activity activity, String html); static void start3DSecureActivity(Activity activity, String html, String title); static boolean handle3DSecureResult(int requestCode, int resultCode, Intent data, Gateway3DSecureCallback callback); static void requestGooglePayData(PaymentsClient paymentsClient, PaymentDataRequest request, Activity activity); static boolean handleGooglePayResult(int requestCode, int resultCode, Intent data, GatewayGooglePayCallback callback); }### Answer:
@Test public void testHandleGooglePayResultReturnsFalseWithNullCallback() { assertFalse(Gateway.handleGooglePayResult(0, 0, null, null)); }
@Test public void testHandleGooglePayResultReturnsFalseIfInvalidRequestCode() { int invalidRequestCode = 10; GatewayGooglePayCallback callback = mock(GatewayGooglePayCallback.class); assertFalse(Gateway.handleGooglePayResult(invalidRequestCode, 0, null, callback)); }
@Test public void testHandleGooglePayResultCallsError() { int requestCode = Gateway.REQUEST_GOOGLE_PAY_LOAD_PAYMENT_DATA; int resultCode = AutoResolveHelper.RESULT_ERROR; Status mockStatus = mock(Status.class); Intent mockData = mock(Intent.class); doReturn(mockStatus).when(mockData).getParcelableExtra("com.google.android.gms.common.api.AutoResolveHelper.status"); GatewayGooglePayCallback callback = spy(new GatewayGooglePayCallback() { @Override public void onReceivedPaymentData(JSONObject paymentData) { fail("Should not have received payment data"); } @Override public void onGooglePayCancelled() { fail("Should not have called cancelled"); } @Override public void onGooglePayError(Status status) { assertEquals(mockStatus, status); } }); boolean result = Gateway.handleGooglePayResult(requestCode, resultCode, mockData, callback); assertTrue(result); verify(callback).onGooglePayError(any()); }
@Test public void testHandleGooglePayResultCallsCancelled() { int requestCode = Gateway.REQUEST_GOOGLE_PAY_LOAD_PAYMENT_DATA; int resultCode = Activity.RESULT_CANCELED; GatewayGooglePayCallback callback = mock(GatewayGooglePayCallback.class); boolean result = Gateway.handleGooglePayResult(requestCode, resultCode, null, callback); assertTrue(result); verify(callback).onGooglePayCancelled(); }
@Test public void testHandleGooglePayResultCallsPaymentDataOnSuccess() { int requestCode = Gateway.REQUEST_GOOGLE_PAY_LOAD_PAYMENT_DATA; int resultCode = Activity.RESULT_OK; PaymentData pData = PaymentData.fromJson("{}"); Intent data = new Intent(); pData.putIntoIntent(data); GatewayGooglePayCallback callback = mock(GatewayGooglePayCallback.class); boolean result = Gateway.handleGooglePayResult(requestCode, resultCode, data, callback); assertTrue(result); verify(callback).onReceivedPaymentData(any()); } |
### Question:
Gateway { String getApiUrl(String apiVersion) { if (Integer.valueOf(apiVersion) < MIN_API_VERSION) { throw new IllegalArgumentException("API version must be >= " + MIN_API_VERSION); } if (region == null) { throw new IllegalStateException("You must initialize the the Gateway instance with a Region before use"); } return "https: } Gateway(); String getMerchantId(); Gateway setMerchantId(String merchantId); Region getRegion(); Gateway setRegion(Region region); void updateSession(String sessionId, String apiVersion, GatewayMap payload, GatewayCallback callback); Single<GatewayMap> updateSession(String sessionId, String apiVersion, GatewayMap payload); static void start3DSecureActivity(Activity activity, String html); static void start3DSecureActivity(Activity activity, String html, String title); static boolean handle3DSecureResult(int requestCode, int resultCode, Intent data, Gateway3DSecureCallback callback); static void requestGooglePayData(PaymentsClient paymentsClient, PaymentDataRequest request, Activity activity); static boolean handleGooglePayResult(int requestCode, int resultCode, Intent data, GatewayGooglePayCallback callback); }### Answer:
@Test public void testGetApiUrlThrowsExceptionIfRegionIsNull() throws Exception { String apiVersion = "44"; gateway.region = null; try { String apiUrl = gateway.getApiUrl(apiVersion); fail("Null region should have caused illegal state exception"); } catch (Exception e) { assertTrue(e instanceof IllegalStateException); } }
@Test public void testGetApiUrlThrowsExceptionIfApiVersionIsLessThanMin() throws Exception { String apiVersion = String.valueOf(Gateway.MIN_API_VERSION - 1); try { String apiUrl = gateway.getApiUrl(apiVersion); fail("Api version less than minimum value should have caused illegal argument exception"); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } }
@Test public void testGetApiUrlWorksAsIntended() throws Exception { gateway.region = Gateway.Region.NORTH_AMERICA; String expectedUrl = "https: assertEquals(expectedUrl, gateway.getApiUrl(String.valueOf(Gateway.MIN_API_VERSION))); } |
### Question:
Gateway3DSecureActivity extends AppCompatActivity { String getExtraHtml() { Bundle extras = getIntent().getExtras(); if (extras != null) { return extras.getString(EXTRA_HTML); } return null; } static final String EXTRA_HTML; static final String EXTRA_TITLE; static final String EXTRA_ACS_RESULT; }### Answer:
@Test public void testGetExtraHtmlReturnsNullIfMissing() { Intent testIntent = new Intent(); doReturn(testIntent).when(activity).getIntent(); String html = activity.getExtraHtml(); assertNull(html); }
@Test public void testGetExtraHtmlReturnsValueIfExists() { String expectedHtml = "<html></html>"; Intent testIntent = new Intent(); testIntent.putExtra(Gateway3DSecureActivity.EXTRA_HTML, expectedHtml); doReturn(testIntent).when(activity).getIntent(); String html = activity.getExtraHtml(); assertEquals(expectedHtml, html); } |
### Question:
Gateway { String getUpdateSessionUrl(String sessionId, String apiVersion) { if (sessionId == null) { throw new IllegalArgumentException("Session Id may not be null"); } if (merchantId == null) { throw new IllegalStateException("You must initialize the the Gateway instance with a Merchant Id before use"); } return getApiUrl(apiVersion) + "/merchant/" + merchantId + "/session/" + sessionId; } Gateway(); String getMerchantId(); Gateway setMerchantId(String merchantId); Region getRegion(); Gateway setRegion(Region region); void updateSession(String sessionId, String apiVersion, GatewayMap payload, GatewayCallback callback); Single<GatewayMap> updateSession(String sessionId, String apiVersion, GatewayMap payload); static void start3DSecureActivity(Activity activity, String html); static void start3DSecureActivity(Activity activity, String html, String title); static boolean handle3DSecureResult(int requestCode, int resultCode, Intent data, Gateway3DSecureCallback callback); static void requestGooglePayData(PaymentsClient paymentsClient, PaymentDataRequest request, Activity activity); static boolean handleGooglePayResult(int requestCode, int resultCode, Intent data, GatewayGooglePayCallback callback); }### Answer:
@Test public void testGetUpdateSessionUrlThrowsExceptionIfSessionIdIsNull() throws Exception { try { gateway.getUpdateSessionUrl(null, String.valueOf(Gateway.MIN_API_VERSION)); fail("Null session id should throw illegal argument exception"); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } }
@Test public void testGetUpdateSessionUrlThrowsExceptionIfMerchantIdIsNull() throws Exception { gateway.merchantId = null; try { String url = gateway.getUpdateSessionUrl("sess1234", String.valueOf(Gateway.MIN_API_VERSION)); fail("Null merchant id should have caused illegal state exception"); } catch (Exception e) { assertTrue(e instanceof IllegalStateException); } }
@Test public void testGetUpdateSessionUrlWorksAsIntended() throws Exception { gateway.merchantId = "somemerchant"; gateway.region = Gateway.Region.NORTH_AMERICA; String expectedUrl = "https: String actualUrl = gateway.getUpdateSessionUrl("sess1234", String.valueOf(Gateway.MIN_API_VERSION)); assertEquals(expectedUrl, actualUrl); } |
### Question:
Gateway { @SuppressWarnings("unchecked") boolean handleCallbackMessage(GatewayCallback callback, Object arg) { if (callback != null) { if (arg instanceof Throwable) { callback.onError((Throwable) arg); } else { callback.onSuccess((GatewayMap) arg); } } return true; } Gateway(); String getMerchantId(); Gateway setMerchantId(String merchantId); Region getRegion(); Gateway setRegion(Region region); void updateSession(String sessionId, String apiVersion, GatewayMap payload, GatewayCallback callback); Single<GatewayMap> updateSession(String sessionId, String apiVersion, GatewayMap payload); static void start3DSecureActivity(Activity activity, String html); static void start3DSecureActivity(Activity activity, String html, String title); static boolean handle3DSecureResult(int requestCode, int resultCode, Intent data, Gateway3DSecureCallback callback); static void requestGooglePayData(PaymentsClient paymentsClient, PaymentDataRequest request, Activity activity); static boolean handleGooglePayResult(int requestCode, int resultCode, Intent data, GatewayGooglePayCallback callback); }### Answer:
@Test public void testHandleCallbackMessageCallsOnErrorWithThrowableArg() throws Exception { GatewayCallback callback = mock(GatewayCallback.class); Throwable arg = new Exception("Some exception"); gateway.handleCallbackMessage(callback, arg); verify(callback).onError(arg); }
@Test public void testHandleCallbackMessageCallsSuccessWithNonThrowableArg() throws Exception { GatewayCallback callback = mock(GatewayCallback.class); GatewayMap arg = mock(GatewayMap.class); gateway.handleCallbackMessage(callback, arg); verify(callback).onSuccess(arg); } |
### Question:
Gateway { boolean isStatusCodeOk(int statusCode) { return (statusCode >= 200 && statusCode < 300); } Gateway(); String getMerchantId(); Gateway setMerchantId(String merchantId); Region getRegion(); Gateway setRegion(Region region); void updateSession(String sessionId, String apiVersion, GatewayMap payload, GatewayCallback callback); Single<GatewayMap> updateSession(String sessionId, String apiVersion, GatewayMap payload); static void start3DSecureActivity(Activity activity, String html); static void start3DSecureActivity(Activity activity, String html, String title); static boolean handle3DSecureResult(int requestCode, int resultCode, Intent data, Gateway3DSecureCallback callback); static void requestGooglePayData(PaymentsClient paymentsClient, PaymentDataRequest request, Activity activity); static boolean handleGooglePayResult(int requestCode, int resultCode, Intent data, GatewayGooglePayCallback callback); }### Answer:
@Test public void testIsStatusOkWorksAsIntended() { int tooLow = 199; int tooHigh = 300; int justRight = 200; assertFalse(gateway.isStatusCodeOk(tooLow)); assertFalse(gateway.isStatusCodeOk(tooHigh)); assertTrue(gateway.isStatusCodeOk(justRight)); } |
### Question:
Gateway { String inputStreamToString(InputStream is) throws IOException { BufferedReader rd = new BufferedReader(new InputStreamReader(is)); StringBuilder total = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { total.append(line); } return total.toString(); } Gateway(); String getMerchantId(); Gateway setMerchantId(String merchantId); Region getRegion(); Gateway setRegion(Region region); void updateSession(String sessionId, String apiVersion, GatewayMap payload, GatewayCallback callback); Single<GatewayMap> updateSession(String sessionId, String apiVersion, GatewayMap payload); static void start3DSecureActivity(Activity activity, String html); static void start3DSecureActivity(Activity activity, String html, String title); static boolean handle3DSecureResult(int requestCode, int resultCode, Intent data, Gateway3DSecureCallback callback); static void requestGooglePayData(PaymentsClient paymentsClient, PaymentDataRequest request, Activity activity); static boolean handleGooglePayResult(int requestCode, int resultCode, Intent data, GatewayGooglePayCallback callback); }### Answer:
@Test public void testInputStreamToStringWorksAsExpected() { String expectedResult = "here is some string data"; InputStream testInputStream = new StringInputStream(expectedResult); try { String result = gateway.inputStreamToString(testInputStream); assertEquals(expectedResult, result); } catch (IOException e) { fail(e.getMessage()); } } |
### Question:
Gateway { String createAuthHeader(String sessionId) { String value = "merchant." + merchantId + ":" + sessionId; return "Basic " + Base64.encodeToString(value.getBytes(), Base64.NO_WRAP); } Gateway(); String getMerchantId(); Gateway setMerchantId(String merchantId); Region getRegion(); Gateway setRegion(Region region); void updateSession(String sessionId, String apiVersion, GatewayMap payload, GatewayCallback callback); Single<GatewayMap> updateSession(String sessionId, String apiVersion, GatewayMap payload); static void start3DSecureActivity(Activity activity, String html); static void start3DSecureActivity(Activity activity, String html, String title); static boolean handle3DSecureResult(int requestCode, int resultCode, Intent data, Gateway3DSecureCallback callback); static void requestGooglePayData(PaymentsClient paymentsClient, PaymentDataRequest request, Activity activity); static boolean handleGooglePayResult(int requestCode, int resultCode, Intent data, GatewayGooglePayCallback callback); }### Answer:
@Test public void testCreateAuthHeaderWorksAsExpected() { String sessionId = "somesession"; gateway.merchantId = "MERCHANT_ID"; String expectedAuthHeader = "Basic bWVyY2hhbnQuTUVSQ0hBTlRfSUQ6c29tZXNlc3Npb24="; String authHeader = gateway.createAuthHeader(sessionId); assertEquals(expectedAuthHeader, authHeader); } |
### Question:
Gateway3DSecureActivity extends AppCompatActivity { void setWebViewHtml(String html) { String encoded = Base64.encodeToString(html.getBytes(), Base64.NO_PADDING | Base64.NO_WRAP); webView.loadData(encoded, "text/html", "base64"); } static final String EXTRA_HTML; static final String EXTRA_TITLE; static final String EXTRA_ACS_RESULT; }### Answer:
@Test public void testSetWebViewHtmlEncodesBase64() { String testHtml = "<html></html>"; String expectedEncodedHtml = "PGh0bWw+PC9odG1sPg"; activity.webView = mock(WebView.class); activity.setWebViewHtml(testHtml); verify(activity.webView).loadData(expectedEncodedHtml, "text/html", "base64"); } |
### Question:
Gateway3DSecureActivity extends AppCompatActivity { void intentToEmail(Uri uri) { Intent emailIntent = new Intent(Intent.ACTION_SENDTO); intentToEmail(uri, emailIntent); } static final String EXTRA_HTML; static final String EXTRA_TITLE; static final String EXTRA_ACS_RESULT; }### Answer:
@Test public void testIntentToEmailWorksAsExpected() { Uri testUri = mock(Uri.class); Intent testIntent = new Intent(); activity.intentToEmail(testUri, testIntent); int flags = testIntent.getFlags(); assertNotEquals(0, flags & Intent.FLAG_ACTIVITY_NEW_TASK); assertEquals(testUri, testIntent.getData()); verify(activity).startActivity(testIntent); } |
### Question:
Gateway3DSecureActivity extends AppCompatActivity { void complete(String acsResult) { Intent intent = new Intent(); complete(acsResult, intent); } static final String EXTRA_HTML; static final String EXTRA_TITLE; static final String EXTRA_ACS_RESULT; }### Answer:
@Test public void testCompleteWorksAsExpected() { String testAcsResult = "test result"; Intent testIntent = new Intent(); activity.complete(testAcsResult, testIntent); assertTrue(testIntent.hasExtra(Gateway3DSecureActivity.EXTRA_ACS_RESULT)); assertEquals(testAcsResult, testIntent.getStringExtra(Gateway3DSecureActivity.EXTRA_ACS_RESULT)); verify(activity).setResult(Activity.RESULT_OK, testIntent); verify(activity).finish(); } |
### Question:
Gateway3DSecureActivity extends AppCompatActivity { String getACSResultFromUri(Uri uri) { String result = null; Set<String> params = uri.getQueryParameterNames(); for (String param : params) { if ("acsResult".equalsIgnoreCase(param)) { result = uri.getQueryParameter(param); } } return result; } static final String EXTRA_HTML; static final String EXTRA_TITLE; static final String EXTRA_ACS_RESULT; }### Answer:
@Test public void testGetAcsResultFromUriWorksAsExpected() { Uri testUri = Uri.parse("gatewaysdk: String result = activity.getACSResultFromUri(testUri); assertEquals("{}", result); } |
### Question:
GatewaySSLContextProvider { X509Certificate readCertificate(String cert) throws CertificateException { byte[] bytes = cert.getBytes(); InputStream is = new ByteArrayInputStream(bytes); return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is); } GatewaySSLContextProvider(); }### Answer:
@Test public void testReadingInternalCertificateWorksAsExpected() throws Exception { X509Certificate certificate = trustProvider.readCertificate(GatewaySSLContextProvider.INTERMEDIATE_CA); String expectedSerialNo = "1372807406"; assertNotNull(certificate); assertEquals(expectedSerialNo, certificate.getSerialNumber().toString()); } |
### Question:
GatewayMap extends LinkedHashMap<String, Object> { @Override public Object put(String keyPath, Object value) { String[] properties = keyPath.split("\\."); Map<String, Object> destinationObject = this; if (properties.length > 1) { for (int i = 0; i < (properties.length - 1); i++) { String property = properties[i]; if (property.contains("[")) { destinationObject = getDestinationMap(property, destinationObject, i == properties.length - 1); } else { destinationObject = getPropertyMapFrom(property, destinationObject); } } } else if (keyPath.contains("[")) { destinationObject = getDestinationMap(keyPath, this, true); } if (destinationObject == this) { return super.put(keyPath, value); } else if (value instanceof Map) { destinationObject.clear(); GatewayMap m = new GatewayMap(); m.putAll((Map<? extends String, ? extends Object>) value); destinationObject.put(properties[properties.length - 1], m); return destinationObject; } else { return destinationObject.put(properties[properties.length - 1], value); } } GatewayMap(int initialCapacity, float loadFactor); GatewayMap(int initialCapacity); GatewayMap(); GatewayMap(Map<String, Object> map); GatewayMap(String jsonMapString); GatewayMap(String keyPath, Object value); @Override Object put(String keyPath, Object value); GatewayMap set(String keyPath, Object value); @Override Object get(Object keyPath); @Override boolean containsKey(Object keyPath); @Override Object remove(Object keyPath); static Map<String, Object> normalize(Map<String, Object> m); }### Answer:
@Test public void cannotOverrideNestedMap() { GatewayMap map = new GatewayMap(); map.put("a", 1); try { map.put("a.b", 2); fail("IllegalArgumentException not raised"); } catch (IllegalArgumentException e) { } catch (Exception e) { fail("Exception " + e + " thrown"); } } |
### Question:
ForkedFrameworkFactory { public RemoteFramework fork(List<String> vmArgs, Map<String, String> systemProperties, Map<String, Object> frameworkProperties, List<String> beforeFrameworkClasspath, List<String> afterFrameworkClasspath) { port = getPort(); LOG.debug("using RMI registry at port {}", port); String rmiName = "ExamRemoteFramework-" + UUID.randomUUID().toString(); try { String address = InetAddress.getLoopbackAddress().getHostAddress(); System.setProperty("java.rmi.server.hostname", address); registry = LocateRegistry.createRegistry(port); Map<String, String> systemPropsNew = new HashMap<>(systemProperties); systemPropsNew.put("java.rmi.server.hostname", address); systemPropsNew.put(RemoteFramework.RMI_PORT_KEY, Integer.toString(port)); systemPropsNew.put(RemoteFramework.RMI_NAME_KEY, rmiName); String[] vmOptions = buildSystemProperties(vmArgs, systemPropsNew); String[] args = buildFrameworkProperties(frameworkProperties); javaRunner = new ExamJavaRunner(false); javaRunner.exec(vmOptions, buildClasspath(beforeFrameworkClasspath, afterFrameworkClasspath), RemoteFrameworkImpl.class.getName(), args, getJavaHome(), null); return findRemoteFramework(address, port, rmiName); } catch (RemoteException | ExecutionException | URISyntaxException exc) { throw new TestContainerException(exc); } } ForkedFrameworkFactory(FrameworkFactory frameworkFactory); FrameworkFactory getFrameworkFactory(); void setFrameworkFactory(FrameworkFactory frameworkFactory); RemoteFramework fork(List<String> vmArgs, Map<String, String> systemProperties,
Map<String, Object> frameworkProperties, List<String> beforeFrameworkClasspath,
List<String> afterFrameworkClasspath); RemoteFramework fork(List<String> vmArgs, Map<String, String> systemProperties,
Map<String, Object> frameworkProperties); void join(); }### Answer:
@Test(expected = TestContainerException.class) public void forkWithInvalidBootClasspath() throws BundleException, IOException, InterruptedException, NotBoundException, URISyntaxException { ServiceLoader<FrameworkFactory> loader = ServiceLoader.load(FrameworkFactory.class); FrameworkFactory frameworkFactory = loader.iterator().next(); ForkedFrameworkFactory forkedFactory = new ForkedFrameworkFactory(frameworkFactory); List<String> bootClasspath = Arrays.asList( CoreOptions.maven("org.kohsuke.metainf-services", "metainf-services", "1.2").getURL() ); Map<String, Object> frameworkProperties = new HashMap<String, Object>(); frameworkProperties.put(Constants.FRAMEWORK_STORAGE, storage.getAbsolutePath()); frameworkProperties.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.kohsuke.metainf_services"); forkedFactory.fork(Collections.<String> emptyList(), Collections.<String, String> emptyMap(), frameworkProperties, null, bootClasspath); } |
### Question:
ForkedFrameworkFactory { protected int getPort() { String configuredPort = System.getProperty(EXAM_FORKED_INVOKER_PORT); if (configuredPort != null) { return Integer.parseInt(configuredPort); } else { int lowerBound = Integer.parseInt(System.getProperty(EXAM_FORKED_INVOKER_PORT_RANGE_LOWERBOUND, "21000")); int upperBound = Integer.parseInt(System.getProperty(EXAM_FORKED_INVOKER_PORT_RANGE_UPPERBOUND, "21099")); return new FreePort(lowerBound, upperBound).getPort(); } } ForkedFrameworkFactory(FrameworkFactory frameworkFactory); FrameworkFactory getFrameworkFactory(); void setFrameworkFactory(FrameworkFactory frameworkFactory); RemoteFramework fork(List<String> vmArgs, Map<String, String> systemProperties,
Map<String, Object> frameworkProperties, List<String> beforeFrameworkClasspath,
List<String> afterFrameworkClasspath); RemoteFramework fork(List<String> vmArgs, Map<String, String> systemProperties,
Map<String, Object> frameworkProperties); void join(); }### Answer:
@Test() public void verifyPortConfiguration() throws Exception { ForkedFrameworkFactory frameworkFactory = new ForkedFrameworkFactory(null); new SystemPropertyRunnable(org.ops4j.pax.exam.Constants.EXAM_FORKED_INVOKER_PORT, "15000") { @Override protected void doRun() { Assert.assertThat(frameworkFactory.getPort(), CoreMatchers.equalTo(15000)); } }.run(); new SystemPropertyRunnable(org.ops4j.pax.exam.Constants.EXAM_FORKED_INVOKER_PORT_RANGE_LOWERBOUND, "15000") { @Override protected void doRun() { Assert.assertThat(frameworkFactory.getPort(), CoreMatchers.equalTo(15000)); } }.run(); } |
### Question:
DependenciesDeployer { static void writeDependenciesFeature(Writer writer, ProvisionOption<?>... provisionOptions) { XMLOutputFactory xof = XMLOutputFactory.newInstance(); xof.setProperty("javax.xml.stream.isRepairingNamespaces", true); XMLStreamWriter sw = null; try { sw = xof.createXMLStreamWriter(writer); sw.writeStartDocument("UTF-8", "1.0"); sw.setDefaultNamespace(KARAF_FEATURE_NS); sw.writeCharacters("\n"); sw.writeStartElement("features"); sw.writeAttribute("name", "test-dependencies"); sw.writeCharacters("\n"); sw.writeStartElement("feature"); sw.writeAttribute("name", "test-dependencies"); sw.writeCharacters("\n"); for (ProvisionOption<?> provisionOption : provisionOptions) { if (provisionOption.getURL().startsWith("link") || provisionOption.getURL().startsWith("scan-features")) { continue; } sw.writeStartElement("bundle"); if (provisionOption.getStartLevel() != null) { sw.writeAttribute("start-level", provisionOption.getStartLevel().toString()); } sw.writeCharacters(provisionOption.getURL()); endElement(sw); } endElement(sw); endElement(sw); sw.writeEndDocument(); } catch (XMLStreamException e) { throw new RuntimeException("Error writing feature " + e.getMessage(), e); } finally { close(sw); } } DependenciesDeployer(ExamSystem subsystem, File karafBase, File karafHome); void copyBootClasspathLibraries(); void copyReferencedArtifactsToDeployFolder(); KarafFeaturesOption getDependenciesFeature(); }### Answer:
@Test public void testEncoding() { WrappedUrlProvisionOption option = wrappedBundle(mavenBundle("mygroup", "myArtifactId", "1.0")); option.instructions("Export-Package=my.package.*"); option.overwriteManifest(OverwriteMode.MERGE); StringWriter wr = new StringWriter(); DependenciesDeployer.writeDependenciesFeature(wr, option); Assert.assertThat(wr.toString(), StringContains.containsString("<bundle>wrap:mvn:mygroup/myArtifactId/1.0$overwrite=MERGE&Export-Package=my.package.*</bundle>")); }
@Test public void testDependencyFeature() { MavenArtifactProvisionOption option = mavenBundle().groupId("mygroup").artifactId("myArtifactId").version("1.0"); StringWriter wr = new StringWriter(); DependenciesDeployer.writeDependenciesFeature(wr, option); Assert.assertEquals( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<features xmlns=\"http: "<feature name=\"test-dependencies\">\n" + "<bundle>mvn:mygroup/myArtifactId/1.0</bundle>\n" + "</feature>\n" + "</features>\n", wr.toString()); }
@Test public void testDependencyFeatureWithBundleStartLevel() { MavenArtifactProvisionOption option = mavenBundle().groupId("mygroup").artifactId("myArtifactId").version("1.0").startLevel(42); StringWriter wr = new StringWriter(); DependenciesDeployer.writeDependenciesFeature(wr, option); Assert.assertEquals( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<features xmlns=\"http: "<feature name=\"test-dependencies\">\n" + "<bundle start-level=\"42\">mvn:mygroup/myArtifactId/1.0</bundle>\n" + "</feature>\n" + "</features>\n", wr.toString()); } |
### Question:
JavaVersionUtil { public static int getMajorVersion() { return getMajorVersion(System.getProperty("java.specification.version")); } static int getMajorVersion(); }### Answer:
@Test public void testVersions() { assertEquals(8, JavaVersionUtil.getMajorVersion("1.8.0_171")); assertEquals(9, JavaVersionUtil.getMajorVersion("9")); assertEquals(10, JavaVersionUtil.getMajorVersion("10")); assertEquals(11, JavaVersionUtil.getMajorVersion("11")); } |
### Question:
KarafConfigFile extends KarafConfigurationFile { @Override public void store() throws IOException { final FileOutputStream fos = new FileOutputStream(file); ConfigurationHandler.write(fos, configuration); fos.close(); } KarafConfigFile(File karafHome, String location); @Override void store(); @SuppressWarnings("unchecked") @Override void load(); @Override void put(final String key, final Object value); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override void extend(final String key, final Object value); @Override Object get(final String key); }### Answer:
@Test public void store() throws Exception { final int[] ints = {1, 2, 3, 4}; final Dictionary<String, Object> configuration = new Hashtable<>(); configuration.put("ints", ints); final FileOutputStream fos = new FileOutputStream("target/store.config"); ConfigurationHandler.write(fos, configuration); fos.close(); } |
### Question:
KarafConfigFile extends KarafConfigurationFile { @SuppressWarnings("unchecked") @Override public void load() throws IOException { if (!file.exists()) { return; } final FileInputStream fis = new FileInputStream(file); configuration = ConfigurationHandler.read(fis); fis.close(); } KarafConfigFile(File karafHome, String location); @Override void store(); @SuppressWarnings("unchecked") @Override void load(); @Override void put(final String key, final Object value); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override void extend(final String key, final Object value); @Override Object get(final String key); }### Answer:
@Test public void load() throws Exception { final int[] expected = {1, 2, 3, 4}; final KarafConfigFile karafConfigFile = new KarafConfigFile(KARAF_ETC, "etc/ints_4.config"); karafConfigFile.load(); final int[] ints = (int[]) karafConfigFile.get("ints"); assertArrayEquals(expected, ints); } |
### Question:
KarafConfigFile extends KarafConfigurationFile { @Override public void put(final String key, final Object value) { configuration.put(key, value); } KarafConfigFile(File karafHome, String location); @Override void store(); @SuppressWarnings("unchecked") @Override void load(); @Override void put(final String key, final Object value); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override void extend(final String key, final Object value); @Override Object get(final String key); }### Answer:
@Test public void put() throws Exception { final Double d = 2D; final KarafConfigFile karafConfigFile = new KarafConfigFile(KARAF_ETC, "etc/na.config"); karafConfigFile.put("Double", d); } |
### Question:
KarafConfigFile extends KarafConfigurationFile { @Override public Object get(final String key) { return configuration.get(key); } KarafConfigFile(File karafHome, String location); @Override void store(); @SuppressWarnings("unchecked") @Override void load(); @Override void put(final String key, final Object value); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override void extend(final String key, final Object value); @Override Object get(final String key); }### Answer:
@Test public void get() throws Exception { final String in = "value"; final KarafConfigFile karafConfigFile = new KarafConfigFile(KARAF_ETC, "etc/na.config"); karafConfigFile.put("key", in); final Object out = karafConfigFile.get("key"); assertEquals(in, out); } |
### Question:
FileFinder { public static File findFile(File rootDir, final String fileName) { FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.equals(fileName); } }; return findFile(rootDir, filter); } private FileFinder(); static File findFile(File rootDir, final String fileName); static File findFile(File rootDir, FilenameFilter filter); }### Answer:
@Test public void findFileInTree() { File rootDir = new File("src/main/java"); File file = FileFinder.findFile(rootDir, "FileFinder.java"); assertFilePath(file, "src/main/java/org/ops4j/pax/exam/spi/war/FileFinder.java"); }
@Test public void findFileInRoot() { File rootDir = new File("src/main/java/org/ops4j/pax/exam/spi/war"); File file = FileFinder.findFile(rootDir, "FileFinder.java"); assertFilePath(file, "src/main/java/org/ops4j/pax/exam/spi/war/FileFinder.java"); }
@Test public void findFileWithFilter() { File rootDir = new File("src/main/java/"); FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.startsWith("Zip"); } }; File file = FileFinder.findFile(rootDir, filter); assertFilePath(file, "src/main/java/org/ops4j/pax/exam/spi/war/ZipBuilder.java"); }
@Test public void findDirectory() { File rootDir = new File("src"); File file = FileFinder.findFile(rootDir, "java"); assertFilePath(file, "src/main/java"); }
@Test public void findSubdirectory() { File rootDir = new File("src/test"); File file = FileFinder.findFile(rootDir, "java"); assertFilePath(file, "src/test/java"); } |
### Question:
WarBuilder { public URI buildWar() { if (option.getName() == null) { option.name(UUID.randomUUID().toString()); } processClassPath(); try { File webResourceDir = getWebResourceDir(); File probeWar = new File(tempDir, option.getName() + ".war"); ZipBuilder builder = new ZipBuilder(probeWar); for (String library : option.getLibraries()) { File file = toLocalFile(library); if (file.isDirectory()) { file = toJar(file); } LOG.debug("including library {} = {}", library, file); builder.addFile(file, "WEB-INF/lib/" + file.getName()); } builder.addDirectory(webResourceDir, ""); builder.close(); URI warUri = probeWar.toURI(); LOG.info("WAR probe = {}", warUri); return warUri; } catch (IOException exc) { throw new TestContainerException(exc); } } WarBuilder(File tempDir, WarProbeOption option); URI buildWar(); }### Answer:
@Test public void buildWar() throws MalformedURLException, IOException { war = localCopy(warProbe().library("target/classes")); assertThat(war.getEntry("WEB-INF/beans.xml"), is(notNullValue())); assertThat(war.getEntry("WEB-INF/lib/pax-exam-spi-" + Info.getPaxExamVersion() + ".jar"), is(notNullValue())); }
@Test public void buildWarWithName() throws MalformedURLException, IOException { WarBuilder warBuilder = new WarBuilder(DefaultExamSystem.createTempDir(), warProbe().library("target/classes").name("foo")); URI uri = warBuilder.buildWar(); assertThat(new File(uri).getName(), is("foo.war")); } |
### Question:
RemoteBundleContextImpl implements RemoteBundleContext, Serializable { @Override public Object remoteCall(final Class<?> serviceType, final String methodName, final Class<?>[] methodParams, String filter, final RelativeTimeout timeout, final Object... actualParams) throws NoSuchServiceException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { LOG.trace("Remote call of [" + serviceType.getName() + "." + methodName + "]"); Object service = ServiceLookup.getService(bundleContext, serviceType, timeout.getValue(), filter); Object obj = null; try { obj = serviceType.getMethod(methodName, methodParams).invoke(service, actualParams); } catch (InvocationTargetException t) { if (t.getTargetException().getCause() instanceof RerunTestException) { LOG.debug("rerun the test"); service = ServiceLookup.getService(bundleContext, serviceType, timeout.getValue(), filter); obj = serviceType.getMethod(methodName, methodParams).invoke(service, actualParams); } else { throw t; } } return obj; } RemoteBundleContextImpl(final BundleContext bundleContext); @Override Object remoteCall(final Class<?> serviceType, final String methodName,
final Class<?>[] methodParams, String filter, final RelativeTimeout timeout,
final Object... actualParams); @Override long installBundle(final String bundleUrl); @Override long installBundle(final String bundleLocation, final byte[] bundle); @Override void uninstallBundle(long id); @Override void startBundle(long bundleId); @Override void stopBundle(long bundleId); @Override void setBundleStartLevel(long bundleId, int startLevel); @Override void waitForState(final long bundleId, final int state, final RelativeTimeout timeout); }### Answer:
@Test public void testfilterWasUsedForProbeInvoker() throws Exception { BundleContext bundleContext = mock(BundleContext.class); RemoteBundleContextImpl remoteBundleContext = new RemoteBundleContextImpl(bundleContext); String rightFilter = "(Probe-Signature=PAXPROBE-the-right-one)"; when(bundleContext.createFilter(anyString())).thenReturn(null); try{ remoteBundleContext.remoteCall(RemoteBundleContextImplTest.class, "filterWasUsedForProbeInvoker", new Class<?>[] {}, rightFilter, RelativeTimeout.TIMEOUT_DEFAULT, new Object[] {}); } catch(NullPointerException e) { } verify(bundleContext).createFilter(contains(rightFilter)); } |
### Question:
ConfigurationManager { public void loadSystemProperties(String configurationKey) { String propertyRef = getProperty(configurationKey); if (propertyRef == null) { return; } if (propertyRef.startsWith("env:")) { propertyRef = propertyRef.substring(4); propertyRef = System.getenv(propertyRef); } if (!propertyRef.startsWith("/")) { propertyRef = "/" + propertyRef; } try { URL url = getClass().getResource(propertyRef); if (url == null) { url = new URL(propertyRef); } Properties props = System.getProperties(); props.load(url.openStream()); System.setProperties(props); } catch (IOException exc) { throw new TestContainerException(exc); } } ConfigurationManager(); String getProperty(String key); String getProperty(String key, String defaultValue); void loadSystemProperties(String configurationKey); }### Answer:
@Test public void loadSystemProperties() { ConfigurationManager cm = new ConfigurationManager(); assertThat(System.getProperty("exam.test.key1"), is(nullValue())); assertThat(System.getProperty("exam.test.key2"), is(nullValue())); String cp = System.getProperty("java.class.path"); cm.loadSystemProperties("exam.test.props"); assertThat(System.getProperty("exam.test.key1"), is("value1")); assertThat(System.getProperty("exam.test.key2"), is("value2")); assertThat(System.getProperty("java.class.path"), is(cp)); } |
### Question:
AdminHandler { public Result showAdmin(Context context) { return Results.html(); } Result showAdmin(Context context); Result showUsers(Context context); Result showSummedTransactions(Context context); Result pagedMTX(Context context, @Param("p") int page); Result deleteMTXProcess(@PathParam("time") Integer time, Context context); Result activateUserProcess(@PathParam("id") Long userId, Context context); Result promoteUserProcess(@PathParam("id") Long userId, Context context); Result deleteUserProcess(@PathParam("id") Long deleteUserId, Context context); Result jsonUserSearch(Context context); @FilterWith(WhitelistFilter.class) Result showDomainWhitelist(Context context); @FilterWith(WhitelistFilter.class) Result callRemoveDomain(Context context, @Param("removeDomainsSelection") Long remDomainId); @FilterWith(WhitelistFilter.class) Result handleRemoveDomain(Context context, @Param("action") String action, @Param("domainId") long domainId); @FilterWith(WhitelistFilter.class) Result addDomain(Context context, @Param("domainName") String domainName); Result showEmailStatistics(Context context, @Param("dayPage") int dayPage, @Param("weekPage") int weekPage,
@Param("sortDailyList") String sortDailyList,
@Param("sortWeeklyList") String sortWeeklyList); Result getEmailSenderTablePage(Context context, @Param("scope") String scope, @Param("page") int page,
@Param("offset") int offset, @Param("limit") int limit,
@Param("sort") String sort, @Param("order") String order); }### Answer:
@Test public void testShowAdmin() { result = ninjaTestBrowser.makeRequest(ninjaTestServer.getBaseUrl() + "/admin"); assertTrue(!result.contains("<li class=\"active\">")); assertFalse(result.contains("FreeMarker template error")); assertFalse(result.contains("<title>404 - not found</title>")); } |
### Question:
MailboxApiController extends AbstractApiController { public Result createMailbox(@JSR303Validation final MailboxData mailboxData, @Attribute("user") final User user, final Context context) { if (context.getValidation().hasViolations()) { return ApiResults.badRequest(context.getValidation().getViolations()); } return doCreateMailbox(mailboxData, user); } Result listMailboxes(@Attribute("userId") @DbId final Long userId, final Context context); Result createMailbox(@JSR303Validation final MailboxData mailboxData, @Attribute("user") final User user,
final Context context); Result getMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@Attribute("userId") @DbId final Long userId, final Context context); Result updateMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@JSR303Validation final MailboxData mailboxData,
@Attribute("userId") @DbId final Long userId, final Context context); Result deleteMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@Attribute("userId") @DbId final Long userId, final Context context); }### Answer:
@Test public void createMailbox_invalidEmail() throws Exception { final HttpResponse response = apiClient.createMailbox("foo(at)bar.com", System.currentTimeMillis(), false); RestApiTestUtils.validateStatusCode(response, 400); RestApiTestUtils.validateErrors(response, "address"); }
@Test public void createMailbox_unknownMailDomain() throws Exception { final HttpResponse response = apiClient.createMailbox("[email protected]", System.currentTimeMillis(), false); RestApiTestUtils.validateStatusCode(response, 403); }
@Test public void createMailbox() throws Exception { final String mailboxAddress = "[email protected]"; final long expirationDate = System.currentTimeMillis(); final boolean forwardEnabled = true; final HttpResponse response = apiClient.createMailbox(mailboxAddress, expirationDate, forwardEnabled); RestApiTestUtils.validateStatusCode(response, 201); final MailboxData mailboxData = RestApiTestUtils.getResponseBodyAs(response, MailboxData.class); RestApiTestUtils.validateMailboxData(mailboxData, mailboxAddress, expirationDate, forwardEnabled); MBox mailbox = MBox.getByAddress(mailboxData.address); RestApiTestUtils.validateMailbox(mailbox, mailboxData); }
@Test public void createMailbox_emailAlreadyTakenBySameUser() throws Exception { MBox mailbox = TestDataUtils.createMailbox(user); final String mailboxAddress = mailbox.getFullAddress(); final long expirationDate = System.currentTimeMillis(); final boolean forwardEnabled = true; final HttpResponse response = apiClient.createMailbox(mailboxAddress, expirationDate, forwardEnabled); RestApiTestUtils.validateStatusCode(response, 200); final MailboxData mailboxData = RestApiTestUtils.getResponseBodyAs(response, MailboxData.class); RestApiTestUtils.validateMailboxData(mailboxData, mailboxAddress, expirationDate, forwardEnabled); mailbox = MBox.getById(mailbox.getId()); RestApiTestUtils.validateMailbox(mailbox, mailboxData); }
@Test public void createMailbox_emailAlreadyTakenByOtherUser() throws Exception { final User otherUser = TestDataUtils.createUser(); final MBox otherUsersMailbox = TestDataUtils.createMailbox(otherUser); final String mailboxAddress = otherUsersMailbox.getFullAddress(); final long expirationDate = System.currentTimeMillis(); final boolean forwardEnabled = true; final HttpResponse response = apiClient.createMailbox(mailboxAddress, expirationDate, forwardEnabled); RestApiTestUtils.validateStatusCode(response, 403); } |
### Question:
MailboxApiController extends AbstractApiController { public Result getMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress, @Attribute("userId") @DbId final Long userId, final Context context) { return performAction(userId, mailboxAddress, context, mailbox -> { final MailboxData mailboxData = new MailboxData(mailbox); return ApiResults.ok().render(mailboxData); }); } Result listMailboxes(@Attribute("userId") @DbId final Long userId, final Context context); Result createMailbox(@JSR303Validation final MailboxData mailboxData, @Attribute("user") final User user,
final Context context); Result getMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@Attribute("userId") @DbId final Long userId, final Context context); Result updateMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@JSR303Validation final MailboxData mailboxData,
@Attribute("userId") @DbId final Long userId, final Context context); Result deleteMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@Attribute("userId") @DbId final Long userId, final Context context); }### Answer:
@Test public void getMailbox() throws Exception { final MBox mailbox = TestDataUtils.createMailbox(user); final HttpResponse response = apiClient.getMailbox(mailbox.getFullAddress()); RestApiTestUtils.validateStatusCode(response, 200); final MailboxData mailboxData = RestApiTestUtils.getResponseBodyAs(response, MailboxData.class); RestApiTestUtils.validateMailboxData(mailboxData, mailbox); }
@Test public void getMailbox_invalidAddress() throws Exception { final HttpResponse response = apiClient.getMailbox(invalidAddress); RestApiTestUtils.validateStatusCode(response, 400); RestApiTestUtils.validateErrors(response, "mailboxAddress"); }
@Test public void getMailbox_unknownMailbox() throws Exception { final HttpResponse response = apiClient.getMailbox(unknownAddress); RestApiTestUtils.validateStatusCode(response, 404); } |
### Question:
MailboxApiController extends AbstractApiController { public Result updateMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress, @JSR303Validation final MailboxData mailboxData, @Attribute("userId") @DbId final Long userId, final Context context) { return performAction(userId, mailboxAddress, context, mailbox -> doUpdateMailbox(mailbox, mailboxData)); } Result listMailboxes(@Attribute("userId") @DbId final Long userId, final Context context); Result createMailbox(@JSR303Validation final MailboxData mailboxData, @Attribute("user") final User user,
final Context context); Result getMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@Attribute("userId") @DbId final Long userId, final Context context); Result updateMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@JSR303Validation final MailboxData mailboxData,
@Attribute("userId") @DbId final Long userId, final Context context); Result deleteMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@Attribute("userId") @DbId final Long userId, final Context context); }### Answer:
@Test public void updateMailbox() throws Exception { MBox mailbox = TestDataUtils.createMailbox(user); final String mailboxAddress = "[email protected]"; final long expirationDate = System.currentTimeMillis(); final boolean forwardEnabled = true; final HttpResponse response = apiClient.updateMailbox(mailbox.getFullAddress(), mailboxAddress, expirationDate, forwardEnabled); RestApiTestUtils.validateStatusCode(response, 200); final MailboxData mailboxData = RestApiTestUtils.getResponseBodyAs(response, MailboxData.class); RestApiTestUtils.validateMailboxData(mailboxData, mailboxAddress, expirationDate, forwardEnabled); mailbox = MBox.getById(mailbox.getId()); RestApiTestUtils.validateMailbox(mailbox, mailboxData); } |
### Question:
MailboxApiController extends AbstractApiController { public Result deleteMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress, @Attribute("userId") @DbId final Long userId, final Context context) { return performAction(userId, mailboxAddress, context, mailbox -> { mailbox.delete(); return ApiResults.noContent(); }); } Result listMailboxes(@Attribute("userId") @DbId final Long userId, final Context context); Result createMailbox(@JSR303Validation final MailboxData mailboxData, @Attribute("user") final User user,
final Context context); Result getMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@Attribute("userId") @DbId final Long userId, final Context context); Result updateMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@JSR303Validation final MailboxData mailboxData,
@Attribute("userId") @DbId final Long userId, final Context context); Result deleteMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@Attribute("userId") @DbId final Long userId, final Context context); }### Answer:
@Test public void deleteMailbox() throws Exception { final MBox mailbox = TestDataUtils.createMailbox(user); Assert.assertNotNull(MBox.getById(mailbox.getId())); final HttpResponse response = apiClient.deleteMailbox(mailbox.getFullAddress()); RestApiTestUtils.validateStatusCode(response, 204); Assert.assertNull(MBox.getById(mailbox.getId())); }
@Test public void deleteMailbox_invalidMailboxAddress() throws Exception { final HttpResponse response = apiClient.deleteMailbox(invalidAddress); RestApiTestUtils.validateStatusCode(response, 400); RestApiTestUtils.validateErrors(response, "mailboxAddress"); }
@Test public void deleteMailbox_unknownMailbox() throws Exception { final HttpResponse response = apiClient.deleteMailbox(unknownAddress); RestApiTestUtils.validateStatusCode(response, 404); } |
### Question:
AdminHandler { public Result jsonUserSearch(Context context) { List<User> userList; String searchString = context.getParameter("s", ""); userList = (searchString.equals("")) ? new ArrayList<User>() : User.findUserLike(searchString); UserFormData userData; List<UserFormData> userDatalist = new ArrayList<UserFormData>(); for (User currentUser : userList) { userData = UserFormData.prepopulate(currentUser); userDatalist.add(userData); } return Results.json().render(userDatalist); } Result showAdmin(Context context); Result showUsers(Context context); Result showSummedTransactions(Context context); Result pagedMTX(Context context, @Param("p") int page); Result deleteMTXProcess(@PathParam("time") Integer time, Context context); Result activateUserProcess(@PathParam("id") Long userId, Context context); Result promoteUserProcess(@PathParam("id") Long userId, Context context); Result deleteUserProcess(@PathParam("id") Long deleteUserId, Context context); Result jsonUserSearch(Context context); @FilterWith(WhitelistFilter.class) Result showDomainWhitelist(Context context); @FilterWith(WhitelistFilter.class) Result callRemoveDomain(Context context, @Param("removeDomainsSelection") Long remDomainId); @FilterWith(WhitelistFilter.class) Result handleRemoveDomain(Context context, @Param("action") String action, @Param("domainId") long domainId); @FilterWith(WhitelistFilter.class) Result addDomain(Context context, @Param("domainName") String domainName); Result showEmailStatistics(Context context, @Param("dayPage") int dayPage, @Param("weekPage") int weekPage,
@Param("sortDailyList") String sortDailyList,
@Param("sortWeeklyList") String sortWeeklyList); Result getEmailSenderTablePage(Context context, @Param("scope") String scope, @Param("page") int page,
@Param("offset") int offset, @Param("limit") int limit,
@Param("sort") String sort, @Param("order") String order); }### Answer:
@Test public void testJsonUserSearch() { formParams.clear(); formParams.put("s", ""); result = ninjaTestBrowser.makeRequest(ninjaTestServer.getBaseUrl() + "/admin/usersearch?s="); assertTrue(result.equals("[]")); assertFalse(result.contains("FreeMarker template error")); assertFalse(result.contains("<title>404 - not found</title>")); formParams.clear(); formParams.put("s", ""); result = ninjaTestBrowser.makeRequest(ninjaTestServer.getBaseUrl() + "/admin/usersearch?s=admi"); assertTrue(result.contains("[email protected]")); assertFalse(result.contains("FreeMarker template error")); assertFalse(result.contains("<title>404 - not found</title>")); } |
### Question:
MailApiController extends AbstractApiController { public Result getMail(@PathParam("mailId") @DbId final Long mailId, @Attribute("userId") @DbId final Long userId, final Context context) { return performAction(mailId, userId, context, mail -> { try { final MailData mailData = new MailData(mail); return ApiResults.ok().render(mailData); } catch (final Exception e) { log.error("Failed to parse MIME message", e); return ApiResults.internalServerError(); } }); } Result listMails(@Param("mailboxAddress") @Email final String mailboxAddress,
@Attribute("userId") @DbId final Long userId, final Context context); Result getMail(@PathParam("mailId") @DbId final Long mailId, @Attribute("userId") @DbId final Long userId,
final Context context); Result getMailAttachment(@PathParam("mailId") @DbId final Long mailId,
@PathParam("attachmentName") @NotBlank final String attachmentName,
@Attribute("userId") @DbId final Long userId, final Context context); Result deleteMail(@PathParam("mailId") @DbId final Long mailId, @Attribute("userId") @DbId final Long userId,
final Context context); }### Answer:
@Test public void getMail() throws Exception { final HttpResponse response = apiClient.getMail(mailId); RestApiTestUtils.validateStatusCode(response, 200); }
@Test public void getMail_someoneElsesMail() throws Exception { final HttpResponse response = apiClient.getMail(otherUsersMailId); RestApiTestUtils.validateStatusCode(response, 403); RestApiTestUtils.validateErrors(response, "mailId"); }
@Test public void getMail_invalidId() throws Exception { final HttpResponse response = apiClient.getMail(invalidId); RestApiTestUtils.validateStatusCode(response, 400); RestApiTestUtils.validateErrors(response, "mailId"); }
@Test public void getMail_unknownMail() throws Exception { final HttpResponse response = apiClient.getMail(unknownId); RestApiTestUtils.validateStatusCode(response, 404); } |
### Question:
MailApiController extends AbstractApiController { public Result getMailAttachment(@PathParam("mailId") @DbId final Long mailId, @PathParam("attachmentName") @NotBlank final String attachmentName, @Attribute("userId") @DbId final Long userId, final Context context) { return performAction(mailId, userId, context, mail -> { return serveMailAttachment(context, mail, attachmentName); }); } Result listMails(@Param("mailboxAddress") @Email final String mailboxAddress,
@Attribute("userId") @DbId final Long userId, final Context context); Result getMail(@PathParam("mailId") @DbId final Long mailId, @Attribute("userId") @DbId final Long userId,
final Context context); Result getMailAttachment(@PathParam("mailId") @DbId final Long mailId,
@PathParam("attachmentName") @NotBlank final String attachmentName,
@Attribute("userId") @DbId final Long userId, final Context context); Result deleteMail(@PathParam("mailId") @DbId final Long mailId, @Attribute("userId") @DbId final Long userId,
final Context context); }### Answer:
@Test public void getMailAttachment() throws Exception { HttpResponse response = apiClient.getMailAttachment(mailId, "test.pdf"); RestApiTestUtils.validateStatusCode(response, 200); RestApiTestUtils.validateResponseContent(response, "application/pdf", 89399); response = apiClient.getMailAttachment(mailId, "test.png"); RestApiTestUtils.validateStatusCode(response, 200); RestApiTestUtils.validateResponseContent(response, "image/png", 5799); }
@Test public void getMailAttachment_unknownName() throws Exception { final HttpResponse response = apiClient.getMailAttachment(mailId, "unknownAttachmentName"); RestApiTestUtils.validateStatusCode(response, 404); } |
### Question:
MailApiController extends AbstractApiController { public Result deleteMail(@PathParam("mailId") @DbId final Long mailId, @Attribute("userId") @DbId final Long userId, final Context context) { return performAction(mailId, userId, context, mail -> { mail.delete(); return ApiResults.noContent(); }); } Result listMails(@Param("mailboxAddress") @Email final String mailboxAddress,
@Attribute("userId") @DbId final Long userId, final Context context); Result getMail(@PathParam("mailId") @DbId final Long mailId, @Attribute("userId") @DbId final Long userId,
final Context context); Result getMailAttachment(@PathParam("mailId") @DbId final Long mailId,
@PathParam("attachmentName") @NotBlank final String attachmentName,
@Attribute("userId") @DbId final Long userId, final Context context); Result deleteMail(@PathParam("mailId") @DbId final Long mailId, @Attribute("userId") @DbId final Long userId,
final Context context); }### Answer:
@Test public void deleteMail() throws Exception { final Mail mail = TestDataUtils.createMailWithAttachments(mailbox); Assert.assertNotNull(Ebean.find(Mail.class, mail.getId())); final HttpResponse response = apiClient.deleteMail(String.valueOf(mail.getId())); RestApiTestUtils.validateStatusCode(response, 204); Assert.assertNull(Ebean.find(Mail.class, mail.getId())); }
@Test public void deleteMail_someoneElsesMail() throws Exception { final HttpResponse response = apiClient.deleteMail(otherUsersMailId); RestApiTestUtils.validateStatusCode(response, 403); RestApiTestUtils.validateErrors(response, "mailId"); }
@Test public void deleteMail_invalidMailId() throws Exception { final HttpResponse response = apiClient.deleteMail(invalidId); RestApiTestUtils.validateStatusCode(response, 400); RestApiTestUtils.validateErrors(response, "mailId"); }
@Test public void deleteMail_unknownMailId() throws Exception { final HttpResponse response = apiClient.deleteMail(unknownId); RestApiTestUtils.validateStatusCode(response, 404); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.