method2testcases
stringlengths 118
6.63k
|
---|
### Question:
Condition implements Internal<Condition<S, T>, T> { public Logger<Condition<S, T>, T> log(Object tag) { return new Logger<>(this, sourceProxy.getConfiguration(), tag); } private Condition(S source, Predicate<T> predicate, boolean negateExpression); S then(Consumer<T> action); S invoke(Action action); Optional<R> thenMap(Function<T, R> mapper); Optional<R> thenTo(@NonNull R item); Optional<R> thenTo(@NonNull Callable<R> itemCallable); Logger<Condition<S, T>, T> log(Object tag); @Override Proxy<Condition<S, T>, T> access(); }### Answer:
@Test public void logWithSelfAsSourceThenReturnSelfAsSource() { Condition<?,?> source = Chain.let(0).when(new Predicate<Integer>() { @Override public boolean test(Integer integer) throws Exception { return false; } }); Logger<?, ?> logger = source.log("1"); assertEquals(source, logger.source); }
@Test public void logWithStringTagThenReturnLoggerWithThatTag() { Condition<?,?> source = Chain.let(0).when(new Predicate<Integer>() { @Override public boolean test(Integer integer) throws Exception { return false; } }); Logger<?, ?> logger = source.log("1"); assertEquals("1", logger.tag); } |
### Question:
Collector implements
Internal<Collector<T>, List<T>>,
And<T>,
Monad<List<T>>,
Functor<T> { @Override public Collector<T> and(T item) { if (item != null) { items.add(item); } return copy(); } Collector(InternalConfiguration configuration); @Override Collector<T> and(T item); Chain<List<T>> toList(); @Override R flatMap(@NonNull Function<List<T>, R> flatMapper); Collector<T> forEach(@NonNull Consumer<T> action); Collector<R> map(Function<T, R> mapper); Chain<T> reduce(BiFunction<T, T, T> reducer); Logger<Collector<T>, List<T>> log(Object tag); @Override Proxy<Collector<T>, List<T>> access(); }### Answer:
@Test public void andWithMultipleItemsThenAppendAllToTheList() { Collector<Boolean> result = new Collector<Boolean>(configuration) .and(true) .and(false) .and(true); assertTrue(result.items.get(0) && !result.items.get(1) && result.items.get(2)); }
@Test public void runCollectorProxyTester() { Collector<Integer> collector = new Collector<>(InternalConfiguration.getInstance("runCollectorProxyTester")); collector.and(1).and(2).and(3); new ProxyTester<>(collector, Arrays.asList(4, 5, 6)).run(); } |
### Question:
Collector implements
Internal<Collector<T>, List<T>>,
And<T>,
Monad<List<T>>,
Functor<T> { public Logger<Collector<T>, List<T>> log(Object tag) { return new Logger<>(this, configuration, tag); } Collector(InternalConfiguration configuration); @Override Collector<T> and(T item); Chain<List<T>> toList(); @Override R flatMap(@NonNull Function<List<T>, R> flatMapper); Collector<T> forEach(@NonNull Consumer<T> action); Collector<R> map(Function<T, R> mapper); Chain<T> reduce(BiFunction<T, T, T> reducer); Logger<Collector<T>, List<T>> log(Object tag); @Override Proxy<Collector<T>, List<T>> access(); }### Answer:
@Test public void logWithSelfAsSourceThenReturnSelfAsSource() { Collector<?> source = Chain.let(0).collect(Integer.class); Logger<?, ?> logger = source.log("1"); assertEquals(source, logger.source); }
@Test public void logWithStringTagThenReturnLoggerWithThatTag() { Collector<?> source = Chain.let(0).collect(Integer.class); Logger<?, ?> logger = source.log("1"); assertEquals("1", logger.tag); } |
### Question:
Guard implements Internal<Guard<S, T>, T> { public static <T> Guard<Chain<T>, T> call(@NonNull Callable<T> callable) { return new Guard<>(new Chain<T>(null, InternalConfiguration.getInstance(null)).access(), callable); } private Guard(Proxy<S, T> proxy, Exception error); Guard(Proxy<S, T> proxy, Callable<T> callable); static Guard<Chain<T>, T> call(@NonNull Callable<T> callable); S onErrorReturnItem(@NonNull T item); Guard<S, T> guard(final @NonNull Function<T, T> action); Guard<S, T> apply(Consumer<T> action); S onErrorReturn(@NonNull Function<Throwable, T> function); void onError(Consumer<Exception> consumer); Logger<Guard<S, T>, T> log(Object tag); Optional<R> onErrorMapItem(R mappedItem); @Override Proxy<Guard<S, T>, T> access(); Optional<R> onErrorMap(Function<Throwable, R> mapperFunction); }### Answer:
@Test public void callWithSetTextOnTestClassThenFindTextValueUpdated() { final TestClass[] result = {new TestClass()}; Guard.call(new Callable<TestClass>() { @Override public TestClass call() throws Exception { result[0].text = "!"; return result[0]; } }); assertEquals("!", result[0].text); }
@Test public void callWithExceptionThenDoNotThrowException() { Guard.call(new Callable<TestClass>() { @Override public TestClass call() throws Exception { throw new UnsupportedOperationException(); } }); }
@Test public void runGuardProxyTester() { Guard<?, Integer> guard = Guard.call(new Callable<Integer>() { @Override public Integer call() throws Exception { return 0; } }); new ProxyTester<>(guard, 1).run(); } |
### Question:
IsEqualComparator implements BiPredicate<T, T> { @Override public boolean test(T leftItem, T rightItem) { return (leftItem == null && rightItem == null) || (leftItem != null && leftItem.equals(rightItem)); } @Override boolean test(T leftItem, T rightItem); }### Answer:
@Test public void testWithNullFirstParameterAndNonNullSecondParameterThenReturnFalse() { assertFalse(new IsEqualComparator<Integer>().test(null, 0)); }
@Test public void testWithNonNullFirstParameterAndNullSecondParameterThenReturnFalse() { assertFalse(new IsEqualComparator<Integer>().test(0, null)); }
@Test public void testWithNullFirstParameterAndNullSecondParameterThenReturnTrue() { assertTrue(new IsEqualComparator<Integer>().test(null, null)); }
@Test public void testWithNonEqualParametersThenReturnFalse() { assertFalse(new IsEqualComparator<Integer>().test(1, 0)); }
@Test public void testWithEqualParametersThenReturnTrue() { assertTrue(new IsEqualComparator<Integer>().test(0, 0)); } |
### Question:
Optional implements
Conditional<Optional<T>, T>,
Internal<Optional<T>, T>,
Function<Consumer<T>, Optional<T>>,
DefaultIfEmpty<T>,
Functor<T> { public Optional<T> debug(Consumer<T> action) { if (chain.configuration.isDebugging() && chain.item != null) { Invoker.invoke(action, chain.item); } return new Optional<>(chain.item, chain.configuration); } Optional(T item, InternalConfiguration configuration); @Override Chain<T> defaultIfEmpty(@NonNull T defaultValue); Optional<T> apply(Consumer<T> action); Optional<T> invoke(Action action); Optional<R> map(Function<T, R> mapper); Maybe<R> flatMapMaybe(Function<T, R> flatMapper); Optional<R> to(@NonNull R item); Optional<R> to(@NonNull Callable<R> itemCallable); Maybe<T> toMaybe(); Logger<Optional<T>, T> log(Object tag); Optional<T> debug(Consumer<T> action); Condition<Optional<T>, T> when(Predicate<T> predicate); Condition<Optional<T>, T> whenNot(Predicate<T> predicate); Condition<Optional<T>, T> whenIn(Collection<T> collection); Condition<Optional<T>, T> whenIn(Collection<T> collection, BiPredicate<T, T> comparator); Condition<Optional<T>, T> whenNotIn(Collection<T> collection); Condition<Optional<T>, T> whenNotIn(Collection<T> collection, BiPredicate<T, T> comparator); @NonNull T callOrCrash(); @NonNull T callOrCrash(String crashMessage); @Override Proxy<Optional<T>, T> access(); }### Answer:
@Test public void debugWhileChainConfigIsDebuggingThenInvokeDebug() { InternalConfiguration config = InternalConfiguration .getInstance("debugWhileChainConfigIsDebuggingThenInvokeDebug"); config.setDebugging(true); final boolean[] result = {false}; new Optional<>(new TestClass(), config) .debug(new Consumer<TestClass>() { @Override public void accept(@NonNull TestClass testClass) throws Exception { result[0] = true; } }); assertTrue(result[0]); }
@Test public void debugWhileChainConfigIsNotDebuggingThenDoNotInvokeDebug() { InternalConfiguration config = InternalConfiguration .getInstance("debugWhileChainConfigIsNotDebuggingThenDoNotInvokeDebug"); config.setDebugging(false); final boolean[] result = {false}; new Optional<>(new TestClass(), config) .debug(new Consumer<TestClass>() { @Override public void accept(@NonNull TestClass testClass) throws Exception { result[0] = true; } }); assertFalse(result[0]); } |
### Question:
Lazy implements Callable<T>, Monad<T>, Functor<T>, Function<Consumer<T>, Lazy<T>> { public static <T, P> Lazy<T> defer(Function<P, T> delayedInitializer, P parameter) { return new Lazy<>(Curry.toCallable(delayedInitializer, parameter)); } Lazy(Callable<T> delayedAction); static Lazy<T> defer(Function<P, T> delayedInitializer, P parameter); @Override R flatMap(Function<T, R> flatMapper); @Override T call(); Lazy<R> map(final Function<T, R> mapper); static Lazy<T> defer(Callable<T> delayedInitializer); @Override Lazy<T> apply(final Consumer<T> lazyAction); }### Answer:
@Test public void deferWithCallableThenAssignCallableVariableOnly() { Lazy<Boolean> lazyBoolean = Lazy.defer(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return true; } }); assertTrue(lazyBoolean.delayedAction != null && lazyBoolean.item == null); } |
### Question:
InOperator implements Predicate<T> { @Override public boolean test(T item) { return item != null && !collection.isEmpty() && new Chain<>(collection, configuration) .apply(removeNulls()) .flatMap(toObservableFromIterable()) .any(hasComparatorTestPassed(item)) .blockingGet(); } InOperator(Collection<T> collection,
BiPredicate<T, T> comparator,
InternalConfiguration configuration); @Override boolean test(T item); }### Answer:
@Test public void testWithValidCollectionAndValidItemThenReturnTrue() { Collection<Integer> collection = Arrays.asList(1, 2, 3, 4); InternalConfiguration config = getInstance("testWithValidCollectionAndValidItemThenReturnTrue"); assertTrue(new InOperator<>(collection, new IsEqualComparator<Integer>(), config).test(2)); }
@Test public void testWithValidCollectionAndInvalidItemThenReturnFalse() { Collection<Integer> collection = Arrays.asList(1, 2, 3, 4); InternalConfiguration config = getInstance("testWithValidCollectionAndInvalidItemThenReturnFalse"); assertFalse(new InOperator<>(collection, new IsEqualComparator<Integer>(), config).test(5)); }
@Test public void testWithValidCollectionAndNullItemThenReturnFalse() { Collection<Integer> collection = Arrays.asList(1, 2, 3, 4); InternalConfiguration config = getInstance("testWithValidCollectionAndNullItemThenReturnFalse"); assertFalse(new InOperator<>(collection, new IsEqualComparator<Integer>(), config).test(null)); }
@Test public void testWithNullCollectionAndValidItemThenReturnFalse() { InternalConfiguration config = getInstance("testWithNullCollectionAndValidItemThenReturnFalse"); assertFalse(new InOperator<>(null, new IsEqualComparator<Integer>(), config).test(2)); } |
### Question:
Chain implements
Conditional<Chain<T>, T>,
Internal<Chain<T>, T>,
Callable<T>,
Function<Consumer<T>, Chain<T>>,
DefaultIfEmpty<T>,
And<T>,
Monad<T>,
Functor<T> { public static <T> Chain<T> call(@NonNull Callable<T> callable) { return new Chain<>(Invoker.invoke(callable), InternalConfiguration.getInstance(null)); } Chain(T item, InternalConfiguration configuration); static Optional<T> optional(@Nullable T item); static Chain<T> let(@NonNull T item); static Chain<T> call(@NonNull Callable<T> callable); Guard<Chain<R>, R> guardMap(Function<T, R> guardMapper); @Override Proxy<Chain<T>, T> access(); Guard<Chain<T>, T> guard(Consumer<T> action); Condition<Chain<T>, T> when(Predicate<T> predicate); Condition<Chain<T>, T> whenNot(Predicate<T> predicate); Condition<Chain<T>, T> whenEmpty(); Condition<Chain<T>, T> whenNotEmpty(); @Deprecated Chain<Pair<T, Boolean>> in(Collection<T> collection); @Deprecated Chain<Pair<T, Boolean>> in(Collection<T> collection, BiPredicate<T, T> comparator); Condition<Chain<T>, T> whenIn(Collection<T> collection); Condition<Chain<T>, T> whenIn(Collection<T> collection, BiPredicate<T, T> comparator); Condition<Chain<T>, T> whenNotIn(Collection<T> collection); Condition<Chain<T>, T> whenNotIn(Collection<T> collection, BiPredicate<T, T> comparator); @Override R flatMap(@NonNull Function<T, R> flatMapper); Chain<T> apply(Consumer<T> action); Chain<T> invoke(Action action); Chain<R> map(@NonNull Function<T, R> mapper); Chain<R> to(@NonNull R item); Chain<R> to(@NonNull Callable<R> itemCallable); @Override T call(); @Override Chain<T> defaultIfEmpty(@NonNull T defaultValue); Chain<T> debug(Consumer<T> action); @Override Collector<T> and(T item); Chain<Pair<T, R>> pair(R item); Chain<Pair<T, R>> pair(Function<T, R> pairedItemMapper); @SuppressWarnings("unchecked") Collector<R> collect(Class<R> type); Logger<Chain<T>, T> log(Object tag); Lazy<T> lazyApply(final Consumer<T> lazyAction); Lazy<R> lazyMap(final Function<T, R> lazyMapper); }### Answer:
@Test public void callWithCallableThenReturnTheCallableResult() { TestClass testClass = Chain.call(new Callable<TestClass>() { @Override public TestClass call() throws Exception { return new TestClass("!"); } }).call(); assertEquals("!", testClass.text); }
@Test(expected = UnsupportedOperationException.class) public void callWithCrashingCallableThenThrowException() { Chain.call(new Callable<TestClassTwo>() { @Override public TestClassTwo call() throws Exception { throw new UnsupportedOperationException(); } }); }
@Test public void callWithValidCallableThenReturnTheValueOfCall() { TestClass testClass = Guard .call(new Callable<TestClass>() { @Override public TestClass call() throws Exception { return new TestClass("!"); } }) .onErrorReturnItem(new TestClass("!!")) .call(); assertEquals("!", testClass.text); }
@Test public void callWithCrashingCallableThenReturnTheValueOfOnErrorReturnItem() { TestClass testClass = Guard .call(new Callable<TestClass>() { @Override public TestClass call() throws Exception { throw new UnsupportedOperationException(); } }) .onErrorReturnItem(new TestClass("!!")) .call(); assertEquals("!!", testClass.text); } |
### Question:
Chain implements
Conditional<Chain<T>, T>,
Internal<Chain<T>, T>,
Callable<T>,
Function<Consumer<T>, Chain<T>>,
DefaultIfEmpty<T>,
And<T>,
Monad<T>,
Functor<T> { public Chain<T> debug(Consumer<T> action) { if (configuration.isDebugging()) { Invoker.invoke(action, item); } return new Chain<>(item, configuration); } Chain(T item, InternalConfiguration configuration); static Optional<T> optional(@Nullable T item); static Chain<T> let(@NonNull T item); static Chain<T> call(@NonNull Callable<T> callable); Guard<Chain<R>, R> guardMap(Function<T, R> guardMapper); @Override Proxy<Chain<T>, T> access(); Guard<Chain<T>, T> guard(Consumer<T> action); Condition<Chain<T>, T> when(Predicate<T> predicate); Condition<Chain<T>, T> whenNot(Predicate<T> predicate); Condition<Chain<T>, T> whenEmpty(); Condition<Chain<T>, T> whenNotEmpty(); @Deprecated Chain<Pair<T, Boolean>> in(Collection<T> collection); @Deprecated Chain<Pair<T, Boolean>> in(Collection<T> collection, BiPredicate<T, T> comparator); Condition<Chain<T>, T> whenIn(Collection<T> collection); Condition<Chain<T>, T> whenIn(Collection<T> collection, BiPredicate<T, T> comparator); Condition<Chain<T>, T> whenNotIn(Collection<T> collection); Condition<Chain<T>, T> whenNotIn(Collection<T> collection, BiPredicate<T, T> comparator); @Override R flatMap(@NonNull Function<T, R> flatMapper); Chain<T> apply(Consumer<T> action); Chain<T> invoke(Action action); Chain<R> map(@NonNull Function<T, R> mapper); Chain<R> to(@NonNull R item); Chain<R> to(@NonNull Callable<R> itemCallable); @Override T call(); @Override Chain<T> defaultIfEmpty(@NonNull T defaultValue); Chain<T> debug(Consumer<T> action); @Override Collector<T> and(T item); Chain<Pair<T, R>> pair(R item); Chain<Pair<T, R>> pair(Function<T, R> pairedItemMapper); @SuppressWarnings("unchecked") Collector<R> collect(Class<R> type); Logger<Chain<T>, T> log(Object tag); Lazy<T> lazyApply(final Consumer<T> lazyAction); Lazy<R> lazyMap(final Function<T, R> lazyMapper); }### Answer:
@Test public void debugWhileChainConfigIsDebuggingThenInvokeDebug() { InternalConfiguration config = InternalConfiguration .getInstance("debugWhileChainConfigIsDebuggingThenInvokeDebug"); config.setDebugging(true); final boolean[] result = {false}; new Chain<>(new TestClass(), config) .debug(new Consumer<TestClass>() { @Override public void accept(@NonNull TestClass testClass) throws Exception { result[0] = true; } }); assertTrue(result[0]); }
@Test public void debugWhileChainConfigIsNotDebuggingThenDoNotInvokeDebug() { InternalConfiguration config = InternalConfiguration .getInstance("debugWhileChainConfigIsNotDebuggingThenDoNotInvokeDebug"); config.setDebugging(false); final boolean[] result = {false}; new Chain<>(new TestClass(), config) .debug(new Consumer<TestClass>() { @Override public void accept(@NonNull TestClass testClass) throws Exception { result[0] = true; } }); assertFalse(result[0]); } |
### Question:
RootContext { public boolean isRooted() { return root.getState() == Root.State.ROOTED; } RootContext(Root root, SuBinary suBinary, SuApp suApp, SELinux seLinux, ContextSwitch contextSwitch); boolean isRooted(); Root getRoot(); SuBinary getSuBinary(); SuApp getSuApp(); SELinux getSELinux(); ContextSwitch getContextSwitch(); @Override String toString(); static final RootContext EMPTY; }### Answer:
@Test public void testRoot() { final Root root = mock(Root.class); final SuBinary binary = mock(SuBinary.class); final SuApp app = mock(SuApp.class); final SELinux seLinux = mock(SELinux.class); final RootContext.ContextSwitch contextSwitch = mock(RootContext.ContextSwitch.class); final RootContext rootContext = new RootContext(root, binary, app, seLinux, contextSwitch); when(root.getState()).thenReturn(Root.State.ROOTED); assertThat(rootContext.isRooted(), is(true)); when(root.getState()).thenReturn(Root.State.DENIED); assertThat(rootContext.isRooted(), is(false)); } |
### Question:
SuBinary { @NonNull public Type getType() { return type; } SuBinary(Type type, @Nullable String path, @Nullable String version, @Nullable String extra, List<String> raw); @NonNull Type getType(); @Nullable String getPath(); String getExtra(); @Nullable String getVersion(); List<String> getRaw(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testCall_normal() { when(session.submit(any(Cmd.class))).thenAnswer(invocation -> Single.just(new Cmd.Result(invocation.getArgument(0), Cmd.ExitCode.OK))); final SuBinary suBinary = new SuBinary.Builder().session(session).build().blockingGet(); assertThat(suBinary.getType(), is(SuBinary.Type.UNKNOWN)); }
@Test public void testCall_fallback() { when(session.submit(any(Cmd.class))).thenAnswer(invocation -> { Cmd cmd = invocation.getArgument(0); if (cmd.getCommands().size() == 1) { return Single.just(new Cmd.Result(invocation.getArgument(0), Cmd.ExitCode.PROBLEM)); } else { return Single.just(new Cmd.Result(invocation.getArgument(0), Cmd.ExitCode.OK)); } }); final SuBinary suBinary = new SuBinary.Builder().session(session).build().blockingGet(); assertThat(suBinary.getType(), is(SuBinary.Type.UNKNOWN)); } |
### Question:
SuBinary { @Override public int hashCode() { int result = type.hashCode(); result = 31 * result + (path != null ? path.hashCode() : 0); result = 31 * result + (extra != null ? extra.hashCode() : 0); result = 31 * result + (version != null ? version.hashCode() : 0); result = 31 * result + (raw != null ? raw.hashCode() : 0); return result; } SuBinary(Type type, @Nullable String path, @Nullable String version, @Nullable String extra, List<String> raw); @NonNull Type getType(); @Nullable String getPath(); String getExtra(); @Nullable String getVersion(); List<String> getRaw(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testEqualsHash() { SuBinary binary1 = new SuBinary(SuBinary.Type.SE_SUPERUSER, "/su/bin/su", "16", "me.phh.superuser cm-su", new ArrayList<>()); SuBinary binary2 = new SuBinary(SuBinary.Type.SE_SUPERUSER, "/su/bin/su", "16", "me.phh.superuser cm-su", new ArrayList<>()); SuBinary binary3 = new SuBinary(SuBinary.Type.UNKNOWN, null, null, null, null); assertThat(binary1, is(binary2)); assertThat(binary2, is(not(binary3))); assertThat(binary1.hashCode(), is(binary2.hashCode())); assertThat(binary2.hashCode(), is(not(binary3.hashCode()))); } |
### Question:
LineReader { @SuppressLint("NewApi") public static String getLineSeparator() { if (ApiWrap.hasKitKat()) return System.lineSeparator(); else return System.getProperty("line.separator", "\n"); } LineReader(); LineReader(String lineSeparator); @SuppressLint("NewApi") static String getLineSeparator(); String readLine(Reader reader); }### Answer:
@Test public void testGetLineSeperator() { assertThat(LineReader.getLineSeparator(), is(notNullValue())); ApiWrap.setSDKInt(26); assertThat(LineReader.getLineSeparator(), is(System.lineSeparator())); ApiWrap.setSDKInt(16); assertThat(LineReader.getLineSeparator(), is(System.getProperty("line.separator", "\n"))); } |
### Question:
LineReader { public String readLine(Reader reader) throws IOException { char curChar; int val; StringBuilder sb = new StringBuilder(40); while ((val = reader.read()) != -1) { curChar = (char) val; if (curChar == '\n' && lineSeparator.length == 1 && curChar == lineSeparator[0]) { return sb.toString(); } else if (curChar == '\r' && lineSeparator.length == 1 && curChar == lineSeparator[0]) { return sb.toString(); } else if (curChar == '\n' && lineSeparator.length == 2 && curChar == lineSeparator[1]) { if (sb.length() > 0 && sb.charAt(sb.length() - 1) == lineSeparator[0]) { sb.deleteCharAt(sb.length() - 1); return sb.toString(); } } sb.append(curChar); } if (sb.length() == 0) return null; return sb.toString(); } LineReader(); LineReader(String lineSeparator); @SuppressLint("NewApi") static String getLineSeparator(); String readLine(Reader reader); }### Answer:
@Test public void testLineEndings_linux() throws IOException { final List<String> output = new ArrayList<>(); final LineReader reader = new LineReader("\n"); Reader stream = new BufferedReader(new InputStreamReader(makeStream("line1\r\nline2\r\nli\rne\n\n"))); String line; while ((line = reader.readLine(stream)) != null) { output.add(line); } assertThat(output.size(), is(4)); assertThat(output.get(0), is("line1\r")); assertThat(output.get(1), is("line2\r")); assertThat(output.get(2), is("li\rne")); assertThat(output.get(3), is("")); }
@Test public void testLineEndings_windows() throws IOException { final List<String> output = new ArrayList<>(); final LineReader reader = new LineReader("\r\n"); Reader stream = new BufferedReader(new InputStreamReader(makeStream("line1\r\nline2\r\n\r\n"))); String line; while ((line = reader.readLine(stream)) != null) { output.add(line); } assertThat(output.size(), is(3)); assertThat(output.get(0), is("line1")); assertThat(output.get(1), is("line2")); assertThat(output.get(2), is("")); }
@Test public void testLineEndings_legacy() throws IOException { final List<String> output = new ArrayList<>(); final LineReader reader = new LineReader("\r"); Reader stream = new BufferedReader(new InputStreamReader(makeStream("line1\n\rline2\n\rli\nne\r\r"))); String line; while ((line = reader.readLine(stream)) != null) { output.add(line); } assertThat(output.size(), is(4)); assertThat(output.get(0), is("line1\n")); assertThat(output.get(1), is("line2\n")); assertThat(output.get(2), is("li\nne")); assertThat(output.get(3), is("")); } |
### Question:
RxShell { public synchronized Single<Session> open() { if (RXSDebug.isDebug()) Timber.tag(TAG).v("open()"); if (session == null) { session = rxProcess.open() .map(session -> { OutputStreamWriter writer = new OutputStreamWriter(session.input(), StandardCharsets.UTF_8); return new Session(session, writer); }) .subscribeOn(Schedulers.io()) .doOnSuccess(s -> { if (RXSDebug.isDebug()) Timber.tag(TAG).v("open():doOnSuccess %s", s); s.waitFor().subscribe(integer -> { synchronized (RxShell.this) { session = null; } }, e -> Timber.tag(TAG).w(e, "Error resetting session.")); }) .doOnError(t -> { if (RXSDebug.isDebug()) Timber.tag(TAG).v(t, "open():doOnError");}) .cache(); } return session; } RxShell(RxProcess rxProcess); synchronized Single<Session> open(); synchronized Single<Boolean> isAlive(); synchronized Completable cancel(); synchronized Single<Integer> close(); }### Answer:
@Test public void testOpen_error() throws IOException { doReturn(Single.error(new InterruptedException())).when(rxProcess).open(); RxShell rxShell = new RxShell(rxProcess); TestObserver<RxShell.Session> sessionObs = rxShell.open().test(); sessionObs.awaitDone(1, TimeUnit.SECONDS).assertError(InterruptedException.class); sessionObs.assertNoValues(); }
@Test public void testWaitFor() throws InterruptedException { RxShell rxShell = new RxShell(rxProcess); RxShell.Session session = rxShell.open().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().values().get(0); assertThat(session.waitFor().test().await(1, TimeUnit.SECONDS), is(false)); waitForEmitter.onSuccess(55); session.waitFor().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().assertValue(55); } |
### Question:
RxShell { public synchronized Single<Boolean> isAlive() { if (RXSDebug.isDebug()) Timber.tag(TAG).v("isAlive()"); if (session == null) return Single.just(false); else return session.flatMap(Session::isAlive); } RxShell(RxProcess rxProcess); synchronized Single<Session> open(); synchronized Single<Boolean> isAlive(); synchronized Completable cancel(); synchronized Single<Integer> close(); }### Answer:
@Test public void testIsAlive() { RxShell rxShell = new RxShell(rxProcess); RxShell.Session session = rxShell.open().test().awaitCount(1).assertNoErrors().values().get(0); session.isAlive().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().assertValue(true); when(rxProcessSession.isAlive()).thenReturn(Single.just(false)); session.isAlive().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().assertValue(false); when(rxProcessSession.isAlive()).thenReturn(Single.just(true)); session.isAlive().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().assertValue(true); verify(rxProcessSession, times(3)).isAlive(); } |
### Question:
RootContext { public ContextSwitch getContextSwitch() { return contextSwitch; } RootContext(Root root, SuBinary suBinary, SuApp suApp, SELinux seLinux, ContextSwitch contextSwitch); boolean isRooted(); Root getRoot(); SuBinary getSuBinary(); SuApp getSuApp(); SELinux getSELinux(); ContextSwitch getContextSwitch(); @Override String toString(); static final RootContext EMPTY; }### Answer:
@Test public void testContextSwitching_superSu() { when(suBinaryBuilder.build()).thenReturn(Single.just(new SuBinary(SuBinary.Type.CHAINFIRE_SUPERSU, null, null, null, new ArrayList<>()))); RootContext.Builder builder = new RootContext.Builder(context); builder.rootBuilder(rootBuilder); builder.seLinuxBuilder(seLinuxBuilder); builder.suAppBuilder(suAppBuilder); builder.suBinaryBuilder(suBinaryBuilder); builder.shellBuilder(shellBuilder); final RootContext rootContext = builder.build().blockingGet(); final String switchCommand = rootContext.getContextSwitch().switchContext("acontext", "somecommand"); assertThat(switchCommand, containsString("'somecommand'")); assertThat(switchCommand, containsString("--context acontext")); assertThat(switchCommand, is("su --context acontext -c 'somecommand' < /dev/null")); } |
### Question:
RxShell { public synchronized Completable cancel() { if (RXSDebug.isDebug()) Timber.tag(TAG).v("cancel()"); if (session == null) return Completable.complete(); else return session.flatMapCompletable(Session::cancel); } RxShell(RxProcess rxProcess); synchronized Single<Session> open(); synchronized Single<Boolean> isAlive(); synchronized Completable cancel(); synchronized Single<Integer> close(); }### Answer:
@Test public void testCancel() { RxShell rxShell = new RxShell(rxProcess); RxShell.Session session = rxShell.open().test().awaitCount(1).assertNoErrors().values().get(0); session.isAlive().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().assertValue(true); session.cancel().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().assertComplete(); session.isAlive().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().assertValue(false); session.cancel().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().assertComplete(); verify(rxProcessSession).destroy(); } |
### Question:
RxShell { public synchronized Single<Integer> close() { if (RXSDebug.isDebug()) Timber.tag(TAG).v("close()"); if (session == null) return Single.just(0); else return session.flatMap(Session::close); } RxShell(RxProcess rxProcess); synchronized Single<Session> open(); synchronized Single<Boolean> isAlive(); synchronized Completable cancel(); synchronized Single<Integer> close(); }### Answer:
@Test public void testClose() throws IOException { RxShell rxShell = new RxShell(rxProcess); RxShell.Session session = rxShell.open().test().awaitDone(10, TimeUnit.SECONDS).assertNoErrors().values().get(0); session.close().test().awaitDone(10, TimeUnit.SECONDS).assertNoErrors().assertValue(0); await().atMost(2, TimeUnit.SECONDS).until(() -> cmdStream.getData().toString().contains("exit" + LineReader.getLineSeparator())); await().atMost(1, TimeUnit.SECONDS).until(() -> cmdStream.isOpen(), is(false)); session.close().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().assertValue(0); } |
### Question:
RxCmdShell { public synchronized Single<Session> open() { if (RXSDebug.isDebug()) Timber.tag(TAG).v("open()"); if (session == null) { session = Single .create((SingleOnSubscribe<Session>) emitter -> rxShell.open().subscribe(new SingleObserver<RxShell.Session>() { @Override public void onSubscribe(Disposable d) { } @Override public void onSuccess(RxShell.Session shellSession) { try { final Iterator<Map.Entry<String, String>> envIterator = environment.entrySet().iterator(); while (envIterator.hasNext()) { final Map.Entry<String, String> entry = envIterator.next(); shellSession.writeLine(entry.getKey() + "=" + entry.getValue(), !envIterator.hasNext()); } } catch (IOException e) { emitter.tryOnError(e); return; } CmdProcessor cmdProcessor = processorFactory.create(); cmdProcessor.attach(shellSession); final Session cmdShellSession = new Session(shellSession, cmdProcessor); emitter.onSuccess(cmdShellSession); } @Override public void onError(Throwable e) { Timber.tag(TAG).w("Failed to open RxShell session!"); synchronized (RxCmdShell.this) { session = null; } emitter.tryOnError(e); } })) .subscribeOn(Schedulers.io()) .doOnSuccess(s -> { if (RXSDebug.isDebug()) Timber.tag(TAG).v("open():doOnSuccess %s", s); s.waitFor().subscribe(integer -> { synchronized (RxCmdShell.this) { session = null; } }, e -> Timber.tag(TAG).w(e, "Error resetting session.")); }) .doOnError(t -> {if (RXSDebug.isDebug()) Timber.tag(TAG).v(t, "open():doOnError");}) .cache(); } return session; } @SuppressWarnings("unused") private RxCmdShell(); RxCmdShell(Builder builder, RxShell rxShell); synchronized Single<Session> open(); Single<Boolean> isAlive(); synchronized Completable cancel(); synchronized Single<Integer> close(); static Builder builder(); }### Answer:
@Test public void testOpen() { RxCmdShell rxCmdShell = new RxCmdShell(builder, rxShell); rxCmdShell.open().test().awaitCount(1).assertNoErrors(); verify(rxShell).open(); }
@Test public void testOpen_exception() { doReturn(Single.error(new IOException())).when(rxShell).open(); RxCmdShell rxCmdShell = new RxCmdShell(builder, rxShell); rxCmdShell.open().test().awaitDone(1, TimeUnit.SECONDS).assertError(IOException.class); verify(rxShell).open(); verify(rxShellSession, never()).outputLines(); verify(rxShellSession, never()).errorLines(); }
@Test public void testReinit_exception() { RxCmdShell shell = new RxCmdShell(builder, rxShell); doReturn(Single.error(new IOException())).when(rxShell).open(); shell.open().test().awaitDone(1, TimeUnit.SECONDS).assertError(IOException.class); doReturn(Single.just(rxShellSession)).when(rxShell).open(); shell.open().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().assertValueCount(1); }
@Test public void testEnvironmentSetting() throws IOException { final HashMap<String, String> envMap = new HashMap<>(); envMap.put("key", "value"); when(builder.getEnvironment()).thenReturn(envMap); RxCmdShell shell = new RxCmdShell(builder, rxShell); shell.open().test().awaitCount(1).assertNoErrors(); verify(rxShellSession).writeLine("key=value", true); }
@Test public void testWaitFor() throws InterruptedException { RxCmdShell shell = new RxCmdShell(builder, rxShell); RxCmdShell.Session session = shell.open().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().values().get(0); assertThat(session.waitFor().test().await(1, TimeUnit.SECONDS), is(false)); waitForEmitter.onSuccess(55); session.waitFor().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().assertValue(55); } |
### Question:
RxCmdShell { public synchronized Completable cancel() { if (RXSDebug.isDebug()) Timber.tag(TAG).v("cancel()"); if (session == null) return Completable.complete(); else return session.flatMapCompletable(Session::cancel); } @SuppressWarnings("unused") private RxCmdShell(); RxCmdShell(Builder builder, RxShell rxShell); synchronized Single<Session> open(); Single<Boolean> isAlive(); synchronized Completable cancel(); synchronized Single<Integer> close(); static Builder builder(); }### Answer:
@Test public void testCancel() { RxCmdShell shell = new RxCmdShell(builder, rxShell); RxCmdShell.Session session1 = shell.open().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().values().get(0); session1.isAlive().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().assertValue(true); session1.cancel().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().assertComplete(); verify(rxShellSession).cancel(); session1.isAlive().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().assertValue(false); RxCmdShell.Session session2 = shell.open().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().values().get(0); assertThat(session2, is(not(session1))); } |
### Question:
RxCmdShell { public synchronized Single<Integer> close() { if (RXSDebug.isDebug()) Timber.tag(TAG).v("close()"); if (session == null) return Single.just(Cmd.ExitCode.OK); else return session.flatMap(Session::close); } @SuppressWarnings("unused") private RxCmdShell(); RxCmdShell(Builder builder, RxShell rxShell); synchronized Single<Session> open(); Single<Boolean> isAlive(); synchronized Completable cancel(); synchronized Single<Integer> close(); static Builder builder(); }### Answer:
@Test public void testClose() throws IOException { RxCmdShell shell = new RxCmdShell(builder, rxShell); RxCmdShell.Session session1 = shell.open().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().values().get(0); session1.isAlive().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().assertValue(true); session1.close().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().assertValue(0); verify(rxShellSession).close(); session1.isAlive().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().assertValue(false); RxCmdShell.Session session2 = shell.open().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().values().get(0); assertThat(session2, is(not(session1))); } |
### Question:
CmdProcessor { public Observable<Boolean> isIdle() { return idlePub.doOnEach(n -> { if (RXSDebug.isDebug()) Timber.tag(TAG).v("isIdle: %s", n);}); } CmdProcessor(Harvester.Factory factory); Single<Cmd.Result> submit(Cmd cmd); synchronized void attach(RxShell.Session session); Observable<Boolean> isIdle(); }### Answer:
@Test public void testIsIdle() { processor.isIdle().test().assertValueCount(1).assertNotComplete().assertValue(true); processor.attach(session); processor.isIdle().test().assertValueCount(1).assertNotComplete().assertValue(true); processor.submit(Cmd.builder("sleep 400").build()).subscribe(); await().atMost(1, TimeUnit.SECONDS).until(() -> processor.isIdle().blockingFirst(), is(false)); await().atMost(1, TimeUnit.SECONDS).until(() -> processor.isIdle().blockingFirst(), is(true)); } |
### Question:
SuApp { @Override public int hashCode() { int result = type.hashCode(); result = 31 * result + (packageName != null ? packageName.hashCode() : 0); result = 31 * result + (versionName != null ? versionName.hashCode() : 0); result = 31 * result + (versionCode != null ? versionCode.hashCode() : 0); result = 31 * result + (apkPath != null ? apkPath.hashCode() : 0); return result; } SuApp(SuBinary.Type type, @Nullable String pkg, @Nullable String versionName, @Nullable Integer versionCode, @Nullable String apkPath); SuBinary.Type getType(); @Nullable String getPackageName(); @Nullable String getVersionName(); @Nullable Integer getVersionCode(); @Nullable String getApkPath(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testEqualsHash() { final SuApp app1 = new SuApp(SuBinary.Type.NONE, "pkg", "vname", 1, "/path"); final SuApp app2 = new SuApp(SuBinary.Type.NONE, "pkg", "vname", 1, "/path"); final SuApp app3 = new SuApp(SuBinary.Type.NONE, "", "vname", 1, "/path"); assertThat(app1, is(app2)); assertThat(app2, is(not(app3))); assertThat(app1.hashCode(), is(app2.hashCode())); assertThat(app2.hashCode(), is(not(app3.hashCode()))); } |
### Question:
RootKiller implements ProcessKiller { public boolean kill(Process process) { if (RXSDebug.isDebug()) Timber.tag(TAG).d("kill(%s)", process); if (!ProcessHelper.isAlive(process)) { if (RXSDebug.isDebug()) Timber.tag(TAG).d("Process is no longer alive, skipping kill."); return true; } Matcher matcher = PID_PATTERN.matcher(process.toString()); if (!matcher.matches()) { if (RXSDebug.isDebug()) Timber.tag(TAG).e("Can't find PID for %s", process); return false; } int pid = Integer.parseInt(matcher.group(1)); List<Integer> allRelatedPids = getAllPids(pid); if (RXSDebug.isDebug()) Timber.tag(TAG).d("Related pids: %s", allRelatedPids); if (allRelatedPids != null && destroyPids(allRelatedPids)) { return true; } else { if (RXSDebug.isDebug()) Timber.tag(TAG).w("Couldn't destroy process via root shell, trying Process.destroy()"); process.destroy(); return false; } } RootKiller(ProcessFactory processFactory); boolean kill(Process process); }### Answer:
@Test public void testKill() { ApiWrap.setSDKInt(26); when(processtoKill.isAlive()).thenReturn(true); when(processtoKill.toString()).thenReturn("Process[pid=1234, hasExited=false]"); ProcessKiller killer = new RootKiller(processFactory); psProcess.addCmdListener(line -> { if (line.startsWith("ps")) { psProcess.printData(" PID PPID PGID WINPID TTY UID STIME COMMAND"); psProcess.printData(" 5678 1234 6316 7860 pty1 1001 Nov 4 /usr/bin/ssh"); } return true; }); assertThat(ProcessHelper.isAlive(processtoKill), is(true)); assertThat(killer.kill(processtoKill), is(true)); assertThat(killProcess.getLastCommandRaw(), is("kill 1234" + LineReader.getLineSeparator())); }
@Test public void testKill_dontKillTheDead() throws IOException { ApiWrap.setSDKInt(26); when(processtoKill.isAlive()).thenReturn(false); ProcessKiller killer = new RootKiller(processFactory); assertThat(killer.kill(processtoKill), is(true)); verify(processFactory, never()).start(any()); }
@Test public void testKill_cantFindProcessPid() throws IOException { ApiWrap.setSDKInt(26); when(processtoKill.isAlive()).thenReturn(true); ProcessKiller killer = new RootKiller(processFactory); when(processtoKill.toString()).thenReturn(""); assertThat(psProcess.getLastCommandRaw(), is(nullValue())); assertThat(killer.kill(processtoKill), is(false)); } |
### Question:
RxProcess { public synchronized Completable close() { if (RXSDebug.isDebug()) Timber.tag(TAG).v("close()"); if (session == null) return Completable.complete(); else return session.flatMapCompletable(s -> s.destroy().andThen(s.waitFor().ignoreElement())); } RxProcess(ProcessFactory processFactory, ProcessKiller processKiller, String... commands); synchronized Single<Session> open(); synchronized Single<Boolean> isAlive(); synchronized Completable close(); }### Answer:
@Test public void testClose() { RxProcess rxProcess = new RxProcess(processFactory, processKiller, "sh"); rxProcess.close().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().assertComplete(); rxProcess.open().test().awaitCount(1).assertNoErrors(); assertThat(mockProcesses.get(0).isAlive(), is(true)); rxProcess.close().test().awaitDone(1, TimeUnit.SECONDS).assertNoErrors().assertComplete(); verify(mockProcesses.get(0)).destroy(); assertThat(mockProcesses.get(0).isAlive(), is(false)); verify(processKiller).kill(mockProcesses.get(0)); } |
### Question:
ProcessHelper { @SuppressLint("NewApi") public static boolean isAlive(Process process) { if (ApiWrap.hasOreo()) { return process.isAlive(); } else { try { process.exitValue(); return false; } catch (IllegalThreadStateException e) { return true; } } } @SuppressLint("NewApi") static boolean isAlive(Process process); }### Answer:
@Test public void testIsAlive_legacy() { ApiWrap.setSDKInt(16); doThrow(new IllegalThreadStateException()).when(process).exitValue(); assertThat(ProcessHelper.isAlive(process), is(true)); doReturn(0).when(process).exitValue(); assertThat(ProcessHelper.isAlive(process), is(false)); }
@Test public void testIsAlive_oreo() { ApiWrap.setSDKInt(26); when(process.isAlive()).thenReturn(true); assertThat(ProcessHelper.isAlive(process), is(true)); when(process.isAlive()).thenReturn(false); assertThat(ProcessHelper.isAlive(process), is(false)); } |
### Question:
UserKiller implements ProcessKiller { @SuppressLint("NewApi") @Override public boolean kill(Process process) { if (RXSDebug.isDebug()) Timber.tag(TAG).d("kill(%s)", process); if (!ProcessHelper.isAlive(process)) { if (RXSDebug.isDebug()) Timber.tag(TAG).d("Process is no longer alive, skipping kill."); return true; } if (ApiWrap.hasOreo()) process.destroyForcibly(); else process.destroy(); return true; } @SuppressLint("NewApi") @Override boolean kill(Process process); }### Answer:
@Test public void testKill_legacy() { ApiWrap.setSDKInt(16); when(process.exitValue()).thenThrow(new IllegalThreadStateException()); final ProcessKiller killer = new UserKiller(); killer.kill(process); verify(process).destroy(); }
@Test public void testKill_oreo() { ApiWrap.setSDKInt(26); when(process.isAlive()).thenReturn(true); final ProcessKiller killer = new UserKiller(); killer.kill(process); verify(process).destroyForcibly(); } |
### Question:
DefaultProcessFactory implements ProcessFactory { @Override public Process start(String... commands) throws IOException { return new ProcessBuilder(commands).start(); } @Override Process start(String... commands); }### Answer:
@Test public void testStart() throws IOException { DefaultProcessFactory pf = new DefaultProcessFactory(); Process process = pf.start("id"); assertThat(process, is(not(nullValue()))); } |
### Question:
Root { @Override public int hashCode() { return state.hashCode(); } Root(State state); State getState(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testEqualsHash() { Root root1 = new Root(Root.State.ROOTED); Root root2 = new Root(Root.State.ROOTED); Root root3 = new Root(Root.State.DENIED); assertThat(root1, is(root2)); assertThat(root1.hashCode(), is(root2.hashCode())); assertThat(root1, is(not(root3))); assertThat(root1.hashCode(), is(not(root3.hashCode()))); } |
### Question:
MordernWar implements War { public MordernWar(Enemy enemy) { this.enemy = enemy; } MordernWar(Enemy enemy); @Override Enemy getEnemy(); @Override void startWar(); @Override void combatting(); @Override void stopWar(); }### Answer:
@Test public void testMordernWar() { MordernWar war = spy(new MordernWar(mock(IntrepidEnemy.class))); testWarEvents(war); } |
### Question:
AncientWar implements War { public AncientWar(Enemy enemy) { this.enemy = enemy; } AncientWar(Enemy enemy); @Override Enemy getEnemy(); @Override void startWar(); @Override void combatting(); @Override void stopWar(); }### Answer:
@Test public void testAncientWar() { final AncientWar war = spy(new AncientWar(mock(IntrepidEnemy.class))); testWarEvents(war); } |
### Question:
Writer { public CharacterComposite sentenceByChinese() { List<ChineseWord> words = new ArrayList<>(); words.add(new ChineseWord(Arrays.asList(new Character('我')))); words.add(new ChineseWord(Arrays.asList(new Character('是')))); words.add(new ChineseWord(Arrays.asList(new Character('来'), new Character('自')))); words.add(new ChineseWord(Arrays.asList(new Character('北'), new Character('京')))); words.add(new ChineseWord(Arrays.asList(new Character('的')))); words.add(new ChineseWord(Arrays.asList(new Character('小'), new Character('明')))); return new ChineseSentence(words); } CharacterComposite sentenceByChinese(); CharacterComposite sentenceByEnglish(); }### Answer:
@Test public void sentenceByChinese() throws Exception { final Writer writer = new Writer(); testWriterCn(writer.sentenceByChinese(), "我是来自北京的小明。"); } |
### Question:
Writer { public CharacterComposite sentenceByEnglish() { List<EnglishWord> words = new ArrayList<>(); words.add(new EnglishWord(Arrays.asList(new Character('I')))); words.add(new EnglishWord(Arrays.asList(new Character('a'), new Character('m')))); words.add(new EnglishWord(Arrays.asList(new Character('a')))); words.add(new EnglishWord(Arrays.asList(new Character('s'), new Character('t'), new Character('u'), new Character('d'), new Character('e'), new Character('n'), new Character('t')))); words.add(new EnglishWord(Arrays.asList(new Character('f'), new Character('r'), new Character('o'), new Character('m')))); words.add(new EnglishWord(Arrays.asList(new Character('L'), new Character('o'), new Character('n'), new Character('d'), new Character('o'), new Character('n')))); return new EnglishSentence(words); } CharacterComposite sentenceByChinese(); CharacterComposite sentenceByEnglish(); }### Answer:
@Test public void sentenceByEnglish() throws Exception { final Writer writer = new Writer(); testWriter(writer.sentenceByEnglish(), "I am a student from London."); } |
### Question:
Prototype implements Cloneable { @Override protected abstract Prototype clone() throws CloneNotSupportedException; }### Answer:
@Test public void testPrototype() throws Exception { assertEquals(this.prototype.toString(), this.expectedString); final Object clone = this.prototype.clone(); assertNotNull(clone); assertSame(clone.getClass(), this.prototype.getClass()); assertNotSame(this.prototype, clone); } |
### Question:
BenchJdbcAvroJob { public static void main(String[] cmdLineArgs) { try { create(cmdLineArgs).run(); } catch (Exception e) { ExceptionHandling.handleException(e); } } BenchJdbcAvroJob(final PipelineOptions pipelineOptions); static BenchJdbcAvroJob create(final String[] cmdLineArgs); void run(); static void main(String[] cmdLineArgs); }### Answer:
@Test public void shouldRunJdbcAvroJob() { BenchJdbcAvroJob.main( new String[] { "--targetParallelism=1", "--skipPartitionCheck", "--connectionUrl=" + CONNECTION_URL, "--username=", "--table=COFFEES", "--output=" + testDir.toString(), "--avroCodec=zstandard1", "--executions=2" }); assertThat(TestHelper.listDir(testDir.toFile()), containsInAnyOrder("run_0", "run_1")); } |
### Question:
JdbcAvroJob { public static JdbcAvroJob create(final PipelineOptions pipelineOptions, final String output) throws IOException, ClassNotFoundException { pipelineOptions.as(DirectOptions.class).setBlockOnRun(false); return new JdbcAvroJob( pipelineOptions, Pipeline.create(pipelineOptions), JdbcExportArgsFactory.fromPipelineOptions(pipelineOptions), output); } JdbcAvroJob(
final PipelineOptions pipelineOptions,
final Pipeline pipeline,
final JdbcExportArgs jdbcExportArgs,
final String output); static JdbcAvroJob create(final PipelineOptions pipelineOptions, final String output); static JdbcAvroJob create(final PipelineOptions pipelineOptions); static JdbcAvroJob create(final String[] cmdLineArgs); static PipelineOptions buildPipelineOptions(final String[] cmdLineArgs); void prepareExport(); Pipeline getPipeline(); JdbcExportArgs getJdbcExportArgs(); String getOutput(); PipelineOptions getPipelineOptions(); PipelineResult runAndWait(); PipelineResult runExport(); static void main(String[] cmdLineArgs); }### Answer:
@Test(expected = IllegalArgumentException.class) public void shouldFailOnMissingInput() throws IOException, ClassNotFoundException { JdbcAvroJob.create(PipelineOptionsFactory.create()); }
@Test(expected = IllegalArgumentException.class) public void shouldFailOnEmptyInput() throws IOException, ClassNotFoundException { PipelineOptions pipelineOptions = PipelineOptionsFactory.create(); pipelineOptions.as(OutputOptions.class).setOutput(""); JdbcAvroJob.create(PipelineOptionsFactory.create()); } |
### Question:
PsqlAvroJob { public static PsqlAvroJob create(final String[] cmdLineArgs) throws IOException, ClassNotFoundException { JdbcAvroJob job = JdbcAvroJob.create(cmdLineArgs); PsqlReplicationCheck.validateOptions(job.getJdbcExportArgs()); final PsqlReplicationCheck psqlReplicationCheck = PsqlReplicationCheck.create(job.getJdbcExportArgs()); return new PsqlAvroJob(job, psqlReplicationCheck); } PsqlAvroJob(final JdbcAvroJob job, final PsqlReplicationCheck psqlReplicationCheck); static PsqlAvroJob create(final String[] cmdLineArgs); static void main(String[] cmdLineArgs); }### Answer:
@Test public void shouldCreatePsqlAvroJob() throws IOException, ClassNotFoundException { PsqlAvroJob.create( new String[] { "--connectionUrl=jdbc:postgresql: "--table=foo", "--partition=2025-02-28", "--skipPartitionCheck", "--output=/fake" }); } |
### Question:
PasswordReader { Optional<String> readPassword(final DBeamPipelineOptions options) throws IOException { FileSystems.setDefaultPipelineOptions(options); if (options.getPasswordFileKmsEncrypted() != null) { LOGGER.info("Decrypting password using KMS..."); return Optional.of( kmsDecrypter .decrypt(BeamHelper.readFromFile(options.getPasswordFileKmsEncrypted())) .trim()); } else if (options.getPasswordFile() != null) { LOGGER.info("Reading password from file: {}", options.getPasswordFile()); return Optional.of(BeamHelper.readFromFile(options.getPasswordFile())); } else { return Optional.ofNullable(options.getPassword()); } } PasswordReader(KmsDecrypter kmsDecrypter); }### Answer:
@Test public void shouldDecryptPasswordOnpasswordFileKmsEncryptedParameter() throws IOException { MockHttpTransport mockHttpTransport = new MockHttpTransport.Builder() .setLowLevelHttpResponse( new MockLowLevelHttpResponse() .setStatusCode(200) .setContentType(Json.MEDIA_TYPE) .setContent( JacksonFactory.getDefaultInstance() .toByteArray( new DecryptResponse() .encodePlaintext("something_decrypted".getBytes())))) .build(); PasswordReader passwordReader = new PasswordReader( KmsDecrypter.decrypter() .project(Optional.of("fake_project")) .credentials(NoopCredentialFactory.fromOptions(null).getCredential()) .transport(mockHttpTransport) .build()); DBeamPipelineOptions options = PipelineOptionsFactory.create().as(DBeamPipelineOptions.class); options.setPasswordFileKmsEncrypted(passwordFile.getPath()); final Optional<String> actualPassword = passwordReader.readPassword(options); Assert.assertEquals(Optional.of("something_decrypted"), actualPassword); } |
### Question:
JobNameConfiguration { public static void configureJobName(final PipelineOptions options, final String... parts) { try { options.as(ApplicationNameOptions.class).setAppName("JdbcAvroJob"); } catch (Exception e) { LOGGER.warn("Unable to configure ApplicationName", e); } if (options.getJobName() == null || "auto".equals(options.getJobName())) { final String randomPart = Integer.toHexString(ThreadLocalRandom.current().nextInt()); final String jobName = String.format( "dbeam-%s-%s", Arrays.stream(parts) .filter(p -> !Strings.isNullOrEmpty(p)) .map(JobNameConfiguration::normalizeString) .collect(Collectors.joining("-")), randomPart); options.setJobName(jobName); } } static void configureJobName(final PipelineOptions options, final String... parts); }### Answer:
@Test public void shouldConfigureJobName() { PipelineOptions pipelineOptions = PipelineOptionsFactory.create(); pipelineOptions.setJobName(null); JobNameConfiguration.configureJobName(pipelineOptions, "some_db", "some_table"); Assert.assertEquals( "JdbcAvroJob", pipelineOptions.as(ApplicationNameOptions.class).getAppName()); assertThat(pipelineOptions.getJobName(), startsWith("dbeam-somedb-sometable-")); }
@Test public void shouldConfigureJobNameWhenJobNameIsAuto() { PipelineOptions pipelineOptions = PipelineOptionsFactory.create(); pipelineOptions.setJobName("auto"); JobNameConfiguration.configureJobName(pipelineOptions, "some_db", "some_table"); Assert.assertEquals( "JdbcAvroJob", pipelineOptions.as(ApplicationNameOptions.class).getAppName()); assertThat(pipelineOptions.getJobName(), startsWith("dbeam-somedb-sometable-")); }
@Test public void shouldConfigureJobNameWithEmptyTableName() { PipelineOptions pipelineOptions = PipelineOptionsFactory.create(); pipelineOptions.setJobName(null); JobNameConfiguration.configureJobName(pipelineOptions, "some_db", null); Assert.assertEquals( "JdbcAvroJob", pipelineOptions.as(ApplicationNameOptions.class).getAppName()); assertThat(pipelineOptions.getJobName(), startsWith("dbeam-somedb-")); Assert.assertEquals(3, pipelineOptions.getJobName().split("-").length); } |
### Question:
QueryBuilderArgs implements Serializable { public static QueryBuilderArgs create(final String tableName) { checkArgument(tableName != null, "TableName cannot be null"); checkArgument(checkTableName(tableName), "'table' must follow [a-zA-Z_][a-zA-Z0-9_]*"); return createBuilder().setBaseSqlQuery(QueryBuilder.fromTablename(tableName)).build(); } abstract Optional<Long> limit(); abstract Optional<String> partitionColumn(); abstract Optional<Instant> partition(); abstract TemporalAmount partitionPeriod(); abstract Optional<String> splitColumn(); abstract Optional<Integer> queryParallelism(); abstract Builder builder(); static QueryBuilderArgs create(final String tableName); static QueryBuilderArgs createFromQuery(final String sqlQuery); String sqlQueryWithLimitOne(); List<String> buildQueries(final Connection connection); }### Answer:
@Test(expected = IllegalArgumentException.class) public void shouldFailOnNullTableName() { QueryBuilderArgs.create(null); }
@Test(expected = IllegalArgumentException.class) public void shouldFailOnInvalidTableName() { QueryBuilderArgs.create("*invalid#name@!"); }
@Test(expected = IllegalArgumentException.class) public void shouldFailOnTableNameWithDots() { QueryBuilderArgs.create("foo.bar"); } |
### Question:
QueryBuilderArgs implements Serializable { public abstract Optional<Instant> partition(); abstract Optional<Long> limit(); abstract Optional<String> partitionColumn(); abstract Optional<Instant> partition(); abstract TemporalAmount partitionPeriod(); abstract Optional<String> splitColumn(); abstract Optional<Integer> queryParallelism(); abstract Builder builder(); static QueryBuilderArgs create(final String tableName); static QueryBuilderArgs createFromQuery(final String sqlQuery); String sqlQueryWithLimitOne(); List<String> buildQueries(final Connection connection); }### Answer:
@Test public void shouldConfigurePartitionForFullIsoString() throws IOException, SQLException { QueryBuilderArgs actual = parseOptions( "--connectionUrl=jdbc:postgresql: + "--partition=2027-07-31T13:37:59Z"); Assert.assertEquals(Optional.of(Instant.parse("2027-07-31T13:37:59Z")), actual.partition()); }
@Test public void shouldConfigurePartitionForMonthlySchedule() throws IOException, SQLException { QueryBuilderArgs actual = parseOptions( "--connectionUrl=jdbc:postgresql: + "--partition=2027-05"); Assert.assertEquals(Optional.of(Instant.parse("2027-05-01T00:00:00Z")), actual.partition()); }
@Test public void shouldConfigurePartitionForHourlySchedule() throws IOException, SQLException { QueryBuilderArgs actual = parseOptions( "--connectionUrl=jdbc:postgresql: + "--partition=2027-05-02T23"); Assert.assertEquals(Optional.of(Instant.parse("2027-05-02T23:00:00Z")), actual.partition()); } |
### Question:
ParallelQueryBuilder implements Serializable { protected static List<String> queriesForBounds( long min, long max, int parallelism, String splitColumn, QueryBuilder queryBuilder) { List<QueryRange> ranges = generateRanges(min, max, parallelism); return ranges.stream() .map( x -> queryBuilder .withParallelizationCondition( splitColumn, x.getStartPointIncl(), x.getEndPoint(), x.isEndPointExcl()) .build() ) .collect(Collectors.toList()); } }### Answer:
@Test public void shouldBuildParallelQueriesGivenRangeAndParallelism3() { final List<String> actual = ParallelQueryBuilder.queriesForBounds(100, 400, 3, "sp", QUERY_FORMAT); assertThat( actual, Matchers.is( Lists.newArrayList( format("%s AND sp >= %s AND sp < %s", QUERY_BASE, 100, 200), format("%s AND sp >= %s AND sp < %s", QUERY_BASE, 200, 300), format("%s AND sp >= %s AND sp <= %s", QUERY_BASE, 300, 400)))); }
@Test public void shouldBuildParallelQueriesGivenRangeThatDoesNotDivideEqually() { final List<String> actual = ParallelQueryBuilder.queriesForBounds(100, 402, 5, "sp", QUERY_FORMAT); assertThat( actual, Matchers.is( Lists.newArrayList( format("%s AND sp >= %s AND sp < %s", QUERY_BASE, 100, 161), format("%s AND sp >= %s AND sp < %s", QUERY_BASE, 161, 222), format("%s AND sp >= %s AND sp < %s", QUERY_BASE, 222, 283), format("%s AND sp >= %s AND sp < %s", QUERY_BASE, 283, 344), format("%s AND sp >= %s AND sp <= %s", QUERY_BASE, 344, 402)))); }
@Test public void shouldBuildSingleQueryWhenParallelismIsMoreThanMaxMin() { final List<String> actual = ParallelQueryBuilder.queriesForBounds(1, 2, 5, "sp", QUERY_FORMAT); assertThat( actual, Matchers.is(Lists.newArrayList(format("%s AND sp >= %s AND sp <= %s", QUERY_BASE, 1, 2)))); }
@Test public void shouldBuildSingleQueryWhenMaxMinIsTheSame() { final List<String> actual = ParallelQueryBuilder.queriesForBounds(1, 1, 5, "sp", QUERY_FORMAT); assertThat( actual, Matchers.is(Lists.newArrayList(format("%s AND sp >= %s AND sp <= %s", QUERY_BASE, 1, 1)))); }
@Test public void shouldBuildSingleQueryWhenParallelismIsOne() { final List<String> actual = ParallelQueryBuilder.queriesForBounds(1, 10, 1, "sp", QUERY_FORMAT); assertThat( actual, Matchers.is(Lists.newArrayList(format("%s AND sp >= %s AND sp <= %s", QUERY_BASE, 1, 10)))); }
@Ignore @Test public void shouldBuildMultipleQueriesWhenQueryingFromTwoRows() { final List<String> actual = ParallelQueryBuilder.queriesForBounds(1, 2, 2, "sp", QUERY_FORMAT); assertThat( actual, Matchers.is( Lists.newArrayList( format("%s AND sp >= %s AND sp < %s", QUERY_BASE, 1, 2), format("%s AND sp >= %s AND sp <= %s", QUERY_BASE, 2, 2)))); } |
### Question:
PathUtils { public static HashCode sha256(final Path file) throws IOException { return MoreFiles.asByteSource(file).hash(Hashing.sha256()); } private PathUtils(); static HashCode sha256(final Path file); static void syncRecursive(final Path source, final Path target); static void removeRecursive(final Path path); }### Answer:
@Test public void testSha256() throws Exception { final Path file = fs.getPath("/", "file"); Files.write(file, new byte[] {0x00, 0x01, 0x02}); final HashCode hashCode = PathUtils.sha256(file); assertThat( hashCode.toString(), is("ae4b3280e56e2faf83f414a6e3dabe9d5fbe18976544c05fed121accb85b53fc")); } |
### Question:
PathUtils { static Path equivalentSubpath(final Path a, final Path b, final Path path) { return b.resolve(a.relativize(path)); } private PathUtils(); static HashCode sha256(final Path file); static void syncRecursive(final Path source, final Path target); static void removeRecursive(final Path path); }### Answer:
@Test public void testEquivalentSubpath() throws Exception { final Path a = fs.getPath("/", "a", "b"); final Path b = fs.getPath("/", "a", "d"); final Path path = fs.getPath("/", "a", "b", "c"); final Path expectedOutput = fs.getPath("/", "a", "d", "c"); final Path actualOutput = PathUtils.equivalentSubpath(a, b, path); assertThat(actualOutput, is(expectedOutput)); } |
### Question:
PathUtils { public static void removeRecursive(final Path path) throws IOException { Files.walkFileTree( path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { Files.deleteIfExists(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException { Files.deleteIfExists(dir); return FileVisitResult.CONTINUE; } }); } private PathUtils(); static HashCode sha256(final Path file); static void syncRecursive(final Path source, final Path target); static void removeRecursive(final Path path); }### Answer:
@Test public void testRemoveRecursive() throws Exception { final Path root = Files.createDirectory(fs.getPath("/", "root")); final Path unrelated = Files.write(root.resolve("unrelated"), new byte[] {0x0f}); final Path dir = Files.createDirectory(root.resolve("dir")); Files.write(dir.resolve("a"), new byte[] {0x00}); Files.write(dir.resolve("b"), new byte[] {0x01}); Files.createSymbolicLink(dir.resolve("c"), dir.resolve("b")); Files.createSymbolicLink(dir.resolve("d"), unrelated); final Path subdir = Files.createDirectory(dir.resolve("subdir")); Files.write(subdir.resolve("e"), new byte[] {0x00}); Files.write(subdir.resolve("f"), new byte[] {0x01}); PathUtils.removeRecursive(dir); assertThat(Files.notExists(dir), describedAs("directory was deleted", is(true))); assertThat(Files.exists(unrelated), describedAs("unrelated file was kept", is(true))); } |
### Question:
ConfigurationServlet extends PassThroughAuthenticationServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doWithAuthentication(request, response, this::updateConfiguration); } @SuppressWarnings("unused") // production constructor ConfigurationServlet(); ConfigurationServlet(WebClientFactory webClientFactory); }### Answer:
@Test(expected = ServletException.class) public void whenPostWithoutFile_reportFailure() throws Exception { servlet.doPost(createPostRequest(), response); }
@Test public void afterSelectedFileHasBadBooleanValue_configurationIsUnchanged() throws Exception { LiveConfiguration.loadFromString(CONFIGURATION); servlet.doPost(createUploadRequest(createEncodedForm("append", ADDED_CONFIGURATION_WITH_BAD_BOOLEAN)), response); assertThat(LiveConfiguration.asString(), equalTo(CONFIGURATION)); }
@Test public void whenServerSends403StatusOnGet_returnToClient() throws Exception { factory.reportNotAuthorized(); servlet.doPost(request, response); assertThat(response.getStatus(), equalTo(SC_FORBIDDEN)); }
@Test public void whenServerSends401StatusOnGet_returnToClient() throws Exception { factory.reportAuthenticationRequired("Test-Realm"); servlet.doPost(request, response); assertThat(response.getStatus(), equalTo(SC_UNAUTHORIZED)); assertThat(response, containsHeader("WWW-Authenticate", "Basic realm=\"Test-Realm\"")); }
@Test public void whenRequestUsesHttp_authenticateWithHttp() throws Exception { servlet.doPost(createUploadRequest(createEncodedForm("replace", CONFIGURATION)), response); assertThat(factory.getClientUrl(), Matchers.startsWith("http:")); }
@Test public void whenRequestUsesHttps_authenticateWithHttps() throws Exception { HttpServletRequestStub request = createUploadRequest(createEncodedForm("replace", CONFIGURATION)); request.setSecure(true); servlet.doPost(request, response); assertThat(factory.getClientUrl(), Matchers.startsWith("https:")); }
@Test public void afterUploadWithReplace_useNewConfiguration() throws Exception { servlet.doPost(createUploadRequest(createEncodedForm("replace", CONFIGURATION)), response); assertThat(LiveConfiguration.asString(), equalTo(CONFIGURATION)); }
@Test public void afterUpload_redirectToMainPage() throws Exception { servlet.doPost(createUploadRequest(createEncodedForm("replace", CONFIGURATION)), response); assertThat(response.getRedirectLocation(), equalTo("")); }
@Test public void whenRestPortInaccessible_switchToLocalPort() throws Exception { LiveConfiguration.loadFromString(CONFIGURATION_WITH_REST_PORT); factory.throwConnectionFailure("localhost", REST_PORT); servlet.doPost(createUploadRequest(createEncodedForm("replace", CONFIGURATION_WITH_REST_PORT)), response); assertThat(createAuthenticationUrl(), containsString(Integer.toString(LOCAL_PORT))); }
@Test public void afterUploadWithAppend_useBothConfiguration() throws Exception { LiveConfiguration.loadFromString(CONFIGURATION); servlet.doPost(createUploadRequest(createEncodedForm("append", ADDED_CONFIGURATION)), createServletResponse()); assertThat(LiveConfiguration.asString(), equalTo(COMBINED_CONFIGURATION)); }
@Test public void whenSelectedFileIsNotYaml_reportError() throws Exception { LiveConfiguration.loadFromString(CONFIGURATION); servlet.doPost(createUploadRequest(createEncodedForm("append", NON_YAML)), response); assertThat(response.getHtml(), containsString(ConfigurationException.NOT_YAML_FORMAT)); }
@Test public void whenSelectedFileHasPartialYaml_reportError() throws Exception { LiveConfiguration.loadFromString(CONFIGURATION); servlet.doPost(createUploadRequest(createEncodedForm("append", PARTIAL_YAML)), response); assertThat(response.getHtml(), containsString(ConfigurationException.BAD_YAML_FORMAT)); }
@Test public void whenSelectedFileHasBadBooleanValue_reportError() throws Exception { LiveConfiguration.loadFromString(CONFIGURATION); servlet.doPost(createUploadRequest(createEncodedForm("append", ADDED_CONFIGURATION_WITH_BAD_BOOLEAN)), response); assertThat(response.getHtml(), containsString("blabla")); } |
### Question:
ExporterConfig { boolean getMetricsNameSnakeCase() { return metricsNameSnakeCase; } private ExporterConfig(Map<String, Object> yaml); static ExporterConfig createEmptyConfig(); static ExporterConfig loadConfig(InputStream inputStream); Map<String, Object> scrapeMetrics(MBeanSelector selector, JsonObject response); MBeanSelector[] getEffectiveQueries(); MBeanSelector[] getQueries(); static ExporterConfig loadConfig(Map<String, Object> yamlConfig); QuerySyncConfiguration getQuerySyncConfiguration(); Integer getRestPort(); void append(ExporterConfig config2); void replace(ExporterConfig config2); @Override String toString(); }### Answer:
@Test public void afterReplace_configHasChangedSnakeCase() { assertThat(getReplacedConfiguration(SERVLET_CONFIG, WORK_MANAGER_CONFIG).getMetricsNameSnakeCase(), is(true)); assertThat(getReplacedConfiguration(WORK_MANAGER_CONFIG, SERVLET_CONFIG).getMetricsNameSnakeCase(), is(false)); }
@Test public void afterAppend_configHasOriginalSnakeCase() { assertThat(getAppendedConfiguration(SERVLET_CONFIG, WORK_MANAGER_CONFIG).getMetricsNameSnakeCase(), is(false)); assertThat(getAppendedConfiguration(WORK_MANAGER_CONFIG, SERVLET_CONFIG).getMetricsNameSnakeCase(), is(true)); } |
### Question:
ExporterConfig { public Integer getRestPort() { return restPort; } private ExporterConfig(Map<String, Object> yaml); static ExporterConfig createEmptyConfig(); static ExporterConfig loadConfig(InputStream inputStream); Map<String, Object> scrapeMetrics(MBeanSelector selector, JsonObject response); MBeanSelector[] getEffectiveQueries(); MBeanSelector[] getQueries(); static ExporterConfig loadConfig(Map<String, Object> yamlConfig); QuerySyncConfiguration getQuerySyncConfiguration(); Integer getRestPort(); void append(ExporterConfig config2); void replace(ExporterConfig config2); @Override String toString(); }### Answer:
@Test public void afterReplace_configHasChangedRestPort() { assertThat(getReplacedConfiguration(SERVLET_CONFIG, REST_PORT_CONFIG).getRestPort(), equalTo(1234)); assertThat(getReplacedConfiguration(REST_PORT_CONFIG, SERVLET_CONFIG).getRestPort(), nullValue()); }
@Test public void afterAppend_configHasOriginalRestPort() { assertThat(getAppendedConfiguration(SERVLET_CONFIG, REST_PORT_CONFIG).getRestPort(), nullValue()); assertThat(getAppendedConfiguration(REST_PORT_CONFIG, SERVLET_CONFIG).getRestPort(), equalTo(1234)); } |
### Question:
ExporterConfig { boolean useDomainQualifier() { return useDomainQualifier && (domainName == null); } private ExporterConfig(Map<String, Object> yaml); static ExporterConfig createEmptyConfig(); static ExporterConfig loadConfig(InputStream inputStream); Map<String, Object> scrapeMetrics(MBeanSelector selector, JsonObject response); MBeanSelector[] getEffectiveQueries(); MBeanSelector[] getQueries(); static ExporterConfig loadConfig(Map<String, Object> yamlConfig); QuerySyncConfiguration getQuerySyncConfiguration(); Integer getRestPort(); void append(ExporterConfig config2); void replace(ExporterConfig config2); @Override String toString(); }### Answer:
@Test public void afterReplace_configHasChangedDomainQualifier() { assertThat(getReplacedConfiguration(SERVLET_CONFIG, DOMAIN_QUALIFIER_CONFIG).useDomainQualifier(), is(true)); assertThat(getReplacedConfiguration(DOMAIN_QUALIFIER_CONFIG, SERVLET_CONFIG).useDomainQualifier(), is(false)); } |
### Question:
ExporterConfig { public MBeanSelector[] getQueries() { if (queries == null) return NO_QUERIES; return queries; } private ExporterConfig(Map<String, Object> yaml); static ExporterConfig createEmptyConfig(); static ExporterConfig loadConfig(InputStream inputStream); Map<String, Object> scrapeMetrics(MBeanSelector selector, JsonObject response); MBeanSelector[] getEffectiveQueries(); MBeanSelector[] getQueries(); static ExporterConfig loadConfig(Map<String, Object> yamlConfig); QuerySyncConfiguration getQuerySyncConfiguration(); Integer getRestPort(); void append(ExporterConfig config2); void replace(ExporterConfig config2); @Override String toString(); }### Answer:
@Test public void afterReplaceWithEmptyConfig_configHasNoQueries() { ExporterConfig config = getReplacedConfiguration(SERVLET_CONFIG, ""); assertThat(config.getQueries(), arrayWithSize(0)); }
@Test public void afterAppendWithNewTopLevelQuery_configHasMultipleTopLevelQueries() { ExporterConfig config = getAppendedConfiguration(SERVLET_CONFIG, PARTITION_CONFIG); assertThat(config.getQueries(), arrayWithSize(2)); }
@Test public void afterAppendWithMatchingTopLevelQuery_configHasMergedQueries() { ExporterConfig config = getAppendedConfiguration(SERVLET_CONFIG, WORK_MANAGER_CONFIG); assertThat(config.getQueries(), arrayWithSize(1)); }
@Test public void whenSpecified_readQueriesFromYaml() { ExporterConfig config = loadFromString(SERVLET_CONFIG); assertThat(config.getQueries(), arrayWithSize(1)); } |
### Question:
ExporterConfig { @Override public String toString() { StringBuilder sb = new StringBuilder(); if (querySyncConfiguration != null) sb.append(querySyncConfiguration); if (metricsNameSnakeCase) sb.append("metricsNameSnakeCase: true\n"); if (useDomainQualifier) sb.append(DOMAIN_QUALIFIER + ": true\n"); if (restPort != null) sb.append(REST_PORT + ": ").append(restPort).append("\n"); sb.append("queries:\n"); for (MBeanSelector query : getQueries()) sb.append(formatQuery(query)); return sb.toString(); } private ExporterConfig(Map<String, Object> yaml); static ExporterConfig createEmptyConfig(); static ExporterConfig loadConfig(InputStream inputStream); Map<String, Object> scrapeMetrics(MBeanSelector selector, JsonObject response); MBeanSelector[] getEffectiveQueries(); MBeanSelector[] getQueries(); static ExporterConfig loadConfig(Map<String, Object> yamlConfig); QuerySyncConfiguration getQuerySyncConfiguration(); Integer getRestPort(); void append(ExporterConfig config2); void replace(ExporterConfig config2); @Override String toString(); }### Answer:
@Test public void whenYamlContainsMergeableQueries_MergeThem() { ExporterConfig config = loadFromString(MERGEABLE_CONFIG); assertThat(config.toString(), equalTo(MERGED_CONFIG)); }
@Test public void whenConfigHasSingleValue_displayAsScalar() { ExporterConfig exporterConfig = loadFromString(CONFIG_WITH_SINGLE_VALUE); assertThat(exporterConfig.toString(), equalTo(CONFIG_WITH_SINGLE_VALUE)); }
@Test public void afterLoad_convertToString() { ExporterConfig config = loadFromString(SNAKE_CASE_CONFIG); assertThat(config.toString(), equalToIgnoringWhiteSpace(SNAKE_CASE_CONFIG)); }
@Test public void includeTopLevelFieldsInString() { ExporterConfig config = loadFromString(CONFIG_WITH_TOP_LEVEL_FIELDS); assertThat(config.toString(), equalToIgnoringWhiteSpace(CONFIG_WITH_TOP_LEVEL_FIELDS)); }
@Test public void includeSnakeCaseTrueSettingInToString() { ExporterConfig config = loadFromString(SNAKE_CASE_CONFIG); assertThat(config.toString(), equalToIgnoringWhiteSpace(SNAKE_CASE_CONFIG)); }
@Test public void includeRestPortSettingInToString() { ExporterConfig config = loadFromString(REST_PORT_CONFIG); assertThat(config.toString(), equalToIgnoringWhiteSpace(REST_PORT_CONFIG)); } |
### Question:
SnakeCaseUtil { static String convert(String s) { return SNAKE_CASE_PATTERN.matcher(s).replaceAll("$1_$2").toLowerCase(); } static boolean isCompliant(String s); }### Answer:
@Test public void convertToSnakeCase() throws Exception { assertThat(SnakeCaseUtil.convert("simple"), equalTo("simple")); assertThat(SnakeCaseUtil.convert("already_snake_case"), equalTo("already_snake_case")); assertThat(SnakeCaseUtil.convert("isCamelCase"), equalTo("is_camel_case")); assertThat(SnakeCaseUtil.convert("PascalCase"), equalTo("pascal_case")); } |
### Question:
SnakeCaseUtil { public static boolean isCompliant(String s) { return s.equals(convert(s)); } static boolean isCompliant(String s); }### Answer:
@Test public void verifiesSnakeCase() throws Exception { assertThat(SnakeCaseUtil.isCompliant("simple"), is(true)); assertThat(SnakeCaseUtil.isCompliant("an_example_with_multiple_words"), is(true)); assertThat(SnakeCaseUtil.isCompliant("camelCaseWithMultipleWords"), is(false)); assertThat(SnakeCaseUtil.isCompliant("PascalCase"), is(false)); } |
### Question:
MapUtils { @SuppressWarnings("unchecked") static String[] getStringArray(Map<String, Object> map, String key) { Object value = map.get(key); if (value instanceof List) return toStringArray((List<Object>) value); else if (!value.getClass().isArray()) return new String[]{value.toString()}; else if (value.getClass().getComponentType() == String.class) return (String[]) value; else throw createBadTypeException(key, value, "an array of strings"); } static boolean isNullOrEmptyString(String s); }### Answer:
@Test public void whenStringArrayValueIsStringArray_returnAsIs() throws Exception { Map<String,Object> map = ImmutableMap.of("values", STRING_ARRAY); assertThat(MapUtils.getStringArray(map, "values"), arrayContaining(STRING_ARRAY)); }
@Test public void whenStringArrayValueIsSingleObject_returnAsLengthOneArray() throws Exception { Map<String,Object> map = ImmutableMap.of("values", 33); assertThat(MapUtils.getStringArray(map, "values"), arrayContaining("33")); }
@Test public void whenStringArrayValueIsList_returnAsArray() throws Exception { Map<String,Object> map = ImmutableMap.of("values", Arrays.asList(7, 8, true)); assertThat(MapUtils.getStringArray(map, "values"), arrayContaining("7", "8", "true")); } |
### Question:
MBeanSelector { public static MBeanSelector create(Map<String, Object> map) { return new MBeanSelector(map); } private MBeanSelector(Map<String, Object> map); private MBeanSelector(MBeanSelector first, MBeanSelector second); static MBeanSelector create(Map<String, Object> map); String getPrintableRequest(); String getRequest(); String getUrl(Protocol protocol, String host, int port); QueryType getQueryType(); }### Answer:
@Test public void queryFieldsMatchValues() { MBeanSelector selector = MBeanSelector.create( ImmutableMap.of(MBeanSelector.VALUES, EXPECTED_COMPONENT_VALUES)); assertThat(querySpec(selector), hasJsonPath("$.fields").withValues(EXPECTED_COMPONENT_VALUES)); }
@Test public void whenKeySpecified_isIncludedInQueryFields() { MBeanSelector selector = MBeanSelector.create( ImmutableMap.of(MBeanSelector.VALUES, EXPECTED_COMPONENT_VALUES, MBeanSelector.KEY, "name")); assertThat(querySpec(selector), hasJsonPath("$.fields").includingValues("name")); }
@Test public void whenTypeSpecified_standardFieldTypeIsIncludedInQueryFields() { MBeanSelector selector = MBeanSelector.create( ImmutableMap.of(MBeanSelector.VALUES, EXPECTED_COMPONENT_VALUES, MBeanSelector.TYPE, "OneTypeOnly")); assertThat(querySpec(selector), hasJsonPath("$.fields").includingValues(MBeanSelector.TYPE_FIELD_NAME)); }
@Test public void whenMapHasNestedElements_pathIncludesChildren() { MBeanSelector selector = MBeanSelector.create(ImmutableMap.of("servlets", ImmutableMap.of(MBeanSelector.VALUES, new String[] {"first", "second"}))); assertThat(querySpec(selector), hasJsonPath("$.children.servlets.fields").withValues("first", "second")); } |
### Question:
MBeanSelector { MBeanSelector merge(MBeanSelector selector) { return new MBeanSelector(this, selector); } private MBeanSelector(Map<String, Object> map); private MBeanSelector(MBeanSelector first, MBeanSelector second); static MBeanSelector create(Map<String, Object> map); String getPrintableRequest(); String getRequest(); String getUrl(Protocol protocol, String host, int port); QueryType getQueryType(); }### Answer:
@Test public void whenMergingLeafElements_combineValues() { MBeanSelector selector1 = createLeaf("first", "second"); MBeanSelector selector2 = createLeaf("second", "third"); assertThat(querySpec(selector1.merge(selector2)), hasJsonPath("$.fields").withValues("first", "second", "third")); } |
### Question:
MBeanSelector { boolean mayMergeWith(MBeanSelector other) { if (!Objects.equals(keyName, other.keyName)) return false; if (!Objects.equals(key, other.key)) return false; if (!Objects.equals(type, other.type)) return false; if (!Objects.equals(prefix, other.prefix)) return false; for (String key : nestedSelectors.keySet()) if (other.nestedSelectors.containsKey(key) && !mayMergeCorrespondingChildren(key, other)) return false; return true; } private MBeanSelector(Map<String, Object> map); private MBeanSelector(MBeanSelector first, MBeanSelector second); static MBeanSelector create(Map<String, Object> map); String getPrintableRequest(); String getRequest(); String getUrl(Protocol protocol, String host, int port); QueryType getQueryType(); }### Answer:
@Test public void whenLeafElementsHaveMatchingAttributes_mayCombine() { MBeanSelector selector1 = createLeaf("type:Type1", "prefix:#_", "key:name", "keyName:numbers", "first", "second"); MBeanSelector selector2 = createLeaf("type:Type1", "prefix:#_", "key:name", "keyName:numbers", "second", "third"); assertThat(selector1.mayMergeWith(selector2), is(true)); }
@Test public void whenLeafElementsHaveMisMatchedAttributes_mayNotCombine() { assertThat(createLeaf("keyName:numbers", "first", "second").mayMergeWith(createLeaf("second", "third")), is(false)); assertThat(createLeaf("prefix:_", "key:Name").mayMergeWith(createLeaf("prefix:_", "aValue")), is(false)); assertThat(createLeaf("key:_", "type:Name").mayMergeWith(createLeaf("key:_", "type:color")), is(false)); assertThat(createLeaf("prefix:__").mayMergeWith(createLeaf("prefix:asdf")), is(false)); } |
### Question:
MBeanSelector { public String getUrl(Protocol protocol, String host, int port) { return protocol.format(queryType.getUrlPattern(), host, port); } private MBeanSelector(Map<String, Object> map); private MBeanSelector(MBeanSelector first, MBeanSelector second); static MBeanSelector create(Map<String, Object> map); String getPrintableRequest(); String getRequest(); String getUrl(Protocol protocol, String host, int port); QueryType getQueryType(); }### Answer:
@Test public void domainNameSelector_selectsConfigurationUrl() { assertThat(MBeanSelector.DOMAIN_NAME_SELECTOR.getUrl(Protocol.HTTP, "myhost", 1234), equalTo(String.format(QueryType.CONFIGURATION_URL_PATTERN, "http", "myhost", 1234))); } |
### Question:
MBeanSelector { String[] getValues() { return values == null ? NO_VALUES : values; } private MBeanSelector(Map<String, Object> map); private MBeanSelector(MBeanSelector first, MBeanSelector second); static MBeanSelector create(Map<String, Object> map); String getPrintableRequest(); String getRequest(); String getUrl(Protocol protocol, String host, int port); QueryType getQueryType(); }### Answer:
@Test public void domainNameSelector_requestsName() { assertThat(MBeanSelector.DOMAIN_NAME_SELECTOR.getValues(), arrayContaining("name")); } |
### Question:
MainServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { LiveConfiguration.updateConfiguration(); LiveConfiguration.setServer(req); resp.getOutputStream().println(ServletConstants.PAGE_HEADER); displayMetricsLink(req, resp.getOutputStream()); displayForm(req, resp.getOutputStream()); displayConfiguration(resp.getOutputStream()); resp.getOutputStream().close(); } @Override void init(ServletConfig servletConfig); }### Answer:
@Test public void whenServletPathIsSlash_showSimpleLinkToMetrics() throws Exception { request.setServletPath("/"); servlet.doGet(request, response); assertThat(response.getHtml(), containsString("href=\"metrics\"")); }
@Test public void whenServletPathIsEmpty_showFullLinkToMetrics() throws Exception { request.setServletPath(""); servlet.doGet(request, response); assertThat(response.getHtml(), containsString("href=\"/exporter/metrics\"")); }
@Test public void getRequest_containsConfigurationForm() throws Exception { request.setServletPath("/"); servlet.doGet(request, response); assertThat(response.getHtml(), containsString("form action=\"" + CONFIGURATION_PAGE + "\" method=\"post\" enctype=\"multipart/form-data\"")); }
@Test public void whenServletPathIsEmpty_showFullPathToConfigurationServlet() throws Exception { request.setServletPath(""); servlet.doGet(request, response); assertThat(response.getHtml(), containsString("action=\"/exporter/" + CONFIGURATION_PAGE + "\"")); } |
### Question:
WebClientFactoryImpl implements WebClientFactory { static Constructor<? extends WebClient> getClientConstructor() { for (String className : CLIENT_CLASS_NAMES) { try { return getClientConstructor(className); } catch (NoClassDefFoundError | NoSuchMethodException ignored) { } } throw new IllegalStateException("Unable to select client constructor"); } @Override WebClient createClient(); }### Answer:
@Test public void whenApacheClientDependentClassesFound_selectApacheClient() { assertThat(WebClientFactoryImpl.getClientConstructor().getDeclaringClass(), sameInstance(WebClientImpl.class)); }
@Test public void whenApacheClientDependentClassesMissing_selectJKD8Client() throws NoSuchFieldException { mementos.add(StaticStubSupport.install(WebClientFactoryImpl.class, "loadClientClass", apacheClassesMissing)); assertThat(WebClientFactoryImpl.getClientConstructor().getDeclaringClass(), sameInstance(WebClient8Impl.class)); } |
### Question:
BuildHelperMojo extends AbstractMojo { public void execute() throws MojoExecutionException { Path source = toPath(sourceFile); Path target = toPath(targetFile); try { getLog().info("Copying " + source + " to " + target); executor.copyFile(source, target); } catch (IOException e) { throw new MojoExecutionException("Unable to copy " + source + " to " + target, e); } } void execute(); }### Answer:
@Test public void whenSourceAndTargetAbsolute_useAbsolutePaths() throws Exception { setMojoParameter("sourceFile", "/root/source"); setMojoParameter("targetFile", new File("/root/target")); mojo.execute(); assertThat(copyExecutorStub.sourcePath, equalTo("/root/source")); assertThat(copyExecutorStub.targetPath, equalTo("/root/target")); }
@Test public void whenSourcePathIsRelative_computeAbsoluteRelativeToUserDir() throws Exception { setMojoParameter("sourceFile", "source"); setMojoParameter("targetFile", new File("/root/target")); setMojoParameter("userDir", new File("/root/nested")); mojo.execute(); assertThat(copyExecutorStub.sourcePath, equalTo("/root/nested/source")); assertThat(copyExecutorStub.targetPath, equalTo("/root/target")); }
@Test public void whenSourcePathIsRelativeAndNoUserDir_useSystemProperty() throws Exception { System.setProperty("user.dir", "/user"); setMojoParameter("sourceFile", "source"); setMojoParameter("targetFile", new File("/root/target")); mojo.execute(); assertThat(copyExecutorStub.sourcePath, equalTo("/user/source")); assertThat(copyExecutorStub.targetPath, equalTo("/root/target")); } |
### Question:
ErrorLog { void log(Throwable throwable) { errors.append(toLogMessage(throwable)); for (Throwable cause = throwable.getCause(); cause != null; cause = cause.getCause()) errors.append(System.lineSeparator()).append(" ").append(toLogMessage(cause)); } }### Answer:
@Test public void afterExceptionReported_isAddedToLog() { errorLog.log(new IOException("Unable to read value")); assertThat(errorLog, containsErrors("IOException: Unable to read value")); }
@Test public void afterExceptionWithNoMessageReported_logSimpleNameOnly() { errorLog.log(new IOException()); assertThat(errorLog, containsErrors("IOException")); }
@Test public void afterExceptionWithNestedThrowableReported_addToLog() { errorLog.log(new IOException("Unable to read value", new RuntimeException("has impossible format"))); assertThat(errorLog, containsErrors("IOException: Unable to read value", " RuntimeException: has impossible format")); } |
### Question:
ConfigurationUpdaterImpl implements ConfigurationUpdater { @Override public long getLatestConfigurationTimestamp() { getLatestConfiguration(); return latest == null ? 0 : latest.getTimestamp(); } ConfigurationUpdaterImpl(QuerySyncConfiguration syncConfiguration, ErrorLog errorLog); ConfigurationUpdaterImpl(Clock clock, WebClientFactory factory); @Override long getLatestConfigurationTimestamp(); @Override void shareConfiguration(String configuration); @Override ConfigurationUpdate getUpdate(); }### Answer:
@Test public void whenUnableToReachServer_returnedTimestampIsZero() { factory.throwWebClientException(new WebClientException()); assertThat(impl.getLatestConfigurationTimestamp(), equalTo(0L)); }
@Test public void extractTimestampFromReply() { factory.addJsonResponse(RESPONSE_1); assertThat(impl.getLatestConfigurationTimestamp(), equalTo(TIMESTAMP_1)); }
@Test public void whenAskedForConfigurationWithinUpdateInterval_returnCachedValue() { clock.setCurrentMsec(0); factory.addJsonResponse(RESPONSE_1); impl.getLatestConfigurationTimestamp(); clock.incrementSeconds(REFRESH_INTERVAL / 2); factory.addJsonResponse(RESPONSE_2); assertThat(impl.getLatestConfigurationTimestamp(), equalTo(TIMESTAMP_1)); }
@Test public void whenAskedForConfigurationAfterUpdateInterval_returnNewValue() { clock.setCurrentMsec(0); factory.addJsonResponse(RESPONSE_1); impl.getLatestConfigurationTimestamp(); clock.incrementSeconds(REFRESH_INTERVAL); factory.addJsonResponse(RESPONSE_2); assertThat(impl.getLatestConfigurationTimestamp(), equalTo(TIMESTAMP_2)); } |
### Question:
ConfigurationUpdaterImpl implements ConfigurationUpdater { @Override public ConfigurationUpdate getUpdate() { getLatestConfiguration(); return latest; } ConfigurationUpdaterImpl(QuerySyncConfiguration syncConfiguration, ErrorLog errorLog); ConfigurationUpdaterImpl(Clock clock, WebClientFactory factory); @Override long getLatestConfigurationTimestamp(); @Override void shareConfiguration(String configuration); @Override ConfigurationUpdate getUpdate(); }### Answer:
@Test public void afterRetrieveUpdate_returnIt() { factory.addJsonResponse(RESPONSE_1); assertThat(impl.getUpdate().getConfiguration(), equalTo(CONFIGURATION_1)); } |
### Question:
ConfigurationUpdaterImpl implements ConfigurationUpdater { @Override public void shareConfiguration(String configuration) { try { WebClient client = factory.createClient().withUrl(repeaterUrl); client.doPutRequest(new Gson().toJson(createUpdate(configuration))); } catch (IOException | WebClientException e) { errorLog.log(e); } } ConfigurationUpdaterImpl(QuerySyncConfiguration syncConfiguration, ErrorLog errorLog); ConfigurationUpdaterImpl(Clock clock, WebClientFactory factory); @Override long getLatestConfigurationTimestamp(); @Override void shareConfiguration(String configuration); @Override ConfigurationUpdate getUpdate(); }### Answer:
@Test public void onShareConfiguration_sendsConfigurationInJsonObject() { impl.shareConfiguration(CONFIGURATION_1); assertThat(factory.getPostedString(), hasJsonPath("$.configuration").withValue(CONFIGURATION_1)); }
@Test public void onShareConfiguration_sendsTimestampInJsonObject() { clock.setCurrentMsec(23); impl.shareConfiguration(CONFIGURATION_1); assertThat(factory.getPostedString(), hasJsonPath("$.timestamp").withValue(23)); } |
### Question:
MultipartContentParser implements ParserActions { String getBoundary() { return boundary; } MultipartContentParser(String contentType); ParserState getState(); @Override boolean isStart(String line); @Override boolean isEnd(String line); @Override ParserState closeItem(ParserState state); @Override ParserState addHeader(String line); @Override ParserState addDataLine(String line); }### Answer:
@Test public void whenCreated_boundaryIsDefined() { assertThat(parser.getBoundary(), equalTo(BOUNDARY)); } |
### Question:
MultipartContentParser implements ParserActions { public ParserState getState() { return state; } MultipartContentParser(String contentType); ParserState getState(); @Override boolean isStart(String line); @Override boolean isEnd(String line); @Override ParserState closeItem(ParserState state); @Override ParserState addHeader(String line); @Override ParserState addDataLine(String line); }### Answer:
@Test public void parseInitialState() { assertThat(parser.getState(), sameInstance(ParserState.INITIAL)); } |
### Question:
MultipartContentParser implements ParserActions { MultipartItem getCurrentItem() { if (currentItem == null) currentItem = new MultipartItemImpl(); return currentItem; } MultipartContentParser(String contentType); ParserState getState(); @Override boolean isStart(String line); @Override boolean isEnd(String line); @Override ParserState closeItem(ParserState state); @Override ParserState addHeader(String line); @Override ParserState addDataLine(String line); }### Answer:
@Test public void WhenNoContentReceived_itemHasEmptyData() { assertThat(parser.getCurrentItem().getString(), equalTo("")); } |
### Question:
MultipartContentParser implements ParserActions { static List<MultipartItem> parse(HttpServletRequest request) throws ServletException { try { final MultipartContentParser parser = new MultipartContentParser(request.getContentType()); new BufferedReader(new InputStreamReader(request.getInputStream())).lines().forEach(parser::process); return parser.getItems(); } catch (IOException e) { throw new ServletException("Unable to parse request", e); } } MultipartContentParser(String contentType); ParserState getState(); @Override boolean isStart(String line); @Override boolean isEnd(String line); @Override ParserState closeItem(ParserState state); @Override ParserState addHeader(String line); @Override ParserState addDataLine(String line); }### Answer:
@Test(expected = ServletException.class) public void whenMultipartRequestNotParseable_throwException() throws ServletException { HttpServletRequest request = HttpServletRequestStub.createPostRequest(); MultipartContentParser.parse(request); } |
### Question:
UrlBuilder { public String createUrl(String urlPattern) { return protocol.format(urlPattern, host, selectPort()); } UrlBuilder(HttpServletRequest request, Integer restPort); static void clearHistory(); String createUrl(String urlPattern); void reportSuccess(); void reportFailure(WebClientException connectionException); }### Answer:
@Test public void whenNoRestPortDefined_generateUrl() { UrlBuilder builder = new UrlBuilder(request, null); assertThat(builder.createUrl(URL_PATTERN), equalTo(String.format(URL_PATTERN, "http", "localhost", LOCAL_PORT))); }
@Test public void whenRestPortDefined_generateUrlWithRestPort() { UrlBuilder builder = new UrlBuilder(request, REST_PORT); assertThat(builder.createUrl(URL_PATTERN), equalTo(String.format(URL_PATTERN, "http", "localhost", REST_PORT))); } |
### Question:
MessagesServlet extends HttpServlet { static List<String> getMessages() { return new ArrayList<>(messages); } }### Answer:
@Test public void afterMaximumExchangesAdded_retrieveAllExchanges() { IntStream.rangeClosed(1, MAX_EXCHANGES).forEach(this::addTestExchange); assertThat(MessagesServlet.getMessages(), contains(getExchangeMatchers(1, MAX_EXCHANGES))); }
@Test public void afterMoreThanMaximumExchangesAdded_retrieveLastMExchanges() { IntStream.rangeClosed(1, MAX_EXCHANGES+EXCESS_EXCHANGES).forEach(this::addTestExchange); assertThat(MessagesServlet.getMessages(), contains(getExchangeMatchers(EXCESS_EXCHANGES+1, MAX_EXCHANGES+EXCESS_EXCHANGES))); } |
### Question:
MessagesServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { try(ServletOutputStream out = resp.getOutputStream()) { for (String message : messages) out.println(message); } } }### Answer:
@Test public void whenServletInvoked_responseDisplaysRecentExchanges() throws IOException { IntStream.rangeClosed(1, MAX_EXCHANGES).forEach(this::addTestExchange); servlet.doGet(request, response); assertThat(response.getHtml(), containsString("request 4")); } |
### Question:
LiveConfiguration { static boolean hasQueries() { return getConfig() != null && getConfig().getQueries().length > 0; } }### Answer:
@Test public void whenInitNotCalled_haveNoQueries() { assertThat(LiveConfiguration.hasQueries(), is(false)); } |
### Question:
LiveConfiguration { static void init(ServletConfig servletConfig) { if (timestamp != null) return; InputStream configurationFile = getConfigurationFile(servletConfig); initialize(Optional.ofNullable(configurationFile) .map(ExporterConfig::loadConfig) .orElse(ExporterConfig.createEmptyConfig())); } }### Answer:
@Test public void whenConfigurationSpecifiesSynchronization_installHttpBasedUpdater() throws Exception { init(CONFIGURATION_WITH_SYNC); assertThat(getConfigurationUpdater(), instanceOf(ConfigurationUpdaterImpl.class)); }
@Test public void whenConfigurationSpecifiesSynchronization_configureUpdater() throws Exception { init(CONFIGURATION_WITH_SYNC); ConfigurationUpdaterImpl configurationUpdater = (ConfigurationUpdaterImpl) getConfigurationUpdater(); assertThat(configurationUpdater.getRepeaterUrl(), equalTo(SYNC_URL)); assertThat(configurationUpdater.getRefreshInterval(), equalTo(REFRESH_INTERVAL)); } |
### Question:
LogServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String errors = LiveConfiguration.getErrors(); if (errors == null || errors.trim().length() == 0) resp.getOutputStream().println("No errors reported."); else resp.getOutputStream().println("<blockquote>" + errors + "</blockquote>"); resp.getOutputStream().close(); } }### Answer:
@Test public void whenNoErrorsReported_saySo() throws ServletException, IOException { servlet.doGet(request, response); assertThat(response.getHtml(), containsString("No errors reported.")); }
@Test public void whenErrorsReported_listThem() throws NoSuchFieldException, ServletException, IOException { ErrorLog errorLog = new ErrorLog(); mementos.add(StaticStubSupport.install(LiveConfiguration.class, "errorLog", errorLog)); errorLog.log(new WebClientException("Unable to reach server")); servlet.doGet(request, response); assertThat(response.getHtml(), containsString("WebClientException: Unable to reach server")); } |
### Question:
MetricsStream extends PrintStream { void printMetric(String name, Object value) { print(name + " " + value + '\n'); scrapeCount++; } MetricsStream(HttpServletRequest request, OutputStream outputStream); MetricsStream(HttpServletRequest request, OutputStream outputStream, PerformanceProbe performanceProbe); }### Answer:
@Test public void whenMetricsPrinted_eachHasItsOwnLineSeparatedByCarriageReturns() { metrics.printMetric("a", 12); metrics.printMetric("b", 120); metrics.printMetric("c", 0); assertThat(getPrintedMetricValues(), hasItems("12", "120", "0", "3")); }
@Test public void whenMetricsPrintedOnWindows_eachHasItsOwnLineSeparatedByCarriageReturns() throws NoSuchFieldException { simulateWindows(); metrics.printMetric("a", 12); metrics.printMetric("b", 120); metrics.printMetric("c", 0); assertThat(getPrintedMetricValues(), hasItems("12", "120", "0", "3")); }
@Test public void afterMetricsScraped_reportScrapedCount() { metrics.printMetric("a", 12); metrics.printMetric("b", 120); metrics.printMetric("c", 0); assertThat(getPrintedMetrics(), containsString("wls_scrape_mbeans_count_total{instance=\"wlshost:7201\"} 3")); } |
### Question:
Header { public String getName() { return name; } Header(String headerLine); String getValue(); String getValue(String key); String getName(); static final String QUOTE; }### Answer:
@Test public void fetchHeaderName() { Header header = new Header("Content-type: text/plain"); assertThat(header.getName(), equalTo("Content-type")); } |
### Question:
Header { public String getValue() { return value; } Header(String headerLine); String getValue(); String getValue(String key); String getName(); static final String QUOTE; }### Answer:
@Test public void fetchMainValue() { Header header = new Header("Content-type: text/plain"); assertThat(header.getValue(), equalTo("text/plain")); }
@Test public void whenSeparatorPresent_truncateValue() { Header header = new Header("Content-type: text/plain; more stuff"); assertThat(header.getValue(), equalTo("text/plain")); }
@Test public void whenParametersPresent_fetchValues() { Header header = new Header("Content-disposition: form-data; name=\"file1\"; filename=\"a.txt\""); assertThat(header.getValue(), equalTo("form-data")); assertThat(header.getValue("name"), equalTo("file1")); assertThat(header.getValue("filename"), equalTo("a.txt")); } |
### Question:
MetricsScraper { Map<String, Object> scrape(MBeanSelector selector, JsonObject response) { metrics = new HashMap<>(); scrapeItem(response, selector, globalQualifiers); return metrics; } MetricsScraper(String globalQualifiers); }### Answer:
@Test public void whenResponseLacksServerRuntimes_generateEmptyMetrics() { assertThat(scraper.scrape(MBeanSelector.create(getFullMap()), getJsonResponse("{}")), anEmptyMap()); }
@Test public void generateFromFullResponse() { Map<String, Object> metrics = scraper.scrape(MBeanSelector.create(getFullMap()), getJsonResponse(RESPONSE)); assertThat(metrics, hasMetric("component_deploymentState{application=\"weblogic\",component=\"ejb30_weblogic\"}", 2)); assertThat(metrics, hasMetric("servlet_invocationTotalCount{application=\"weblogic\",component=\"ejb30_weblogic\",servletName=\"JspServlet\"}", 0)); }
@Test public void whenTypeNotSpecified_includeAllComponents() { Map<String, Object> metrics = scraper.scrape(MBeanSelector.create(getFullMap()), getJsonResponse(RESPONSE)); assertThat(metrics, hasMetric("component_deploymentState{application=\"weblogic\",component=\"ejb30_weblogic\"}", 2)); assertThat(metrics, hasMetric("component_deploymentState{application=\"mbeans\",component=\"EjbStatusBean\"}", 2)); }
@Test public void selectOnlyWebApps() { componentMap.put(MBeanSelector.TYPE, "WebAppComponentRuntime"); Map<String, Object> metrics = scraper.scrape(MBeanSelector.create(getFullMap()), getJsonResponse(RESPONSE)); assertThat(metrics, hasMetric("component_deploymentState{application=\"weblogic\",component=\"ejb30_weblogic\"}", 2)); assertThat(metrics, not(hasMetric("component_deploymentState{application=\"mbeans\",component=\"EjbStatusBean\"}", 2))); }
@Test public void whenValuesAtTopLevel_scrapeThem() { final MBeanSelector selector = MBeanSelector.create(getMetricsMap()); final JsonObject jsonResponse = getJsonResponse(METRICS_RESPONSE); Map<String, Object> metrics = scraper.scrape(selector, jsonResponse); assertThat(metrics, hasMetric("heapSizeCurrent", 123456)); assertThat(metrics, hasMetric("processCpuLoad", .0028)); } |
### Question:
ExporterConfig { public static ExporterConfig loadConfig(InputStream inputStream) { try { return loadConfig(asMap(new Yaml().load(inputStream))); } catch (ScannerException e) { throw new YamlParserException(e); } } private ExporterConfig(Map<String, Object> yaml); static ExporterConfig createEmptyConfig(); static ExporterConfig loadConfig(InputStream inputStream); Map<String, Object> scrapeMetrics(MBeanSelector selector, JsonObject response); MBeanSelector[] getEffectiveQueries(); MBeanSelector[] getQueries(); static ExporterConfig loadConfig(Map<String, Object> yamlConfig); QuerySyncConfiguration getQuerySyncConfiguration(); Integer getRestPort(); void append(ExporterConfig config2); void replace(ExporterConfig config2); @Override String toString(); }### Answer:
@Test public void whenYamlConfigEmpty_returnNonNullConfiguration() { assertThat(ExporterConfig.loadConfig(NULL_MAP), notNullValue()); } |
### Question:
ExporterConfig { public MBeanSelector[] getEffectiveQueries() { if (queries == null) return NO_QUERIES; return withPossibleDomainNameQuery(Arrays.stream(queries)).toArray(MBeanSelector[]::new); } private ExporterConfig(Map<String, Object> yaml); static ExporterConfig createEmptyConfig(); static ExporterConfig loadConfig(InputStream inputStream); Map<String, Object> scrapeMetrics(MBeanSelector selector, JsonObject response); MBeanSelector[] getEffectiveQueries(); MBeanSelector[] getQueries(); static ExporterConfig loadConfig(Map<String, Object> yamlConfig); QuerySyncConfiguration getQuerySyncConfiguration(); Integer getRestPort(); void append(ExporterConfig config2); void replace(ExporterConfig config2); @Override String toString(); }### Answer:
@Test public void whenDomainQualifierNotSpecified_dontModifyQueries() { ExporterConfig config = loadFromString(SERVLET_CONFIG); MBeanSelector[] queries = config.getEffectiveQueries(); assertThat(queries, arrayWithSize(1)); assertThat(queries[0].getUrl(Protocol.HTTP, "myhost", 1234), equalTo(String.format(QueryType.RUNTIME_URL_PATTERN, "http", "myhost", 1234))); }
@Test public void whenSpecified_prependConfigurationQuery() { ExporterConfig config = loadFromString(DOMAIN_QUALIFIER_CONFIG); MBeanSelector[] queries = config.getEffectiveQueries(); assertThat(queries, arrayWithSize(2)); assertThat(queries[0], sameInstance(MBeanSelector.DOMAIN_NAME_SELECTOR)); assertThat(queries[1].getUrl(Protocol.HTTP, "myhost", 1234), equalTo(String.format(QueryType.RUNTIME_URL_PATTERN, "http", "myhost", 1234))); } |
### Question:
ExporterConfig { public QuerySyncConfiguration getQuerySyncConfiguration() { return querySyncConfiguration; } private ExporterConfig(Map<String, Object> yaml); static ExporterConfig createEmptyConfig(); static ExporterConfig loadConfig(InputStream inputStream); Map<String, Object> scrapeMetrics(MBeanSelector selector, JsonObject response); MBeanSelector[] getEffectiveQueries(); MBeanSelector[] getQueries(); static ExporterConfig loadConfig(Map<String, Object> yamlConfig); QuerySyncConfiguration getQuerySyncConfiguration(); Integer getRestPort(); void append(ExporterConfig config2); void replace(ExporterConfig config2); @Override String toString(); }### Answer:
@Test public void whenQuerySyncDefined_returnIt() { ExporterConfig config = loadFromString(CONFIG_WITH_SYNC_SPEC); final QuerySyncConfiguration syncConfiguration = config.getQuerySyncConfiguration(); assertThat(syncConfiguration.getUrl(), equalTo("http: assertThat(syncConfiguration.getRefreshInterval(), equalTo(3L)); }
@Test public void whenQuerySyncDefinedWithoutInterval_useDefault() { ExporterConfig config = loadFromString(CONFIG_WITH_SYNC_URL); final QuerySyncConfiguration syncConfiguration = config.getQuerySyncConfiguration(); assertThat(syncConfiguration.getUrl(), equalTo("http: assertThat(syncConfiguration.getRefreshInterval(), equalTo(10L)); } |
### Question:
AuthUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = repository.findOne(username); if (user == null) { throw new UsernameNotFoundException(username); } log.debug(" User from username ", user.toString()); return user; } @Override UserDetails loadUserByUsername(String username); }### Answer:
@Test public void getUsernameWhenUserExists() { final User user = new User(); when(repository.findOne(any())).thenReturn(user); UserDetails loaded = service.loadUserByUsername("Username"); assertEquals(user, loaded); }
@Test(expected = UsernameNotFoundException.class) public void getUsernameWhenUserNotExists() { service.loadUserByUsername("Username"); } |
### Question:
UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @DS("master") @Override public void addUser(User user) { baseMapper.insert(user); } @DS("master") @Override void addUser(User user); }### Answer:
@Test public void addUser() { User userMaster = User.builder().name("主库添加").age(20).build(); userService.addUser(userMaster); User userSlave = User.builder().name("从库添加").age(20).build(); userService.save(userSlave); } |
### Question:
RedisUtil { public PageResult<String> findKeysForPage(String patternKey, int currentPage, int pageSize) { ScanOptions options = ScanOptions.scanOptions() .match(patternKey) .build(); RedisConnectionFactory factory = stringRedisTemplate.getConnectionFactory(); RedisConnection rc = factory.getConnection(); Cursor<byte[]> cursor = rc.scan(options); List<String> result = Lists.newArrayList(); long tmpIndex = 0; int startIndex = (currentPage - 1) * pageSize; int end = currentPage * pageSize; while (cursor.hasNext()) { String key = new String(cursor.next()); if (tmpIndex >= startIndex && tmpIndex < end) { result.add(key); } tmpIndex++; } try { cursor.close(); RedisConnectionUtils.releaseConnection(rc, factory); } catch (Exception e) { log.warn("Redis连接关闭异常,", e); } return new PageResult<>(result, tmpIndex); } PageResult<String> findKeysForPage(String patternKey, int currentPage, int pageSize); void delete(String key); void delete(Collection<String> keys); }### Answer:
@Test public void findKeysForPage() { PageResult pageResult = redisUtil.findKeysForPage(Consts.REDIS_JWT_KEY_PREFIX + Consts.SYMBOL_STAR, 2, 1); log.info("【pageResult】= {}", JSONUtil.toJsonStr(pageResult)); } |
### Question:
SelectIndexDataActivity extends BaseActivity { public static int partition(int[] a, int p, int r) { int x = a[r]; int i = p - 1; for (int j = p; j < r; j++) { if (a[j] <= x) { i = i + 1; swap(a, i, j); System.out.println("交换=" + "i=" + i + Arrays.toString(a)); }else{ System.out.println("未交换=" + "i=" + i + Arrays.toString(a)); } } swap(a, i + 1, r); System.out.println("结果=" + "i=" + i + Arrays.toString(a)); return i + 1; } static int partition(int[] a, int p, int r); static int randomizedSelect(int[] a, int p, int r, int i); }### Answer:
@Test public void testPartition() throws Exception{ int a[]={2,5,3,0,2,3,0,3}; int b[]={9,6,7,3,8,2,4,5}; int c[]={1,2,3,4,5,6,7,9}; int result = selectIndexDataActivity.partition(b,0,b.length-1); System.out.println("result =" + result); Random random = new Random(); } |
### Question:
SelectIndexDataActivity extends BaseActivity { public static int randomizedSelect(int[] a, int p, int r, int i) { if (p == r) { return a[p]; } int q = randomizedPartition(a, p, r); int k = q - p + 1; if (i == k) { return a[q]; } else if (i < k) { return randomizedSelect(a, p, q - 1, i); } else { return randomizedSelect(a, q + 1, r, i - k); } } static int partition(int[] a, int p, int r); static int randomizedSelect(int[] a, int p, int r, int i); }### Answer:
@Test public void testSort() throws Exception { int a[]={2,5,3,0,2,3,0,3}; int result= selectIndexDataActivity.randomizedSelect(a,0,a.length-1,3); System.out.println("快速选择算法求出的,第"+3+"个最小数是:"+result); assertEquals(2,result); } |
### Question:
PermissiveURI { public static URI create(String s) { return URI.create(s.replace(" ", "%20")); } static URI create(String s); }### Answer:
@Test public void simple() throws Exception { URI i = PermissiveURI.create("file:/funk"); assertEquals("/funk", Paths.get(i).toString()); }
@Test public void undone() throws Exception { URI i = PermissiveURI.create("file:/file important"); assertEquals("/file important", Paths.get(i).toString()); } |
### Question:
AddAnimalPresenter extends BasePresenter<AddAnimalContract.View> implements AddAnimalContract.Presenter<AddAnimalContract.View> { @Override public void addNewDog(DogFirebase dogFirebase) { firebaseRepository.addNew(dogFirebase); } AddAnimalPresenter(Repository.Firebase<DogFirebase> repository); @Override String generateUniqueID(); @Override void addNewDog(DogFirebase dogFirebase); }### Answer:
@Test public void should_be_one_dog_after_save() { InMemoryDogRepository repository = InMemoryDogRepository.getInstance(); AddAnimalPresenter presenter = new AddAnimalPresenter(repository); presenter.attachView(mockView); presenter.addNewDog(new DogFirebase()); assertThat(repository.getCachedDogs().size(), is(1)); } |
### Question:
DeleteMessage extends UpdatableChatRequest { public static DeleteMessageBuilder forMessage(Message<?> message) { Objects.requireNonNull(message, "message cannot be null"); return builder() .chatId(message.getChat().getChatId()) .messageId(message.getMessageId()); } @Builder DeleteMessage(Consumer<TelegramException> errorHandler, Runnable callback, ChatId chatId, int messageId); static DeleteMessageBuilder forMessage(Message<?> message); }### Answer:
@Test public void toDeleteMessageRequest_output_same_as_forMessage() { DeleteMessage expected = DeleteMessage.forMessage(messageMock).build(); DeleteMessage actual = messageMock.toDeleteRequest().build(); assertEquals(expected, actual); } |
### Question:
EditMessageMedia extends SendableInputFileInlineRequest<Message> { public static EditMessageMediaBuilder forMessage(AudioMessage message) { Objects.requireNonNull(message, "audio message cannot be null"); return builder() .chatId(message.getChat().getChatId()) .messageId(message.getMessageId()); } @Builder protected EditMessageMedia(Consumer<Message> callback, Consumer<TelegramException> errorHandler,
ChatId chatId, Integer messageId, String inlineMessageId, InputMedia media); @Override List<InputFile> getInputFiles(); static EditMessageMediaBuilder forMessage(AudioMessage message); static EditMessageMediaBuilder forMessage(DocumentMessage message); static EditMessageMediaBuilder forMessage(PhotoMessage message); static EditMessageMediaBuilder forMessage(VideoMessage message); static EditMessageMediaBuilder forInlineMessage(String inlineMessageId); }### Answer:
@Test public void toEditMediaRequest_output_same_as_forMessage_audio() { EditMessageMedia expected = EditMessageMedia.forMessage(audioMessageMock).build(); EditMessageMedia actual = audioMessageMock.toEditMediaRequest().build(); assertEquals(expected, actual); }
@Test public void toEditMediaRequest_output_same_as_forMessage_document() { EditMessageMedia expected = EditMessageMedia.forMessage(documentMessageMock).build(); EditMessageMedia actual = documentMessageMock.toEditMediaRequest().build(); assertEquals(expected, actual); }
@Test public void toEditMediaRequest_output_same_as_forMessage_photo() { EditMessageMedia expected = EditMessageMedia.forMessage(photoMessageMock).build(); EditMessageMedia actual = photoMessageMock.toEditMediaRequest().build(); assertEquals(expected, actual); }
@Test public void toEditMediaRequest_output_same_as_forMessage_video() { EditMessageMedia expected = EditMessageMedia.forMessage(videoMessageMock).build(); EditMessageMedia actual = videoMessageMock.toEditMediaRequest().build(); assertEquals(expected, actual); } |
### Question:
EditMessageMedia extends SendableInputFileInlineRequest<Message> { public static EditMessageMediaBuilder forInlineMessage(String inlineMessageId) { Objects.requireNonNull(inlineMessageId, "inline message ID cannot be null"); return builder().inlineMessageId(inlineMessageId); } @Builder protected EditMessageMedia(Consumer<Message> callback, Consumer<TelegramException> errorHandler,
ChatId chatId, Integer messageId, String inlineMessageId, InputMedia media); @Override List<InputFile> getInputFiles(); static EditMessageMediaBuilder forMessage(AudioMessage message); static EditMessageMediaBuilder forMessage(DocumentMessage message); static EditMessageMediaBuilder forMessage(PhotoMessage message); static EditMessageMediaBuilder forMessage(VideoMessage message); static EditMessageMediaBuilder forInlineMessage(String inlineMessageId); }### Answer:
@Test public void builds_with_correct_inlineid() { EditMessageMedia request = EditMessageMedia.forInlineMessage(INLINE_ID).build(); assertNull(request.getChatId()); assertNull(request.getMessageId()); assertEquals(INLINE_ID, request.getInlineMessageId()); } |
### Question:
EditMessageReplyMarkup extends EditMessageRequest<Message> { public static EditMessageReplyMarkupBuilder forMessage(Message<?> message) { Objects.requireNonNull(message, "message cannot be null"); return builder() .chatId(message.getChat().getChatId()) .messageId(message.getMessageId()); } @Builder EditMessageReplyMarkup(Consumer<Message> callback, Consumer<TelegramException> errorHandler, ChatId chatId, int messageId, String inlineMessageId, ReplyMarkup replyMarkup); static EditMessageReplyMarkupBuilder forMessage(Message<?> message); static EditMessageReplyMarkupBuilder forInlineMessage(String inlineMessageId); }### Answer:
@Test public void toEditTextRequest_output_same_as_forMessage() { EditMessageReplyMarkup expected = EditMessageReplyMarkup.forMessage(messageMock).build(); EditMessageReplyMarkup actual = messageMock.toEditReplyMarkupRequest().build(); assertEquals(expected, actual); } |
### Question:
EditMessageReplyMarkup extends EditMessageRequest<Message> { public static EditMessageReplyMarkupBuilder forInlineMessage(String inlineMessageId) { Objects.requireNonNull(inlineMessageId, "inline message ID cannot be null"); return builder().inlineMessageId(inlineMessageId); } @Builder EditMessageReplyMarkup(Consumer<Message> callback, Consumer<TelegramException> errorHandler, ChatId chatId, int messageId, String inlineMessageId, ReplyMarkup replyMarkup); static EditMessageReplyMarkupBuilder forMessage(Message<?> message); static EditMessageReplyMarkupBuilder forInlineMessage(String inlineMessageId); }### Answer:
@Test public void builds_with_correct_inlineid() { EditMessageReplyMarkup request = EditMessageReplyMarkup.forInlineMessage(INLINE_ID).build(); assertNull(request.getChatId()); assertEquals(0, request.getMessageId()); assertEquals(INLINE_ID, request.getInlineMessageId()); } |
### Question:
EditTextMessage extends EditMessageRequest<TextMessage> { public static EditTextMessageBuilder forMessage(TextMessage message) { Objects.requireNonNull(message, "text message cannot be null"); return builder() .chatId(message.getChat().getChatId()) .messageId(message.getMessageId()); } @Builder EditTextMessage(Consumer<TextMessage> callback, Consumer<TelegramException> errorHandler, ChatId chatId, int messageId, String inlineMessageId, ReplyMarkup replyMarkup, String text, ParseMode parseMode, boolean disableWebPagePreview); static EditTextMessageBuilder forMessage(TextMessage message); static EditTextMessageBuilder forMessage(GameMessage message); static EditTextMessageBuilder forInlineMessage(String inlineMessageId); }### Answer:
@Test public void toEditTextRequest_output_same_as_forMessage_text() { EditTextMessage expected = EditTextMessage.forMessage(textMessageMock).build(); EditTextMessage actual = textMessageMock.toEditTextRequest().build(); assertEquals(expected, actual); }
@Test public void toEditTextRequest_output_same_as_forMessage_game() { EditTextMessage expected = EditTextMessage.forMessage(gameMessageMock).build(); EditTextMessage actual = gameMessageMock.toEditTextRequest().build(); assertEquals(expected, actual); } |
### Question:
EditTextMessage extends EditMessageRequest<TextMessage> { public static EditTextMessageBuilder forInlineMessage(String inlineMessageId) { Objects.requireNonNull(inlineMessageId, "inline message ID cannot be null"); return builder().inlineMessageId(inlineMessageId); } @Builder EditTextMessage(Consumer<TextMessage> callback, Consumer<TelegramException> errorHandler, ChatId chatId, int messageId, String inlineMessageId, ReplyMarkup replyMarkup, String text, ParseMode parseMode, boolean disableWebPagePreview); static EditTextMessageBuilder forMessage(TextMessage message); static EditTextMessageBuilder forMessage(GameMessage message); static EditTextMessageBuilder forInlineMessage(String inlineMessageId); }### Answer:
@Test public void builds_with_correct_inlineid() { EditTextMessage request = EditTextMessage.forInlineMessage(INLINE_ID).build(); assertNull(request.getChatId()); assertEquals(0, request.getMessageId()); assertEquals(INLINE_ID, request.getInlineMessageId()); } |
### Question:
EditMessageLiveLocation extends SendableInlineRequest<Message> { public static EditMessageLiveLocationBuilder forMessage(LocationMessage message) { Objects.requireNonNull(message, "message cannot be null"); return builder() .chatId(message.getChat().getChatId()) .messageId(message.getMessageId()); } @Builder protected EditMessageLiveLocation(Consumer<Message> callback, Consumer<TelegramException> errorHandler, ChatId chatId, Integer messageId, String inlineMessageId, Float latitude, Float longitude, Integer livePeriod); static EditMessageLiveLocationBuilder forMessage(LocationMessage message); static EditMessageLiveLocationBuilder forInlineMessage(String inlineMessageId); }### Answer:
@Test public void toEditLiveLocationRequest_output_same_as_forMessage() { EditMessageLiveLocation expected = EditMessageLiveLocation.forMessage(locationMessageMock).build(); EditMessageLiveLocation actual = locationMessageMock.toEditLiveLocationRequest().build(); assertEquals(expected, actual); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.