method2testcases
stringlengths
118
3.08k
### Question: ThreadUtil { public static boolean isMainThread() { return Looper.myLooper() == Looper.getMainLooper(); } static void setNeedDetectRunningThread(boolean sNeedDetect); static void setMainScheduler(Scheduler sMainScheduler); static void setComputationScheduler(Scheduler sComputationScheduler); static Scheduler mainScheduler(); static Scheduler computationScheduler(); static boolean isMainThread(); static void ensureMainThread(String tag); static void ensureMainThread(); static void ensureWorkThread(String tag); static void ensureWorkThread(); static @NonNull Handler createIfNotExistHandler(String tag); static @Nullable Handler obtainHandler(String tag); static void destoryHandler(String tag); static Executor sMain; }### Answer: @Test public void isMainThread() { boolean isMainThread = ThreadUtil.isMainThread(); assertTrue(isMainThread); final boolean[] isMainThreadInThread = {true}; Thread thread = new Thread(new Runnable() { @Override public void run() { isMainThreadInThread[0] = ThreadUtil.isMainThread(); } }); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } assertFalse(isMainThreadInThread[0]); }
### Question: ProcessUtils { public static String myProcessName(Context context) { if (sProcessName != null) { return sProcessName; } synchronized (sNameLock) { if (sProcessName != null) { return sProcessName; } sProcessName = obtainProcessName(context); return sProcessName; } } static String myProcessName(Context context); static int getCurrentPid(); static int getCurrentUid(); static boolean isMainProcess(Application application); }### Answer: @Test public void myProcessName() { String myProcessName = ProcessUtils.myProcessName(ApplicationProvider.getApplicationContext()); Assert.assertEquals("cn.hikyson.godeye.core", myProcessName); String myProcessName2 = ProcessUtils.myProcessName(ApplicationProvider.getApplicationContext()); Assert.assertEquals("cn.hikyson.godeye.core", myProcessName2); }
### Question: ProcessUtils { public static int getCurrentPid() { return android.os.Process.myPid(); } static String myProcessName(Context context); static int getCurrentPid(); static int getCurrentUid(); static boolean isMainProcess(Application application); }### Answer: @Test public void getCurrentPid() { int pid = ProcessUtils.getCurrentPid(); }
### Question: ProcessUtils { public static int getCurrentUid() { return android.os.Process.myUid(); } static String myProcessName(Context context); static int getCurrentPid(); static int getCurrentUid(); static boolean isMainProcess(Application application); }### Answer: @Test public void getCurrentUid() { int uid = ProcessUtils.getCurrentUid(); }
### Question: ProcessUtils { public static boolean isMainProcess(Application application) { int pid = android.os.Process.myPid(); String processName = ""; ActivityManager manager = (ActivityManager) application.getSystemService (Context.ACTIVITY_SERVICE); for (ActivityManager.RunningAppProcessInfo process : manager.getRunningAppProcesses()) { if (process.pid == pid) { processName = process.processName; } } return application.getPackageName().equals(processName); } static String myProcessName(Context context); static int getCurrentPid(); static int getCurrentUid(); static boolean isMainProcess(Application application); }### Answer: @Test public void isMainProcess() { boolean isMainProcess = ProcessUtils.isMainProcess(ApplicationProvider.getApplicationContext()); Assert.assertTrue(isMainProcess); }
### Question: StacktraceUtil { public static List<String> stackTraceToStringArray(List<StackTraceElement> stackTraceElements) { List<String> stackList = new ArrayList<>(); for (StackTraceElement traceElement : stackTraceElements) { stackList.add(String.valueOf(traceElement)); } return stackList; } static List<String> stackTraceToStringArray(List<StackTraceElement> stackTraceElements); static List<String> getStackTraceOfThread(Thread thread); static String getStringOfThrowable(Throwable throwable); }### Answer: @Test public void stackTraceToStringArray() { List<String> stackTrace = StacktraceUtil.stackTraceToStringArray(Arrays.asList(Thread.currentThread().getStackTrace())); Assert.assertTrue(String.valueOf(stackTrace).contains(StacktraceUtilTest.class.getSimpleName())); }
### Question: StacktraceUtil { public static List<String> getStackTraceOfThread(Thread thread) { StackTraceElement[] stackTraceElements = thread.getStackTrace(); return stackTraceToStringArray(Arrays.asList(stackTraceElements)); } static List<String> stackTraceToStringArray(List<StackTraceElement> stackTraceElements); static List<String> getStackTraceOfThread(Thread thread); static String getStringOfThrowable(Throwable throwable); }### Answer: @Test public void getStackTraceOfThread() { List<String> stackTrace = StacktraceUtil.getStackTraceOfThread(Thread.currentThread()); Assert.assertTrue(String.valueOf(stackTrace).contains(StacktraceUtilTest.class.getSimpleName())); }
### Question: StacktraceUtil { public static String getStringOfThrowable(Throwable throwable) { return throwable.getLocalizedMessage() + "\n" + stackTraceToString(throwable.getStackTrace()); } static List<String> stackTraceToStringArray(List<StackTraceElement> stackTraceElements); static List<String> getStackTraceOfThread(Thread thread); static String getStringOfThrowable(Throwable throwable); }### Answer: @Test public void getStringOfThrowable() { String detail = StacktraceUtil.getStringOfThrowable(new Throwable("AndroidGodEye-Exception")); Assert.assertTrue(detail.contains(StacktraceUtilTest.class.getSimpleName())); Assert.assertTrue(detail.contains("AndroidGodEye-Exception")); }
### Question: AndroidDebug { public static boolean isDebugging() { return Debug.isDebuggerConnected(); } static boolean isDebugging(); }### Answer: @Test public void isDebugging() { long startTime = SystemClock.elapsedRealtime(); for (int i = 0; i < 1000; i++) { AndroidDebug.isDebugging(); } Log4Test.d(String.format("AndroidDebugTest isDebugging cost %sms for 1000 times.", SystemClock.elapsedRealtime() - startTime)); }
### Question: Notifier { public static int notice(Context context, Config config) { return notice(context, createNoticeId(), create(context, config)); } static Notification create(Context context, Config config); static int createNoticeId(); static int notice(Context context, Config config); static int notice(Context context, int id, Notification notification); static void cancelNotice(Context context, int id); }### Answer: @Config(sdk = Build.VERSION_CODES.O) @Test @Ignore("local") public void noticeHigherThanO() { notice(); } @Config(sdk = Build.VERSION_CODES.LOLLIPOP) @Test public void noticeLowerThanO() { notice(); }
### Question: GodEyeHelper { public static void onFragmentPageVisibilityChange(Object fragmentPage, boolean visible) throws UninstallException { if (fragmentPage instanceof Fragment) { if (visible) { GodEye.instance().<Pageload>getModule(GodEye.ModuleName.PAGELOAD).onFragmentV4Show((Fragment) fragmentPage); } else { GodEye.instance().<Pageload>getModule(GodEye.ModuleName.PAGELOAD).onFragmentV4Hide((Fragment) fragmentPage); } } else if (fragmentPage instanceof android.app.Fragment) { if (visible) { GodEye.instance().<Pageload>getModule(GodEye.ModuleName.PAGELOAD).onFragmentShow((android.app.Fragment) fragmentPage); } else { GodEye.instance().<Pageload>getModule(GodEye.ModuleName.PAGELOAD).onFragmentHide((android.app.Fragment) fragmentPage); } } else { throw new UnexpectException("GodEyeHelper.onFragmentPageVisibilityChange's fragmentPage must be instance of Fragment."); } L.d("GodEyeHelper onFragmentPageVisibilityChange: " + fragmentPage.getClass().getSimpleName() + ", visible:" + visible); } static void onPageLoaded(Object page); static void onFragmentPageVisibilityChange(Object fragmentPage, boolean visible); static void onAppStartEnd(StartupInfo startupInfo); static void onNetworkEnd(NetworkInfo networkInfo); @Deprecated static void inspectView(); static void startMethodCanaryRecording(String tag); static void stopMethodCanaryRecording(String tag); static boolean isMethodCanaryRecording(String tag); static void setMonitorAppInfoConext(AppInfoConext appInfoConext); static void startMonitor(int port); static void startMonitor(); static void shutdownMonitor(); }### Answer: @Test public void onFragmentPageVisibilityChangeWhenIllegal() { try { GodEye.instance().uninstall(); GodEyeHelper.onFragmentPageVisibilityChange(null, true); fail(); } catch (RuntimeException ignore) { } catch (UninstallException e) { fail(); } }
### Question: Hook { boolean isValid() { try { new URL(this.uri); } catch (MalformedURLException ex) { return false; } return this.command != null; } Hook(String uri, FtpEventName command); Hook(); long getId(); String getUri(); FtpEventName getCommand(); void setCommand(FtpEventName command); static final String findByCommand; }### Answer: @Test public void validUri() { Hook cut = new Hook("http: assertTrue(cut.isValid()); } @Test public void invalidUri() { Hook cut = new Hook("asdf", FtpEventName.EVERYTHING); assertFalse(cut.isValid()); }
### Question: RegexReplacement { public String replace(String in) { boolean matches = regex.matcher(in).find(); if(matches) { return in.replaceAll(original, replacement); } else { return in; } } RegexReplacement(String regex, String original, String replacement); boolean match(String in); String replace(String in); }### Answer: @Test public void testReplacement() { RegexReplacement rr = new RegexReplacement("<version.light[a-z-]+4j>\\d*\\.\\d*\\.\\d*</version.light[a-z-]+4j>", "1.5.5", "1.5.6"); String result = rr.replace("<version.light-4j>1.5.5</version.light-4j>"); System.out.println(result); Assert.assertEquals("<version.light-4j>1.5.6</version.light-4j>", result); result = rr.replace("abc"); System.out.println(result); Assert.assertEquals("abc", result); result = rr.replace("abc<version.light-rest-4j>1.5.5</version.light-rest-4j>def"); System.out.println(result); Assert.assertEquals("abc<version.light-rest-4j>1.5.6</version.light-rest-4j>def", result); }
### Question: ExtendedProperties implements Map<String, String>, Serializable, Cloneable { @Override public void putAll(final Map<? extends String, ? extends String> map) { for (Entry<? extends String, ? extends String> entry : map.entrySet()) { put(entry.getKey(), entry.getValue()); } } ExtendedProperties(); ExtendedProperties(final Map<String, String> defaults); static ExtendedProperties fromProperties(final Properties props); @Override void clear(); @Override String get(final Object key); String get(final Object key, final String defaultValue); String get(final Object key, final boolean process); boolean getBoolean(final String key); boolean getBoolean(final String key, final boolean defaultValue); long getLong(final String key); long getLong(final String key, final long defaultValue); int getInteger(final String key); int getInteger(final String key, final int defaultValue); @Override String put(final String key, final String value); @Override boolean containsKey(final Object key); @Override boolean containsValue(final Object value); @Override Set<Entry<String, String>> entrySet(); @Override boolean isEmpty(); @Override void putAll(final Map<? extends String, ? extends String> map); @Override String remove(final Object key); @Override Collection<String> values(); @Override Set<String> keySet(); @Override int size(); String processPropertyValue(final String input); @Override boolean equals(final Object obj); @Override int hashCode(); Properties toProperties(); @Override String toString(); void load(final InputStream is); void load(final InputStream is, final String encoding); void load(final Reader reader); void store(final OutputStream os, final String comments, final boolean sorted, final boolean process); void store(final OutputStream os, final String encoding, final String comments, final boolean sorted, final boolean process); void store(final Writer writer, final String comments, final boolean sorted, final boolean process); @Override ExtendedProperties clone(); }### Answer: @Test public void testPutAll() { ExtendedProperties newProps = new ExtendedProperties(); newProps.putAll(props); assertProps(newProps); }
### Question: CheckHtml4String extends WebDriverStep { @Override public void execute() { log.info("String '{}' must {}exist in the page source. Search is {}case-sensitive.", string, mustExist ? "" : "not ", caseSensitive ? "" : "not "); String pageSource = getWebDriver().getPageSource(); boolean outcome = caseSensitive ? pageSource.contains(string) : containsIgnoreCase(pageSource, string); if (mustExist != outcome) { if (mustExist) { throw new ValidationException("Could not find string '" + string + "' (case-sensitive=" + caseSensitive + ")"); } throw new ValidationException("String '" + string + "' must not occur"); } } CheckHtml4String(final String string); CheckHtml4String(final String string, final boolean caseSensitive); CheckHtml4String(final String string, final boolean caseSensitive, final boolean mustExist); @Override void execute(); }### Answer: @Test public void stringMustExistCaseSensitively() { CheckHtml4String checkHtml4String = new CheckHtml4String("Case-Sensitive"); checkHtml4String.setWebDriver(webDriver); checkHtml4String.execute(); } @Test public void stringMustExistNotCaseSensitively() { CheckHtml4String checkHtml4String = new CheckHtml4String("case-sensitive", false); checkHtml4String.setWebDriver(webDriver); checkHtml4String.execute(); } @Test public void stringMustNotExistCaseSensitively() { CheckHtml4String checkHtml4String = new CheckHtml4String("foo", true, false); checkHtml4String.setWebDriver(webDriver); checkHtml4String.execute(); } @Test public void stringMustNotExistNotCaseSensitively() { CheckHtml4String checkHtml4String = new CheckHtml4String("foo", false, false); checkHtml4String.setWebDriver(webDriver); checkHtml4String.execute(); }
### Question: ExcelDataSource extends BaseDataSource { @Override public boolean hasMoreData(final String dataSetKey) { for (ExcelFile excelFile : getExcelFiles()) { Map<String, List<Map<String, String>>> data = excelFile.getData(); List<Map<String, String>> dataList = data.get(dataSetKey); if (dataList != null) { MutableInt counter = dataSetIndices.get(dataSetKey); int size = dataList.size(); return counter == null && size > 0 || size > counter.getValue(); } } return false; } @Inject ExcelDataSource(final Configuration configuration, final DataFormatter dataFormatter); @Override boolean hasMoreData(final String dataSetKey); @Override void doReset(); }### Answer: @Test public void testHasMoreData() { ExcelDataSource dataSource = createDataSource("src/test/resources/rowbased.xlsx", DataOrientation.rowbased); String dataSetKey = "sheet_0"; for (int i = 0; i < 3; ++i) { if (dataSource.hasMoreData(dataSetKey)) { dataSource.getNextDataSet(dataSetKey); } } assertThat(dataSource.hasMoreData(dataSetKey)).describedAs("no more data should be available").isFalse(); }
### Question: CsvDataSource extends BaseDataSource { @Override public boolean hasMoreData(final String dataSetKey) { if (getCsvFiles().containsKey(dataSetKey)) { CsvFile csvFile = getCsvFiles().get(dataSetKey); if (csvFile.lines == null) { try { csvFile.load(); } catch (IOException e) { throw new IllegalArgumentException("Could not load CSV file " + csvFile.fileName, e); } } return csvFile.hasNextLine(); } return false; } @Inject CsvDataSource(final Configuration configuration); @Override boolean hasMoreData(final String dataSetKey); @Override void doReset(); }### Answer: @Test public void testHasMoreData() { int i = 0; while (ds.hasMoreData("bar")) { ds.getNextDataSet("bar"); ++i; } Assert.assertEquals(i, 2); i = 0; while (ds.hasMoreData("foo")) { ds.getNextDataSet("foo"); ++i; } Assert.assertEquals(i, 2); }
### Question: ContainerDataSource implements DataSource { @Override public DataSet getNextDataSet(final String key) { List<? extends DataSource> dataSources = dataSourcesProvider.get(); for (DataSource ds : dataSources) { DataSet data = ds.getNextDataSet(key); if (data != null) { return data; } } return null; } @Inject ContainerDataSource(final Provider<List<? extends DataSource>> dataSourcesProvider); @Override DataSet getNextDataSet(final String key); @Override DataSet getCurrentDataSet(final String key); @Override Map<String, DataSet> getCurrentDataSets(); @Override boolean hasMoreData(final String dataSetKey); @Override void resetFixedValue(final String dataSetKey, final String entryKey); @Override void resetFixedValues(final String dataSetKey); @Override void resetFixedValues(); @Override void setFixedValue(final String dataSetKey, final String entryKey, final String value); @Override String getName(); @Override void copyDataSetKey(final String key, final String newKey); @Override void removeDataSet(final String key); @Override String toString(); @Override void reset(); }### Answer: @Test public void testDataSetsAvailable() { DataSet data1 = ds.getNextDataSet("test1"); Assert.assertNotNull(data1); DataSet data2 = ds.getNextDataSet("test2"); Assert.assertNotNull(data2); } @Test public void testDataSetNotAvailable() { DataSet data = ds.getNextDataSet("test3"); Assert.assertNull(data); }
### Question: ArchiveDataSource extends BaseDataSource { @Override public boolean hasMoreData(final String dataSetKey) { return true; } @Inject ArchiveDataSource(final Configuration configuration); @Override boolean hasMoreData(final String dataSetKey); @Override void doReset(); }### Answer: @Test(dataProvider = "dataSources") public void testHasMoreData(final DataSource ds) { Assert.assertTrue(ds.hasMoreData("countryId")); Assert.assertTrue(ds.hasMoreData("languageId")); Assert.assertTrue(ds.hasMoreData("searchTerm")); }
### Question: LoremIpsumGenerator { public String generateLoremIpsum(final int length) { if (loremLength < length) { int multiplier = length / loremLength; int remainder = length % loremLength; StrBuilder sb = new StrBuilder(multiplier * length + remainder); for (int i = 0; i < multiplier; ++i) { sb.append(loremIpsum); } sb.append(loremIpsum.substring(0, remainder)); return sb.toString(); } return loremIpsum.substring(0, length); } @Inject LoremIpsumGenerator(@LoremIpsum final String loremIpsum); String generateLoremIpsum(final int length); }### Answer: @Test public void testMinimum() { String result = generator.generateLoremIpsum(1); assertEquals(result, "L"); } @Test public void testMaximum() { String result = generator.generateLoremIpsum(loremIpsum.length()); assertEquals(result, loremIpsum); } @Test public void testMultiple() { String result = generator.generateLoremIpsum(10000); assertEquals(result.length(), 10000); }
### Question: LoremIpsumField extends Field { @Override public String getString(final FieldCase c) { int size = c.getSize(); if (size == FieldCase.JUST_ABOVE_MAX) { size++; } else if (size == FieldCase.JUST_BELOW_MIN) { size--; } if (size <= 0) { return ""; } int loremLength = loremIpsum.length(); if (loremLength < size) { int multiplier = size / loremLength; int remainder = size % loremLength; StrBuilder sb = new StrBuilder(multiplier * size + remainder); for (int i = 0; i < multiplier; ++i) { sb.append(loremIpsum); } sb.append(loremIpsum.substring(0, remainder)); return sb.toString(); } return loremIpsum.substring(0, size); } LoremIpsumField(final MathRandom random, final Element element, final String characterSetId); @Override int getMaxLength(); @Override Range getRange(); @Override void setRange(final Range range); @Override String getString(final FieldCase c); }### Answer: @Test public void testMinimum() { String value = field.getString(new FieldCase(1)); assertEquals(value, "L"); } @Test public void testMaximum() { String value = field.getString(new FieldCase(100)); assertEquals(value, loremIpsum.substring(0, 100)); } @Test public void testVeryLongOne() { String value = field.getString(new FieldCase(10000)); assertEquals(value.length(), 10000); }
### Question: DataSetAdapter extends ForwardingMap<String, String> { @Override public String get(final Object key) { String[] pair = getKeysPair(key); if (pair.length == 1) { return null; } String dsKey = pair[0]; DataSet currentDataSet = dataSourceProvider.get().getCurrentDataSet(dsKey); if (currentDataSet == null) { log.warn("No data set available: '" + dsKey + "'. Forgot to call 'generate?'"); return null; } String value = pair[1]; String[] split = value.split(JFunkConstants.INDEXED_KEY_SEPARATOR); return split.length > 1 ? currentDataSet.getValue(split[0], Integer.parseInt(split[1])) : currentDataSet.getValue(split[0]); } @Inject DataSetAdapter(final Provider<DataSource> dataSourceProvider); @Override String get(final Object key); }### Answer: @Test public void testExistingValues() { dataSource.getNextDataSet("test"); String testValue1 = adapter.get("test testKey1"); Assert.assertEquals(testValue1, "testValue1"); String testValue2 = adapter.get("test testKey2"); Assert.assertEquals(testValue2, "testValue2"); } @Test public void testNulls() { dataSource.getNextDataSet("test"); String testValue1 = adapter.get("keyWithoutValue"); Assert.assertNull(testValue1); String testValue2 = adapter.get("nonExistingDsKey foo"); Assert.assertNull(testValue2); }
### Question: ScreenCapturer { public static void captureScreen(final File file) { Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); captureScreenRect(file, rectangle); } @Inject ScreenCapturer(@ModuleArchiveDir final Provider<File> moduleArchiveDirProvider, final Set<Class<? extends AbstractBaseEvent>> screenCaptureEvents, final Provider<MutableInt> counterProvider, @CaptureScreenOnError final boolean captureScreenOnError); static void captureScreen(final File file); static void captureScreenRect(final File file, final Rectangle rectangle); @Subscribe @AllowConcurrentEvents void handleEvent(final AbstractBaseEvent event); void captureAndArchiveScreen(final String screenshotName); }### Answer: @Test(groups = "excludeFromCI") public void testCaptureScreen() throws IOException { testFileOrDir = File.createTempFile("jFunkScreenCapture", ".png"); ScreenCapturer.captureScreen(testFileOrDir); assertThat(testFileOrDir).exists(); }
### Question: CsvDataProcessor { @Inject CsvDataProcessor(final Provider<Configuration> configProvider, final Provider<DataSource> dataSourceProvider) { this.configProvider = configProvider; this.dataSourceProvider = dataSourceProvider; } @Inject CsvDataProcessor(final Provider<Configuration> configProvider, final Provider<DataSource> dataSourceProvider); void processFile(final Reader reader, final String delimiter, final char quoteChar, final Runnable command); }### Answer: @Test public void testCsvDataProcessor() { final Configuration config = new Configuration(Charsets.UTF_8); config.put("foo", "foovalue"); final DataSource dataSource = new TestDataSource(config); CsvDataProcessor csvProc = new CsvDataProcessor(Providers.of(config), Providers.of(dataSource)); final MutableInt counter = new MutableInt(); csvProc.processFile(new StringReader(CSV_LINES), ";", '\0', new Runnable() { @Override public void run() { dataSource.getNextDataSet("test"); int counterValue = counter.intValue(); assertEquals(config.get("foo"), "foo" + counterValue); assertEquals(dataSource.getCurrentDataSet("test").getValue("testKey1"), "newTestValue1" + counterValue); assertEquals(dataSource.getCurrentDataSet("test").getValue("testKey2"), "testValue2"); dataSource.setFixedValue("test", "testKey1", "blablubb"); dataSource.setFixedValue("test", "testKey2", "blablubb"); counter.increment(); } }); }
### Question: MailAccountManager { public MailAccount reserveMailAccount() { return reserveMailAccount(DEFAULT_ACCOUNT_RESERVATION_KEY); } @Inject MailAccountManager(final SetMultimap<String, MailAccount> emailAddressPools, final MathRandom random, final Provider<EventBus> eventBusProvider, final Configuration config); MailAccount reserveMailAccount(); MailAccount reserveMailAccount(final String accountReservationKey); MailAccount reserveMailAccount(final String accountReservationKey, final String pool); MailAccount lookupUsedMailAccountForCurrentThread(final String accountReservationKey); boolean isReserved(final MailAccount mailAccount); Set<MailAccount> getReservedMailAccountsForCurrentThread(); Set<String> getRegisteredAccountReservationKeysForCurrentThread(); void releaseAllMailAccounts(); void releaseAllMailAccountsForThread(); void releaseMailAccountForThread(final MailAccount account); void releaseMailAccountForThread(final String accountReservationKey); static final String DEFAULT_ACCOUNT_RESERVATION_KEY; }### Answer: @Test public void mailboxShouldBePurgedOnReservation() { init(1); MailboxPurger purger = mock(MailboxPurger.class); eventBus.register(purger); try { MailAccount mailAccount = manager.reserveMailAccount(); verify(purger) .purgeMailbox( new MailAccountReservationEvent(MailAccountManager.DEFAULT_ACCOUNT_RESERVATION_KEY, mailAccount)); } finally { eventBus.unregister(purger); } }
### Question: ThreadScope extends BaseScope { @Override public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) { return new Provider<T>() { @Override public T get() { Map<Key<?>, Object> map = getScopeMapForCurrentThread(); checkState(map != null, "No scope map found for the current thread. Forgot to call enterScope()?"); return getScopedObject(key, unscoped, map); } @Override public String toString() { return String.format("%s[%s]", unscoped, ThreadScope.this); } }; } @Override Provider<T> scope(final Key<T> key, final Provider<T> unscoped); @Override void enterScope(); void enterScopeNonInheritable(); boolean isScopeEntered(); @Override void exitScope(); }### Answer: @Test public void testToString() { ThreadScope scope = new ThreadScope(); Provider<String> prov = scope.scope(Key.get(String.class), new Provider<String>() { @Override public String get() { return "dummy"; } @Override public String toString() { return get(); } }); Assert.assertEquals(prov.toString(), "dummy[ThreadScope]"); }
### Question: WmsVersion implements Comparable<WmsVersion> { @Override public int compareTo(WmsVersion o) { if (o == null) { throw new NullPointerException("Version to compare to must not be null"); } if (this.major != o.major) { return this.major < o.major ? -1 : 1; } if (this.minor != o.minor) { return this.minor < o.minor ? -1 : 1; } if (this.build != o.build) { return this.build < o.build ? -1 : 1; } return 0; } WmsVersion(String version); WmsVersion(int major, int minor, int build); int getMajor(); int getMinor(); int getBuild(); @Override int compareTo(WmsVersion o); @Override String toString(); String toVersionString(); static void validateVersion(String version); }### Answer: @Test public void testCompareTo() { WmsVersion version111 = new WmsVersion("1.1.1"); WmsVersion version112 = new WmsVersion("1.1.2"); WmsVersion version110 = new WmsVersion("1.1"); WmsVersion version130 = new WmsVersion("1.3"); WmsVersion version200 = new WmsVersion("2.0"); assertThat(version111.compareTo(version112), is(-1)); assertThat(version112.compareTo(version111), is(1)); assertThat(version111.compareTo(version130), is(-1)); assertThat(version130.compareTo(version111), is(1)); assertThat(version130.compareTo(version130), is(0)); assertThat(version110.compareTo(version111), is(-1)); assertThat(version200.compareTo(version111), is(1)); assertThat(version130.compareTo(version200), is(-1)); } @Test(expected = NullPointerException.class) public void testCompareToNull() { WmsVersion version = new WmsVersion("1.1.1"); version.compareTo(null); }
### Question: WmsRequestBuilder { public WmsRequestBuilder transparent(boolean transparent) { parameters.put(WmsRequestParameter.TRANSPARENT, Boolean .valueOf(transparent) .toString()); return this; } static WmsRequestBuilder createGetMapRequest(String serviceUrl); static WmsRequestBuilder createGetMapRequest( Map<WmsRequestParameter, String> params); WmsRequestBuilder layers(String layers); WmsRequestBuilder styles(String styles); WmsRequestBuilder format(String format); WmsRequestBuilder boundingBox(String boundingBox); WmsRequestBuilder transparent(boolean transparent); WmsRequestBuilder version(String version); WmsRequestBuilder srsCrs(String srsCrs); WmsRequestBuilder urlParameters(String urlParameters); WmsRequestBuilder width(int width); WmsRequestBuilder height(int height); URL toMapUrl(); }### Answer: @Test public void testTransparent() throws MalformedURLException { String url = basicRequestBuilder().toMapUrl().toExternalForm(); assertThat(url, containsString("TRANSPARENT=FALSE")); }
### Question: WmsRequestBuilder { public WmsRequestBuilder version(String version) { parameters.put(WmsRequestParameter.VERSION, version); return this; } static WmsRequestBuilder createGetMapRequest(String serviceUrl); static WmsRequestBuilder createGetMapRequest( Map<WmsRequestParameter, String> params); WmsRequestBuilder layers(String layers); WmsRequestBuilder styles(String styles); WmsRequestBuilder format(String format); WmsRequestBuilder boundingBox(String boundingBox); WmsRequestBuilder transparent(boolean transparent); WmsRequestBuilder version(String version); WmsRequestBuilder srsCrs(String srsCrs); WmsRequestBuilder urlParameters(String urlParameters); WmsRequestBuilder width(int width); WmsRequestBuilder height(int height); URL toMapUrl(); }### Answer: @Test public void testVersion() throws MalformedURLException { String url = basicRequestBuilder().toMapUrl().toExternalForm(); assertThat(url, containsString("VERSION=1.1.1")); }
### Question: WmsVersion implements Comparable<WmsVersion> { @Override public String toString() { return format("%d.%d.%d", major, minor, build); } WmsVersion(String version); WmsVersion(int major, int minor, int build); int getMajor(); int getMinor(); int getBuild(); @Override int compareTo(WmsVersion o); @Override String toString(); String toVersionString(); static void validateVersion(String version); }### Answer: @Test public void testToString() { WmsVersion version = new WmsVersion("1.3"); assertThat(version.toString(), is("1.3.0")); }
### Question: WmsVersion implements Comparable<WmsVersion> { public String toVersionString() { StringBuilder version = new StringBuilder(); version.append(major); if (minor != 0) { version.append('.').append(minor); } if (build != 0) { version.append('.').append(build); } return version.toString(); } WmsVersion(String version); WmsVersion(int major, int minor, int build); int getMajor(); int getMinor(); int getBuild(); @Override int compareTo(WmsVersion o); @Override String toString(); String toVersionString(); static void validateVersion(String version); }### Answer: @Test public void testToVersionString() { WmsVersion version1 = new WmsVersion(1, 0, 0); assertThat(version1.toVersionString(), is("1")); WmsVersion version13 = new WmsVersion(1, 3, 0); assertThat(version13.toVersionString(), is("1.3")); WmsVersion version111 = new WmsVersion(1, 1, 1); assertThat(version111.toVersionString(), is("1.1.1")); }
### Question: WmsMapElementHtmlHandler implements GenericElementHtmlHandler { @Override public boolean toExport(JRGenericPrintElement element) { return true; } static WmsMapElementHtmlHandler getInstance(); @Override String getHtmlFragment(JRHtmlExporterContext context, JRGenericPrintElement element); @Override boolean toExport(JRGenericPrintElement element); }### Answer: @Test public void testToExport() { assertTrue(handler.toExport(null)); }
### Question: WmsMapElementGraphics2DHandler implements GenericElementGraphics2DHandler { @Override public void exportElement(JRGraphics2DExporterContext context, JRGenericPrintElement element, Graphics2D grx, Offset offset) { try { JRGraphics2DExporter exporter = (JRGraphics2DExporter) context .getExporter(); ImageDrawer imageDrawer = exporter.getFrameDrawer().getDrawVisitor() .getImageDrawer(); JRPrintImage image = getImage(context.getJasperReportsContext(), element); imageDrawer.draw(grx, image, offset.getX(), offset.getY()); } catch (Exception e) { throw new RuntimeException(e); } } static WmsMapElementGraphics2DHandler getInstance(); @Override void exportElement(JRGraphics2DExporterContext context, JRGenericPrintElement element, Graphics2D grx, Offset offset); @Override boolean toExport(JRGenericPrintElement element); }### Answer: @Ignore @Test public void testExportElement() throws JRException { JRGraphics2DExporter exporter = new JRGraphics2DExporter(); JRGraphics2DExporterContext context = mock(JRGraphics2DExporterContext.class); when(context.getExporter()).thenReturn(exporter); JRGenericPrintElement element = mock(JRGenericPrintElement.class); java.awt.Container container = new Container(); Graphics2D graphics = (Graphics2D) container.getGraphics(); Offset offset = new Offset(0, 0); handler.exportElement(context, element, graphics, offset); }
### Question: WmsMapElementGraphics2DHandler implements GenericElementGraphics2DHandler { @Override public boolean toExport(JRGenericPrintElement element) { return true; } static WmsMapElementGraphics2DHandler getInstance(); @Override void exportElement(JRGraphics2DExporterContext context, JRGenericPrintElement element, Graphics2D grx, Offset offset); @Override boolean toExport(JRGenericPrintElement element); }### Answer: @Test public void testToExport() { assertTrue(handler.toExport(mock(JRGenericPrintElement.class))); }
### Question: Station { @JsonSetter("tags") public void setTags(final String commaTags) { tagList = Arrays.asList(commaTags.split(",")); } @JsonGetter("tags") String getTags(); @JsonSetter("tags") void setTags(final String commaTags); @JsonGetter("language") String getLanguage(); @JsonSetter("language") void setLanguage(final String commaLanguages); @Override String toString(); }### Answer: @Test public void setTagsCommaSeparated() { Station testMe = new Station(); testMe.setTags("foo,bar,baz"); assertThat(Arrays.asList("foo", "bar", "baz"), is(testMe.getTagList())); }
### Question: EndpointDiscovery { public Optional<String> discover() throws IOException { List<DiscoveryResult> discoveryResults = discoverApiUrls(apiUrls()); return discoveryResults .stream() .sorted(Comparator.comparingLong(o -> o.duration)) .map(DiscoveryResult::getEndpoint) .findFirst(); } EndpointDiscovery(@NonNull final String myUserAgent); Optional<String> discover(); }### Answer: @Test public void discover(@Mocked Client clientMock, @Mocked ClientBuilder clientBuilderMock, @Mocked WebTarget webTargetMock, @Mocked InetAddress inetAddressMock) throws IOException { new Expectations() {{ ClientBuilder.newBuilder(); result = clientBuilderMock; clientBuilderMock.build(); result = clientMock; clientMock.target("https: InetAddress.getAllByName(EndpointDiscovery.DNS_API_ADDRESS); result = new InetAddress[] {inetAddressMock}; inetAddressMock.getCanonicalHostName(); result = "127.0.0.1"; }}; Optional<String> name = endpointDiscovery.discover(); assertThat(name.isPresent(), is(true)); }
### Question: EndpointDiscovery { Stats getStats(final String endpoint, final int timeout) { if (timeout <= 0) { throw new IllegalArgumentException( "timeout must be > 0, but is " + timeout); } Client client = ClientBuilder.newBuilder() .register(JacksonFeature.class) .build(); client.property(ClientProperties.CONNECT_TIMEOUT, timeout); client.property(ClientProperties.READ_TIMEOUT, timeout); WebTarget webTarget = client.target(endpoint); return webTarget.path("json/stats") .request(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE) .header("User-Agent", userAgent) .get(Stats.class); } EndpointDiscovery(@NonNull final String myUserAgent); Optional<String> discover(); }### Answer: @Test public void getStats(@Mocked Client clientMock, @Mocked ClientBuilder clientBuilderMock, @Mocked WebTarget webTargetMock, @Mocked Invocation.Builder invocationBuilderMock) { Stats myStats = new Stats(); new Expectations() {{ ClientBuilder.newBuilder(); result = clientBuilderMock; clientBuilderMock.build(); result = clientMock; clientMock.target(RadioBrowser.DEFAULT_API_URL); result = webTargetMock; invocationBuilderMock.get(Stats.class); result = myStats; }}; Stats stats = endpointDiscovery.getStats(RadioBrowser.DEFAULT_API_URL, 5000); assertThat(stats, is(myStats)); }
### Question: Station { @JsonGetter("tags") public String getTags() { return String.join(",", tagList); } @JsonGetter("tags") String getTags(); @JsonSetter("tags") void setTags(final String commaTags); @JsonGetter("language") String getLanguage(); @JsonSetter("language") void setLanguage(final String commaLanguages); @Override String toString(); }### Answer: @Test public void getTagsCommaSeparated() { Station testMe = new Station(); testMe.setTagList(Arrays.asList("foo", "bar", "baz")); assertThat("foo,bar,baz", is(testMe.getTags())); }
### Question: ListParameter { public static ListParameter create() { return new ListParameter(); } private ListParameter(); static ListParameter create(); ListParameter order(@NonNull final FieldName fieldName); ListParameter reverseOrder(final boolean reverse); }### Answer: @Test public void create() { ListParameter listParameter = ListParameter.create(); assertThat(listParameter, is(not(nullValue()))); }
### Question: PagingSpliterator extends Spliterators.AbstractSpliterator<T> { PagingSpliterator(final Function<Paging, List<T>> fetchPageFunction) { super(Long.MAX_VALUE, 0); currentPage = Paging.at(0, FETCH_SIZE_DEFAULT); this.fetchPage = fetchPageFunction; loadPage(); } PagingSpliterator(final Function<Paging, List<T>> fetchPageFunction); @Override boolean tryAdvance(final Consumer<? super T> action); }### Answer: @Test public void testPagingSpliterator() { PagingSpliterator<Integer> integerPagingSpliterator = new PagingSpliterator<>( paging -> { List<Integer> data; if (paging.getOffset() < 100) { data = IntStream.range(paging.getOffset(), paging.getOffset() + paging.getLimit()) .boxed() .collect(Collectors.toList()); if (data.size() > paging.getLimit()) { throw new IllegalStateException(); } } else { data = Collections.emptyList(); } return data; } ); List<Integer> actual = StreamSupport.stream(integerPagingSpliterator, false) .collect(Collectors.toList()); List<Integer> expected = IntStream.range(0, 128) .boxed() .collect(Collectors.toList()); assertThat(actual, is(expected)); }
### Question: Paging { public static Paging at(final int offset, final int limit) { return new Paging(offset, limit); } private Paging(final int myOffset, final int myLimit); static Paging at(final int offset, final int limit); Paging previous(); Paging next(); static final Paging DEFAULT_START; }### Answer: @Test public void at() { Paging paging = Paging.at(0, 1); assertThat(paging.getOffset(), is(0)); assertThat(paging.getLimit(), is(1)); } @Test(expected = IllegalArgumentException.class) public void atWithZeroLimit() { Paging.at(0, 0); } @Test(expected = IllegalArgumentException.class) public void atWithNegativeOffset() { Paging.at(-1, 1); }
### Question: Paging { public Paging next() { return new Paging(offset + limit, limit); } private Paging(final int myOffset, final int myLimit); static Paging at(final int offset, final int limit); Paging previous(); Paging next(); static final Paging DEFAULT_START; }### Answer: @Test public void next() { Paging pagingFirst = Paging.at(0, 64); Paging next = pagingFirst.next(); assertThat(next.getOffset(), is(64)); assertThat(next.getLimit(), is(64)); }
### Question: Paging { public Paging previous() { int newOffset = offset - limit; if (newOffset < 0) { newOffset = 0; } return new Paging(newOffset, limit); } private Paging(final int myOffset, final int myLimit); static Paging at(final int offset, final int limit); Paging previous(); Paging next(); static final Paging DEFAULT_START; }### Answer: @Test public void previous() { Paging pagingFirst = Paging.at(64, 32); Paging next = pagingFirst.previous(); assertThat(next.getOffset(), is(64 - 32 )); assertThat(next.getLimit(), is(32)); }
### Question: EndpointDiscovery { List<String> apiUrls() throws UnknownHostException { InetAddress[] addresses = InetAddress.getAllByName(DNS_API_ADDRESS); List<String> fqdns = new ArrayList<>(); for (InetAddress inetAddress : addresses) { fqdns.add(inetAddress.getCanonicalHostName()); } return fqdns.stream() .map(s -> String.format("https: .collect(Collectors.toList()); } EndpointDiscovery(@NonNull final String myUserAgent); Optional<String> discover(); }### Answer: @Test public void apiUrls(@Mocked InetAddress inetAddressMock) throws UnknownHostException { InetAddress[] inetAddresses = new InetAddress[1]; inetAddresses[0] = inetAddressMock; new Expectations() {{ InetAddress.getAllByName(EndpointDiscovery.DNS_API_ADDRESS); result = inetAddresses; inetAddressMock.getCanonicalHostName(); result = "127.0.0.1"; }}; List<String> urls = endpointDiscovery.apiUrls(); assertThat(urls, is(Collections.singletonList("https: new Verifications() {{ InetAddress.getAllByName(EndpointDiscovery.DNS_API_ADDRESS); times = 1; }}; }
### Question: EndpointDiscovery { List<DiscoveryResult> discoverApiUrls(final List<String> apiUrls) { ExecutorService executorService = Executors.newFixedThreadPool(DEFAULT_THREADS); try { List<Future<DiscoveryResult>> futureList = new ArrayList<>(); for (final String apiUrl : apiUrls) { Callable<DiscoveryResult> discoveryResultCallable = () -> { long start = System.currentTimeMillis(); log.debug("Starting check for {}", apiUrl); Stats stats = getStats(apiUrl, DEFAULT_TIMEOUT_MILLIS); long duration = System.currentTimeMillis() - start; log.debug("Finished check for {}, took {} ms", apiUrl, duration); return new DiscoveryResult(apiUrl, duration, stats); }; futureList.add(executorService.submit(discoveryResultCallable)); } List<DiscoveryResult> discoveryResults = new ArrayList<>(); for (Future<DiscoveryResult> future : futureList) { try { DiscoveryResult discoveryResult = future.get( DEFAULT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); discoveryResults.add(discoveryResult); } catch (ExecutionException | TimeoutException | InterruptedException e) { log.warn("Endpoint " + (apiUrls.get(futureList.indexOf(future))) + " had an exception", e); } } return discoveryResults; } finally { executorService.shutdown(); } } EndpointDiscovery(@NonNull final String myUserAgent); Optional<String> discover(); }### Answer: @Test public void discoverApiUrls(@Mocked Client clientMock, @Mocked ClientBuilder clientBuilderMock, @Mocked WebTarget webTargetMock) { new Expectations() {{ ClientBuilder.newBuilder(); result = clientBuilderMock; clientBuilderMock.build(); result = clientMock; clientMock.target("https: }}; List<EndpointDiscovery.DiscoveryResult> results = endpointDiscovery.discoverApiUrls(Collections.singletonList("https: assertThat(results.size(), is(1)); assertThat(results.get(0).getDuration(), is(Matchers.greaterThan(0L))); new Verifications() {{ clientMock.target("https: }}; }
### Question: RevisionNameSerializer extends AbstractElementSerializer<RevisionName> { private RevisionNameSerializer() { super( RevisionNameComparator.INSTANCE ); } private RevisionNameSerializer(); RevisionName fromBytes( byte[] in ); RevisionName fromBytes( byte[] in, int start ); @Override byte[] serialize( RevisionName revisionName ); @Override RevisionName deserialize( BufferHandler bufferHandler ); @Override RevisionName deserialize( ByteBuffer buffer ); }### Answer: @Test public void testRevisionNameSerializer() throws IOException { RevisionName value = null; try { serializer.serialize( value ); fail(); } catch ( Exception e ) { } value = new RevisionName( 1L, null ); byte[] result = serializer.serialize( value ); assertEquals( 12, result.length ); assertEquals( 1L, ( long ) LongSerializer.deserialize( result ) ); assertNull( StringSerializer.deserialize( result, 8 ) ); assertEquals( value, serializer.deserialize( new BufferHandler( result ) ) ); value = new RevisionName( 0L, "" ); result = serializer.serialize( value ); assertEquals( value, serializer.deserialize( new BufferHandler( result ) ) ); value = new RevisionName( 0L, "L\u00E9charny" ); result = serializer.serialize( value ); assertEquals( value, serializer.deserialize( new BufferHandler( result ) ) ); }
### Question: BooleanSerializer extends AbstractElementSerializer<Boolean> { private BooleanSerializer() { super( BooleanComparator.INSTANCE ); } private BooleanSerializer(); byte[] serialize( Boolean element ); static byte[] serialize( boolean element ); static byte[] serialize( byte[] buffer, int start, boolean element ); static Boolean deserialize( byte[] in ); static Boolean deserialize( byte[] in, int start ); Boolean fromBytes( byte[] in ); Boolean fromBytes( byte[] in, int start ); Boolean deserialize( ByteBuffer buffer ); @Override Boolean deserialize( BufferHandler bufferHandler ); static final BooleanSerializer INSTANCE; }### Answer: @Test public void testBooleanSerializer() throws IOException { boolean value = true; byte[] result = BooleanSerializer.serialize( value ); assertEquals( ( byte ) 0x01, result[0] ); assertEquals( value, serializer.deserialize( new BufferHandler( result ) ).booleanValue() ); value = false; result = BooleanSerializer.serialize( value ); assertEquals( ( byte ) 0x00, result[0] ); assertEquals( value, serializer.deserialize( new BufferHandler( result ) ).booleanValue() ); }
### Question: ByteSerializer extends AbstractElementSerializer<Byte> { private ByteSerializer() { super( ByteComparator.INSTANCE ); } private ByteSerializer(); byte[] serialize( Byte element ); static byte[] serialize( byte value ); static byte[] serialize( byte[] buffer, int start, byte value ); static Byte deserialize( byte[] in ); static Byte deserialize( byte[] in, int start ); Byte fromBytes( byte[] in ); Byte fromBytes( byte[] in, int start ); Byte deserialize( ByteBuffer buffer ); Byte deserialize( BufferHandler bufferHandler ); static final ByteSerializer INSTANCE; }### Answer: @Test public void testByteSerializer() throws IOException { byte value = 0x00; byte[] result = ByteSerializer.serialize( value ); assertEquals( ( byte ) 0x00, result[0] ); assertEquals( value, serializer.deserialize( new BufferHandler( result ) ).byteValue() ); value = 0x01; result = ByteSerializer.serialize( value ); assertEquals( ( byte ) 0x01, result[0] ); assertEquals( value, serializer.deserialize( new BufferHandler( result ) ).byteValue() ); value = 0x7F; result = ByteSerializer.serialize( value ); assertEquals( ( byte ) 0x7F, result[0] ); assertEquals( value, serializer.deserialize( new BufferHandler( result ) ).byteValue() ); value = ( byte ) 0x80; result = ByteSerializer.serialize( value ); assertEquals( ( byte ) 0x80, result[0] ); assertEquals( value, serializer.deserialize( new BufferHandler( result ) ).byteValue() ); value = ( byte ) 0xFF; result = ByteSerializer.serialize( value ); assertEquals( ( byte ) 0xFF, result[0] ); assertEquals( value, serializer.deserialize( new BufferHandler( result ) ).byteValue() ); }
### Question: RevisionNameComparator implements Comparator<RevisionName> { private RevisionNameComparator() { } private RevisionNameComparator(); int compare( RevisionName rn1, RevisionName rn2 ); static final RevisionNameComparator INSTANCE; }### Answer: @Test public void testRevisionNameComparator() { RevisionNameComparator comparator = RevisionNameComparator.INSTANCE; assertEquals( 0, comparator.compare( null, null ) ); assertEquals( 0, comparator.compare( new RevisionName( 0L, "test" ), new RevisionName( 0L, "test" ) ) ); assertEquals( 1, comparator.compare( new RevisionName( 3L, "test" ), new RevisionName( 0L, "test" ) ) ); assertEquals( -1, comparator.compare( new RevisionName( 3L, "test" ), new RevisionName( 5L, "test" ) ) ); assertEquals( 1, comparator.compare( new RevisionName( 3L, "test2" ), new RevisionName( 3L, "test1" ) ) ); assertEquals( -1, comparator.compare( new RevisionName( 3L, "test" ), new RevisionName( 3L, "test2" ) ) ); }
### Question: InMemoryBTree extends AbstractBTree<K, V> implements Closeable { public void close() throws IOException { if ( getType() == BTreeTypeEnum.BACKED_ON_DISK ) { flush(); journalChannel.close(); } } InMemoryBTree(); InMemoryBTree( InMemoryBTreeConfiguration<K, V> configuration ); void close(); void flush( File file ); void load( File file ); Page<K, V> getRootPage( long revision ); Page<K, V> getRootPage(); void flush(); File getFile(); void setFilePath( String filePath ); File getJournal(); boolean isInMemory(); boolean isPersistent(); String toString(); static final String DEFAULT_JOURNAL; static final String DATA_SUFFIX; static final String JOURNAL_SUFFIX; }### Answer: @Test public void testBrowseEmptyTree() throws Exception { BTree<Integer, String> btree = BTreeFactory.createInMemoryBTree( "test", IntSerializer.INSTANCE, StringSerializer.INSTANCE ); btree.setPageSize( 8 ); TupleCursor<Integer, String> cursor = btree.browse(); assertFalse( cursor.hasNext() ); assertFalse( cursor.hasPrev() ); cursor.close(); btree.close(); } @Test public void testExist() throws IOException, KeyNotFoundException { BTree<Integer, String> btree = createTwoLevelBTreeFullLeaves(); for ( int i = 1; i < 21; i++ ) { assertTrue( btree.hasKey( 5 ) ); } assertFalse( btree.hasKey( 0 ) ); assertFalse( btree.hasKey( 21 ) ); btree.close(); }
### Question: CharComparator implements Comparator<Character> { private CharComparator() { } private CharComparator(); int compare( Character char1, Character char2 ); static final CharComparator INSTANCE; }### Answer: @Test public void testCharComparator() { CharComparator comparator = CharComparator.INSTANCE; assertEquals( 0, comparator.compare( null, null ) ); assertEquals( 0, comparator.compare( 'a', 'a' ) ); assertEquals( 0, comparator.compare( '\u00e9', '\u00e9' ) ); assertEquals( 1, comparator.compare( 'a', null ) ); assertEquals( -1, comparator.compare( 'A', 'a' ) ); assertEquals( 1, comparator.compare( 'a', 'A' ) ); assertEquals( -1, comparator.compare( null, 'a' ) ); assertEquals( -1, comparator.compare( 'a', 'b' ) ); }
### Question: ShortComparator implements Comparator<Short> { private ShortComparator() { } private ShortComparator(); int compare( Short short1, Short short2 ); static final ShortComparator INSTANCE; }### Answer: @Test public void testShortComparator() { ShortComparator comparator = ShortComparator.INSTANCE; assertEquals( 0, comparator.compare( null, null ) ); assertEquals( 0, comparator.compare( ( short ) 1, ( short ) 1 ) ); assertEquals( 0, comparator.compare( ( short ) -1, ( short ) -1 ) ); assertEquals( 1, comparator.compare( ( short ) 1, null ) ); assertEquals( 1, comparator.compare( ( short ) 2, ( short ) 1 ) ); assertEquals( 1, comparator.compare( ( short ) 3, ( short ) 1 ) ); assertEquals( 1, comparator.compare( ( short ) 1, ( short ) -1 ) ); assertEquals( -1, comparator.compare( null, ( short ) 1 ) ); assertEquals( -1, comparator.compare( ( short ) 1, ( short ) 2 ) ); assertEquals( -1, comparator.compare( ( short ) -1, ( short ) 1 ) ); }
### Question: BooleanArrayComparator implements Comparator<boolean[]> { private BooleanArrayComparator() { } private BooleanArrayComparator(); int compare( boolean[] booleanArray1, boolean[] booleanArray2 ); static final BooleanArrayComparator INSTANCE; }### Answer: @Test public void testBooleanArrayComparator() { BooleanArrayComparator comparator = BooleanArrayComparator.INSTANCE; assertEquals( 0, comparator.compare( null, null ) ); boolean[] b1 = new boolean[] { true, true, true }; boolean[] b2 = new boolean[] { true, true, false }; boolean[] b3 = new boolean[] { true, false, true }; boolean[] b4 = new boolean[] { false, true, true }; boolean[] b5 = new boolean[] { true, true }; assertEquals( 0, comparator.compare( null, null ) ); assertEquals( 0, comparator.compare( new boolean[] {}, new boolean[] {} ) ); assertEquals( 0, comparator.compare( b1, b1 ) ); assertEquals( -1, comparator.compare( null, new boolean[] {} ) ); assertEquals( -1, comparator.compare( null, b1 ) ); assertEquals( -1, comparator.compare( new boolean[] {}, b1 ) ); assertEquals( -1, comparator.compare( new boolean[] {}, b4 ) ); assertEquals( -1, comparator.compare( b5, b1 ) ); assertEquals( -1, comparator.compare( b5, b3 ) ); assertEquals( 1, comparator.compare( new boolean[] {}, null ) ); assertEquals( 1, comparator.compare( b1, null ) ); assertEquals( 1, comparator.compare( b1, new boolean[] {} ) ); assertEquals( 1, comparator.compare( b1, b2 ) ); assertEquals( 1, comparator.compare( b1, b3 ) ); assertEquals( 1, comparator.compare( b1, b4 ) ); assertEquals( 1, comparator.compare( b1, b5 ) ); }
### Question: CharArrayComparator implements Comparator<char[]> { private CharArrayComparator() { } private CharArrayComparator(); int compare( char[] charArray1, char[] charArray2 ); static final CharArrayComparator INSTANCE; }### Answer: @Test public void testCharArrayComparator() { CharArrayComparator comparator = CharArrayComparator.INSTANCE; assertEquals( 0, comparator.compare( null, null ) ); assertEquals( 0, comparator.compare( new char[] {}, new char[] {} ) ); assertEquals( 0, comparator.compare( new char[] { 'a', 'b' }, new char[] { 'a', 'b' } ) ); assertEquals( 1, comparator.compare( new char[] {}, null ) ); assertEquals( 1, comparator.compare( new char[] { 'a' }, null ) ); assertEquals( 1, comparator.compare( new char[] { 'a', 'b' }, new char[] { 'a', 'a' } ) ); assertEquals( 1, comparator.compare( new char[] { 'a', 'b', 'a' }, new char[] { 'a', 'b' } ) ); assertEquals( 1, comparator.compare( new char[] { 'a', 'b' }, new char[] { 'a', 'a', 'b' } ) ); assertEquals( -1, comparator.compare( null, new char[] {} ) ); assertEquals( -1, comparator.compare( null, new char[] { 'a', 'b' } ) ); assertEquals( -1, comparator.compare( null, new char[] { '\uffff', 'b' } ) ); assertEquals( -1, comparator.compare( new char[] {}, new char[] { 'a', 'b' } ) ); assertEquals( -1, comparator.compare( new char[] {}, new char[] { '\uffff', 'b' } ) ); assertEquals( -1, comparator.compare( new char[] { '0', 'a' }, new char[] { 'a', 'a', 'b' } ) ); char[] array = new char[3]; array[0] = 'a'; array[1] = 'b'; assertEquals( -1, comparator.compare( new char[] { 'a', 'b' }, array ) ); }
### Question: ByteComparator implements Comparator<Byte> { private ByteComparator() { } private ByteComparator(); int compare( Byte byte1, Byte byte2 ); static final ByteComparator INSTANCE; }### Answer: @Test public void testByteComparator() { ByteComparator comparator = ByteComparator.INSTANCE; assertEquals( 0, comparator.compare( null, null ) ); assertEquals( 0, comparator.compare( ( byte ) 0x00, ( byte ) 0x00 ) ); assertEquals( 0, comparator.compare( ( byte ) 0xFE, ( byte ) 0xFE ) ); assertEquals( 1, comparator.compare( ( byte ) 0x01, null ) ); assertEquals( 1, comparator.compare( ( byte ) 0x01, ( byte ) 0x00 ) ); assertEquals( 1, comparator.compare( ( byte ) 0x00, ( byte ) 0xFF ) ); assertEquals( 1, comparator.compare( ( byte ) 0x7F, ( byte ) 0x01 ) ); assertEquals( -1, comparator.compare( null, ( byte ) 0x00 ) ); assertEquals( -1, comparator.compare( null, ( byte ) 0xFF ) ); assertEquals( -1, comparator.compare( ( byte ) 0x00, ( byte ) 0x01 ) ); assertEquals( -1, comparator.compare( ( byte ) 0xF0, ( byte ) 0xFF ) ); assertEquals( -1, comparator.compare( ( byte ) 0xFF, ( byte ) 0x01 ) ); }
### Question: LongComparator implements Comparator<Long> { private LongComparator() { } private LongComparator(); int compare( Long long1, Long long2 ); static final LongComparator INSTANCE; }### Answer: @Test public void testLongComparator() { LongComparator comparator = LongComparator.INSTANCE; assertEquals( 0, comparator.compare( null, null ) ); assertEquals( 0, comparator.compare( 1L, 1L ) ); assertEquals( 0, comparator.compare( -1L, -1L ) ); assertEquals( 1, comparator.compare( 1L, null ) ); assertEquals( 1, comparator.compare( 2L, 1L ) ); assertEquals( 1, comparator.compare( 3L, 1L ) ); assertEquals( 1, comparator.compare( 1L, -1L ) ); assertEquals( -1, comparator.compare( null, 1L ) ); assertEquals( -1, comparator.compare( 1L, 2L ) ); assertEquals( -1, comparator.compare( -1L, 1L ) ); }
### Question: IntComparator implements Comparator<Integer> { private IntComparator() { } private IntComparator(); int compare( Integer integer1, Integer integer2 ); static final IntComparator INSTANCE; }### Answer: @Test public void testIntComparator() { IntComparator comparator = IntComparator.INSTANCE; assertEquals( 0, comparator.compare( null, null ) ); assertEquals( 0, comparator.compare( 1, 1 ) ); assertEquals( 0, comparator.compare( -1, -1 ) ); assertEquals( 1, comparator.compare( 1, null ) ); assertEquals( 1, comparator.compare( 2, 1 ) ); assertEquals( 1, comparator.compare( 3, 1 ) ); assertEquals( 1, comparator.compare( 1, -1 ) ); assertEquals( -1, comparator.compare( null, 1 ) ); assertEquals( -1, comparator.compare( 1, 2 ) ); assertEquals( -1, comparator.compare( -1, 1 ) ); }
### Question: BooleanComparator implements Comparator<Boolean> { private BooleanComparator() { } private BooleanComparator(); int compare( Boolean boolean1, Boolean boolean2 ); static final BooleanComparator INSTANCE; }### Answer: @Test public void testBooleanComparator() { BooleanComparator comparator = BooleanComparator.INSTANCE; assertEquals( 0, comparator.compare( null, null ) ); assertEquals( 0, comparator.compare( true, true ) ); assertEquals( 0, comparator.compare( false, false ) ); assertEquals( 1, comparator.compare( false, null ) ); assertEquals( 1, comparator.compare( true, null ) ); assertEquals( 1, comparator.compare( true, false ) ); assertEquals( -1, comparator.compare( null, false ) ); assertEquals( -1, comparator.compare( null, true ) ); assertEquals( -1, comparator.compare( false, true ) ); }
### Question: StringComparator implements Comparator<String> { private StringComparator() { } private StringComparator(); int compare( String string1, String string2 ); static final StringComparator INSTANCE; }### Answer: @Test public void testStringComparator() { StringComparator comparator = StringComparator.INSTANCE; assertEquals( 0, comparator.compare( null, null ) ); assertEquals( 0, comparator.compare( "", "" ) ); assertEquals( 0, comparator.compare( "abc", "abc" ) ); assertEquals( 1, comparator.compare( "", null ) ); assertEquals( 1, comparator.compare( "abc", "" ) ); assertEquals( 1, comparator.compare( "ac", "ab" ) ); assertEquals( 1, comparator.compare( "abc", "ab" ) ); assertEquals( -1, comparator.compare( null, "" ) ); assertEquals( -1, comparator.compare( "ab", "abc" ) ); assertEquals( -1, comparator.compare( "ab", "abc" ) ); }
### Question: IntArrayComparator implements Comparator<int[]> { private IntArrayComparator() { } private IntArrayComparator(); int compare( int[] intArray1, int[] intArray2 ); static final IntArrayComparator INSTANCE; }### Answer: @Test public void testIntArrayComparator() { IntArrayComparator comparator = IntArrayComparator.INSTANCE; assertEquals( 0, comparator.compare( null, null ) ); assertEquals( 0, comparator.compare( new int[] {}, new int[] {} ) ); assertEquals( 0, comparator.compare( new int[] { 1, 2 }, new int[] { 1, 2 } ) ); assertEquals( 1, comparator.compare( new int[] {}, null ) ); assertEquals( 1, comparator.compare( new int[] { 1 }, null ) ); assertEquals( 1, comparator.compare( new int[] { 1, 2 }, new int[] { 1, 1 } ) ); assertEquals( 1, comparator.compare( new int[] { 1, 2, 1 }, new int[] { 1, 2 } ) ); assertEquals( 1, comparator.compare( new int[] { 1, 2 }, new int[] { 1, 1, 2 } ) ); assertEquals( -1, comparator.compare( null, new int[] {} ) ); assertEquals( -1, comparator.compare( null, new int[] { 1, 2 } ) ); assertEquals( -1, comparator.compare( null, new int[] { -1, 2 } ) ); assertEquals( -1, comparator.compare( new int[] {}, new int[] { 1, 2 } ) ); assertEquals( -1, comparator.compare( new int[] {}, new int[] { -1, 2 } ) ); assertEquals( -1, comparator.compare( new int[] { -1, 1 }, new int[] { 1, 1, 2 } ) ); int[] array = new int[3]; array[0] = 1; array[1] = 2; assertEquals( -1, comparator.compare( new int[] { 1, 2 }, array ) ); }
### Question: CanBeClaimed implements Feature { @Override public CanBeClaimed of(JobView jobView) { this.job = jobView; return this; } @Override CanBeClaimed of(JobView jobView); @Override Claim asJson(); }### Answer: @Test public void should_know_if_a_failing_build_has_been_claimed() throws Exception { String ourPotentialHero = "Adam", theReason = "I broke it, sorry, fixing now"; job = a(jobView().which(new CanBeClaimed()).of( a(job().whereTheLast(build().finishedWith(FAILURE).and().wasClaimedBy(ourPotentialHero, theReason))))); assertThat(serialisedClaimOf(job).author(), is(ourPotentialHero)); assertThat(serialisedClaimOf(job).reason(), is(theReason)); } @Test public void should_know_if_a_failing_build_has_not_been_claimed() throws Exception { job = a(jobView().which(new CanBeClaimed()).of( a(job().whereTheLast(build().finishedWith(FAILURE))))); assertThat(serialisedClaimOf(job), is(nullValue())); } @Test public void should_complain_if_the_build_was_not_claimable() throws Exception { job = a(jobView().of( a(job().withName("my-project").whereTheLast(build().finishedWith(FAILURE))))); thrown.expectMessage("CanBeClaimed is not a feature of this project: 'my-project'"); job.which(CanBeClaimed.class); }
### Question: HasBadgesBadgePlugin implements Feature<HasBadgesBadgePlugin.Badges> { @Override public HasBadgesBadgePlugin of(JobView jobView) { this.job = jobView; return this; } @Override HasBadgesBadgePlugin of(JobView jobView); @Override Badges asJson(); }### Answer: @Test public void should_support_job_without_badges() throws Exception { job = a(jobView().which(new HasBadgesBadgePlugin()).of( a(job()))); assertThat(serialisedBadgesDetailsOf(job), is(nullValue())); } @Test public void should_convert_badges_to_json() throws Exception { job = a(jobView().which(new HasBadgesBadgePlugin()).of( a(job().whereTheLast(build().hasBadgesBadgePlugin(badgePluginBadge().withText("badge1"), badgePluginBadge().withText("badge2")))))); assertThat(serialisedBadgesDetailsOf(job).value(), hasSize(2)); } @Test public void should_ignore_badges_with_icon() throws Exception { job = a(jobView().which(new HasBadgesBadgePlugin()).of( a(job().whereTheLast(build().hasBadgesBadgePlugin(badgePluginBadge().withIcon("icon.gif", "badge1"), badgePluginBadge().withText("badge2")))))); assertThat(serialisedBadgesDetailsOf(job).value(), hasSize(1)); } @Test public void should_report_badges_from_latest_build() throws Exception { job = a(jobView().which(new HasBadgesBadgePlugin()).of( a(job().whereTheLast(build().isStillBuilding().hasBadgesBadgePlugin(badgePluginBadge().withText("badge1"))) .andThePrevious(build().hasBadgesBadgePlugin(badgePluginBadge().withText("badge1"), badgePluginBadge().withText("badge2")))))); assertThat(serialisedBadgesDetailsOf(job).value(), hasSize(1)); }
### Question: PipelineHelper { public static boolean isWorkflowRun(Run<?, ?> build, StaticJenkinsAPIs staticJenkinsAPIs) { if (hasWorkflowClass == null) { if (!staticJenkinsAPIs.hasPlugin(PIPELINE_PLUGIN)) { hasWorkflowClass = false; return false; } try { workflowRunClass = Class.forName(WORKFLOW_RUN_CLASS_NAME); hasWorkflowClass = true; } catch (ClassNotFoundException e) { hasWorkflowClass = false; return false; } } if (hasWorkflowClass) { return workflowRunClass.isInstance(build); } return false; } private PipelineHelper(); static boolean isWorkflowRun(Run<?, ?> build, StaticJenkinsAPIs staticJenkinsAPIs); static List<String> getPipelines(Run<?, ?> run); }### Answer: @Test public void isWorkflowRun() { Assert.assertTrue(PipelineHelper.isWorkflowRun(workflowRun, new StaticJenkinsAPIs())); } @Test public void isNotWorkflowRun() { Assert.assertFalse(PipelineHelper.isWorkflowRun(abstractBuild, new StaticJenkinsAPIs())); }
### Question: BuildMonitorInstallation { public String anonymousCorrelationId() { if (UNKNOWN.equalsIgnoreCase(anonymousCorrelationId)) { anonymousCorrelationId = sha256().hashString(jenkins.encodedPublicKey(), UTF_8).toString(); } return anonymousCorrelationId; } BuildMonitorInstallation(); BuildMonitorInstallation(StaticJenkinsAPIs jenkinsAPIs); String anonymousCorrelationId(); int size(); Audience audience(); String buildMonitorVersion(); }### Answer: @Test public void helps_to_avoid_duplicated_stats_and_keep_jenkins_instance_anonymous() throws Exception { BuildMonitorInstallation installation = new BuildMonitorInstallation(withPublicKey(PUBLIC_KEY)); assertThat(installation.anonymousCorrelationId(), is(not(PUBLIC_KEY))); assertThat(installation.anonymousCorrelationId().length(), is(64)); } @Test public void only_calculates_the_correlation_hash_once() throws Exception { StaticJenkinsAPIs jenkinsAPIs = withPublicKey(PUBLIC_KEY); BuildMonitorInstallation installation = new BuildMonitorInstallation(jenkinsAPIs); installation.anonymousCorrelationId(); installation.anonymousCorrelationId(); verify(jenkinsAPIs, times(1)).encodedPublicKey(); }
### Question: BuildMonitorDescriptor extends ViewDescriptor { public FormValidation doCheckIncludeRegex(@QueryParameter String value) { String v = Util.fixEmpty(value); if (v != null) { try { Pattern.compile(v); } catch (PatternSyntaxException pse) { return FormValidation.error(pse.getMessage()); } } return FormValidation.ok(); } BuildMonitorDescriptor(); @Override String getDisplayName(); FormValidation doCheckIncludeRegex(@QueryParameter String value); @Override boolean configure(StaplerRequest req, JSONObject json); boolean getPermissionToCollectAnonymousUsageStatistics(); @SuppressWarnings("unused") // used in global.jelly void setPermissionToCollectAnonymousUsageStatistics(boolean collect); }### Answer: @Test public void form_validator_should_allow_valid_reg_ex_specifying_what_jobs_to_include() throws Exception { for (String regex : asFollows(null, "", ".*", "myproject-.*")) { assertThat(itShouldAllow(regex), validator.doCheckIncludeRegex(regex).kind, is(OK)); } } @Test public void form_validator_should_advise_how_a_regex_could_be_improved() throws Exception { FormValidation result = validator.doCheckIncludeRegex(")"); assertThat(result.kind, is(ERROR)); assertThat(htmlDecoded(result.getMessage()), containsString("Unmatched closing ')'")); }
### Question: CanBeDiagnosedForProblems implements Feature<CanBeDiagnosedForProblems.Problems> { @Override public CanBeDiagnosedForProblems of(JobView jobView) { this.job = jobView; return this; } CanBeDiagnosedForProblems(BuildFailureAnalyzerDisplayedField displayedField); @Override CanBeDiagnosedForProblems of(JobView jobView); @Override Problems asJson(); }### Answer: @Test public void should_describe_known_problems() { String rogueAi = "Pod bay doors didn't open"; job = a(jobView().which(new CanBeDiagnosedForProblems(BuildFailureAnalyzerDisplayedField.Name)).of( a(job().whereTheLast(build().finishedWith(FAILURE).and().knownProblems(rogueAi))))); assertThat(diagnosedFailuresOf(job).value(), hasItem(rogueAi)); }
### Question: GameAnnouncement { public static GameAnnouncementFactory getFactory() { return new GameAnnouncementFactory(); } GameAnnouncement(); static GameAnnouncementFactory getFactory(); final GameType getGameType(); final CardList getDiscardedCards(); final boolean isSchneider(); final boolean isSchwarz(); final boolean isOuvert(); final boolean isHand(); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer: @Test public void testEmptyGameType() { final GameAnnouncementFactory factory = GameAnnouncement.getFactory(); final GameAnnouncement announcement = factory.getAnnouncement(); assertNull(announcement); }
### Question: CardDeck extends CardList { public static EnumSet<Card> getAllCards() { EnumSet<Card> allCards = EnumSet.allOf(Card.class); return allCards; } CardDeck(); CardDeck(List<Card> foreHandCards, List<Card> middleHandCards, List<Card> rearHandCards, List<Card> skatCards); CardDeck(String foreHandCards, String middleHandCards, String rearHandCards, String skatCards); CardDeck(final String cards); CardDeck(final CardList cards); @Override boolean add(final Card card); static EnumSet<Card> getAllCards(); static CardDeck getPerfectDistribution(); void shuffle(); final static Map<Suit, List<Card>> SUIT_CARDS; final static Map<Rank, List<Card>> RANK_CARDS; }### Answer: @Test public void getAllCards001() { assertThat(CardDeck.getAllCards()).hasSize(32); }
### Question: CardDeck extends CardList { @Override public boolean add(final Card card) { if (size() == MAX_CARDS) { throw new IllegalStateException("Card deck is already filled with " + MAX_CARDS + " cards."); } if (contains(card)) { throw new IllegalArgumentException("Card " + card + " is already contained in card deck."); } return super.add(card); } CardDeck(); CardDeck(List<Card> foreHandCards, List<Card> middleHandCards, List<Card> rearHandCards, List<Card> skatCards); CardDeck(String foreHandCards, String middleHandCards, String rearHandCards, String skatCards); CardDeck(final String cards); CardDeck(final CardList cards); @Override boolean add(final Card card); static EnumSet<Card> getAllCards(); static CardDeck getPerfectDistribution(); void shuffle(); final static Map<Suit, List<Card>> SUIT_CARDS; final static Map<Rank, List<Card>> RANK_CARDS; }### Answer: @Test public void addDoubleCard() { assertThrows(IllegalArgumentException.class, () -> { final CardDeck cards = new CardDeck(); cards.remove(Card.CA); cards.add(Card.CJ); }); } @Test public void addTooMuchCards() { assertThrows(IllegalStateException.class, () -> { final CardDeck cards = new CardDeck( "CJ SJ HJ CK CQ SK C7 C8 S7 H7 D7 DJ CA CT C9 SQ HA HK HQ S8 H8 H9 HT SA ST S9 D8 D9 DT DA DK DQ"); cards.add(Card.CJ); }); }
### Question: VersionChecker { public static boolean isHigherVersionAvailable(final String localVersion, final String remoteVersion) { boolean result = false; List<Integer> localVersionParts = getVersionParts(localVersion); List<Integer> remoteVersionParts = getVersionParts(remoteVersion); int previousLocalPart = 0; int previousRemotePart = 0; int index = 0; for (Integer localVersionPart : localVersionParts) { if (remoteVersionParts.size() > index) { int remoteVersionPart = remoteVersionParts.get(index); if (previousLocalPart == previousRemotePart && localVersionPart < remoteVersionPart) { result = true; } previousLocalPart = localVersionPart; previousRemotePart = remoteVersionPart; } index++; } return result; } static String getLatestVersion(); static boolean isHigherVersionAvailable(final String localVersion, final String remoteVersion); }### Answer: @Test public void testIsHigherVersionAvailable() { assertTrue(VersionChecker.isHigherVersionAvailable("0.10.0", "0.10.1")); assertTrue(VersionChecker.isHigherVersionAvailable("0.10.1", "1.0.0")); assertTrue(VersionChecker.isHigherVersionAvailable("0.10.1", "0.11.0")); assertFalse(VersionChecker.isHigherVersionAvailable("0.11.0", "0.10.1")); assertFalse(VersionChecker.isHigherVersionAvailable("0.10.0", "0.10.0")); assertFalse(VersionChecker.isHigherVersionAvailable("0.10.0", "0.9.0")); }
### Question: NullRule extends AbstractSkatRule { @Override public int calcGameResult(final SkatGameData gameData) { int result = getGameValueForWonGame(gameData); if (gameData.isGameLost()) { result = result * -2; } return result; } @Override int getGameValueForWonGame(final SkatGameData gameData); @Override int calcGameResult(final SkatGameData gameData); @Override boolean isCardBeatsCard( @SuppressWarnings("unused") final GameType gameType, final Card cardToBeat, final Card card); @Override boolean isCardAllowed(final GameType gameType, final Card initialCard, final CardList hand, final Card card); @Override boolean isGameWon(final SkatGameData gameData); @Override boolean hasSuit(final GameType gameType, final CardList hand, final Suit suit); @Override int getMultiplier( @SuppressWarnings("unused") final SkatGameData gameData); @Override boolean isPlayWithJacks( @SuppressWarnings("unused") final SkatGameData gameData); }### Answer: @Test public void calcGameResultGameLostHand() { factory.setHand(true); data.setAnnouncement(factory.getAnnouncement()); playWinningTricks(); playLoosingTrick(); data.calcResult(); assertThat(nullRules.calcGameResult(data)).isEqualTo(-70); } @Test public void calcGameResultGameLostOuvert() { factory.setHand(false); factory.setOuvert(Boolean.TRUE); data.setAnnouncement(factory.getAnnouncement()); playWinningTricks(); playLoosingTrick(); data.calcResult(); assertThat(nullRules.calcGameResult(data)).isEqualTo(-92); } @Test public void calcGameResultGameLostHandOuvert() { factory.setHand(true); factory.setOuvert(true); data.setAnnouncement(factory.getAnnouncement()); playWinningTricks(); playLoosingTrick(); data.calcResult(); assertThat(nullRules.calcGameResult(data)).isEqualTo(-118); }
### Question: JSkatPlayerResolver { public static Set<String> getAllAIPlayerImplementations() { final Set<String> result = getAllImplementations(); result.removeAll(EXCLUDED_PLAYER_CLASSES); result.removeAll(UNIT_TEST_PLAYER_CLASSES); LOG.info("Found {} implementations of AbstractJSkatPlayer.", result.size()); return result; } static Set<String> getAllAIPlayerImplementations(); static final String HUMAN_PLAYER_CLASS; static final Set<String> EXCLUDED_PLAYER_CLASSES; static final Set<String> UNIT_TEST_PLAYER_CLASSES; }### Answer: @Test public void testGetAllAIPlayerImplementations() { final Set<String> implementations = JSkatPlayerResolver.getAllAIPlayerImplementations(); assertThat(implementations).hasSize(2); }
### Question: BidEvaluator { int getMaxBid() { return maxBid; } BidEvaluator(final CardList cards); }### Answer: @Test public void testGetMaxBid() { log.debug("++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); final CardList cards = new CardList(Arrays.asList(Card.CJ, Card.DJ, Card.CA, Card.CK, Card.CQ, Card.C8, Card.SQ, Card.HT, Card.H8, Card.D9)); BidEvaluator eval = new BidEvaluator(cards); assertThat(eval.getMaxBid()).isEqualTo(24); cards.remove(Card.DJ); cards.add(Card.SJ); cards.sort(null); eval = new BidEvaluator(cards); assertThat(eval.getMaxBid()).isEqualTo(36); log.debug("++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); }
### Question: RamschRule extends SuitGrandRamschRule { @Override public int getMultiplier(final SkatGameData gameData) { int multiplier = 1; if (gameData.isJungfrau()) { log.debug("One player is jungfrau"); multiplier = 2; } log.debug(gameData.getGeschoben() + " player did schieben"); multiplier = (int) (multiplier * Math.pow(2, gameData.getGeschoben())); return multiplier; } @Override int getGameValueForWonGame(final SkatGameData gameData); @Override int calcGameResult(final SkatGameData gameData); @Override boolean isGameWon(final SkatGameData gameData); static final boolean isDurchmarsch(final Player player, final SkatGameData gameData); static final boolean isJungfrau(final Player player, final SkatGameData gameData); @Override int getMultiplier(final SkatGameData gameData); @Override boolean isPlayWithJacks(final SkatGameData gameData); }### Answer: @Test public void testGetMultiplierGeschoben() { assertThat(ramschRules.getMultiplier(data)).isEqualTo(1); data.addGeschoben(); assertThat(ramschRules.getMultiplier(data)).isEqualTo(2); data.addGeschoben(); assertThat(ramschRules.getMultiplier(data)).isEqualTo(4); data.addGeschoben(); assertThat(ramschRules.getMultiplier(data)).isEqualTo(8); }
### Question: ProductServiceImpl implements ProductService { @Override public ProductInfo findOne(String productId) { return repository.findOne(productId); } @Override ProductInfo findOne(String productId); @Override List<ProductInfo> findUpAll(); @Override Page<ProductInfo> findAll(Pageable pageable); @Override ProductInfo save(ProductInfo productInfo); @Override @Transactional void increaseStock(List<CartDTO> cartDTOList); @Override @Transactional void decreaseStock(List<CartDTO> cartDTOList); @Override ProductInfo onSale(String productId); @Override ProductInfo offSale(String productId); }### Answer: @Test public void findOne() throws Exception { ProductInfo productInfo = productService.findOne("123456"); Assert.assertEquals("123456", productInfo.getProductId()); }
### Question: CategoryServiceImpl implements CategoryService { @Override public List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList) { return repository.findByCategoryTypeIn(categoryTypeList); } @Override ProductCategory findOne(Integer categoryId); @Override List<ProductCategory> findAll(); @Override List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList); @Override ProductCategory save(ProductCategory productCategory); }### Answer: @Test public void findByCategoryTypeIn() throws Exception { List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(Arrays.asList(1,2,3,4)); Assert.assertNotEquals(0, productCategoryList.size()); }
### Question: CategoryServiceImpl implements CategoryService { @Override public ProductCategory save(ProductCategory productCategory) { return repository.save(productCategory); } @Override ProductCategory findOne(Integer categoryId); @Override List<ProductCategory> findAll(); @Override List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList); @Override ProductCategory save(ProductCategory productCategory); }### Answer: @Test public void save() throws Exception { ProductCategory productCategory = new ProductCategory("男生专享", 10); ProductCategory result = categoryService.save(productCategory); Assert.assertNotNull(result); }
### Question: OrderServiceImpl implements OrderService { @Override public OrderDTO findOne(String orderId) { OrderMaster orderMaster = orderMasterRepository.findOne(orderId); if (orderMaster == null) { throw new SellException(ResultEnum.ORDER_NOT_EXIST); } List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderId); if (CollectionUtils.isEmpty(orderDetailList)) { throw new SellException(ResultEnum.ORDERDETAIL_NOT_EXIST); } OrderDTO orderDTO = new OrderDTO(); BeanUtils.copyProperties(orderMaster, orderDTO); orderDTO.setOrderDetailList(orderDetailList); return orderDTO; } @Override @Transactional OrderDTO create(OrderDTO orderDTO); @Override OrderDTO findOne(String orderId); @Override Page<OrderDTO> findList(String buyerOpenid, Pageable pageable); @Override @Transactional OrderDTO cancel(OrderDTO orderDTO); @Override @Transactional OrderDTO finish(OrderDTO orderDTO); @Override @Transactional OrderDTO paid(OrderDTO orderDTO); @Override Page<OrderDTO> findList(Pageable pageable); }### Answer: @Test public void findOne() throws Exception { OrderDTO result = orderService.findOne(ORDER_ID); log.info("【查询单个订单】result={}", result); Assert.assertEquals(ORDER_ID, result.getOrderId()); }
### Question: OrderServiceImpl implements OrderService { @Override public Page<OrderDTO> findList(String buyerOpenid, Pageable pageable) { Page<OrderMaster> orderMasterPage = orderMasterRepository.findByBuyerOpenid(buyerOpenid, pageable); List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.convert(orderMasterPage.getContent()); return new PageImpl<OrderDTO>(orderDTOList, pageable, orderMasterPage.getTotalElements()); } @Override @Transactional OrderDTO create(OrderDTO orderDTO); @Override OrderDTO findOne(String orderId); @Override Page<OrderDTO> findList(String buyerOpenid, Pageable pageable); @Override @Transactional OrderDTO cancel(OrderDTO orderDTO); @Override @Transactional OrderDTO finish(OrderDTO orderDTO); @Override @Transactional OrderDTO paid(OrderDTO orderDTO); @Override Page<OrderDTO> findList(Pageable pageable); }### Answer: @Test public void findList() throws Exception { PageRequest request = new PageRequest(0,2); Page<OrderDTO> orderDTOPage = orderService.findList(BUYER_OPENID, request); Assert.assertNotEquals(0, orderDTOPage.getTotalElements()); } @Test public void list() { PageRequest request = new PageRequest(0,2); Page<OrderDTO> orderDTOPage = orderService.findList(request); Assert.assertTrue("查询所有的订单列表", orderDTOPage.getTotalElements() > 0); }
### Question: OrderServiceImpl implements OrderService { @Override @Transactional public OrderDTO finish(OrderDTO orderDTO) { if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) { log.error("【完结订单】订单状态不正确, orderId={}, orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus()); throw new SellException(ResultEnum.ORDER_STATUS_ERROR); } orderDTO.setOrderStatus(OrderStatusEnum.FINISHED.getCode()); OrderMaster orderMaster = new OrderMaster(); BeanUtils.copyProperties(orderDTO, orderMaster); OrderMaster updateResult = orderMasterRepository.save(orderMaster); if (updateResult == null) { log.error("【完结订单】更新失败, orderMaster={}", orderMaster); throw new SellException(ResultEnum.ORDER_UPDATE_FAIL); } pushMessageService.orderStatus(orderDTO); return orderDTO; } @Override @Transactional OrderDTO create(OrderDTO orderDTO); @Override OrderDTO findOne(String orderId); @Override Page<OrderDTO> findList(String buyerOpenid, Pageable pageable); @Override @Transactional OrderDTO cancel(OrderDTO orderDTO); @Override @Transactional OrderDTO finish(OrderDTO orderDTO); @Override @Transactional OrderDTO paid(OrderDTO orderDTO); @Override Page<OrderDTO> findList(Pageable pageable); }### Answer: @Test public void finish() throws Exception { OrderDTO orderDTO = orderService.findOne(ORDER_ID); OrderDTO result = orderService.finish(orderDTO); Assert.assertEquals(OrderStatusEnum.FINISHED.getCode(), result.getOrderStatus()); }
### Question: OrderServiceImpl implements OrderService { @Override @Transactional public OrderDTO paid(OrderDTO orderDTO) { if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) { log.error("【订单支付完成】订单状态不正确, orderId={}, orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus()); throw new SellException(ResultEnum.ORDER_STATUS_ERROR); } if (!orderDTO.getPayStatus().equals(PayStatusEnum.WAIT.getCode())) { log.error("【订单支付完成】订单支付状态不正确, orderDTO={}", orderDTO); throw new SellException(ResultEnum.ORDER_PAY_STATUS_ERROR); } orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode()); OrderMaster orderMaster = new OrderMaster(); BeanUtils.copyProperties(orderDTO, orderMaster); OrderMaster updateResult = orderMasterRepository.save(orderMaster); if (updateResult == null) { log.error("【订单支付完成】更新失败, orderMaster={}", orderMaster); throw new SellException(ResultEnum.ORDER_UPDATE_FAIL); } return orderDTO; } @Override @Transactional OrderDTO create(OrderDTO orderDTO); @Override OrderDTO findOne(String orderId); @Override Page<OrderDTO> findList(String buyerOpenid, Pageable pageable); @Override @Transactional OrderDTO cancel(OrderDTO orderDTO); @Override @Transactional OrderDTO finish(OrderDTO orderDTO); @Override @Transactional OrderDTO paid(OrderDTO orderDTO); @Override Page<OrderDTO> findList(Pageable pageable); }### Answer: @Test public void paid() throws Exception { OrderDTO orderDTO = orderService.findOne(ORDER_ID); OrderDTO result = orderService.paid(orderDTO); Assert.assertEquals(PayStatusEnum.SUCCESS.getCode(), result.getPayStatus()); }
### Question: PayServiceImpl implements PayService { @Override public PayResponse create(OrderDTO orderDTO) { PayRequest payRequest = new PayRequest(); payRequest.setOpenid(orderDTO.getBuyerOpenid()); payRequest.setOrderAmount(orderDTO.getOrderAmount().doubleValue()); payRequest.setOrderId(orderDTO.getOrderId()); payRequest.setOrderName(ORDER_NAME); payRequest.setPayTypeEnum(BestPayTypeEnum.WXPAY_H5); log.info("【微信支付】发起支付, request={}", JsonUtil.toJson(payRequest)); PayResponse payResponse = bestPayService.pay(payRequest); log.info("【微信支付】发起支付, response={}", JsonUtil.toJson(payResponse)); return payResponse; } @Override PayResponse create(OrderDTO orderDTO); @Override PayResponse notify(String notifyData); @Override RefundResponse refund(OrderDTO orderDTO); }### Answer: @Test public void create() throws Exception { OrderDTO orderDTO = orderService.findOne("1499097366838352541"); payService.create(orderDTO); }
### Question: ProductServiceImpl implements ProductService { @Override public List<ProductInfo> findUpAll() { return repository.findByProductStatus(ProductStatusEnum.UP.getCode()); } @Override ProductInfo findOne(String productId); @Override List<ProductInfo> findUpAll(); @Override Page<ProductInfo> findAll(Pageable pageable); @Override ProductInfo save(ProductInfo productInfo); @Override @Transactional void increaseStock(List<CartDTO> cartDTOList); @Override @Transactional void decreaseStock(List<CartDTO> cartDTOList); @Override ProductInfo onSale(String productId); @Override ProductInfo offSale(String productId); }### Answer: @Test public void findUpAll() throws Exception { List<ProductInfo> productInfoList = productService.findUpAll(); Assert.assertNotEquals(0, productInfoList.size()); }
### Question: PayServiceImpl implements PayService { @Override public RefundResponse refund(OrderDTO orderDTO) { RefundRequest refundRequest = new RefundRequest(); refundRequest.setOrderId(orderDTO.getOrderId()); refundRequest.setOrderAmount(orderDTO.getOrderAmount().doubleValue()); refundRequest.setPayTypeEnum(BestPayTypeEnum.WXPAY_H5); log.info("【微信退款】request={}", JsonUtil.toJson(refundRequest)); RefundResponse refundResponse = bestPayService.refund(refundRequest); log.info("【微信退款】response={}", JsonUtil.toJson(refundResponse)); return refundResponse; } @Override PayResponse create(OrderDTO orderDTO); @Override PayResponse notify(String notifyData); @Override RefundResponse refund(OrderDTO orderDTO); }### Answer: @Test public void refund() { OrderDTO orderDTO = orderService.findOne("1499592887470659070"); payService.refund(orderDTO); }
### Question: ProductServiceImpl implements ProductService { @Override public Page<ProductInfo> findAll(Pageable pageable) { return repository.findAll(pageable); } @Override ProductInfo findOne(String productId); @Override List<ProductInfo> findUpAll(); @Override Page<ProductInfo> findAll(Pageable pageable); @Override ProductInfo save(ProductInfo productInfo); @Override @Transactional void increaseStock(List<CartDTO> cartDTOList); @Override @Transactional void decreaseStock(List<CartDTO> cartDTOList); @Override ProductInfo onSale(String productId); @Override ProductInfo offSale(String productId); }### Answer: @Test public void findAll() throws Exception { PageRequest request = new PageRequest(0, 2); Page<ProductInfo> productInfoPage = productService.findAll(request); Assert.assertNotEquals(0, productInfoPage.getTotalElements()); }
### Question: ProductServiceImpl implements ProductService { @Override public ProductInfo save(ProductInfo productInfo) { return repository.save(productInfo); } @Override ProductInfo findOne(String productId); @Override List<ProductInfo> findUpAll(); @Override Page<ProductInfo> findAll(Pageable pageable); @Override ProductInfo save(ProductInfo productInfo); @Override @Transactional void increaseStock(List<CartDTO> cartDTOList); @Override @Transactional void decreaseStock(List<CartDTO> cartDTOList); @Override ProductInfo onSale(String productId); @Override ProductInfo offSale(String productId); }### Answer: @Test public void save() throws Exception { ProductInfo productInfo = new ProductInfo(); productInfo.setProductId("123457"); productInfo.setProductName("皮皮虾"); productInfo.setProductPrice(new BigDecimal(3.2)); productInfo.setProductStock(100); productInfo.setProductDescription("很好吃的虾"); productInfo.setProductIcon("http: productInfo.setProductStatus(ProductStatusEnum.DOWN.getCode()); productInfo.setCategoryType(2); ProductInfo result = productService.save(productInfo); Assert.assertNotNull(result); }
### Question: ProductServiceImpl implements ProductService { @Override public ProductInfo onSale(String productId) { ProductInfo productInfo = repository.findOne(productId); if (productInfo == null) { throw new SellException(ResultEnum.PRODUCT_NOT_EXIST); } if (productInfo.getProductStatusEnum() == ProductStatusEnum.UP) { throw new SellException(ResultEnum.PRODUCT_STATUS_ERROR); } productInfo.setProductStatus(ProductStatusEnum.UP.getCode()); return repository.save(productInfo); } @Override ProductInfo findOne(String productId); @Override List<ProductInfo> findUpAll(); @Override Page<ProductInfo> findAll(Pageable pageable); @Override ProductInfo save(ProductInfo productInfo); @Override @Transactional void increaseStock(List<CartDTO> cartDTOList); @Override @Transactional void decreaseStock(List<CartDTO> cartDTOList); @Override ProductInfo onSale(String productId); @Override ProductInfo offSale(String productId); }### Answer: @Test public void onSale() { ProductInfo result = productService.onSale("123456"); Assert.assertEquals(ProductStatusEnum.UP, result.getProductStatusEnum()); }
### Question: ProductServiceImpl implements ProductService { @Override public ProductInfo offSale(String productId) { ProductInfo productInfo = repository.findOne(productId); if (productInfo == null) { throw new SellException(ResultEnum.PRODUCT_NOT_EXIST); } if (productInfo.getProductStatusEnum() == ProductStatusEnum.DOWN) { throw new SellException(ResultEnum.PRODUCT_STATUS_ERROR); } productInfo.setProductStatus(ProductStatusEnum.DOWN.getCode()); return repository.save(productInfo); } @Override ProductInfo findOne(String productId); @Override List<ProductInfo> findUpAll(); @Override Page<ProductInfo> findAll(Pageable pageable); @Override ProductInfo save(ProductInfo productInfo); @Override @Transactional void increaseStock(List<CartDTO> cartDTOList); @Override @Transactional void decreaseStock(List<CartDTO> cartDTOList); @Override ProductInfo onSale(String productId); @Override ProductInfo offSale(String productId); }### Answer: @Test public void offSale() { ProductInfo result = productService.offSale("123456"); Assert.assertEquals(ProductStatusEnum.DOWN, result.getProductStatusEnum()); }
### Question: SellerServiceImpl implements SellerService { @Override public SellerInfo findSellerInfoByOpenid(String openid) { return repository.findByOpenid(openid); } @Override SellerInfo findSellerInfoByOpenid(String openid); }### Answer: @Test public void findSellerInfoByOpenid() throws Exception { SellerInfo result = sellerService.findSellerInfoByOpenid(openid); Assert.assertEquals(openid, result.getOpenid()); }
### Question: PushMessageServiceImpl implements PushMessageService { @Override public void orderStatus(OrderDTO orderDTO) { WxMpTemplateMessage templateMessage = new WxMpTemplateMessage(); templateMessage.setTemplateId(accountConfig.getTemplateId().get("orderStatus")); templateMessage.setToUser(orderDTO.getBuyerOpenid()); List<WxMpTemplateData> data = Arrays.asList( new WxMpTemplateData("first", "亲,请记得收货。"), new WxMpTemplateData("keyword1", "微信点餐"), new WxMpTemplateData("keyword2", "18868812345"), new WxMpTemplateData("keyword3", orderDTO.getOrderId()), new WxMpTemplateData("keyword4", orderDTO.getOrderStatusEnum().getMessage()), new WxMpTemplateData("keyword5", "¥" + orderDTO.getOrderAmount()), new WxMpTemplateData("remark", "欢迎再次光临!") ); templateMessage.setData(data); try { wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage); }catch (WxErrorException e) { log.error("【微信模版消息】发送失败, {}", e); } } @Override void orderStatus(OrderDTO orderDTO); }### Answer: @Test public void orderStatus() throws Exception { OrderDTO orderDTO = orderService.findOne("1499097346204378750"); pushMessageService.orderStatus(orderDTO); }
### Question: CategoryServiceImpl implements CategoryService { @Override public ProductCategory findOne(Integer categoryId) { return repository.findOne(categoryId); } @Override ProductCategory findOne(Integer categoryId); @Override List<ProductCategory> findAll(); @Override List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList); @Override ProductCategory save(ProductCategory productCategory); }### Answer: @Test public void findOne() throws Exception { ProductCategory productCategory = categoryService.findOne(1); Assert.assertEquals(new Integer(1), productCategory.getCategoryId()); }
### Question: CategoryServiceImpl implements CategoryService { @Override public List<ProductCategory> findAll() { return repository.findAll(); } @Override ProductCategory findOne(Integer categoryId); @Override List<ProductCategory> findAll(); @Override List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList); @Override ProductCategory save(ProductCategory productCategory); }### Answer: @Test public void findAll() throws Exception { List<ProductCategory> productCategoryList = categoryService.findAll(); Assert.assertNotEquals(0, productCategoryList.size()); }
### Question: Util { public static int len(Object[] arr) { return empty(arr) ? 0 : arr.length; } private Util(); static int len(Object[] arr); static int len(Collection collection); static int len(Map map); static int len(String str); static boolean empty(String str); static boolean empty(Object[] arr); static boolean empty(Collection collection); static boolean empty(Map map); static boolean empty(char ch); static void validateKey(Object key); static void validateKey(String key); static String obtainValidKey(Class type); static void validateValue(T value, boolean allowNullValues); static void illegalArg(boolean throwIt, String msg); static void illegalState(boolean throwIt, String msg); static void illegalAccess(boolean throwIt, String msg); static void runtimeException(String msg, Throwable thr); static void notNullArg(Object bob, String msg); static void notNull(Object bob, String msg); static void nonEmptyArg(char ch, String msg); static void nonEmptyArg(String str, String msg); static void nonEmptyArg(Object[] arr, String msg); static void nonEmptyArg(Collection collection, String msg); static void nonEmpty(char ch, String msg); static void nonEmpty(String str, String msg); static void nonEmpty(Object[] arr, String msg); static void nonEmpty(Collection collection, String msg); static void nonEmpty(Map map, String msg); @SuppressWarnings("unchecked") static UncheckedFuture<V> unchecked(Future<V> future); static V getUnchecked(Future<V> future); static void pokeball(Throwable pokemon); static void closeSilently(Closeable closeable); @SuppressWarnings("unchecked") static Class<T> checkedClass(T value); static Future<T> present(T result); static ExecutorService newFixedCachedThread(int threads, ThreadFactory threadFactory); @SuppressWarnings("unchecked") static Cache<K, V> newCacheInstance(Class<? extends Cache> imp, CacheOptions opts); }### Answer: @Test public void testLenArray() { assertEquals(0, Util.len((Object[]) null)); assertEquals(0, Util.len(new Object[]{})); assertEquals(1, Util.len(new Object[]{"hello"})); }
### Question: Present implements Future<T> { @Override public T get() throws InterruptedException, ExecutionException { return mValue; } Present(T value); @Override boolean cancel(boolean b); @Override boolean isCancelled(); @Override boolean isDone(); @Override T get(); @Override T get(long l, TimeUnit timeUnit); }### Answer: @Test public void presentWithNullGetsNull() throws ExecutionException, InterruptedException { final Present present = new Present(null); Assert.assertEquals(null, present.get()); } @Test public void presentWithObjGetsObj() throws ExecutionException, InterruptedException { final Object obj = new Object(); Present present = new Present(obj); Assert.assertEquals(obj, present.get()); }
### Question: UncheckedFuture implements Future<V> { public V getUnchecked() { try { return get(); } catch (Throwable pokemon) { Util.pokeball(pokemon); } return null; } UncheckedFuture(Future<V> future); @Override boolean cancel(boolean b); @Override boolean isCancelled(); @Override boolean isDone(); @Override V get(); @Override V get(long l, TimeUnit timeUnit); V getUnchecked(); V getUnchecked(long l, TimeUnit timeUnit); }### Answer: @Test public void getUncheckedWithNullGetsNull() { Assert.assertEquals(null, new UncheckedFuture(null).getUnchecked()); } @Test public void getUncheckedWithObjGetsObj() { final Object obj = new Object(); final Future<Object> theFutureNow = new TheFutureNow(obj); Assert.assertEquals(obj, new UncheckedFuture(theFutureNow).getUnchecked()); }
### Question: UnmodifiableCache implements Cache<K, V> { @Override public UnmodifiableCache<K, V> set(K key, V value) { illegalAccess(true, "You must not try to modify an UnmodifiableCache."); return null; } UnmodifiableCache(Cache<K, V> cache); @Override V get(K key); @Override UnmodifiableCache<K, V> set(K key, V value); }### Answer: @Test (expected = Throwable.class) public void testUnmodifiableIsUnmodifiable() { final ReferenceCache<Object, Object> notNullCache = gimmeReferenceCacheOfOne(); final UnmodifiableCache<Object, Object> unmodifiable = unmodifiable(notNullCache); unmodifiable.set("something", "here"); }
### Question: MapCache implements Cache<K, V> { @Override public MapCache<K, V> set(K key, V value) { if (value == null) { return this; } validateKey(key); mCache.put(key, value); return this; } <O extends MapCache.Options> MapCache(O opts); @Override V get(K key); @Override MapCache<K, V> set(K key, V value); static final float DEFAULT_LOAD_FACTOR; }### Answer: @Test public void testNullNoOp() { gimmeCacheOfOne().set("key", null); }
### Question: AzureFunctionsPlugin implements Plugin<Project> { public void apply(Project project) { AzureFunctionsExtension azureFunctionsExtension = new AzureFunctionsExtension(); project.getExtensions().add(AZURE_FUNCTIONS, azureFunctionsExtension); } void apply(Project project); static final String AZURE_FUNCTIONS; }### Answer: @Test public void greeterPluginAddsGreetingTaskToProject() { Project project = ProjectBuilder.builder().build(); project.getPluginManager().apply("lenala.azure.azurefunctions"); assertTrue(project.getTasks().findByPath("package") instanceof PackageTask); }
### Question: AzureWebappPlugin implements Plugin<Project> { public void apply(Project project) { AzureWebAppExtension azureWebAppExtension = new AzureWebAppExtension(project); project.getExtensions().add(WEBAPP_EXTENSION_NAME, azureWebAppExtension); project.getTasks().create(DeployTask.TASK_NAME, DeployTask.class, (task) -> { task.setAzureWebAppExtension(azureWebAppExtension); }); } void apply(Project project); }### Answer: @Test public void greeterPluginAddsGreetingTaskToProject() { Project project = ProjectBuilder.builder().build(); project.getPluginManager().apply("lenala.azure.azurewebapp"); assertTrue(project.getTasks().findByPath("azureWebappDeploy") instanceof DeployTask); }
### Question: ProteinSubstitution extends ProteinChange { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ProteinSubstitution other = (ProteinSubstitution) obj; if (location == null) { if (other.location != null) return false; } else if (!location.equals(other.location)) return false; if (targetAA == null) { if (other.targetAA != null) return false; } else if (!targetAA.equals(other.targetAA)) return false; return true; } ProteinSubstitution(boolean onlyPredicted, ProteinPointLocation location, String targetAA); static ProteinSubstitution build(boolean onlyPredicted, String sourceAA, int pos, String targetAA); static ProteinSubstitution buildWithOffset(boolean onlyPredicted, String sourceAA, int pos, int offset, String targetAA); static ProteinSubstitution buildDownstreamOfTerminal(boolean onlyPredicted, String sourceAA, int pos, String targetAA); ProteinPointLocation getLocation(); String getTargetAA(); @Override String toHGVSString(AminoAcidCode code); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); @Override ProteinChange withOnlyPredicted(boolean onlyPredicted); }### Answer: @Test public void testEquals() { Assert.assertTrue(sub1.equals(sub2)); Assert.assertTrue(sub2.equals(sub1)); Assert.assertFalse(sub1.equals(sub3)); Assert.assertFalse(sub3.equals(sub1)); }