src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
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; } | @Test void canonicalizedPathRemovesMultipleSlashes() { assertEquals(signing_obj.canonicalPath(" }
@Test void canonicalizedPathRemovesTrailingSlash() { assertEquals(signing_obj.canonicalPath("/path/"), "/path"); } |
SignedHeaderAuth implements HttpRequestFilter { public HttpRequest filter(HttpRequest input) throws HttpException { HttpRequest request = input.toBuilder().endpoint(input.getEndpoint().toString().replace("%3F", "?")).build(); String contentHash = hashBody(request.getPayload()); Multimap<String, String> headers = ArrayListMultimap.create(); headers.put("X-Ops-Content-Hash", contentHash); String timestamp = timeStampProvider.get(); String toSign = createStringToSign(request.getMethod(), hashPath(request.getEndpoint().getPath()), contentHash, timestamp); headers.put("X-Ops-Userid", creds.get().identity); headers.put("X-Ops-Sign", SIGNING_DESCRIPTION); request = calculateAndReplaceAuthorizationHeaders(request, toSign); headers.put("X-Ops-Timestamp", timestamp); utils.logRequest(signatureLog, request, "<<"); return request.toBuilder().replaceHeaders(headers).build(); } @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; } | @Test void shouldGenerateTheCorrectStringToSignAndSignatureWithNoBody() { HttpRequest request = HttpRequest.builder().method(HttpMethod.DELETE).endpoint("http: .build(); request = signing_obj.filter(request); Multimap<String, String> headersWithoutContentLength = LinkedHashMultimap.create(request.getHeaders()); assertEqualsNoOrder(headersWithoutContentLength.entries().toArray(), EXPECTED_SIGN_RESULT_EMPTY.entries() .toArray()); }
@Test void shouldNotChokeWhenSigningARequestForAResourceWithALongName() { StringBuilder path = new StringBuilder("nodes/"); for (int i = 0; i < 100; i++) path.append('A'); HttpRequest request = HttpRequest.builder().method(HttpMethod.PUT) .endpoint("http: signing_obj.filter(request); }
@Test void shouldReplacePercentage3FWithQuestionMarkAtUrl() { StringBuilder path = new StringBuilder("nodes/"); path.append("test/cookbooks/myCookBook%3Fnum_versions=5"); HttpRequest request = HttpRequest.builder().method(HttpMethod.GET) .endpoint("http: request = signing_obj.filter(request); assertTrue(request.getRequestLine().contains("?num_versions=5")); } |
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); } | @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()); } |
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); } | @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); } |
GroupName implements Function<Object, String> { @Override public String apply(Object from) { return ((Group) checkNotNull(from, "from")).getGroupname(); } @Override String apply(Object from); } | @Test(expectedExceptions = NullPointerException.class) public void testInvalidNullInput() { new GroupName().apply(null); } |
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); } | @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); } |
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); } | @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); } |
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); } | @Test(expectedExceptions = NoSuchElementException.class) public void testFindRoleInRunListThrowsNoSuchElementOnRecipe() { ChefUtils.findRoleInRunList(ImmutableList.of("recipe[java]")); } |
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(); } | @Test public void extension_createContext_returnsContext() { PowerMockito.mockStatic(LocalNotificationsContext.class); when(LocalNotificationsContext.getInstance()).thenReturn(context); assertSame(context, getSubject().createContext("anyId")); } |
SoundSettings { public Uri getSoundUri() { String soundName = getSoundName(); if (soundName == null) return null; return NotificationSoundProvider.getSoundUri(soundName); } SoundSettings(Bundle bundle); Uri getSoundUri(); int getSoundDefault(); } | @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()); } |
SoundSettings { public int getSoundDefault() { return shouldPlayDefaultSound()? Notification.DEFAULT_SOUND : 0; } SoundSettings(Bundle bundle); Uri getSoundUri(); int getSoundDefault(); } | @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()); } |
Application extends android.app.Application { @Override public void onCreate() { super.onCreate(); registerActivityLifecycleCallbacks(new LifecycleCallbacks()); } @Override void onCreate(); } | @Test public void application_addsCallbacks_onCreate() { getSubject().onCreate(); verify(getSubject()).registerActivityLifecycleCallbacks(callbacks); } |
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } LocalNotificationIntentService(); @Override final void onHandleIntent(Intent intent); } | @Test public void intentService_onHandleIntent_doesNotDispatchNotificationWhenUserResponseNotPresent() { try { PowerMockito.whenNew(LocalNotificationEventDispatcher.class) .withArguments("KeyCode", data, "ActionId", null) .thenReturn(dispatcher); } catch(Exception e) { e.printStackTrace(); } when(intent.getStringExtra(Constants.USER_RESPONSE_KEY)).thenReturn(null); getSubject().onHandleIntent(intent); verify(notificationDispatcher, never()).dispatch(); }
@Test public void intentService_onHandleIntent_closesDialogs() { getSubject().onHandleIntent(intent); verify(getSubject()).sendBroadcast(closeIntent); }
@Test public void intentService_onHandleIntent_triesToDispatchEventToBackground() { getSubject().onHandleIntent(intent); verify(dispatcher).dispatchWhenActive(); }
@Test public void intentService_onHandleIntent_doesNotStartForegroundActivityWhenInForeground() { when(intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false)).thenReturn(false); getSubject().onHandleIntent(intent); verify(context, never()).startActivity(any(Intent.class)); }
@Test public void intentService_onHandleIntent_startsForegroundActivityWhenNotInForeground_andNotActive() { when(ApplicationStatus.getActive()).thenReturn(false); when(ApplicationStatus.getInForeground()).thenReturn(false); when(intent.getStringExtra(Constants.MAIN_ACTIVITY_CLASS_NAME_KEY)).thenReturn("MainActivityClass"); getSubject().onHandleIntent(intent); verify(intent).setClassName(context, "MainActivityClass"); verify(intent).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); verify(intent).putExtra(Constants.BACKGROUND_MODE_KEY, false); verify(context).startActivity(intent); }
@Test public void intentService_onHandleIntent_startsForegroundActivityWhenNotInForeground_andActive() { when(ApplicationStatus.getInForeground()).thenReturn(false); when(intent.getStringExtra(Constants.MAIN_ACTIVITY_CLASS_NAME_KEY)).thenReturn("MainActivityClass"); getSubject().onHandleIntent(intent); verify(intent).setClassName(context, "MainActivityClass"); verify(intent).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); verify(intent).putExtra(Constants.BACKGROUND_MODE_KEY, false); verify(context).startActivity(intent); }
@Test public void intentService_onHandleIntent_doesNotStartBackgroundActivityWhenInForeground() { when(intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false)).thenReturn(true); getSubject().onHandleIntent(intent); verify(context, never()).startActivity(any(Intent.class)); }
@Test public void intentService_onHandleIntent_doesNotStartBackgroundActivityWhenNotInForeground_andActive() { when(ApplicationStatus.getInForeground()).thenReturn(false); when(intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false)).thenReturn(true); getSubject().onHandleIntent(intent); verify(context, never()).startActivity(any(Intent.class)); }
@Test public void intentService_onHandleIntent_startsBackgroundActivityWhenNotInForeground_andNotActive() { when(ApplicationStatus.getActive()).thenReturn(false); when(ApplicationStatus.getInForeground()).thenReturn(false); when(intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false)).thenReturn(true); when(intent.getStringExtra(Constants.MAIN_ACTIVITY_CLASS_NAME_KEY)).thenReturn("MainActivityClass"); getSubject().onHandleIntent(intent); verify(intent).setClassName(context, "MainActivityClass"); verify(intent).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); verify(intent).putExtra(Constants.BACKGROUND_MODE_KEY, true); verify(context).startActivity(intent); }
@Test public void intentService_onHandleIntent_dispatchesNotificationWhenUserResponsePresent() { when(intent.getStringExtra(Constants.USER_RESPONSE_KEY)).thenReturn("User Response"); getSubject().onHandleIntent(intent); verify(notificationDispatcher).dispatch(); } |
LocalNotification implements ISerializable, IDeserializable { public void deserialize(JSONObject jsonObject) { if (jsonObject != null) { code = jsonObject.optString("code", code); tickerText = jsonObject.optString("tickerText", tickerText); title = jsonObject.optString("title", title); body = jsonObject.optString("body", body); playSound = jsonObject.optBoolean("playSound", playSound); vibrate = jsonObject.optBoolean("vibrate", vibrate); iconResourceId = jsonObject.optInt("iconResourceId", iconResourceId); numberAnnotation = jsonObject.optInt("numberAnnotation", numberAnnotation); cancelOnSelect = jsonObject.optBoolean("cancelOnSelect", cancelOnSelect); ongoing = jsonObject.optBoolean("ongoing", ongoing); alertPolicy = jsonObject.optString("alertPolicy", alertPolicy); hasAction = jsonObject.optBoolean("hasAction", hasAction); soundName = jsonObject.optString("soundName", soundName); activityClassName = jsonObject.optString("activityClassName", activityClassName); priority = jsonObject.optInt("priority", priority); showInForeground = jsonObject.optBoolean("showInForeground", showInForeground); category = jsonObject.optString("category", category); isExact = jsonObject.optBoolean("isExact", isExact); allowWhileIdle = jsonObject.optBoolean("allowWhileIdle", allowWhileIdle); long dateTime = jsonObject.optLong("fireDate", fireDate.getTime()); fireDate = new Date(dateTime); repeatInterval = jsonObject.optInt("repeatInterval", repeatInterval); try { JSONArray jsonArray = jsonObject.getJSONArray("actionData"); int dataLength = jsonArray.length(); actionData = new byte[dataLength]; for (int i = 0; i < dataLength; i++) { actionData[i] = (byte) jsonArray.getInt(i); } } catch (Exception e) { Logger.log("LocalNotification::deserialize Exception while reading actionData"); } } } 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; } | @Test public void notification_deserialize_deserializesFromJsonObject() { when(jsonObject.optString("code", "")).thenReturn("MyCode"); when(jsonObject.optString("tickerText", "")).thenReturn("Ticker"); when(jsonObject.optString("title", "")).thenReturn("Title"); when(jsonObject.optString("body", "")).thenReturn("Body"); when(jsonObject.optInt("iconResourceId", 0)).thenReturn(10); when(jsonObject.optInt("numberAnnotation", 0)).thenReturn(5); when(jsonObject.optString("alertPolicy", "")).thenReturn("policy"); when(jsonObject.optString("soundName", "")).thenReturn("sound.mp3"); when(jsonObject.optString("activityClassName", null)).thenReturn("ClassName"); when(jsonObject.optInt("priority", 0)).thenReturn(2); when(jsonObject.optLong("fireDate", getSubject().fireDate.getTime())).thenReturn((long)100000); when(jsonObject.optInt("repeatInterval", 0)).thenReturn(2000); when(jsonObject.optString("category", "")).thenReturn("Category"); assertEquals("", getSubject().code); assertEquals("", getSubject().tickerText); assertEquals("", getSubject().title); assertEquals("", getSubject().body); assertEquals(0, getSubject().iconResourceId); assertEquals(0, getSubject().numberAnnotation); assertEquals("", getSubject().alertPolicy); assertEquals("", getSubject().soundName); assertNull(getSubject().activityClassName); assertEquals(0, getSubject().priority); assertEquals(new Date(getSubject().fireDate.getTime()), getSubject().fireDate); assertEquals(0, getSubject().repeatInterval); assertEquals("", getSubject().category); getSubject().deserialize(jsonObject); assertEquals("MyCode", getSubject().code); assertEquals("Ticker", getSubject().tickerText); assertEquals("Title", getSubject().title); assertEquals("Body", getSubject().body); assertEquals(10, getSubject().iconResourceId); assertEquals(5, getSubject().numberAnnotation); assertEquals("policy", getSubject().alertPolicy); assertEquals("sound.mp3", getSubject().soundName); assertEquals("ClassName", getSubject().activityClassName); assertEquals(2, getSubject().priority); assertEquals(new Date(100000), getSubject().fireDate); assertEquals(2000, getSubject().repeatInterval); assertEquals("Category", getSubject().category); }
@Test public void notification_deserialize_deserializesPlaySoundFromJsonObject() { when(jsonObject.optBoolean("playSound", false)).thenReturn(true); assertEquals(false, getSubject().playSound); getSubject().deserialize(jsonObject); assertEquals(true, getSubject().playSound); }
@Test public void notification_deserialize_deserializesVibrateFromJsonObject() { when(jsonObject.optBoolean("vibrate", false)).thenReturn(true); assertEquals(false, getSubject().vibrate); getSubject().deserialize(jsonObject); assertEquals(true, getSubject().vibrate); }
@Test public void notification_deserialize_deserializesCancelOnSelectFromJsonObject() { when(jsonObject.optBoolean("cancelOnSelect", false)).thenReturn(true); assertEquals(false, getSubject().cancelOnSelect); getSubject().deserialize(jsonObject); assertEquals(true, getSubject().cancelOnSelect); }
@Test public void notification_deserialize_deserializesOngoingFromJsonObject() { when(jsonObject.optBoolean("ongoing", false)).thenReturn(true); assertEquals(false, getSubject().ongoing); getSubject().deserialize(jsonObject); assertEquals(true, getSubject().ongoing); }
@Test public void notification_deserialize_deserializesHasActionFromJsonObject() { when(jsonObject.optBoolean("hasAction", false)).thenReturn(true); assertEquals(false, getSubject().hasAction); getSubject().deserialize(jsonObject); assertEquals(true, getSubject().hasAction); }
@Test public void notification_deserialize_deserializesShowInForegroundFromJsonObject() { when(jsonObject.optBoolean("showInForeground", false)).thenReturn(true); assertEquals(false, getSubject().showInForeground); getSubject().deserialize(jsonObject); assertEquals(true, getSubject().showInForeground); }
@Test public void notification_deserialize_deserializesByteDataFromJsonObject() { try { when(jsonObject.getJSONArray("actionData")).thenReturn(jsonArray); when(jsonArray.length()).thenReturn(2); when(jsonArray.getInt(0)).thenReturn(101); when(jsonArray.getInt(1)).thenReturn(30); } catch (Throwable e) { e.printStackTrace(); } getSubject().deserialize(jsonObject); assertArrayEquals(new byte[]{101, 30}, getSubject().actionData); }
@Test public void notification_deserialize_deserializesIsExactFromJsonObject() { when(jsonObject.optBoolean("isExact", false)).thenReturn(true); assertEquals(false, getSubject().isExact); getSubject().deserialize(jsonObject); assertEquals(true, getSubject().isExact); }
@Test public void notification_deserialize_deserializesAllowWhileIdleFromJsonObject() { when(jsonObject.optBoolean("allowWhileIdle", false)).thenReturn(true); assertEquals(false, getSubject().allowWhileIdle); getSubject().deserialize(jsonObject); assertEquals(true, getSubject().allowWhileIdle); }
@Test public void notification_deserialize_doesNothingIfJsonObjectIsNull() { getSubject().deserialize(null); verify(jsonObject, never()).optString(eq("code"), anyString()); verify(jsonObject, never()).optString(eq("tickerText"), anyString()); verify(jsonObject, never()).optString(eq("title"), anyString()); verify(jsonObject, never()).optString(eq("body"), anyString()); verify(jsonObject, never()).optBoolean(eq("playSound"), anyBoolean()); verify(jsonObject, never()).optInt(eq("iconResourceId"), anyInt()); verify(jsonObject, never()).optInt(eq("numberAnnotation"), anyInt()); verify(jsonObject, never()).optBoolean(eq("cancelOnSelect"), anyBoolean()); verify(jsonObject, never()).optBoolean(eq("ongoing"), anyBoolean()); verify(jsonObject, never()).optString(eq("alertPolicy"), anyString()); verify(jsonObject, never()).optBoolean(eq("hasAction"), anyBoolean()); verify(jsonObject, never()).optString(eq("soundName"), anyString()); verify(jsonObject, never()).optString(eq("activityClassName"), anyString()); verify(jsonObject, never()).optInt(eq("priority"), anyInt()); verify(jsonObject, never()).optBoolean(eq("showInForeground"), anyBoolean()); verify(jsonObject, never()).optLong(eq("fireDate"), anyLong()); verify(jsonObject, never()).optInt(eq("repeatInterval"), anyInt()); verify(jsonObject, never()).optString(eq("category"), anyString()); }
@Test public void notification_deserialize_stopsDeserializingByteArrayIfAnExceptionIsThrown() { try { when(jsonObject.getJSONArray("actionData")).thenReturn(jsonArray); when(jsonArray.length()).thenReturn(2); when(jsonArray.getInt(0)).thenReturn(101); when(jsonArray.getInt(1)).thenThrow(mock(JSONException.class)); getSubject().deserialize(jsonObject); } catch (Throwable e) { e.printStackTrace(); } assertArrayEquals(new byte[]{101, 0}, getSubject().actionData); getSubject().actionData = null; try { when(jsonObject.getJSONArray("actionData")).thenThrow(mock(JSONException.class)); } catch (Throwable e) { e.printStackTrace(); } getSubject().deserialize(jsonObject); assertNull(getSubject().actionData); } |
LocalNotification implements ISerializable, IDeserializable { public JSONObject serialize() { JSONObject jsonObject = new JSONObject(); try { jsonObject.putOpt("code", code); jsonObject.putOpt("tickerText", tickerText); jsonObject.putOpt("title", title); jsonObject.putOpt("body", body); jsonObject.putOpt("playSound", playSound); jsonObject.putOpt("vibrate", vibrate); jsonObject.putOpt("iconResourceId", iconResourceId); jsonObject.putOpt("numberAnnotation", numberAnnotation); jsonObject.putOpt("cancelOnSelect", cancelOnSelect); jsonObject.putOpt("ongoing", ongoing); jsonObject.putOpt("alertPolicy", alertPolicy); jsonObject.putOpt("hasAction", hasAction); jsonObject.putOpt("soundName", soundName); jsonObject.putOpt("fireDate", fireDate.getTime()); jsonObject.putOpt("repeatInterval", repeatInterval); jsonObject.putOpt("activityClassName", activityClassName); jsonObject.putOpt("priority", priority); jsonObject.putOpt("showInForeground", showInForeground); jsonObject.putOpt("category", category); jsonObject.putOpt("isExact", isExact); jsonObject.putOpt("allowWhileIdle", allowWhileIdle); for (byte anActionData : actionData) { jsonObject.accumulate("actionData", (int)anActionData); } } catch (Exception e) { Logger.log("LocalNotification::serialize Exception"); } return jsonObject; } 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; } | @Test public void notification_serialize_serializesNotification() { try { assertSame(jsonObject, getSubject("MyCode").serialize()); verify(jsonObject).putOpt("code", "MyCode"); verify(jsonObject).putOpt("tickerText", "Ticker2"); verify(jsonObject).putOpt("title", "Title2"); verify(jsonObject).putOpt("body", "Body2"); verify(jsonObject).putOpt("iconResourceId", 32); verify(jsonObject).putOpt("numberAnnotation", 12); verify(jsonObject).putOpt("alertPolicy", "policy2"); verify(jsonObject).putOpt("soundName", "sound2.mp3"); verify(jsonObject).putOpt("fireDate", (long)50000); verify(jsonObject).putOpt("repeatInterval", 231); verify(jsonObject).putOpt("activityClassName", "ClassName2"); verify(jsonObject).putOpt("priority", 1); verify(jsonObject).putOpt("category", "Category2"); } catch (JSONException e) { e.printStackTrace(); } }
@Test public void notification_serialize_serializesPlaySound() { try { getSubject().playSound = true; assertSame(jsonObject, getSubject().serialize()); verify(jsonObject).putOpt("playSound", true); } catch (JSONException e) { e.printStackTrace(); } }
@Test public void notification_serialize_serializesVibrate() { try { getSubject().vibrate = true; assertSame(jsonObject, getSubject().serialize()); verify(jsonObject).putOpt("vibrate", true); } catch (JSONException e) { e.printStackTrace(); } }
@Test public void notification_serialize_serializesCancelOnSelect() { try { getSubject().cancelOnSelect = true; assertSame(jsonObject, getSubject().serialize()); verify(jsonObject).putOpt("cancelOnSelect", true); } catch (JSONException e) { e.printStackTrace(); } }
@Test public void notification_serialize_serializesOngoing() { try { getSubject().ongoing = true; assertSame(jsonObject, getSubject().serialize()); verify(jsonObject).putOpt("ongoing", true); } catch (JSONException e) { e.printStackTrace(); } }
@Test public void notification_serialize_serializesHasAction() { try { getSubject().hasAction = true; assertSame(jsonObject, getSubject().serialize()); verify(jsonObject).putOpt("hasAction", true); } catch (JSONException e) { e.printStackTrace(); } }
@Test public void notification_serialize_serializesShowInForeground() { try { getSubject().showInForeground = true; assertSame(jsonObject, getSubject().serialize()); verify(jsonObject).putOpt("showInForeground", true); } catch (JSONException e) { e.printStackTrace(); } }
@Test public void notification_serialize_serializesByteData() { try { getSubject().actionData = new byte[]{102, 127}; assertSame(jsonObject, getSubject().serialize()); verify(jsonObject).accumulate("actionData", 102); verify(jsonObject).accumulate("actionData", 127); } catch (JSONException e) { e.printStackTrace(); } }
@Test public void notification_serialize_serializesIsExact() { try { getSubject().isExact = true; assertSame(jsonObject, getSubject().serialize()); verify(jsonObject).putOpt("isExact", true); } catch (JSONException e) { e.printStackTrace(); } }
@Test public void notification_serialize_serializesAllowWhileIdle() { try { getSubject().allowWhileIdle = true; assertSame(jsonObject, getSubject().serialize()); verify(jsonObject).putOpt("allowWhileIdle", true); } catch (JSONException e) { e.printStackTrace(); } }
@Test public void notification_serialize_stopsSerializingDataIfAnExceptionIsThrown() { try { getSubject().actionData = new byte[]{102, 127}; when(jsonObject.accumulate("actionData", 102)).thenThrow(mock(JSONException.class)); assertSame(jsonObject, getSubject().serialize()); verify(jsonObject).accumulate("actionData", 102); verify(jsonObject, never()).accumulate("actionData", 127); } catch (JSONException e) { e.printStackTrace(); } } |
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; } | @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); } |
LocalNotification implements ISerializable, IDeserializable { public boolean repeatsRecurrently() { return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT || isExact) && repeatInterval != 0; } 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; } | @Test public void notification_repeatsRecurrently_returnsTrueIfHasRepeatInterval_afterKitKat() { Whitebox.setInternalState(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.KITKAT); getSubject().repeatInterval = 10; getSubject().isExact = false; assertTrue(getSubject().repeatsRecurrently()); }
@Test public void notification_repeatsRecurrently_returnsTrueIfHasRepeatIntervalAndIsExact() { Whitebox.setInternalState(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.KITKAT - 1); getSubject().repeatInterval = 10; getSubject().isExact = true; assertTrue(getSubject().repeatsRecurrently()); }
@Test public void notification_repeatsRecurrently_returnsFalseIfDoesNotHaveRepeatInterval() { Whitebox.setInternalState(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.KITKAT); getSubject().repeatInterval = 0; getSubject().isExact = true; assertFalse(getSubject().repeatsRecurrently()); }
@Test public void notification_repeatsRecurrently_returnsFalseIfNonExact_beforeKitKat() { Whitebox.setInternalState(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.KITKAT - 1); getSubject().repeatInterval = 10; getSubject().isExact = false; assertFalse(getSubject().repeatsRecurrently()); } |
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; } | @Test public void context_dispatchNotificationSelectedEvent_dispatchesEvent() { getSubject().dispatchNotificationSelectedEvent(); verify(getSubject()).dispatchStatusEventAsync("notificationSelected", "status"); } |
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIBED; } | @Test public void context_functions_getSelectedNotificationData() { byte[] data = {}; PowerMockito.mockStatic(LocalNotificationCache.class); PowerMockito.mockStatic(ExtensionUtils.class); when(LocalNotificationCache.getInstance()).thenReturn(cache); when(cache.getNotificationData()).thenReturn(data); when(ExtensionUtils.getFreObject(data)).thenReturn(freObject); assertSame(freObject, callFunction("getSelectedNotificationData")); }
@Test public void context_functions_getSelectedNotificationCode() { PowerMockito.mockStatic(LocalNotificationCache.class); PowerMockito.mockStatic(FREObject.class); when(LocalNotificationCache.getInstance()).thenReturn(cache); when(cache.getNotificationCode()).thenReturn("Code"); try { when(FREObject.newObject("Code")).thenReturn(freObject); } catch (Throwable e) { e.printStackTrace(); } assertSame(freObject, callFunction("getSelectedNotificationCode")); }
@Test public void context_functions_getSelectedActionId() { PowerMockito.mockStatic(LocalNotificationCache.class); PowerMockito.mockStatic(FREObject.class); when(LocalNotificationCache.getInstance()).thenReturn(cache); when(cache.getActionId()).thenReturn("ActionId"); try { when(FREObject.newObject("ActionId")).thenReturn(freObject); } catch (Throwable e) { e.printStackTrace(); } assertSame(freObject, callFunction("getSelectedNotificationAction")); }
@Test public void context_functions_getSelectedUserResponse() { PowerMockito.mockStatic(LocalNotificationCache.class); PowerMockito.mockStatic(FREObject.class); when(LocalNotificationCache.getInstance()).thenReturn(cache); when(cache.getUserResponse()).thenReturn("User Response"); try { when(FREObject.newObject("User Response")).thenReturn(freObject); } catch (Throwable e) { e.printStackTrace(); } assertSame(freObject, callFunction("getSelectedNotificationUserResponse")); }
@Test public void context_functions_checkForNotificationAction_whenCacheWasUpdated() { byte data[] = {}; LocalNotificationCache.getInstance().reset(); LocalNotificationCache.getInstance().setData("MyCode", data, "actionId", "User Response"); callFunction("checkForNotificationAction"); verify(getSubject()).dispatchStatusEventAsync("notificationSelected", "status"); }
@Test public void context_functions_checkForNotificationAction_whenCacheWasNotUpdated() { LocalNotificationCache.getInstance().reset(); callFunction("checkForNotificationAction"); verify(getSubject(), never()).dispatchStatusEventAsync("notificationSelected", "status"); }
@Test public void context_functions_checkForNotificationAction_dispatchesOnlyOnce() { byte data[] = {}; LocalNotificationCache.getInstance().reset(); LocalNotificationCache.getInstance().setData("MyCode", data, "actionId", "User Response"); callFunction("checkForNotificationAction"); callFunction("checkForNotificationAction"); verify(getSubject(), times(1)).dispatchStatusEventAsync("notificationSelected", "status"); } |
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; } | @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"); } |
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; } | @Test public void context_functions_cancelAll() { callFunction("cancelAll"); verify(manager).cancelAll(); verify(persistenceManager).clearNotifications(); } |
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; } | @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()); } |
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } LocalNotificationEventDispatcher(String code, byte[] data); LocalNotificationEventDispatcher(String code, byte[] data, String actionId, String userResponse); } | @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(); } |
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); final static int YEAR_CALENDAR_UNIT; final static int MONTH_CALENDAR_UNIT; final static int DAY_CALENDAR_UNIT; final static int HOUR_CALENDAR_UNIT; final static int MINUTE_CALENDAR_UNIT; final static int SECOND_CALENDAR_UNIT; final static int MILLISECOND_CALENDAR_UNIT; final static int WEEK_CALENDAR_UNIT; final static int QUARTER_CALENDAR_UNIT; } | @Test public void notificationTimeInterval_yearInterval_toMilliseconds() { assertEquals( (long)1000 * 60 * 60 * 24 * 365, getSubject(LocalNotificationTimeInterval.YEAR_CALENDAR_UNIT).toMilliseconds() ); }
@Test public void notificationTimeInterval_monthInterval_toMilliseconds() { assertEquals( (long)1000 * 60 * 60 * 24 * 30, getSubject(LocalNotificationTimeInterval.MONTH_CALENDAR_UNIT).toMilliseconds() ); }
@Test public void notificationTimeInterval_dayInterval_toMilliseconds() { assertEquals( 1000 * 60 * 60 * 24, getSubject(LocalNotificationTimeInterval.DAY_CALENDAR_UNIT).toMilliseconds() ); }
@Test public void notificationTimeInterval_hourInterval_toMilliseconds() { assertEquals( 1000 * 60 * 60, getSubject(LocalNotificationTimeInterval.HOUR_CALENDAR_UNIT).toMilliseconds() ); }
@Test public void notificationTimeInterval_minuteInterval_toMilliseconds() { assertEquals( 1000 * 60, getSubject(LocalNotificationTimeInterval.MINUTE_CALENDAR_UNIT).toMilliseconds() ); }
@Test public void notificationTimeInterval_secondInterval_toMilliseconds() { assertEquals( 1000, getSubject(LocalNotificationTimeInterval.SECOND_CALENDAR_UNIT).toMilliseconds() ); }
@Test public void notificationTimeInterval_weekInterval_toMilliseconds() { assertEquals( 1000 * 60 * 60 * 24 * 7, getSubject(LocalNotificationTimeInterval.WEEK_CALENDAR_UNIT).toMilliseconds() ); }
@Test public void notificationTimeInterval_quarterInterval_toMilliseconds() { assertEquals( (long)1000 * 60 * 60 * 24 * 91, getSubject(LocalNotificationTimeInterval.QUARTER_CALENDAR_UNIT).toMilliseconds() ); }
@Test public void notificationTimeInterval_unkownIntervalInterval_returnsZeroMilliseconds() { assertEquals(0, getSubject(1 << 20).toMilliseconds()); }
@Test public void notificationTimeInterval_toMillisecondsWithParameter_multipliesIntervalByParameter() { assertEquals( 4000, getSubject(LocalNotificationTimeInterval.SECOND_CALENDAR_UNIT).toMilliseconds(4) ); } |
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); } | @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"); } |
TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); } @SuppressWarnings("ConstantConditions") @Override void onReceive(Context context, Intent intent); } | @Test public void service_onReceive_startsService() { getSubject().onReceive(context, intent); verify(notificationIntent).setClass(context, LocalNotificationIntentService.class); verify(context).startService(notificationIntent); }
@Test public void service_onReceive_tonesDownNotificationService() { getSubject().onReceive(context, intent); verify(notificationIntent).putExtra(Constants.VIBRATE, false); verify(notificationIntent).putExtra(Constants.PLAY_SOUND, false); verify(notificationIntent).putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT); }
@Test public void service_onReceive_mergesIntentIntoNotificationIntent() { getSubject().onReceive(context, intent); verify(notificationIntent).putExtras(bundle); }
@Test public void service_onReceive_onLessThanNougat_doesNotMergeIntentIntoNotificationIntent() { Whitebox.setInternalState(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.N - 1); getSubject().onReceive(context, intent); verify(notificationIntent, never()).putExtra(eq(Constants.USER_RESPONSE_KEY), anyString()); }
@Test public void service_onReceive_noNougatOrHigher_mergesUserResponseIntoNotificationIntent() { Whitebox.setInternalState(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.N); Bundle resultsBundle = mock(Bundle.class); PowerMockito.mockStatic(RemoteInput.class); when(RemoteInput.getResultsFromIntent(intent)).thenReturn(resultsBundle); when(resultsBundle.getString(Constants.USER_RESPONSE_KEY)).thenReturn("User Response"); getSubject().onReceive(context, intent); verify(notificationIntent).putExtra(Constants.USER_RESPONSE_KEY, "User Response"); } |
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); } | @Test public void callbacks_setAppInForeground_whenActivityStarted() { ApplicationStatus.setInForeground(false); getSubject().onActivityStarted(null); assertTrue(ApplicationStatus.getInForeground()); } |
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); } | @Test public void callbacks_setAppInForeground_whenActivityStopped() { ApplicationStatus.setInForeground(true); getSubject().onActivityStopped(null); assertFalse(ApplicationStatus.getInForeground()); } |
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); } | @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); } |
LocalNotificationManager { void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCode(), intentFactory.createIntent(notification), PendingIntent.FLAG_CANCEL_CURRENT); long repeatInterval = notification.getRepeatIntervalMilliseconds(); if (repeatInterval != 0) { notifier.notifyRepeating(notificationTime, repeatInterval, pendingIntent, notification); } else { notifier.notify(notificationTime, pendingIntent, notification); } } LocalNotificationManager(Context context); } | @Test public void manager_notify_notifiesOnce_whenIntervalIsZero() { setupIntervalCalculator(); when(PendingIntent.getBroadcast(context, "MyCode".hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT)) .thenReturn(pendingIntent); when(calculator.getTime(any(Date.class))).thenReturn(100L); notification.repeatInterval = 0; getSubject().notify(notification); verify(notifier).notify(100L, pendingIntent, notification); }
@Test public void manager_notify_notifiesRepeating_whenIntervalIsNonZero() { setupIntervalCalculator(); when(PendingIntent.getBroadcast(context, "MyCode".hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT)) .thenReturn(pendingIntent); when(calculator.getTime(any(Date.class))).thenReturn(100L); notification.repeatInterval = LocalNotificationTimeInterval.MINUTE_CALENDAR_UNIT; getSubject().notify(notification); verify(notifier).notifyRepeating(100L, notification.getRepeatIntervalMilliseconds(), pendingIntent, notification); }
@Test public void manager_notify_calculatesNextTriggerTimeBasedOnCurrentDate() { when(PendingIntent.getBroadcast(context, "MyCode".hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT)) .thenReturn(pendingIntent); Date date = mock(Date.class); try { PowerMockito .whenNew(Date.class) .withNoArguments() .thenReturn(date); PowerMockito.whenNew(NextNotificationCalculator.class) .withArguments(notification) .thenReturn(calculator); } catch (Throwable e) { e.printStackTrace(); } LocalNotification notification = getNotification(); getSubject().notify(notification); verify(calculator).getTime(date); }
@Test public void manager_notify_setsUpIntent() { getSubject().notify(getNotification()); verify(intentFactory).createIntent(notification); } |
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); } | @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); } |
NotificationDispatcher { void dispatch() { dispatchNotification(); } NotificationDispatcher(Context context, Bundle bundle); } | @Test public void dispatcher_dispatch_whenAppIsInForeground_andNormalNotification_doesNotDisplayNotification() { getSubject().dispatch(); verify(notificationManager).notify("testCode", Constants.STANDARD_NOTIFICATION_ID, notification); } |
AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); } @Override void onReceive(Context context, Intent intent); } | @Test public void intentService_onReceiveWhenAppIsInForeground_andNormalNotification_doesNotDispatchNotification() { when(eventDispatcher.dispatchWhenInForeground()).thenReturn(true); getSubject().onReceive(context, intent); verify(notificationDispatcher, never()).dispatch(); }
@Test public void intentService_onReceiveWhenAppIsNotInForeground_andNormalNotification_dispatchesNotification() { when(eventDispatcher.dispatchWhenInForeground()).thenReturn(false); mockNotificationDispatch(); getSubject().onReceive(context, intent); verify(notificationDispatcher).dispatch(); }
@Test public void intentService_onReceiveWhenNotificationShowsInForeground_dispatchesNotification() { when(eventDispatcher.dispatchWhenInForeground()).thenReturn(true); when(bundle.getBoolean(Constants.SHOW_IN_FOREGROUND)).thenReturn(true); mockNotificationDispatch(); getSubject().onReceive(context, intent); verify(notificationDispatcher).dispatch(); verify(eventDispatcher, never()).dispatchWhenInForeground(); }
@Test public void intentService_onReceiveWhenNotification_doesNotTriggersNewNotification_whenIntervalNotSent() { mockNotificationDispatch(); try { PowerMockito.whenNew(LocalNotificationManager.class).withArguments(context) .thenReturn(notificationManager); } catch(Throwable e) { e.printStackTrace(); } getSubject().onReceive(context, intent); verify(notificationManager, never()).notify(any(LocalNotification.class)); }
@Test public void intentService_onReceiveWhenNotification_triggersNewNotification_whenIntervalSent() { when(bundle.getInt(Constants.REPEAT_INTERVAL, 0)).thenReturn(1); mockNotificationDispatch(); try { PowerMockito.whenNew(LocalNotificationManager.class).withArguments(context) .thenReturn(notificationManager); PowerMockito.whenNew(PersistenceManager.class).withArguments(context) .thenReturn(persistenceManager); } catch(Throwable e) { e.printStackTrace(); } LocalNotification notification = new LocalNotification(); when(persistenceManager.readNotification("KeyCode")).thenReturn(notification); getSubject().onReceive(context, intent); verify(notificationManager).notify(notification); } |
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; } | @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: } |
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; } | @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(); } } |
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); } | @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]) ); } } |
HelloBean { @Deprecated public String sayHello() { return "Hello world!"; } HelloBean(); @Override String toString(); @Deprecated String sayHello(); @SuppressWarnings("all") long getValue(); } | @Test public void testHello() { String ret = helloBean.sayHello(); Assertions.assertNotNull(ret); System.out.println(ret); } |
HelloBean { @Override public String toString() { return "HelloBean says hello world!"; } HelloBean(); @Override String toString(); @Deprecated String sayHello(); @SuppressWarnings("all") long getValue(); } | @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() )); } |
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); } | @Test public void testHello() { Object ret = helloController.hello("test", null, null); Assertions.assertTrue(ret.toString().contains("test")); System.out.println(ret); } |
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); } | @Test public void testServerUrl() { String ret = serverConfig.getServerUrl(); Assertions.assertTrue(ret.contains("http: System.out.println(ret); } |
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); } | @Test public void testSendQueue() { for (Object obj : msgArr) { mqService.sendQueue(obj); } } |
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); } | @Test public void testSendTopic() { for (Object obj : msgArr) { mqService.sendTopic(obj); } } |
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); } | @Test public void testApp() { App.main(null); } |
Inst3 { public static Inst3 getInst() { synchronized (Inst3.class) { if (inst == null) { inst = new Inst3(); } } return inst; } private Inst3(); static Inst3 getInst(); } | @Test public void testGetInst() { Inst3 inst = Inst3.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); } |
Inst2 { public static Inst2 getInst() { if (inst == null) { inst = new Inst2(); } return inst; } private Inst2(); static Inst2 getInst(); } | @Test public void testGetInst() { Inst2 inst = Inst2.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); } |
Inst4 { public static Inst4 getInst() { if (inst == null) { synchronized (Inst4.class) { if (inst == null) { inst = new Inst4(); } } } return inst; } private Inst4(); static Inst4 getInst(); } | @Test public void testGetInst() { Inst4 inst = Inst4.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); } |
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); } | @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)); } |
Inst5 { public static Inst5 getInst() { return Holder.inst; } private Inst5(); static Inst5 getInst(); } | @Test public void testGetInst() { Inst5 inst = Inst5.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); } |
Inst1 { public static Inst1 getInst() { return inst; } private Inst1(); static Inst1 getInst(); } | @Test public void testGetInst() { Inst1 inst = Inst1.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); } |
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); } | @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); } |
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); } | @Test public void testSendHttpGet() { String html = httpService.sendHttpGet("https: String ret = html.substring(100, 130); System.out.println(ret); Assertions.assertNotNull(ret); } |
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); } | @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); } |
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); } | @Test public void testTts() throws IOException { MockHttpServletResponse response = new MockHttpServletResponse(); Object ret = aiController.tts(response, "测试AiController"); System.out.println(ret); Assertions.assertEquals("ok", ret); } |
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); } | @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); } |
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(); } | @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)); } } |
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(); } | @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)); } } |
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); } | @Test public void testApp() { new App().main(null); } |
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); } | @Test public void testApp() { App.main(null); } |
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); } | @Test public void testPlayUrl() throws Exception { URL fileUrl = new URL("http: Player.asyncPlay(fileUrl); Thread.sleep(3000); } |
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); } | @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()); } |
SplitNumbers { public static boolean splitStr(String str, int index, List<BigInteger> numbers) { if (index >= str.length()) { return numbers.size() >= 2; } if (index < 0 || str.charAt(index) == '0') { return false; } BigInteger offset = new BigInteger("-1"); for (int i = index; i < str.length(); i++) { if (numbers.size() == 0 && i >= str.length() / 2) { break; } BigInteger tmp = new BigInteger(str.substring(index, i + 1)); if (numbers.size() == 0 || tmp.add(offset).equals(numbers.get(numbers.size() - 1))) { numbers.add(tmp); if (splitStr(str, i + 1, numbers)) { return true; } else { numbers.remove(numbers.size() - 1); } } else if (tmp.add(offset).compareTo(numbers.get(numbers.size() - 1)) >= 0) { break; } } return false; } static boolean splitStr(String str, int index, List<BigInteger> numbers); } | @Test public void testSplitNumbers() { Map<String, String> ioMap = new HashMap<String, String>() {{ put("101112", "YES 10"); put("1234", "YES 1"); put("91011", "YES 9"); put("99100", "YES 99"); put("101103", "NO"); put("010203", "NO"); put("13", "NO"); put("1", "NO"); put("11111111111111111111111111111111", "NO"); }}; List<BigInteger> numbers = new ArrayList<BigInteger>(); for (Map.Entry<String, String> io : ioMap.entrySet()) { String str = io.getKey(); numbers.clear(); String ret = SplitNumbers.splitStr(str, 0, numbers) ? ("YES " + String.valueOf(numbers.get(0))) : "NO"; if (!ret.equals(io.getValue())) { System.out.printf("%s %s", io.getValue(), ret); } Assert.assertEquals(io.getValue(), ret); } } |
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; } | @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); } } |
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); } | @Test public void testFrequency() { String input = "1226#24#"; int[] output = StringDecoder.frequency(input); Assert.assertEquals(1, output[0]); Assert.assertEquals(1, output[1]); } |
SortHotel { static int[] sort_hotels(String keywords, int[] hotel_ids, String[] reviews) { if (keywords == null || keywords.trim().length() <= 0 || hotel_ids == null || hotel_ids.length <= 0 || reviews == null || reviews.length <= 0 || hotel_ids.length != reviews.length) { return null; } final String[] keywordArr = keywords.trim().toLowerCase() .replace("-", "") .split(" "); if (keywordArr == null || keywordArr.length <= 0) { return null; } Set<String> keywordSet = new HashSet<String>(keywordArr.length){{ addAll(Arrays.asList(keywordArr)); }}; Map<Integer, Hotel> hotelMap = new HashMap<Integer, Hotel>(); for (int i = 0; i < hotel_ids.length; i++) { int id = hotel_ids[i]; Hotel hotel = hotelMap.get(id); if (hotel == null) { hotel = new Hotel(id); hotelMap.put(id, hotel); } String review = reviews[i]; if (review == null || review.trim().length() <= 0) { continue; } review = review.trim().toLowerCase() .replace(",", " ") .replace(".", " ") .replace("!", " ") .replace("-", ""); String[] reviewArr = review.split(" "); if (reviewArr == null || reviewArr.length <= 0) { continue; } for (String tmp : reviewArr) { if (tmp != null && tmp.trim().length() > 0 && keywordSet.contains(tmp.trim())) { hotel.reviewCount++; } } } Hotel[] hotelArr = new Hotel[hotelMap.size()]; hotelMap.values().toArray(hotelArr); Arrays.sort(hotelArr); int[] idArr = new int[hotelArr.length]; for (int i = 0; i < hotelArr.length; i++) { idArr[i] = hotelArr[i].id; } return idArr; } } | @Test public void testSortHotels() { int[] ret = SortHotel.sort_hotels( "breakfast beach citycenter location metro view staff price", new int[]{1, 2, 1, 1, 2}, new String[]{ "This hotel has a nice view of the citycenter. The location is perfect.", "The breakfast is ok. Regarding location, it is quite far from citycenter buth price is cheap so it is worth.", "Location is excellent, 5 minutes from citycenter. There is also a metro station very close to the hotel.", "They said I couldn't take my dog and there were other guests with dogs! That is not fair.", "Very friendly staff and good cost-benefit ratio. Its location is a bit far from citycenter." }); Assert.assertArrayEquals(new int[] {2, 1}, ret); } |
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); } | @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); } } |
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); } | @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)); } |
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); } | @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); } } |
Coupon { public static long findValidLogs(List<String> logs) { if (logs == null || logs.size() <= 0) { return -1; } long index = 0; long freeErrors = 0; HashMap<Long, String> map = new HashMap<Long, String>(); for (String log : logs) { index++; if (log == null || log.length() <= 0) { break; } String[] values = log.split(" "); if (values == null || values.length <= 0) { break; } if (values.length == 1) { if ("?".equals(values[0])) { freeErrors++; continue; } else { break; } } String value = values[0]; Long key = -1L; try { key = Long.valueOf(values[1]); } catch (Exception e) { e.printStackTrace(); break; } if (map.containsKey(key)) { if ("o".equalsIgnoreCase(value)) { map.remove(key); } else if (freeErrors-- <= 0) { break; } } else { if ("i".equalsIgnoreCase(value)) { map.put(key, value); } else if (freeErrors-- <= 0) { break; } } } if (index >= logs.size() && freeErrors >= 0) { index = -1; } return index; } static void main(String[] args); static long findValidLogs(List<String> logs); } | @Test public void testFindValidLogs() { Map<String[], Long> mapIO = new HashMap<String[], Long>() {{ put(new String[]{}, -1L); put(new String[]{"o 1"}, 1L); put(new String[]{"?", "o 1"}, -1L); put(new String[]{"I 1", "?", "O 1"}, -1L); put(new String[]{"i 2", "o 1"}, 2L); put(new String[]{"?", "O 1", "?", "O 2"}, -1L); }}; for (Map.Entry<String[], Long> io : mapIO.entrySet()) { List<String> ar = new ArrayList<String>(); for (String str : io.getKey()) { ar.add(str); } Assert.assertEquals( io.getValue().longValue(), Coupon.findValidLogs(ar) ); } } |
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); } | @Test public void testElectionWinner() { String ret = ElectionWinner.electionWinner(new String[] {"Alex", "Michael", "harry", "Dave", "Michael", "Victor", "Harry", "Alex", "Mary", "Mary"}); Assert.assertEquals("Michael", ret); } |
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); } | @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); } } |
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; } } | @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); } } |
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); } | @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); } } |
LeaderBoard { public static int[] getRanks(int[] scores, int[] alice) { Player[] players = new Player[scores.length]; for (int i = 0; i < scores.length; i++) { players[i] = new Player(scores[i], 0); } Arrays.sort(players); for (int i = 0; i < scores.length; i++) { if (i == 0) { players[i].setRank(1); } else if (players[i].getScore() == players[i - 1].getScore()) { players[i].setRank(players[i - 1].getRank()); } else if (players[i].getScore() < players[i - 1].getScore()) { players[i].setRank(players[i - 1].getRank() + 1); } } int[] ranks = new int[alice.length]; int j = players.length - 1; for (int i = 0; i < alice.length; i++) { int score = alice[i]; for (; j >= 0; j--) { if (score < players[j].getScore()) { ranks[i] = players[j].getRank() + 1; break; } else if (score == players[j].getScore()) { ranks[i] = players[j].getRank(); break; } } if (j < 0) { ranks[i] = 1; } } return ranks; } static int[] getRanks(int[] scores, int[] alice); static void main(String[] args); } | @Test public void testGetRanks() { Map<List<int[]>, int[]> ioMap = new HashMap<List<int[]>, int[]>() {{ put(new ArrayList() {{ add(new int[] {100, 100, 50, 40, 40, 20, 10}); add(new int[] {5, 25, 50, 120}); }}, new int[] {6, 4, 2, 1}); }}; for (Map.Entry<List<int[]>, int[]> io : ioMap.entrySet()) { int[] ranks = LeaderBoard.getRanks(io.getKey().get(0), io.getKey().get(1)); Assert.assertArrayEquals(ranks, io.getValue()); } } |
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); } | @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); } } |
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); } | @Test public void testMain() { Hello.main(null); } |
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); } | @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); } } |
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); } | @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); } } |
MaxMin { public static long[] maxMin(String[] operations, int[] values) { if (operations == null || values == null || operations.length > values.length) { return null; } long[] products = new long[operations.length]; int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; int[] arr = new int[operations.length]; int index = 0; for (int i = 0; i < operations.length; i++) { String op = operations[i]; int v = values[i]; if ("push".equalsIgnoreCase(op)) { arr[index++] = v; if (max < v) { max = v; } if (min > v) { min = v; } } else if ("pop".equalsIgnoreCase(op)) { for (int j = 0; j < index; j++) { if (arr[j] == v) { for (int k = j + 1; k < index; k++) { arr[k - 1] = arr[k]; } arr[index--] = 0; break; } } if (max == v || min == v) { max = Integer.MIN_VALUE; min = Integer.MAX_VALUE; for (int j = 0; j <= index; j++) { v = arr[j]; if (max < v) { max = v; } if (min > v) { min = v; } } } } products[i] = max * min; } return products; } static long[] maxMin(String[] operations, int[] values); } | @Test public void testMaxMin() { Map<Object[], long[]> pairIO = new HashMap<Object[], long[]>() {{ put(new Object[] {new String[]{"push", "push", "push", "pop"}, new int[]{1, 2, 3, 1}}, new long[]{1, 2, 3, 6}); put(new Object[] {new String[]{"push", "push"}, new int[] {3, 2}}, new long[]{9, 6}); }}; for (Map.Entry<Object[], long[]> io : pairIO.entrySet()) { long[] ret = MaxMin.maxMin((String[])io.getKey()[0], (int[])io.getKey()[1]); Assert.assertArrayEquals(io.getValue(), ret); } } |
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); } | @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]) ); } } |
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); } | @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); } } |
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); } | @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); } } |
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); } | @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); } } |
BestTrio { static int bestTrio(int friends_nodes, int[] friends_from, int[] friends_to) { if (friends_nodes < 0 || friends_from == null || friends_to == null || friends_from.length > friends_to.length) { return -1; } List<HashSet<Integer>> friends = new ArrayList<HashSet<Integer>>(friends_nodes); for (int i = 0; i < friends_nodes; i++) { friends.add(new HashSet<Integer>()); } for (int i = 0; i < friends_from.length; i++) { int from = friends_from[i] - 1; int to = friends_to[i] - 1; friends.get(from).add(to); friends.get(to).add(from); } int min = Integer.MAX_VALUE; for (int i = 0; i < friends.size(); i++) { final HashSet<Integer> edges = friends.get(i); for (int j : edges) { final HashSet<Integer> edgesB = friends.get(j); for (int k : edgesB) { final HashSet<Integer> edgesC = friends.get(k); if (edgesC.contains(i)) { List<HashSet> arr = new ArrayList<HashSet>() {{ add(edges); add(edgesB); add(edgesC); }}; int score = 0; for (HashSet<Integer> u : arr) { HashSet<Integer> trio = new HashSet<Integer>(u); trio.remove(i); trio.remove(j); trio.remove(k); score += trio.size(); } if (min > score) { min = score; } } } } } if (min == Integer.MAX_VALUE) { min = -1; } return min; } } | @Test public void testBestTrio() { Map<Object[], Integer> mapIO = new HashMap<Object[], Integer>() {{ put(new Object[]{5, new int[]{1, 1, 2, 2, 3, 4}, new int[]{2, 3, 3, 4, 4, 5}}, 2); put(new Object[]{7, new int[]{2, 3, 5, 1}, new int[]{1, 6, 1, 7}}, -1); }}; for (Map.Entry<Object[], Integer> io : mapIO.entrySet()) { int ret = BestTrio.bestTrio((Integer) io.getKey()[0], (int[]) io.getKey()[1], (int[]) io.getKey()[2]); Assert.assertEquals(io.getValue().intValue(), ret); } } |
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); } | @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); } |
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); } | @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); } } |
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); } | @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); } |
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); } | @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); } } |
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); } | @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); } } |
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(); } } | @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); } } |
WinOrLose2 { public static int calculateLoop(List<Long> ar) { int n = ar.size(); if (n <= 1 || (n & (n - 1)) != 0) { return 0; } Iterator<Long> iterator = ar.iterator(); long score = iterator.next(); long index = 0; long mark = 1; int loop = 0; while (iterator.hasNext()) { if (winOrLose(score, iterator.next()) == 1) { index++; if (index >= mark) { mark *= 2; loop++; } } else { break; } } if (loop <= 0 && ((double)score / ar.get(1) > 0)) { loop++; } return loop; } static void main(String[] args); static int calculateLoop(List<Long> ar); static int winOrLose(long first, long second); } | @Test public void testCalculateLoop() { Map<long[], Integer> mapIO = new HashMap<long[], Integer>() {{ put(new long[] {7, 1, 2, 3, 1, 3, 1, 2, 5, 6, 1, 6, 2, 5}, 0); put(new long[] {4, 1}, 1); put(new long[] {1000000, 1, 2, -1000000}, 2); put(new long[] {4, 1, 2, 3, 1, 3, 1, 2}, 3); put(new long[] {7, 1, 2, 3, 1, 3, 1, 2, 5, 6, 1, 6, 2, 5, 3, 6}, 4); put(new long[] {4, 1, 2, 3}, 2); put(new long[] {-5, -3, 1, 0, 2, -6, -4, -6}, 1); put(new long[] {-10, 6, -6, -2}, 0); }}; for (Map.Entry<long[], Integer> io : mapIO.entrySet()) { long[] ar = io.getKey(); ArrayList<Long> list = new ArrayList<Long>(ar.length); for (long item : ar) { list.add(item); } Assert.assertEquals( io.getValue().intValue(), WinOrLose2.calculateLoop(list) ); } } |
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); } | @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); } } |
PickNumbers { public static int pickNumbers(int[] ar) { if (ar == null || ar.length <= 0) { return 0; } Arrays.sort(ar); int n = ar.length; int max = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { int count = 0; int diff = 0; for (int j = i - 1; j >= 0; j--) { int tmp = Math.abs(ar[i] - ar[j]); if (tmp <= 1) { count++; if (diff < tmp) { diff = tmp; } } else { break; } } for (int j = i + 1; j < n; j++) { int tmp = Math.abs(ar[i] - ar[j]); if (diff + tmp <= 1) { count++; } else { break; } } if (max < count) { max = count; } } return max + 1; } static int pickNumbers(int[] ar); } | @Test public void testPickNumbers() { Map<int[], Integer> mapIO = new HashMap<int[], Integer>() {{ put(null, 0); put(new int[]{4, 6, 5, 3, 3, 1}, 3); put(new int[]{1, 2, 2, 3, 1, 2}, 5); put(new int[]{ 4, 2, 3, 4, 4, 9, 98, 98, 3, 3, 3, 4, 2, 98, 1, 98, 98, 1, 1, 4, 98, 2, 98, 3, 9, 9, 3, 1, 4, 1, 98, 9, 9, 2, 9, 4, 2, 2, 9, 98, 4, 98, 1, 3, 4, 9, 1, 98, 98, 4, 2, 3, 98, 98, 1, 99, 9, 98, 98, 3, 98, 98, 4, 98, 2, 98, 4, 2, 1, 1, 9, 2, 4}, 22); }}; for (Map.Entry<int[], Integer> io : mapIO.entrySet()) { int ret = PickNumbers.pickNumbers(io.getKey()); Assert.assertEquals(io.getValue().intValue(), ret); } } |
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; } } | @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); } } |
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); } | @Test public void testGetInstrumentedObject() { AopInstrumenter instrumenter = new AopInstrumenter(); AopService service = (AopService) instrumenter.getInstrumentedClass(AopServiceImpl.class); service.findInfo("Instrumenter from test"); } |
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); } | @Test public void testApp() { App.main(null); } |
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); } | @Test public void testGetAopProxyedObject() { AopService service = (AopService) AopFactory.getAopProxyedObject(AopServiceImpl.class.getName()); service.findInfo("Jonn from test"); } |
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); } | @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); } |
HookMetadataParser { SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); } HookMetadataParser(Collection<Path> hookJars); SortedSet<HookMetadata> parse(Predicate<String> classNameFilter); } | @Test void testServletHook() throws ClassNotFoundException, IOException { String expected = ServletTestHook.class.getName() + " instruments [javax.servlet.Filter, javax.servlet.Servlet]:\n" + " * doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse)\n" + " * service(javax.servlet.ServletRequest, javax.servlet.ServletResponse)"; SortedSet<HookMetadata> result = parser.parse(className -> className.equals(ServletTestHook.class.getName())); Assertions.assertEquals(1, result.size()); Assertions.assertEquals(expected, result.first().toString()); }
@Test void testPrimitiveTypes() throws ClassNotFoundException, IOException { String expected = PrimitiveTypesTestHook.class.getName() + " instruments [com.example.Some]:\n" + " * arrayArgs(java.lang.Object[], int[], java.lang.String[])\n" + " * boxedArgs(java.lang.Boolean, java.lang.Character, java.lang.Byte, java.lang.Short, java.lang.Integer, java.lang.Float, java.lang.Long, java.lang.Double)\n" + " * noArgs()\n" + " * primitiveArgs(boolean, char, byte, short, int, float, long, double)"; SortedSet<HookMetadata> result = parser.parse(className -> className.equals(PrimitiveTypesTestHook.class.getName())); Assertions.assertEquals(1, result.size()); Assertions.assertEquals(expected, result.first().toString()); }
@Test void testReturnedAndThrown() throws IOException, ClassNotFoundException { String expected = ReturnedAndThrownTestHook.class.getName() + " instruments [com.example.ReturnThrown]:\n" + " * div(int, int)"; SortedSet<HookMetadata> result = parser.parse(className -> className.equals(ReturnedAndThrownTestHook.class.getName())); Assertions.assertEquals(1, result.size()); Assertions.assertEquals(expected, result.first().toString()); }
@Test void testNoHook() throws ClassNotFoundException, IOException { SortedSet<HookMetadata> result = parser.parse(className -> className.equals(HookMetadataParserTest.class.getName())); Assertions.assertTrue(result.isEmpty()); } |
JarFiles { static Path findAgentJarFromCmdline(List<String> cmdlineArgs) { Pattern p = Pattern.compile("^-javaagent:(.*promagent([^/]*).jar)(=.*)?$"); for (String arg : cmdlineArgs) { Matcher m = p.matcher(arg); if (m.matches()) { return Paths.get(m.group(1)); } } throw new RuntimeException("Failed to locate promagent.jar file."); } private JarFiles(List<Path> perDeploymentJars, List<Path> sharedJars); } | @Test void testCmdlineParserWildfly() { String[] cmdlineArgs = new String[]{ "-D[Standalone]", "-Xbootclasspath/p:/tmp/wildfly-10.1.0.Final/modules/system/layers/base/org/jboss/logmanager/main/jboss-logmanager-2.0.4.Final.jar", "-Djboss.modules.system.pkgs=org.jboss.logmanager,io.promagent.agent", "-Djava.util.logging.manager=org.jboss.logmanager.LogManager", "-javaagent:../promagent/promagent-dist/target/promagent.jar=port=9300", "-Dorg.jboss.boot.log.file=/tmp/wildfly-10.1.0.Final/standalone/log/server.log", "-Dlogging.configuration=file:/tmp/wildfly-10.1.0.Final/standalone/configuration/logging.properties" }; assertEquals("../promagent/promagent-dist/target/promagent.jar", findAgentJarFromCmdline(asList(cmdlineArgs)).toString()); }
@Test void testCmdlineParserVersioned() { String[] cmdlineArgs = new String[] { "-javaagent:promagent-1.0-SNAPSHOT.jar" }; assertEquals("promagent-1.0-SNAPSHOT.jar", findAgentJarFromCmdline(asList(cmdlineArgs)).toString()); }
@Test() void testCmdlineParserFailed() { String[] cmdlineArgs = new String[] { "-javaagent:/some/other/agent.jar", "-jar", "promagent.jar" }; Exception e = assertThrows(Exception.class, () -> findAgentJarFromCmdline(asList(cmdlineArgs))); assertTrue(e.getMessage().contains("promagent.jar")); } |
SyncMetadataService extends BaseService implements IMetadataService { @Override public SalientAttributes getAttributes() throws RemotePeerException, IOException { SalientAttributes originAttributes = new SalientAttributes(); originAttributes.setApplication(context.getApplication()); originAttributes.setVersion(context.getVersion()); originAttributes.setPeerId(context.getHost().getPeerID()); Block lastBlock = blockchain.getLastBlock(); originAttributes.setNetworkID(fork.getGenesisBlockID().toString()); originAttributes.setFork(fork.getNumber(lastBlock.getTimestamp())); originAttributes.setHistoryFromHeight(storage.metadata().getHistoryFromHeight()); if (context.getHost().getAddress() != null && context.getHost().getAddress().length() > 0) { originAttributes.setAnnouncedAddress(context.getHost().getAddress()); } return originAttributes; } SyncMetadataService(IFork fork, ExecutionContext context, IBlockchainProvider blockchain, Storage storage); @Override SalientAttributes getAttributes(); @Override String[] getWellKnownNodes(); @Override boolean addPeer(long peerID, String address); } | @Test public void getAttributes() throws Exception { long peerId = 100500L; String hostAddress = "testAddress.com"; String app = "testApp"; String version = "testVersion"; ExecutionContext ctx = mock(ExecutionContext.class); ExecutionContext.Host host = mock(ExecutionContext.Host.class); fork = mock(IFork.class); when(fork.isPassed(anyInt())).thenReturn(false); when(fork.getGenesisBlockID()).thenReturn(new BlockID(12345L)); when(ctx.getHost()).thenReturn(host); when(host.getPeerID()).thenReturn(peerId); when(host.getAddress()).thenReturn(hostAddress); when(ctx.getApplication()).thenReturn(app); when(ctx.getVersion()).thenReturn(version); Block block = mock(Block.class); blockchain = mock(IBlockchainProvider.class); when(blockchain.getLastBlock()).thenReturn(block); storage = mock(Storage.class); when(storage.metadata()).thenReturn(mock(Storage.Metadata.class)); SyncMetadataService sms = new SyncMetadataService(fork, ctx, blockchain, storage); SalientAttributes attrs = sms.getAttributes(); assertEquals(peerId, attrs.getPeerId()); assertEquals(hostAddress, attrs.getAnnouncedAddress()); assertEquals(app, attrs.getApplication()); assertEquals(version, attrs.getVersion()); when(host.getAddress()).thenReturn(null); attrs = sms.getAttributes(); assertEquals(peerId, attrs.getPeerId()); assertEquals(null, attrs.getAnnouncedAddress()); assertEquals(app, attrs.getApplication()); assertEquals(version, attrs.getVersion()); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.