method2testcases
stringlengths
118
3.08k
### Question: IgnoreRightFunction implements BinaryFunction<L, R, T> { public static <L, R, T> IgnoreRightFunction<L, R, T> adapt(Function<? super L, ? extends T> function) { return null == function ? null : new IgnoreRightFunction<L, R, T>(function); } IgnoreRightFunction(Function<? super L, ? extends T> function); T evaluate(L left, R right); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static IgnoreRightFunction<L, R, T> adapt(Function<? super L, ? extends T> function); }### Answer: @Test public void testAdaptNull() throws Exception { assertNull(IgnoreRightFunction.adapt(null)); } @Test public void testAdapt() throws Exception { assertNotNull(IgnoreRightFunction.adapt(Constant.of("xyzzy"))); }
### Question: FullyBoundNullaryFunction implements NullaryFunction<T> { public T evaluate() { return function.evaluate(left, right); } @SuppressWarnings("unchecked") <L, R> FullyBoundNullaryFunction( BinaryFunction<? super L, ? super R, ? extends T> function, L left, R right); T evaluate(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static FullyBoundNullaryFunction<T> bind( BinaryFunction<? super L, ? super R, ? extends T> function, L left, R right); }### Answer: @Test public void testEvaluate() throws Exception { NullaryFunction<Object> f = new FullyBoundNullaryFunction<Object>(RightIdentity.FUNCTION, null, "foo"); assertEquals("foo", f.evaluate()); }
### Question: FullyBoundNullaryFunction implements NullaryFunction<T> { public static <L, R, T> FullyBoundNullaryFunction<T> bind( BinaryFunction<? super L, ? super R, ? extends T> function, L left, R right) { return null == function ? null : new FullyBoundNullaryFunction<T>(function, left, right); } @SuppressWarnings("unchecked") <L, R> FullyBoundNullaryFunction( BinaryFunction<? super L, ? super R, ? extends T> function, L left, R right); T evaluate(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static FullyBoundNullaryFunction<T> bind( BinaryFunction<? super L, ? super R, ? extends T> function, L left, R right); }### Answer: @Test public void testAdaptNull() throws Exception { assertNull(FullyBoundNullaryFunction.bind(null, null, "xyzzy")); } @Test public void testAdapt() throws Exception { assertNotNull(FullyBoundNullaryFunction.bind(RightIdentity.FUNCTION, "xyzzy", "foobar")); assertNotNull(FullyBoundNullaryFunction.bind(RightIdentity.FUNCTION, null, null)); }
### Question: BinaryFunctionFunction implements Function<A, T> { @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof BinaryFunctionFunction<?, ?>)) { return false; } BinaryFunctionFunction<?, ?> that = (BinaryFunctionFunction<?, ?>) obj; return this.function.equals(that.function); } BinaryFunctionFunction(BinaryFunction<? super A, ? super A, ? extends T> function); T evaluate(A obj); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static Function<A, T> adapt(BinaryFunction<? super A, ? super A, ? extends T> function); }### Answer: @Test public void testEquals() throws Exception { Function<Object, Boolean> f = new BinaryFunctionFunction<Object, Boolean>(BinaryPredicateBinaryFunction.adapt(IsSame.INSTANCE)); assertEquals(f, f); assertObjectsAreEqual(f, new BinaryFunctionFunction<Object, Boolean>(BinaryPredicateBinaryFunction.adapt(IsSame.INSTANCE))); assertObjectsAreNotEqual(f, Constant.truePredicate()); assertObjectsAreNotEqual(f, new BinaryFunctionFunction<Object, Boolean>(BinaryPredicateBinaryFunction.adapt(IsNotSame.INSTANCE))); }
### Question: BinaryFunctionFunction implements Function<A, T> { public static <A, T> Function<A, T> adapt(BinaryFunction<? super A, ? super A, ? extends T> function) { return null == function ? null : new BinaryFunctionFunction<A, T>(function); } BinaryFunctionFunction(BinaryFunction<? super A, ? super A, ? extends T> function); T evaluate(A obj); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static Function<A, T> adapt(BinaryFunction<? super A, ? super A, ? extends T> function); }### Answer: @Test public void testAdaptNull() throws Exception { assertNull(BinaryFunctionFunction.adapt(null)); } @Test public void testAdapt() throws Exception { assertNotNull(BinaryFunctionFunction.adapt(Constant.TRUE)); }
### Question: ArrayListBackedAggregator extends AbstractListBackedAggregator<T> { @Override protected List<T> createList() { return new ArrayList<T>(); } ArrayListBackedAggregator(Function<List<T>, T> aggregationFunction); ArrayListBackedAggregator(Function<List<T>, T> aggregationFunction, long interval); ArrayListBackedAggregator(Function<List<T>, T> aggregationFunction, long interval, boolean useSharedTimer); @Override String toString(); }### Answer: @Test public void testCreateList() throws Exception { @SuppressWarnings("unchecked") ArrayListBackedAggregator<Object> fct = (ArrayListBackedAggregator<Object>) makeFunctor(); assertNotNull(fct.getSeries()); assertTrue(fct.getSeries() instanceof ArrayList); assertEquals(fct.getSeries().size(), 0); int initialSize = 31; fct = new ArrayListBackedAggregator<Object>(new SelectFirstFunction<Object>(), initialSize); assertNotNull(fct.getSeries()); assertTrue(fct.getSeries() instanceof ArrayList); assertEquals(fct.getSeries().size(), 0); }
### Question: AbstractListBackedAggregator extends AbstractTimedAggregator<T> { protected final List<T> getSeries() { return series; } AbstractListBackedAggregator(Function<List<T>, T> aggregationFunction); AbstractListBackedAggregator(Function<List<T>, T> aggregationFunction, long interval); AbstractListBackedAggregator(Function<List<T>, T> aggregationFunction, long interval, boolean useSharedTimer); @Override final void doAdd(T data); @Override String toString(); }### Answer: @Test public void testListCreated() throws Exception { @SuppressWarnings("unchecked") TestListBackedAggregator<Object> fct = (TestListBackedAggregator<Object>) makeFunctor(); assertNotNull(fct.getSeries()); assertEquals(fct.getSeries().size(), 0); } @Test public void testAdd() throws Exception { @SuppressWarnings("unchecked") TestListBackedAggregator<Object> fct = (TestListBackedAggregator<Object>) makeFunctor(); int calls = 31; for (int i = 1; i <= calls; i++) { fct.add(new Object()); assertEquals(fct.getSeries().size(), i); assertEquals(fct.callsCreateList, 0); } } @Test public void testReset() throws Exception { @SuppressWarnings("unchecked") TestListBackedAggregator<Object> fct = (TestListBackedAggregator<Object>) makeFunctor(); int calls = 31; for (int i = 1; i <= calls; i++) { fct.reset(); assertEquals(fct.getSeries().size(), 0); assertEquals(fct.callsCreateList, 0); } }
### Question: AbstractNoStoreAggregator extends AbstractTimedAggregator<T> { final T getResult() { return result; } AbstractNoStoreAggregator(BinaryFunction<T, T, T> aggregationFunction); AbstractNoStoreAggregator(BinaryFunction<T, T, T> aggregationFunction, long interval); AbstractNoStoreAggregator(BinaryFunction<T, T, T> aggregationFunction, long interval, boolean useSharedTimer); @Override String toString(); }### Answer: @Test public void testReset() throws Exception { @SuppressWarnings("unchecked") TestNoStoreAggregator<Object> fct = (TestNoStoreAggregator<Object>) makeFunctor(); int calls = 31; for (int i = 1; i <= calls; i++) { fct.reset(); assertEquals(INITIAL, fct.getResult()); assertEquals(fct.callsInitialValue, i + 1); } }
### Question: AbstractNoStoreAggregator extends AbstractTimedAggregator<T> { @Override protected int retrieveDataSize() { return 0; } AbstractNoStoreAggregator(BinaryFunction<T, T, T> aggregationFunction); AbstractNoStoreAggregator(BinaryFunction<T, T, T> aggregationFunction, long interval); AbstractNoStoreAggregator(BinaryFunction<T, T, T> aggregationFunction, long interval, boolean useSharedTimer); @Override String toString(); }### Answer: @Test public void testDataSize() { assertEquals(0, new TestNoStoreAggregator<Object>(new Object()).retrieveDataSize()); }
### Question: DoubleMaxAggregatorFunction implements Function<List<Double>, Double> { public Double evaluate(List<Double> data) { if (data == null || data.size() == 0) { return null; } Double max = null; for (Double d : data) { if (max == null) { max = d; } else { if (max.doubleValue() < d.doubleValue()) { max = d; } } } return max; } Double evaluate(List<Double> data); @Override String toString(); }### Answer: @Test public void testEmptyList() throws Exception { DoubleMaxAggregatorFunction fct = (DoubleMaxAggregatorFunction) makeFunctor(); List<Double> lst = null; Double res = fct.evaluate(lst); assertNull(res); lst = new ArrayList<Double>(); res = fct.evaluate(lst); assertNull(res); } @Test public void testSum() throws Exception { DoubleMaxAggregatorFunction fct = (DoubleMaxAggregatorFunction) makeFunctor(); List<Double> lst = new ArrayList<Double>(); lst.add(0.0); double res = fct.evaluate(lst); assertEquals(res, 0.0, 0.01); lst.add(1.0); res = fct.evaluate(lst); assertEquals(res, 1.0, 0.01); lst.add(2.0); res = fct.evaluate(lst); assertEquals(res, 2.0, 0.01); lst.clear(); int calls = 31; double max = 0.0; Random rnd = new Random(); for (int i = 0; i < calls; i++) { double random = rnd.nextDouble(); lst.add(random); if (random > max) { max = random; } res = fct.evaluate(lst); assertEquals(res, max, 0.01); } }
### Question: DoubleSumAggregatorBinaryFunction implements BinaryFunction<Double, Double, Double> { public Double evaluate(Double left, Double right) { if (left == null) { return right; } if (right == null) { return left; } return left + right; } Double evaluate(Double left, Double right); @Override String toString(); }### Answer: @Test public void testNulls() throws Exception { DoubleSumAggregatorBinaryFunction fct = (DoubleSumAggregatorBinaryFunction)makeFunctor(); Double d = fct.evaluate(null, null); assertNull( d ); d = fct.evaluate( null, 1.0 ); assertEquals( 1.0, d.doubleValue(), DELTA ); d = fct.evaluate( 2.0, null ); assertEquals( 2.0, d.doubleValue(), DELTA ); } @Test public void testSum() throws Exception { DoubleSumAggregatorBinaryFunction fct = (DoubleSumAggregatorBinaryFunction)makeFunctor(); double total = 0.0; double result = 0.0; int calls = 31; Random rnd = new Random(); for( int i = 0; i < calls; i++ ) { double number = rnd.nextDouble(); total += number; result = fct.evaluate(result, number); assertEquals( result, total, DELTA ); } }
### Question: DoubleMeanValueAggregatorFunction implements Function<List<Double>, Double> { public Double evaluate(List<Double> data) { if (data == null || data.size() == 0) { return null; } double mean = 0.0; int n = data.size(); for (Double d : data) { mean += d.doubleValue(); } mean /= n; return mean; } Double evaluate(List<Double> data); @Override String toString(); }### Answer: @Test public void testEmptyList() throws Exception { DoubleMeanValueAggregatorFunction fct = (DoubleMeanValueAggregatorFunction)makeFunctor(); List<Double> lst = null; Double res = fct.evaluate(lst); assertNull( res ); lst = new ArrayList<Double>(); res = fct.evaluate(lst); assertNull( res ); } @Test public void testMean() throws Exception { DoubleMeanValueAggregatorFunction fct = (DoubleMeanValueAggregatorFunction)makeFunctor(); List<Double> lst = new ArrayList<Double>(); lst.add( 0.0 ); double res = fct.evaluate(lst); assertEquals(res, 0.0, 0.01); lst.add( 1.0 ); res = fct.evaluate( lst ); assertEquals( res, 0.5, 0.01 ); lst.add( 2.0 ); res = fct.evaluate( lst ); assertEquals( res, 1.0, 0.01 ); int calls = 31; double total; for( int i = 2; i <= calls; i++ ) { lst.clear(); total = 0.0; for( int j = 1; j <= i; j++ ) { lst.add( (double)j ); total += j; } total /= i; res = fct.evaluate( lst ); assertEquals( res, total, 0.01 ); } }
### Question: DoubleSumAggregatorFunction implements Function<List<Double>, Double> { public Double evaluate(List<Double> data) { if (data == null || data.size() == 0) { return null; } double sum = 0.0; for (Double d : data) { sum += d; } return sum; } Double evaluate(List<Double> data); @Override String toString(); }### Answer: @Test public void testEmptyList() throws Exception { DoubleSumAggregatorFunction fct = (DoubleSumAggregatorFunction) makeFunctor(); List<Double> lst = null; Double res = fct.evaluate(lst); assertNull(res); lst = new ArrayList<Double>(); res = fct.evaluate(lst); assertNull(res); } @Test public void testSum() throws Exception { DoubleSumAggregatorFunction fct = (DoubleSumAggregatorFunction) makeFunctor(); List<Double> lst = new ArrayList<Double>(); lst.add(0.0); double res = fct.evaluate(lst); assertEquals(res, 0.0, 0.01); lst.add(1.0); res = fct.evaluate(lst); assertEquals(res, 1.0, 0.01); lst.add(2.0); res = fct.evaluate(lst); assertEquals(res, 3.0, 0.01); lst.clear(); int calls = 31; double total = 0.0; Random rnd = new Random(); for (int i = 0; i < calls; i++) { double random = rnd.nextDouble(); lst.add(random); total += random; res = fct.evaluate(lst); assertEquals(res, total, 0.01); } }
### Question: DoubleMaxAggregatorBinaryFunction implements BinaryFunction<Double, Double, Double> { public Double evaluate(Double left, Double right) { if (left == null) { return right; } if (right == null) { return left; } if (left.doubleValue() < right.doubleValue()) { return right; } return left; } Double evaluate(Double left, Double right); @Override String toString(); }### Answer: @Test public void testNulls() throws Exception { DoubleMaxAggregatorBinaryFunction fct = (DoubleMaxAggregatorBinaryFunction) makeFunctor(); Double d = fct.evaluate(null, null); assertNull(d); d = fct.evaluate(null, 1.0); assertEquals(1.0, d.doubleValue(), DELTA); d = fct.evaluate(2.0, null); assertEquals(2.0, d.doubleValue(), DELTA); } @Test public void testMax() throws Exception { DoubleMaxAggregatorBinaryFunction fct = (DoubleMaxAggregatorBinaryFunction) makeFunctor(); double max = 0.0; double result = 0.0; double number1 = 0.0; double number2 = 0.0; int calls = 31; Random rnd = new Random(); for (int i = 0; i < calls; i++) { number1 = rnd.nextDouble(); number2 = rnd.nextDouble(); max = Math.max(number1, number2); result = fct.evaluate(number1, number2); assertEquals(result, max, DELTA); } }
### Question: DoubleMedianValueAggregatorFunction implements Function<List<Double>, Double> { public boolean isUseCopy() { return useCopy; } DoubleMedianValueAggregatorFunction(); DoubleMedianValueAggregatorFunction(boolean useCopy); boolean isUseCopy(); Double evaluate(List<Double> data); @Override String toString(); }### Answer: @Test public void testMedianCopy() throws Exception { DoubleMedianValueAggregatorFunction fct = new DoubleMedianValueAggregatorFunction(true); assertTrue(fct.isUseCopy()); checkMedianCopy(fct); fct = (DoubleMedianValueAggregatorFunction) makeFunctor(); checkMedianCopy(fct); }
### Question: UntilGenerate extends LoopGenerator<E> { @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof UntilGenerate<?>)) { return false; } UntilGenerate<?> other = (UntilGenerate<?>) obj; return other.getWrappedGenerator().equals(getWrappedGenerator()) && other.test.equals(test); } UntilGenerate(Predicate<? super E> test, Generator<? extends E> wrapped); void run(final Procedure<? super E> proc); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer: @Test public void testEquals() { Generator<Integer> anotherGenerate = new UntilGenerate<Integer>( isGreaterThanFive, IteratorToGeneratorAdapter.adapt(new IntegerRange(1, 10))); assertEquals(untilGenerate, untilGenerate); assertEquals(untilGenerate, anotherGenerate); assertTrue(!untilGenerate.equals((UntilGenerate<Integer>)null)); Generator<Integer> aGenerateWithADifferentPredicate = new UntilGenerate<Integer>( new Predicate<Integer>() { public boolean test(Integer obj) { return obj < FIVE; } }, IteratorToGeneratorAdapter.adapt(new IntegerRange(1, 10))); assertTrue(!untilGenerate.equals(aGenerateWithADifferentPredicate)); Generator<Integer> aGenerateWithADifferentWrapped = new UntilGenerate<Integer>( isGreaterThanFive, IteratorToGeneratorAdapter.adapt(new IntegerRange(1,2))); assertTrue(!untilGenerate.equals(aGenerateWithADifferentWrapped)); }
### Question: UntilGenerate extends LoopGenerator<E> { @Override public int hashCode() { int result = "UntilGenerate".hashCode(); result <<= 2; Generator<?> gen = getWrappedGenerator(); result ^= gen.hashCode(); result <<= 2; result ^= test.hashCode(); return result; } UntilGenerate(Predicate<? super E> test, Generator<? extends E> wrapped); void run(final Procedure<? super E> proc); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer: @Test public void testHashcode() { assertEquals(untilGenerate.hashCode(), untilGenerate.hashCode()); assertEquals(untilGenerate.hashCode(), new UntilGenerate<Integer>(isGreaterThanFive, wrappedGenerator).hashCode()); }
### Question: UntilGenerate extends LoopGenerator<E> { public void run(final Procedure<? super E> proc) { getWrappedGenerator().run(new Procedure<E>() { public void run(E obj) { if (test.test(obj)) { UntilGenerate.this.stop(); } else { proc.run(obj); } } }); } UntilGenerate(Predicate<? super E> test, Generator<? extends E> wrapped); void run(final Procedure<? super E> proc); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer: @Test public void testGenerate() { final List<Integer> numbersGreaterThanFive = new ArrayList<Integer>(); untilGenerate.run(new Procedure<Integer>() { public void run( Integer obj ) { numbersGreaterThanFive.add(obj); } }); assertEquals(5, numbersGreaterThanFive.size()); final List<Integer> expected = Arrays.asList(1, 2, 3, 4, 5); assertEquals(expected, numbersGreaterThanFive); }
### Question: IteratorToGeneratorAdapter extends LoopGenerator<E> { public static <E> IteratorToGeneratorAdapter<E> adapt(Iterator<? extends E> iter) { return null == iter ? null : new IteratorToGeneratorAdapter<E>(iter); } IteratorToGeneratorAdapter(Iterator<? extends E> iter); void run(Procedure<? super E> proc); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static IteratorToGeneratorAdapter<E> adapt(Iterator<? extends E> iter); static IteratorToGeneratorAdapter<E> adapt(Iterable<? extends E> iterable); }### Answer: @Test public void testAdaptNull() { assertNull(IteratorToGeneratorAdapter.adapt((Iterator<?>) null)); } @Test public void testAdaptNonNull() { assertNotNull(IteratorToGeneratorAdapter.adapt(list.iterator())); }
### Question: GqlInputConverter { static GraphQLArgument createArgument(Descriptor descriptor, String name) { return GraphQLArgument.newArgument().name(name).type(getInputTypeReference(descriptor)).build(); } private GqlInputConverter( BiMap<String, Descriptor> descriptorMapping, BiMap<String, EnumDescriptor> enumMapping); static Builder newBuilder(); Message createProtoBuf( Descriptor descriptor, Message.Builder builder, Map<String, Object> input); }### Answer: @Test public void unknownProtoShouldPass() { Truth.assertThat(GqlInputConverter.createArgument(Proto1.getDescriptor(), "input")).isNotNull(); } @Test public void inputConverterShouldCreateArgument() { GraphQLArgument argument = GqlInputConverter.createArgument(Proto1.getDescriptor(), "input"); Truth.assertThat(argument.getName()).isEqualTo("input"); Truth.assertThat(((GraphQLNamedType) argument.getType()).getName()) .isEqualTo("Input_javatests_com_google_api_graphql_rejoiner_proto_Proto1"); } @Test public void inputConverterShouldCreateArgumentForMessagesInSameFile() { GraphQLArgument argument = GqlInputConverter.createArgument(Proto2.getDescriptor(), "input"); Truth.assertThat(argument.getName()).isEqualTo("input"); Truth.assertThat(((GraphQLNamedType) argument.getType()).getName()) .isEqualTo("Input_javatests_com_google_api_graphql_rejoiner_proto_Proto2"); }
### Question: ProtoToGql { static String getReferenceName(GenericDescriptor descriptor) { return CharMatcher.anyOf(".").replaceFrom(descriptor.getFullName(), "_"); } private ProtoToGql(); }### Answer: @Test public void getReferenceNameShouldReturnCorrectValueForMessages() { assertThat(ProtoToGql.getReferenceName(Proto1.getDescriptor())) .isEqualTo("javatests_com_google_api_graphql_rejoiner_proto_Proto1"); assertThat(ProtoToGql.getReferenceName(Proto2.getDescriptor())) .isEqualTo("javatests_com_google_api_graphql_rejoiner_proto_Proto2"); } @Test public void getReferenceNameShouldReturnCorrectValueForInnerMessages() { assertThat(ProtoToGql.getReferenceName(InnerProto.getDescriptor())) .isEqualTo("javatests_com_google_api_graphql_rejoiner_proto_Proto1_InnerProto"); } @Test public void getReferenceNameShouldReturnCorrectValueForEnums() { assertThat(ProtoToGql.getReferenceName(TestEnum.getDescriptor())) .isEqualTo("javatests_com_google_api_graphql_rejoiner_proto_Proto2_TestEnum"); }
### Question: QueryResponseToProto { public static <T extends Message> T buildMessage(T message, Map<String, Object> fields) { @SuppressWarnings("unchecked") T populatedMessage = (T) buildMessage(message.toBuilder(), fields); return populatedMessage; } private QueryResponseToProto(); static T buildMessage(T message, Map<String, Object> fields); }### Answer: @Test public void getReferenceNameShouldReturnCorrectValueForMessages() { ProtoTruth.assertThat( QueryResponseToProto.buildMessage( TestProto.Proto1.getDefaultInstance(), ImmutableMap.of( "id", "abc", "intField", 123, "testProto", ImmutableMap.of("innerId", "abc_inner", "enums", ImmutableList.of("FOO"))))) .isEqualTo( Proto1.newBuilder() .setId("abc") .setIntField(123) .setTestProto( Proto2.newBuilder() .setInnerId("abc_inner") .addEnumsValue(Proto2.TestEnum.FOO_VALUE)) .build()); }
### Question: Type { public static ModifiableType find(String typeReferenceName) { return new ModifiableType(typeReferenceName); } private Type(); static ModifiableType find(String typeReferenceName); static ModifiableType find(GenericDescriptor typeDescriptor); }### Answer: @Test public void removeFieldShouldRemoveField() throws Exception { TypeModification typeModification = Type.find("project").removeField("name"); assertThat(typeModification.apply(OBJECT_TYPE).getFieldDefinition("project")).isNull(); } @Test public void removeFieldShouldIgnoreUnknownField() throws Exception { Type.find("project").removeField("unknown_field").apply(OBJECT_TYPE); }
### Question: PostMessageEventListener { public void onMessageEvent(final String eventData) { try { final JSONValue root = JSONParser.parseStrict(eventData); final JSONObject fullJSONMessage = root.isObject(); if (isActionWatched(fullJSONMessage)) { handleJSONMessage(fullJSONMessage); } } catch (final Exception e) { GWT.log("Error while parsing content of message", e); } } void onMessageEvent(final String eventData); abstract String getActionToWatch(); }### Answer: @Test public void onSuccessOrError_should_not_be_called_with_action_not_watched() throws Exception { final String jsonMessage = "{\"message\":\"error\",\"action\":\"\"}"; customPostMessageEventListener.setActionToWatch("Start process"); customPostMessageEventListener.onMessageEvent(jsonMessage); verify(customPostMessageEventListener, never()).success(anyString()); verify(customPostMessageEventListener, never()).error(anyString(), anyInt()); } @Test public void onSuccessOrError_should_be_called_with_valid_json() throws Exception { final String jsonMessage = "{\"message\":\"error\",\"action\":\"\"}"; customPostMessageEventListener.setActionToWatch(""); customPostMessageEventListener.onMessageEvent(jsonMessage); verify(customPostMessageEventListener).error(anyString(), anyInt()); } @Test public void onSuccessOrError_should_not_be_called_with_invalid_json() throws Exception { final String jsonMessage = "{\"message\":\"success\",action\":\"Start process\"}"; customPostMessageEventListener.setActionToWatch("Start process"); customPostMessageEventListener.onMessageEvent(jsonMessage); verify(customPostMessageEventListener, never()).success(anyString()); verify(customPostMessageEventListener, never()).error(anyString(), anyInt()); }
### Question: LogoutUrl { public void setParameter(String key, String value) { builder.addParameter(key, value); } LogoutUrl(UrlBuilder builder, String locale); void setParameter(String key, String value); @Override String toString(); static final String LOGOUT_URL; }### Answer: @Test public void testWeCanSetAParameter() throws Exception { LogoutUrl logoutUrl = new LogoutUrl(builder, "fr"); logoutUrl.setParameter("aParameter", "itsValue"); new LogoutUrl(builder, "fr"); verify(builder).addParameter("aParameter", "itsValue"); }
### Question: VariableUtils { public static void inject(HtmlAccessor accessor, String name, SafeHtml value) { accessor.setInnerHTML(replaceAll(accessor.getInnerHTML(), name, value)); } static void inject(HtmlAccessor accessor, String name, SafeHtml value); }### Answer: @Test public void testWeCanReplaceASpecificVariable() throws Exception { doReturn("<p>This is %variable1% for variable1 but not for variable2</p>") .when(accessor) .getInnerHTML(); VariableUtils.inject(accessor, "variable1", SafeHtmlUtils.fromTrustedString("working")); verify(accessor).setInnerHTML("<p>This is working for variable1 but not for variable2</p>"); } @Test public void testWeHtmlWithoutVariableStayTheSame() throws Exception { doReturn("<p class='aside'>This is a test</p>") .when(accessor) .getInnerHTML(); VariableUtils.inject(accessor, "variable", SafeHtmlUtils.fromTrustedString("value")); verify(accessor).setInnerHTML("<p class='aside'>This is a test</p>"); } @Test public void testWeCanReplaceMultipleVariables() throws Exception { doReturn("<p class='%variable%'>This is %variable%</p>") .when(accessor) .getInnerHTML(); VariableUtils.inject(accessor, "variable", SafeHtmlUtils.fromTrustedString("working")); verify(accessor).setInnerHTML("<p class='working'>This is working</p>"); }
### Question: ProcessFormService { public long ensureProcessDefinitionId(final APISession apiSession, final long processDefinitionId, final long processInstanceId, final long taskInstanceId) throws ArchivedProcessInstanceNotFoundException, ActivityInstanceNotFoundException, BonitaException { if (processDefinitionId != -1L) { return processDefinitionId; } else if (processInstanceId != -1L) { return getProcessDefinitionIdFromProcessInstanceId(apiSession, processInstanceId); } else { return getProcessDefinitionIdFromTaskId(apiSession, taskInstanceId); } } String getProcessPath(final APISession apiSession, final long processDefinitionId); String encodePathSegment(final String stringToEncode); long getProcessDefinitionId(final APISession apiSession, final String processName, final String processVersion); long getTaskInstanceId(final APISession apiSession, final long processInstanceId, final String taskName, final long userId); String getTaskName(final APISession apiSession, final long taskInstanceId); long ensureProcessDefinitionId(final APISession apiSession, final long processDefinitionId, final long processInstanceId, final long taskInstanceId); boolean isAllowedToSeeTask(final APISession apiSession, final long taskInstanceId, final long enforcedUserId, final boolean assignTask); boolean isAllowedToSeeProcessInstance(final APISession apiSession, final long processInstanceId, final long enforcedUserId); boolean isAllowedToStartProcess(final APISession apiSession, final long processDefinitionId, final long enforcedUserId); boolean isAllowedAsAdminOrProcessSupervisor(final HttpServletRequest request, final APISession apiSession, final long processDefinitionId, final long taskInstanceId, final long userId, final boolean assignTask); }### Answer: @Test public void ensureProcessDefinitionId_with_processDefinitionId() throws Exception { assertEquals(42L, processFormService.ensureProcessDefinitionId(apiSession, 42L, -1L, -1L)); }
### Question: ProcessFormService { public long getProcessDefinitionId(final APISession apiSession, final String processName, final String processVersion) throws ProcessDefinitionNotFoundException, BonitaException { if (processName != null && processVersion != null) { try { return getProcessAPI(apiSession).getProcessDefinitionId(processName, processVersion); } catch (final ProcessDefinitionNotFoundException e) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Wrong parameters for process name and version", e); } } } return -1L; } String getProcessPath(final APISession apiSession, final long processDefinitionId); String encodePathSegment(final String stringToEncode); long getProcessDefinitionId(final APISession apiSession, final String processName, final String processVersion); long getTaskInstanceId(final APISession apiSession, final long processInstanceId, final String taskName, final long userId); String getTaskName(final APISession apiSession, final long taskInstanceId); long ensureProcessDefinitionId(final APISession apiSession, final long processDefinitionId, final long processInstanceId, final long taskInstanceId); boolean isAllowedToSeeTask(final APISession apiSession, final long taskInstanceId, final long enforcedUserId, final boolean assignTask); boolean isAllowedToSeeProcessInstance(final APISession apiSession, final long processInstanceId, final long enforcedUserId); boolean isAllowedToStartProcess(final APISession apiSession, final long processDefinitionId, final long enforcedUserId); boolean isAllowedAsAdminOrProcessSupervisor(final HttpServletRequest request, final APISession apiSession, final long processDefinitionId, final long taskInstanceId, final long userId, final boolean assignTask); }### Answer: @Test public void getProcessDefinitionId_with_no_version() throws Exception { assertEquals(-1L, processFormService.getProcessDefinitionId(apiSession, "myProcess", null)); } @Test public void getProcessDefinitionId_with_no_name_and_version() throws Exception { assertEquals(-1L, processFormService.getProcessDefinitionId(apiSession, null, null)); }
### Question: AuthenticationFilter extends ExcludingPatternFilter { protected void redirectTo(final HttpServletRequestAccessor request, final HttpServletResponse response, final long tenantId, final String pagePath) throws ServletException { try { response.sendRedirect(request.asHttpServletRequest().getContextPath() + pagePath); } catch (final IOException e) { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, e.getMessage()); } } } AuthenticationFilter(); String getDefaultExcludedPages(); @Override void proceedWithFiltering(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); }### Answer: @Test public void testRedirectTo() throws Exception { final String context = "/bonita"; when(httpRequest.getContextPath()).thenReturn(context); final long tenantId = 0L; authenticationFilter.redirectTo(request, httpResponse, tenantId, AuthenticationFilter.MAINTENANCE_JSP); verify(httpResponse, times(1)).sendRedirect(context + AuthenticationFilter.MAINTENANCE_JSP); verify(httpRequest, times(1)).getContextPath(); }
### Question: AuthenticationFilter extends ExcludingPatternFilter { protected RedirectUrl makeRedirectUrl(final HttpServletRequestAccessor httpRequest) { final RedirectUrlBuilder builder = new RedirectUrlBuilder(httpRequest.getRequestedUri()); builder.appendParameters(httpRequest.getParameterMap()); return builder.build(); } AuthenticationFilter(); String getDefaultExcludedPages(); @Override void proceedWithFiltering(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); }### Answer: @Test public void testMakeRedirectUrl() throws Exception { when(request.getRequestedUri()).thenReturn("/portal/homepage"); final RedirectUrl redirectUrl = authenticationFilter.makeRedirectUrl(request); verify(request, times(1)).getRequestedUri(); assertThat(redirectUrl.getUrl()).isEqualToIgnoringCase("/portal/homepage"); } @Test public void testMakeRedirectUrlFromRequestUrl() throws Exception { when(request.getRequestedUri()).thenReturn("portal/homepage"); when(httpRequest.getRequestURL()).thenReturn(new StringBuffer("http: final RedirectUrl redirectUrl = authenticationFilter.makeRedirectUrl(request); verify(request, times(1)).getRequestedUri(); verify(httpRequest, never()).getRequestURI(); assertThat(redirectUrl.getUrl()).isEqualToIgnoringCase("portal/homepage"); }
### Question: TokenGenerator { public String createOrLoadToken(final HttpSession session) { Object apiTokenFromClient = session.getAttribute(API_TOKEN); if (apiTokenFromClient == null) { apiTokenFromClient = new APIToken().getToken(); session.setAttribute(API_TOKEN, apiTokenFromClient); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Bonita API Token generated: " + apiTokenFromClient); } } return apiTokenFromClient.toString(); } @Deprecated void setTokenToResponseCookie(HttpServletRequest request, HttpServletResponse res, Object apiTokenFromClient); String createOrLoadToken(final HttpSession session); void setTokenToResponseHeader(final HttpServletResponse res, final String token); static final String API_TOKEN; static final String X_BONITA_API_TOKEN; }### Answer: @Test public void should_create_token_and_store_it_in_session() throws Exception { final String token = tokenGenerator.createOrLoadToken(session); assertThat(token).isNotEmpty(); assertThat(session.getAttribute(TokenGenerator.API_TOKEN)).isEqualTo(token); } @Test public void should_load_token_from_session() throws Exception { session.setAttribute(TokenGenerator.API_TOKEN, BONITA_TOKEN_VALUE); final String token = tokenGenerator.createOrLoadToken(session); assertThat(token).isNotEmpty(); assertThat(token).isEqualTo(BONITA_TOKEN_VALUE); }
### Question: TokenGenerator { @Deprecated public void setTokenToResponseCookie(HttpServletRequest request, HttpServletResponse res, Object apiTokenFromClient) { PortalCookies portalCookies = new PortalCookies(); portalCookies.addCSRFTokenCookieToResponse(request, res, apiTokenFromClient); } @Deprecated void setTokenToResponseCookie(HttpServletRequest request, HttpServletResponse res, Object apiTokenFromClient); String createOrLoadToken(final HttpSession session); void setTokenToResponseHeader(final HttpServletResponse res, final String token); static final String API_TOKEN; static final String X_BONITA_API_TOKEN; }### Answer: @Test public void testSetTokenToResponseCookie() throws Exception { portalCookies.addCSRFTokenCookieToResponse(request, response, BONITA_TOKEN_VALUE); final Cookie csrfCookie = response.getCookie(BONITA_TOKEN_NAME); assertThat(csrfCookie.getName()).isEqualTo(BONITA_TOKEN_NAME); assertThat(csrfCookie.getPath()).isEqualTo(CONTEXT_PATH); assertThat(csrfCookie.getValue()).isEqualTo(BONITA_TOKEN_VALUE); assertThat(csrfCookie.getSecure()).isFalse(); }
### Question: TokenGenerator { public void setTokenToResponseHeader(final HttpServletResponse res, final String token) { if(res.containsHeader(X_BONITA_API_TOKEN)){ res.setHeader(X_BONITA_API_TOKEN, token); } else { res.addHeader(X_BONITA_API_TOKEN, token); } } @Deprecated void setTokenToResponseCookie(HttpServletRequest request, HttpServletResponse res, Object apiTokenFromClient); String createOrLoadToken(final HttpSession session); void setTokenToResponseHeader(final HttpServletResponse res, final String token); static final String API_TOKEN; static final String X_BONITA_API_TOKEN; }### Answer: @Test public void testSetTokenToResponseHeader() throws Exception { tokenGenerator.setTokenToResponseHeader(response, BONITA_TOKEN_VALUE); assertThat(response.getHeader(BONITA_TOKEN_NAME)).isEqualTo(BONITA_TOKEN_VALUE); }
### Question: AlreadyLoggedInRule extends AuthenticationRule { @Override public boolean doAuthorize(final HttpServletRequestAccessor request, HttpServletResponse response, final TenantIdAccessor tenantIdAccessor) throws ServletException { if (isUserAlreadyLoggedIn(request, tenantIdAccessor)) { ensureUserSession(request.asHttpServletRequest(), request.getHttpSession(), request.getApiSession()); return true; } return false; } @Override boolean doAuthorize(final HttpServletRequestAccessor request, HttpServletResponse response, final TenantIdAccessor tenantIdAccessor); }### Answer: @Test public void testIfRuleAuthorizeAlreadyLoggedUser() throws Exception { doReturn(apiSession).when(request).getApiSession(); doReturn("").when(httpSession).getAttribute(SessionUtil.USER_SESSION_PARAM_KEY); final boolean authorization = rule.doAuthorize(request, response, tenantAccessor); assertThat(authorization, is(true)); } @Test public void testIfRuleDoesntAuthorizeNullSession() throws Exception { doReturn(null).when(request).getApiSession(); final boolean authorization = rule.doAuthorize(request, response, tenantAccessor); assertFalse(authorization); }
### Question: V6FormsAutoLoginRule extends AuthenticationRule { @Override public boolean doAuthorize(final HttpServletRequestAccessor request, HttpServletResponse response, final TenantIdAccessor tenantIdAccessor) throws ServletException { final long tenantId = tenantIdAccessor.ensureTenantId(); return doAutoLogin(request, response, tenantId); } @Override boolean doAuthorize(final HttpServletRequestAccessor request, HttpServletResponse response, final TenantIdAccessor tenantIdAccessor); }### Answer: @Test public void testWeAreNotAutoLoggedWhenNotConfigured() throws Exception { doReturn("process3--2.9").when(request).getAutoLoginScope(); doReturn(1L).when(tenantAccessor).getRequestedTenantId(); when(autoLoginCredentialsFinder.getCredential(new ProcessIdentifier("process3--2.9"),1L)).thenReturn(null); final boolean authorized = rule.doAuthorize(request, response, tenantAccessor); assertFalse(authorized); }
### Question: RestAPIAuthorizationFilter extends AbstractAuthorizationFilter { protected boolean checkPermissions(final HttpServletRequest request) throws ServletException { final RestRequestParser restRequestParser = new RestRequestParser(request).invoke(); return checkPermissions(request, restRequestParser.getApiName(), restRequestParser.getResourceName(), restRequestParser.getResourceQualifiers()); } RestAPIAuthorizationFilter(final boolean reload); RestAPIAuthorizationFilter(); static final String SCRIPT_TYPE_AUTHORIZATION_PREFIX; }### Answer: @Test public void should_checkPermissions_parse_the_request() throws Exception { doReturn("API/bpm/case/15").when(request).getPathInfo(); final RestAPIAuthorizationFilter restAPIAuthorizationFilterSpy = spy(restAPIAuthorizationFilter); doReturn(true).when(restAPIAuthorizationFilterSpy).checkPermissions(eq(request), eq("bpm"), eq("case"), eq(APIID.makeAPIID(15l))); restAPIAuthorizationFilterSpy.checkPermissions(request); verify(restAPIAuthorizationFilterSpy).checkPermissions(eq(request), eq("bpm"), eq("case"), eq(APIID.makeAPIID(15l))); }
### Question: RestAPIAuthorizationFilter extends AbstractAuthorizationFilter { protected boolean staticCheck(final APICallContext apiCallContext, final Set<String> permissionsOfUser, final Set<String> resourcePermissions, final String username) { for (final String resourcePermission : resourcePermissions) { if (permissionsOfUser.contains(resourcePermission)) { return true; } } if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "Unauthorized access to " + apiCallContext.getMethod() + " " + apiCallContext.getApiName() + "/" + apiCallContext.getResourceName() + (apiCallContext.getResourceId() != null ? "/" + apiCallContext.getResourceId() : "") + " attempted by " + username + " required permissions: " + resourcePermissions); } return false; } RestAPIAuthorizationFilter(final boolean reload); RestAPIAuthorizationFilter(); static final String SCRIPT_TYPE_AUTHORIZATION_PREFIX; }### Answer: @Test public void test_staticCheck_authorized() throws Exception { final Set<String> userPermissions = new HashSet<String>(Arrays.asList("MyPermission", "AnOtherPermission")); final List<String> resourcePermissions = Arrays.asList("CasePermission", "AnOtherPermission"); returnPermissionFor("GET", "bpm", "case", null, resourcePermissions); final boolean isAuthorized = restAPIAuthorizationFilter.staticCheck(new APICallContext("GET", "bpm", "case", null), userPermissions, new HashSet<String>(resourcePermissions), username); assertThat(isAuthorized).isTrue(); } @Test public void test_staticCheck_unauthorized() throws Exception { final Set<String> userPermissions = new HashSet<String>(Arrays.asList("MyPermission", "AnOtherPermission")); final List<String> resourcePermissions = Arrays.asList("CasePermission", "SecondPermission"); returnPermissionFor("GET", "bpm", "case", null, resourcePermissions); final boolean isAuthorized = restAPIAuthorizationFilter.staticCheck(new APICallContext("GET", "bpm", "case", null), userPermissions, new HashSet<String>(resourcePermissions), username); assertThat(isAuthorized).isFalse(); }
### Question: RestAPIAuthorizationFilter extends AbstractAuthorizationFilter { protected boolean dynamicCheck(final APICallContext apiCallContext, final Set<String> userPermissions, final Set<String> resourceAuthorizations, final APISession apiSession) throws ServletException { checkResourceAuthorizationsSyntax(resourceAuthorizations); if (checkDynamicPermissionsWithUsername(resourceAuthorizations, apiSession) || checkDynamicPermissionsWithProfiles(resourceAuthorizations, userPermissions)) { return true; } final String resourceClassname = getResourceClassname(resourceAuthorizations); if (resourceClassname != null) { return checkDynamicPermissionsWithScript(apiCallContext, resourceClassname, apiSession); } return false; } RestAPIAuthorizationFilter(final boolean reload); RestAPIAuthorizationFilter(); static final String SCRIPT_TYPE_AUTHORIZATION_PREFIX; }### Answer: @Test public void should_dynamicCheck_return_false_on_resource_with_no_script() throws Exception { final boolean isAuthorized = restAPIAuthorizationFilter.dynamicCheck(new APICallContext("GET", "bpm", "case", null, "", ""), new HashSet<String>(), new HashSet<String>(), apiSession); assertThat(isAuthorized).isFalse(); }
### Question: RestAPIAuthorizationFilter extends AbstractAuthorizationFilter { protected boolean checkResourceAuthorizationsSyntax(final Set<String> resourceAuthorizations) { boolean valid = true; for (final String resourceAuthorization : resourceAuthorizations) { if (!resourceAuthorization.matches("(" + PermissionsBuilder.USER_TYPE_AUTHORIZATION_PREFIX + "|" + PermissionsBuilder.PROFILE_TYPE_AUTHORIZATION_PREFIX + "|" + SCRIPT_TYPE_AUTHORIZATION_PREFIX + ")\\|.+")) { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.log(Level.WARNING, "Error while getting dynamic authoriations. Unknown syntax: " + resourceAuthorization + " defined in dynamic-permissions-checks.properties"); } valid = false; } } return valid; } RestAPIAuthorizationFilter(final boolean reload); RestAPIAuthorizationFilter(); static final String SCRIPT_TYPE_AUTHORIZATION_PREFIX; }### Answer: @Test public void checkResourceAuthorizationsSyntax_should_return_false_if_syntax_is_invalid() throws Exception { final RestAPIAuthorizationFilter restAPIAuthorizationFilterSpy = spy(restAPIAuthorizationFilter); final Set<String> resourceAuthorizations = new HashSet<String>(); resourceAuthorizations.add("any string"); final boolean isValid = restAPIAuthorizationFilterSpy.checkResourceAuthorizationsSyntax(resourceAuthorizations); assertThat(isValid).isFalse(); } @Test public void checkResourceAuthorizationsSyntax_should_return_true_if_syntax_is_valid() throws Exception { final RestAPIAuthorizationFilter restAPIAuthorizationFilterSpy = spy(restAPIAuthorizationFilter); final Set<String> resourceAuthorizations = new HashSet<String>(Arrays.asList("user|any.username", "profile|any.profile", "check|className")); final boolean isValid = restAPIAuthorizationFilterSpy.checkResourceAuthorizationsSyntax(resourceAuthorizations); assertThat(isValid).isTrue(); }
### Question: MultiReadHttpServletRequest extends HttpServletRequestWrapper { @Override public ServletInputStream getInputStream() throws IOException { if (readBytes == null) { readInputStream(); } return new CachedServletInputStream(); } MultiReadHttpServletRequest(final HttpServletRequest request); @Override ServletInputStream getInputStream(); @Override BufferedReader getReader(); }### Answer: @Test public void should_getInputStream_work_when_called_twice() throws Exception { ServletInputStream fakeInputStream = null; try { fakeInputStream = new FakeServletInputStream(); doReturn(fakeInputStream).when(request).getInputStream(); final MultiReadHttpServletRequest multiReadHttpServletRequest = new MultiReadHttpServletRequest(request); final InputStream inputStream = multiReadHttpServletRequest.getInputStream(); Assert.assertEquals("body content", IOUtils.toString(inputStream)); final InputStream inputStream2 = multiReadHttpServletRequest.getInputStream(); Assert.assertEquals("body content", IOUtils.toString(inputStream2)); } finally { if (fakeInputStream != null) { fakeInputStream.close(); } } }
### Question: AutoLoginCredentialsFinder { public AutoLoginCredentials getCredential(ProcessIdentifier processIdentifier, long tenantId){ AutoLoginCredentials autoLoginCredentials = getAutoLoginCredentials(processIdentifier, tenantId); return autoLoginCredentials; } AutoLoginCredentialsFinder(ConfigurationFilesManager configurationFilesManager); AutoLoginCredentials getCredential(ProcessIdentifier processIdentifier, long tenantId); }### Answer: @Test public void should_retrieve_credentials_when_autologin_available_for_the_requested_process_and_tenant() throws Exception{ when(configurationFilesManager.getTenantAutoLoginConfiguration(TENANT_ID)).thenReturn(autoLoginConfiguration); AutoLoginCredentials autoLoginCredentials = autoLoginCredentialsFinder.getCredential(new ProcessIdentifier("my process", "2.0"), TENANT_ID); assertThat(autoLoginCredentials.getUserName()).isEqualTo("john.bates"); assertThat(autoLoginCredentials.getPassword()).isEqualTo("bpm"); } @Test public void should_retrieve_empty_credentials_when_autologin_not_available_for_the_requested_process_and_tenant() throws Exception{ when(configurationFilesManager.getTenantAutoLoginConfiguration(TENANT_ID)).thenReturn(autoLoginConfiguration); AutoLoginCredentials autoLoginCredentials = autoLoginCredentialsFinder.getCredential(new ProcessIdentifier("process without autologin", "1.0"), TENANT_ID); assertThat(autoLoginCredentials).isEqualTo(null); } @Test public void should_retrieve_empty_credentials_when_cannot_read_configuration() throws Exception{ when(configurationFilesManager.getTenantAutoLoginConfiguration(TENANT_ID)).thenReturn(null); AutoLoginCredentials autoLoginCredentials = autoLoginCredentialsFinder.getCredential(new ProcessIdentifier("process without autologin", "1.0"), TENANT_ID); assertThat(autoLoginCredentials).isEqualTo(null); }
### Question: TenantIdAccessor { public long getRequestedTenantId() throws ServletException { return parseTenantId(request.getTenantId()); } TenantIdAccessor(HttpServletRequestAccessor request); long getRequestedTenantId(); long ensureTenantId(); long getDefaultTenantId(); long getTenantIdFromRequestOrCookie(); }### Answer: @Test public void testIfWeRetrieveRequestedTenantId() throws Exception { doReturn("5").when(requestAccessor).getTenantId(); TenantIdAccessor accessor = new TenantIdAccessor(requestAccessor); assertEquals(5L, accessor.getRequestedTenantId()); } @Test public void testNullTenantId() throws Exception { doReturn(null).when(requestAccessor).getTenantId(); TenantIdAccessor accessor = new TenantIdAccessor(requestAccessor); assertEquals(-1L, accessor.getRequestedTenantId()); }
### Question: TenantIdAccessor { public long ensureTenantId() throws ServletException { long tenantId = parseTenantId(request.getTenantId()); if(tenantId < 0) { return getDefaultTenantId(); } return getRequestedTenantId(); } TenantIdAccessor(HttpServletRequestAccessor request); long getRequestedTenantId(); long ensureTenantId(); long getDefaultTenantId(); long getTenantIdFromRequestOrCookie(); }### Answer: @Test(expected = ServletException.class) public void testInvalidTenantIdThrowsException() throws Exception { doReturn("invalid").when(requestAccessor).getTenantId(); new TenantIdAccessor(requestAccessor).ensureTenantId(); }
### Question: TenantIdAccessor { public long getTenantIdFromRequestOrCookie() throws ServletException { String tenantId = request.getTenantId(); if (tenantId == null) { tenantId = portalCookies.getTenantCookieFromRequest(request.asHttpServletRequest()); } if (tenantId == null) { return getDefaultTenantId(); } return parseTenantId(tenantId); } TenantIdAccessor(HttpServletRequestAccessor request); long getRequestedTenantId(); long ensureTenantId(); long getDefaultTenantId(); long getTenantIdFromRequestOrCookie(); }### Answer: @Test public void should_retrieve_tenant_id_from_request_when_set_in_request_parameters() throws Exception { request.setCookies(new Cookie("bonita.tenant", "123")); doReturn("5").when(requestAccessor).getTenantId(); long tenantId = tenantIdAccessor.getTenantIdFromRequestOrCookie(); assertThat(tenantId).isEqualTo(5); } @Test public void should_retrieve_tenant_id_from_cookies_when_not_set_in_request_parameters() throws Exception { request.setCookies(new Cookie("bonita.tenant", "123")); long tenantId = tenantIdAccessor.getTenantIdFromRequestOrCookie(); assertThat(tenantId).isEqualTo(123); }
### Question: LogoutServlet extends HttpServlet { protected String sanitizeLoginPageUrl(final String loginURL) { return new RedirectUrlBuilder(new URLProtector().protectRedirectUrl(loginURL)).build().getUrl(); } }### Answer: @Test public void testtSanitizeLoginPageUrlEmptyLoginPageUrl() throws Exception { String loginPage = logoutServlet.sanitizeLoginPageUrl(""); assertThat(loginPage).isEqualToIgnoringCase(""); } @Test public void testtSanitizeLoginPageUrlFromMaliciousRedirectShouldReturnBrokenUrl() throws Exception { try { logoutServlet.sanitizeLoginPageUrl("http: fail("building a login page with a different host on the redirectURL should fail"); } catch (Exception e) { if (!(e.getCause() instanceof URISyntaxException)) { fail("Exception root cause should be a URISyntaxException"); } } } @Test public void testtSanitizeLoginPageUrlFromMaliciousRedirectShouldReturnBrokenUrl2() throws Exception { String loginPage = logoutServlet.sanitizeLoginPageUrl("test.com"); assertThat(loginPage).isEqualToIgnoringCase("test.com"); } @Test public void testSanitizeLoginPageUrlShouldReturnCorrectUrl() throws Exception { String loginPage = logoutServlet.sanitizeLoginPageUrl("portal/homepage?p=test#poutpout"); assertThat(loginPage).isEqualToIgnoringCase("portal/homepage?p=test#poutpout"); }
### Question: LogoutServlet extends HttpServlet { protected String getURLToRedirectTo(final HttpServletRequestAccessor requestAccessor, final long tenantId) throws AuthenticationManagerNotFoundException, UnsupportedEncodingException, ConsumerNotFoundException, ServletException { final AuthenticationManager authenticationManager = getAuthenticationManager(tenantId); final HttpServletRequest request = requestAccessor.asHttpServletRequest(); final String redirectURL = createRedirectUrl(requestAccessor, tenantId); final String logoutPage = authenticationManager.getLogoutPageURL(requestAccessor, redirectURL); String redirectionPage = null; if (logoutPage != null) { redirectionPage = logoutPage; } else { final String loginPageURLFromRequest = request.getParameter(LOGIN_URL_PARAM_NAME); if (loginPageURLFromRequest != null) { redirectionPage = sanitizeLoginPageUrl(loginPageURLFromRequest); } else { LoginUrl loginPageURL = new LoginUrl(authenticationManager, redirectURL, requestAccessor); redirectionPage = loginPageURL.getLocation(); } } return redirectionPage; } }### Answer: @Test public void testGetURLToRedirectToFromAuthenticationManagerLogin() throws Exception { doReturn("loginURL").when(authenticationManager).getLoginPageURL(eq(requestAccessor), anyString()); String loginPage = logoutServlet.getURLToRedirectTo(requestAccessor, 1L); assertThat(loginPage).isEqualTo("loginURL"); } @Test public void testGetURLToRedirectToFromRequest() throws Exception { doReturn(null).when(authenticationManager).getLoginPageURL(eq(requestAccessor), anyString()); doReturn("redirectURLFromRequest").when(request).getParameter(LogoutServlet.LOGIN_URL_PARAM_NAME); String loginPage = logoutServlet.getURLToRedirectTo(requestAccessor, 1L); assertThat(loginPage).isEqualTo("redirectURLFromRequest"); }
### Question: LogoutServlet extends HttpServlet { protected String createRedirectUrl(final HttpServletRequestAccessor request, final long tenantId) throws ServletException { final String redirectUrlFromRequest = request.getRedirectUrl(); String redirectUrl = redirectUrlFromRequest != null ? redirectUrlFromRequest : getDefaultRedirectUrl(tenantId); return new RedirectUrlBuilder(redirectUrl).build().getUrl(); } }### Answer: @Test public void testCreateRedirectUrlWithDefaultRedirect() throws Exception { doReturn(null).when(requestAccessor).getRedirectUrl(); String redirectURL = logoutServlet.createRedirectUrl(requestAccessor, 1L); assertThat(redirectURL).isEqualTo(AuthenticationManager.DEFAULT_DIRECT_URL); } @Test public void testCreateRedirectUrlWithDefaultRedirectAndNonDefaultTenant() throws Exception { doReturn(null).when(requestAccessor).getRedirectUrl(); String redirectURL = logoutServlet.createRedirectUrl(requestAccessor, 3L); assertThat(redirectURL).isEqualTo(AuthenticationManager.DEFAULT_DIRECT_URL + "?tenant=3"); } @Test public void testCreateRedirectUrl() throws Exception { doReturn("redirectURL").when(requestAccessor).getRedirectUrl(); String redirectURL = logoutServlet.createRedirectUrl(requestAccessor, 1L); assertThat(redirectURL).isEqualTo("redirectURL"); }
### Question: LoginServlet extends HttpServlet { @Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException { try { request.setCharacterEncoding(StandardCharsets.UTF_8.name()); } catch (final UnsupportedEncodingException e) { throw new ServletException(e); } if (request.getContentType() != null && !MediaType.APPLICATION_WWW_FORM.equals(ContentType.readMediaType(request.getContentType()))) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "The only content type supported by this service is application/x-www-form-urlencoded. The content-type request header needs to be set accordingly."); } response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); } else { handleLogin(request, response); } } String dropPassword(final String content); }### Answer: @Test public void should_send_error_415_when_login_with_wrong_content_type() throws Exception { final LoginServlet servlet = spy(new LoginServlet()); doReturn("application/json").when(req).getContentType(); servlet.doPost(req, resp); verify(resp).setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); }
### Question: URLProtector { public String protectRedirectUrl(String redirectUrl) { if (redirectUrl != null && !redirectUrl.startsWith("portal")) { return removeTokenFromUrl(redirectUrl, new ArrayList<String>(tokens)); } return redirectUrl; } String protectRedirectUrl(String redirectUrl); }### Answer: @Test public void testProtectRedirectUrlShouldRemoveHTTPFromURL() { assertEquals("google", urlProtecter.protectRedirectUrl("httpgoogle")); } @Test public void testProtectRedirectUrlShouldRemoveHTTPSFromURL() { assertEquals("google", urlProtecter.protectRedirectUrl("httpsgoogle")); } @Test public void testProtectRedirectUrlShouldNotChangeURL() { assertEquals("mobile/#home", urlProtecter.protectRedirectUrl("mobile/#home")); assertEquals("/bonita/mobile/#login", urlProtecter.protectRedirectUrl("/bonita/mobile/#login")); assertEquals("/bonita/portal", urlProtecter.protectRedirectUrl("/bonita/portal")); } @Test public void testProtectRedirectUrlRedirectingtoCaseListingUser() { assertEquals("#?_p=caselistinguser", urlProtecter.protectRedirectUrl("#?_p=caselistinguser")); } @Test public void testProtectRedirectUrlIsNotChangedIfStartingWithBonitaPortal() { assertEquals("portal/homepage#?_p=caselistinguser&test=http: urlProtecter.protectRedirectUrl("portal/homepage#?_p=caselistinguser&test=http: } @Test public void it_should_filter_capital_letters(){ assertEquals(":.google.com", urlProtecter.protectRedirectUrl("HTTPS: } @Test public void it_should_filter_double_backslash() { assertEquals(".google.com", urlProtecter.protectRedirectUrl(" assertEquals("google.com", urlProtecter.protectRedirectUrl(" }
### Question: RedirectUrlBuilder { public RedirectUrl build() { return new RedirectUrl(urlBuilder.build()); } RedirectUrlBuilder(final String redirectUrl); RedirectUrl build(); void appendParameters(final Map<String, String[]> parameters); void appendParameter(String name, String... values); }### Answer: @Test public void testWeCanBuildHashTaggedParamAreKept() throws Exception { final RedirectUrlBuilder redirectUrlBuilder = new RedirectUrlBuilder("myredirecturl?parambeforehash=true#hashparam=true"); final String url = redirectUrlBuilder.build().getUrl(); assertEquals("myredirecturl?parambeforehash=true#hashparam=true", url); } @Test public void testPostParamsAreNotAddedToTheUrl() { final Map<String, String[]> parameters = new HashMap<String, String[]>(); parameters.put("postParam", someValues("true")); final RedirectUrlBuilder redirectUrlBuilder = new RedirectUrlBuilder("myredirecturl?someparam=value#hashparam=true"); final String url = redirectUrlBuilder.build().getUrl(); assertEquals("myredirecturl?someparam=value#hashparam=true", url); }
### Question: ProcessInstanceExpressionsEvaluator { public Map<String, Serializable> evaluate(ProcessInstanceAccessor instance, final Map<Expression, Map<String, Serializable>> expressions, boolean atProcessInstanciation) throws BPMEngineException, BPMExpressionEvaluationException { if (atProcessInstanciation) { return evaluateExpressionsAtProcessInstanciation(instance.getId(), expressions); } else if (instance.isArchived()) { return evaluateExpressionsOnCompleted(instance.getId(), expressions); } else { return evaluateExpressionsOnProcessInstance(instance.getId(), expressions); } } ProcessInstanceExpressionsEvaluator(ExpressionEvaluatorEngineClient engineEvaluator); Map<String, Serializable> evaluate(ProcessInstanceAccessor instance, final Map<Expression, Map<String, Serializable>> expressions, boolean atProcessInstanciation); }### Answer: @Test public void testEvaluateExpressionOnCompletedProcessInstance() throws Exception { when(processInstance.getId()).thenReturn(2L); when(processInstance.isArchived()).thenReturn(true); when(engineEvaluator.evaluateExpressionsOnCompletedProcessInstance(2L, someExpressions)) .thenReturn(aKnownResultSet()); Map<String, Serializable> evaluated = evaluator.evaluate(processInstance, someExpressions, false); assertEquals(aKnownResultSet(), evaluated); }
### Question: TenantIdAccessorFactory { @SuppressWarnings("unchecked") public static TenantIdAccessor getTenantIdAccessor(HttpServletRequestAccessor requestAccessor) { ServerProperties serverProperties = ServerProperties.getInstance(); String tenantIdAccessorClassName = serverProperties.getValue(TENANTIDACCESSOR_PROPERTY_NAME); TenantIdAccessor tenantIdAccessor; if (tenantIdAccessorClassName == null || tenantIdAccessorClassName.isEmpty()) { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "auth.TenantIdAccessor is undefined. Using default implementation : " + TenantIdAccessor.class.getName()); } tenantIdAccessor = new TenantIdAccessor(requestAccessor); } else { try { Constructor<TenantIdAccessor> constructor = (Constructor<TenantIdAccessor>) Class.forName(tenantIdAccessorClassName).getConstructor(HttpServletRequestAccessor.class); tenantIdAccessor = constructor.newInstance(requestAccessor); } catch (Exception e) { LOGGER.log(Level.SEVERE, "The TenantIdAccessor specified " + tenantIdAccessorClassName + " could not be instantiated! Using default implementation : " + TenantIdAccessor.class.getName(), e); tenantIdAccessor = new TenantIdAccessor(requestAccessor); } } return tenantIdAccessor; } @SuppressWarnings("unchecked") static TenantIdAccessor getTenantIdAccessor(HttpServletRequestAccessor requestAccessor); }### Answer: @Test public void should_return_TenantIdAccessor() { assertThat(TenantIdAccessorFactory.getTenantIdAccessor(requestAccessor)).isInstanceOf(TenantIdAccessor.class); }
### Question: PortalCookies { public String getTenantCookieFromRequest(HttpServletRequest request) { return getCookieValue(request, TENANT_COOKIE_NAME); } void addCSRFTokenCookieToResponse(HttpServletRequest request, HttpServletResponse res, Object apiTokenFromClient); void invalidateRootCookie(HttpServletResponse res, Cookie cookie, String path); boolean isCSRFTokenCookieSecure(); void addTenantCookieToResponse(HttpServletResponse response, Long tenantId); String getTenantCookieFromRequest(HttpServletRequest request); Cookie getCookie(HttpServletRequest request, String name); }### Answer: @Test public void should_get_tenant_cookie_from_request() throws Exception { request.setCookies(new Cookie("bonita.tenant", "123")); String tenant = portalCookies.getTenantCookieFromRequest(request); assertThat(tenant).isEqualTo("123"); }
### Question: PortalCookies { public Cookie getCookie(HttpServletRequest request, String name) { Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(name)) { return cookie; } } } return null; } void addCSRFTokenCookieToResponse(HttpServletRequest request, HttpServletResponse res, Object apiTokenFromClient); void invalidateRootCookie(HttpServletResponse res, Cookie cookie, String path); boolean isCSRFTokenCookieSecure(); void addTenantCookieToResponse(HttpServletResponse response, Long tenantId); String getTenantCookieFromRequest(HttpServletRequest request); Cookie getCookie(HttpServletRequest request, String name); }### Answer: @Test public void should_get_cookie_by_name_from_request() throws Exception { Cookie cookie = new Cookie("bonita.tenant", "123"); request.setCookies(cookie); Cookie fetchedCookie = portalCookies.getCookie(request, "bonita.tenant"); assertThat(fetchedCookie).isEqualTo(cookie); }
### Question: WidgetExpressionEntry { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } WidgetExpressionEntry other = (WidgetExpressionEntry) obj; if (entry == null) { if (other.entry != null) { return false; } } else if (!entry.equals(other.entry)) { return false; } return true; } WidgetExpressionEntry(String widgetId, ExpressionId expressionId); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testTwoWidgetExpressionEntryEqualAREEquals() { WidgetExpressionEntry widget1 = new WidgetExpressionEntry("widgetId", ExpressionId.WIDGET_DISPLAY_CONDITION); WidgetExpressionEntry widget2 = new WidgetExpressionEntry("widgetId", ExpressionId.WIDGET_DISPLAY_CONDITION); boolean result = widget1.equals(widget2); assertTrue(result); } @Test public void testWidgetExpressionEntryIsNotEqualsToNull() { WidgetExpressionEntry widget = new WidgetExpressionEntry("widgetId", ExpressionId.WIDGET_DISPLAY_CONDITION); boolean result = widget.equals(null); assertFalse(result); }
### Question: TenantFileUploadServlet extends FileUploadServlet { @Override protected void setUploadSizeMax(final ServletFileUpload serviceFileUpload, final HttpServletRequest request) { serviceFileUpload.setFileSizeMax(getConsoleProperties(getAPISession(request).getTenantId()).getMaxSize() * MEGABYTE); } }### Answer: @Test public void should_throw_fileTooBigException_when_file_is_bigger_in_than_conf_file() throws Exception { final ServletFileUpload serviceFileUpload = mock(ServletFileUpload.class); when(consoleProperties.getMaxSize()).thenReturn(1L); fileUploadServlet.setUploadSizeMax(serviceFileUpload, request); verify(serviceFileUpload).setFileSizeMax(FileUploadServlet.MEGABYTE); }
### Question: FileUploadServlet extends HttpServlet { protected String getExtension(final String fileName) { String extension = ""; final String filenameLastSegment = getFilenameLastSegment(fileName); final int dotPos = filenameLastSegment.lastIndexOf('.'); if (dotPos > -1) { extension = filenameLastSegment.substring(dotPos); } return extension; } @Override void init(); @Override @SuppressWarnings("unchecked") void doPost(final HttpServletRequest request, final HttpServletResponse response); static final String RESPONSE_SEPARATOR; static final int MEGABYTE; }### Answer: @Test public void getExtension_should_return_proper_extension() throws IOException { final String filename = "C:\\Users\\Desktop\\process.bar"; final String extension = fileUploadServlet.getExtension(filename); assertThat(extension).isEqualTo(".bar"); } @Test public void getExtension_should_return_an_empty_extension() throws IOException { final String filename = "C:\\Users\\Desktop\\process"; final String extension = fileUploadServlet.getExtension(filename); assertThat(extension).isEqualTo(""); } @Test public void getExtension_should_return_a_proper_extension_without_taking_care_of_dots() throws IOException { final String filename = "C:\\Users\\Deskt.op\\proc.ess.bar"; final String extension = fileUploadServlet.getExtension(filename); assertThat(extension).isEqualTo(".bar"); } @Test public void getExtension_should_return_proper_extension_for_short_filename() throws IOException { final String filename = "process.bar"; final String extension = fileUploadServlet.getExtension(filename); assertThat(extension).isEqualTo(".bar"); } @Test public void getExtension_should_return_proper_extension_for_linux_like_paths() throws IOException { final String filename = "/Users/Deskt.op/proc.ess.bar"; final String extension = fileUploadServlet.getExtension(filename); assertThat(extension).isEqualTo(".bar"); } @Test public void getExtension_should_return_an_empty_extension_for_parent_folder_filename() throws IOException { final String filename = "../../../"; final String extension = fileUploadServlet.getExtension(filename); assertThat(extension).isEqualTo(""); }
### Question: FileUploadServlet extends HttpServlet { protected String getFilenameLastSegment(final String fileName) { int slashPos = fileName.lastIndexOf("/"); if (slashPos == -1) { slashPos = fileName.lastIndexOf("\\"); } return fileName.substring(slashPos+1); } @Override void init(); @Override @SuppressWarnings("unchecked") void doPost(final HttpServletRequest request, final HttpServletResponse response); static final String RESPONSE_SEPARATOR; static final int MEGABYTE; }### Answer: @Test public void getFilenameLastSegment_should_return_proper_filename() { final String filename = "C:\\Users\\Desktop\\process.bar"; final String filenameLastSegment = fileUploadServlet.getFilenameLastSegment(filename); assertThat(filenameLastSegment).isEqualTo("process.bar"); } @Test public void getFilenameLastSegment_should_return_proper_filename_for_linux_paths() { final String filename = "/Users/Deskt.op/process.bar"; final String filenameLastSegment = fileUploadServlet.getFilenameLastSegment(filename); assertThat(filenameLastSegment).isEqualTo("process.bar"); } @Test public void getFilenameLastSegment_should_return_an_empty_filename_for_parent_folder_filename() throws IOException { final String filename = "../../../"; final String filenameLastSegment = fileUploadServlet.getFilenameLastSegment(filename); assertThat(filenameLastSegment).isEqualTo(""); }
### Question: UrlBuilder { public String build() { if (!parameters.isEmpty()) { uriBuilder.setParameters(parameters); } return uriBuilder.toString(); } UrlBuilder(final String urlString); void appendParameter(final String key, final String... values); void appendParameters(final Map<String, String[]> parameters); String build(); }### Answer: @Test public void should_leave_path_unchanged() throws Exception { urlBuilder = new UrlBuilder("http: assertThat(urlBuilder.build()).isEqualTo("http: } @Test public void should_leave_path_unchanged2() throws Exception { urlBuilder = new UrlBuilder("http: assertThat(urlBuilder.build()).isEqualTo("http: } @Test public void should_leave_path_with_space_unchanged() throws Exception { urlBuilder = new UrlBuilder("http: assertThat(urlBuilder.build()).isEqualTo("http: } @Test public void should_leave_URL_without_querystring_unchanged() throws Exception { urlBuilder = new UrlBuilder("http: assertThat(urlBuilder.build()).isEqualTo("http: }
### Question: ContractTypeConverter { public ContractDefinition getAdaptedContractDefinition(final ContractDefinition contract) { final List<ConstraintDefinition> constraints = contract.getConstraints(); final List<InputDefinition> inputDefinitions = adaptContractInputList(contract.getInputs()); final ContractDefinitionImpl contractDefinition = getContractDefinition(constraints, inputDefinitions); return contractDefinition; } ContractTypeConverter(final String[] datePatterns); Map<String, Serializable> getProcessedInput(final ContractDefinition processContract, final Map<String, Serializable> inputs, final long maxSizeForTenant, final long tenantId); void deleteTemporaryFiles(Map<String, Serializable> inputs, long tenantId); ContractDefinition getAdaptedContractDefinition(final ContractDefinition contract); static final String[] ISO_8601_DATE_PATTERNS; }### Answer: @Test public void getAdaptedContractDefinition_should_return_a_converter_contract() throws IOException { final ContractDefinitionImpl processContract = new ContractDefinitionImpl(); final List<InputDefinition> inputDefinitions = new ArrayList<>(); inputDefinitions.add(new InputDefinitionImpl(InputDefinition.FILE_INPUT_FILENAME, Type.TEXT, "Name of the file", false)); inputDefinitions.add(new InputDefinitionImpl(InputDefinition.FILE_INPUT_CONTENT, Type.BYTE_ARRAY, "Content of the file", false)); processContract.addInput(new InputDefinitionImpl("inputFile", "this is a input file", false, Type.FILE, inputDefinitions)); final ContractDefinition adaptedContractDefinition = contractTypeConverter.getAdaptedContractDefinition(processContract); final InputDefinition tempPathFileInputDefinition = adaptedContractDefinition.getInputs().get(0).getInputs().get(1); assertThat(tempPathFileInputDefinition.getType()).isEqualTo(Type.TEXT); assertThat(tempPathFileInputDefinition.getName()).isEqualTo(ContractTypeConverter.FILE_TEMP_PATH); assertThat(tempPathFileInputDefinition.getDescription()).isEqualTo(ContractTypeConverter.TEMP_PATH_DESCRIPTION); }
### Question: AuthenticationManagerFactory { public static AuthenticationManager getAuthenticationManager(final long tenantId) throws AuthenticationManagerNotFoundException { String authenticationManagerName = null; if (!map.containsKey(tenantId)) { try { authenticationManagerName = getManagerImplementationClassName(tenantId); final AuthenticationManager authenticationManager = (AuthenticationManager) Class.forName(authenticationManagerName).newInstance(); map.put(tenantId, authenticationManager); } catch (final Exception e) { final String message = "The AuthenticationManager implementation " + authenticationManagerName + " does not exist!"; throw new AuthenticationManagerNotFoundException(message); } } return map.get(tenantId); } static AuthenticationManager getAuthenticationManager(final long tenantId); }### Answer: @Test public void testGetLoginManager() throws AuthenticationManagerNotFoundException { assertNotNull("Cannot get the login manager", AuthenticationManagerFactory.getAuthenticationManager(0L)); }
### Question: PageResourceProviderImpl implements PageResourceProvider { @Override public File getPageDirectory() { return pageDirectory; } PageResourceProviderImpl(final String pageName, final long tenantId); PageResourceProviderImpl(final Page page, final long tenantId); private PageResourceProviderImpl(final String pageName, final long tenantId, final Long pageId, final Long processDefinitionId); @Override InputStream getResourceAsStream(final String resourceName); @Override File getResourceAsFile(final String resourceName); @Override String getResourceURL(final String resourceName); @Override String getBonitaThemeCSSURL(); @Override File getPageDirectory(); File getTempPageFile(); void setResourceClassLoader(final ClassLoader resourceClassLoader); @Override ResourceBundle getResourceBundle(final String name, final Locale locale); @Override String getPageName(); @Override Page getPage(final PageAPI pageAPI); @Override String getFullPageName(); }### Answer: @Test public void should_pagedirectory_be_distinct() throws Exception { assertThat(pageResourceProvider.getPageDirectory()).as("should be distinct").isNotEqualTo(pageResourceProviderWithProcessDefinition.getPageDirectory()); }
### Question: PageResourceProviderImpl implements PageResourceProvider { public File getTempPageFile() { return pageTempFile; } PageResourceProviderImpl(final String pageName, final long tenantId); PageResourceProviderImpl(final Page page, final long tenantId); private PageResourceProviderImpl(final String pageName, final long tenantId, final Long pageId, final Long processDefinitionId); @Override InputStream getResourceAsStream(final String resourceName); @Override File getResourceAsFile(final String resourceName); @Override String getResourceURL(final String resourceName); @Override String getBonitaThemeCSSURL(); @Override File getPageDirectory(); File getTempPageFile(); void setResourceClassLoader(final ClassLoader resourceClassLoader); @Override ResourceBundle getResourceBundle(final String name, final Locale locale); @Override String getPageName(); @Override Page getPage(final PageAPI pageAPI); @Override String getFullPageName(); }### Answer: @Test public void should_temp_page_file_be_distinct() throws Exception { assertThat(pageResourceProvider.getTempPageFile()).as("should be page name").isNotEqualTo(pageResourceProviderWithProcessDefinition.getTempPageFile()); }
### Question: PageResourceProviderImpl implements PageResourceProvider { @Override public String getFullPageName() { return fullPageName; } PageResourceProviderImpl(final String pageName, final long tenantId); PageResourceProviderImpl(final Page page, final long tenantId); private PageResourceProviderImpl(final String pageName, final long tenantId, final Long pageId, final Long processDefinitionId); @Override InputStream getResourceAsStream(final String resourceName); @Override File getResourceAsFile(final String resourceName); @Override String getResourceURL(final String resourceName); @Override String getBonitaThemeCSSURL(); @Override File getPageDirectory(); File getTempPageFile(); void setResourceClassLoader(final ClassLoader resourceClassLoader); @Override ResourceBundle getResourceBundle(final String name, final Locale locale); @Override String getPageName(); @Override Page getPage(final PageAPI pageAPI); @Override String getFullPageName(); }### Answer: @Test public void should_testGetFullPageName_return_unique_key() throws Exception { assertThat(pageResourceProvider.getFullPageName()).as("should be page name").isEqualTo(PAGE_NAME); assertThat(pageResourceProvider.getFullPageName()).as("should be page name").isNotEqualTo(pageResourceProviderWithProcessDefinition.getFullPageName()); }
### Question: PageResourceProviderImpl implements PageResourceProvider { @Override public Page getPage(final PageAPI pageAPI) throws PageNotFoundException { if (pageId != null) { return pageAPI.getPage(pageId); } return pageAPI.getPageByName(getPageName()); } PageResourceProviderImpl(final String pageName, final long tenantId); PageResourceProviderImpl(final Page page, final long tenantId); private PageResourceProviderImpl(final String pageName, final long tenantId, final Long pageId, final Long processDefinitionId); @Override InputStream getResourceAsStream(final String resourceName); @Override File getResourceAsFile(final String resourceName); @Override String getResourceURL(final String resourceName); @Override String getBonitaThemeCSSURL(); @Override File getPageDirectory(); File getTempPageFile(); void setResourceClassLoader(final ClassLoader resourceClassLoader); @Override ResourceBundle getResourceBundle(final String name, final Locale locale); @Override String getPageName(); @Override Page getPage(final PageAPI pageAPI); @Override String getFullPageName(); }### Answer: @Test public void should_getPage_by_name() throws Exception { pageResourceProvider.getPage(pageApi); verify(pageApi).getPageByName(PAGE_NAME); } @Test public void should_getPage_by_id() throws Exception { pageResourceProviderWithProcessDefinition.getPage(pageApi); verify(pageApi,never()).getPageByName(anyString()); verify(pageApi).getPage(PAGE_ID); }
### Question: PageContextHelper { public String getCurrentProfile() { return request.getParameter(PROFILE_PARAM); } PageContextHelper(HttpServletRequest request); String getCurrentProfile(); Locale getCurrentLocale(); APISession getApiSession(); static final String PROFILE_PARAM; static final String ATTRIBUTE_API_SESSION; }### Answer: @Test public void should_return_CurrentProfile() throws Exception { doReturn(MY_PROFILE).when(request).getParameter(PageContextHelper.PROFILE_PARAM); pageContextHelper = new PageContextHelper(request); final String currentProfile = pageContextHelper.getCurrentProfile(); assertThat(currentProfile).isEqualTo(MY_PROFILE); }
### Question: PageContextHelper { public Locale getCurrentLocale() { return LocaleUtils.getUserLocale(request); } PageContextHelper(HttpServletRequest request); String getCurrentProfile(); Locale getCurrentLocale(); APISession getApiSession(); static final String PROFILE_PARAM; static final String ATTRIBUTE_API_SESSION; }### Answer: @Test public void should_getCurrentLocale_return_request_parameter() throws Exception { doReturn(locale.toString()).when(request).getParameter(LocaleUtils.LOCALE_PARAM); pageContextHelper = new PageContextHelper(request); final Locale returnedLocale = pageContextHelper.getCurrentLocale(); assertThat(returnedLocale).isEqualToComparingFieldByField(locale); } @Test public void should_getCurrentLocale_return_cookie_locale() throws Exception { Cookie[] cookieList = new Cookie[1]; cookieList[0] = new Cookie(LocaleUtils.LOCALE_COOKIE_NAME, locale.getLanguage()); doReturn(null).when(request).getParameter(LocaleUtils.LOCALE_PARAM); doReturn(cookieList).when(request).getCookies(); pageContextHelper = new PageContextHelper(request); final Locale returnedLocale = pageContextHelper.getCurrentLocale(); assertThat(returnedLocale).isEqualToComparingFieldByField(locale); } @Test public void should_getCurrentLocale_return_default_locale() throws Exception { Cookie[] cookieList = new Cookie[1]; cookieList[0] = new Cookie("otherCookie", "otherValue"); doReturn(null).when(request).getParameter(LocaleUtils.LOCALE_PARAM); doReturn(cookieList).when(request).getCookies(); pageContextHelper = new PageContextHelper(request); final Locale returnedLocale = pageContextHelper.getCurrentLocale(); assertThat(returnedLocale.toString()).isEqualTo(LocaleUtils.DEFAULT_LOCALE); }
### Question: PageContextHelper { public APISession getApiSession() { final HttpSession httpSession = request.getSession(); return (APISession) httpSession.getAttribute(ATTRIBUTE_API_SESSION); } PageContextHelper(HttpServletRequest request); String getCurrentProfile(); Locale getCurrentLocale(); APISession getApiSession(); static final String PROFILE_PARAM; static final String ATTRIBUTE_API_SESSION; }### Answer: @Test public void should_return_ApiSession() throws Exception { doReturn(httpSession).when(request).getSession(); doReturn(apiSession).when(httpSession).getAttribute(pageContextHelper.ATTRIBUTE_API_SESSION); pageContextHelper = new PageContextHelper(request); final APISession returnedApiSession = pageContextHelper.getApiSession(); assertThat(returnedApiSession).isEqualTo(apiSession); }
### Question: CustomPageDependenciesResolver { public File getTempFolder() { if (libTempFolder == null) { throw new IllegalStateException("Custom page dependencies must be resolved first."); } return libTempFolder; } CustomPageDependenciesResolver(final String pageName, final File pageDirectory, final WebBonitaConstantsUtils webBonitaConstantsUtils); Map<String, byte[]> resolveCustomPageDependencies(); static File removePageLibTempFolder(final String pageName); File getTempFolder(); }### Answer: @Test public void should_throw_an_IllegalStateException_when_accessing_tmp_folder_before_resolving_libraries() throws Exception { final CustomPageDependenciesResolver resolver = newCustomPageDependenciesResolver(null); expectedException.expect(IllegalStateException.class); resolver.getTempFolder(); }
### Question: CustomPageDependenciesResolver { public Map<String, byte[]> resolveCustomPageDependencies() { final File customPageLibDirectory = new File(pageDirectory, LIB_FOLDER_NAME); if (customPageLibDirectory.exists()) { this.libTempFolder = new File(this.webBonitaConstantsUtils.getTempFolder(), pageName + Long.toString(new Date().getTime())); if (!this.libTempFolder.exists()) { this.libTempFolder.mkdirs(); } removePageLibTempFolder(pageName); PAGES_LIB_TMPDIR.put(pageName, this.libTempFolder); return loadLibraries(customPageLibDirectory); } return Collections.emptyMap(); } CustomPageDependenciesResolver(final String pageName, final File pageDirectory, final WebBonitaConstantsUtils webBonitaConstantsUtils); Map<String, byte[]> resolveCustomPageDependencies(); static File removePageLibTempFolder(final String pageName); File getTempFolder(); }### Answer: @Test public void should_resolve_dependencies_return_an_empty_map_if_no_lib_folder_is_found_in_custom_page() throws Exception { final CustomPageDependenciesResolver resolver = newCustomPageDependenciesResolver(null); final Map<String, byte[]> dependenciesContent = resolver.resolveCustomPageDependencies(); assertThat(dependenciesContent).isEmpty(); }
### Question: ResourceRenderer { public List<String> getPathSegments(final String pathInfo) throws UnsupportedEncodingException { final List<String> segments = new ArrayList<>(); if (pathInfo != null) { for (final String segment : pathInfo.split("/")) { if (!segment.isEmpty()) { segments.add(URLDecoder.decode(segment, "UTF-8")); } } } return segments; } void renderFile(final HttpServletRequest request, final HttpServletResponse response, final File resourceFile, final APISession apiSession); List<String> getPathSegments(final String pathInfo); }### Answer: @Test public void getPathSegments_should_return_expected_token_list() throws UnsupportedEncodingException { when(req.getPathInfo()).thenReturn("a/b"); final List<String> tokens = resourceRenderer.getPathSegments("a/b"); assertThat(tokens).hasSize(2).containsExactly("a", "b"); } @Test public void getPathSegments_should_return_expected_token_list_ondouble_slash() throws UnsupportedEncodingException { when(req.getPathInfo()).thenReturn("a final List<String> tokens = resourceRenderer.getPathSegments("a assertThat(tokens).hasSize(2).containsExactly("a", "b"); } @Test public void getPathSegments_should_return_expected_token_list_if_no_slash() throws UnsupportedEncodingException { when(req.getPathInfo()).thenReturn("a"); final List<String> tokens = resourceRenderer.getPathSegments("a"); assertThat(tokens).hasSize(1).containsExactly("a"); }
### Question: PageRenderer { public PageResourceProviderImpl getPageResourceProvider(final String pageName, final long tenantId) { return new PageResourceProviderImpl(pageName, tenantId); } PageRenderer(final ResourceRenderer resourceRenderer); void displayCustomPage(final HttpServletRequest request, final HttpServletResponse response, final APISession apiSession, final String pageName); void displayCustomPage(final HttpServletRequest request, final HttpServletResponse response, final APISession apiSession, final String pageName, final Locale currentLocale); void displayCustomPage(final HttpServletRequest request, final HttpServletResponse response, final APISession apiSession, final long pageId); void displayCustomPage(final HttpServletRequest request, final HttpServletResponse response, final APISession apiSession, final long pageId, final Locale currentLocale); void ensurePageFolderIsPresent(final APISession apiSession, final PageResourceProviderImpl pageResourceProvider); String getCurrentProfile(final HttpServletRequest request); Locale getCurrentLocale(final HttpServletRequest request); PageResourceProviderImpl getPageResourceProvider(final String pageName, final long tenantId); PageResourceProviderImpl getPageResourceProvider(final long pageId, final APISession apiSession); static final String PROFILE_PARAM; static final String LOCALE_PARAM; static final String DEFAULT_LOCALE; static final String LOCALE_COOKIE_NAME; }### Answer: @Test public void should_get_pageResourceProvider_by_pageId() throws Exception { final String pageName = "pageName"; doReturn(pageName).when(page).getName(); doReturn(page).when(customPageService).getPage(apiSession, 42L); final PageResourceProviderImpl pageResourceProvider = pageRenderer.getPageResourceProvider(42L, apiSession); assertThat(pageResourceProvider.getPageName()).isEqualTo(pageName); } @Test public void should_get_pageResourceProvider_by_pageName() throws Exception { final String pageName = "pageName"; doReturn(pageName).when(page).getName(); final PageResourceProviderImpl pageResourceProvider = pageRenderer.getPageResourceProvider(pageName,1L); assertThat(pageResourceProvider.getPageName()).isEqualTo(pageName); }
### Question: ConsoleServiceFactory implements ServiceFactory { @Override public Service getService(final String calledToolToken) { if (OrganizationImportService.TOKEN.equals(calledToolToken)) { return new OrganizationImportService(); } else if (ProcessActorImportService.TOKEN.equals(calledToolToken)) { return new ProcessActorImportService(); } else if (ApplicationsImportService.TOKEN.equals(calledToolToken)) { return new ApplicationsImportService(); } throw new ServiceNotFoundException(calledToolToken); } @Override Service getService(final String calledToolToken); }### Answer: @Test public void getService_should_return_OrganizationImportService_when_organization_import() throws Exception { ConsoleServiceFactory consoleServiceFacotry = new ConsoleServiceFactory(); Service service = consoleServiceFacotry.getService("/organization/import"); assertThat(service).isInstanceOf(OrganizationImportService.class); } @Test public void getService_should_return_ProcessActorImportService_when_bpm_process_importActors() throws Exception { ConsoleServiceFactory consoleServiceFacotry = new ConsoleServiceFactory(); Service service = consoleServiceFacotry.getService("/bpm/process/importActors"); assertThat(service).isInstanceOf(ProcessActorImportService.class); } @Test(expected=ServiceNotFoundException.class) public void getService_should_throw_ServiceNotFoundException_when_invalid_input(){ ConsoleServiceFactory consoleServiceFacotry = new ConsoleServiceFactory(); consoleServiceFacotry.getService("invalidService"); }
### Question: ApplicationsImportService extends BonitaImportService { @Override public ImportStatusMessages importFileContent(final byte[] fileContent, final String importPolicyAsString) throws ExecutionException, ImportException, AlreadyExistsException, InvalidSessionException, BonitaHomeNotSetException, ServerAPIException, UnknownAPITypeException { final ApplicationImportPolicy importPolicy = ApplicationImportPolicy.valueOf(importPolicyAsString); final List<ImportStatus> ImportStatusList = getApplicationAPI().importApplications(fileContent, importPolicy); return new ImportStatusMessages(ImportStatusList); } @Override String getToken(); @Override String getFileUploadParamName(); @Override ImportStatusMessages importFileContent(final byte[] fileContent, final String importPolicyAsString); final static String TOKEN; static final String FILE_UPLOAD; }### Answer: @Test public void should_importFileContent_call_ApplicationAPI_with_valid_param() throws Exception { spiedApplicationImportService.importFileContent(new byte[0], "FAIL_ON_DUPLICATES"); verify(applicationAPI).importApplications(new byte[0], ApplicationImportPolicy.FAIL_ON_DUPLICATES); } @Test public void should_importFileContent_return_ImportStatusMessages() throws Exception { final ArrayList<ImportStatus> statusList = new ArrayList<ImportStatus>(); statusList.add(new ImportStatus("status")); doReturn(statusList).when(applicationAPI).importApplications(new byte[0], ApplicationImportPolicy.FAIL_ON_DUPLICATES); final ImportStatusMessages importStatusMessages = spiedApplicationImportService.importFileContent(new byte[0], "FAIL_ON_DUPLICATES"); assertEquals(importStatusMessages.getImported().size(), 1); } @Test(expected = IllegalArgumentException.class) public void should_importFileContent_with_invalid_policy_throw_error() throws Exception { spiedApplicationImportService.importFileContent(new byte[0], "NOT_AUTHORIZED_POLICY"); }
### Question: ApplicationsImportService extends BonitaImportService { @Override protected Logger getLogger() { return LOGGER; } @Override String getToken(); @Override String getFileUploadParamName(); @Override ImportStatusMessages importFileContent(final byte[] fileContent, final String importPolicyAsString); final static String TOKEN; static final String FILE_UPLOAD; }### Answer: @Test public void should_Logger_log_using_expected_class_name() throws Exception { assertEquals(spiedApplicationImportService.getLogger().getName(), "org.bonitasoft.console.server.service.ApplicationsImportService"); }
### Question: ApplicationsImportService extends BonitaImportService { @Override protected String getFileReadingError() { return _("Error during Application import file reading."); } @Override String getToken(); @Override String getFileUploadParamName(); @Override ImportStatusMessages importFileContent(final byte[] fileContent, final String importPolicyAsString); final static String TOKEN; static final String FILE_UPLOAD; }### Answer: @Test public void should_FileReadingError_talk_about_application() throws Exception { assertEquals(spiedApplicationImportService.getFileReadingError(), "Error during Application import file reading."); }
### Question: ApplicationsImportService extends BonitaImportService { @Override protected String getFileFormatExceptionMessage() { return _("Can't import Applications.", getLocale()); } @Override String getToken(); @Override String getFileUploadParamName(); @Override ImportStatusMessages importFileContent(final byte[] fileContent, final String importPolicyAsString); final static String TOKEN; static final String FILE_UPLOAD; }### Answer: @Test public void should_getFileFormatExceptionMessage_talk_about_application() throws Exception { assertEquals(spiedApplicationImportService.getFileFormatExceptionMessage(), "Can't import Applications."); }
### Question: ApplicationsImportService extends BonitaImportService { @Override protected String getAlreadyExistsExceptionMessage(final AlreadyExistsException e) { return _("Can't import applications. An application '%token%' already exists", getLocale(), new Arg("token", e.getName())); } @Override String getToken(); @Override String getFileUploadParamName(); @Override ImportStatusMessages importFileContent(final byte[] fileContent, final String importPolicyAsString); final static String TOKEN; static final String FILE_UPLOAD; }### Answer: @Test public void should_AlreadyExistsExceptionMessage_talk_about_application() throws Exception { final AlreadyExistsException alreadyExistsException = new AlreadyExistsException("name", "token"); assertEquals(spiedApplicationImportService.getAlreadyExistsExceptionMessage(alreadyExistsException), "Can't import applications. An application 'token' already exists"); }
### Question: ApplicationsImportService extends BonitaImportService { @Override public String getToken() { return TOKEN; } @Override String getToken(); @Override String getFileUploadParamName(); @Override ImportStatusMessages importFileContent(final byte[] fileContent, final String importPolicyAsString); final static String TOKEN; static final String FILE_UPLOAD; }### Answer: @Test public void should_getToken_return_expected_name() throws Exception { assertEquals(spiedApplicationImportService.getToken(), "/application/import"); }
### Question: ApplicationsImportService extends BonitaImportService { @Override public String getFileUploadParamName() { return FILE_UPLOAD; } @Override String getToken(); @Override String getFileUploadParamName(); @Override ImportStatusMessages importFileContent(final byte[] fileContent, final String importPolicyAsString); final static String TOKEN; static final String FILE_UPLOAD; }### Answer: @Test public void should_getFileUploadParamName_return_expected_name() throws Exception { assertEquals(spiedApplicationImportService.getFileUploadParamName(), "applicationsDataUpload"); }
### Question: ApplicationsExportServlet extends ExportByIdsServlet { @Override protected byte[] exportResources(final long[] ids, final APISession apiSession) throws BonitaHomeNotSetException, ServerAPIException, UnknownAPITypeException, ExecutionException, ExportException { final ApplicationAPI applicationAPI = getApplicationAPI(apiSession); return applicationAPI.exportApplications(ids); } }### Answer: @Test public void should_call_engine_export_with_the_good_id() throws Exception { spiedApplicationsExportServlet.exportResources(new long[] { 1 }, session); verify(applicationAPI, times(1)).exportApplications(new long[] { 1 }); }
### Question: ApplicationsExportServlet extends ExportByIdsServlet { @Override protected Logger getLogger() { return LOGGER; } }### Answer: @Test public void should_logger_log_with_name_of_the_Servlet() throws Exception { assertThat(spiedApplicationsExportServlet.getLogger().getName()).isEqualTo("org.bonitasoft.console.server.servlet.ApplicationsExportServlet"); }
### Question: ApplicationsExportServlet extends ExportByIdsServlet { @Override protected String getFileExportName() { return EXPORT_FILE_NAME; } }### Answer: @Test public void should_getFileExportName_return_a_valide_file_name() throws Exception { assertThat(spiedApplicationsExportServlet.getFileExportName()).isEqualTo("applicationDescriptorFile.xml"); }
### Question: BonitaExportServlet extends HttpServlet { @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { OutputStream out = null; try { final byte[] resourceBytes = exportResources(request); setResponseHeaders(request, response); out = response.getOutputStream(); out.write(resourceBytes); out.flush(); } catch (final InvalidSessionException e) { String message = "Session expired. Please log in again."; if (getLogger().isLoggable(Level.FINE)) { getLogger().log(Level.FINE, message, e); } response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message); } catch (final FileNotFoundException e) { String message = "There is no BDM Access control installed."; if (getLogger().isLoggable(Level.INFO)) { getLogger().log(Level.INFO, message); } response.sendError(HttpServletResponse.SC_NOT_FOUND, message); } catch (final Exception e) { if (getLogger().isLoggable(Level.SEVERE)) { getLogger().log(Level.SEVERE, e.getMessage(), e); } throw new ServletException(e.getMessage(), e); } finally { try { if (out != null) { out.close(); } } catch (final IOException e) { getLogger().log(Level.SEVERE, e.getMessage(), e); } } } }### Answer: @Test(expected = ServletException.class) public void should_do_get_without_session_return_servlet_exception() throws Exception { given(hsRequest.getSession()).willReturn(httpSession); given(httpSession.getAttribute("apiSession")).willReturn(null); spiedApplicationsExportServlet.doGet(hsRequest, hsResponse); }
### Question: MenuFactory { public List<Menu> create(final List<ApplicationMenu> menuList) throws ApplicationPageNotFoundException, SearchException { return collect(menuList, new RootMenuCollector()); } MenuFactory(final ApplicationAPI applicationApi); List<Menu> create(final List<ApplicationMenu> menuList); }### Answer: @Test public void should_create_a_MenuLink_with_the_page_token_it_is_pointing_at_when_menu_is_a_link() throws Exception { MenuFactory factory = new MenuFactory(applicationApi); assertThat(factory.create(asList((ApplicationMenu) aMenuLink)).get(0).getHtml()) .isEqualTo("<li><a href=\"token\">link</a></li>"); } @Test public void should_create_an_empty_MenuContainer() throws Exception { MenuFactory factory = new MenuFactory(applicationApi); assertThat(factory.create(asList((ApplicationMenu) aMenuContainer)).get(0).getHtml()) .isEqualTo(new StringBuilder() .append("<li class=\"dropdown\"><a href=\"#\" class=\"dropdown-toggle\" data-toggle=\"dropdown\">container <span class=\"caret\"></span></a>") .append("<ul class=\"dropdown-menu\" role=\"menu\">") .append("</ul></li>").toString()); } @Test public void should_create_a_MenuContainer_containing_a_MenuLink() throws Exception { MenuFactory factory = new MenuFactory(applicationApi); assertThat(factory.create(asList((ApplicationMenu) aMenuContainer, aNestedMenuLink)).get(0).getHtml()) .isEqualTo(new StringBuilder() .append("<li class=\"dropdown\"><a href=\"#\" class=\"dropdown-toggle\" data-toggle=\"dropdown\">container <span class=\"caret\"></span></a>") .append("<ul class=\"dropdown-menu\" role=\"menu\">") .append("<li><a href=\"token\">nested-link</a></li>") .append("</ul></li>").toString()); }
### Question: RootMenuCollector implements Collector { @Override public boolean isCollectible(final ApplicationMenu menu) { return menu.getParentId() == null; } @Override boolean isCollectible(final ApplicationMenu menu); }### Answer: @Test public void should_be_collectible_when_the_menu_has_no_parentId() { menu.setParentId(null); assertThat(collector.isCollectible(menu)).isTrue(); } @Test public void should_not_be_collectible_when_the_menu_has_a_parentId() { menu.setParentId(3L); assertThat(collector.isCollectible(menu)).isFalse(); }
### Question: ChildrenMenuCollector implements Collector { @Override public boolean isCollectible(final ApplicationMenu menu) { return parentId.equals(menu.getParentId()); } ChildrenMenuCollector(final Long parentId); @Override boolean isCollectible(final ApplicationMenu menu); }### Answer: @Test public void should_be_collectible_when_menu_parentId_is_the_given_parentId() { menu.setParentId(1L); assertThat(collector.isCollectible(menu)).isTrue(); } @Test public void should_not_be_collectible_when_menu_parentId_is_not_the_given_parentId() { menu.setParentId(2L); assertThat(collector.isCollectible(menu)).isFalse(); } @Test public void should_not_be_collectible_when_menu_parentId_is_null() { menu.setParentId(null); assertThat(collector.isCollectible(menu)).isFalse(); }
### Question: ApplicationModel { public List<Menu> getMenuList() throws SearchException, ApplicationPageNotFoundException { return factory.create(applicationApi.searchApplicationMenus(new SearchOptionsBuilder(0, Integer.MAX_VALUE) .filter(ApplicationMenuSearchDescriptor.APPLICATION_ID, application.getId()) .sort(ApplicationMenuSearchDescriptor.INDEX, Order.ASC).done()) .getResult()); } ApplicationModel( final ApplicationAPI applicationApi, final PageAPI pageApi, final ProfileAPI profileApi, final Application application, final MenuFactory factory); long getId(); String getApplicationLayoutName(); String getApplicationThemeName(); Long getApplicationThemeId(); String getApplicationHomePage(); boolean hasPage(final String pageToken); boolean authorize(final APISession session); boolean hasProfileMapped(); Page getCustomPage(final String pageToken); List<Menu> getMenuList(); }### Answer: @Test public void should_sort_application_menu_search() throws Exception { givenSearchApplicationMenusWillReturns(Collections.<ApplicationMenu> emptyList()); model.getMenuList(); final ArgumentCaptor<SearchOptions> captor = ArgumentCaptor.forClass(SearchOptions.class); verify(applicationApi).searchApplicationMenus(captor.capture()); final Sort sort = captor.getValue().getSorts().get(0); assertThat(sort.getField()).isEqualTo(ApplicationMenuSearchDescriptor.INDEX); assertThat(sort.getOrder()).isEqualTo(Order.ASC); } @Test public void should_create_menu_using_menuList() throws Exception { final List<ApplicationMenu> menuList = Arrays.<ApplicationMenu> asList(new ApplicationMenuImpl("name", 1L, 2L, 1)); givenSearchApplicationMenusWillReturns(menuList); model.getMenuList(); verify(factory).create(menuList); }
### Question: ApplicationModel { public boolean authorize(final APISession session) { for (final Profile userProfile : getUserProfiles(session)) { if (userProfile.getId() == application.getProfileId()) { return true; } } return false; } ApplicationModel( final ApplicationAPI applicationApi, final PageAPI pageApi, final ProfileAPI profileApi, final Application application, final MenuFactory factory); long getId(); String getApplicationLayoutName(); String getApplicationThemeName(); Long getApplicationThemeId(); String getApplicationHomePage(); boolean hasPage(final String pageToken); boolean authorize(final APISession session); boolean hasProfileMapped(); Page getCustomPage(final String pageToken); List<Menu> getMenuList(); }### Answer: @Test public void should_authorize_a_user_with_the_configured_application_profile() throws Exception { final ProfileImpl profile1 = new ProfileImpl("user"); profile1.setId(1L); final ProfileImpl profile2 = new ProfileImpl("administrator"); profile1.setId(2L); given(profileApi.getProfilesForUser(1L, 0, Integer.MAX_VALUE, ProfileCriterion.ID_ASC)) .willReturn(asList((Profile) profile1, profile2)); given(session.getUserId()).willReturn(1L); application.setProfileId(2L); assertThat(model.authorize(session)).isTrue(); } @Test public void should_not_authorize_a_user_without_the_configured_application_profile() throws Exception { final ProfileImpl profile1 = new ProfileImpl("user"); profile1.setId(1L); final ProfileImpl profile2 = new ProfileImpl("administrator"); profile1.setId(2L); given(profileApi.getProfilesForUser(1L, 0, Integer.MAX_VALUE, ProfileCriterion.ID_ASC)) .willReturn(asList((Profile) profile1, profile2)); given(session.getUserId()).willReturn(1L); application.setProfileId(3L); assertThat(model.authorize(session)).isFalse(); }
### Question: ApplicationModel { public long getId() { return application.getId(); } ApplicationModel( final ApplicationAPI applicationApi, final PageAPI pageApi, final ProfileAPI profileApi, final Application application, final MenuFactory factory); long getId(); String getApplicationLayoutName(); String getApplicationThemeName(); Long getApplicationThemeId(); String getApplicationHomePage(); boolean hasPage(final String pageToken); boolean authorize(final APISession session); boolean hasProfileMapped(); Page getCustomPage(final String pageToken); List<Menu> getMenuList(); }### Answer: @Test public void should_getId_return_applicationId() throws Exception { assertThat(model.getId()).isEqualTo(1L); }
### Question: ApplicationModel { public String getApplicationHomePage() throws ApplicationPageNotFoundException { return applicationApi.getApplicationHomePage(application.getId()).getToken() + "/"; } ApplicationModel( final ApplicationAPI applicationApi, final PageAPI pageApi, final ProfileAPI profileApi, final Application application, final MenuFactory factory); long getId(); String getApplicationLayoutName(); String getApplicationThemeName(); Long getApplicationThemeId(); String getApplicationHomePage(); boolean hasPage(final String pageToken); boolean authorize(final APISession session); boolean hasProfileMapped(); Page getCustomPage(final String pageToken); List<Menu> getMenuList(); }### Answer: @Test public void should_ApplicationHomePage_return_valide_path() throws Exception { given(applicationApi.getApplicationHomePage(1L)).willReturn(new ApplicationPageImpl(1, 1, "pageToken")); assertThat(model.getApplicationHomePage()).isEqualTo("pageToken/"); }
### Question: ApplicationModel { public String getApplicationLayoutName() throws PageNotFoundException { return pageApi.getPage(application.getLayoutId()).getName(); } ApplicationModel( final ApplicationAPI applicationApi, final PageAPI pageApi, final ProfileAPI profileApi, final Application application, final MenuFactory factory); long getId(); String getApplicationLayoutName(); String getApplicationThemeName(); Long getApplicationThemeId(); String getApplicationHomePage(); boolean hasPage(final String pageToken); boolean authorize(final APISession session); boolean hasProfileMapped(); Page getCustomPage(final String pageToken); List<Menu> getMenuList(); }### Answer: @Test public void should_getApplicationLayoutName_return_valide_name() throws Exception { given(page.getName()).willReturn("layoutPage"); given(pageApi.getPage(1L)).willReturn(page); String appLayoutName = model.getApplicationLayoutName(); assertThat(appLayoutName).isEqualTo("layoutPage"); }
### Question: ApplicationModel { public String getApplicationThemeName() throws PageNotFoundException { return pageApi.getPage(application.getThemeId()).getName(); } ApplicationModel( final ApplicationAPI applicationApi, final PageAPI pageApi, final ProfileAPI profileApi, final Application application, final MenuFactory factory); long getId(); String getApplicationLayoutName(); String getApplicationThemeName(); Long getApplicationThemeId(); String getApplicationHomePage(); boolean hasPage(final String pageToken); boolean authorize(final APISession session); boolean hasProfileMapped(); Page getCustomPage(final String pageToken); List<Menu> getMenuList(); }### Answer: @Test public void should_getApplicationThemeName_return_valide_name() throws Exception { given(page.getName()).willReturn("themePage"); given(pageApi.getPage(2L)).willReturn(page); String appLayoutName = model.getApplicationThemeName(); assertThat(appLayoutName).isEqualTo("themePage"); }
### Question: ApplicationModel { public boolean hasPage(final String pageToken) { try { applicationApi.getApplicationPage(application.getToken(), pageToken); return true; } catch (final ApplicationPageNotFoundException e) { return false; } } ApplicationModel( final ApplicationAPI applicationApi, final PageAPI pageApi, final ProfileAPI profileApi, final Application application, final MenuFactory factory); long getId(); String getApplicationLayoutName(); String getApplicationThemeName(); Long getApplicationThemeId(); String getApplicationHomePage(); boolean hasPage(final String pageToken); boolean authorize(final APISession session); boolean hasProfileMapped(); Page getCustomPage(final String pageToken); List<Menu> getMenuList(); }### Answer: @Test public void should_hasPage_return_true() throws Exception { given(applicationApi.getApplicationPage("token", "pageToken")).willReturn(new ApplicationPageImpl(1, 1, "pageToken")); assertThat(model.hasPage("pageToken")).isEqualTo(true); } @Test public void should_hasPage_return_false() throws Exception { given(applicationApi.getApplicationPage("token", "pageToken")).willThrow(new ApplicationPageNotFoundException("")); assertThat(model.hasPage("pageToken")).isEqualTo(false); }
### Question: ApplicationModel { public boolean hasProfileMapped() { return application.getProfileId() != null; } ApplicationModel( final ApplicationAPI applicationApi, final PageAPI pageApi, final ProfileAPI profileApi, final Application application, final MenuFactory factory); long getId(); String getApplicationLayoutName(); String getApplicationThemeName(); Long getApplicationThemeId(); String getApplicationHomePage(); boolean hasPage(final String pageToken); boolean authorize(final APISession session); boolean hasProfileMapped(); Page getCustomPage(final String pageToken); List<Menu> getMenuList(); }### Answer: @Test public void should_check_that_application_has_a_profile_mapped_to_it() throws Exception { application.setProfileId(1L); assertThat(model.hasProfileMapped()).isEqualTo(true); application.setProfileId(null); assertThat(model.hasProfileMapped()).isEqualTo(false); }
### Question: CacheUtil { public static void store(final String diskStorePath, final String cacheName, final Object key, final Object value) { final CacheManager cacheManager = getCacheManager(diskStorePath); Cache cache = cacheManager.getCache(cacheName); if (cache == null) { cache = createCache(cacheManager, cacheName); } final Element element = new Element(key, value); cache.put(element); if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "####Element " + key + " created in cache with name " + cacheName); } } static void store(final String diskStorePath, final String cacheName, final Object key, final Object value); static Object get(final String diskStorePath, final String cacheName, final Object key); static void clear(final String diskStorePath, final String cacheName); }### Answer: @Test public void testStore() { CacheUtil.store(cacheManager.getConfiguration().getDiskStoreConfiguration().getPath(), cacheManager.getName(), new String("testStoreKey"), new String("testStoreValue")); assertNotNull("Cannot store", cacheManager.getCache(cacheManager.getName())); }
### Question: FinderFactory { public Serializable getContextResultElement(final Serializable object) { final ResourceFinder resourceFinderFor = getResourceFinderFor(object); if (resourceFinderFor != null) { return resourceFinderFor.toClientObject(object); } return object; } FinderFactory(); FinderFactory(final Map<Class<? extends ServerResource>, ResourceFinder> finders); Finder create(final Class<? extends ServerResource> clazz); Finder createExtensionResource(); ResourceFinder getResourceFinderFor(final Serializable object); Serializable getContextResultElement(final Serializable object); }### Answer: @Test public void should_getResourceFinderFor_return_result_of_first_handler(){ final FinderFactory finderFactory = new FinderFactory(Collections.<Class<? extends ServerResource>,ResourceFinder>singletonMap(null, new ResourceFinder() { @Override public Serializable toClientObject(final Serializable object) { return "resultA"; } @Override public boolean handlesResource(final Serializable object) { return object.equals("objectA"); } })); final Serializable objectA = finderFactory.getContextResultElement("objectA"); assertThat(objectA).isEqualTo("resultA"); } @Test public void should_getResourceFinderFor_return_the_object_if_no_handler(){ final FinderFactory finderFactory = new FinderFactory(Collections.<Class<? extends ServerResource>,ResourceFinder>singletonMap(null, new ResourceFinder() { @Override public Serializable toClientObject(final Serializable object) { return "resultA"; } @Override public boolean handlesResource(final Serializable object) { return object.equals("objectB"); } })); final Serializable objectA = finderFactory.getContextResultElement("objectA"); assertThat(objectA).isEqualTo("objectA"); }
### Question: CacheUtil { public static Object get(final String diskStorePath, final String cacheName, final Object key) { Object value = null; final CacheManager cacheManager = getCacheManager(diskStorePath); final Cache cache = cacheManager.getCache(cacheName); if (cache != null) { final Element element = cache.get(key); if (element != null) { value = element.getValue(); if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "####Element " + key + " found in cache with name " + cacheName); } } else { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "####Element " + key + " not found in cache with name " + cacheName); } } } else { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "####Cache with name " + cacheName + " doesn't exists or wasn't created yet."); } } return value; } static void store(final String diskStorePath, final String cacheName, final Object key, final Object value); static Object get(final String diskStorePath, final String cacheName, final Object key); static void clear(final String diskStorePath, final String cacheName); }### Answer: @Test public void testGet() { CacheUtil.store(cacheManager.getConfiguration().getDiskStoreConfiguration().getPath(), cacheManager.getName(), new String("testStoreKey"), new String("testStoreValue")); assertNotNull("Cannot get the element in the cache", CacheUtil.get(cacheManager.getConfiguration().getDiskStoreConfiguration().getPath(), cacheManager.getName(), "testStoreKey")); }
### Question: CacheUtil { public static void clear(final String diskStorePath, final String cacheName) { final CacheManager cacheManager = getCacheManager(diskStorePath); final Cache cache = cacheManager.getCache(cacheName); if (cache != null) { cache.removeAll(); } } static void store(final String diskStorePath, final String cacheName, final Object key, final Object value); static Object get(final String diskStorePath, final String cacheName, final Object key); static void clear(final String diskStorePath, final String cacheName); }### Answer: @Test public void testClear() { CacheUtil.clear(cacheManager.getConfiguration().getDiskStoreConfiguration().getPath(), cacheManager.getName()); assertNull("Cannot clear the cache", CacheUtil.get(cacheManager.getName(), cacheManager.getConfiguration().getDiskStoreConfiguration().getPath(), "testStoreKey")); }
### Question: Field { @Override public String toString() { return field; } Field(String attribute, AttributeConverter convert); Field(String attribute); @Override String toString(); }### Answer: @Test public void testFieldConvertion() { Mockito.doReturn("converted").when(converter).convert("attribute"); Field field = new Field("attribute", converter); String s = field.toString(); Assert.assertEquals("converted", s); }