method2testcases
stringlengths 118
3.08k
|
---|
### Question:
ValidationError { public ValidationError traceId(String traceId) { this.traceId = traceId; return this; } ValidationError type(String type); @javax.annotation.Nullable @ApiModelProperty(example = "https://tools.ietf.org/html/rfc7231#section-6.5.1", value = "") String getType(); void setType(String type); ValidationError title(String title); @javax.annotation.Nullable @ApiModelProperty(example = "One or more validation errors occurred.", value = "") String getTitle(); void setTitle(String title); ValidationError status(BigDecimal status); @javax.annotation.Nullable @ApiModelProperty(example = "400", value = "") BigDecimal getStatus(); void setStatus(BigDecimal status); ValidationError traceId(String traceId); @javax.annotation.Nullable @ApiModelProperty(example = "d200e8b5-4271a5461ce5342f", value = "") String getTraceId(); void setTraceId(String traceId); ValidationError errors(String errors); @javax.annotation.Nullable @ApiModelProperty(value = "") String getErrors(); void setErrors(String errors); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_TYPE; static final String SERIALIZED_NAME_TITLE; static final String SERIALIZED_NAME_STATUS; static final String SERIALIZED_NAME_TRACE_ID; static final String SERIALIZED_NAME_ERRORS; }### Answer:
@Test public void traceIdTest() { } |
### Question:
RunListBuilder { public List<String> build() { return ImmutableList.copyOf(list); } RunListBuilder addRecipe(String recipe); RunListBuilder addRecipes(String... recipes); RunListBuilder addRole(String role); RunListBuilder addRoles(String... roles); List<String> build(); }### Answer:
@Test public void testNoneRecipe() { RunListBuilder options = new RunListBuilder(); assertEquals(options.build(), ImmutableList.<String> of()); } |
### Question:
ParseErrorFromJsonOrReturnBody implements Function<HttpResponse, String> { @Override public String apply(HttpResponse response) { String content = returnStringIf200.apply(response); if (content == null) return null; return parse(content); } @Inject ParseErrorFromJsonOrReturnBody(ReturnStringIf2xx returnStringIf200); @Override String apply(HttpResponse response); String parse(String in); }### Answer:
@Test public void testApplyInputStreamDetails() throws UnknownHostException { InputStream is = Strings2 .toInputStream("{\"error\":[\"invalid tarball: tarball root must contain java-bytearray\"]}"); ParseErrorFromJsonOrReturnBody parser = new ParseErrorFromJsonOrReturnBody(new ReturnStringIf2xx()); String response = parser.apply(HttpResponse.builder().statusCode(200).message("ok").payload(is).build()); assertEquals(response, "invalid tarball: tarball root must contain java-bytearray"); } |
### Question:
BootstrapConfigForGroup implements Function<String, DatabagItem> { @Override public DatabagItem apply(String from) { DatabagItem bootstrapConfig = api.getDatabagItem(databag, from); checkState(bootstrapConfig != null, "databag item %s/%s not found", databag, from); return bootstrapConfig; } @Inject BootstrapConfigForGroup(@Named(CHEF_BOOTSTRAP_DATABAG) String databag, ChefApi api); @Override DatabagItem apply(String from); static final Type BOOTSTRAP_CONFIG_TYPE; }### Answer:
@Test(expectedExceptions = IllegalStateException.class) public void testWhenNoDatabagItem() throws IOException { ChefApi chefApi = createMock(ChefApi.class); Client client = createMock(Client.class); BootstrapConfigForGroup fn = new BootstrapConfigForGroup("jclouds", chefApi); expect(chefApi.getDatabagItem("jclouds", "foo")).andReturn(null); replay(client); replay(chefApi); fn.apply("foo"); verify(client); verify(chefApi); }
@Test public void testReturnsItem() throws IOException { ChefApi chefApi = createMock(ChefApi.class); Api api = createMock(Api.class); BootstrapConfigForGroup fn = new BootstrapConfigForGroup("jclouds", chefApi); DatabagItem config = new DatabagItem("foo", "{\"tomcat6\":{\"ssl_port\":8433},\"run_list\":[\"recipe[apache2]\",\"role[webserver]\"]}"); expect(chefApi.getDatabagItem("jclouds", "foo")).andReturn(config); replay(api); replay(chefApi); assertEquals(fn.apply("foo"), config); verify(api); verify(chefApi); } |
### Question:
RunListForGroup implements Function<String, List<String>> { @Override public List<String> apply(String from) { DatabagItem bootstrapConfig = bootstrapConfigForGroup.apply(from); Map<String, JsonBall> config = json.fromJson(bootstrapConfig.toString(), BootstrapConfigForGroup.BOOTSTRAP_CONFIG_TYPE); JsonBall runlist = config.get("run_list"); return json.fromJson(runlist.toString(), RUN_LIST_TYPE); } @Inject RunListForGroup(BootstrapConfigForGroup bootstrapConfigForGroup, Json json); @Override List<String> apply(String from); static final Type RUN_LIST_TYPE; }### Answer:
@Test(expectedExceptions = IllegalStateException.class) public void testWhenNoDatabagItem() throws IOException { ChefApi chefApi = createMock(ChefApi.class); Client client = createMock(Client.class); RunListForGroup fn = new RunListForGroup(new BootstrapConfigForGroup("jclouds", chefApi), json); expect(chefApi.getDatabagItem("jclouds", "foo")).andReturn(null); replay(client); replay(chefApi); fn.apply("foo"); verify(client); verify(chefApi); }
@Test public void testReadRunList() throws IOException { ChefApi chefApi = createMock(ChefApi.class); Api api = createMock(Api.class); RunListForGroup fn = new RunListForGroup(new BootstrapConfigForGroup("jclouds", chefApi), json); DatabagItem config = new DatabagItem("foo", "{\"tomcat6\":{\"ssl_port\":8433},\"run_list\":[\"recipe[apache2]\",\"role[webserver]\"]}"); expect(chefApi.getDatabagItem("jclouds", "foo")).andReturn(config); replay(api); replay(chefApi); assertEquals(fn.apply("foo"), ImmutableList.of("recipe[apache2]", "role[webserver]")); verify(api); verify(chefApi); } |
### Question:
SignedHeaderAuth implements HttpRequestFilter { @VisibleForTesting String canonicalPath(String path) { path = path.replaceAll("\\/+", "/"); return path.endsWith("/") && path.length() > 1 ? path.substring(0, path.length() - 1) : path; } @Inject SignedHeaderAuth(SignatureWire signatureWire, @org.jclouds.location.Provider Supplier<Credentials> creds,
Supplier<PrivateKey> supplyKey, @TimeStamp Provider<String> timeStampProvider, HttpUtils utils); HttpRequest filter(HttpRequest input); String createStringToSign(String request, String hashedPath, String contentHash, String timestamp); String sign(String toSign); static final String SIGNING_DESCRIPTION; }### Answer:
@Test void canonicalizedPathRemovesMultipleSlashes() { assertEquals(signing_obj.canonicalPath(" }
@Test void canonicalizedPathRemovesTrailingSlash() { assertEquals(signing_obj.canonicalPath("/path/"), "/path"); } |
### Question:
BindGroupToUpdateRequestJsonPayload extends BindToJsonPayload { @Override public <R extends HttpRequest> R bindToRequest(R request, Object payload) { checkArgument(checkNotNull(payload, "payload") instanceof Group, "this binder is only valid for Group objects"); GroupUpdateRequest updateGroup = new GroupUpdateRequest((Group) payload); return super.bindToRequest(request, updateGroup); } @Inject BindGroupToUpdateRequestJsonPayload(Json jsonBinder); @Override R bindToRequest(R request, Object payload); }### Answer:
@Test(expectedExceptions = NullPointerException.class) public void testInvalidNullInput() { HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http: binder.bindToRequest(request, null); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testInvalidTypeInput() { HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http: binder.bindToRequest(request, new Object()); } |
### Question:
BindGroupNameToJsonPayload extends BindToStringPayload { @Override public <R extends HttpRequest> R bindToRequest(R request, Object payload) { super.bindToRequest(request, String.format("{\"groupname\":\"%s\"}", checkNotNull(payload, "payload"))); request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON); return request; } @Override R bindToRequest(R request, Object payload); }### Answer:
@Test(expectedExceptions = NullPointerException.class) public void testInvalidNullInput() { BindGroupNameToJsonPayload binder = new BindGroupNameToJsonPayload(); HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http: binder.bindToRequest(request, null); } |
### Question:
GroupName implements Function<Object, String> { @Override public String apply(Object from) { return ((Group) checkNotNull(from, "from")).getGroupname(); } @Override String apply(Object from); }### Answer:
@Test(expectedExceptions = NullPointerException.class) public void testInvalidNullInput() { new GroupName().apply(null); } |
### Question:
CreateNodeAndPopulateAutomaticAttributesImpl implements CreateNodeAndPopulateAutomaticAttributes { @Override public Node execute(Node node) { logger.trace("creating node %s", node.getName()); node.getAutomatic().putAll(automaticSupplier.get()); chef.createNode(node); logger.debug("created node %s", node.getName()); return node; } @Inject CreateNodeAndPopulateAutomaticAttributesImpl(ChefApi chef,
@Automatic Supplier<Map<String, JsonBall>> automaticSupplier); @Override Node execute(Node node); @Override Node execute(String nodeName, Iterable<String> runList); }### Answer:
@Test public void testWithNoRunlist() { ChefApi chef = createMock(ChefApi.class); Map<String, JsonBall> automatic = ImmutableMap.<String, JsonBall> of(); Node node = new Node("name", ImmutableSet.<String> of(), "_default"); Supplier<Map<String, JsonBall>> automaticSupplier = Suppliers.<Map<String, JsonBall>> ofInstance(automatic); Node nodeWithAutomatic = new Node("name", ImmutableMap.<String, JsonBall> of(), ImmutableMap.<String, JsonBall> of(), ImmutableMap.<String, JsonBall> of(), automatic, ImmutableSet.<String> of(), "_default"); node.getAutomatic().putAll(automaticSupplier.get()); chef.createNode(nodeWithAutomatic); replay(chef); CreateNodeAndPopulateAutomaticAttributesImpl updater = new CreateNodeAndPopulateAutomaticAttributesImpl(chef, automaticSupplier); updater.execute("name", ImmutableSet.<String> of()); verify(chef); } |
### Question:
UpdateAutomaticAttributesOnNodeImpl implements UpdateAutomaticAttributesOnNode { @Override public void execute(String nodeName) { logger.trace("updating node %s", nodeName); Node node = chef.getNode(nodeName); Node mutable = new Node(node.getName(), node.getNormal(), node.getOverride(), node.getDefault(), automaticSupplier.get(), node.getRunList(), node.getChefEnvironment()); chef.updateNode(mutable); logger.debug("updated node %s", nodeName); } @Inject UpdateAutomaticAttributesOnNodeImpl(ChefApi chef, @Automatic Supplier<Map<String, JsonBall>> automaticSupplier); @Override void execute(String nodeName); }### Answer:
@Test public void test() { ChefApi chef = createMock(ChefApi.class); Map<String, JsonBall> automatic = ImmutableMap.<String, JsonBall> of(); Node node = new Node("name", ImmutableSet.<String> of(), "_default"); Supplier<Map<String, JsonBall>> automaticSupplier = Suppliers.<Map<String, JsonBall>> ofInstance(automatic); Node nodeWithAutomatic = new Node("name", ImmutableMap.<String, JsonBall> of(), ImmutableMap.<String, JsonBall> of(), ImmutableMap.<String, JsonBall> of(), automatic, ImmutableSet.<String> of(), "_default"); expect(chef.getNode("name")).andReturn(node); node.getAutomatic().putAll(automaticSupplier.get()); expect(chef.updateNode(nodeWithAutomatic)).andReturn(null); replay(chef); UpdateAutomaticAttributesOnNodeImpl updater = new UpdateAutomaticAttributesOnNodeImpl(chef, automaticSupplier); updater.execute("name"); verify(chef); } |
### Question:
ChefUtils { public static String findRoleInRunList(List<String> runList) { final Pattern pattern = Pattern.compile("^role\\[(.*)\\]$"); String roleToParse = Iterables.find(runList, new Predicate<String>() { @Override public boolean apply(String input) { return pattern.matcher(input).matches(); } }); Matcher matcher = pattern.matcher(roleToParse); matcher.find(); return matcher.group(1); } static Date fromOhaiTime(JsonBall ohaiDate); static JsonBall toOhaiTime(long millis); static MapBinder<String, Supplier<JsonBall>> ohaiAutomaticAttributeBinder(Binder binder); static String findRoleInRunList(List<String> runList); }### Answer:
@Test(expectedExceptions = NoSuchElementException.class) public void testFindRoleInRunListThrowsNoSuchElementOnRecipe() { ChefUtils.findRoleInRunList(ImmutableList.of("recipe[java]")); } |
### Question:
Extension implements FREExtension { @Override public FREContext createContext(String extId) { Logger.log("Create Context"); return LocalNotificationsContext.getInstance(); } @Override FREContext createContext(String extId); @Override void initialize(); @Override void dispose(); }### Answer:
@Test public void extension_createContext_returnsContext() { PowerMockito.mockStatic(LocalNotificationsContext.class); when(LocalNotificationsContext.getInstance()).thenReturn(context); assertSame(context, getSubject().createContext("anyId")); } |
### Question:
SoundSettings { public Uri getSoundUri() { String soundName = getSoundName(); if (soundName == null) return null; return NotificationSoundProvider.getSoundUri(soundName); } SoundSettings(Bundle bundle); Uri getSoundUri(); int getSoundDefault(); }### Answer:
@Test public void settings_getSoundUri_returnsNullIfBundleDoesNotPlaySoundAndDoesNotHaveSoundName() { assertNull(getSubject().getSoundUri()); }
@Test public void settings_getSoundUri_returnsUriIfBundlePlaysSoundAndHasSoundName() { when(bundle.getString(Constants.SOUND_NAME)).thenReturn("sound.mp3"); when(bundle.getBoolean(Constants.PLAY_SOUND)).thenReturn(true); NotificationSoundProvider.CONTENT_URI = "content: assertNotNull(getSubject().getSoundUri()); verifyStatic(Uri.class); Uri.parse("content: }
@Test public void settings_getSoundUri_returnsNullIfBundlePlaysSoundAndDoesNotHaveSoundName() { when(bundle.getBoolean(Constants.PLAY_SOUND)).thenReturn(true); assertNull(getSubject().getSoundUri()); when(bundle.getString(Constants.SOUND_NAME)).thenReturn(""); when(bundle.getBoolean(Constants.PLAY_SOUND)).thenReturn(true); assertNull(getSubject().getSoundUri()); }
@Test public void settings_getSoundUri_returnsNullIfBundleDoesNotPlaySoundAndHasSoundName() { when(bundle.getString(Constants.SOUND_NAME)).thenReturn("sound.mp3"); assertNull(getSubject().getSoundUri()); } |
### Question:
SoundSettings { public int getSoundDefault() { return shouldPlayDefaultSound()? Notification.DEFAULT_SOUND : 0; } SoundSettings(Bundle bundle); Uri getSoundUri(); int getSoundDefault(); }### Answer:
@Test public void settings_getSoundDefault_returnsZeroIfBundlePlaysSoundAndDoesNotHaveSoundName() { when(bundle.getBoolean(Constants.PLAY_SOUND)).thenReturn(true); assertEquals(Notification.DEFAULT_SOUND, getSubject().getSoundDefault()); }
@Test public void settings_getSoundDefault_returnsZeroIfBundlePlaysSoundAndHasSoundName() { when(bundle.getString(Constants.SOUND_NAME)).thenReturn("sound.mp3"); when(bundle.getBoolean(Constants.PLAY_SOUND)).thenReturn(true); assertEquals(0, getSubject().getSoundDefault()); }
@Test public void settings_getSoundDefault_returnsZeroIfBundleDoesNotPlaySoundAndHasSoundName() { when(bundle.getString(Constants.SOUND_NAME)).thenReturn("sound.mp3"); when(bundle.getBoolean(Constants.PLAY_SOUND)).thenReturn(false); assertEquals(0, getSubject().getSoundDefault()); }
@Test public void settings_getSoundDefault_returnsZeroIfBundleDoesNotPlaySoundAndDoesNotHaveSoundName() { assertEquals(0, getSubject().getSoundDefault()); } |
### Question:
Application extends android.app.Application { @Override public void onCreate() { super.onCreate(); registerActivityLifecycleCallbacks(new LifecycleCallbacks()); } @Override void onCreate(); }### Answer:
@Test public void application_addsCallbacks_onCreate() { getSubject().onCreate(); verify(getSubject()).registerActivityLifecycleCallbacks(callbacks); } |
### Question:
LocalNotification implements ISerializable, IDeserializable { @SuppressWarnings("WeakerAccess") public long getRepeatIntervalMilliseconds() { return new LocalNotificationTimeInterval(repeatInterval) .toMilliseconds(); } LocalNotification(); LocalNotification(String activityClassName); @SuppressWarnings("WeakerAccess") long getRepeatIntervalMilliseconds(); boolean repeatsRecurrently(); JSONObject serialize(); void deserialize(JSONObject jsonObject); public String code; public String tickerText; public String title; public String body; public boolean isExact; public boolean allowWhileIdle; public boolean playSound; public boolean vibrate; public int iconResourceId; public int numberAnnotation; public boolean cancelOnSelect; public boolean ongoing; public String alertPolicy; public String soundName; public boolean hasAction; public byte[] actionData; public Date fireDate; public int repeatInterval; public int priority; public boolean showInForeground; public String activityClassName; public String category; }### Answer:
@Test public void notification_getRepeatIntervalMilliseconds_returnsTimeInMilliseconds() { LocalNotificationTimeInterval intervalMock = mock(LocalNotificationTimeInterval.class); try { PowerMockito.whenNew(LocalNotificationTimeInterval.class) .withArguments(10) .thenReturn(intervalMock); } catch (Throwable e) { e.printStackTrace(); } when(intervalMock.toMilliseconds()).thenReturn(20000L); getSubject().repeatInterval = 10; assertEquals(getSubject().getRepeatIntervalMilliseconds(), 20000L); } |
### Question:
LocalNotificationsContext extends FREContext { void dispatchNotificationSelectedEvent() { LocalNotificationCache.getInstance().reset(); dispatchStatusEventAsync(NOTIFICATION_SELECTED, STATUS); } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIBED; }### Answer:
@Test public void context_dispatchNotificationSelectedEvent_dispatchesEvent() { getSubject().dispatchNotificationSelectedEvent(); verify(getSubject()).dispatchStatusEventAsync("notificationSelected", "status"); } |
### Question:
LocalNotificationsContext extends FREContext { private void cancel(String notificationCode) { getPersistenceManager().removeNotification(notificationCode); getManager().cancel(notificationCode); } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIBED; }### Answer:
@Test public void context_functions_cancel() { try { when(arg1.getAsString()).thenReturn("MyID"); } catch (Throwable e) { e.printStackTrace(); } callFunction("cancel"); verify(manager).cancel("MyID"); verify(persistenceManager).removeNotification("MyID"); } |
### Question:
LocalNotificationsContext extends FREContext { private void cancelAll() { getManager().cancelAll(); getPersistenceManager().clearNotifications(); } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIBED; }### Answer:
@Test public void context_functions_cancelAll() { callFunction("cancelAll"); verify(manager).cancelAll(); verify(persistenceManager).clearNotifications(); } |
### Question:
LocalNotificationsContext extends FREContext { private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIBED; }### Answer:
@Test public void context_functions_activate_legacy() { when(activity.getApplication()).thenReturn(legacyApplication); ApplicationStatus.setInForeground(false); callFunction("activate"); assertTrue(ApplicationStatus.getInForeground()); }
@Test public void context_functions_deactivate_legacy() { when(activity.getApplication()).thenReturn(legacyApplication); ApplicationStatus.setInForeground(true); callFunction("deactivate"); assertFalse(ApplicationStatus.getInForeground()); }
@Test public void context_functions_activate() { ApplicationStatus.setInForeground(false); callFunction("activate"); assertFalse(ApplicationStatus.getInForeground()); }
@Test public void context_functions_deactivate() { ApplicationStatus.setInForeground(true); callFunction("deactivate"); assertTrue(ApplicationStatus.getInForeground()); } |
### Question:
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } LocalNotificationEventDispatcher(String code, byte[] data); LocalNotificationEventDispatcher(String code, byte[] data, String actionId, String userResponse); }### Answer:
@Test public void dispatcher_dispatchInForeground_setsCacheIfAppIsNotActive() { getSubject().dispatchWhenInForeground(); assertCache(); }
@Test public void dispatcher_dispatchInForeground_doesNotDispatchesIfAppIsNotActive() { getSubject().dispatchWhenInForeground(); verify(context, never()).dispatchNotificationSelectedEvent(); }
@Test public void dispatcher_dispatchInForeground_setsCacheIfAppIsInBackground() { ApplicationStatus.setInForeground(true); ApplicationStatus.setInForeground(false); getSubject().dispatchWhenInForeground(); assertCache(); }
@Test public void dispatcher_dispatchInForeground_doesNotDispatchesIfAppIsInBackground() { ApplicationStatus.reset(); getSubject().dispatchWhenInForeground(); verify(context, never()).dispatchNotificationSelectedEvent(); }
@Test public void dispatcher_dispatchInForeground_setsCacheIfAppIsInForeground() { ApplicationStatus.setInForeground(true); getSubject().dispatchWhenInForeground(); assertCache(); }
@Test public void dispatcher_dispatchInForeground_dispatchesIfAppIsInForeground() { ApplicationStatus.setInForeground(true); getSubject().dispatchWhenInForeground(); verify(context).dispatchNotificationSelectedEvent(); } |
### Question:
AlarmRestoreOnBoot extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction() == null || !intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { return; } PersistenceManager persistenceManager = new PersistenceManager(context); final Set<String> notificationIds = persistenceManager.readNotificationKeys(); final LocalNotificationManager manager = new LocalNotificationManager(context); Date now = new Date(); for (String notificationId : notificationIds) { try { LocalNotification notification = persistenceManager.readNotification(notificationId); if (notification == null) continue; long nextTime = new NextNotificationCalculator(notification).getTime(now); if (nextTime >= now.getTime()) { manager.notify(notification); } else { persistenceManager.removeNotification(notification.code); } } catch (Exception e) { Logger.log("AlarmRestoreOnBoot: Error while restoring alarm details after reboot: " + e.toString()); } Logger.log("AlarmRestoreOnBoot: Successfully restored alarms upon reboot"); } } @Override void onReceive(Context context, Intent intent); }### Answer:
@Test public void provider_onReceive_doesNothing_ifNotRightPermission() { when(intent.getAction()).thenReturn("any.other.permission"); getSubject().onReceive(context, intent); verify(persistenceManager, never()).readNotificationKeys(); }
@Test public void provider_onReceive_notifiesEventsInTheFuture() { initNotifications(); getSubject().onReceive(context, intent); verify(notificationManager).notify(notification1); }
@Test public void provider_onReceive_removesEventsInThePast() { initNotifications(); getSubject().onReceive(context, intent); verify(persistenceManager).removeNotification("NOTIF2"); } |
### Question:
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityStarted(Activity activity) { ApplicationStatus.setInForeground(true); } @Override void onActivityCreated(Activity activity, Bundle bundle); @Override void onActivityStarted(Activity activity); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onActivityStopped(Activity activity); @Override void onActivitySaveInstanceState(Activity activity, Bundle bundle); @Override void onActivityDestroyed(Activity activity); }### Answer:
@Test public void callbacks_setAppInForeground_whenActivityStarted() { ApplicationStatus.setInForeground(false); getSubject().onActivityStarted(null); assertTrue(ApplicationStatus.getInForeground()); } |
### Question:
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityStopped(Activity activity) { ApplicationStatus.setInForeground(false); } @Override void onActivityCreated(Activity activity, Bundle bundle); @Override void onActivityStarted(Activity activity); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onActivityStopped(Activity activity); @Override void onActivitySaveInstanceState(Activity activity, Bundle bundle); @Override void onActivityDestroyed(Activity activity); }### Answer:
@Test public void callbacks_setAppInForeground_whenActivityStopped() { ApplicationStatus.setInForeground(true); getSubject().onActivityStopped(null); assertFalse(ApplicationStatus.getInForeground()); } |
### Question:
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityCreated(Activity activity, Bundle bundle) { if (getBackgroundMode(activity)) { activity.moveTaskToBack(true); } } @Override void onActivityCreated(Activity activity, Bundle bundle); @Override void onActivityStarted(Activity activity); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onActivityStopped(Activity activity); @Override void onActivitySaveInstanceState(Activity activity, Bundle bundle); @Override void onActivityDestroyed(Activity activity); }### Answer:
@Test public void callbacks_doesNothing_whenNullIntent() { when(activity.getIntent()).thenReturn(null); getSubject().onActivityCreated(activity, null); verify(activity, never()).moveTaskToBack(true); }
@Test public void callbacks_doesNothing_whenNotInBackgroundMode() { when(activity.getIntent()).thenReturn(intent); when(intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false)).thenReturn(false); getSubject().onActivityCreated(activity, null); verify(activity, never()).moveTaskToBack(true); }
@Test public void callbacks_hideActivity_whenInBackgroundMode() { when(activity.getIntent()).thenReturn(intent); when(intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false)).thenReturn(true); getSubject().onActivityCreated(activity, null); verify(activity).moveTaskToBack(true); } |
### Question:
LocalNotificationManager { void cancel(String notificationCode) { final Intent intent = new Intent(context, AlarmIntentService.class); intent.setAction(notificationCode); final PendingIntent pi = PendingIntent.getBroadcast(context, notificationCode.hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT); final AlarmManager am = getAlarmManager(); try { am.cancel(pi); } catch (Exception e) { Logger.log("LocalNotificationManager::cancel Exception: " + e.getMessage()); } finally { notificationManager.cancel(notificationCode, Constants.STANDARD_NOTIFICATION_ID); } } LocalNotificationManager(Context context); }### Answer:
@Test public void manager_cancel_cancelsAllStoredAlarms() { when(PendingIntent.getBroadcast(context, "notif1".hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT)) .thenReturn(pendingIntent); getSubject().cancel("notif1"); verify(intent).setAction("notif1"); verify(alarmManager).cancel(pendingIntent); } |
### Question:
NotificationDispatcher { void dispatch() { dispatchNotification(); } NotificationDispatcher(Context context, Bundle bundle); }### Answer:
@Test public void dispatcher_dispatch_whenAppIsInForeground_andNormalNotification_doesNotDisplayNotification() { getSubject().dispatch(); verify(notificationManager).notify("testCode", Constants.STANDARD_NOTIFICATION_ID, notification); } |
### Question:
NotificationSoundProvider extends ContentProvider { @Override public void attachInfo(Context context, ProviderInfo info) { super.attachInfo(context, info); AUTHORITY = info.authority; CONTENT_URI = "content: } NotificationSoundProvider(); static Uri getSoundUri(String soundName); @Override int delete(Uri uri, String selection, String[] selectionArgs); @Override String getType(Uri uri); @Override Uri insert(Uri uri, ContentValues values); @Override boolean onCreate(); @Override Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder); @Override int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs); @Override void attachInfo(Context context, ProviderInfo info); @Override AssetFileDescriptor openAssetFile(Uri uri, String mode); static String AUTHORITY; static String CONTENT_URI; }### Answer:
@Test public void provider_attachInfo_updatesAuthority() { assertEquals("expected.authority", NotificationSoundProvider.AUTHORITY); getSubject().attachInfo(null, info); assertEquals("new.authority", NotificationSoundProvider.AUTHORITY); }
@Test public void provider_attachInfo_updatesUri() { assertEquals("content: getSubject().attachInfo(null, info); assertEquals("content: } |
### Question:
NotificationSoundProvider extends ContentProvider { @Override public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException { String lastPathSegment = uri.getLastPathSegment(); if (!lastPathSegment.endsWith(".wav") && !lastPathSegment.endsWith(".mp3")) { return null; } return new AssetDecompressor(getContext()).decompress(uri.getLastPathSegment()); } NotificationSoundProvider(); static Uri getSoundUri(String soundName); @Override int delete(Uri uri, String selection, String[] selectionArgs); @Override String getType(Uri uri); @Override Uri insert(Uri uri, ContentValues values); @Override boolean onCreate(); @Override Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder); @Override int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs); @Override void attachInfo(Context context, ProviderInfo info); @Override AssetFileDescriptor openAssetFile(Uri uri, String mode); static String AUTHORITY; static String CONTENT_URI; }### Answer:
@Test public void provider_openAssetFile_returnsNullIfNotMp3OrWav() { when(uri.getLastPathSegment()).thenReturn("sound.mp3"); try { assertSame(fileDescriptor, getSubject().openAssetFile(uri, "")); } catch (FileNotFoundException e) { e.printStackTrace(); } when(uri.getLastPathSegment()).thenReturn("sound.wav"); try { assertSame(fileDescriptor, getSubject().openAssetFile(uri, "")); } catch (FileNotFoundException e) { e.printStackTrace(); } when(uri.getLastPathSegment()).thenReturn("sound.any"); try { assertNull(getSubject().openAssetFile(uri, "")); } catch (FileNotFoundException e) { e.printStackTrace(); } }
@Test public void provider_openAssetFile_decompressesUriLastSegment() { when(uri.getLastPathSegment()).thenReturn("sound.mp3"); try { getSubject().openAssetFile(uri, ""); verify(decompressor).decompress("sound.mp3"); } catch (FileNotFoundException e) { e.printStackTrace(); } } |
### Question:
WinOrLose { public static int winOrLose(long first, long second) { final long compare = first - second; if (compare > 0) return 1; else if (compare < 0) return 0; return random.nextBoolean() ? 1 : 0; } static void main(String[] args); static int winOrLose(long first, long second); }### Answer:
@Test public void testWinOrLose() { Map<Integer, Long[]> mapIO = new HashMap<Integer, Long[]>() {{ put(0, new Long[]{new Long("2"), new Long("3")}); put(1, new Long[]{new Long("5"), new Long("3")}); }}; for (Map.Entry<Integer, Long[]> io : mapIO.entrySet()) { Assert.assertEquals( io.getKey().intValue(), WinOrLose.winOrLose(io.getValue()[0], io.getValue()[1]) ); } } |
### Question:
HelloBean { @Deprecated public String sayHello() { return "Hello world!"; } HelloBean(); @Override String toString(); @Deprecated String sayHello(); @SuppressWarnings("all") long getValue(); }### Answer:
@Test public void testHello() { String ret = helloBean.sayHello(); Assertions.assertNotNull(ret); System.out.println(ret); } |
### Question:
HelloBean { @Override public String toString() { return "HelloBean says hello world!"; } HelloBean(); @Override String toString(); @Deprecated String sayHello(); @SuppressWarnings("all") long getValue(); }### Answer:
@Test public void testValue() { String ret = helloBean.osName; Assertions.assertNotNull(ret); System.out.println(String.format("osName:%s, resource: %s", helloBean.osName, helloBean.url.toString() )); } |
### Question:
HelloController { @ResponseStatus(HttpStatus.ACCEPTED) @AccessLimited(count = 1) @RequestMapping(path="hello/{name}", method = {RequestMethod.GET, RequestMethod.POST}) public Object hello(@RequestAttribute String ip, @PathVariable String name, @RequestParam String gender) { return new HashMap<String, Object>() {{ put("ip", ip); put("name", name); put("gender", gender); put("msg", helloBean.sayHello()); }}; } @ResponseStatus(HttpStatus.ACCEPTED) @AccessLimited(count = 1) @RequestMapping(path="hello/{name}", method = {RequestMethod.GET, RequestMethod.POST}) Object hello(@RequestAttribute String ip, @PathVariable String name, @RequestParam String gender); }### Answer:
@Test public void testHello() { Object ret = helloController.hello("test", null, null); Assertions.assertTrue(ret.toString().contains("test")); System.out.println(ret); } |
### Question:
ServerConfig { public String getServerUrl() { String strPort = port > 0 && port != 80 ? String.format(":%d", port) : ""; return String.format("http: } void setDomain(String domain); void setPort(long port); String getServerUrl(); boolean isSkipInit(); void setSkipInit(boolean skipInit); boolean isTesting(); void setTesting(boolean testing); }### Answer:
@Test public void testServerUrl() { String ret = serverConfig.getServerUrl(); Assertions.assertTrue(ret.contains("http: System.out.println(ret); } |
### Question:
MqService { public void sendQueue(Object msgObj) { System.out.printf("Send queue msg: %s\n", msgObj); try { jmsMessagingTemplate.convertAndSend(queue, msgObj); } catch (MessagingException e) { System.out.println(e.getMessage()); throw e; } } void sendQueue(Object msgObj); void sendTopic(Object msgObj); }### Answer:
@Test public void testSendQueue() { for (Object obj : msgArr) { mqService.sendQueue(obj); } } |
### Question:
MqService { public void sendTopic(Object msgObj) { System.out.printf("Send topic msg: %s\n", msgObj); try { jmsMessagingTemplate.convertAndSend(topic, msgObj); } catch (MessagingException e) { System.out.println(e.getMessage()); throw e; } } void sendQueue(Object msgObj); void sendTopic(Object msgObj); }### Answer:
@Test public void testSendTopic() { for (Object obj : msgArr) { mqService.sendTopic(obj); } } |
### Question:
App { public static void main(String[] args) { final JFrame frame = new Frame(); frame.setTitle("Hello App"); frame.setSize(300, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(false); frame.setVisible(true); } static void main(String[] args); }### Answer:
@Test public void testApp() { App.main(null); } |
### Question:
Inst3 { public static Inst3 getInst() { synchronized (Inst3.class) { if (inst == null) { inst = new Inst3(); } } return inst; } private Inst3(); static Inst3 getInst(); }### Answer:
@Test public void testGetInst() { Inst3 inst = Inst3.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); } |
### Question:
Inst2 { public static Inst2 getInst() { if (inst == null) { inst = new Inst2(); } return inst; } private Inst2(); static Inst2 getInst(); }### Answer:
@Test public void testGetInst() { Inst2 inst = Inst2.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); } |
### Question:
Inst4 { public static Inst4 getInst() { if (inst == null) { synchronized (Inst4.class) { if (inst == null) { inst = new Inst4(); } } } return inst; } private Inst4(); static Inst4 getInst(); }### Answer:
@Test public void testGetInst() { Inst4 inst = Inst4.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); } |
### Question:
MinDifference { public static int getMinDifference(int[] arA, int n, int[] arB, int m) { if (n <= 0 || n > m || n != arA.length || m != arB.length) { return 0; } int minDiff = Integer.MAX_VALUE; for (int j = n - 1; j < m; j++) { int diff = 0; for (int i = 0; i < n; i++) { int tmp = arA[i] - arB[j - n + 1 + i]; diff += tmp * tmp; } if (minDiff > diff) { minDiff = diff; } if (minDiff == 0) { break; } } if (minDiff == Integer.MAX_VALUE) { minDiff = 0; } return minDiff; } static void main(String[] args); static int getMinDifference(int[] arA, int n, int[] arB, int m); }### Answer:
@Test public void testGetMinDifference() { int n = 2, m = 4; int[] arA = {1, 2}, arB = {3, 1, 2, 4}; Assert.assertEquals(0, MinDifference.getMinDifference(arA, n, arB, m)); }
@Test public void testGetMinDifference2() { int n = 2, m = 4; int[] arA = {1, 2}, arB = {1, 4, 2, 3}; Assert.assertEquals(2, MinDifference.getMinDifference(arA, n, arB, m)); } |
### Question:
Inst5 { public static Inst5 getInst() { return Holder.inst; } private Inst5(); static Inst5 getInst(); }### Answer:
@Test public void testGetInst() { Inst5 inst = Inst5.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); } |
### Question:
Inst1 { public static Inst1 getInst() { return inst; } private Inst1(); static Inst1 getInst(); }### Answer:
@Test public void testGetInst() { Inst1 inst = Inst1.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); } |
### Question:
FtpUtil { public static boolean upload(String pathname, String fileName, InputStream inputStream) { System.out.printf("Start upload: %s\n", fileName); FTPClient ftpClient = getInst(); ftpClient.enterLocalPassiveMode(); try { ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.makeDirectory(pathname); ftpClient.changeWorkingDirectory(pathname); ftpClient.storeFile(fileName, inputStream); } catch (IOException e) { System.err.printf("Fail to upload: %s, %s\n", fileName, e.getMessage()); return false; } System.out.printf("Success upload: %s\n", fileName); return true; } static void close(); static boolean upload(String pathname, String fileName, InputStream inputStream); }### Answer:
@Test public void testUpload() throws IOException { String filePath = "readme.md"; InputStream fileStream = new FileInputStream(new File(filePath)); boolean ret = FtpUtil.upload("unit-testing", String.format("%d_%s", new Date().getHours(), filePath), fileStream); fileStream.close(); FtpUtil.close(); Assert.assertTrue(ret); } |
### Question:
HttpService { public <T> T sendHttpGet(String url, ResponseHandler<T> handler) { return sendRequest(new HttpGet(url), handler); } T sendRequest(HttpRequestBase httpRequest, ResponseHandler<T> handler); T sendHttpGet(String url, ResponseHandler<T> handler); T sendHttpForm(String httpUrl, Map<String, String> headers, Map<String, Object> params, ResponseHandler<T> handler); }### Answer:
@Test public void testSendHttpGet() { String html = httpService.sendHttpGet("https: String ret = html.substring(100, 130); System.out.println(ret); Assertions.assertNotNull(ret); } |
### Question:
HttpService { public <T> T sendHttpForm(String httpUrl, Map<String, String> headers, Map<String, Object> params, ResponseHandler<T> handler) { HttpPost httpPost = new HttpPost(httpUrl); fillHeaders(httpPost, headers); if (params != null) { List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size()); for (Map.Entry<String, Object> param : params.entrySet()) { Object value = param.getValue(); if (value != null) { pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(value))); } } try { httpPost.setEntity(new UrlEncodedFormEntity(pairs)); } catch (UnsupportedEncodingException e) { System.out.printf("Error when setEntity in sendHttpForm: %s\n", e.getMessage()); } } return sendRequest(httpPost, handler); } T sendRequest(HttpRequestBase httpRequest, ResponseHandler<T> handler); T sendHttpGet(String url, ResponseHandler<T> handler); T sendHttpForm(String httpUrl, Map<String, String> headers, Map<String, Object> params, ResponseHandler<T> handler); }### Answer:
@Test public void testBaiduToken() throws UnsupportedEncodingException { String url = "https: Map<String, String> headers = new HashMap<String, String>() {{ put("Content-Type", "application/x-www-form-urlencoded"); }}; Map<String, Object> params = new HashMap<String, Object>() {{ put("grant_type", "client_credentials"); put("client_id", "kVcnfD9iW2XVZSMaLMrtLYIz"); put("client_secret", "O9o1O213UgG5LFn0bDGNtoRN3VWl2du6"); }}; JSONObject ret = httpService.sendHttpForm(url, headers, params, new RespJsonObj()); System.out.println(ret); Assertions.assertNotNull(ret); String token = ret.getString("access_token"); testBaiduTts(token); } |
### Question:
AiController { @ApiOperation("语音合成") @GetMapping("/tts") public Object tts(HttpServletResponse response, @RequestParam("text") String text) { String url = "https: Map<String, String> headers = new HashMap<String, String>() {{ put("Content-Type", "application/x-www-form-urlencoded"); }}; Map<String, Object> params = new HashMap<String, Object>() {{ put("tex", URLEncoder.encode(text)); put("tok", token()); put("cuid", "starter_api_http_service"); put("ctp", "1"); put("lan", "zh"); put("spd", "6"); put("pit", "5"); put("vol", "5"); put("per", "0"); put("aue", "6"); }}; RespData respData = new RespData(); httpService.sendHttpForm(url, headers, params, respData); try { OutputStream outputStream = response.getOutputStream(); outputStream.write(respData.getBytes()); } catch (IOException e) { System.out.printf("写入语音合成数据错误: %s\n", e.getMessage()); } response.setContentLength(respData.getContentLength()); response.setContentType(respData.getContentType()); return "ok"; } @ApiOperation("语音合成") @GetMapping("/tts") Object tts(HttpServletResponse response, @RequestParam("text") String text); }### Answer:
@Test public void testTts() throws IOException { MockHttpServletResponse response = new MockHttpServletResponse(); Object ret = aiController.tts(response, "测试AiController"); System.out.println(ret); Assertions.assertEquals("ok", ret); } |
### Question:
FileController { @ApiOperation("上传文件") @PostMapping("/upload") public Object upload(@RequestPart MultipartFile file) { File tmpFile = new File(file.getOriginalFilename()); String fileName = tmpFile.getName(); Path path = Paths.get(fileName); try { Files.write(path, file.getBytes()); } catch (IOException e) { System.out.printf("保存文件失败: %s, %s\n", path.toString(), e.getMessage()); } return new HashMap<String, Object>() {{ put("code", "ok"); put("msg", path.toString()); }}; } @ApiOperation("上传文件") @PostMapping("/upload") Object upload(@RequestPart MultipartFile file); @ApiOperation("下载文件") @GetMapping("/{name}") void download(HttpServletResponse response, @PathVariable("name") String name); }### Answer:
@Test public void testUpload() throws IOException { File file = File.createTempFile("tmp", ".txt"); MockMultipartFile multipartFile = new MockMultipartFile( file.getName(), file.getName(), null, new FileInputStream(file) ); Object ret = fileController.upload(multipartFile); System.out.println(ret); String name = (String) ((Map<String, Object>) ret).get("msg"); Assertions.assertNotNull(name); testDownload(name); } |
### Question:
DateUtil { public static String getYYMMDD() { Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd"); return sdf.format(d); } static String getYYMMDD(); static String getYYMMDDHHmmSS(); static String getHHmmSS(); static String getStringDate(String rule, Date date); static Date getStartOfToday(); static Date getEndOfToday(); }### Answer:
@Test public void testGetYYMMDD() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Map<String, String> io = new HashMap<String, String>() {{ put("yy-MM-dd", "getYYMMDD"); put("yy-MM-dd:HH:mm:ss", "getYYMMDDHHmmSS"); put("HH:mm:ss", "getHHmmSS"); }}; for (Map.Entry<String, String> entry : io.entrySet()) { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat(entry.getKey()); String expected = sdf.format(date); Assert.assertEquals(expected, DateUtil.class.getMethod(entry.getValue()).invoke(DateUtil.class)); } } |
### Question:
DateUtil { public static String getStringDate(String rule, Date date) { SimpleDateFormat sdf = new SimpleDateFormat(rule); return sdf.format(date); } static String getYYMMDD(); static String getYYMMDDHHmmSS(); static String getHHmmSS(); static String getStringDate(String rule, Date date); static Date getStartOfToday(); static Date getEndOfToday(); }### Answer:
@Test public void testGetStringDate() { Date date = mock(Date.class); String[] io = {"yyyy-MM-dd:HH:mm:ss", "yyyy-MM-dd", "HH:mm:ss"}; for (String i : io) { String format = i; SimpleDateFormat sdf = new SimpleDateFormat(format); String expected = sdf.format(date); Assert.assertEquals(expected, DateUtil.getStringDate(format, date)); } } |
### Question:
App { public static void main(String[] args) { Clerk clerk = new Clerk(); executorService.execute(new Producer(clerk)); executorService.execute(new Consumer(clerk)); } static void main(String[] args); }### Answer:
@Test public void testApp() { new App().main(null); } |
### Question:
App { public static void main(String[] args) { final JFrame frame = new JFrame("Audio"); frame.setSize(300, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(false); JPanel panel = new JPanel(); Box verticalBox = Box.createVerticalBox(); panel.add(verticalBox); final long msDuration = 5000; final String title = "Record"; final JButton recordBtn = new JButton(title); recordBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { recordBtn.setText(String.format("%s(%d)", title, msDuration / 1000)); final RecordHelper recordHelper = RecordHelper.getInst(); recordHelper.record(new TimeListener() { @Override public void timeUpdated(long seconds) { recordBtn.setText(String.format("%s(%d)", title, msDuration / 1000 - seconds)); } @Override public void stopped(long seconds) { recordBtn.setText(title); recordHelper.play(); } }, msDuration); } }); verticalBox.add(recordBtn); frame.setContentPane(panel); frame.setVisible(true); } static void main(String[] args); }### Answer:
@Test public void testApp() { App.main(null); } |
### Question:
Player implements Runnable { public static void asyncPlay(byte[] audioBytes) { if (audioBytes == null || audioBytes.length <= 0) { return; } ByteArrayInputStream audioStream = new ByteArrayInputStream(audioBytes); Player player = new Player(); try { player.audioStream = AudioSystem.getAudioInputStream(audioStream); } catch (UnsupportedAudioFileException e) { System.err.println(e.getMessage()); } catch (IOException e) { System.err.println(e.getMessage()); } executorService.execute(player); } private Player(); static void asyncPlay(byte[] audioBytes); static void asyncPlay(URL fileUrl); static void asyncPlay(ByteArrayOutputStream byteOutputStream); @Override void run(); static void play(AudioInputStream audioStream, AudioFormat audioFormat); }### Answer:
@Test public void testPlayUrl() throws Exception { URL fileUrl = new URL("http: Player.asyncPlay(fileUrl); Thread.sleep(3000); } |
### Question:
RecordHelper { public void record(TimeListener timeListener, Long msDuration) { byteOutputStream = new ByteArrayOutputStream(); Recorder.record(byteOutputStream, timeListener, msDuration); } private RecordHelper(); static RecordHelper getInst(); void record(TimeListener timeListener, Long msDuration); void stop(); void stop(long millis); void play(); T save(T fileOrStream); }### Answer:
@Test public void testRecord() throws Exception { RecordHelper recordHelper = RecordHelper.getInst(); recordHelper.record(null, null); recordHelper.stop(5000); ByteArrayOutputStream ret = recordHelper.save(new ByteArrayOutputStream()); System.out.printf("data: %d\n", ret == null ? 0 : ret.size()); recordHelper.play(); Thread.sleep(3000); File file = recordHelper.save(new File("rec.wav")); System.out.println(file.getName()); } |
### Question:
DayOfProgrammer { public static String solve(int year) { int month = 0; int day = DAY_OF_PROGRAMMER; for (; month < 12; month++) { int days = DAYS_OF_MONTH[month]; if (day > days) { day -= days; } else { break; } } if (year == 1918) { day += 13; if (day > DAYS_OF_MONTH[month]) { day -= DAYS_OF_MONTH[month]; month++; } } if ((year > 1918 && (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))) || (year < 1918 && year % 4 == 0)) { day -= 1; if (day <= 0) { month--; day += DAYS_OF_MONTH[month]; } } return String.format("%02d.%02d.%04d", day, month + 1, year); } static String solve(int year); static int[] DAYS_OF_MONTH; static int DAY_OF_PROGRAMMER; }### Answer:
@Test public void testResolve() { Map<Integer, String> ioMap = new HashMap<Integer, String>() {{ put(2016, "12.09.2016"); }}; for (Map.Entry<Integer, String> io : ioMap.entrySet()) { String r = DayOfProgrammer.solve(io.getKey()); if (!io.getValue().equals(r)) { System.out.println(r); } Assert.assertEquals(io.getValue(), r); } } |
### Question:
StringDecoder { static int[] frequency(String s) { int[] chars = new int[26]; if (s == null || s.length() <= 0) { return chars; } int i = 0; final int count = s.length(); final char SYMBOL = '#'; while (i < count) { char c = s.charAt(i); if (c >= '3' && c <= '9') { addFrequency(chars, c - '1'); i++; } else if (c >= '1' && c <= '2') { boolean isDouble = false; if (i + 2 < count && s.charAt(i + 2) == SYMBOL) { String subStr = s.substring(i, i + 2); addFrequency(chars, Integer.valueOf(subStr) - 1); i += 3; } else { addFrequency(chars, c - '1'); i++; } } else { System.out.printf("Error in str, %c", c); i++; } } return chars; } static void main(String[] args); }### Answer:
@Test public void testFrequency() { String input = "1226#24#"; int[] output = StringDecoder.frequency(input); Assert.assertEquals(1, output[0]); Assert.assertEquals(1, output[1]); } |
### Question:
Triangle { public static int triangle(int a, int b, int c) { if (a <= 0 || b <= 0 || c <= 0) { return 0; } if (a == b && b == c) { return 1; } else if (a + b > c && b + c > a && a + c > b) { return 2; } return 0; } static int triangle(int a, int b, int c); static String[] triangleOrNot(int[] a, int[] b, int[] c); }### Answer:
@Test public void testTriangle() { Map<int[], Integer> mapIO = new HashMap<int[], Integer>() {{ put(new int[]{3, 3, 3}, 1); put(new int[]{3, 5, 4}, 2); }}; for (Map.Entry<int[], Integer> io : mapIO.entrySet()) { int[] i = io.getKey(); int ret = Triangle.triangle(i[0], i[1], i[2]); Assert.assertEquals(io.getValue().intValue(), ret); } } |
### Question:
Triangle { public static String[] triangleOrNot(int[] a, int[] b, int[] c) { if (a == null || b == null || c == null || a.length != b.length || a.length != c.length) { return null; } final int count = a.length; String[] results = new String[count]; for (int i = 0; i < count; i++) { if (triangle(a[i], b[i], c[i]) > 0) { results[i] = "Yes"; } else { results[i] = "No"; } } return results; } static int triangle(int a, int b, int c); static String[] triangleOrNot(int[] a, int[] b, int[] c); }### Answer:
@Test public void testTriangleOrNot() { int[] a = {7, 10, 7}; int[] b = {2, 3, 4}; int[] c = {2, 7, 4}; String[] results = Triangle.triangleOrNot(a, b, c); System.out.println(Arrays.asList(results)); } |
### Question:
CustomerServiceCapacity { public static int howManyAgentsToAdd(int noOfCurrentAgents, int[][] callsTimes) { if (callsTimes == null || callsTimes.length <= 0) { return 0; } Call[] calls = new Call[callsTimes.length]; for (int i = 0; i < calls.length; i++) { calls[i] = new Call(callsTimes[i][0], callsTimes[i][1]); } Arrays.sort(calls); for (int i = 0; i < calls.length - 1; i++) { for (int j = i + 1; j < calls.length; j++) { if (calls[i].isOverlap(calls[j])) { calls[i].addCount(); } else { break; } } } int max = calls[0].count; for (int i = 1; i < calls.length; i++) { if (max < calls[i].count) { max = calls[i].count; } } if (max <= noOfCurrentAgents) { return 0; } return max - noOfCurrentAgents; } static int howManyAgentsToAdd(int noOfCurrentAgents, int[][] callsTimes); }### Answer:
@Test public void testHowManyAgentsToAdd() { Map<int[][], int[]> mapIO = new HashMap<int[][], int[]>(){{ put(new int[][] {{1481122000, 1481122020}, {1481122000, 1481122040}, {1481122030, 1481122035}}, new int[]{1, 1}); }}; for (Map.Entry<int[][], int[]> io : mapIO.entrySet()) { int ret = CustomerServiceCapacity.howManyAgentsToAdd(io.getValue()[0], io.getKey()); Assert.assertEquals(io.getValue()[1], ret); } } |
### Question:
ElectionWinner { public static String electionWinner(String[] votes) { if (votes == null || votes.length <= 0) { return null; } Map<String, Integer> voteCountMap = new HashMap<String, Integer>(); int maxCount = 0; for (String vote : votes) { String tmp = vote.trim(); int count = 1 + (voteCountMap.containsKey(tmp) ? voteCountMap.get(tmp) : 0); voteCountMap.put(tmp, count); if (maxCount < count) { maxCount = count; } } List<String> candidateList = new ArrayList<String>(); for (Map.Entry<String, Integer> voteCount : voteCountMap.entrySet()) { if (voteCount.getValue() == maxCount) { candidateList.add(voteCount.getKey()); } } if (candidateList.size() <= 0) { return null; } else if (candidateList.size() == 1) { return candidateList.get(0); } String[] candidatesArr = new String[candidateList.size()]; candidateList.toArray(candidatesArr); Arrays.sort(candidatesArr); return candidatesArr[candidatesArr.length - 1]; } static String electionWinner(String[] votes); }### Answer:
@Test public void testElectionWinner() { String ret = ElectionWinner.electionWinner(new String[] {"Alex", "Michael", "harry", "Dave", "Michael", "Victor", "Harry", "Alex", "Mary", "Mary"}); Assert.assertEquals("Michael", ret); } |
### Question:
DeltaEncode { public static int[] delta_encode(final int[] array) { if (array == null || array.length <= 1) { return array; } List<Integer> encode = new ArrayList<Integer>(){{ add(array[0]); }}; for (int i = 1; i < array.length; i++) { int diff = array[i] - array[i - 1]; if (diff < -127 || diff > 127) { encode.add(-128); } encode.add(diff); } int[] encodeArr = new int[encode.size()]; for (int i = 0; i < encode.size(); i++) { encodeArr[i] = encode.get(i); } return encodeArr; } static int[] delta_encode(final int[] array); }### Answer:
@Test public void testDeltaEncode() { Map<int[], int[]> mapIO = new HashMap<int[], int[]>(){{ put(new int[]{25626, 25757, 24367, 24267, 16, 100, 2, 7277}, new int[]{25626, -128, 131, -128, -1390, -100, -128, -24251, 84, -98, -128, 7275}); }}; for (Map.Entry<int[], int[]> io : mapIO.entrySet()) { int[] ret = DeltaEncode.delta_encode(io.getKey()); Assert.assertArrayEquals(io.getValue(), ret); } } |
### Question:
ZombieCluster { static int zombieCluster(String[] zombieArr) { if (zombieArr == null || zombieArr.length <= 0) { return 0; } int len = zombieArr.length; boolean[][] zombieMatric = new boolean[len][len]; for (int i = 0; i < len; i++) { int j = 0; for (char c : zombieArr[i].toCharArray()) { zombieMatric[i][j++] = (c == '1'); } } markCluster(zombieMatric, len, 0); int count = 0; for (int i = 0; i < len; i++) { if (zombieMatric[i][i]) { count++; } } return count; } }### Answer:
@Test public void testZombieCluster() { Map<String[], Integer> mapIO = new HashMap<String[], Integer>() {{ put(new String[]{"10000", "01000", "00100", "00010", "00001"}, 5); put(new String[]{"1100", "1110", "0110", "0001"}, 2); }}; for (Map.Entry<String[], Integer> io : mapIO.entrySet()) { int ret = ZombieCluster.zombieCluster(io.getKey()); Assert.assertEquals(io.getValue().intValue(), ret); } } |
### Question:
GetDay { public static String getDay(String day, String month, String year) { if (day == null || day.length() <= 0 || month == null || month.length() <= 0 || year == null || year.length() <= 0) { return ""; } String dateStr = String.format("%s-%s-%s", year, month, day); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = df.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } if (date == null) { return ""; } Calendar cal = Calendar.getInstance(); cal.setTime(date); int dayInt = cal.get(Calendar.DAY_OF_WEEK); return (new String[]{ "SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY" })[dayInt - 1]; } static String getDay(String day, String month, String year); }### Answer:
@Test public void testGetDay() { Map<String[], String> mapIO = new HashMap<String[], String>() {{ put(new String[]{"05", "08", "2015"}, "WEDNESDAY"); put(new String[]{"04", "06", "2018"}, "MONDAY"); put(new String[]{"06", "06", "2018"}, "WEDNESDAY"); }}; for (Map.Entry<String[], String> io : mapIO.entrySet()) { String[] params = io.getKey(); String ret = GetDay.getDay(params[0], params[1], params[2]); Assert.assertEquals(io.getValue(), ret); } } |
### Question:
WaitingTime { public static long waitingTime(int[] tickets, int p) { if (tickets == null || tickets.length <= 0 || p < 0 || p >= tickets.length) { return -1; } int count = 0; int ticket = tickets[p]; for (int i = 0; i < tickets.length; i++) { int tmp = tickets[i]; if (tmp < ticket) { count += tmp; } else { count += ticket; if (i > p) { count--; } } } return count; } static long waitingTime(int[] tickets, int p); }### Answer:
@Test public void testWaitingTime() { Map<int[], long[]> mapIO = new HashMap<int[], long[]>(){{ put(new int[]{2, 6, 3, 4, 5}, new long[]{2, 12}); put(new int[]{1, 1, 1, 1}, new long[]{0, 1}); put(new int[]{5, 5, 2, 3}, new long[]{3, 11}); }}; for(Map.Entry<int[], long[]> io : mapIO.entrySet()) { long ret = WaitingTime.waitingTime(io.getKey(), (int)io.getValue()[0]); Assert.assertEquals(io.getValue()[1], ret); } } |
### Question:
Hello { public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>() {{ put("a", 1); put("b", 2); }}; System.out.println(map.toString()); System.out.println(map.keySet().toString()); } static void main(String[] args); }### Answer:
@Test public void testMain() { Hello.main(null); } |
### Question:
IP { public static boolean isValid(String ip) { if (ip == null || ip.length() <= 0) { return false; } return ip.trim().matches(new MyRegex().pattern); } static boolean isValid(String ip); }### Answer:
@Test public void testIsValid() { Map<String, Boolean> mapIO = new HashMap<String, Boolean>() {{ put("000.12.12.034", true); put("121.234.12.12", true); put("23.45.12.56", true); put("000.12.234.23.23", false); put("666.666.23.23", false); put(".213.123.23.32", false); put("23.45.22.32.", false); put("I.Am.not.an.ip", false); put("00.12.123.123123.123", false); put("122.23", false); put("Hello.IP", false); put("259.259.259.259", false); put("266.266.266.266", false); put("255.255.255.255", true); put("555.555.555.555", false); put("666.666.666.666", false); put("249.249.249.249", true); put("249.2", false); }}; for (Map.Entry<String, Boolean> io : mapIO.entrySet()) { boolean ret = IP.isValid(io.getKey()); if (io.getValue() != ret) { System.out.println(io.getKey()); } Assert.assertEquals(io.getValue(), ret); } } |
### Question:
PermutationEquation { public static int[] permutationEquation(final int[] p) { if (p == null || p.length <= 0) { return null; } Map<Integer, Integer> equationMap = new HashMap<Integer, Integer>(){{ for (int i = 0; i < p.length; i++) { put(p[i], i + 1); } }}; int[] arr = new int[p.length]; for (int i = 0; i < arr.length; i++) { arr[i] = equationMap.get(equationMap.get(i + 1)); } return arr; } static int[] permutationEquation(final int[] p); }### Answer:
@Test public void testPermutationEquation() { Map<int[], int[]> mapIO = new HashMap<int[], int[]>(){{ put(new int[]{2, 3, 1}, new int[] {2, 3, 1}); }}; for (Map.Entry<int[], int[]> io : mapIO.entrySet()) { int[] ret = PermutationEquation.permutationEquation(io.getKey()); Assert.assertArrayEquals(io.getValue(), ret); } } |
### Question:
WinOrLose2 { public static int winOrLose(long first, long second) { if (first > second) return 1; else if (first < second) return 0; return random.nextBoolean() ? 1 : 0; } static void main(String[] args); static int calculateLoop(List<Long> ar); static int winOrLose(long first, long second); }### Answer:
@Test public void testWinOrLose() { Map<Integer, int[]> mapIO = new HashMap<Integer, int[]>() {{ put(0, new int[] {2, 3}); put(1, new int[] {5, 3}); }}; for (Map.Entry<Integer, int[]> io : mapIO.entrySet()) { Assert.assertEquals( io.getKey().intValue(), WinOrLose2.winOrLose(io.getValue()[0], io.getValue()[1]) ); } } |
### Question:
CutSticks { public static int[] cutSticks(int[] lengths) { if (lengths == null || lengths.length <= 0) { return null; } Arrays.sort(lengths); int index = 0, count = lengths.length; List<Integer> countList = new ArrayList<Integer>(); while (index < count) { countList.add(count - index); if (index == count - 1) { break; } int value = lengths[index]; for (int i = index + 1; i < count; i++) { if (lengths[i] != value || i == count - 1) { index = i; for (int j = i; j < count; j++) { lengths[j] -= value; } break; } } } int[] arr = new int[countList.size()]; for (int i = 0; i < countList.size(); i++) { arr[i] = countList.get(i); } return arr; } static int[] cutSticks(int[] lengths); }### Answer:
@Test public void testCutSticks() { Map<int[], int[]> mapIO = new HashMap<int[], int[]>() {{ put(new int[]{1, 1, 2, 3}, new int[]{4, 2, 1}); put(new int[]{5, 4, 4, 2, 2, 8}, new int[]{6, 4, 2, 1}); }}; for (Map.Entry<int[], int[]> io : mapIO.entrySet()) { int[] ret = CutSticks.cutSticks(io.getKey()); Assert.assertArrayEquals(io.getValue(), ret); } } |
### Question:
BinarySubString { public static int counting(String s) { if (s == null || s.trim().length() <= 1) { return 0; } char[] arr = s.trim().toCharArray(); int len = arr.length; int count = 0; for (int i = 0; i < len - 1; i++) { if (arr[i] != arr[i + 1]) { count++; int m = i - 1; int n = i + 1 + 1; while (m >= 0 && n < len && arr[i] == arr[m] && arr[i + 1] == arr[n]) { count++; m--; n++; } } } return count; } static int counting(String s); }### Answer:
@Test public void testCounting() { Map<String, Integer> mapIO = new HashMap<String, Integer>(){{ put("10001", 2); put("10101", 4); put("00110", 3); }}; for (Map.Entry<String, Integer> io : mapIO.entrySet()) { int ret = BinarySubString.counting(io.getKey()); Assert.assertEquals(io.getValue().intValue(), ret); } } |
### Question:
Portfolio { public static long findMax(int n, String tree) { if (n <= 0 || tree == null || tree.trim().length() <= 0) { return 0; } String[] nodes = tree.trim().split(" "); if (nodes.length < n) { return 0; } List<Long> sumList = new ArrayList<Long>(); int countExpected = 1; int count = 0; int index = 0; long sum = 0; for (int i = 0; i < nodes.length; i++) { String node = nodes[i]; if (!node.equals("#")) { count++; sum += Long.valueOf(node); } index++; if (index >= countExpected) { sumList.add(sum); countExpected = (int)Math.pow(2, count); count = 0; index = 0; sum = 0; } } Long[] sumArr = new Long[sumList.size()]; sumList.toArray(sumArr); return findMax(sumArr, 0); } static long findMax(int n, String tree); }### Answer:
@Test public void testFindMax() { Map<String, int[]> mapIO = new HashMap<String, int[]>() {{ put("3 4 5 1 3 # 1", new int[]{6, 9}); put("3 2 3 # 3 # 1", new int[]{5, 7}); }}; for (Map.Entry<String, int[]> io : mapIO.entrySet()) { long ret = Portfolio.findMax(io.getValue()[0], io.getKey()); Assert.assertEquals((long)(io.getValue()[1]), ret); } } |
### Question:
MovieTitles { public static String[] getMovieTitles(String substr) { if (substr == null || substr.trim().length() <= 0) { return null; } int page = 1; final String url = "https: Gson gson = new Gson(); List<String> movies = new ArrayList<String>(); while (true) { String response = null; try { response = httpGet(String.format(url, substr, page)); } catch (Exception e) { e.printStackTrace(); } if (response == null || response.trim().length() <= 0) { break; } MoviePage moviePage = gson.fromJson(response, MoviePage.class); if (moviePage == null || moviePage.data == null || moviePage.data.size() <= 0) { break; } for (Movie movie : moviePage.data) { movies.add(movie.Title); } if (page < moviePage.total_pages) { page++; } else { break; } } String[] titles = new String[movies.size()]; movies.toArray(titles); Arrays.sort(titles); return titles; } static String[] getMovieTitles(String substr); static String httpGet(String url); }### Answer:
@Test public void testMovieTitles() { final String[] ret = MovieTitles.getMovieTitles("spiderman"); System.out.println(Arrays.asList(ret).toString()); Assert.assertArrayEquals(new String[]{ "Amazing Spiderman Syndrome", "Fighting, Flying and Driving: The Stunts of Spiderman 3", "Hollywood's Master Storytellers: Spiderman Live", "Italian Spiderman", "Spiderman", "Spiderman", "Spiderman 5", "Spiderman and Grandma", "Spiderman in Cannes", "Superman, Spiderman or Batman", "The Amazing Spiderman T4 Premiere Special", "The Death of Spiderman", "They Call Me Spiderman", }, ret); } |
### Question:
ReductionCost { public static int reductionCost(int[] numArr) { if (numArr == null || numArr.length <= 0) { return 0; } int cost = 0; for (int i = 0; i < numArr.length - 1; i++) { Arrays.sort(numArr); int sum = numArr[i] + numArr[i + 1]; numArr[i] = 0; numArr[i + 1] = sum; cost += sum; } return cost; } static int reductionCost(int[] numArr); }### Answer:
@Test public void testReductionCost() { Map<int[], Integer> mapIO = new HashMap<int[], Integer>() {{ put(new int[] {1, 2, 3}, 9); put(new int[] {1, 2, 3, 4}, 19); }}; for (Map.Entry<int[], Integer> io : mapIO.entrySet()) { int ret = ReductionCost.reductionCost(io.getKey()); Assert.assertEquals(io.getValue().intValue(), ret); } } |
### Question:
Arbitrage { public static int[] arbitrage(String[] quotes) { if (quotes == null || quotes.length <= 0) { return null; } int[] profits = new int[quotes.length]; for (int i = 0; i < quotes.length; i++) { double[] prices = parseQuote(quotes[i]); int profit = 0; if (prices != null) { double dollar = 100000; for (int j = 0; j < prices.length; j++) { dollar /= prices[j]; } profit = (int) dollar - 100000; if (profit < 0) { profit = 0; } } profits[i] = profit; } return profits; } static int[] arbitrage(String[] quotes); }### Answer:
@Test public void testArbitrage() { int[] ret = Arbitrage.arbitrage(new String[]{"1.1837 1.3829 0.6102", "1.1234 1.2134 1.2311"}); Assert.assertArrayEquals(new int[]{114, 0}, ret); } |
### Question:
SubStr { public static String[] splitTokens(String str) { if (str == null || str.trim().length() <= 0) { return null; } String[] strArr = str.trim().split("[ !,?._'@]+"); return strArr; } static String[] splitTokens(String str); static String getSmallestAndLargest(String str, int k); }### Answer:
@Test public void testSplitTokens() { Map<String, Integer> mapIO = new HashMap<String, Integer>() {{ put("He is a very very good boy, isn't he?", 10); put(" YES leading spaces are valid, problemsetters are evillllll", 8); put("", 0); put(null, 0); }}; for (Map.Entry<String, Integer> io : mapIO.entrySet()) { String[] ret = SubStr.splitTokens(io.getKey()); Assert.assertEquals(io.getValue().intValue(), ret == null ? 0 : ret.length); } } |
### Question:
SubStr { public static String getSmallestAndLargest(String str, int k) { if (str == null || str.length() < k || k <= 0) { return "\n"; } String smallest = str.substring(0, k); String largest = smallest; for (int i = 1; i < str.length() - k + 1; i++) { String sub = str.substring(i, i + k); if (smallest.compareTo(sub) > 0) { smallest = sub; } if (largest.compareTo(sub) < 0) { largest = sub; } } return smallest + "\n" + largest; } static String[] splitTokens(String str); static String getSmallestAndLargest(String str, int k); }### Answer:
@Test public void testGetSmallestAndLargest() { Map<String, String> mapIO = new HashMap<String, String>() {{ put("welcometojava", "ava\nwel"); }}; for (Map.Entry<String, String> io : mapIO.entrySet()) { String ret = SubStr.getSmallestAndLargest(io.getKey(), 3); Assert.assertEquals(io.getValue(), ret); } } |
### Question:
NumberOfPairs { static int numberOfPairs(int[] a, long k) { if (a == null || a.length <= 1) { return 0; } Arrays.sort(a); Map<Integer, Integer> pairMap = new HashMap<Integer, Integer>(); for (int i = 0; i < a.length; i++) { int m = a[i]; for (int j = a.length - 1; j > i; j--) { int n = a[j]; if (m + n < k) { break; } else if (m + n == k) { if (m < n) { pairMap.put(m, n); } else { pairMap.put(n, m); } } } } return pairMap.size(); } }### Answer:
@Test public void testBraces() { Map<int[], Integer[]> mapIO = new HashMap<int[], Integer[]>() {{ put(new int[] {6, 6, 3, 9, 3, 5, 1}, new Integer[]{12, 2}); }}; for (Map.Entry<int[], Integer[]> io : mapIO.entrySet()) { Integer ret = NumberOfPairs.numberOfPairs(io.getKey(), io.getValue()[0]); Assert.assertEquals(io.getValue()[1], ret); } } |
### Question:
Palindrome { static int getScore(String s) { if (s == null || s.trim().length() <= 1) { return 0; } if (s.length() == 2) { return 1; } int score = 0; for (int i = 1; i < s.length(); i++) { String p1 = getMaxPalindrome(s.substring(0, i)); String p2 = getMaxPalindrome(s.substring(i, s.length())); int tmp = (p1 == null ? 0 : p1.length()) * (p2 == null ? 0 : p2.length()); if (score < tmp) { score = tmp; } } return score; } static boolean isPalindrome(String str); }### Answer:
@Test public void testGetScore() { Map<String, Integer> mapIO = new HashMap<String, Integer>(){{ put("acdapmpomp", 15); put("axbawbaseksqke", 25); put("aa", 1); put("ab", 1); put("abb", 2); put("aab", 2); }}; for (Map.Entry<String, Integer> io : mapIO.entrySet()) { int ret = Palindrome.getScore(io.getKey()); Assert.assertEquals(io.getValue().intValue(), ret); } } |
### Question:
Braces { static String[] braces(String[] values) { if (values == null || values.length <= 0) { return null; } Map<Integer, Integer> braceMap = new HashMap<Integer, Integer>() {{ put((int)')', (int)'('); put((int)']', (int)'['); put((int)'}', (int)'{'); }}; String[] ret = new String[values.length]; for (int i = 0; i < values.length; i++) { String value = values[i]; char[] braceArr = new char[value.length() / 2 + 1]; int j = -1; boolean closed = true; for (char c : value.toCharArray()) { if (braceMap.keySet().contains((int)c)) { if (j >= 0 && braceArr[j] == braceMap.get((int)c)) { j--; } else { closed = false; break; } } else { if (j < braceArr.length) { ++j; braceArr[j] = c; } else { closed = false; break; } } } ret[i] = j < 0 && closed ? "YES" : "NO"; } return ret; } }### Answer:
@Test public void testBraces() { Map<String[], String[]> mapIO = new HashMap<String[], String[]>() {{ put(new String[] {"{}[]()", "{[}]}"}, new String[] {"YES", "NO"}); put(new String[] {"}][}}(}][))]"}, new String[] {"NO"}); }}; for (Map.Entry<String[], String[]> io : mapIO.entrySet()) { String[] ret = Braces.braces(io.getKey()); Assert.assertArrayEquals(io.getValue(), ret); } } |
### Question:
AopInstrumenter implements MethodInterceptor { public Object getInstrumentedClass(Class clz) { enhancer.setSuperclass(clz); enhancer.setCallback(this); return enhancer.create(); } Object getInstrumentedClass(Class clz); Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy); }### Answer:
@Test public void testGetInstrumentedObject() { AopInstrumenter instrumenter = new AopInstrumenter(); AopService service = (AopService) instrumenter.getInstrumentedClass(AopServiceImpl.class); service.findInfo("Instrumenter from test"); } |
### Question:
App { public static void main(String[] args) { AopService service = (AopService) AopFactory.getAopProxyedObject(AopServiceImpl.class.getName()); service.findInfo("Jonn from app.main"); AopInstrumenter instrumenter = new AopInstrumenter(); service = (AopService) instrumenter.getInstrumentedClass(AopServiceImpl.class); service.findInfo("Instumenter from app.main"); } static void main(String[] args); }### Answer:
@Test public void testApp() { App.main(null); } |
### Question:
AopFactory { public static Object getAopProxyedObject(String clzName) { Object proxy = null; AopHandler handler = new AopHandler(); Object obj = getClassInst(clzName); if (obj != null) { proxy = handler.bind(obj); } else { System.out.println("Can't get the proxyObj"); } return proxy; } static Object getAopProxyedObject(String clzName); }### Answer:
@Test public void testGetAopProxyedObject() { AopService service = (AopService) AopFactory.getAopProxyedObject(AopServiceImpl.class.getName()); service.findInfo("Jonn from test"); } |
### Question:
RedisService { public long incr(String key) { Long ret = strValOps.increment(key, 1L); return ret == null ? 0 : ret; } long incr(String key); boolean expire(String key, long seconds); }### Answer:
@Test public void testIncr() { String key = "RedisServiceTest.testStr"; long ret = redisService.incr(key); Assertions.assertTrue(ret > 0); System.out.println(ret); redisService.expire(key, 1); } |
### Question:
LengthValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { int length = tx.getLength(); if (length > Constant.TRANSACTION_MAX_PAYLOAD_LENGTH) { return ValidationResult.error("Invalid transaction length."); } return ValidationResult.success; } @Override ValidationResult validate(Transaction tx, ILedger ledger); }### Answer:
@Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Test public void length_exceeds_limit() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid transaction length."); Transaction tx = spy(Builder.newTransaction(timeProvider).build(networkID, sender)); when(tx.getLength()).thenReturn(Constant.TRANSACTION_MAX_PAYLOAD_LENGTH + 1); validate(tx); } |
### Question:
AccountBotService { public State getState(String id) throws RemotePeerException, IOException { Account account = getAccount(id); if (account != null) { return State.OK; } IBacklog backlog = this.backlog; for (TransactionID item : backlog) { Transaction transaction = backlog.get(item); if (transaction != null && transaction.getType() == TransactionType.Registration) { if (transaction.getData().keySet().contains(id)) { return State.Processing; } } } return State.NotFound; } AccountBotService(IBacklog backlog, LedgerProvider ledgerProvider, IBlockchainProvider blockchain); State getState(String id); Info getInformation(String id); EONBalance getBalance(String id); }### Answer:
@Test public void getState_for_existing_account_should_return_OK() throws Exception { AccountID id = new AccountID(12345L); ledger = ledger.putAccount(new Account(id)); assertEquals(AccountBotService.State.OK, service.getState(id.toString())); }
@Test public void getState_for_processing_account() throws Exception { ISigner sender = new TestSigner("00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"); ISigner newAccount = new TestSigner("112233445566778899aabbccddeeff00112233445566778899aabbccddeeff00"); Transaction tx = RegistrationBuilder.createNew(newAccount.getPublicKey()).build(new BlockID(0L), sender); backlog.put(tx); AccountID id = new AccountID(newAccount.getPublicKey()); assertEquals(AccountBotService.State.Processing, service.getState(id.toString())); }
@Test public void getState_for_notexisting_account() throws Exception { assertEquals(AccountBotService.State.NotFound, service.getState(new AccountID(12345L).toString())); } |
### Question:
Fork implements IFork { @Override public boolean isCome(int timestamp) { return items.getFirst().isCome(timestamp); } Fork(BlockID genesisBlockID, ForkItem[] items, String beginAll); Fork(BlockID genesisBlockID, ForkItem[] items); Fork(BlockID genesisBlockID, ForkItem[] items, long beginAll); @Override BlockID getGenesisBlockID(); @Override boolean isPassed(int timestamp); @Override boolean isCome(int timestamp); @Override int getNumber(int timestamp); @Override Set<Integer> getTransactionTypes(int timestamp); @Override int getBlockVersion(int timestamp); @Override ILedger convert(ILedger ledger, int timestamp); @Override ITransactionParser getParser(int timestamp); long getMinDepositSize(); void setMinDepositSize(long minDepositSize); }### Answer:
@Test public void isCome() { assertFalse("Before fork", forkState.isCome(50)); assertFalse("Fork started", forkState.isCome(100)); assertTrue("On fork", forkState.isCome(150)); assertTrue("Fork ended", forkState.isCome(200)); assertTrue("After fork", forkState.isCome(250)); } |
### Question:
Fork implements IFork { @Override public boolean isPassed(int timestamp) { return items.getFirst().isPassed(timestamp); } Fork(BlockID genesisBlockID, ForkItem[] items, String beginAll); Fork(BlockID genesisBlockID, ForkItem[] items); Fork(BlockID genesisBlockID, ForkItem[] items, long beginAll); @Override BlockID getGenesisBlockID(); @Override boolean isPassed(int timestamp); @Override boolean isCome(int timestamp); @Override int getNumber(int timestamp); @Override Set<Integer> getTransactionTypes(int timestamp); @Override int getBlockVersion(int timestamp); @Override ILedger convert(ILedger ledger, int timestamp); @Override ITransactionParser getParser(int timestamp); long getMinDepositSize(); void setMinDepositSize(long minDepositSize); }### Answer:
@Test public void isPassed() { assertFalse("Before fork", forkState.isPassed(50)); assertFalse("Fork started", forkState.isPassed(100)); assertFalse("On fork", forkState.isPassed(150)); assertFalse("Fork ended", forkState.isPassed(200)); assertTrue("After fork", forkState.isPassed(250)); } |
### Question:
Fork implements IFork { @Override public int getNumber(int timestamp) { Item item = getItem(timestamp); return (item == null) ? -1 : item.getNumber(); } Fork(BlockID genesisBlockID, ForkItem[] items, String beginAll); Fork(BlockID genesisBlockID, ForkItem[] items); Fork(BlockID genesisBlockID, ForkItem[] items, long beginAll); @Override BlockID getGenesisBlockID(); @Override boolean isPassed(int timestamp); @Override boolean isCome(int timestamp); @Override int getNumber(int timestamp); @Override Set<Integer> getTransactionTypes(int timestamp); @Override int getBlockVersion(int timestamp); @Override ILedger convert(ILedger ledger, int timestamp); @Override ITransactionParser getParser(int timestamp); long getMinDepositSize(); void setMinDepositSize(long minDepositSize); }### Answer:
@Test public void getNumber() { assertEquals("Before fork", 1, forkState.getNumber(50)); assertEquals("Fork started", 1, forkState.getNumber(100)); assertEquals("On fork", 2, forkState.getNumber(150)); assertEquals("Fork ended", 2, forkState.getNumber(200)); assertEquals("After fork", 2, forkState.getNumber(250)); } |
### Question:
VersionValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.getVersion() != 1) { return ValidationResult.error("Version is not supported."); } return ValidationResult.success; } @Override ValidationResult validate(Transaction tx, ILedger ledger); }### Answer:
@Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Test public void unknown_version() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Version is not supported."); Transaction tx = Builder.newTransaction(timeProvider).version(12345).build(networkID, sender); validate(tx); } |
### Question:
FeePerByteValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { int length = tx.getLength(); long fee = tx.getFee(); if (fee < length * Constant.TRANSACTION_MIN_FEE_PER_BYTE) { return ValidationResult.error("Invalid fee."); } return ValidationResult.success; } @Override ValidationResult validate(Transaction tx, ILedger ledger); }### Answer:
@Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Test public void fee_zero() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid fee."); Transaction tx = Builder.newTransaction(timeProvider).forFee(0L).build(networkID, sender); tx.setLength(1); validate(tx); }
@Test public void too_small_fee() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid fee."); Transaction tx = Builder.newTransaction(timeProvider).forFee(10L).build(networkID, sender); tx.setLength(1024 + 1); validate(tx); } |
### Question:
FutureTimestampValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.isFuture(timeProvider.get())) { return ValidationResult.error(new LifecycleException()); } return ValidationResult.success; } FutureTimestampValidationRule(ITimeProvider timeProvider); FutureTimestampValidationRule(int timestamp); @Override ValidationResult validate(Transaction tx, ILedger ledger); }### Answer:
@Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Test public void future_timestamp() throws Exception { expectedException.expect(LifecycleException.class); Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); int timestamp = tx.getTimestamp() - 1; Mockito.when(timeProvider.get()).thenReturn(timestamp); validate(tx); } |
### Question:
TypeValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (allowedTypes.contains(tx.getType())) { return ValidationResult.success; } return ValidationResult.error("Invalid transaction type. Type :" + tx.getType()); } TypeValidationRule(Set<Integer> allowedTypes); @Override ValidationResult validate(Transaction tx, ILedger ledger); }### Answer:
@Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).type(10).build(networkID, sender); validate(tx); }
@Test public void unknown_type() throws Exception { int type = 12345; expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid transaction type. Type :" + type); Transaction tx = Builder.newTransaction(timeProvider).type(type).build(networkID, sender); validate(tx); } |
### Question:
PayerValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.getPayer() == null) { return ValidationResult.success; } if (tx.getSenderID().equals(tx.getPayer())) { return ValidationResult.error("Invalid payer"); } if (tx.getConfirmations() == null || !tx.getConfirmations().containsKey(tx.getPayer().toString())) { return ValidationResult.error("Payer not confirm"); } return ValidationResult.success; } @Override ValidationResult validate(Transaction tx, ILedger ledger); }### Answer:
@Test public void payer_success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider) .payedBy(payerAccount) .build(networkID, sender, new ISigner[] {payer}); validate(tx); }
@Test public void no_payer_success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Test public void illegal_payer() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid payer"); Transaction tx = Builder.newTransaction(timeProvider) .payedBy(new AccountID(sender.getPublicKey())) .build(networkID, sender); validate(tx); }
@Test public void payer_not_confirm() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Payer not confirm"); Transaction tx = Builder.newTransaction(timeProvider).payedBy(payerAccount).build(networkID, sender); validate(tx); } |
### Question:
ExpiredTimestampValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.isExpired(timeProvider.get())) { return ValidationResult.error(new LifecycleException()); } return ValidationResult.success; } ExpiredTimestampValidationRule(ITimeProvider timeProvider); ExpiredTimestampValidationRule(int timestamp); @Override ValidationResult validate(Transaction tx, ILedger ledger); }### Answer:
@Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Test public void expired() throws Exception { expectedException.expect(LifecycleException.class); Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); int timestamp = tx.getTimestamp() + tx.getDeadline() + 1; Mockito.when(timeProvider.get()).thenReturn(timestamp); validate(tx); } |
### Question:
DeadlineValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.getDeadline() < 1 || tx.getDeadline() > Constant.TRANSACTION_MAX_LIFETIME) { return ValidationResult.error(new LifecycleException()); } return ValidationResult.success; } @Override ValidationResult validate(Transaction tx, ILedger ledger); }### Answer:
@Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Test public void deadline_zero() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid timestamp or other params for set the time."); Transaction tx = Builder.newTransaction(timestamp).deadline((short) 0).build(networkID, sender); validate(tx); }
@Test public void deadline_max() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid timestamp or other params for set the time."); Transaction tx = Builder.newTransaction(timeProvider) .deadline((short) (Constant.TRANSACTION_MAX_LIFETIME + 1)) .build(networkID, sender); validate(tx); } |
### Question:
ReferencedTransactionValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.getReference() != null) { return ValidationResult.error("Illegal reference."); } return ValidationResult.success; } @Override ValidationResult validate(Transaction tx, ILedger ledger); }### Answer:
@Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Test public void success_without_note() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Illegal reference."); Transaction tx = Builder.newTransaction(timeProvider).refBy(new TransactionID(12345L)).build(networkID, sender); validate(tx); } |
### Question:
EmptyPayerValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.getPayer() != null) { return ValidationResult.error("Forbidden."); } if (tx.hasNestedTransactions()) { for (Transaction transaction : tx.getNestedTransactions().values()) { ValidationResult result = this.validate(transaction, ledger); if (result.hasError) { return result; } } } return ValidationResult.success; } @Override ValidationResult validate(Transaction tx, ILedger ledger); }### Answer:
@Test public void payer_error() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Forbidden."); Transaction tx = Builder.newTransaction(timeProvider) .payedBy(payerAccount) .build(networkID, sender, new ISigner[] {payer}); validate(tx); }
@Test public void payer_success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Test public void payer_nested_error() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Forbidden."); Transaction tx = Builder.newTransaction(timeProvider) .payedBy(payerAccount) .build(networkID, sender, new ISigner[] {payer}); validate(Builder.newTransaction(timeProvider).addNested(tx).build(networkID, sender)); }
@Test public void payer_nested_success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(Builder.newTransaction(timeProvider).addNested(tx).build(networkID, sender)); } |
### Question:
Sift { private Sift() { } private Sift(); static void open(@NonNull Context context,
Config config,
String activityName); static void open(@NonNull Context context, String activityName); static void open(@NonNull Context context, Config config); static void open(@NonNull Context context); static void collect(); static void pause(); static void resume(@NonNull Context context); static void resume(@NonNull Context context, String activityName); static void close(); static synchronized void setUserId(String userId); static synchronized void unsetUserId(); }### Answer:
@Test public void testSift() throws Exception { MemorySharedPreferences preferences = new MemorySharedPreferences(); SiftImpl sift = new SiftImpl( mockContext(preferences), null, "", false, mockTaskManager()); assertNotNull(sift.getConfig()); assertNull(sift.getConfig().accountId); assertNull(sift.getConfig().beaconKey); assertNotNull(sift.getConfig().serverUrlFormat); assertFalse(sift.getConfig().disallowLocationCollection); assertNull(sift.getUserId()); assertNotNull(sift.getQueue(SiftImpl.DEVICE_PROPERTIES_QUEUE_IDENTIFIER)); assertNull(sift.getQueue("some-queue")); assertNotNull(sift.createQueue("some-queue", new Queue.Config.Builder().build())); try { sift.createQueue("some-queue", new Queue.Config.Builder().build()); fail(); } catch (IllegalStateException e) { assertEquals("Queue exists: some-queue", e.getMessage()); } assertTrue(preferences.fields.isEmpty()); } |
### Question:
Sift { public static synchronized void unsetUserId() { setUserId(null); } private Sift(); static void open(@NonNull Context context,
Config config,
String activityName); static void open(@NonNull Context context, String activityName); static void open(@NonNull Context context, Config config); static void open(@NonNull Context context); static void collect(); static void pause(); static void resume(@NonNull Context context); static void resume(@NonNull Context context, String activityName); static void close(); static synchronized void setUserId(String userId); static synchronized void unsetUserId(); }### Answer:
@Test public void testUnsetUserId() throws Exception { MemorySharedPreferences preferences = new MemorySharedPreferences(); SiftImpl sift = new SiftImpl(mockContext(preferences), null, "", false, mockTaskManager()); sift.setUserId("gary"); sift.getQueue(SiftImpl.APP_STATE_QUEUE_IDENTIFIER).append(new MobileEventJson()); sift.getQueue(SiftImpl.APP_STATE_QUEUE_IDENTIFIER).append(new MobileEventJson()); MobileEventJson event = sift.getQueue(SiftImpl.APP_STATE_QUEUE_IDENTIFIER).flush().get(0); assertEquals("gary", event.userId); sift.unsetUserId(); sift.getQueue(SiftImpl.APP_STATE_QUEUE_IDENTIFIER).append(new MobileEventJson()); event = sift.getQueue(SiftImpl.APP_STATE_QUEUE_IDENTIFIER).flush().get(0); assertNull(event.userId); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.