src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
CompositeRequestHandler implements RequestHandler { @Override public Publisher<Void> apply(HttpServerRequest request, HttpServerResponse response) { final long requestStartTime = System.currentTimeMillis(); try { for (RequestHandler handler : handlers) { Publisher<Void> result = handler.apply(request, response); if (result != null) { return Flux.from(result).onErrorResume(exception -> exceptionHandler .handleException(request, response, exception)); } } } catch (Exception exception) { return exceptionHandler.handleException(request, response, exception); } return Flux.from(exceptionHandler.handleException(request, response, new WebException(HttpResponseStatus.NOT_FOUND))) .doOnTerminate(() -> RequestLogger.logRequestResponse(request, response, requestStartTime, log)) .doOnSubscribe(s -> connectionCounter.increase()) .doFinally(s -> connectionCounter.decrease()); } @Inject CompositeRequestHandler(Set<RequestHandler> handlers, ExceptionHandler exceptionHandler, ConnectionCounter connectionCounter); @Override Publisher<Void> apply(HttpServerRequest request, HttpServerResponse response); } | @Test public void shouldOnlyCallOneRequestHandler() { AtomicInteger callCounter = new AtomicInteger(); requestHandlers.add((request, response) -> { callCounter.incrementAndGet(); return Flux.empty(); }); requestHandlers.add((request, response) -> { callCounter.incrementAndGet(); return Flux.empty(); }); Flux.from(compositeRequestHandler.apply(request, response)).count().block(); assertThat(callCounter.get()).isEqualTo(1); }
@Test public void exceptionHandlerShallBeInvokedByRuntimeException() { IllegalArgumentException illegalArgumentException = new IllegalArgumentException("expected exception"); when(exceptionHandler.handleException(request, response, illegalArgumentException)).thenReturn(Flux.empty()); requestHandlers.add((request, response) -> { throw illegalArgumentException; }); Flux.from(compositeRequestHandler.apply(request, response)).count().block(); verify(exceptionHandler, times(1)).handleException(request, response, illegalArgumentException); }
@Test public void exceptionHandlerShallBeInvokedWhenNoRequestHandlerIsGiven() { when(exceptionHandler.handleException(any(), any(), any())).thenReturn(Flux.empty()); IllegalArgumentException illegalArgumentException = new IllegalArgumentException("expected exception"); when(exceptionHandler.handleException(request, response, illegalArgumentException)).thenReturn(Flux.empty()); Flux.from(compositeRequestHandler.apply(request, response)).count().block(); verify(exceptionHandler, times(1)).handleException(any(), any(), any(WebException.class)); assertThat(connectionCounter.getCount()).isEqualTo(0); }
@Test public void exceptionHandlerShallBeInvokedWhenNullIsReturnedByRequestHandler() { when(response.status()).thenReturn(HttpResponseStatus.OK); requestHandlers.add((request, response) -> null); Flux.from(compositeRequestHandler.apply(request, response)).count().block(); verify(exceptionHandler, times(1)).handleException(any(), any(), any(WebException.class)); } |
JaxRsRequest { public Mono<JaxRsRequest> loadBody() { HttpMethod httpMethod = req.method(); if (POST.equals(httpMethod) || PUT.equals(httpMethod) || PATCH.equals(httpMethod) || DELETE.equals(httpMethod)) { return collector.collectBytes(req.receive() .doOnError(e -> LOG.error("Error reading data for request " + httpMethod + " " + req.uri(), e))) .defaultIfEmpty(new byte[0]) .map(reqBody -> create(req, matcher, reqBody, collector)); } return Mono.just(this); } protected JaxRsRequest(HttpServerRequest req, Matcher matcher, byte[] body, ByteBufCollector collector); JaxRsRequest(HttpServerRequest request); JaxRsRequest(HttpServerRequest request, ByteBufCollector collector); boolean hasMethod(HttpMethod httpMethod); byte[] getBody(); Mono<JaxRsRequest> loadBody(); String getQueryParam(String key); String getQueryParam(String key, String defaultValue); String getPathParam(String key); String getPathParam(String key, String defaultValue); String getHeader(String key); String getHeader(String key, String defaultValue); String getFormParam(String key); String getFormParam(String key, String defaultValue); Set<Cookie> getCookie(String key); String getCookieValue(String key); String getCookieValue(String key, String defaultValue); String getPath(); boolean matchesPath(Pattern pathPattern); } | @Test public void shouldFailWhenDecodingTooLargeBody() { String input = generateLargeString(6); HttpServerRequest serverReq = new MockHttpServerRequest("/", HttpMethod.DELETE, input); JaxRsRequest req = new JaxRsRequest(serverReq, new ByteBufCollector(5 * 1024 * 1024)); try { req.loadBody().block(); Assert.fail("Should throw exception"); } catch (WebException e) { assertThat(e.getError()).isEqualTo("too.large.input"); } } |
RequestLogger { public static String getHeaderValueOrRedact(Map.Entry<String, String> header) { if (header == null) { return null; } else if ("Authorization".equalsIgnoreCase(header.getKey())) { return "REDACTED"; } return header.getValue(); } RequestLogger(Logger logger); static void headersToString(HttpServerRequest request, StringBuilder logLine); static void headersToString(HttpServerResponse response, StringBuilder logLine); static String getHeaderValueOrRedact(Map.Entry<String, String> header); static Set<Map.Entry<String, String>> getHeaderValuesOrRedact(Map<String, String> headers); static void logAccess(HttpServerRequest request, HttpServerResponse response, long duration, StringBuilder logLine); static void logRequestResponse(HttpServerRequest request, HttpServerResponse response, long requestStartTime, Logger log); void log(HttpServerRequest request, HttpServerResponse response, long requestStartTime); } | @Test public void shouldRedactAuthorizationValue() { Map.Entry<String,String> header = new AbstractMap.SimpleEntry<>("Authorization", "secret"); String result = RequestLogger.getHeaderValueOrRedact(header); assertEquals(result, "REDACTED"); }
@Test public void shouldNotRedactAuthorizationValue() { Map.Entry<String,String> header = new AbstractMap.SimpleEntry<>("OtherHeader", "notasecret"); String result = RequestLogger.getHeaderValueOrRedact(header); assertEquals(result, "notasecret"); }
@Test public void shouldReturnNull_getHeaderValueOrRedact() { assertNull(RequestLogger.getHeaderValueOrRedact(null)); } |
JsonSerializerFactory { public <T> Function<T, String> createStringSerializer(TypeReference<T> paramType) { return createStringSerializer(mapper.writerFor(paramType)); } @Inject JsonSerializerFactory(ObjectMapper mapper); JsonSerializerFactory(); Function<T, String> createStringSerializer(TypeReference<T> paramType); Function<T, String> createStringSerializer(Class<T> paramType); Function<T, String> createStringSerializer(Type type); Function<T, byte[]> createByteSerializer(TypeReference<T> paramType); Function<T, byte[]> createByteSerializer(Class<T> paramType); } | @Test public void shouldSerializeUsingProtectedProp() { PrivateEntity entity = new PrivateEntity(); entity.setProtectedProp("hello"); Function<PrivateEntity, String> serializer = serializerFactory.createStringSerializer(PrivateEntity.class); assertThat(serializer.apply(entity)).isEqualTo("{\"protectedProp\":\"hello\"}"); }
@Test public void shouldSerializeUsingPrivateClassWithPublicProp() { PrivateEntity entity = new PrivateEntity(); entity.setPublicPropInPrivateClass("hello"); Function<PrivateEntity, String> serializer = serializerFactory.createStringSerializer(PrivateEntity.class); assertThat(serializer.apply(entity)).isEqualTo("{\"publicPropInPrivateClass\":\"hello\"}"); }
@Test public void shouldSerializeUsingFieldProp() { PrivateEntity entity = new PrivateEntity(); entity.fieldProp = "hello"; Function<PrivateEntity, String> serializer = serializerFactory.createStringSerializer(PrivateEntity.class); assertThat(serializer.apply(entity)).isEqualTo("{\"fieldProp\":\"hello\"}"); }
@Test public void shouldSerializeFromType() throws NoSuchMethodException { Method method = this.getClass().getDeclaredMethod("methodReturningListOfString"); Type type = method.getGenericReturnType(); Function<List<String>, String> serializeList = serializerFactory.createStringSerializer(type); assertThat(serializeList.apply(methodReturningListOfString())).isEqualTo("[\"a\",\"b\"]"); } |
RequestLogger { public static Set<Map.Entry<String, String>> getHeaderValuesOrRedact(Map<String, String> headers) { if (headers == null) { return Collections.emptySet(); } return headers .entrySet() .stream() .collect(Collectors.toMap( Map.Entry::getKey, RequestLogger::getHeaderValueOrRedact )) .entrySet(); } RequestLogger(Logger logger); static void headersToString(HttpServerRequest request, StringBuilder logLine); static void headersToString(HttpServerResponse response, StringBuilder logLine); static String getHeaderValueOrRedact(Map.Entry<String, String> header); static Set<Map.Entry<String, String>> getHeaderValuesOrRedact(Map<String, String> headers); static void logAccess(HttpServerRequest request, HttpServerResponse response, long duration, StringBuilder logLine); static void logRequestResponse(HttpServerRequest request, HttpServerResponse response, long requestStartTime, Logger log); void log(HttpServerRequest request, HttpServerResponse response, long requestStartTime); } | @Test public void shouldRedactAuthorizationValues() { Map<String,String> headers = new HashMap<>(); headers.put("Authorization", "secret"); headers.put("OtherHeader", "notasecret"); Set<Map.Entry<String, String>> result = RequestLogger.getHeaderValuesOrRedact(headers); Map<String, String> expectedValue = new HashMap<>(); expectedValue.put("Authorization", "REDACTED"); expectedValue.put("OtherHeader", "notasecret"); assertTrue(CollectionUtils.isEqualCollection(result, expectedValue.entrySet())); }
@Test public void shouldReturnNull_getHeaderValuesOrRedact() { Set<Map.Entry<String, String>> result = RequestLogger.getHeaderValuesOrRedact(null); assertTrue(CollectionUtils.isEqualCollection(result, Collections.emptySet())); } |
JaxRsMeta { public static Optional<Class<?>> getJaxRsClass(Class<?> cls) { if (!cls.isInterface()) { if (cls.getAnnotation(Path.class) != null) { return Optional.of(cls); } for (Class<?> iface : cls.getInterfaces()) { if (iface.getAnnotation(Path.class) != null) { return Optional.of(iface); } } } return Optional.empty(); } JaxRsMeta(Method method); JaxRsMeta(Method method, Path classPath); static Path getPath(Class<? extends Object> cls); static String concatPaths(Path path1, Path path2); HttpMethod getHttpMethod(); void setMethod(HttpMethod method); String getProduces(); Consumes getConsumes(); String getFullPath(); static Optional<Class<?>> getJaxRsClass(Class<?> cls); } | @Test public void shouldFindJaxRsClassFromImplementation() { Optional<Class<?>> jaxRsClass = JaxRsMeta.getJaxRsClass(ResourceImplementingInterface.class); assertThat(jaxRsClass.isPresent()).isTrue(); assertThat(jaxRsClass.get()).isEqualTo(ResourceInterface.class); }
@Test public void shouldFindJaxRsClassFromImplementationWithoutInterface() { Optional<Class<?>> jaxRsClass = JaxRsMeta.getJaxRsClass(ResourceImplementation.class); assertThat(jaxRsClass.isPresent()).isTrue(); assertThat(jaxRsClass.get()).isEqualTo(ResourceImplementation.class); }
@Test public void shouldNotReturnJaxRsClassFromInterface() { Optional<Class<?>> jaxRsClass = JaxRsMeta.getJaxRsClass(ResourceInterface.class); assertThat(jaxRsClass.isPresent()).isFalse(); } |
LocalTimeDeserializer implements Deserializer<LocalTime> { @Override public LocalTime deserialize(String value) throws DeserializerException { if (value == null || value.length() == 0) { return null; } try { return LocalTime.parse(value); } catch (DateTimeParseException e) { LOG.warn("Unable to parse " + value + " as LocalTime", e); throw new DeserializerException("invalid.localtime"); } } @Override LocalTime deserialize(String value); } | @Test public void shouldDeserialize() throws DeserializerException { LocalTime deserialized = DESERIALIZER.deserialize("14:10:15"); assertThat(deserialized.toString()).isEqualTo("14:10:15"); }
@Test public void shouldDeserializeNull() throws DeserializerException { LocalTime deserialized = DESERIALIZER.deserialize(null); assertThat(deserialized).isNull(); }
@Test public void shouldThrowDeserializerExceptionForBadDates() { try { DESERIALIZER.deserialize("not a date"); fail("Expected exception, but none was thrown"); } catch (Exception exception) { assertThat(exception).isInstanceOf(DeserializerException.class); assertThat(exception.getMessage()).isEqualTo("invalid.localtime"); } } |
EnumDeserializer implements Deserializer<T> { @Override public T deserialize(String value) throws DeserializerException { if (value == null || value.isEmpty()) { return null; } try { return Enum.valueOf(paramType, value); } catch (Exception parseException) { try { return Enum.valueOf(paramType, value.toUpperCase()); } catch (Exception e) { throw new DeserializerException("invalid.enum"); } } } EnumDeserializer(Class<T> paramType); @Override T deserialize(String value); } | @Test public void shouldDeserialize() throws DeserializerException { TestEnum deserialized = DESERIALIZER.deserialize("FIRST"); assertThat(deserialized).isEqualTo(TestEnum.FIRST); }
@Test public void shouldDeserializeNull() throws DeserializerException { TestEnum deserialized = DESERIALIZER.deserialize(null); assertThat(deserialized).isNull(); }
@Test public void shouldBeCaseInsensitive() throws DeserializerException { TestEnum deserialized = DESERIALIZER.deserialize("first"); assertThat(deserialized).isEqualTo(TestEnum.FIRST); }
@Test public void shouldThrowDeserializerExceptionForUnknownEnums() { try { DESERIALIZER.deserialize("not a recognized value"); fail("Expected exception, but none was thrown"); } catch (Exception exception) { assertThat(exception).isInstanceOf(DeserializerException.class); assertThat(exception.getMessage()).isEqualTo("invalid.enum"); } } |
LocalDateDeserializer implements Deserializer<LocalDate> { @Override public LocalDate deserialize(String value) throws DeserializerException { if (value == null || value.length() == 0) { return null; } try { return LocalDate.parse(value); } catch (DateTimeParseException e) { LOG.warn("Unable to parse " + value + " as LocalDate", e); } try { return LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(value)), DEFAULT_TIME_ZONE.toZoneId()).toLocalDate(); } catch (NumberFormatException | DateTimeException e) { throw new DeserializerException("invalid.localdate"); } } @Override LocalDate deserialize(String value); } | @Test public void shouldDeserialize() throws DeserializerException { LocalDate deserialized = DESERIALIZER.deserialize("2010-01-01"); assertThat(deserialized.toString()).isEqualTo("2010-01-01"); }
@Test public void shouldDeserializeTimestampsInMilliseconds() throws DeserializerException { LocalDate deserialized = DESERIALIZER.deserialize("1262304000000"); assertThat(deserialized.toString()).isEqualTo("2010-01-01"); }
@Test public void shouldDeserializeNull() throws DeserializerException { LocalDate deserialized = DESERIALIZER.deserialize(null); assertThat(deserialized).isNull(); }
@Test public void shouldThrowDeserializerExceptionForBadDates() { try { DESERIALIZER.deserialize("not a date"); fail("Expected exception, but none was thrown"); } catch (Exception exception) { assertThat(exception).isInstanceOf(DeserializerException.class); assertThat(exception.getMessage()).isEqualTo("invalid.localdate"); } } |
UUIDDeserializer implements Deserializer<UUID> { @Override public UUID deserialize(String value) throws DeserializerException { try { return value == null || value.equals("") ? null : UUID.fromString(value); } catch (Exception e) { throw new DeserializerException("invalid.uuid"); } } @Override UUID deserialize(String value); } | @Test public void shouldDeserialize() throws DeserializerException { assertThat(DESERIALIZER.deserialize("b0b895d4-3be8-11e8-b467-0ed5f89f718b").toString()).isEqualTo("b0b895d4-3be8-11e8-b467-0ed5f89f718b"); }
@Test public void shouldNotDeserializeNull() throws DeserializerException { assertThat(DESERIALIZER.deserialize(null)).isNull(); }
@Test public void shouldThrowDeserializerExceptionForUnparsableStrings() { try { DESERIALIZER.deserialize("not a recognized value"); fail("Expected exception, but none was thrown"); } catch (Exception exception) { assertThat(exception).isInstanceOf(DeserializerException.class); assertThat(exception.getMessage()).isEqualTo("invalid.uuid"); } } |
BooleanDeserializer implements Deserializer<Boolean> { @Override public Boolean deserialize(String value) throws DeserializerException { return (value == null) ? null : Boolean.valueOf(value.trim()); } @Override Boolean deserialize(String value); } | @Test public void shouldDeserializeTrue() throws DeserializerException { assertThat(DESERIALIZER.deserialize("true")).isEqualTo(true); assertThat(DESERIALIZER.deserialize("TRUE")).isEqualTo(true); assertThat(DESERIALIZER.deserialize("True")).isEqualTo(true); }
@Test public void shouldDeserializeFalse() throws DeserializerException { assertThat(DESERIALIZER.deserialize("false")).isEqualTo(false); assertThat(DESERIALIZER.deserialize("FALSE")).isEqualTo(false); assertThat(DESERIALIZER.deserialize("False")).isEqualTo(false); }
@Test public void shouldDeserializeUnknownValuesToFalse() throws DeserializerException { assertThat(DESERIALIZER.deserialize("anything")).isEqualTo(false); }
@Test public void shouldDeserializeNull() throws DeserializerException { Boolean deserialized = DESERIALIZER.deserialize(null); assertThat(deserialized).isNull(); } |
DateDeserializer implements Deserializer<Date> { @Override public Date deserialize(String value) throws DeserializerException { if (value == null) { return null; } try { return new Date(Long.parseLong(value)); } catch (NumberFormatException e) { try { return dateFormatProvider.get().parse(value); } catch (Exception parseException) { throw new DeserializerException("invalid.date"); } } } DateDeserializer(Provider<DateFormat> dateFormatProvider); @Override Date deserialize(String value); } | @Test public void shouldDeserialize() throws DeserializerException { Date deserialized = DESERIALIZER.deserialize("2010-01-01"); assertThat(deserialized.toString()).isEqualTo("Fri Jan 01 00:00:00 UTC 2010"); }
@Test public void shouldDeserializeTimestampsInMilliseconds() throws DeserializerException { Date deserialized = DESERIALIZER.deserialize("1262304000000"); assertThat(deserialized.toString()).isEqualTo("Fri Jan 01 00:00:00 UTC 2010"); }
@Test public void shouldDeserializeNull() throws DeserializerException { Date deserialized = DESERIALIZER.deserialize(null); assertThat(deserialized).isNull(); }
@Test public void shouldThrowDeserializerExceptionForBadDates() { try { DESERIALIZER.deserialize("not a date"); fail("Expected exception, but none was thrown"); } catch (Exception exception) { assertThat(exception).isInstanceOf(DeserializerException.class); assertThat(exception.getMessage()).isEqualTo("invalid.date"); } } |
ArrayDeserializer implements Deserializer<T[]> { @Override public T[] deserialize(String value) throws DeserializerException { if (value == null) { return null; } String[] rawValues = value.split(","); try { T[] deserialized = (T[])Array.newInstance(arrayType, rawValues.length); for (int i = 0; i < deserialized.length; i++) { deserialized[i] = inner.deserialize(rawValues[i]); } return deserialized; } catch (DeserializerException e) { throw e; } catch (Exception e) { throw new DeserializerException("invalid.array"); } } ArrayDeserializer(Deserializer<T> inner, Class<T> arrayType); @Override T[] deserialize(String value); } | @Test public void shouldDeserializeCommaSeparatedStrings() throws DeserializerException { assertThat(DESERIALIZER.deserialize("entry")).hasSize(1); assertThat(DESERIALIZER.deserialize("entry,second,third")).hasSize(3); }
@Test public void shouldHandleDeserializationErrorsForEntries() { Deserializer<Boolean[]> longDeserializer = new ArrayDeserializer(new LongDeserializer(), Long.class); try { longDeserializer.deserialize("5,a,5"); fail("Expected exception, but none was thrown"); } catch (Exception exception) { assertThat(exception).isInstanceOf(DeserializerException.class); assertThat(exception.getMessage()).isEqualTo("invalid.long"); } }
@Test public void shouldDeserializeNull() throws DeserializerException { assertThat(DESERIALIZER.deserialize(null)).isNull(); } |
BooleanNotNullDeserializer implements Deserializer<Boolean> { @Override public Boolean deserialize(String value) throws DeserializerException { if (value == null) { throw new DeserializerException("invalid.boolean"); } return Boolean.valueOf(value.trim()); } @Override Boolean deserialize(String value); } | @Test public void shouldDeserializeTrue() throws DeserializerException { assertThat(DESERIALIZER.deserialize("true")).isEqualTo(true); assertThat(DESERIALIZER.deserialize("TRUE")).isEqualTo(true); assertThat(DESERIALIZER.deserialize("True")).isEqualTo(true); }
@Test public void shouldDeserializeFalse() throws DeserializerException { assertThat(DESERIALIZER.deserialize("false")).isEqualTo(false); assertThat(DESERIALIZER.deserialize("FALSE")).isEqualTo(false); assertThat(DESERIALIZER.deserialize("False")).isEqualTo(false); }
@Test public void shouldDeserializeUnknownValuesToFalse() throws DeserializerException { assertThat(DESERIALIZER.deserialize("anything")).isEqualTo(false); }
@Test public void shouldThrowExceptionForNull() throws DeserializerException { try { DESERIALIZER.deserialize(null); fail("Expected exception, but none was thrown"); } catch (Exception exception) { assertThat(exception).isInstanceOf(DeserializerException.class); assertThat(exception.getMessage()).isEqualTo("invalid.boolean"); } } |
ListDeserializer implements Deserializer<List<T>> { @Override public List<T> deserialize(String value) throws DeserializerException { if (value == null) { return null; } if (value.isEmpty()) { return Collections.emptyList(); } String[] rawValues = value.split(","); List<T> deserialized = new ArrayList<>(rawValues.length); for (String rawValue : rawValues) { deserialized.add(inner.deserialize(rawValue)); } return deserialized; } ListDeserializer(Deserializer<T> inner); @Override List<T> deserialize(String value); } | @Test public void shouldDeserializeCommaSeparatedStrings() throws DeserializerException { assertThat(DESERIALIZER.deserialize("entry")).hasSize(1); assertThat(DESERIALIZER.deserialize("entry,second,third")).hasSize(3); }
@Test public void shouldDeserializeEmptyLists() throws DeserializerException { assertThat(DESERIALIZER.deserialize("")).hasSize(0); }
@Test public void shouldHandleDeserializationErrorsForEntries() { Deserializer<Boolean[]> longDeserializer = new ArrayDeserializer(new LongDeserializer(), Long.class); try { longDeserializer.deserialize("5,notlong,5"); fail("Expected exception, but none was thrown"); } catch (Exception exception) { assertThat(exception).isInstanceOf(DeserializerException.class); assertThat(exception.getMessage()).isEqualTo("invalid.long"); } }
@Test public void shouldDeserializeNull() throws DeserializerException { assertThat(DESERIALIZER.deserialize(null)).isNull(); } |
JaxRsResource implements Comparable<JaxRsResource> { protected Mono<JaxRsResult<T>> call(JaxRsRequest request) { return request.loadBody() .flatMap(this::resolveArgs) .map(this::call); } JaxRsResource(Method method,
Object resourceInstance,
ParamResolverFactories paramResolverFactories,
JaxRsResultFactoryFactory jaxRsResultFactoryFactory,
JaxRsMeta meta
); boolean canHandleRequest(JaxRsRequest request); @Override int compareTo(JaxRsResource jaxRsResource); @Override String toString(); Method getResourceMethod(); Method getInstanceMethod(); HttpMethod getHttpMethod(); String getProduces(); void log(HttpServerRequest request, HttpServerResponse response, long requestStartTime); String getPath(); } | @Test public void shouldConcatPaths() throws InvocationTargetException, IllegalAccessException { JaxRsResources resources = new JaxRsResources(new Object[]{new Testresource()}, new JaxRsResourceFactory(), false); JaxRsRequest jaxRsRequest = new JaxRsRequest(new MockHttpServerRequest("/test/acceptsString"), new ByteBufCollector()); assertThat(resources.findResource(jaxRsRequest).call(jaxRsRequest)).isNotNull(); }
@Test public void shouldResolveCustomType() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, JsonProcessingException { MockHttpServerRequest req = new MockHttpServerRequest("/test/accepts/res?fid=5678"); req.cookies().put("fnox_5678", new HashSet<>(asList(new DefaultCookie("fnox_5678","888")))); Foo foo = Mockito.mock(Foo.class); when(foo.getStr()).thenReturn("5678"); ParamResolver<Foo> fooResolver = new ParamResolver<Foo>() { @Override public Mono<Foo> resolve(JaxRsRequest request) { return Mono.just(foo); } }; ParamResolvers paramResolvers = new ParamResolvers(fooResolver); JaxRsResources jaxRsResources = new JaxRsResources( new Object[]{new FooTest()}, new JaxRsResourceFactory( new ParamResolverFactories( new DeserializerFactory(), paramResolvers, new AnnotatedParamResolverFactories(), new WrapSupportingParamTypeResolver()), new JaxRsResultFactoryFactory()), false); JaxRsRequest jaxRsRequest = new JaxRsRequest(req, new ByteBufCollector()); Mono<? extends JaxRsResult<?>> result = jaxRsResources.findResource(jaxRsRequest).call(jaxRsRequest); MockHttpServerResponse response = new MockHttpServerResponse(); Flux.from(result.block().write(response)).count().block(); assertThat(response.getOutp()).isEqualTo("\"foo: 5678\""); } |
JaxRsResource implements Comparable<JaxRsResource> { @Override public String toString() { return format("%1$s\t%2$s (%3$s.%4$s)", meta.getHttpMethod(), meta.getFullPath(), method.getDeclaringClass().getName(), method.getName()); } JaxRsResource(Method method,
Object resourceInstance,
ParamResolverFactories paramResolverFactories,
JaxRsResultFactoryFactory jaxRsResultFactoryFactory,
JaxRsMeta meta
); boolean canHandleRequest(JaxRsRequest request); @Override int compareTo(JaxRsResource jaxRsResource); @Override String toString(); Method getResourceMethod(); Method getInstanceMethod(); HttpMethod getHttpMethod(); String getProduces(); void log(HttpServerRequest request, HttpServerResponse response, long requestStartTime); String getPath(); } | @Test public void shouldSupportUuidAsQueryParameter() { UUID uuid = UUID.randomUUID(); assertThat(body( get(service, "/test/acceptsUuid?id=" + uuid.toString()))) .isEqualTo("\"Id: " + uuid + "\""); }
@Test public void shouldSupportUuidAsHeader() { UUID uuid = UUID.randomUUID(); assertThat(body(JaxRsTestUtil.getWithHeaders(service, "/test/acceptsUuidHeader", new HashMap<String, List<String>>() { { put("id", asList(uuid.toString())); } } ))).isEqualTo("\"Id: " + uuid.toString() + "\""); } |
JaxRsRequestContext { public static void open() { if (CONTEXT.get() != null) { throw new IllegalStateException("A context already exists"); } CONTEXT.set(new JaxRsRequestContext()); } private JaxRsRequestContext(); static Optional<T> getValue(Object key); static void setValue(Object key, Object value); static void open(); static void close(); } | @Test(expected = IllegalStateException.class) public void shouldFailOnReentry() { JaxRsRequestContext.open(); } |
JaxRsRequestContextInterceptor implements JaxRsResourceInterceptor { @Override public void preHandle(JaxRsResourceContext context) { JaxRsRequestContext.open(); } @Override void preHandle(JaxRsResourceContext context); @Override void postHandle(JaxRsResourceContext context, Publisher<Void> resourceCall); } | @Test public void shouldOpenContextOnHandle() { interceptor.preHandle(null); assertThat(JaxRsRequestContext.getContext()).isNotNull(); } |
JaxRsRequestContextInterceptor implements JaxRsResourceInterceptor { @Override public void postHandle(JaxRsResourceContext context, Publisher<Void> resourceCall) { JaxRsRequestContext.close(); } @Override void preHandle(JaxRsResourceContext context); @Override void postHandle(JaxRsResourceContext context, Publisher<Void> resourceCall); } | @Test public void shouldCloseContextAfterHandle() { JaxRsRequestContext.open(); interceptor.postHandle(null, null); assertThat(JaxRsRequestContext.getContext()).isNull(); } |
ConfigReader { public static <T> T fromFile(String configFile, Class<T> cls) { try { return fromTree(readTree(configFile), cls); } catch (Exception e) { throw new RuntimeException(e); } } static T fromFile(String configFile, Class<T> cls); static T fromTree(JsonNode tree, Class<T> cls); static JsonNode readTree(String fileName); } | @Test public void shouldQuoteReplacementString() { Map<String, String> env = new HashMap<>(System.getenv()); env.put("CUSTOM_ENV_VAR", "^THIS.IS.A.\\d{6}T\\d{7}.REGEX1$"); setEnv(env); TestConfig testConfig = ConfigReader.fromFile("src/test/resources/testconfig.yml", TestConfig.class); assertThat(testConfig.getConfigWithEnvPlaceholder()).isEqualTo("^THIS.IS.A.\\d{6}T\\d{7}.REGEX1$"); }
@Test public void shouldSupportEmptyConfig() { EmptyConfig testConfig = ConfigReader.fromFile("src/test/resources/testconfig.yml", EmptyConfig.class); assertThat(testConfig).isNotNull(); }
@Test public void shouldThrowExceptionForInvalidYaml() { try { ConfigReader.fromFile("src/test/resources/testconfig-invalid.yml", EmptyConfig.class); fail("Expected exception, but none was thrown"); } catch (RuntimeException exception) { assertThat(exception).hasRootCauseInstanceOf(MarkedYAMLException.class); } }
@Test public void shouldReplaceEscapedNewLines() { Map<String, String> env = new HashMap<>(System.getenv()); env.put("CLIENTS", "" + "clients:\\n" + " client1:\\n" + " - key41\\n" + " - key24\\n" + " client2:\\n" + " - key55"); setEnv(env); TestConfigNewLine testConfig = ConfigReader.fromFile("src/test/resources/testconfig-newline.yml", TestConfigNewLine.class); assertThat(testConfig.getClients().get("client1").get(0)).isEqualTo("key41"); assertThat(testConfig.getClients().get("client1").get(1)).isEqualTo("key24"); assertThat(testConfig.getClients().get("client2").get(0)).isEqualTo("key55"); } |
ConfigFactory { @Inject public ConfigFactory(@Named("args") String[] args) { this(args.length == 0 ? null : args[args.length - 1]); } @Inject ConfigFactory(@Named("args") String[] args); ConfigFactory(String configFile); T get(Class<T> cls); } | @Test public void testConfigFactory() { try { new ConfigFactory(""); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException || e.getCause() instanceof IOException); } } |
MethodSetter implements Setter<I,T> { @Override public void invoke(I instance, T value) { setterLambda.accept(instance, value); } private MethodSetter(Method method, Class<T> parameterType, Type genericParameterType); static Setter<I,T> create(Class<I> cls, Method method); @Override void invoke(I instance, T value); @Override Class<?> getParameterType(); @Override Type getGenericParameterType(); @Override BiConsumer<I, T> setterFunction(); } | @Test public void shouldSetValue() throws Exception { GenericMethodSubclass foo = new GenericMethodSubclass(1); value.invoke(foo, 9); assertThat(foo.getValue()).isEqualTo(9); genericSuperKey.invoke(foo, "9"); assertThat(foo.getSuperKey()).isEqualTo("9"); genericSuperValue.invoke(foo, 9); assertThat(foo.getSuperValue()); MethodSubclass bar = new MethodSubclass("1", 2); superKey.invoke(bar, "9"); assertThat(bar.getSuperKey()).isEqualTo("9"); superValue.invoke(bar, 9); assertThat(bar.getSuperValue()).isEqualTo(9); } |
MethodSetter implements Setter<I,T> { @Override public Class<?> getParameterType() { return parameterType; } private MethodSetter(Method method, Class<T> parameterType, Type genericParameterType); static Setter<I,T> create(Class<I> cls, Method method); @Override void invoke(I instance, T value); @Override Class<?> getParameterType(); @Override Type getGenericParameterType(); @Override BiConsumer<I, T> setterFunction(); } | @Test public void shouldGetParameterType() { assertThat(value.getParameterType()).isEqualTo(Integer.class); assertThat(genericSuperKey.getParameterType()).isEqualTo(String.class); assertThat(genericSuperValue.getParameterType()).isEqualTo(Integer.class); assertThat(superKey.getParameterType()).isEqualTo(String.class); assertThat(superValue.getParameterType()).isEqualTo(Integer.class); } |
MethodSetter implements Setter<I,T> { @Override public Type getGenericParameterType() { return genericParameterType; } private MethodSetter(Method method, Class<T> parameterType, Type genericParameterType); static Setter<I,T> create(Class<I> cls, Method method); @Override void invoke(I instance, T value); @Override Class<?> getParameterType(); @Override Type getGenericParameterType(); @Override BiConsumer<I, T> setterFunction(); } | @Test public void shouldGetGenericParameterType() { assertThat(longObservable.getGenericParameterType().toString()).isEqualTo("rx.Observable<java.lang.Long>"); assertThat(genericSuperKey.getGenericParameterType().toString()).isEqualTo("class java.lang.String"); assertThat(genericSuperValue.getGenericParameterType().toString()).isEqualTo("class java.lang.Integer"); assertThat(superKey.getGenericParameterType().toString()).isEqualTo("class java.lang.String"); assertThat(superValue.getGenericParameterType().toString()).isEqualTo("class java.lang.Integer"); } |
ReflectionUtil { static Getter getGetter(Class<?> cls, String propertyName) { return getGetter(cls, cls, propertyName); } static Type getTypeOfObservable(Method method); static Class<?> getGenericParameter(Type type); static Method getOverriddenMethod(Method method); static Optional<Method> findMethodInClass(Method method, Class<?> cls); static T getAnnotation(Method method, Class<T> annotationClass); static List<Annotation> getAnnotations(Method method); static List<List<Annotation>> getParameterAnnotations(Method method); static List<Annotation> getParameterAnnotations(Parameter parameter); static Class<?> getRawType(Type type); static Optional<PropertyResolver> getPropertyResolver(Type type, String... propertyNames); static Method getInstanceMethod(Method method, Object resourceInstance); static Supplier<T> instantiator(Class<T> cls); static Optional<Function<I,T>> getter(Class<I> instanceCls, String propertyPath); static Optional<BiConsumer<I,T>> setter(Class<I> instanceCls, String propertyPath); } | @Test public void shouldFindSizeMethod() { Getter size = ReflectionUtil.getGetter(List.class, "size"); assertThat(size).isNotNull(); } |
ReflectionUtil { public static <T> Supplier<T> instantiator(Class<T> cls) { try { Constructor<?> constructor = Stream.of(cls.getDeclaredConstructors()) .filter(c -> c.getParameterCount() == 0) .findFirst() .orElseThrow(NoSuchMethodException::new); MethodHandles.Lookup lookup = lookupFor(cls, constructor); constructor.setAccessible(true); MethodHandle methodHandle = lookup.unreflectConstructor(constructor); CallSite callSite = LambdaMetafactory.metafactory( lookup, "get", MethodType.methodType(Supplier.class), MethodType.methodType(Object.class), methodHandle, methodHandle.type() ); return (Supplier<T>)callSite.getTarget().invoke(); } catch (NoSuchMethodException e) { throw new RuntimeException("No constructor with zero parameters found on " + cls.getSimpleName(), e); } catch (Throwable e) { throw new RuntimeException(e); } } static Type getTypeOfObservable(Method method); static Class<?> getGenericParameter(Type type); static Method getOverriddenMethod(Method method); static Optional<Method> findMethodInClass(Method method, Class<?> cls); static T getAnnotation(Method method, Class<T> annotationClass); static List<Annotation> getAnnotations(Method method); static List<List<Annotation>> getParameterAnnotations(Method method); static List<Annotation> getParameterAnnotations(Parameter parameter); static Class<?> getRawType(Type type); static Optional<PropertyResolver> getPropertyResolver(Type type, String... propertyNames); static Method getInstanceMethod(Method method, Object resourceInstance); static Supplier<T> instantiator(Class<T> cls); static Optional<Function<I,T>> getter(Class<I> instanceCls, String propertyPath); static Optional<BiConsumer<I,T>> setter(Class<I> instanceCls, String propertyPath); } | @Test public void shouldInstantiate() { assertThat(ReflectionUtil.instantiator(Parent.class).get()).isNotNull(); assertThat(ReflectionUtil.instantiator(Child.class).get()).isNotNull(); assertThat(ReflectionUtil.instantiator(PrivateDefaultConstructor.class).get()).isNotNull(); }
@Test public void shouldCreateInstantiator() { assertThat(ReflectionUtil.instantiator(Parent.class).get()).isInstanceOf(Parent.class); }
@Test public void shouldThrowHelpfulExceptionWhenNoZeroParametersConstructorExists() { try { ReflectionUtil.instantiator(NoZeroParametersConstructorClass.class).get(); fail("Expected RuntimeException, but none was thrown"); } catch (RuntimeException exception) { assertThat(exception.getMessage()) .isEqualTo("No constructor with zero parameters found on NoZeroParametersConstructorClass"); } } |
ReflectionUtil { public static <I,T> Optional<Function<I,T>> getter(Class<I> instanceCls, String propertyPath) { Optional<PropertyResolver> propertyResolver = ReflectionUtil.getPropertyResolver(instanceCls, propertyPath.split("\\.")); return propertyResolver.map(PropertyResolver::getter); } static Type getTypeOfObservable(Method method); static Class<?> getGenericParameter(Type type); static Method getOverriddenMethod(Method method); static Optional<Method> findMethodInClass(Method method, Class<?> cls); static T getAnnotation(Method method, Class<T> annotationClass); static List<Annotation> getAnnotations(Method method); static List<List<Annotation>> getParameterAnnotations(Method method); static List<Annotation> getParameterAnnotations(Parameter parameter); static Class<?> getRawType(Type type); static Optional<PropertyResolver> getPropertyResolver(Type type, String... propertyNames); static Method getInstanceMethod(Method method, Object resourceInstance); static Supplier<T> instantiator(Class<T> cls); static Optional<Function<I,T>> getter(Class<I> instanceCls, String propertyPath); static Optional<BiConsumer<I,T>> setter(Class<I> instanceCls, String propertyPath); } | @Test public void shouldCreateGetterLambda() { Parent parent = new Parent(); parent.setI(3); Function<Parent, Integer> getFromParent = ReflectionUtil.<Parent,Integer>getter(Parent.class, "i").get(); assertThat(getFromParent.apply(parent)).isEqualTo(3); Inner inner = new Inner(); inner.setI(5); parent.setInner(inner); Function<Parent, Integer> getFromInner = ReflectionUtil.<Parent,Integer>getter(Parent.class, "inner.i").get(); assertThat(getFromInner.apply(parent)).isEqualTo(5); } |
ReflectionUtil { public static <I,T> Optional<BiConsumer<I,T>> setter(Class<I> instanceCls, String propertyPath) { Optional<PropertyResolver> propertyResolver = ReflectionUtil.getPropertyResolver(instanceCls, propertyPath.split("\\.")); return propertyResolver.map(PropertyResolver::setter); } static Type getTypeOfObservable(Method method); static Class<?> getGenericParameter(Type type); static Method getOverriddenMethod(Method method); static Optional<Method> findMethodInClass(Method method, Class<?> cls); static T getAnnotation(Method method, Class<T> annotationClass); static List<Annotation> getAnnotations(Method method); static List<List<Annotation>> getParameterAnnotations(Method method); static List<Annotation> getParameterAnnotations(Parameter parameter); static Class<?> getRawType(Type type); static Optional<PropertyResolver> getPropertyResolver(Type type, String... propertyNames); static Method getInstanceMethod(Method method, Object resourceInstance); static Supplier<T> instantiator(Class<T> cls); static Optional<Function<I,T>> getter(Class<I> instanceCls, String propertyPath); static Optional<BiConsumer<I,T>> setter(Class<I> instanceCls, String propertyPath); } | @Test public void shouldCreateSetterLambda() { Parent parent = new Parent(); BiConsumer<Parent, Integer> setOnParent = ReflectionUtil.<Parent,Integer>setter(Parent.class, "i").get(); setOnParent.accept(parent, 2); assertThat(parent.getI()).isEqualTo(2); Inner inner = new Inner(); parent.setInner(inner); BiConsumer<Parent, Integer> setOnInner = ReflectionUtil.<Parent,Integer>setter(Parent.class, "inner.i").get(); setOnInner.accept(parent, 4); assertThat(parent.getInner().getI()).isEqualTo(4); }
@Test public void shouldSupportNullsOnSetterPath() { Parent parent = new Parent(); BiConsumer<Parent, Integer> setter = ReflectionUtil.<Parent,Integer>setter(Parent.class, "inner.i").get(); setter.accept(parent, 7); assertThat(parent.getInner().getI()).isEqualTo(7); } |
FieldGetter implements Getter<I,T> { @Override public T invoke(I instance) { return fieldLambda.apply(instance); } private FieldGetter(Field field, Class<T> returnType, Type genericReturnType); static Getter<I,T> create(Class<I> cls, Field field); @Override T invoke(I instance); @Override Class<?> getReturnType(); @Override Type getGenericReturnType(); @Override Function<I,T> getterFunction(); } | @Test public void shouldGetValue() throws Exception { assertThat(value.invoke(new GenericFieldSubclass(5))).isEqualTo(5); assertThat(genericSuperKey.invoke(new GenericFieldSubclass(5))).isEqualTo("5"); assertThat(genericSuperValue.invoke(new GenericFieldSubclass(5))).isEqualTo(5); assertThat(superKey.invoke(new FieldSubclass(5))).isEqualTo("5"); assertThat(superValue.invoke(new FieldSubclass(5))).isEqualTo(5); } |
FieldGetter implements Getter<I,T> { @Override public Function<I,T> getterFunction() { return fieldLambda; } private FieldGetter(Field field, Class<T> returnType, Type genericReturnType); static Getter<I,T> create(Class<I> cls, Field field); @Override T invoke(I instance); @Override Class<?> getReturnType(); @Override Type getGenericReturnType(); @Override Function<I,T> getterFunction(); } | @Test public void shouldSupportLambdaGetter() { Function<GenericFieldSubclass, Integer> getter = value.getterFunction(); assertThat(getter.apply(new GenericFieldSubclass(5))).isEqualTo(5); } |
FieldGetter implements Getter<I,T> { @Override public Class<?> getReturnType() { return returnType; } private FieldGetter(Field field, Class<T> returnType, Type genericReturnType); static Getter<I,T> create(Class<I> cls, Field field); @Override T invoke(I instance); @Override Class<?> getReturnType(); @Override Type getGenericReturnType(); @Override Function<I,T> getterFunction(); } | @Test public void shouldGetReturnType() { assertThat(value.getReturnType()).isEqualTo(Integer.class); assertThat(genericSuperKey.getReturnType()).isEqualTo(String.class); assertThat(genericSuperValue.getReturnType()).isEqualTo(Integer.class); assertThat(superKey.getReturnType()).isEqualTo(String.class); assertThat(superValue.getReturnType()).isEqualTo(Integer.class); } |
FieldGetter implements Getter<I,T> { @Override public Type getGenericReturnType() { return genericReturnType; } private FieldGetter(Field field, Class<T> returnType, Type genericReturnType); static Getter<I,T> create(Class<I> cls, Field field); @Override T invoke(I instance); @Override Class<?> getReturnType(); @Override Type getGenericReturnType(); @Override Function<I,T> getterFunction(); } | @Test public void shouldGetGenericReturnType() { assertThat(longObservable.getGenericReturnType().toString()).isEqualTo("rx.Observable<java.lang.Long>"); assertThat(genericSuperKey.getGenericReturnType().toString()).isEqualTo("class java.lang.String"); assertThat(genericSuperValue.getGenericReturnType().toString()).isEqualTo("class java.lang.Integer"); assertThat(superKey.getGenericReturnType().toString()).isEqualTo("class java.lang.String"); assertThat(superValue.getGenericReturnType().toString()).isEqualTo("class java.lang.Integer"); } |
ManifestUtil { public static Optional<ManifestValues> getManifestValues() { return Optional.ofNullable(manifestValues); } static Optional<ManifestValues> getManifestValues(); } | @Test public void shouldLoadTestManifest() { Optional<ManifestUtil.ManifestValues> manifestValuesOptional = ManifestUtil.getManifestValues(); assertThat(manifestValuesOptional.isPresent()).isTrue(); ManifestUtil.ManifestValues manifestValues = manifestValuesOptional.get(); assertThat(manifestValues.getVersion()).isEqualTo("0.0.1-SNAPSHOT"); assertThat(manifestValues.getArtifactId()).isEqualTo("reactivewizard-utils"); } |
RxUtils { public static FirstThen first(Observable<?> doFirst) { return FirstThen.first(doFirst); } static FirstThen first(Observable<?> doFirst); static IfThenElse<T> ifTrue(Observable<Boolean> ifValue); static Observable<T1> consolidate(Observable<T1> observableLeft, Observable<T2> observableRight, Action2<T1, T2> action); static Observable<T> async(List<T> list); static Observable<T> async(Observable<T> observable); static Observable<Double> sum(Observable<Double> observable); static Observable<T> doIfEmpty(Observable<T> output, Action0 action); static Observable<T> exception(Supplier<Exception> supplier); static Observable<T> singleOrEmpty(Observable<? extends Collection<T>> collectionObservable); } | @Test public void testFirst() { assertThat(RxUtils.first(just(true))).isInstanceOf(FirstThen.class); } |
RxUtils { public static <T> IfThenElse<T> ifTrue(Observable<Boolean> ifValue) { return new IfThenElse<T>(ifValue); } static FirstThen first(Observable<?> doFirst); static IfThenElse<T> ifTrue(Observable<Boolean> ifValue); static Observable<T1> consolidate(Observable<T1> observableLeft, Observable<T2> observableRight, Action2<T1, T2> action); static Observable<T> async(List<T> list); static Observable<T> async(Observable<T> observable); static Observable<Double> sum(Observable<Double> observable); static Observable<T> doIfEmpty(Observable<T> output, Action0 action); static Observable<T> exception(Supplier<Exception> supplier); static Observable<T> singleOrEmpty(Observable<? extends Collection<T>> collectionObservable); } | @Test public void testIfTrue() { assertThat(RxUtils.ifTrue(just(true))).isInstanceOf(IfThenElse.class); } |
RxUtils { public static Observable<Double> sum(Observable<Double> observable) { return observable.scan((valueA, valueB) -> valueA + valueB).lastOrDefault(0d); } static FirstThen first(Observable<?> doFirst); static IfThenElse<T> ifTrue(Observable<Boolean> ifValue); static Observable<T1> consolidate(Observable<T1> observableLeft, Observable<T2> observableRight, Action2<T1, T2> action); static Observable<T> async(List<T> list); static Observable<T> async(Observable<T> observable); static Observable<Double> sum(Observable<Double> observable); static Observable<T> doIfEmpty(Observable<T> output, Action0 action); static Observable<T> exception(Supplier<Exception> supplier); static Observable<T> singleOrEmpty(Observable<? extends Collection<T>> collectionObservable); } | @Test public void testSum() { Double sum = RxUtils.sum(just(3d, 3d, 3d)) .toBlocking() .single(); assertThat(sum).isEqualTo(9d); } |
RxUtils { public static <T> Observable<T> doIfEmpty(Observable<T> output, Action0 action) { return output.doOnEach(new Observer<T>() { AtomicBoolean empty = new AtomicBoolean(true); @Override public void onCompleted() { if (empty.get()) { action.call(); } } @Override public void onError(Throwable throwable) { } @Override public void onNext(T type) { empty.set(false); } }); } static FirstThen first(Observable<?> doFirst); static IfThenElse<T> ifTrue(Observable<Boolean> ifValue); static Observable<T1> consolidate(Observable<T1> observableLeft, Observable<T2> observableRight, Action2<T1, T2> action); static Observable<T> async(List<T> list); static Observable<T> async(Observable<T> observable); static Observable<Double> sum(Observable<Double> observable); static Observable<T> doIfEmpty(Observable<T> output, Action0 action); static Observable<T> exception(Supplier<Exception> supplier); static Observable<T> singleOrEmpty(Observable<? extends Collection<T>> collectionObservable); } | @Test public void shouldNotDoIfObservableIsEmpty() { Observable<Boolean> observable = just(true, false, true); Consumer<Boolean> thenMock = mock(Consumer.class); RxUtils.doIfEmpty(observable, () -> thenMock.accept(true)).toBlocking().subscribe(); verify(thenMock, never()).accept(anyBoolean()); }
@Test public void shouldDoIfObservableIsEmpty() { Observable<Object> observable = empty(); Consumer<Boolean> thenMock = mock(Consumer.class); RxUtils.doIfEmpty(observable, () -> thenMock.accept(true)).toBlocking().subscribe(); verify(thenMock).accept(eq(true)); }
@Test public void shouldNotDoIfObservableFails() { Observable<Object> observable = error(new RuntimeException()); Consumer<Boolean> thenMock = mock(Consumer.class); try { RxUtils.doIfEmpty(observable, () -> thenMock.accept(true)).toBlocking().subscribe(); } catch (RuntimeException e) { } verify(thenMock, never()).accept(anyBoolean()); } |
RxUtils { public static <T1, T2> Observable<T1> consolidate(Observable<T1> observableLeft, Observable<T2> observableRight, Action2<T1, T2> action) { return Observable.zip(observableLeft, observableRight, (leftObj, rightObj) -> { action.call(leftObj, rightObj); return leftObj; }); } static FirstThen first(Observable<?> doFirst); static IfThenElse<T> ifTrue(Observable<Boolean> ifValue); static Observable<T1> consolidate(Observable<T1> observableLeft, Observable<T2> observableRight, Action2<T1, T2> action); static Observable<T> async(List<T> list); static Observable<T> async(Observable<T> observable); static Observable<Double> sum(Observable<Double> observable); static Observable<T> doIfEmpty(Observable<T> output, Action0 action); static Observable<T> exception(Supplier<Exception> supplier); static Observable<T> singleOrEmpty(Observable<? extends Collection<T>> collectionObservable); } | @Test public void testConsolidate() { Bar bar1; Bar bar2; Observable<Foo> fooObservable = Observable.just(new Foo(), new Foo()); Observable<Bar> barObservable = Observable.just(bar1 = new Bar(), bar2 = new Bar()); Observable<Foo> fooObservableResult = RxUtils.consolidate(fooObservable, barObservable.toList(), Foo::setBars); fooObservableResult.forEach(foo -> { assertThat(foo.getBars().size()).isEqualTo(2); assertThat(foo.getBars().get(0)).isEqualTo(bar1); assertThat(foo.getBars().get(1)).isEqualTo(bar2); }); } |
RxUtils { public static <T> Observable<T> async(List<T> list) { return async(Observable.from(list)); } static FirstThen first(Observable<?> doFirst); static IfThenElse<T> ifTrue(Observable<Boolean> ifValue); static Observable<T1> consolidate(Observable<T1> observableLeft, Observable<T2> observableRight, Action2<T1, T2> action); static Observable<T> async(List<T> list); static Observable<T> async(Observable<T> observable); static Observable<Double> sum(Observable<Double> observable); static Observable<T> doIfEmpty(Observable<T> output, Action0 action); static Observable<T> exception(Supplier<Exception> supplier); static Observable<T> singleOrEmpty(Observable<? extends Collection<T>> collectionObservable); } | @Test public void testAsync() { List<Integer> input = Arrays.asList(0, 4, 3, 1, 2); List<Integer> expectedResult = Arrays.asList(0, 1, 2, 3, 4); List<Integer> actualResult = RxUtils.async(input) .flatMap(i -> Observable.just(i).delay(i * 100, TimeUnit.MILLISECONDS)) .toList() .toBlocking() .single(); assertThat(actualResult).isEqualTo(expectedResult); } |
RxUtils { public static <T> Observable<T> exception(Supplier<Exception> supplier) { return defer(() -> error(supplier.get())); } static FirstThen first(Observable<?> doFirst); static IfThenElse<T> ifTrue(Observable<Boolean> ifValue); static Observable<T1> consolidate(Observable<T1> observableLeft, Observable<T2> observableRight, Action2<T1, T2> action); static Observable<T> async(List<T> list); static Observable<T> async(Observable<T> observable); static Observable<Double> sum(Observable<Double> observable); static Observable<T> doIfEmpty(Observable<T> output, Action0 action); static Observable<T> exception(Supplier<Exception> supplier); static Observable<T> singleOrEmpty(Observable<? extends Collection<T>> collectionObservable); } | @Test(expected = RuntimeException.class) public void testException() { empty() .switchIfEmpty(RxUtils.exception(RuntimeException::new)) .toBlocking() .first(); } |
SpanBuilderR implements Tracer.SpanBuilder { @Override public Span start() { Span wspan = wrapped.start(); String spanId = UUID.randomUUID().toString(); wspan.setBaggageItem(BAGGAGE_SPANID_KEY, spanId); if (references.isEmpty() && !ignoreActiveSpan && null != scopeManager.activeSpan()) { asChildOf(scopeManager.activeSpan()); } return new SpanR(wspan, reporter, spanId, operationName, tags, references); } SpanBuilderR(Tracer.SpanBuilder wrapped, Reporter reporter, String operationName, ScopeManager scopeManager); @Override Tracer.SpanBuilder asChildOf(SpanContext spanContext); @Override Tracer.SpanBuilder asChildOf(Span parent); @Override Tracer.SpanBuilder addReference(String s, SpanContext spanContext); @Override Tracer.SpanBuilder ignoreActiveSpan(); @Override Tracer.SpanBuilder withTag(String s, String s1); @Override Tracer.SpanBuilder withTag(String s, boolean b); @Override Tracer.SpanBuilder withTag(String s, Number number); @Override Tracer.SpanBuilder withTag(final Tag<T> tag, final T value); @Override Tracer.SpanBuilder withStartTimestamp(long l); @Override Span start(); } | @Test public void subspan_implicitAsChildOf() { final String spanId = "some-span-id-" + System.currentTimeMillis(); final Map<String, String> parentBaggage = new HashMap<>(); parentBaggage.put(SpanBuilderR.BAGGAGE_SPANID_KEY, spanId); when(scopeManagerMock.activeSpan()).thenReturn(parentSpanMock); when(parentSpanContextMock.baggageItems()).thenReturn(parentBaggage.entrySet()); final SpanR spanR = (SpanR) new SpanBuilderR(spanBuilderMock, reporterMock, "some-operation", scopeManagerMock).start(); assertFalse(spanR.references.isEmpty()); verify(scopeManagerMock, atLeastOnce()).activeSpan(); verify(spanBuilderMock).start(); verify(parentSpanMock).context(); verify(parentSpanContextMock, atLeastOnce()).baggageItems(); assertEquals(spanId, spanR.references.get(CHILD_OF)); } |
HtmlUtil { public static void fixImageSourceUrls(Map<String, Object> fileContents, JBakeConfiguration configuration) { String htmlContent = fileContents.get(Attributes.BODY).toString(); boolean prependSiteHost = configuration.getImgPathPrependHost(); String siteHost = configuration.getSiteHost(); String uri = getDocumentUri(fileContents); Document document = Jsoup.parseBodyFragment(htmlContent); Elements allImgs = document.getElementsByTag("img"); for (Element img : allImgs) { transformImageSource(img, uri, siteHost, prependSiteHost); } fileContents.put(Attributes.BODY, document.body().html()); } private HtmlUtil(); static void fixImageSourceUrls(Map<String, Object> fileContents, JBakeConfiguration configuration); } | @Test public void shouldNotAddBodyHTMLElement() { Map<String, Object> fileContent = new HashMap<String, Object>(); fileContent.put(Attributes.ROOTPATH, "../../../"); fileContent.put(Attributes.URI, "blog/2017/05/first_post.html"); fileContent.put(Attributes.BODY, "<div> Test <img src='/blog/2017/05/first.jpg' /></div>"); HtmlUtil.fixImageSourceUrls(fileContent, config); String body = fileContent.get(Attributes.BODY).toString(); assertThat(body).doesNotContain("<body>"); assertThat(body).doesNotContain("</body>"); }
@Test public void shouldNotAddSiteHost() { Map<String, Object> fileContent = new HashMap<String, Object>(); fileContent.put(Attributes.ROOTPATH, "../../../"); fileContent.put(Attributes.URI, "blog/2017/05/first_post.html"); fileContent.put(Attributes.BODY, "<div> Test <img src='./first.jpg' /></div>"); config.setImgPathPrependHost(false); HtmlUtil.fixImageSourceUrls(fileContent, config); String body = fileContent.get(Attributes.BODY).toString(); assertThat(body).contains("src=\"blog/2017/05/first.jpg\""); }
@Test public void shouldAddSiteHostWithRelativeImageToDocument() { Map<String, Object> fileContent = new HashMap<>(); fileContent.put(Attributes.ROOTPATH, "../../../"); fileContent.put(Attributes.URI, "blog/2017/05/first_post.html"); fileContent.put(Attributes.BODY, "<div> Test <img src='img/deeper/underground.jpg' /></div>"); config.setImgPathPrependHost(true); HtmlUtil.fixImageSourceUrls(fileContent, config); String body = fileContent.get(Attributes.BODY).toString(); assertThat(body).contains("src=\"http: }
@Test public void shouldAddContentPath() { Map<String, Object> fileContent = new HashMap<String, Object>(); fileContent.put(Attributes.ROOTPATH, "../../../"); fileContent.put(Attributes.URI, "blog/2017/05/first_post.html"); fileContent.put(Attributes.BODY, "<div> Test <img src='./first.jpg' /></div>"); HtmlUtil.fixImageSourceUrls(fileContent, config); String body = fileContent.get(Attributes.BODY).toString(); assertThat(body).contains("src=\"http: }
@Test public void shouldAddContentPathForCurrentDirectory() { Map<String, Object> fileContent = new HashMap<String, Object>(); fileContent.put(Attributes.ROOTPATH, "../../../"); fileContent.put(Attributes.URI, "blog/2017/05/first_post.html"); fileContent.put(Attributes.BODY, "<div> Test <img src='first.jpg' /></div>"); HtmlUtil.fixImageSourceUrls(fileContent, config); String body = fileContent.get(Attributes.BODY).toString(); assertThat(body).contains("src=\"http: }
@Test public void shouldNotAddRootPath() { Map<String, Object> fileContent = new HashMap<String, Object>(); fileContent.put(Attributes.ROOTPATH, "../../../"); fileContent.put(Attributes.URI, "blog/2017/05/first_post.html"); fileContent.put(Attributes.BODY, "<div> Test <img src='/blog/2017/05/first.jpg' /></div>"); HtmlUtil.fixImageSourceUrls(fileContent, config); String body = fileContent.get(Attributes.BODY).toString(); assertThat(body).contains("src=\"http: }
@Test public void shouldNotAddRootPathForNoExtension() { Map<String, Object> fileContent = new HashMap<String, Object>(); fileContent.put(Attributes.ROOTPATH, "../../../"); fileContent.put(Attributes.URI, "blog/2017/05/first_post.html"); fileContent.put(Attributes.NO_EXTENSION_URI, "blog/2017/05/first_post/"); fileContent.put(Attributes.BODY, "<div> Test <img src='/blog/2017/05/first.jpg' /></div>"); HtmlUtil.fixImageSourceUrls(fileContent, config); String body = fileContent.get(Attributes.BODY).toString(); assertThat(body).contains("src=\"http: }
@Test public void shouldAddContentPathForNoExtension() { Map<String, Object> fileContent = new HashMap<String, Object>(); fileContent.put(Attributes.ROOTPATH, "../../../"); fileContent.put(Attributes.URI, "blog/2017/05/first_post.html"); fileContent.put(Attributes.NO_EXTENSION_URI, "blog/2017/05/first_post/"); fileContent.put(Attributes.BODY, "<div> Test <img src='./first.jpg' /></div>"); HtmlUtil.fixImageSourceUrls(fileContent, config); String body = fileContent.get(Attributes.BODY).toString(); assertThat(body).contains("src=\"http: }
@Test public void shouldNotChangeForHTTP() { Map<String, Object> fileContent = new HashMap<String, Object>(); fileContent.put(Attributes.ROOTPATH, "../../../"); fileContent.put(Attributes.URI, "blog/2017/05/first_post.html"); fileContent.put(Attributes.NO_EXTENSION_URI, "blog/2017/05/first_post/"); fileContent.put(Attributes.BODY, "<div> Test <img src='http: HtmlUtil.fixImageSourceUrls(fileContent, config); String body = fileContent.get(Attributes.BODY).toString(); assertThat(body).contains("src=\"http: }
@Test public void shouldNotChangeForHTTPS() { Map<String, Object> fileContent = new HashMap<String, Object>(); fileContent.put(Attributes.ROOTPATH, "../../../"); fileContent.put(Attributes.URI, "blog/2017/05/first_post.html"); fileContent.put(Attributes.NO_EXTENSION_URI, "blog/2017/05/first_post/"); fileContent.put(Attributes.BODY, "<div> Test <img src='https: HtmlUtil.fixImageSourceUrls(fileContent, config); String body = fileContent.get(Attributes.BODY).toString(); assertThat(body).contains("src=\"https: } |
FileUtil { public static boolean isFileInDirectory(File file, File directory) throws IOException { return (file.exists() && !file.isHidden() && directory.isDirectory() && file.getCanonicalPath().startsWith(directory.getCanonicalPath())); } static FileFilter getFileFilter(); static FileFilter getNotContentFileFilter(); static boolean directoryOnlyIfNotIgnored(File file); static boolean isExistingFolder(File f); static File getRunningLocation(); static String fileExt(File src); static String fileExt(String name); static String sha1(File sourceFile); static String asPath(File file); static String asPath(String path); static String getPathToRoot(JBakeConfiguration config, File rootPath, File sourceFile); static String getUriPathToDestinationRoot(JBakeConfiguration config, File sourceFile); static String getUriPathToContentRoot(JBakeConfiguration config, File sourceFile); static boolean isFileInDirectory(File file, File directory); static final String URI_SEPARATOR_CHAR; } | @Test public void testIsFileInDirectory() throws Exception { File fixtureDir = new File(this.getClass().getResource("/fixture").getFile()); File jbakeFile = new File(fixtureDir.getCanonicalPath() + File.separatorChar + "jbake.properties"); assertTrue("jbake.properties expected to be in /fixture directory", FileUtil.isFileInDirectory(jbakeFile, fixtureDir)); File contentFile = new File(fixtureDir.getCanonicalPath() + File.separatorChar + "content" + File.separatorChar + "projects.html"); assertTrue("projects.html expected to be nested in the /fixture directory", FileUtil.isFileInDirectory(contentFile, fixtureDir)); File contentDir = contentFile.getParentFile(); assertFalse("jbake.properties file should not be in the /fixture/content directory", FileUtil.isFileInDirectory(jbakeFile, contentDir)); } |
FileUtil { static public String getUriPathToContentRoot(JBakeConfiguration config, File sourceFile) { return getPathToRoot(config, config.getContentFolder(), sourceFile); } static FileFilter getFileFilter(); static FileFilter getNotContentFileFilter(); static boolean directoryOnlyIfNotIgnored(File file); static boolean isExistingFolder(File f); static File getRunningLocation(); static String fileExt(File src); static String fileExt(String name); static String sha1(File sourceFile); static String asPath(File file); static String asPath(String path); static String getPathToRoot(JBakeConfiguration config, File rootPath, File sourceFile); static String getUriPathToDestinationRoot(JBakeConfiguration config, File sourceFile); static String getUriPathToContentRoot(JBakeConfiguration config, File sourceFile); static boolean isFileInDirectory(File file, File directory); static final String URI_SEPARATOR_CHAR; } | @Test public void testGetContentRoothPath() throws Exception { File source = TestUtils.getTestResourcesAsSourceFolder(); ConfigUtil util = new ConfigUtil(); DefaultJBakeConfiguration config = (DefaultJBakeConfiguration) util.loadConfig(source); String path = FileUtil.getUriPathToContentRoot(config, new File(config.getContentFolder(), "index.html")); assertThat(path).isEqualTo(""); path = FileUtil.getUriPathToContentRoot(config, new File(config.getContentFolder(), "/blog/index.html")); assertThat(path).isEqualTo("../"); path = FileUtil.getUriPathToContentRoot(config, new File(config.getContentFolder(), "/blog/level2/index.html")); assertThat(path).isEqualTo("../../"); } |
ContentStore { public ODocument mergeDocument(Map<String, ? extends Object> incomingDocMap) { String sourceUri = (String) incomingDocMap.get(DocumentAttributes.SOURCE_URI.toString()); if (null == sourceUri) { throw new IllegalArgumentException("Document sourceUri is null."); } String docType = (String) incomingDocMap.get(Crawler.Attributes.TYPE); if (null == docType) { throw new IllegalArgumentException("Document docType is null."); } String sql = "SELECT * FROM " + docType + " WHERE sourceuri=?"; activateOnCurrentThread(); List<ODocument> results = db.command(new OSQLSynchQuery<ODocument>(sql)).execute(sourceUri); if (results.isEmpty()) { throw new JBakeException("No document with sourceUri '" + sourceUri + "'."); } ODocument incomingDoc = new ODocument(docType); incomingDoc.fromMap(incomingDocMap); ODocument merged = results.get(0).merge(incomingDoc, true, false); return merged; } ContentStore(final String type, String name); void startup(); long getStart(); void setStart(int start); long getLimit(); void setLimit(int limit); void resetPagination(); final void updateSchema(); void close(); void shutdown(); void drop(); ODocument mergeDocument(Map<String, ? extends Object> incomingDocMap); long getDocumentCount(String docType); long getPublishedCount(String docType); DocumentList getDocumentByUri(String docType, String uri); DocumentList getDocumentStatus(String docType, String uri); DocumentList getPublishedPosts(); DocumentList getPublishedPosts(boolean applyPaging); DocumentList getPublishedPostsByTag(String tag); DocumentList getPublishedDocumentsByTag(String tag); DocumentList getPublishedPages(); DocumentList getPublishedContent(String docType); DocumentList getAllContent(String docType); DocumentList getAllContent(String docType, boolean applyPaging); DocumentList getUnrenderedContent(String docType); void deleteContent(String docType, String uri); void markContentAsRendered(String docType); void deleteAllByDocType(String docType); Set<String> getTags(); Set<String> getAllTags(); void updateAndClearCacheIfNeeded(boolean needed, File templateFolder); boolean isActive(); } | @Test public void testMergeDocument() { final String uri = "test/testMergeDocument"; ODocument doc = new ODocument(DOC_TYPE_POST); Map<String, String> values = new HashMap(); values.put(Crawler.Attributes.TYPE, DOC_TYPE_POST); values.put(DocumentAttributes.SOURCE_URI.toString(), uri); values.put("foo", "originalValue"); doc.fromMap(values); doc.save(); values.put("foo", "newValue"); db.mergeDocument(values); DocumentList docs = db.getDocumentByUri(DOC_TYPE_POST, uri); assertEquals(1, docs.size()); assertEquals("newValue", docs.get(0).get("foo")); values.put("foo", "anotherValue"); db.mergeDocument(values); docs = db.getDocumentByUri(DOC_TYPE_POST, uri); assertEquals(1, docs.size()); assertEquals("anotherValue", docs.get(0).get("foo")); db.deleteContent(DOC_TYPE_POST, uri); docs = db.getDocumentByUri(DOC_TYPE_POST, uri); assertEquals(0, docs.size()); } |
Parser { public Map<String, Object> processFile(File file) { ParserEngine engine = Engines.get(FileUtil.fileExt(file)); if (engine==null) { LOGGER.error("Unable to find suitable markup engine for {}",file); return null; } return engine.parse(config, file); } Parser(JBakeConfiguration config); Map<String, Object> processFile(File file); } | @Test public void parseValidHTMLFile() { Map<String, Object> map = parser.processFile(validHTMLFile); Assert.assertNotNull(map); Assert.assertEquals("draft", map.get("status")); Assert.assertEquals("post", map.get("type")); Assert.assertEquals("This is a Title = This is a valid Title", map.get("title")); Assert.assertNotNull(map.get("date")); Calendar cal = Calendar.getInstance(); cal.setTime((Date) map.get("date")); Assert.assertEquals(8, cal.get(Calendar.MONTH)); Assert.assertEquals(2, cal.get(Calendar.DAY_OF_MONTH)); Assert.assertEquals(2013, cal.get(Calendar.YEAR)); }
@Test public void parseInvalidHTMLFile() { Map<String, Object> map = parser.processFile(invalidHTMLFile); Assert.assertNull(map); }
@Test public void parseInvalidExtension(){ Map<String, Object> map = parser.processFile(invalidExtensionFile); Assert.assertNull(map); }
@Test public void parseMarkdownFileWithCustomHeaderSeparator() { config.setHeaderSeparator(customHeaderSeparator); Map<String, Object> map = parser.processFile(validMarkdownFileWithCustomHeader); Assert.assertNotNull(map); Assert.assertEquals("draft", map.get("status")); Assert.assertEquals("post", map.get("type")); assertThat(map.get("body").toString()) .contains("<p>A paragraph</p>"); }
@Test public void parseMarkdownFileWithDefaultStatus() { config.setDefaultStatus("published"); Map<String, Object> map = parser.processFile(validMarkdownFileWithDefaultStatus); Assert.assertNotNull(map); Assert.assertEquals("published", map.get("status")); Assert.assertEquals("post", map.get("type")); }
@Test public void parseMarkdownFileWithDefaultTypeAndStatus() { config.setDefaultStatus("published"); config.setDefaultType("page"); Map<String, Object> map = parser.processFile(validMarkdownFileWithDefaultTypeAndStatus); Assert.assertNotNull(map); Assert.assertEquals("published", map.get("status")); Assert.assertEquals("page", map.get("type")); }
@Test public void parseInvalidMarkdownFileWithoutDefaultStatus() { config.setDefaultStatus(""); config.setDefaultType("page"); Map<String, Object> map = parser.processFile(invalidMarkdownFileWithoutDefaultStatus); Assert.assertNull(map); }
@Test public void parseInvalidMarkdownFile() { Map<String, Object> map = parser.processFile(invalidMDFile); Assert.assertNull(map); }
@Test public void sanitizeKeysAndValues() { Map<String, Object> map = parser.processFile(validaAsciidocWithUnsanitizedHeader); assertThat(map.get("status")).isEqualTo("draft"); assertThat(map.get("title")).isEqualTo("Title"); assertThat(map.get("type")).isEqualTo("post"); assertThat(map.get("custom")).isEqualTo("custom without bom's"); assertThat(map.get("tags")).isEqualTo(Arrays.asList("jbake", "java", "tag with space").toArray()); }
@Test public void sanitizeTags() { config.setProperty(JBakeProperty.TAG_SANITIZE, true); Map<String, Object> map = parser.processFile(validaAsciidocWithUnsanitizedHeader); assertThat(map.get("tags")).isEqualTo(Arrays.asList("jbake", "java", "tag-with-space").toArray()); }
@Test public void parseValidHTMLWithJSONFile() { Map<String, Object> map = parser.processFile(validHTMLWithJSONFile); assertJSONExtracted(map.get("jsondata")); }
@Test public void parseValidAsciiDocWithJSONFile() { Map<String, Object> map = parser.processFile(validAsciiDocWithJSONFile); assertJSONExtracted(map.get("jsondata")); }
@Test public void testValidAsciiDocWithADHeaderJSONFile() { Map<String, Object> map = parser.processFile(validAsciiDocWithADHeaderJSONFile); assertJSONExtracted(map.get("jsondata")); } |
PagingHelper { public int getNumberOfPages() { return (int) Math.ceil((totalDocuments * 1.0) / (postsPerPage * 1.0)); } PagingHelper(long totalDocuments, int postsPerPage); int getNumberOfPages(); String getNextFileName(int currentPageNumber); String getPreviousFileName(int currentPageNumber); String getCurrentFileName(int page, String fileName); } | @Test public void getNumberOfPages() throws Exception { int expected = 3; int total = 5; int perPage = 2; PagingHelper helper = new PagingHelper(total,perPage); Assert.assertEquals( expected, helper.getNumberOfPages() ); } |
Crawler { public void crawl() { crawl(config.getContentFolder()); LOGGER.info("Content detected:"); for (String docType : DocumentTypes.getDocumentTypes()) { long count = db.getDocumentCount(docType); if (count > 0) { LOGGER.info("Parsed {} files of type: {}", count, docType); } } } @Deprecated Crawler(ContentStore db, File source, CompositeConfiguration config); Crawler(ContentStore db, JBakeConfiguration config); void crawl(); } | @Test public void crawl() { Crawler crawler = new Crawler(db, config); crawler.crawl(); Assert.assertEquals(4, db.getDocumentCount("post")); Assert.assertEquals(3, db.getDocumentCount("page")); DocumentList results = db.getPublishedPosts(); assertThat(results.size()).isEqualTo(3); for (Map<String, Object> content : results) { assertThat(content) .containsKey(Crawler.Attributes.ROOTPATH) .containsValue("../../../"); } DocumentList allPosts = db.getAllContent("post"); assertThat(allPosts.size()).isEqualTo(4); for (Map<String, Object> content : allPosts) { if (content.get(Crawler.Attributes.TITLE).equals("Draft Post")) { assertThat(content).containsKey(Crawler.Attributes.DATE); } } DocumentList publishedPostsByTag = db.getPublishedPostsByTag("blog"); Assert.assertEquals(3, publishedPostsByTag.size()); }
@Test public void renderWithPrettyUrls() throws Exception { config.setUriWithoutExtension(true); config.setPrefixForUriWithoutExtension("/blog"); Crawler crawler = new Crawler(db, config); crawler.crawl(); Assert.assertEquals(4, db.getDocumentCount("post")); Assert.assertEquals(3, db.getDocumentCount("page")); DocumentList documents = db.getPublishedPosts(); for (Map<String, Object> model : documents) { String noExtensionUri = "blog/\\d{4}/" + FilenameUtils.getBaseName((String) model.get("file")) + "/"; Assert.assertThat(model.get("noExtensionUri"), RegexMatcher.matches(noExtensionUri)); Assert.assertThat(model.get("uri"), RegexMatcher.matches(noExtensionUri + "index\\.html")); assertThat(model).containsEntry("rootpath", "../../../"); } } |
Oven { public Utensils getUtensils() { return utensils; } @Deprecated Oven(final File source, final File destination, final boolean isClearCache); @Deprecated Oven(final File source, final File destination, final CompositeConfiguration config, final boolean isClearCache); Oven(JBakeConfiguration config); Oven(Utensils utensils); @Deprecated CompositeConfiguration getConfig(); @Deprecated void setConfig(final CompositeConfiguration config); @Deprecated void setupPaths(); void bake(File fileToBake); void bake(); List<Throwable> getErrors(); Utensils getUtensils(); } | @Test public void shouldInstantiateNeededUtensils() throws Exception { configuration.setTemplateFolder( folder.newFolder("template") ); configuration.setContentFolder( folder.newFolder("content") ); configuration.setAssetFolder( folder.newFolder("assets") ); Oven oven = new Oven(configuration); assertThat(oven.getUtensils().getContentStore()).isNotNull(); assertThat(oven.getUtensils().getCrawler()).isNotNull(); assertThat(oven.getUtensils().getRenderer()).isNotNull(); assertThat(oven.getUtensils().getAsset()).isNotNull(); assertThat(oven.getUtensils().getConfiguration()).isEqualTo(configuration); } |
Oven { public void bake(File fileToBake) { Asset asset = utensils.getAsset(); if(asset.isAssetFile(fileToBake)) { LOGGER.info("Baking a change to an asset [" + fileToBake.getPath() + "]"); asset.copySingleFile(fileToBake); } else { LOGGER.info("Playing it safe and running a full bake..."); bake(); } } @Deprecated Oven(final File source, final File destination, final boolean isClearCache); @Deprecated Oven(final File source, final File destination, final CompositeConfiguration config, final boolean isClearCache); Oven(JBakeConfiguration config); Oven(Utensils utensils); @Deprecated CompositeConfiguration getConfig(); @Deprecated void setConfig(final CompositeConfiguration config); @Deprecated void setupPaths(); void bake(File fileToBake); void bake(); List<Throwable> getErrors(); Utensils getUtensils(); } | @Test public void shouldCrawlRenderAndCopyAssets() throws Exception { configuration.setTemplateFolder( folder.newFolder("template") ); configuration.setContentFolder( folder.newFolder("content") ); configuration.setAssetFolder( folder.newFolder("assets") ); contentStore = spy(new ContentStore("memory", "documents"+ System.currentTimeMillis())); Crawler crawler = mock(Crawler.class); Renderer renderer = mock(Renderer.class); Asset asset = mock(Asset.class); Utensils utensils = new Utensils(); utensils.setConfiguration(configuration); utensils.setContentStore(contentStore); utensils.setRenderer(renderer); utensils.setCrawler(crawler); utensils.setAsset(asset); Oven oven = new Oven(utensils); oven.bake(); verify(contentStore, times(1)).startup(); verify(renderer,atLeastOnce()).renderIndex(anyString()); verify(crawler,times(1)).crawl(); verify(asset,times(1)).copy(); } |
PagingHelper { public String getPreviousFileName(int currentPageNumber) throws URISyntaxException { if (isFirstPage(currentPageNumber)) { return null; } else { if ( currentPageNumber == 2 ) { return ""; } else { return new URI((currentPageNumber - 1) + URI_SEPARATOR).toString(); } } } PagingHelper(long totalDocuments, int postsPerPage); int getNumberOfPages(); String getNextFileName(int currentPageNumber); String getPreviousFileName(int currentPageNumber); String getCurrentFileName(int page, String fileName); } | @Test public void shouldReturnRootIndexPage() throws Exception { PagingHelper helper = new PagingHelper(5,2); String previousFileName = helper.getPreviousFileName(2); Assert.assertThat("", is( previousFileName) ); }
@Test public void shouldReturnPreviousFileName() throws Exception { PagingHelper helper = new PagingHelper(5,2); String previousFileName = helper.getPreviousFileName(3); Assert.assertThat("2/", is( previousFileName) ); }
@Test public void shouldReturnNullIfNoPreviousPageAvailable() throws Exception { PagingHelper helper = new PagingHelper(5,2); String previousFileName = helper.getPreviousFileName(1); Assert.assertNull( previousFileName ); } |
ModelExtractorsDocumentTypeListener implements DocumentTypeListener { @Override public void added(String doctype) { ModelExtractors.getInstance().registerExtractorsForCustomTypes(doctype); } @Override void added(String doctype); } | @Test public void shouldRegisterExtractorsForCustomType() { String newDocumentType = "project"; DocumentTypes.addDocumentType(newDocumentType); ModelExtractorsDocumentTypeListener listener = new ModelExtractorsDocumentTypeListener(); listener.added(newDocumentType); assertThat(ModelExtractors.getInstance().containsKey("projects")).isTrue(); assertThat(ModelExtractors.getInstance().containsKey("published_projects")).isTrue(); } |
PagingHelper { public String getNextFileName(int currentPageNumber) throws URISyntaxException { if (currentPageNumber < getNumberOfPages()) { return new URI((currentPageNumber + 1) + URI_SEPARATOR).toString(); } else { return null; } } PagingHelper(long totalDocuments, int postsPerPage); int getNumberOfPages(); String getNextFileName(int currentPageNumber); String getPreviousFileName(int currentPageNumber); String getCurrentFileName(int page, String fileName); } | @Test public void shouldReturnNullIfNextPageNotAvailable() throws Exception { PagingHelper helper = new PagingHelper(5,2); String nextFileName = helper.getNextFileName(3); Assert.assertNull( nextFileName ); }
@Test public void shouldReturnNextFileName() throws Exception { PagingHelper helper = new PagingHelper(5,2); String nextFileName = helper.getNextFileName(2); Assert.assertThat("3/", is( nextFileName) ); } |
Main { protected void run(String[] args) { SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); LaunchOptions res = parseArguments(args); final JBakeConfiguration config; try { if (res.isRunServer()) { config = getJBakeConfigurationFactory().createJettyJbakeConfiguration(res.getSource(), res.getDestination(), res.isClearCache()); } else { config = getJBakeConfigurationFactory().createDefaultJbakeConfiguration(res.getSource(), res.getDestination(), res.isClearCache()); } } catch (final ConfigurationException e) { throw new JBakeException("Configuration error: " + e.getMessage(), e); } run(res, config); } Main(); protected Main(Baker baker, JettyServer jetty, BakeWatcher watcher); static void main(final String[] args); JBakeConfigurationFactory getJBakeConfigurationFactory(); void setJBakeConfigurationFactory(JBakeConfigurationFactory factory); } | @Test public void launchJetty() throws Exception { File currentWorkingdir = folder.newFolder("src", "jbake"); File expectedOutput = new File(currentWorkingdir,"output"); mockJettyConfiguration(currentWorkingdir,expectedOutput); String[] args = {"-s"}; main.run(args); verify(mockJetty).run(expectedOutput.getPath(),"8820"); }
@Test public void launchBakeAndJetty() throws Exception { File sourceFolder = folder.newFolder("src", "jbake"); File expectedOutput = new File(sourceFolder, "output"); mockJettyConfiguration(sourceFolder, expectedOutput); String[] args = {"-b", "-s"}; main.run(args); verify(mockJetty).run(expectedOutput.getPath(),"8820"); }
@Test public void launchBakeAndJettyWithCustomDirForJetty() throws ConfigurationException, IOException { mockValidSourceFolder("src/jbake", true); String expectedRunPath = "src" + File.separator + "jbake" + File.separator + "output"; String[] args = {"-b", "-s", "src/jbake"}; main.run(args); verify(mockJetty).run(expectedRunPath,"8820"); }
@Test public void launchJettyWithCustomServerSourceDir() throws Exception { File sourceFolder = mockValidSourceFolder("build/jbake", true); String[] args = {sourceFolder.getPath(), "-s"}; main.run(args); verify(mockJetty).run(sourceFolder.getPath(),"8820"); }
@Test public void launchJettyWithCustomDestinationDir() throws Exception { File sourceFolder = mockValidSourceFolder("src/jbake", true); String[] args = {"-s", sourceFolder.getPath()}; main.run(args); verify(mockJetty).run(sourceFolder.getPath(),"8820"); }
@Test public void launchJettyWithCustomSrcAndDestDir() throws Exception { File sourceFolder = mockValidSourceFolder("src/jbake", true); final File exampleOutput = folder.newFolder("build","jbake"); String[] args = {sourceFolder.getPath(), exampleOutput.getPath(), "-s"}; main.run(args); verify(mockJetty).run(exampleOutput.getPath(),"8820"); }
@Test public void launchJettyWithCustomDestViaConfig() throws Exception { String[] args = {"-s"}; final File exampleOutput = folder.newFolder("build","jbake"); DefaultJBakeConfiguration configuration = stubConfig(); configuration.setDestinationFolder(exampleOutput); main.run(stubOptions(args), configuration); verify(mockJetty).run(exampleOutput.getPath(),"8820"); }
@Test public void launchJettyWithCmdlineOverridingProperties() throws Exception { File sourceFolder = mockValidSourceFolder("src/jbake", true); final File expectedOutput = folder.newFolder("build","jbake"); final File configTarget = folder.newFolder("target","jbake"); String[] args = {sourceFolder.getPath(), expectedOutput.getPath(), "-s"}; DefaultJBakeConfiguration configuration = stubConfig(); configuration.setDestinationFolder(configTarget); main.run(stubOptions(args), configuration); verify(mockJetty).run(expectedOutput.getPath(),"8820"); } |
LaunchOptions { public boolean isHelpNeeded() { return helpNeeded || !(isBake() || isRunServer() || isInit() || source != null || destination != null); } String getTemplate(); File getSource(); String getSourceValue(); File getDestination(); String getDestinationValue(); boolean isHelpNeeded(); boolean isRunServer(); boolean isInit(); boolean isClearCache(); boolean isBake(); } | @Test public void showHelp() throws Exception { String[] args = {"-h"}; LaunchOptions res = new LaunchOptions(); CmdLineParser parser = new CmdLineParser(res); parser.parseArgument(args); assertThat(res.isHelpNeeded()).isTrue(); } |
LaunchOptions { public boolean isRunServer() { return runServer; } String getTemplate(); File getSource(); String getSourceValue(); File getDestination(); String getDestinationValue(); boolean isHelpNeeded(); boolean isRunServer(); boolean isInit(); boolean isClearCache(); boolean isBake(); } | @Test public void runServer() throws Exception { String[] args = {"-s"}; LaunchOptions res = new LaunchOptions(); CmdLineParser parser = new CmdLineParser(res); parser.parseArgument(args); assertThat(res.isRunServer()).isTrue(); } |
LaunchOptions { public boolean isBake() { return bake || (source != null && destination != null); } String getTemplate(); File getSource(); String getSourceValue(); File getDestination(); String getDestinationValue(); boolean isHelpNeeded(); boolean isRunServer(); boolean isInit(); boolean isClearCache(); boolean isBake(); } | @Test public void bake() throws Exception { String[] args = {"-b"}; LaunchOptions res = new LaunchOptions(); CmdLineParser parser = new CmdLineParser(res); parser.parseArgument(args); assertThat(res.isBake()).isTrue(); } |
DocumentTypes { public static boolean contains(String documentType) { return DEFAULT_DOC_TYPES.contains(documentType); } private DocumentTypes(); static void resetDocumentTypes(); static void addDocumentType(String docType); static void addListener( DocumentTypeListener listener ); static String[] getDocumentTypes(); static boolean contains(String documentType); } | @Test public void shouldTellIfDocumentTypeIsUnknown() { String unknownType = "unknown"; assertThat( DocumentTypes.contains(unknownType) ).isFalse(); } |
SitemapRenderer implements RenderingTool { @Override public int render(Renderer renderer, ContentStore db, JBakeConfiguration config) throws RenderingException { if (config.getRenderSiteMap()) { try { renderer.renderSitemap(config.getSiteMapFileName()); return 1; } catch (Exception e) { throw new RenderingException(e); } } else { return 0; } } @Override int render(Renderer renderer, ContentStore db, JBakeConfiguration config); @Override int render(Renderer renderer, ContentStore db, File destination, File templatesPath, CompositeConfiguration config); } | @Test public void returnsZeroWhenConfigDoesNotRenderSitemaps() throws RenderingException { SitemapRenderer renderer = new SitemapRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderSiteMap()).thenReturn(false); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); int renderResponse = renderer.render(mockRenderer, contentStore, configuration); assertThat(renderResponse).isEqualTo(0); }
@Test public void doesNotRenderWhenConfigDoesNotRenderSitemaps() throws Exception { SitemapRenderer renderer = new SitemapRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderSiteMap()).thenReturn(false); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); renderer.render(mockRenderer, contentStore, configuration); verify(mockRenderer, never()).renderSitemap(anyString()); }
@Test public void returnsOneWhenConfigRendersSitemaps() throws RenderingException { SitemapRenderer renderer = new SitemapRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderSiteMap()).thenReturn(true); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); int renderResponse = renderer.render(mockRenderer, contentStore, configuration); assertThat(renderResponse).isEqualTo(1); }
@Test public void doesRenderWhenConfigDoesRenderSitemaps() throws Exception { SitemapRenderer renderer = new SitemapRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderSiteMap()).thenReturn(true); when(configuration.getSiteMapFileName()).thenReturn("mocksitemap.html"); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); renderer.render(mockRenderer, contentStore, configuration); verify(mockRenderer, times(1)).renderSitemap(anyString()); }
@Test(expected = RenderingException.class) public void propogatesRenderingException() throws Exception { SitemapRenderer renderer = new SitemapRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderSiteMap()).thenReturn(true); when(configuration.getSiteMapFileName()).thenReturn("mocksitemap.html"); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); doThrow(new Exception()).when(mockRenderer).renderSitemap(anyString()); renderer.render(mockRenderer, contentStore, configuration); verify(mockRenderer, never()).renderSitemap(anyString()); } |
TagsRenderer implements RenderingTool { @Override public int render(Renderer renderer, ContentStore db, JBakeConfiguration config) throws RenderingException { if (config.getRenderTags()) { try { return renderer.renderTags(config.getTagPathName()); } catch (Exception e) { throw new RenderingException(e); } } else { return 0; } } @Override int render(Renderer renderer, ContentStore db, JBakeConfiguration config); @Override int render(Renderer renderer, ContentStore db, File destination, File templatesPath, CompositeConfiguration config); } | @Test public void returnsZeroWhenConfigDoesNotRenderTags() throws RenderingException { TagsRenderer renderer = new TagsRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderTags()).thenReturn(false); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); int renderResponse = renderer.render(mockRenderer, contentStore, configuration); assertThat(renderResponse).isEqualTo(0); }
@Test public void doesNotRenderWhenConfigDoesNotRenderTags() throws Exception { TagsRenderer renderer = new TagsRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderTags()).thenReturn(false); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); renderer.render(mockRenderer, contentStore, configuration); verify(mockRenderer, never()).renderTags(anyString()); }
@Test public void returnsOneWhenConfigRendersIndices() throws Exception { TagsRenderer renderer = new TagsRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderTags()).thenReturn(true); when(configuration.getTagPathName()).thenReturn("mocktagpath"); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); Set<String> tags = new HashSet<String>(Arrays.asList("tag1", "tags2")); when(contentStore.getTags()).thenReturn(tags); when(mockRenderer.renderTags(anyString())).thenReturn(1); int renderResponse = renderer.render(mockRenderer, contentStore, configuration); assertThat(renderResponse).isEqualTo(1); }
@Test public void doesRenderWhenConfigDoesRenderIndices() throws Exception { TagsRenderer renderer = new TagsRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderTags()).thenReturn(true); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); Set<String> tags = new HashSet<String>(Arrays.asList("tag1", "tags2")); when(contentStore.getTags()).thenReturn(tags); when(configuration.getTagPathName()).thenReturn("mockTagfile.html"); renderer.render(mockRenderer, contentStore, configuration); verify(mockRenderer, times(1)).renderTags(anyString()); }
@Test(expected = RenderingException.class) public void propogatesRenderingException() throws Exception { TagsRenderer renderer = new TagsRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderTags()).thenReturn(true); when(configuration.getTagPathName()).thenReturn("mocktagpath/tag"); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); doThrow(new Exception()).when(mockRenderer).renderTags(anyString()); renderer.render(mockRenderer, contentStore, configuration); verify(mockRenderer, never()).renderTags(anyString()); } |
IndexRenderer implements RenderingTool { @Override public int render(Renderer renderer, ContentStore db, JBakeConfiguration config) throws RenderingException { if (config.getRenderIndex()) { try { String fileName = config.getIndexFileName(); if (config.getPaginateIndex()) { renderer.renderIndexPaging(fileName); } else { renderer.renderIndex(fileName); } return 1; } catch (Exception e) { throw new RenderingException(e); } } else { return 0; } } @Override int render(Renderer renderer, ContentStore db, JBakeConfiguration config); @Override int render(Renderer renderer, ContentStore db, File destination, File templatesPath, CompositeConfiguration config); } | @Test public void returnsZeroWhenConfigDoesNotRenderIndices() throws RenderingException { IndexRenderer renderer = new IndexRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderIndex()).thenReturn(false); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); int renderResponse = renderer.render(mockRenderer, contentStore, configuration); assertThat(renderResponse).isEqualTo(0); }
@Test public void doesNotRenderWhenConfigDoesNotRenderIndices() throws Exception { IndexRenderer renderer = new IndexRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderIndex()).thenReturn(false); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); renderer.render(mockRenderer, contentStore, configuration); verify(mockRenderer, never()).renderIndex(anyString()); }
@Test public void returnsOneWhenConfigRendersIndices() throws RenderingException { IndexRenderer renderer = new IndexRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderIndex()).thenReturn(true); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); int renderResponse = renderer.render(mockRenderer, contentStore, configuration); assertThat(renderResponse).isEqualTo(1); }
@Test(expected = RenderingException.class) public void propagatesRenderingException() throws Exception { IndexRenderer renderer = new IndexRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderIndex()).thenReturn(true); when(configuration.getIndexFileName()).thenReturn("mockindex.html"); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); doThrow(new Exception()).when(mockRenderer).renderIndex(anyString()); renderer.render(mockRenderer, contentStore, configuration); verify(mockRenderer, never()).renderIndex(anyString()); }
@Test public void shouldFallbackToStandardIndexRenderingIfPropertyIsMissing() throws Exception { IndexRenderer renderer = new IndexRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderIndex()).thenReturn(true); when(configuration.getIndexFileName()).thenReturn("mockindex.html"); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); renderer.render(mockRenderer, contentStore, configuration); verify(mockRenderer, times(1)).renderIndex(anyString()); }
@Test public void shouldRenderPaginatedIndex() throws Exception { IndexRenderer renderer = new IndexRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderIndex()).thenReturn(true); when(configuration.getPaginateIndex()).thenReturn(true); when(configuration.getIndexFileName()).thenReturn("mockindex.html"); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); renderer.render(mockRenderer, contentStore, configuration); verify(mockRenderer, times(1)).renderIndexPaging(anyString()); } |
ArchiveRenderer implements RenderingTool { @Override public int render(Renderer renderer, ContentStore db, JBakeConfiguration config) throws RenderingException { if (config.getRenderArchive()) { try { renderer.renderArchive(config.getArchiveFileName()); return 1; } catch (Exception e) { throw new RenderingException(e); } } else { return 0; } } @Override int render(Renderer renderer, ContentStore db, JBakeConfiguration config); @Override int render(Renderer renderer, ContentStore db, File destination, File templatesPath, CompositeConfiguration config); } | @Test public void returnsZeroWhenConfigDoesNotRenderArchives() throws RenderingException { ArchiveRenderer renderer = new ArchiveRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderArchive()).thenReturn(false); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); int renderResponse = renderer.render(mockRenderer, contentStore, configuration); assertThat(renderResponse).isEqualTo(0); }
@Test public void doesNotRenderWhenConfigDoesNotRenderArchives() throws Exception { ArchiveRenderer renderer = new ArchiveRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderArchive()).thenReturn(false); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); renderer.render(mockRenderer, contentStore, configuration); verify(mockRenderer, never()).renderArchive(anyString()); }
@Test public void returnsOneWhenConfigRendersArchives() throws RenderingException { ArchiveRenderer renderer = new ArchiveRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderArchive()).thenReturn(true); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); int renderResponse = renderer.render(mockRenderer, contentStore, configuration); assertThat(renderResponse).isEqualTo(1); }
@Test public void doesRenderWhenConfigDoesRenderArchives() throws Exception { ArchiveRenderer renderer = new ArchiveRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderArchive()).thenReturn(true); when(configuration.getArchiveFileName()).thenReturn("mockarchive.html"); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); renderer.render(mockRenderer, contentStore, configuration); verify(mockRenderer, times(1)).renderArchive(anyString()); }
@Test(expected = RenderingException.class) public void propogatesRenderingException() throws Exception { ArchiveRenderer renderer = new ArchiveRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderArchive()).thenReturn(true); when(configuration.getArchiveFileName()).thenReturn("mockarchive.html"); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); doThrow(new Exception()).when(mockRenderer).renderArchive(anyString()); renderer.render(mockRenderer, contentStore, configuration); verify(mockRenderer, never()).renderArchive("random string"); } |
DocumentsRenderer implements RenderingTool { @Override public int render(Renderer renderer, ContentStore db, JBakeConfiguration config) throws RenderingException { int renderedCount = 0; final List<String> errors = new LinkedList<>(); for (String docType : DocumentTypes.getDocumentTypes()) { DocumentList documentList = db.getUnrenderedContent(docType); if (documentList == null) { continue; } int index = 0; Map<String, Object> nextDocument = null; while (index < documentList.size()) { try { Map<String, Object> document = documentList.get(index); document.put("nextContent", null); document.put("previousContent", null); if (index > 0) { document.put("nextContent", getContentForNav(nextDocument)); } if (index < documentList.size() - 1) { Map<String, Object> tempNext = documentList.get(index + 1); document.put("previousContent", getContentForNav(tempNext)); } nextDocument = document; renderer.render(document); renderedCount++; } catch (Exception e) { errors.add(e.getMessage()); } index++; } db.markContentAsRendered(docType); } if (!errors.isEmpty()) { StringBuilder sb = new StringBuilder(); sb.append("Failed to render documents. Cause(s):"); for (String error : errors) { sb.append("\n").append(error); } throw new RenderingException(sb.toString()); } else { return renderedCount; } } @Override int render(Renderer renderer, ContentStore db, JBakeConfiguration config); @Override int render(Renderer renderer, ContentStore db, File destination, File templatesPath, CompositeConfiguration config); } | @Test public void shouldReturnZeroIfNothingHasRendered() throws Exception { when(db.getUnrenderedContent(anyString())).thenReturn(emptyDocumentList); int renderResponse = documentsRenderer.render(renderer, db, configuration); assertThat(renderResponse).isEqualTo(0); }
@Test public void shouldReturnCountOfProcessedDocuments() throws Exception { DocumentTypes.addDocumentType("customType"); DocumentList documentList = new DocumentList(); documentList.add(emptyDocument()); documentList.add(emptyDocument()); when(db.getUnrenderedContent(anyString())).thenReturn(emptyDocumentList); when(db.getUnrenderedContent("customType")).thenReturn(documentList); int renderResponse = documentsRenderer.render(renderer, db, configuration); assertThat(renderResponse).isEqualTo(2); }
@Test public void shouldThrowAnExceptionWithCollectedErrorMessages() throws Exception { String fakeExceptionMessage = "fake exception"; exception.expect(RenderingException.class); exception.expectMessage(fakeExceptionMessage + "\n" + fakeExceptionMessage); DocumentTypes.addDocumentType("customType"); DocumentList documentList = new DocumentList(); HashMap<String, Object> document = emptyDocument(); HashMap<String, Object> document2 = emptyDocument(); documentList.add(document); documentList.add(document2); doThrow(new Exception(fakeExceptionMessage)).when(renderer).render(ArgumentMatchers.<String, Object>anyMap()); when(db.getUnrenderedContent(anyString())).thenReturn(emptyDocumentList); when(db.getUnrenderedContent("customType")).thenReturn(documentList); int renderResponse = documentsRenderer.render(renderer, db, configuration); assertThat(renderResponse).isEqualTo(2); }
@Test public void shouldContainPostNavigation() throws Exception { DocumentTypes.addDocumentType("customType"); String first = "First Document"; String second = "Second Document"; String third = "Third Document"; String fourth = "Fourth Document"; DocumentList documents = new DocumentList(); documents.add(simpleDocument(fourth)); documents.add(simpleDocument(third)); documents.add(simpleDocument(second)); documents.add(simpleDocument(first)); when(db.getUnrenderedContent("customType")).thenReturn(documents); int renderResponse = documentsRenderer.render(renderer, db, configuration); Map<String, Object> fourthDoc = simpleDocument(fourth); fourthDoc.put("previousContent", simpleDocument(third)); fourthDoc.put("nextContent", null); Map<String, Object> thirdDoc = simpleDocument(third); thirdDoc.put("nextContent", simpleDocument(fourth)); thirdDoc.put("previousContent", simpleDocument(second)); Map<String, Object> secondDoc = simpleDocument(second); secondDoc.put("nextContent", simpleDocument(third)); secondDoc.put("previousContent", simpleDocument(first)); Map<String, Object> firstDoc = simpleDocument(first); firstDoc.put("nextContent", simpleDocument(second)); firstDoc.put("previousContent", null); verify(renderer, times(4)).render(argument.capture()); List<Map<String, Object>> maps = argument.getAllValues(); assertThat(maps).contains(fourthDoc); assertThat(maps).contains(thirdDoc); assertThat(maps).contains(secondDoc); assertThat(maps).contains(firstDoc); assertThat(renderResponse).isEqualTo(4); } |
FeedRenderer implements RenderingTool { @Override public int render(Renderer renderer, ContentStore db, JBakeConfiguration config) throws RenderingException { if (config.getRenderFeed()) { try { renderer.renderFeed(config.getFeedFileName()); return 1; } catch (Exception e) { throw new RenderingException(e); } } else { return 0; } } @Override int render(Renderer renderer, ContentStore db, JBakeConfiguration config); @Override int render(Renderer renderer, ContentStore db, File destination, File templatesPath, CompositeConfiguration config); } | @Test public void returnsZeroWhenConfigDoesNotRenderFeeds() throws RenderingException { FeedRenderer renderer = new FeedRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderFeed()).thenReturn(false); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); int renderResponse = renderer.render(mockRenderer, contentStore, configuration); assertThat(renderResponse).isEqualTo(0); }
@Test public void doesNotRenderWhenConfigDoesNotRenderFeeds() throws Exception { FeedRenderer renderer = new FeedRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderFeed()).thenReturn(false); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); renderer.render(mockRenderer, contentStore, configuration); verify(mockRenderer, never()).renderFeed(anyString()); }
@Test public void returnsOneWhenConfigRendersFeeds() throws RenderingException { FeedRenderer renderer = new FeedRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderFeed()).thenReturn(true); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); int renderResponse = renderer.render(mockRenderer, contentStore, configuration); assertThat(renderResponse).isEqualTo(1); }
@Test public void doesRenderWhenConfigDoesRenderFeeds() throws Exception { FeedRenderer renderer = new FeedRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderFeed()).thenReturn(true); when(configuration.getFeedFileName()).thenReturn("mockfeedfile.xml"); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); renderer.render(mockRenderer, contentStore, configuration); verify(mockRenderer, times(1)).renderFeed(anyString()); }
@Test(expected = RenderingException.class) public void propogatesRenderingException() throws Exception { FeedRenderer renderer = new FeedRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderFeed()).thenReturn(true); when(configuration.getFeedFileName()).thenReturn("mockfeedfile.xml"); ContentStore contentStore = mock(ContentStore.class); Renderer mockRenderer = mock(Renderer.class); doThrow(new Exception()).when(mockRenderer).renderFeed(anyString()); renderer.render(mockRenderer, contentStore, configuration); verify(mockRenderer, never()).renderFeed("random string"); } |
ConfigUtil { public JBakeConfiguration loadConfig(File source) throws ConfigurationException { CompositeConfiguration configuration = load(source); return new DefaultJBakeConfiguration(source, configuration); } JBakeConfiguration loadConfig(File source); } | @Test public void shouldLoadSiteHost() throws Exception { JBakeConfiguration config = util.loadConfig(TestUtils.getTestResourcesAsSourceFolder()); assertThat(config.getSiteHost()).isEqualTo("http: }
@Test public void shouldLoadADefaultConfiguration() throws Exception { JBakeConfiguration config = util.loadConfig(TestUtils.getTestResourcesAsSourceFolder()); assertDefaultPropertiesPresent(config); }
@Test public void shouldLoadACustomConfiguration() throws Exception { File customConfigFile = new File(sourceFolder.toFile(), "jbake.properties"); BufferedWriter writer = new BufferedWriter(new FileWriter(customConfigFile)); writer.append("test.property=12345"); writer.close(); JBakeConfiguration configuration = util.loadConfig(sourceFolder.toFile()); assertThat(configuration.get("test.property")).isEqualTo("12345"); assertDefaultPropertiesPresent(configuration); }
@Test public void shouldThrowAnExceptionIfSourcefolderDoesNotExist() throws Exception { File nonExistentSourceFolder = mock(File.class); when(nonExistentSourceFolder.getAbsolutePath()).thenReturn("/tmp/nonexistent"); when(nonExistentSourceFolder.exists()).thenReturn(false); try { util.loadConfig(nonExistentSourceFolder); fail("Exception should be thrown, as source folder does not exist"); } catch (JBakeException e) { assertThat(e.getMessage()).isEqualTo("The given source folder '/tmp/nonexistent' does not exist."); } }
@Test public void shouldAddSourcefolderToConfiguration() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); JBakeConfiguration config = util.loadConfig(sourceFolder); assertThat(config.getSourceFolder()).isEqualTo(sourceFolder); }
@Test public void shouldThrowAnExceptionIfSourcefolderIsNotADirectory() throws Exception { File sourceFolder = mock(File.class); when(sourceFolder.exists()).thenReturn(true); when(sourceFolder.isDirectory()).thenReturn(false); try { util.loadConfig(sourceFolder); fail("Exception should be thrown if given source folder is not a directory."); } catch (JBakeException e) { assertThat(e.getMessage()).isEqualTo("The given source folder is not a directory."); } }
@Test public void shouldReturnDestinationFolderFromConfiguration() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); File expectedDestinationFolder = new File(sourceFolder, "output"); JBakeConfiguration config = util.loadConfig(sourceFolder); assertThat(config.getDestinationFolder()).isEqualTo(expectedDestinationFolder); }
@Test public void shouldReturnAssetFolderFromConfiguration() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); File expectedDestinationFolder = new File(sourceFolder, "assets"); JBakeConfiguration config = util.loadConfig(sourceFolder); assertThat(config.getAssetFolder()).isEqualTo(expectedDestinationFolder); }
@Test public void shouldReturnTemplateFolderFromConfiguration() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); File expectedDestinationFolder = new File(sourceFolder, "templates"); JBakeConfiguration config = util.loadConfig(sourceFolder); assertThat(config.getTemplateFolder()).isEqualTo(expectedDestinationFolder); }
@Test public void shouldReturnContentFolderFromConfiguration() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); File expectedDestinationFolder = new File(sourceFolder, "content"); JBakeConfiguration config = util.loadConfig(sourceFolder); assertThat(config.getContentFolder()).isEqualTo(expectedDestinationFolder); }
@Test public void shouldGetTemplateFileDoctype() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); File expectedTemplateFile = new File(sourceFolder, "templates/index.ftl"); JBakeConfiguration config = util.loadConfig(sourceFolder); File templateFile = config.getTemplateFileByDocType("masterindex"); assertThat(templateFile).isEqualTo(expectedTemplateFile); }
@Test public void shouldLogWarningIfDocumentTypeNotFound() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); JBakeConfiguration config = util.loadConfig(sourceFolder); config.getTemplateFileByDocType("none"); verify(mockAppender, times(1)).doAppend(captorLoggingEvent.capture()); LoggingEvent loggingEvent = captorLoggingEvent.getValue(); assertThat(loggingEvent.getMessage()).isEqualTo("Cannot find configuration key '{}' for document type '{}'"); }
@Test public void shouldGetTemplateOutputExtension() throws Exception { String docType = "masterindex"; File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); DefaultJBakeConfiguration config = (DefaultJBakeConfiguration) util.loadConfig(sourceFolder); config.setTemplateExtensionForDocType(docType, ".xhtml"); String extension = config.getOutputExtensionByDocType(docType); assertThat(extension).isEqualTo(".xhtml"); }
@Test public void shouldGetMarkdownExtensionsAsList() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); DefaultJBakeConfiguration config = (DefaultJBakeConfiguration) util.loadConfig(sourceFolder); List<String> markdownExtensions = config.getMarkdownExtensions(); assertThat(markdownExtensions).containsExactly("HARDWRAPS", "AUTOLINKS", "FENCED_CODE_BLOCKS", "DEFINITIONS"); }
@Test public void shouldReturnConfiguredDocTypes() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); DefaultJBakeConfiguration config = (DefaultJBakeConfiguration) util.loadConfig(sourceFolder); List<String> docTypes = config.getDocumentTypes(); assertThat(docTypes).containsExactly("allcontent", "masterindex", "feed", "archive", "tag", "tagsindex", "sitemap", "post", "page"); }
@Test public void shouldReturnAListOfAsciidoctorOptionsKeys() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); DefaultJBakeConfiguration config = (DefaultJBakeConfiguration) util.loadConfig(sourceFolder); config.setProperty("asciidoctor.option.requires", "asciidoctor-diagram"); config.setProperty("asciidoctor.option.template_dirs", "src/template1,src/template2"); List<String> options = config.getAsciidoctorOptionKeys(); assertThat(options).contains("requires", "template_dirs"); }
@Test public void shouldReturnAnAsciidoctorOption() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); DefaultJBakeConfiguration config = (DefaultJBakeConfiguration) util.loadConfig(sourceFolder); config.setProperty("asciidoctor.option.requires", "asciidoctor-diagram"); config.setProperty("asciidoctor.option.template_dirs", "src/template1,src/template2"); Object option = config.getAsciidoctorOption("requires"); assertThat(String.valueOf(option)).contains("asciidoctor-diagram"); }
@Test public void shouldReturnAnAsciidoctorOptionWithAListValue() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); DefaultJBakeConfiguration config = (DefaultJBakeConfiguration) util.loadConfig(sourceFolder); config.setProperty("asciidoctor.option.requires", "asciidoctor-diagram"); config.setProperty("asciidoctor.option.template_dirs", "src/template1,src/template2"); Object option = config.getAsciidoctorOption("template_dirs"); assertTrue(option instanceof List); assertThat((List<String>) option).contains("src/template1", "src/template2"); }
@Test public void shouldReturnEmptyStringIfOptionNotAvailable() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); DefaultJBakeConfiguration config = (DefaultJBakeConfiguration) util.loadConfig(sourceFolder); Object option = config.getAsciidoctorOption("template_dirs"); assertThat(String.valueOf(option)).isEmpty(); }
@Test public void shouldLogAWarningIfAsciidocOptionCouldNotBeFound() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); DefaultJBakeConfiguration config = (DefaultJBakeConfiguration) util.loadConfig(sourceFolder); config.getAsciidoctorOption("template_dirs"); verify(mockAppender, times(1)).doAppend(captorLoggingEvent.capture()); LoggingEvent loggingEvent = captorLoggingEvent.getValue(); assertThat(loggingEvent.getMessage()).isEqualTo("Cannot find asciidoctor option '{}.{}'"); }
@Test public void shouldHandleNonExistingFiles() throws Exception { File source = TestUtils.getTestResourcesAsSourceFolder(); File expectedTemplateFolder = new File(source, "templates"); File expectedAssetFolder = new File(source, "assets"); File expectedContentFolder = new File(source, "content"); File expectedDestinationFolder = new File(source, "output"); DefaultJBakeConfiguration config = (DefaultJBakeConfiguration) util.loadConfig(source); config.setTemplateFolder(null); config.setAssetFolder(null); config.setContentFolder(null); config.setDestinationFolder(null); File templateFolder = config.getTemplateFolder(); File assetFolder = config.getAssetFolder(); File contentFolder = config.getContentFolder(); File destinationFolder = config.getDestinationFolder(); assertThat(templateFolder).isEqualTo(expectedTemplateFolder); assertThat(assetFolder).isEqualTo(expectedAssetFolder); assertThat(contentFolder).isEqualTo(expectedContentFolder); assertThat(destinationFolder).isEqualTo(expectedDestinationFolder); }
@Test public void shouldHandleCustomTemplateFolder() throws Exception { File source = TestUtils.getTestResourcesAsSourceFolder(); DefaultJBakeConfiguration config = (DefaultJBakeConfiguration) util.loadConfig(source); config.setTemplateFolder(TestUtils.newFolder(sourceFolder.toFile(), "my_custom_templates")); assertThat(config.getTemplateFolderName()).isEqualTo("my_custom_templates"); }
@Test public void shouldHandleCustomContentFolder() throws Exception { File source = TestUtils.getTestResourcesAsSourceFolder(); DefaultJBakeConfiguration config = (DefaultJBakeConfiguration) util.loadConfig(source); config.setContentFolder(TestUtils.newFolder(sourceFolder.toFile(), "my_custom_content")); assertThat(config.getContentFolderName()).isEqualTo("my_custom_content"); }
@Test public void shouldHandleCustomAssetFolder() throws Exception { File source = TestUtils.getTestResourcesAsSourceFolder(); DefaultJBakeConfiguration config = (DefaultJBakeConfiguration) util.loadConfig(source); config.setAssetFolder(TestUtils.newFolder(sourceFolder.toFile(), "my_custom_asset")); assertThat(config.getAssetFolderName()).isEqualTo("my_custom_asset"); } |
JBakeConfigurationFactory { public DefaultJBakeConfiguration createDefaultJbakeConfiguration(File sourceFolder, File destination, boolean isClearCache) throws ConfigurationException { DefaultJBakeConfiguration configuration = (DefaultJBakeConfiguration) getConfigUtil().loadConfig(sourceFolder); configuration.setDestinationFolder(destination); configuration.setClearCache(isClearCache); return configuration; } JBakeConfigurationFactory(); DefaultJBakeConfiguration createDefaultJbakeConfiguration(File sourceFolder, File destination, boolean isClearCache); DefaultJBakeConfiguration createDefaultJbakeConfiguration(File sourceFolder, File destination, CompositeConfiguration compositeConfiguration, boolean isClearCache); DefaultJBakeConfiguration createDefaultJbakeConfiguration(File sourceFolder, File destination, CompositeConfiguration compositeConfiguration); DefaultJBakeConfiguration createDefaultJbakeConfiguration(File sourceFolder, CompositeConfiguration config); DefaultJBakeConfiguration createJettyJbakeConfiguration(File sourceFolder, File destinationFolder, boolean isClearCache); ConfigUtil getConfigUtil(); void setConfigUtil(ConfigUtil configUtil); } | @Test public void shouldReturnDefaultConfigurationWithDefaultFolders() throws Exception { File sourceFolder = folder.getRoot(); File destinationFolder = folder.newFolder("output"); File templateFolder = new File(folder.getRoot(), "templates"); File assetFolder = new File(folder.getRoot(), "assets"); JBakeConfiguration configuration = new JBakeConfigurationFactory().createDefaultJbakeConfiguration(sourceFolder, destinationFolder, true); assertThat(configuration.getSourceFolder()).isEqualTo(sourceFolder); assertThat(configuration.getDestinationFolder()).isEqualTo(destinationFolder); assertThat(configuration.getTemplateFolder()).isEqualTo(templateFolder); assertThat(configuration.getAssetFolder()).isEqualTo(assetFolder); assertThat(configuration.getClearCache()).isEqualTo(true); }
@Test public void shouldReturnADefaultConfigurationWithSitehost() throws Exception { File sourceFolder = folder.getRoot(); File destinationFolder = folder.newFolder("output"); String siteHost = "http: JBakeConfiguration configuration = new JBakeConfigurationFactory().createDefaultJbakeConfiguration(sourceFolder, destinationFolder, true); assertThat(configuration.getSiteHost()).isEqualTo(siteHost); } |
JBakeConfigurationFactory { public DefaultJBakeConfiguration createJettyJbakeConfiguration(File sourceFolder, File destinationFolder, boolean isClearCache) throws ConfigurationException { DefaultJBakeConfiguration configuration = (DefaultJBakeConfiguration) getConfigUtil().loadConfig(sourceFolder); configuration.setDestinationFolder(destinationFolder); configuration.setClearCache(isClearCache); configuration.setSiteHost("http: return configuration; } JBakeConfigurationFactory(); DefaultJBakeConfiguration createDefaultJbakeConfiguration(File sourceFolder, File destination, boolean isClearCache); DefaultJBakeConfiguration createDefaultJbakeConfiguration(File sourceFolder, File destination, CompositeConfiguration compositeConfiguration, boolean isClearCache); DefaultJBakeConfiguration createDefaultJbakeConfiguration(File sourceFolder, File destination, CompositeConfiguration compositeConfiguration); DefaultJBakeConfiguration createDefaultJbakeConfiguration(File sourceFolder, CompositeConfiguration config); DefaultJBakeConfiguration createJettyJbakeConfiguration(File sourceFolder, File destinationFolder, boolean isClearCache); ConfigUtil getConfigUtil(); void setConfigUtil(ConfigUtil configUtil); } | @Test public void shouldReturnAJettyConfiguration() throws Exception { File sourceFolder = folder.getRoot(); File destinationFolder = folder.newFolder("output"); String siteHost = "http: JBakeConfiguration configuration = new JBakeConfigurationFactory().createJettyJbakeConfiguration(sourceFolder, destinationFolder, true); assertThat(configuration.getSiteHost()).isEqualTo(siteHost); } |
JBakeConfigurationInspector { public void inspect() throws JBakeException { ensureSource(); ensureTemplateFolder(); ensureContentFolder(); ensureDestination(); checkAssetFolder(); } JBakeConfigurationInspector(JBakeConfiguration configuration); void inspect(); } | @Test public void shouldThrowExceptionIfSourceFolderDoesNotExist() throws Exception { File nonExistentFile = new File(folder.toFile(), "nofolder"); JBakeConfiguration configuration = mock(JBakeConfiguration.class); when(configuration.getSourceFolder()).thenReturn(nonExistentFile); JBakeConfigurationInspector inspector = new JBakeConfigurationInspector(configuration); try { inspector.inspect(); fail("should throw a JBakeException"); } catch (JBakeException e) { assertThat(e.getMessage()).isEqualTo("Error: Source folder must exist: " + nonExistentFile.getAbsolutePath()); } }
@Test public void shouldThrowExceptionIfSourceFolderIsNotReadable() throws Exception { File nonReadableFile = mock(File.class); when(nonReadableFile.exists()).thenReturn(true); when(nonReadableFile.isDirectory()).thenReturn(true); when(nonReadableFile.canRead()).thenReturn(false); JBakeConfiguration configuration = mock(JBakeConfiguration.class); when(configuration.getSourceFolder()).thenReturn(nonReadableFile); JBakeConfigurationInspector inspector = new JBakeConfigurationInspector(configuration); try { inspector.inspect(); fail("should throw a JBakeException"); } catch (JBakeException e) { assertThat(e.getMessage()).isEqualTo("Error: Source folder is not readable: " + nonReadableFile.getAbsolutePath()); } }
@Test public void shouldThrowExceptionIfTemplateFolderDoesNotExist() throws Exception { String templateFolderName = "template"; File expectedFolder = new File(folder.toFile(), templateFolderName); JBakeConfiguration configuration = mock(JBakeConfiguration.class); when(configuration.getSourceFolder()).thenReturn(folder.toFile()); when(configuration.getTemplateFolder()).thenReturn(expectedFolder); when(configuration.getTemplateFolderName()).thenReturn(templateFolderName); JBakeConfigurationInspector inspector = new JBakeConfigurationInspector(configuration); try { inspector.inspect(); fail("should throw a JBakeException"); } catch (JBakeException e) { assertThat(e.getMessage()).isEqualTo("Error: Required folder cannot be found! Expected to find [" + templateFolderName + "] at: " + expectedFolder.getAbsolutePath()); } }
@Test public void shouldThrowExceptionIfContentFolderDoesNotExist() throws Exception { String contentFolderName = "content"; String templateFolderName = "template"; File templateFolder = TestUtils.newFolder(folder.toFile(), templateFolderName); File contentFolder = new File(folder.toFile(), contentFolderName); JBakeConfiguration configuration = mock(JBakeConfiguration.class); when(configuration.getSourceFolder()).thenReturn(folder.toFile()); when(configuration.getTemplateFolder()).thenReturn(templateFolder); when(configuration.getTemplateFolderName()).thenReturn(templateFolderName); when(configuration.getContentFolder()).thenReturn(contentFolder); when(configuration.getContentFolderName()).thenReturn(contentFolderName); JBakeConfigurationInspector inspector = new JBakeConfigurationInspector(configuration); try { inspector.inspect(); fail("should throw a JBakeException"); } catch (JBakeException e) { assertThat(e.getMessage()).isEqualTo("Error: Required folder cannot be found! Expected to find [" + contentFolderName + "] at: " + contentFolder.getAbsolutePath()); } }
@Test public void shouldCreateDestinationFolderIfNotExists() throws Exception { String contentFolderName = "content"; String templateFolderName = "template"; String destinationFolderName = "output"; File templateFolder = TestUtils.newFolder(folder.toFile(), templateFolderName); File contentFolder = TestUtils.newFolder(folder.toFile(), contentFolderName); File destinationFolder = new File(folder.toFile(), destinationFolderName); JBakeConfiguration configuration = mock(JBakeConfiguration.class); when(configuration.getSourceFolder()).thenReturn(folder.toFile()); when(configuration.getTemplateFolder()).thenReturn(templateFolder); when(configuration.getTemplateFolderName()).thenReturn(templateFolderName); when(configuration.getContentFolder()).thenReturn(contentFolder); when(configuration.getContentFolderName()).thenReturn(contentFolderName); when(configuration.getDestinationFolder()).thenReturn(destinationFolder); when(configuration.getAssetFolder()).thenReturn(destinationFolder); JBakeConfigurationInspector inspector = new JBakeConfigurationInspector(configuration); inspector.inspect(); assertThat(destinationFolder).exists(); }
@Test public void shouldThrowExceptionIfDestinationFolderNotWritable() throws Exception { String contentFolderName = "content"; String templateFolderName = "template"; File templateFolder = TestUtils.newFolder(folder.toFile(), templateFolderName); File contentFolder = TestUtils.newFolder(folder.toFile(), contentFolderName); File destinationFolder = mock(File.class); when(destinationFolder.exists()).thenReturn(true); JBakeConfiguration configuration = mock(JBakeConfiguration.class); when(configuration.getSourceFolder()).thenReturn(folder.toFile()); when(configuration.getTemplateFolder()).thenReturn(templateFolder); when(configuration.getTemplateFolderName()).thenReturn(templateFolderName); when(configuration.getContentFolder()).thenReturn(contentFolder); when(configuration.getContentFolderName()).thenReturn(contentFolderName); when(configuration.getDestinationFolder()).thenReturn(destinationFolder); JBakeConfigurationInspector inspector = new JBakeConfigurationInspector(configuration); try { inspector.inspect(); fail("should throw JBakeException"); } catch (JBakeException e) { assertThat(e.getMessage()).contains("Error: Destination folder is not writable:"); } }
@Test public void shouldLogWarningIfAssetFolderDoesNotExist() throws Exception { String contentFolderName = "content"; String templateFolderName = "template"; String destinationFolderName = "output"; String assetFolderName = "assets"; File templateFolder = TestUtils.newFolder(folder.toFile(), templateFolderName); File contentFolder = TestUtils.newFolder(folder.toFile(), contentFolderName); File destinationFolder = TestUtils.newFolder(folder.toFile(), destinationFolderName); File assetFolder = new File(folder.toFile(), assetFolderName); JBakeConfiguration configuration = mock(JBakeConfiguration.class); when(configuration.getSourceFolder()).thenReturn(folder.toFile()); when(configuration.getTemplateFolder()).thenReturn(templateFolder); when(configuration.getTemplateFolderName()).thenReturn(templateFolderName); when(configuration.getContentFolder()).thenReturn(contentFolder); when(configuration.getContentFolderName()).thenReturn(contentFolderName); when(configuration.getDestinationFolder()).thenReturn(destinationFolder); when(configuration.getAssetFolder()).thenReturn(assetFolder); JBakeConfigurationInspector inspector = new JBakeConfigurationInspector(configuration); inspector.inspect(); verify(mockAppender, times(1)).doAppend(captorLoggingEvent.capture()); LoggingEvent loggingEvent = captorLoggingEvent.getValue(); assertThat(loggingEvent.getMessage()).isEqualTo("No asset folder '{}' was found!"); assertThat(loggingEvent.getFormattedMessage()).isEqualTo("No asset folder '" + assetFolder.getAbsolutePath() + "' was found!"); } |
Asset { public void copy() { copy(config.getAssetFolder()); } @Deprecated Asset(File source, File destination, CompositeConfiguration config); Asset(JBakeConfiguration config); void copy(); void copy(File path); void copySingleFile(File asset); boolean isAssetFile(File path); void copyAssetsFromContent(File path); List<Throwable> getErrors(); } | @Test public void testCopy() throws Exception { Asset asset = new Asset(config); asset.copy(); File cssFile = new File(folder.toString() + File.separatorChar + "css" + File.separatorChar + "bootstrap.min.css"); Assertions.assertTrue(cssFile.exists(), () -> "File " + cssFile.getAbsolutePath() + " does not exist"); File imgFile = new File(folder.toString() + File.separatorChar + "img" + File.separatorChar + "glyphicons-halflings.png"); Assertions.assertTrue(imgFile.exists(), () -> "File " + imgFile.getAbsolutePath() + " does not exist"); File jsFile = new File(folder.toString() + File.separatorChar + "js" + File.separatorChar + "bootstrap.min.js"); Assertions.assertTrue(jsFile.exists(), () -> "File " + jsFile.getAbsolutePath() + " does not exist"); Assertions.assertTrue(asset.getErrors().isEmpty(), "Errors during asset copying"); }
@Test public void testUnlistable() throws Exception { config.setAssetFolder(new File(config.getSourceFolder(), "non-exsitent")); Asset asset = new Asset(config); asset.copy(); } |
Asset { public void copySingleFile(File asset) { try { if ( !asset.isDirectory() ) { String targetPath = config.getDestinationFolder().getCanonicalPath() + File.separatorChar + assetSubPath(asset); LOGGER.info("Copying single asset file to [{}]", targetPath); copyFile(asset, new File(targetPath)); } else { LOGGER.info("Skip copying single asset file [{}]. Is a directory.", asset.getPath()); } } catch (IOException io) { LOGGER.error("Failed to copy the asset file.", io); } } @Deprecated Asset(File source, File destination, CompositeConfiguration config); Asset(JBakeConfiguration config); void copy(); void copy(File path); void copySingleFile(File asset); boolean isAssetFile(File path); void copyAssetsFromContent(File path); List<Throwable> getErrors(); } | @Test public void testCopySingleFile() throws Exception { Asset asset = new Asset(config); String cssSubPath = File.separatorChar + "css" + File.separatorChar + "bootstrap.min.css"; String contentImgPath = File.separatorChar + "blog" + File.separatorChar + "2013" + File.separatorChar + "images" + File.separatorChar + "custom-image.jpg"; File expected = new File(folder.toString() + cssSubPath); Assertions.assertFalse(expected.exists(), "cssFile should not exist before running the test; avoids false positives"); File cssFile = new File(fixtureDir.getPath() + File.separatorChar + "assets" + cssSubPath); asset.copySingleFile(cssFile); Assertions.assertTrue(expected.exists(), "Css asset file did not copy"); expected = new File(folder.toString() + contentImgPath); Assertions.assertFalse(expected.exists(), "content image file should not exist before running the test"); File imgFile = new File(fixtureDir.getPath() + File.separatorChar + "content" + contentImgPath); asset.copySingleFile(imgFile); Assertions.assertTrue(expected.exists(), "Content img file did not copy"); }
@Test public void shouldSkipCopyingSingleFileIfDirectory() throws IOException { Asset asset = new Asset(config); File emptyDir = new File(folder.toFile(),"emptyDir"); emptyDir.mkdir(); File expectedDir = new File(fixtureDir.getCanonicalPath(), "emptyDir"); asset.copySingleFile(emptyDir); Assertions.assertFalse(expectedDir.exists(), "Directory should be skipped"); }
@Test public void shouldLogSkipCopyingSingleFileIfDirectory() throws IOException { Asset asset = new Asset(config); File emptyDir = new File(folder.toFile(),"emptyDir"); emptyDir.mkdir(); asset.copySingleFile(emptyDir); verify(mockAppender, times(1)).doAppend(captorLoggingEvent.capture()); LoggingEvent loggingEvent = captorLoggingEvent.getValue(); assertThat(loggingEvent.getMessage()).isEqualTo("Skip copying single asset file [{}]. Is a directory."); } |
Asset { public void copyAssetsFromContent(File path) { copy(path, config.getDestinationFolder(), FileUtil.getNotContentFileFilter()); } @Deprecated Asset(File source, File destination, CompositeConfiguration config); Asset(JBakeConfiguration config); void copy(); void copy(File path); void copySingleFile(File asset); boolean isAssetFile(File path); void copyAssetsFromContent(File path); List<Throwable> getErrors(); } | @Test public void testCopyAssetsFromContent() { URL contentUrl = this.getClass().getResource("/fixture/content"); File contents = new File(contentUrl.getFile()); Asset asset = new Asset(config); asset.copyAssetsFromContent(contents); int totalFiles = countFiles(folder.toFile()); int expected = 3; Assertions.assertTrue(totalFiles == expected, () -> String.format("Number of files copied must be %d but are %d", expected, totalFiles)); File pngFile = new File(folder.toString() + File.separatorChar + "blog" + File.separatorChar + "2012/images/custom-image.png"); Assertions.assertTrue(pngFile.exists(), () -> "File " + pngFile.getAbsolutePath() + " does not exist"); File jpgFile = new File(folder.toString() + File.separatorChar + "blog" + File.separatorChar + "2013/images/custom-image.jpg"); Assertions.assertTrue(jpgFile.exists(), () -> "File " + jpgFile.getAbsolutePath() + " does not exist"); File jsonFile = new File(folder.toString() + File.separatorChar + "blog" + File.separatorChar + "2012/sample.json"); Assertions.assertTrue(jsonFile.exists(), () -> "File " + jsonFile.getAbsolutePath() + " does not exist"); Assertions.assertTrue(asset.getErrors().isEmpty(), "Errors during asset copying"); } |
Asset { public boolean isAssetFile(File path) { boolean isAsset = false; try { if(FileUtil.directoryOnlyIfNotIgnored(path.getParentFile())) { if (FileUtil.isFileInDirectory(path, config.getAssetFolder())) { isAsset = true; } else if (FileUtil.isFileInDirectory(path, config.getContentFolder()) && FileUtil.getNotContentFileFilter().accept(path)) { isAsset = true; } } } catch (IOException ioe) { LOGGER.error("Unable to determine the path to asset file {}", path.getPath(), ioe); } return isAsset; } @Deprecated Asset(File source, File destination, CompositeConfiguration config); Asset(JBakeConfiguration config); void copy(); void copy(File path); void copySingleFile(File asset); boolean isAssetFile(File path); void copyAssetsFromContent(File path); List<Throwable> getErrors(); } | @Test public void testIsFileAsset() { File cssAsset = new File(config.getAssetFolder().getAbsolutePath() + File.separatorChar + "css" + File.separatorChar + "bootstrap.min.css"); Assertions.assertTrue(cssAsset.exists()); File contentFile = new File(config.getContentFolder().getAbsolutePath() + File.separatorChar + "about.html"); Assertions.assertTrue(contentFile.exists()); Asset asset = new Asset(config); Assertions.assertTrue(asset.isAssetFile(cssAsset)); Assertions.assertFalse(asset.isAssetFile(contentFile)); } |
FileUtil { public static File getRunningLocation() throws Exception { String codePath = FileUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath(); String decodedPath = URLDecoder.decode(codePath, "UTF-8"); File codeFile = new File(decodedPath); if (!codeFile.exists()) { throw new Exception("Cannot locate running location of JBake!"); } File codeFolder = codeFile.getParentFile().getParentFile(); if (!codeFolder.exists()) { throw new Exception("Cannot locate running location of JBake!"); } return codeFolder; } static FileFilter getFileFilter(); static FileFilter getNotContentFileFilter(); static boolean directoryOnlyIfNotIgnored(File file); static boolean isExistingFolder(File f); static File getRunningLocation(); static String fileExt(File src); static String fileExt(String name); static String sha1(File sourceFile); static String asPath(File file); static String asPath(String path); static String getPathToRoot(JBakeConfiguration config, File rootPath, File sourceFile); static String getUriPathToDestinationRoot(JBakeConfiguration config, File sourceFile); static String getUriPathToContentRoot(JBakeConfiguration config, File sourceFile); static boolean isFileInDirectory(File file, File directory); static final String URI_SEPARATOR_CHAR; } | @Test public void testGetRunningLocation() throws Exception { File path = FileUtil.getRunningLocation(); assertEquals(new File("build/classes").getAbsolutePath(), path.getPath()); } |
OperationService { public double divide(int a,int b){ try { return verifyResult(a / b); }catch(ArithmeticException ex){ this.counter.overflow(); throw new ArithmeticWebException(ex.getMessage()); } } @PostConstruct void init(); @Interceptors(CircuitBreaker.class) int add(int a, int b); double divide(int a,int b); int multiply(int a,int b); int substract(int a,int b); } | @Test(expected = ArithmeticWebException.class) public void divideByZero(){ this.cut.divide(2,0); } |
MetricsCounter { @Schedule(minute = "*",second = "*/10",hour = "*") public void calculateMetrics() { System.out.println("."); this.successesPerSecond = ((double)(success.longValue() - this.lastSuccess))/10; this.lastSuccess = success.longValue(); this.overflowsPerSecond = ((double)(overflow.longValue() - this.lastOverflow))/10; this.lastOverflow = overflow.longValue(); } @PostConstruct void init(); @GET @Path("kpis") JsonObject metrics(); @GET @Path("open-circuits") JsonObject openCircuits(); void onOpenCircuitInvocation(@Observes SubsequentInvocationsFailure failure); void fortyTwo(); void overflow(); void success(); @Schedule(minute = "*",second = "*/10",hour = "*") void calculateMetrics(); } | @Test public void calculateMetrics() { this.cut.lastSuccess = 10; this.cut.success.set(40); this.cut.calculateMetrics(); assertThat(this.cut.successesPerSecond,is(3d)); assertThat(this.cut.lastSuccess,is(this.cut.success.longValue())); } |
VectorCommand { public static VectorCommand createVectorCommand(String svgCommandString) { SVGCommand cmd = SVGCommand.valueOf(svgCommandString.substring(0, 1)); String[] argsAsString = svgCommandString.substring(1).split(SVG_ARG_DELIMITER); float[] args = new float[argsAsString.length]; int i = 0; for (String arg : argsAsString) { args[i++] = Float.parseFloat(arg); } switch (cmd) { case m: case M: { if (checkArguments(cmd, args)) { return new MoveToCommand(cmd.argFormat, args); } else { throw new IllegalArgumentException(String.format( Locale.US, "VectorCommand MoveTo requires two arguments, but got %s", args.toString())); } } case q: case Q: { if (checkArguments(cmd, args)) { return new QuadraticToCommand(cmd.argFormat, args); } else { throw new IllegalArgumentException(String.format( Locale.US, "VectorCommand QuadraticTo requires four arguments, but got %s", args.toString())); } } case c: case C: { if (checkArguments(cmd, args)) { return new CubicToCommand(cmd.argFormat, args); } else { throw new IllegalArgumentException(String.format( Locale.US, "VectorCommand CubicTo requires six arguments, but got %s", args.toString())); } } case l: case L: { if (checkArguments(cmd, args)) { return new LineToCommand(cmd.argFormat, args); } else { throw new IllegalArgumentException(String.format( Locale.US, "VectorCommand LineTo requires two arguments, but got %s", args.toString())); } } default: { throw new IllegalArgumentException(String.format( Locale.US, "Unhandled vector command: %s", svgCommandString)); } } } VectorCommand(ArgFormat argFormat, float[] args); static VectorCommand createVectorCommand(String svgCommandString); static boolean checkArguments(SVGCommand command, float[] args); static float[] convertUp(float[] startPoint, float[] fromArgs, float[] destArgs); abstract void apply(KFPath path); void interpolate(
VectorCommand toCommand,
float progress,
KFPath destPath); } | @Test public void testUnrecognizedCommand() { try { VectorCommand.createVectorCommand("A1,2"); Assert.fail("Expected exception not thrown."); } catch (Exception e) { Assert.assertTrue(e instanceof IllegalArgumentException); Assert.assertTrue(e.getMessage().contains("No enum constant")); } }
@Test public void testValidParsingMove() { VectorCommand moveToCommand = VectorCommand.createVectorCommand("M1,2"); Assert.assertTrue(moveToCommand instanceof VectorCommand.MoveToCommand); Assert.assertEquals(VectorCommand.ArgFormat.ABSOLUTE, moveToCommand.mArgFormat); Assert.assertEquals(2, moveToCommand.mArgs.length); Assert.assertEquals(1, moveToCommand.mArgs[0], 0); Assert.assertEquals(2, moveToCommand.mArgs[1], 0); moveToCommand = VectorCommand.createVectorCommand("m3,4"); Assert.assertTrue(moveToCommand instanceof VectorCommand.MoveToCommand); Assert.assertEquals(VectorCommand.ArgFormat.RELATIVE, moveToCommand.mArgFormat); Assert.assertEquals(2, moveToCommand.mArgs.length); Assert.assertEquals(3, moveToCommand.mArgs[0], 0); Assert.assertEquals(4, moveToCommand.mArgs[1], 0); }
@Test public void testInvalidParsingMove() { try { VectorCommand.createVectorCommand("M1"); Assert.fail("Expected exception not thrown."); } catch (Exception e) { Assert.assertTrue(e instanceof IllegalArgumentException); Assert.assertTrue(e.getMessage().contains("requires two arguments")); } try { VectorCommand.createVectorCommand("M1,2,3"); Assert.fail("Expected exception not thrown."); } catch (Exception e) { Assert.assertTrue(e instanceof IllegalArgumentException); Assert.assertTrue(e.getMessage().contains("requires two arguments")); } }
@Test public void testValidParsingQuadratic() { VectorCommand quadraticToCommand = VectorCommand.createVectorCommand("Q1,2,3,4"); Assert.assertTrue(quadraticToCommand instanceof VectorCommand.QuadraticToCommand); Assert.assertEquals(VectorCommand.ArgFormat.ABSOLUTE, quadraticToCommand.mArgFormat); Assert.assertEquals(4, quadraticToCommand.mArgs.length); Assert.assertEquals(1, quadraticToCommand.mArgs[0], 0); Assert.assertEquals(2, quadraticToCommand.mArgs[1], 0); Assert.assertEquals(3, quadraticToCommand.mArgs[2], 0); Assert.assertEquals(4, quadraticToCommand.mArgs[3], 0); quadraticToCommand = VectorCommand.createVectorCommand("q5,6,7,8"); Assert.assertTrue(quadraticToCommand instanceof VectorCommand.QuadraticToCommand); Assert.assertEquals(VectorCommand.ArgFormat.RELATIVE, quadraticToCommand.mArgFormat); Assert.assertEquals(4, quadraticToCommand.mArgs.length); Assert.assertEquals(5, quadraticToCommand.mArgs[0], 0); Assert.assertEquals(6, quadraticToCommand.mArgs[1], 0); Assert.assertEquals(7, quadraticToCommand.mArgs[2], 0); Assert.assertEquals(8, quadraticToCommand.mArgs[3], 0); }
@Test public void testInvalidParsingQuadratic() { try { VectorCommand.createVectorCommand("Q1,2"); Assert.fail("Expected exception not thrown."); } catch (Exception e) { Assert.assertTrue(e instanceof IllegalArgumentException); Assert.assertTrue(e.getMessage().contains("requires four arguments")); } try { VectorCommand.createVectorCommand("Q1,2,3,4,5"); Assert.fail("Expected exception not thrown."); } catch (Exception e) { Assert.assertTrue(e instanceof IllegalArgumentException); Assert.assertTrue(e.getMessage().contains("requires four arguments")); } }
@Test public void testValidParsingCubic() { VectorCommand cubicToCommand = VectorCommand.createVectorCommand("C1,2,3,4,5,6"); Assert.assertTrue(cubicToCommand instanceof VectorCommand.CubicToCommand); Assert.assertEquals(VectorCommand.ArgFormat.ABSOLUTE, cubicToCommand.mArgFormat); Assert.assertEquals(6, cubicToCommand.mArgs.length); Assert.assertEquals(1, cubicToCommand.mArgs[0], 0); Assert.assertEquals(2, cubicToCommand.mArgs[1], 0); Assert.assertEquals(3, cubicToCommand.mArgs[2], 0); Assert.assertEquals(4, cubicToCommand.mArgs[3], 0); Assert.assertEquals(5, cubicToCommand.mArgs[4], 0); Assert.assertEquals(6, cubicToCommand.mArgs[5], 0); cubicToCommand = VectorCommand.createVectorCommand("c7,8,9,10,11,12"); Assert.assertTrue(cubicToCommand instanceof VectorCommand.CubicToCommand); Assert.assertEquals(VectorCommand.ArgFormat.RELATIVE, cubicToCommand.mArgFormat); Assert.assertEquals(6, cubicToCommand.mArgs.length); Assert.assertEquals(7, cubicToCommand.mArgs[0], 0); Assert.assertEquals(8, cubicToCommand.mArgs[1], 0); Assert.assertEquals(9, cubicToCommand.mArgs[2], 0); Assert.assertEquals(10, cubicToCommand.mArgs[3], 0); Assert.assertEquals(11, cubicToCommand.mArgs[4], 0); Assert.assertEquals(12, cubicToCommand.mArgs[5], 0); }
@Test public void testInvalidParsingCubic() { try { VectorCommand.createVectorCommand("C1,2,3,4"); Assert.fail("Expected exception not thrown."); } catch (Exception e) { Assert.assertTrue(e instanceof IllegalArgumentException); Assert.assertTrue(e.getMessage().contains("requires six arguments")); } try { VectorCommand.createVectorCommand("C1,2,3,4,5,6,7"); Assert.fail("Expected exception not thrown."); } catch (Exception e) { Assert.assertTrue(e instanceof IllegalArgumentException); Assert.assertTrue(e.getMessage().contains("requires six arguments")); } }
@Test public void testValidParsingLine() { VectorCommand lineToCommand = VectorCommand.createVectorCommand("L1,2"); Assert.assertTrue(lineToCommand instanceof VectorCommand.LineToCommand); Assert.assertEquals(VectorCommand.ArgFormat.ABSOLUTE, lineToCommand.mArgFormat); Assert.assertEquals(2, lineToCommand.mArgs.length); Assert.assertEquals(1, lineToCommand.mArgs[0], 0); Assert.assertEquals(2, lineToCommand.mArgs[1], 0); lineToCommand = VectorCommand.createVectorCommand("l3,4"); Assert.assertTrue(lineToCommand instanceof VectorCommand.LineToCommand); Assert.assertEquals(VectorCommand.ArgFormat.RELATIVE, lineToCommand.mArgFormat); Assert.assertEquals(2, lineToCommand.mArgs.length); Assert.assertEquals(3, lineToCommand.mArgs[0], 0); Assert.assertEquals(4, lineToCommand.mArgs[1], 0); }
@Test public void testInvalidParsingLine() { try { VectorCommand.createVectorCommand("L1"); Assert.fail("Expected exception not thrown."); } catch (Exception e) { Assert.assertTrue(e instanceof IllegalArgumentException); Assert.assertTrue(e.getMessage().contains("requires two arguments")); } try { VectorCommand.createVectorCommand("L1,2,3"); Assert.fail("Expected exception not thrown."); } catch (Exception e) { Assert.assertTrue(e instanceof IllegalArgumentException); Assert.assertTrue(e.getMessage().contains("requires two arguments")); } } |
VectorCommand { public static float[] convertUp(float[] startPoint, float[] fromArgs, float[] destArgs) { if (fromArgs.length >= destArgs.length) { throw new IllegalArgumentException("convertUp should only be called to convert a lower " + "order argument array to a higher one."); } if (fromArgs.length == 2) { if (destArgs.length == 4) { destArgs[0] = (startPoint[0] + fromArgs[0]) / 2f; destArgs[1] = (startPoint[1] + fromArgs[1]) / 2f; destArgs[2] = fromArgs[0]; destArgs[3] = fromArgs[1]; } else if (destArgs.length == 6) { destArgs[0] = startPoint[0] + (fromArgs[0] - startPoint[0]) / 3f; destArgs[1] = startPoint[1] + (fromArgs[1] - startPoint[1]) / 3f; destArgs[2] = fromArgs[0] + (startPoint[0] - fromArgs[0]) / 3f; destArgs[3] = fromArgs[1] + (startPoint[1] - fromArgs[1]) / 3f; destArgs[4] = fromArgs[0]; destArgs[5] = fromArgs[1]; } else { throw new IllegalArgumentException(String.format( "Unknown conversion from %d args to %d", fromArgs.length, destArgs.length)); } } else if (fromArgs.length == 4) { if (destArgs.length == 6) { destArgs[0] = startPoint[0] + 2f / 3f * (fromArgs[0] - startPoint[0]); destArgs[1] = startPoint[1] + 2f / 3f * (fromArgs[1] - startPoint[1]); destArgs[2] = fromArgs[2] + 2f / 3f * (fromArgs[0] - fromArgs[2]); destArgs[3] = fromArgs[3] + 2f / 3f * (fromArgs[1] - fromArgs[3]); destArgs[4] = fromArgs[2]; destArgs[5] = fromArgs[3]; } else { throw new IllegalArgumentException(String.format( "Unknown conversion from %d args to %d", fromArgs.length, destArgs.length)); } } else { throw new IllegalArgumentException(String.format( "Unknown conversion from %d args to %d", fromArgs.length, destArgs.length)); } return destArgs; } VectorCommand(ArgFormat argFormat, float[] args); static VectorCommand createVectorCommand(String svgCommandString); static boolean checkArguments(SVGCommand command, float[] args); static float[] convertUp(float[] startPoint, float[] fromArgs, float[] destArgs); abstract void apply(KFPath path); void interpolate(
VectorCommand toCommand,
float progress,
KFPath destPath); } | @Test public void testConvertUp() { float[] startPoint = {10, 10}; float[] quadDest = new float[4]; float[] cubicDest = new float[6]; VectorCommand.convertUp(startPoint, new float[]{20f, 20f}, quadDest); Assert.assertArrayEquals(new float[]{15f, 15f, 20f, 20f}, quadDest, 0.1f); VectorCommand.convertUp(startPoint, new float[]{20f, 20f}, cubicDest); Assert.assertArrayEquals(new float[]{13.3f, 13.3f, 16.6f, 16.6f, 20f, 20f}, cubicDest, 0.1f); VectorCommand.convertUp(startPoint, new float[]{15, 15, 20, 10}, cubicDest); Assert.assertArrayEquals(new float[]{13.3f, 13.3f, 16.6f, 13.3f, 20f, 10f}, cubicDest, 0.1f); } |
BooksActivityPresenter { public void loadBooks() { compositeDisposable.add(booksRepository.getBooks() .subscribeOn(Schedulers.io()) .observeOn(mainScheduler) .subscribeWith(new DisposableSingleObserver<List<Book>>() { @Override public void onSuccess(List<Book> bookList) { System.out.println("Thread subscribe(): " + Thread.currentThread().getId()); if (bookList.isEmpty()) { view.displayNoBooks(); } else { view.displayBooks(bookList); } } @Override public void onError(Throwable e) { view.displayError(); } })); } BooksActivityPresenter(BooksActivityView view, BooksRepository booksRepository, Scheduler mainScheduler); void loadBooks(); void unsubscribe(); } | @Test public void shouldPassBooksToView() { when(booksRepository.getBooks()).thenReturn(Single.just(MANY_BOOKS)); presenter.loadBooks(); verify(view).displayBooks(MANY_BOOKS); }
@Test public void shouldHandleNoBooksFound() throws InterruptedException { when(booksRepository.getBooks()).thenReturn(Single.just(Collections.emptyList())); presenter.loadBooks(); verify(view).displayNoBooks(); }
@Test public void shouldHandleError() { when(booksRepository.getBooks()).thenReturn(Single.<List<Book>>error(new Throwable("boom"))); presenter.loadBooks(); verify(view).displayError(); } |
Activator { @Activate public void start(ActivatorConfiguration config) { String[] authorizableIds = config.pwdreset_authorizables(); Session session = null; try { ResourceResolver resolver = resolverFactory.getAdministrativeResourceResolver(null); UserManager userManager = resolver.adaptTo(UserManager.class); session = resolver.adaptTo(Session.class); for (String authorizable : authorizableIds) { try { Authorizable user = userManager.getAuthorizable(authorizable); if (user != null) { ((User) user).changePassword(authorizable); if (!userManager.isAutoSave()) { session.save(); } log.info("Changed the password for {}", authorizable); } else { log.error("Could not find authorizable {}", authorizable); } } catch (RepositoryException repEx) { log.error("Could not change password for {}", authorizable, repEx); } } } catch (LoginException loginEx) { log.error("Could not login to the repository", loginEx); } finally { if(session != null) { session.logout(); } } } @Activate void start(ActivatorConfiguration config); } | @Test public void testPasswordChangeNoAutoSave() throws Exception { when(mockUserManager.getAuthorizable(anyString())).thenReturn(mockAuthorizable); when(mockUserManager.isAutoSave()).thenReturn(false); Activator activator = spy(createActivator()); activator.start(mockConfiguration); verify(mockAuthorizable, times(1)).changePassword(anyString()); verify(mockSession, times(1)).save(); verify(mockSession, times(1)).logout(); }
@Test public void testPasswordChangeAutoSave() throws Exception { when(mockUserManager.getAuthorizable(anyString())).thenReturn(mockAuthorizable); when(mockUserManager.isAutoSave()).thenReturn(true); Activator activator = spy(createActivator()); activator.start(mockConfiguration); verify(mockAuthorizable, times(1)).changePassword(anyString()); verify(mockSession, times(0)).save(); verify(mockSession, times(1)).logout(); }
@Test public void testAdminNotFound() throws Exception { when(mockUserManager.getAuthorizable(eq("admin"))).thenReturn(null); when(mockUserManager.getAuthorizable(not(eq("admin")))).thenReturn(mockAuthorizable); Activator activator = spy(createActivator()); activator.start(mockConfiguration); verify(mockAuthorizable, times(0)).changePassword("admin"); verify(mockSession, times(0)).save(); verify(mockSession, times(1)).logout(); }
@Test public void testAdminLoginError() throws Exception { when(mockResolverFactory.getAdministrativeResourceResolver(null)).thenThrow(new LoginException()); Activator activator = spy(createActivator()); activator.start(mockConfiguration); verify(mockAuthorizable, times(0)).changePassword(anyString()); verify(mockSession, times(0)).save(); verify(mockSession, times(0)).logout(); verifyZeroInteractions(mockResolver); verifyZeroInteractions(mockAuthorizable); verifyZeroInteractions(mockUserManager); verifyZeroInteractions(mockSession); }
@Test public void testSessionSaveError() throws Exception { when(mockUserManager.getAuthorizable(anyString())).thenReturn(mockAuthorizable); when(mockUserManager.isAutoSave()).thenReturn(true); doThrow(new RepositoryException()).when(mockSession).save(); Activator activator = spy(createActivator()); activator.start(mockConfiguration); verify(mockAuthorizable, times(1)).changePassword(anyString()); verify(mockSession, times(0)).save(); verify(mockSession, times(1)).logout(); }
@Test public void testPasswordChangeMultipleIDs() throws Exception { when(mockConfiguration.pwdreset_authorizables()).thenReturn(new String[]{"deployer", "importer"}); when(mockUserManager.getAuthorizable(anyString())).thenReturn(mockAuthorizable); when(mockUserManager.isAutoSave()).thenReturn(false); Activator activator = spy(createActivator()); activator.start(mockConfiguration); verify(mockAuthorizable, times(2)).changePassword(anyString()); verify(mockSession, times(2)).save(); verify(mockSession, times(1)).logout(); } |
SqoopOutputFormatLoadExecutor { public RecordWriter<Data, NullWritable> getRecordWriter() { consumerFuture = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat ("OutputFormatLoader-consumer").build()).submit( new ConsumerThread()); return producer; } SqoopOutputFormatLoadExecutor(boolean isTest, String loaderName); SqoopOutputFormatLoadExecutor(JobContext jobctx); RecordWriter<Data, NullWritable> getRecordWriter(); static final Log LOG; } | @Test(expected = BrokenBarrierException.class) public void testWhenLoaderThrows() throws Throwable { conf.set(JobConstants.JOB_TYPE, "EXPORT"); conf.set(JobConstants.JOB_ETL_LOADER, ThrowingLoader.class.getName()); SqoopOutputFormatLoadExecutor executor = new SqoopOutputFormatLoadExecutor(true, ThrowingLoader.class.getName()); RecordWriter<Data, NullWritable> writer = executor.getRecordWriter(); Data data = new Data(); try { for (int count = 0; count < 100; count++) { data.setContent(String.valueOf(count), Data.CSV_RECORD); writer.write(data, null); } } catch (SqoopException ex) { throw ex.getCause(); } }
@Test public void testSuccessfulContinuousLoader() throws Throwable { conf.set(JobConstants.JOB_TYPE, "EXPORT"); conf.set(JobConstants.JOB_ETL_LOADER, GoodContinuousLoader.class.getName()); SqoopOutputFormatLoadExecutor executor = new SqoopOutputFormatLoadExecutor(true, GoodContinuousLoader.class.getName()); RecordWriter<Data, NullWritable> writer = executor.getRecordWriter(); Data data = new Data(); for (int i = 0; i < 10; i++) { StringBuilder builder = new StringBuilder(); for (int count = 0; count < 100; count++) { builder.append(String.valueOf(count)); if (count != 99) { builder.append(","); } } data.setContent(builder.toString(), Data.CSV_RECORD); writer.write(data, null); } writer.close(null); }
@Test (expected = SqoopException.class) public void testSuccessfulLoader() throws Throwable { SqoopOutputFormatLoadExecutor executor = new SqoopOutputFormatLoadExecutor(true, GoodLoader.class.getName()); RecordWriter<Data, NullWritable> writer = executor.getRecordWriter(); Data data = new Data(); StringBuilder builder = new StringBuilder(); for (int count = 0; count < 100; count++) { builder.append(String.valueOf(count)); if (count != 99) { builder.append(","); } } data.setContent(builder.toString(), Data.CSV_RECORD); writer.write(data, null); TimeUnit.SECONDS.sleep(5); writer.close(null); }
@Test(expected = ConcurrentModificationException.class) public void testThrowingContinuousLoader() throws Throwable { conf.set(JobConstants.JOB_TYPE, "EXPORT"); conf.set(JobConstants.JOB_ETL_LOADER, ThrowingContinuousLoader.class.getName()); SqoopOutputFormatLoadExecutor executor = new SqoopOutputFormatLoadExecutor(true, ThrowingContinuousLoader.class.getName()); RecordWriter<Data, NullWritable> writer = executor.getRecordWriter(); Data data = new Data(); try { for (int i = 0; i < 10; i++) { StringBuilder builder = new StringBuilder(); for (int count = 0; count < 100; count++) { builder.append(String.valueOf(count)); if (count != 99) { builder.append(","); } } data.setContent(builder.toString(), Data.CSV_RECORD); writer.write(data, null); } writer.close(null); } catch (SqoopException ex) { throw ex.getCause(); } } |
DoubanHotMoviePresenterImpl extends BasePresenter<DoubanHotMoviePresenter.View> implements DoubanHotMoviePresenter.Presenter { @Override public void fetchHotMovie() { invoke(mDoubanService.fetchHotMovie(),new Callback<HotMovieBean>(){}); } @Inject DoubanHotMoviePresenterImpl(DoubanService mDoubanService); @Override void fetchHotMovie(); } | @Test public void fetchHotMovie() throws Exception { } |
Objects { static String toString(Object o) { return (o == null) ? "null" : o.toString(); } } | @Test public void toString_nullValueAsParam_returnNullString() { final Object objectA = null; final String nullString = Objects.toString(objectA); assertThat(nullString, is(notNullValue())); assertThat(nullString, is("null")); }
@Test public void toString_nonNullValueAsParam_returnObjectToStringValue() { final Object objectA = new Object() { @Override public String toString() { return "notNull"; } }; final String nonNullString = Objects.toString(objectA); assertThat(nonNullString, is(nonNullString)); assertThat(nonNullString, is("notNull")); } |
Objects { static int hash(Object... values) { return Arrays.hashCode(values); } } | @Test public void hash_nullValueAsParam_returnNumber() { final Object nullObject = null; final int hash = Objects.hash(nullObject); assertThat(hash, is(notNullValue())); }
@Test public void hash_ObjectValueAsParam_returnNumber() { final Object objectA = new Object(); final int hash = Objects.hash(objectA); assertThat(hash, is(notNullValue())); } |
Objects { static boolean equals(Object a, Object b) { return (a == null) ? (b == null) : a.equals(b); } } | @Test public void equals_nullValueAsFirstParam_returnFalse() { final Object objectA = null; final Object objectB = new Object(); final boolean result = Objects.equals(objectA, objectB); assertThat(result, is(false)); }
@Test public void equals_nullValueAsSecondParam_returnFalse() { final Object objectA = new Object(); final Object objectB = null; final boolean result = Objects.equals(objectA, objectB); assertThat(result, is(false)); }
@Test public void equals_nullValueAsBothParams_returnTrue() { final Object objectA = null; final Object objectB = null; final boolean result = Objects.equals(objectA, objectB); assertThat(result, is(true)); }
@Test public void equals_differentBooleanParams_returnFalse() { final boolean paramA = true; final boolean paramB = false; final boolean result = Objects.equals(paramA, paramB); assertThat(result, is(false)); }
@Test public void equals_sameBooleanParams_returnTrue() { final boolean paramA = true; final boolean paramB = true; final boolean result = Objects.equals(paramA, paramB); assertThat(result, is(true)); } |
JavaRemoteInformationInvocationHandler implements RemoteObjectHandler { @Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { RemoteAccessCommunicationRequest request = new RemoteAccessCommunicationRequest(method.getName(), clazz, uuid, args); try { sender.objectToServer(request); } catch (SendFailedException e) { return executeFallback(e, method, args); } Semaphore semaphore = remoteAccessBlockRegistration.await(request); semaphore.acquire(); RemoteAccessCommunicationResponse response = remoteAccessBlockRegistration.getResponse(uuid); remoteAccessBlockRegistration.clearResult(uuid); remoteAccessBlockRegistration.clearSemaphore(uuid); semaphore.release(); if (response.getThrownThrowable() != null) { return testForThrow(clazz, method, response.getThrownThrowable(), args); } return response.getResult(); } @APILevel JavaRemoteInformationInvocationHandler(final Sender sender, final RemoteAccessBlockRegistration remoteAccessBlockRegistration,
final Class<T> clazz, final UUID uuid); @Override Object invoke(final Object proxy, final Method method, final Object[] args); void setFallbackRunnable(Runnable fallbackRunnable); void setFallbackInstance(S fallbackInstance); } | @Test public void invoke() throws Throwable { UUID id = UUID.randomUUID(); Sender sender = mock(Sender.class); doAnswer(invocationOnMock -> { continueSemaphore(); return null; }).when(sender).objectToServer(any(RemoteAccessCommunicationRequest.class)); RemoteAccessBlockRegistration registration = mock(RemoteAccessBlockRegistration.class); when(registration.getResponse(any())).thenReturn(new RemoteAccessCommunicationResponse(UUID.randomUUID(), null, null)); when(registration.await(any())).thenReturn(getAndAcquire()); JavaRemoteInformationInvocationHandler<TestInterface> handler = new JavaRemoteInformationInvocationHandler<>(sender, registration, TestInterface.class, id); Object result = handler.invoke(null, TestInterface.class.getMethod("testMethod"), new Object[0]); verify(sender, atLeastOnce()).objectToServer(any(RemoteAccessCommunicationRequest.class)); assertNull(result); } |
NativeServerStart implements ServerStart { @Override public final Awaiting createNewConnection(final Session session, final Class key) { final Client client = clientList.getClient(session).orElseThrow(() -> new UnknownClientException("No Client found for " + session)); return client.createNewConnection(key); } NativeServerStart(final InetSocketAddress address); @Override final void addClientConnectedHandler(final ClientConnectedHandler clientConnectedHandler); @Override final void removeClientConnectedHandler(final ClientConnectedHandler clientConnectedHandler); @Override final ClientFactory getClientFactory(); @Override final synchronized void launch(); @Override final void acceptNextClient(); @Override final void acceptAllNextClients(); @Override final void disconnect(); @Override final ClientList clientList(); @Override final Awaiting createNewConnection(final Session session, final Class key); @Override final Cache cache(); @Override final CommunicationRegistration getCommunicationRegistration(); @Override final void setLogging(final Logging logging); @Override final void softStop(); @Override final boolean running(); @Override final int getPort(); @Override final void setPort(final int to); @Override final void setConnectorCore(final ConnectorCore connectorCore); } | @Test(expected = UnknownClientException.class) public void createNewConnectionWithoutClient() throws Exception { Awaiting awaiting = serverStart.createNewConnection(mock(Session.class), TestConnectionKey.class); fail(); }
@Test public void createNewConnection() throws Exception { Client client = mock(Client.class); Session session = mock(Session.class); when(client.getSession()).thenReturn(session); serverStart.clientList().add(client); serverStart.createNewConnection(session, TestConnectionKey.class); verify(client).createNewConnection(eq(TestConnectionKey.class)); } |
NativeClientList implements ClientList { @Override public final Stream<Session> sessionStream() { return snapShot().stream() .map(Client::getSession); } NativeClientList(); @Override final void remove(final Client client); @Override final void add(final Client client); @Override final void close(); @Override final void open(); @Override final boolean isOpen(); @Override final void clear(); @Override final boolean isEmpty(); @Override final Collection<Client> snapShot(); @Override final Optional<Client> getClient(Session session); @Override final Optional<Client> getClient(ClientID clientID); @Override final Stream<Client> stream(); @Override final Stream<Session> sessionStream(); @Override final Iterator<Client> iterator(); @Override final String toString(); } | @Test @Ignore public void sessionStream() throws Exception { Client client = mock(Client.class); when(client.getID()).thenReturn(ClientID.fromString(UUID_SEED_1)); Session clientSession = mock(Session.class); when(client.getSession()).thenReturn(clientSession); Client client2 = mock(Client.class); when(client2.getID()).thenReturn(ClientID.fromString(UUID_SEED_2)); Session session2 = mock(Session.class); when(client2.getSession()).thenReturn(session2); Client client3 = mock(Client.class); when(client3.getID()).thenReturn(ClientID.fromString(UUID_SEED_3)); when(client3.getSession()).thenReturn(null); NativeClientList clients = new NativeClientList(); List<Session> expectedSessions = Arrays.asList(clientSession, session2); clients.add(client); clients.add(client2); clients.add(client3); Stream<Session> sessionStream = clients.sessionStream(); List<Session> streamContents = sessionStream.collect(Collectors.toList()); assertThat(streamContents, consistsOf(expectedSessions)); } |
NativeClientList implements ClientList { @Override public final void close() { logging.debug("Closing " + this); openValue.set(false); } NativeClientList(); @Override final void remove(final Client client); @Override final void add(final Client client); @Override final void close(); @Override final void open(); @Override final boolean isOpen(); @Override final void clear(); @Override final boolean isEmpty(); @Override final Collection<Client> snapShot(); @Override final Optional<Client> getClient(Session session); @Override final Optional<Client> getClient(ClientID clientID); @Override final Stream<Client> stream(); @Override final Stream<Session> sessionStream(); @Override final Iterator<Client> iterator(); @Override final String toString(); } | @Test @Ignore public void close() throws Exception { Client aClient = mock(Client.class); when(aClient.getID()).thenReturn(ClientID.fromString(UUID_SEED_1)); Client anotherClient = mock(Client.class); when(anotherClient.getID()).thenReturn(ClientID.fromString(UUID_SEED_2)); NativeClientList clients = new NativeClientList(); clients.add(aClient); clients.add(anotherClient); clients.close(); assertFalse(clients.isOpen()); verify(aClient).disconnect(); verify(anotherClient).disconnect(); } |
NativeClientList implements ClientList { @Override public final void open() { logging.debug("Opening " + this); openValue.set(true); } NativeClientList(); @Override final void remove(final Client client); @Override final void add(final Client client); @Override final void close(); @Override final void open(); @Override final boolean isOpen(); @Override final void clear(); @Override final boolean isEmpty(); @Override final Collection<Client> snapShot(); @Override final Optional<Client> getClient(Session session); @Override final Optional<Client> getClient(ClientID clientID); @Override final Stream<Client> stream(); @Override final Stream<Session> sessionStream(); @Override final Iterator<Client> iterator(); @Override final String toString(); } | @Test public void open() throws Exception { NativeClientList clients = new NativeClientList(); clients.open(); assertTrue(clients.isOpen()); } |
NativeClientList implements ClientList { @Override public final boolean isOpen() { return openValue.get(); } NativeClientList(); @Override final void remove(final Client client); @Override final void add(final Client client); @Override final void close(); @Override final void open(); @Override final boolean isOpen(); @Override final void clear(); @Override final boolean isEmpty(); @Override final Collection<Client> snapShot(); @Override final Optional<Client> getClient(Session session); @Override final Optional<Client> getClient(ClientID clientID); @Override final Stream<Client> stream(); @Override final Stream<Session> sessionStream(); @Override final Iterator<Client> iterator(); @Override final String toString(); } | @Test @Ignore public void isOpen() throws Exception { NativeClientList clients = new NativeClientList(); assertTrue(clients.isOpen()); } |
JavaInvocationHandlerProducer implements InvocationHandlerProducer { @Override public <T> JavaRemoteInformationInvocationHandler<T> produce(final UUID uuid, final Class<T> clazz) { NetCom2Utils.parameterNotNull(clazz, uuid); return new JavaRemoteInformationInvocationHandler<>(sender, remoteAccessBlockRegistration, clazz, uuid); } JavaInvocationHandlerProducer(final Sender sender, final RemoteAccessBlockRegistration remoteAccessBlockRegistration); @Override JavaRemoteInformationInvocationHandler<T> produce(final UUID uuid, final Class<T> clazz); } | @Test(expected = IllegalArgumentException.class) public void produceClassNull() throws Exception { JavaInvocationHandlerProducer producer = new JavaInvocationHandlerProducer(mock(Sender.class), mock(RemoteAccessBlockRegistration.class)); producer.produce(UUID.fromString(TestUtils.UUID_SEED_1), null); fail(); }
@Test(expected = IllegalArgumentException.class) public void produceUUIDAndClassNull() throws Exception { JavaInvocationHandlerProducer producer = new JavaInvocationHandlerProducer(mock(Sender.class), mock(RemoteAccessBlockRegistration.class)); producer.produce(null, null); fail(); }
@Test public void produce() throws Exception { JavaInvocationHandlerProducer producer = new JavaInvocationHandlerProducer(mock(Sender.class), mock(RemoteAccessBlockRegistration.class)); JavaRemoteInformationInvocationHandler<TestInterface> test = producer.produce(UUID.fromString(TestUtils.UUID_SEED_1), TestInterface.class); assertNotNull(test); }
@Test(expected = IllegalArgumentException.class) public void produceUUIDNull() throws Exception { JavaInvocationHandlerProducer producer = new JavaInvocationHandlerProducer(mock(Sender.class), mock(RemoteAccessBlockRegistration.class)); producer.produce(null, TestInterface.class); fail(); } |
NativeRemoteObjectRegistration implements RemoteObjectRegistration { @Override public final void register(final Object object) { NetCom2Utils.parameterNotNull(object); register(object, object.getClass()); } @APILevel NativeRemoteObjectRegistration(); @Override final void setup(final ServerStart serverStart); @Override final void close(); @Override final void register(final Object object); @Override final void register(final Object o, final Class<?>... identifier); @Override final void hook(final Object object); @Override final void unregister(final Object object); @Override final void unregister(final Object object, final Class... identifiers); @Override final void unregister(final Class... identifier); @Override final void unhook(final Object object); @Override final void clear(); @Override final RemoteAccessCommunicationResponse run(final RemoteAccessCommunicationRequest request); } | @Test(expected=IllegalArgumentException.class) public void registerInvalidArrayLength() throws Exception { NativeRemoteObjectRegistration remoteObjectRegistration = new NativeRemoteObjectRegistration(); TestRemoteObject remoteObject = new TestRemoteObject(); Class[] classes = new Class[0]; remoteObjectRegistration.register(remoteObject, classes); fail(); } |
NativeRemoteObjectRegistration implements RemoteObjectRegistration { @Override public final void hook(final Object object) { NetCom2Utils.parameterNotNull(object); final List<Class<?>> classList = new ArrayList<>(Arrays.asList(object.getClass().getInterfaces())); classList.add(object.getClass().getSuperclass()); classList.add(object.getClass()); register(object, classList.toArray(new Class[classList.size()])); } @APILevel NativeRemoteObjectRegistration(); @Override final void setup(final ServerStart serverStart); @Override final void close(); @Override final void register(final Object object); @Override final void register(final Object o, final Class<?>... identifier); @Override final void hook(final Object object); @Override final void unregister(final Object object); @Override final void unregister(final Object object, final Class... identifiers); @Override final void unregister(final Class... identifier); @Override final void unhook(final Object object); @Override final void clear(); @Override final RemoteAccessCommunicationResponse run(final RemoteAccessCommunicationRequest request); } | @Test(expected = IllegalArgumentException.class) public void hookNull() throws Exception { NativeRemoteObjectRegistration remoteObjectRegistration = new NativeRemoteObjectRegistration(); remoteObjectRegistration.hook(null); fail(); } |
NativeRemoteObjectRegistration implements RemoteObjectRegistration { @Override public final void unregister(final Object object) { NetCom2Utils.parameterNotNull(object); unregister(object, object.getClass()); } @APILevel NativeRemoteObjectRegistration(); @Override final void setup(final ServerStart serverStart); @Override final void close(); @Override final void register(final Object object); @Override final void register(final Object o, final Class<?>... identifier); @Override final void hook(final Object object); @Override final void unregister(final Object object); @Override final void unregister(final Object object, final Class... identifiers); @Override final void unregister(final Class... identifier); @Override final void unhook(final Object object); @Override final void clear(); @Override final RemoteAccessCommunicationResponse run(final RemoteAccessCommunicationRequest request); } | @Test(expected = IllegalArgumentException.class) public void unregisterNullClassArray() throws Exception { NativeRemoteObjectRegistration remoteObjectRegistration = new NativeRemoteObjectRegistration(); remoteObjectRegistration.unregister((Class[]) null); fail(); }
@Test(expected = IllegalArgumentException.class) public void unregisterNullObject() throws Exception { NativeRemoteObjectRegistration remoteObjectRegistration = new NativeRemoteObjectRegistration(); remoteObjectRegistration.unregister((Object) null); fail(); }
@Test(expected = IllegalArgumentException.class) public void unregisterNullObjectAndClassArray() throws Exception { NativeRemoteObjectRegistration remoteObjectRegistration = new NativeRemoteObjectRegistration(); remoteObjectRegistration.unregister(null, (Class[]) null); fail(); }
@Test(expected = IllegalArgumentException.class) public void unregisterNullObjectWithClassArray() throws Exception { NativeRemoteObjectRegistration remoteObjectRegistration = new NativeRemoteObjectRegistration(); remoteObjectRegistration.unregister((Object) null, TestRemoteObject.class); fail(); }
@Test(expected = IllegalArgumentException.class) public void unregisterNullClassArrayWithObject() throws Exception { NativeRemoteObjectRegistration remoteObjectRegistration = new NativeRemoteObjectRegistration(); remoteObjectRegistration.unregister(new TestRemoteObject(), (Class[]) null); fail(); } |
NativeRemoteObjectRegistration implements RemoteObjectRegistration { @Override public final void unhook(final Object object) { NetCom2Utils.parameterNotNull(object); final List<Class> classList = new ArrayList<>(Arrays.asList(object.getClass().getInterfaces())); classList.add(object.getClass().getSuperclass()); classList.add(object.getClass()); unregister(object, classList.toArray(new Class[classList.size()])); } @APILevel NativeRemoteObjectRegistration(); @Override final void setup(final ServerStart serverStart); @Override final void close(); @Override final void register(final Object object); @Override final void register(final Object o, final Class<?>... identifier); @Override final void hook(final Object object); @Override final void unregister(final Object object); @Override final void unregister(final Object object, final Class... identifiers); @Override final void unregister(final Class... identifier); @Override final void unhook(final Object object); @Override final void clear(); @Override final RemoteAccessCommunicationResponse run(final RemoteAccessCommunicationRequest request); } | @Test public void unhook() throws Exception { NativeRemoteObjectRegistration remoteObjectRegistration = new NativeRemoteObjectRegistration(); TestRemoteObjectWithInterface object = spy(new TestRemoteObjectWithInterface()); String methodName = "anInterfaceMethod"; String methodName2 = "aMethod"; Class<TestRemoteObjectWithInterface> clazz = TestRemoteObjectWithInterface.class; UUID uuid = UUID.fromString(UUID_SEED_1); RemoteAccessCommunicationRequest request = new RemoteAccessCommunicationRequest(methodName, clazz, uuid, null); RemoteAccessCommunicationRequest request2 = new RemoteAccessCommunicationRequest(methodName2, clazz, uuid, null); remoteObjectRegistration.hook(object); remoteObjectRegistration.unhook(object); remoteObjectRegistration.run(request); remoteObjectRegistration.run(request2); verify(object, never()).anInterfaceMethod(); verify(object, never()).aMethod(); }
@Test(expected = IllegalArgumentException.class) public void unhookNull() throws Exception { NativeRemoteObjectRegistration remoteObjectRegistration = new NativeRemoteObjectRegistration(); remoteObjectRegistration.unhook(null); fail(); } |
JavaRemoteInformationInvocationHandler implements RemoteObjectHandler { public void setFallbackRunnable(Runnable fallbackRunnable) { synchronized (this) { this.fallbackRunnable = fallbackRunnable; this.fallbackInstance = null; } } @APILevel JavaRemoteInformationInvocationHandler(final Sender sender, final RemoteAccessBlockRegistration remoteAccessBlockRegistration,
final Class<T> clazz, final UUID uuid); @Override Object invoke(final Object proxy, final Method method, final Object[] args); void setFallbackRunnable(Runnable fallbackRunnable); void setFallbackInstance(S fallbackInstance); } | @Test(expected = PipelineAccessException.class) public void setFallbackRunnable() throws Throwable { UUID id = UUID.randomUUID(); Sender sender = mock(Sender.class); doThrow(new SendFailedException("MockedSendFailed")).when(sender).objectToServer(any()); RemoteAccessBlockRegistration registration = mock(RemoteAccessBlockRegistration.class); JavaRemoteInformationInvocationHandler<TestInterface> handler = new JavaRemoteInformationInvocationHandler<>(sender, registration, TestInterface.class, id); handler.setFallbackRunnable(() -> { throw new PipelineAccessException(""); }); handler.invoke(null, TestInterface.class.getMethod("testMethod"), new Object[0]); fail(); } |
NativeRemoteObjectRegistration implements RemoteObjectRegistration { @Override public final void clear() { logging.debug("Clearing the RemoteObjectRegistration " + toString()); synchronized (mapping) { mapping.clear(); } } @APILevel NativeRemoteObjectRegistration(); @Override final void setup(final ServerStart serverStart); @Override final void close(); @Override final void register(final Object object); @Override final void register(final Object o, final Class<?>... identifier); @Override final void hook(final Object object); @Override final void unregister(final Object object); @Override final void unregister(final Object object, final Class... identifiers); @Override final void unregister(final Class... identifier); @Override final void unhook(final Object object); @Override final void clear(); @Override final RemoteAccessCommunicationResponse run(final RemoteAccessCommunicationRequest request); } | @Test public void clear() throws Exception { NativeRemoteObjectRegistration remoteObjectRegistration = new NativeRemoteObjectRegistration(); TestRemoteObject remoteObject = spy(new TestRemoteObject()); Class<?> classToAssign = TestRemoteObject.class; String methodName = "aMethod"; UUID uuid = UUID.fromString(UUID_SEED_1); RemoteAccessCommunicationRequest communicationRequest = new RemoteAccessCommunicationRequest(methodName, classToAssign, uuid, null); remoteObjectRegistration.register(remoteObject, classToAssign); remoteObjectRegistration.clear(); remoteObjectRegistration.run(communicationRequest); verify(remoteObject, never()).aMethod(); } |
NativeRemoteObjectRegistration implements RemoteObjectRegistration { @Override public final RemoteAccessCommunicationResponse run(final RemoteAccessCommunicationRequest request) { NetCom2Utils.parameterNotNull(request); NetCom2Utils.parameterNotNull(request.getMethodName(), request.getClazz(), request.getUuid()); final Object handlingObject; synchronized (mapping) { handlingObject = mapping.get(request.getClazz()); } if (handlingObject == null) { logging.error("No registered Objects found for " + request.getClazz()); logging.trace("Returning exception for no registered Object.."); return generateResult(request.getUuid(), new RemoteObjectNotRegisteredException(request.getClazz() + " is not registered!"), null, request.getClazz(), null); } Exception exception = null; Object methodCallResult = null; Method methodToCall = null; for (final Method method : handlingObject.getClass().getMethods()) { if (method.getName().equals(request.getMethodName()) && parameterTypesEqual(method, request.getParameters())) { logging.debug("Found suitable Method " + method.getName() + " of " + handlingObject); methodToCall = method; break; } } if (methodToCall != null) { final Object[] args = orderParameters(request.getParameters(), methodToCall); try { methodCallResult = handleMethod(methodToCall, handlingObject, args); logging.debug("Computed result detected: " + methodCallResult); } catch (final Exception e) { logging.catching(e); exception = e; } catch (final Throwable throwable) { logging.fatal("Encountered throwable, non Exception: " + throwable + " while executing " + methodToCall + " on " + handlingObject.getClass(), throwable); exception = new RemoteException("RemoteObjectRegistration encountered " + throwable.getClass()); } } else { exception = new RemoteObjectInvalidMethodException("No suitable method found for name " + request.getMethodName() + " with parameters" + Arrays.toString(request.getParameters())); } logging.trace("Finalizing run of " + request.getClazz()); return generateResult(request.getUuid(), exception, methodCallResult, request.getClazz(), methodToCall); } @APILevel NativeRemoteObjectRegistration(); @Override final void setup(final ServerStart serverStart); @Override final void close(); @Override final void register(final Object object); @Override final void register(final Object o, final Class<?>... identifier); @Override final void hook(final Object object); @Override final void unregister(final Object object); @Override final void unregister(final Object object, final Class... identifiers); @Override final void unregister(final Class... identifier); @Override final void unhook(final Object object); @Override final void clear(); @Override final RemoteAccessCommunicationResponse run(final RemoteAccessCommunicationRequest request); } | @Test(expected = IllegalArgumentException.class) public void runNullRequest() throws Exception { NativeRemoteObjectRegistration remoteObjectRegistration = new NativeRemoteObjectRegistration(); remoteObjectRegistration.run(null); fail(); } |
EmptyReceivePipelineCondition implements ReceivePipelineCondition<T> { @Override public ReceivePipelineCondition<T> require(BiPredicate<Session, T> userPredicate) { return this; } @Override ReceivePipelineCondition<T> require(BiPredicate<Session, T> userPredicate); @Override ReceivePipelineCondition<T> require(Predicate<Session> userPredicate); } | @Test public void testEmptyReceivePipelineCondition() { QueuedReceivePipeline<ReceivePipelineTestObject> pipeline = new QueuedReceivePipeline<>(ReceivePipelineTestObject.class); ReceivePipelineTestObject object = new ReceivePipelineTestObject(); pipeline.addFirstIfNotContained(testObject -> testObject.value = 1); ReceivePipelineCondition<ReceivePipelineTestObject> condition = pipeline.addFirstIfNotContained(testObject -> testObject.value = 1); condition.require(Session::isIdentified); condition.require((session, testObject) -> false); pipeline.run(mock(ConnectionContext.class), mock(Session.class), object); assertEquals(1, object.value); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.