method2testcases
stringlengths 118
3.08k
|
---|
### Question:
SourceCodeVerification extends StripeJsonModel { @NonNull @Override public Map<String, Object> toMap() { Map<String, Object> hashMap = new HashMap<>(); hashMap.put(FIELD_ATTEMPTS_REMAINING, mAttemptsRemaining); if (mStatus != null) { hashMap.put(FIELD_STATUS, mStatus); } return hashMap; } SourceCodeVerification(int attemptsRemaining, @Status String status); int getAttemptsRemaining(); @Status String getStatus(); @NonNull @Override Map<String, Object> toMap(); @NonNull @Override JSONObject toJson(); @Nullable static SourceCodeVerification fromString(@Nullable String jsonString); @Nullable static SourceCodeVerification fromJson(@Nullable JSONObject jsonObject); }### Answer:
@Test public void fromJsonString_toMap_createsExpectedMap() { assertMapEquals(EXAMPLE_MAP_CODE_VERIFICATION, mCodeVerification.toMap()); } |
### Question:
SourceReceiver extends StripeJsonModel { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); StripeJsonUtils.putStringIfNotNull(jsonObject, FIELD_ADDRESS, mAddress); try { jsonObject.put(FIELD_AMOUNT_CHARGED, mAmountCharged); jsonObject.put(FIELD_AMOUNT_RECEIVED, mAmountReceived); jsonObject.put(FIELD_AMOUNT_RETURNED, mAmountReturned); } catch (JSONException jsonException) { return jsonObject; } return jsonObject; } SourceReceiver(String address,
long amountCharged,
long amountReceived,
long amountReturned); String getAddress(); void setAddress(String address); long getAmountCharged(); void setAmountCharged(long amountCharged); long getAmountReceived(); void setAmountReceived(long amountReceived); long getAmountReturned(); void setAmountReturned(long amountReturned); @NonNull @Override Map<String, Object> toMap(); @NonNull @Override JSONObject toJson(); @Nullable static SourceReceiver fromString(@Nullable String jsonString); @Nullable static SourceReceiver fromJson(@Nullable JSONObject jsonObject); }### Answer:
@Test public void fromJsonString_backToJson_createsIdenticalElement() { try { JSONObject rawConversion = new JSONObject(EXAMPLE_JSON_RECEIVER); assertJsonEquals(rawConversion, mSourceReceiver.toJson()); } catch (JSONException jsonException) { fail("Test Data failure: " + jsonException.getLocalizedMessage()); } } |
### Question:
SourceReceiver extends StripeJsonModel { @NonNull @Override public Map<String, Object> toMap() { Map<String, Object> hashMap = new HashMap<>(); if (!StripeTextUtils.isBlank(mAddress)) { hashMap.put(FIELD_ADDRESS, mAddress); } hashMap.put(FIELD_ADDRESS, mAddress); hashMap.put(FIELD_AMOUNT_CHARGED, mAmountCharged); hashMap.put(FIELD_AMOUNT_RECEIVED, mAmountReceived); hashMap.put(FIELD_AMOUNT_RETURNED, mAmountReturned); return hashMap; } SourceReceiver(String address,
long amountCharged,
long amountReceived,
long amountReturned); String getAddress(); void setAddress(String address); long getAmountCharged(); void setAmountCharged(long amountCharged); long getAmountReceived(); void setAmountReceived(long amountReceived); long getAmountReturned(); void setAmountReturned(long amountReturned); @NonNull @Override Map<String, Object> toMap(); @NonNull @Override JSONObject toJson(); @Nullable static SourceReceiver fromString(@Nullable String jsonString); @Nullable static SourceReceiver fromJson(@Nullable JSONObject jsonObject); }### Answer:
@Test public void fromJsonString_toMap_createsExpectedMap() { assertMapEquals(EXAMPLE_MAP_RECEIVER, mSourceReceiver.toMap()); } |
### Question:
StripeJsonUtils { @Nullable static String getString( @NonNull JSONObject jsonObject, @NonNull @Size(min = 1) String fieldName) throws JSONException { return nullIfNullOrEmpty(jsonObject.getString(fieldName)); } }### Answer:
@Test public void getString_whenFieldContainsRawNull_returnsNull() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("key", "null"); assertNull(StripeJsonUtils.getString(jsonObject, "key")); } catch (JSONException jex) { fail("No exception expected"); } }
@Test(expected = JSONException.class) public void getString_whenFieldNotPresent_throwsJsonException() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("key", "value"); StripeJsonUtils.getString(jsonObject, "differentKey"); fail("Expected an exception."); }
@Test public void getString_whenFieldPresent_findsAndReturnsField() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("key", "value"); assertEquals("value", StripeJsonUtils.getString(jsonObject, "key")); } catch (JSONException jex) { fail("No exception expected"); } } |
### Question:
LoggingUtils { @NonNull static String getEventParamName(@NonNull @LoggingEventName String eventName) { return ANALYTICS_NAME + '.' + eventName; } }### Answer:
@Test public void getEventParamName_withTokenCreation_createsExpectedParameter() { final String expectedEventParam = "stripe_android.token_creation"; assertEquals(expectedEventParam, LoggingUtils.getEventParamName(LoggingUtils.EVENT_TOKEN_CREATION)); } |
### Question:
LoggingUtils { @NonNull static String getAnalyticsUa() { return ANALYTICS_PREFIX + "." + ANALYTICS_NAME + "-" + ANALYTICS_VERSION; } }### Answer:
@Test public void getAnalyticsUa_returnsExpectedValue() { final String androidAnalyticsUserAgent = "analytics.stripe_android-1.0"; assertEquals(androidAnalyticsUserAgent, LoggingUtils.getAnalyticsUa()); } |
### Question:
StripeJsonUtils { @Nullable static String optString( @NonNull JSONObject jsonObject, @NonNull @Size(min = 1) String fieldName) { return nullIfNullOrEmpty(jsonObject.optString(fieldName)); } }### Answer:
@Test public void optString_whenFieldPresent_findsAndReturnsField() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("key", "value"); assertEquals("value", StripeJsonUtils.optString(jsonObject, "key")); } catch (JSONException jex) { fail("No exception expected"); } }
@Test public void optString_whenFieldContainsRawNull_returnsNull() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("key", "null"); assertNull(StripeJsonUtils.optString(jsonObject, "key")); } catch (JSONException jex) { fail("No exception expected"); } }
@Test public void optString_whenFieldNotPresent_returnsNull() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("key", "value"); Object ob = StripeJsonUtils.optString(jsonObject, "nokeyshere"); assertNull(ob); } catch (JSONException jex) { fail("No exception expected"); } } |
### Question:
MaskedCardView extends LinearLayout { @VisibleForTesting int[] getTextColorValues() { int[] colorValues = new int[4]; colorValues[0] = mSelectedColorInt; colorValues[1] = mSelectedAlphaColorInt; colorValues[2] = mUnselectedTextColorInt; colorValues[3] = mUnselectedTextAlphaColorInt; return colorValues; } MaskedCardView(Context context); MaskedCardView(Context context, AttributeSet attrs); MaskedCardView(Context context, AttributeSet attrs, int defStyle); @Override boolean isSelected(); @Override void setSelected(boolean selected); }### Answer:
@Test public void init_setsColorValuesWithAlpha() { final int alpha = 204; int[] colorValues = mMaskedCardView.getTextColorValues(); assertEquals(4, colorValues.length); assertEquals(colorValues[1], ColorUtils.setAlphaComponent(colorValues[0], alpha)); assertEquals(colorValues[3], ColorUtils.setAlphaComponent(colorValues[2], alpha)); } |
### Question:
SelectShippingMethodWidget extends FrameLayout { public ShippingMethod getSelectedShippingMethod() { return mShippingMethodAdapter.getSelectedShippingMethod(); } SelectShippingMethodWidget(Context context); SelectShippingMethodWidget(Context context, AttributeSet attrs); SelectShippingMethodWidget(Context context, AttributeSet attrs, int defStyleAttr); ShippingMethod getSelectedShippingMethod(); void setShippingMethods(List<ShippingMethod> shippingMethods, ShippingMethod defaultShippingMethod); }### Answer:
@Test public void selectShippingMethodWidget_whenSelected_selectionChanges() { assertEquals(mShippingMethodAdapter.getSelectedShippingMethod(), mShippingMethods.get(0)); mShippingMethodAdapter.setSelectedIndex(1); assertEquals(mShippingMethodAdapter.getSelectedShippingMethod(), mShippingMethods.get(1)); } |
### Question:
ExpiryDateEditText extends StripeEditText { public boolean isDateValid() { return mIsDateValid; } ExpiryDateEditText(Context context); ExpiryDateEditText(Context context, AttributeSet attrs); ExpiryDateEditText(Context context, AttributeSet attrs, int defStyleAttr); boolean isDateValid(); @Nullable @Size(2) int[] getValidDateFields(); void setExpiryDateEditListener(ExpiryDateEditListener expiryDateEditListener); }### Answer:
@Test public void afterAddingFinalDigit_whenGoingFromInvalidToValid_callsListener() { if (Calendar.getInstance().get(Calendar.YEAR) > 2059) { fail("Update the code with a date that is still valid. Also, hello from the past."); } mExpiryDateEditText.append("1"); mExpiryDateEditText.append("2"); mExpiryDateEditText.append("5"); verifyZeroInteractions(mExpiryDateEditListener); mExpiryDateEditText.append("9"); assertTrue(mExpiryDateEditText.isDateValid()); verify(mExpiryDateEditListener, times(1)).onExpiryDateComplete(); }
@Test public void afterAddingFinalDigit_whenDeletingItem_revertsToInvalidState() { if (Calendar.getInstance().get(Calendar.YEAR) > 2059) { fail("Update the code with a date that is still valid. Also, hello from the past."); } mExpiryDateEditText.append("12"); mExpiryDateEditText.append("59"); assertTrue(mExpiryDateEditText.isDateValid()); ViewTestUtils.sendDeleteKeyEvent(mExpiryDateEditText); verify(mExpiryDateEditListener, times(1)).onExpiryDateComplete(); assertFalse(mExpiryDateEditText.isDateValid()); } |
### Question:
ExpiryDateEditText extends StripeEditText { @VisibleForTesting int updateSelectionIndex( int newLength, int editActionStart, int editActionAddition) { int newPosition, gapsJumped = 0; boolean skipBack = false; if (editActionStart <= 2 && editActionStart + editActionAddition >= 2) { gapsJumped = 1; } if (editActionAddition == 0 && editActionStart == 3) { skipBack = true; } newPosition = editActionStart + editActionAddition + gapsJumped; if (skipBack && newPosition > 0) { newPosition--; } return newPosition <= newLength ? newPosition : newLength; } ExpiryDateEditText(Context context); ExpiryDateEditText(Context context, AttributeSet attrs); ExpiryDateEditText(Context context, AttributeSet attrs, int defStyleAttr); boolean isDateValid(); @Nullable @Size(2) int[] getValidDateFields(); void setExpiryDateEditListener(ExpiryDateEditListener expiryDateEditListener); }### Answer:
@Test public void updateSelectionIndex_whenMovingAcrossTheGap_movesToEnd() { assertEquals(3, mExpiryDateEditText.updateSelectionIndex(3, 1, 1)); }
@Test public void updateSelectionIndex_atStart_onlyMovesForwardByOne() { assertEquals(1, mExpiryDateEditText.updateSelectionIndex(1, 0, 1)); }
@Test public void updateSelectionIndex_whenDeletingAcrossTheGap_staysAtEnd() { assertEquals(2, mExpiryDateEditText.updateSelectionIndex(2, 4, 0)); } |
### Question:
StripeJsonUtils { @Nullable @SuppressWarnings("unchecked") static JSONArray listToJsonArray(@Nullable List values) { if (values == null) { return null; } JSONArray jsonArray = new JSONArray(); for (Object object : values) { if (object instanceof Map<?, ?>) { try { Map<String, Object> mapObject = (Map<String, Object>) object; jsonArray.put(mapToJsonObject(mapObject)); } catch (ClassCastException classCastException) { } } else if (object instanceof List<?>) { jsonArray.put(listToJsonArray((List) object)); } else if (object instanceof Number || object instanceof Boolean) { jsonArray.put(object); } else { jsonArray.put(object.toString()); } } return jsonArray; } }### Answer:
@Test public void listToJsonArray_forNull_returnsNull() { assertNull(StripeJsonUtils.listToJsonArray(null)); }
@Test public void listToJsonArray_forSimpleList_returnsExpectedArray() { List<Object> testList = new ArrayList<>(); testList.add(1); testList.add(2); testList.add(3); testList.add("a"); testList.add(true); testList.add("cde"); try { JSONArray expectedJsonArray = new JSONArray(SIMPLE_JSON_TEST_ARRAY); JSONArray testJsonArray = StripeJsonUtils.listToJsonArray(testList); JsonTestUtils.assertJsonArrayEquals(expectedJsonArray, testJsonArray); } catch (JSONException jsonException) { fail("Test data failure " + jsonException.getLocalizedMessage()); } } |
### Question:
StripeJsonUtils { @Nullable static List<Object> jsonArrayToList(@Nullable JSONArray jsonArray) { if (jsonArray == null) { return null; } List<Object> objectList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { try { Object ob = jsonArray.get(i); if (ob instanceof JSONArray) { objectList.add(jsonArrayToList((JSONArray) ob)); } else if (ob instanceof JSONObject) { Map<String, Object> objectMap = jsonObjectToMap((JSONObject) ob); if (objectMap != null) { objectList.add(objectMap); } } else { if (NULL.equals(ob)) { continue; } objectList.add(ob); } } catch (JSONException ignored) { } } return objectList; } }### Answer:
@Test public void jsonArrayToList_forNull_returnsNull() { assertNull(StripeJsonUtils.jsonArrayToList(null)); }
@Test public void jsonArrayToList_forSimpleList_returnsExpectedList() { List<Object> expectedList = new ArrayList<>(); expectedList.add(1); expectedList.add(2); expectedList.add(3); expectedList.add("a"); expectedList.add(true); expectedList.add("cde"); try { JSONArray testJsonArray = new JSONArray(SIMPLE_JSON_TEST_ARRAY); List<Object> convertedJsonArray = StripeJsonUtils.jsonArrayToList(testJsonArray); JsonTestUtils.assertListEquals(expectedList, convertedJsonArray); } catch (JSONException jsonException) { fail("Test data failure " + jsonException.getLocalizedMessage()); } } |
### Question:
StripeEditText extends TextInputEditText { @ColorInt @SuppressWarnings("deprecation") public int getDefaultErrorColorInt() { @ColorInt int errorColor; determineDefaultErrorColor(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { errorColor = getResources().getColor(mDefaultErrorColorResId, null); } else { errorColor = getResources().getColor(mDefaultErrorColorResId); } return errorColor; } StripeEditText(Context context); StripeEditText(Context context, AttributeSet attrs); StripeEditText(Context context, AttributeSet attrs, int defStyleAttr); @Nullable ColorStateList getCachedColorStateList(); boolean getShouldShowError(); @ColorInt @SuppressWarnings("deprecation") int getDefaultErrorColorInt(); @Override InputConnection onCreateInputConnection(EditorInfo outAttrs); void setErrorColor(@ColorInt int errorColor); void setHintDelayed(@StringRes final int hintResource, long delayMilliseconds); @SuppressWarnings("deprecation") void setShouldShowError(boolean shouldShowError); }### Answer:
@Test @SuppressWarnings("deprecation") public void getDefaultErrorColorInt_onDarkTheme_returnsDarkError() { mEditText.setTextColor( mActivityController.get().getResources() .getColor(android.R.color.primary_text_dark)); @ColorInt int colorInt = mEditText.getDefaultErrorColorInt(); @ColorInt int expectedErrorInt = mActivityController.get().getResources().getColor(R.color.error_text_dark_theme); assertEquals(expectedErrorInt, colorInt); }
@Test @SuppressWarnings("deprecation") public void getDefaultErrorColorInt_onLightTheme_returnsLightError() { mEditText.setTextColor( mActivityController.get().getResources() .getColor(android.R.color.primary_text_light)); @ColorInt int colorInt = mEditText.getDefaultErrorColorInt(); @ColorInt int expectedErrorInt = mActivityController.get().getResources().getColor(R.color.error_text_light_theme); assertEquals(expectedErrorInt, colorInt); } |
### Question:
CardMultilineWidget extends LinearLayout { static boolean isPostalCodeMaximalLength(boolean isZip, @Nullable String text) { return isZip && text != null && text.length() == 5; } CardMultilineWidget(Context context); CardMultilineWidget(Context context, AttributeSet attrs); CardMultilineWidget(Context context, AttributeSet attrs, int defStyleAttr); @VisibleForTesting CardMultilineWidget(Context context, boolean shouldShowPostalCode); void clear(); void setCardInputListener(@Nullable CardInputListener cardInputListener); @Nullable Card getCard(); boolean validateAllFields(); @Override void onWindowFocusChanged(boolean hasWindowFocus); void setShouldShowPostalCode(boolean shouldShowPostalCode); @Override boolean isEnabled(); @Override void setEnabled(boolean enabled); }### Answer:
@Test public void isPostalCodeMaximalLength_whenZipEnteredAndIsMaximalLength_returnsTrue() { assertTrue(CardMultilineWidget.isPostalCodeMaximalLength(true, "12345")); }
@Test public void isPostalCodeMaximalLength_whenZipEnteredAndIsNotMaximalLength_returnsFalse() { assertFalse(CardMultilineWidget.isPostalCodeMaximalLength(true, "123")); }
@Test public void isPostalCodeMaximalLength_whenZipEnteredAndIsEmpty_returnsFalse() { assertFalse(CardMultilineWidget.isPostalCodeMaximalLength(true, "")); }
@Test public void isPostalCodeMaximalLength_whenZipEnteredAndIsNull_returnsFalse() { assertFalse(CardMultilineWidget.isPostalCodeMaximalLength(true, null)); }
@Test public void isPostalCodeMaximalLength_whenNotZip_returnsFalse() { assertFalse(CardMultilineWidget.isPostalCodeMaximalLength(false, "12345")); } |
### Question:
CardMultilineWidget extends LinearLayout { public void clear() { mCardNumberEditText.setText(""); mExpiryDateEditText.setText(""); mCvcEditText.setText(""); mPostalCodeEditText.setText(""); mCardNumberEditText.setShouldShowError(false); mExpiryDateEditText.setShouldShowError(false); mCvcEditText.setShouldShowError(false); mPostalCodeEditText.setShouldShowError(false); updateBrand(Card.UNKNOWN); } CardMultilineWidget(Context context); CardMultilineWidget(Context context, AttributeSet attrs); CardMultilineWidget(Context context, AttributeSet attrs, int defStyleAttr); @VisibleForTesting CardMultilineWidget(Context context, boolean shouldShowPostalCode); void clear(); void setCardInputListener(@Nullable CardInputListener cardInputListener); @Nullable Card getCard(); boolean validateAllFields(); @Override void onWindowFocusChanged(boolean hasWindowFocus); void setShouldShowPostalCode(boolean shouldShowPostalCode); @Override boolean isEnabled(); @Override void setEnabled(boolean enabled); }### Answer:
@Test public void clear_whenZipRequiredAndAllFieldsEntered_clearsAllfields() { assertTrue(Calendar.getInstance().get(Calendar.YEAR) < 2050); mFullGroup.cardNumberEditText.setText(VALID_VISA_WITH_SPACES); mFullGroup.expiryDateEditText.append("12"); mFullGroup.expiryDateEditText.append("50"); mFullGroup.cvcEditText.append("123"); mFullGroup.postalCodeEditText.append("12345"); mCardMultilineWidget.clear(); assertEquals("", mFullGroup.cardNumberEditText.getText().toString()); assertEquals("", mFullGroup.expiryDateEditText.getText().toString()); assertEquals("", mFullGroup.cvcEditText.getText().toString()); assertEquals("", mFullGroup.postalCodeEditText.getText().toString()); } |
### Question:
DateUtils { static String createDateStringFromIntegerInput( @IntRange(from = 1, to = 12) int month, @IntRange(from = 0, to = 9999) int year) { String monthString = String.valueOf(month); if (monthString.length() == 1) { monthString = "0" + monthString; } String yearString = String.valueOf(year); if (yearString.length() == 3) { return ""; } if (yearString.length() > 2) { yearString = yearString.substring(yearString.length() - 2); } else if (yearString.length() == 1) { yearString = "0" + yearString; } return monthString + yearString; } }### Answer:
@Test public void createDateStringFromIntegerInput_whenDateHasOneDigitMonthAndYear_addsZero() { assertEquals("0102", DateUtils.createDateStringFromIntegerInput(1, 2)); }
@Test public void createDateStringFromIntegerInput_whenDateHasTwoDigitValues_returnsExpectedValue() { assertEquals("1132", DateUtils.createDateStringFromIntegerInput(11, 32)); }
@Test public void createDateStringFromIntegerInput_whenDateHasFullYear_truncatesYear() { assertEquals("0132", DateUtils.createDateStringFromIntegerInput(1, 2032)); }
@Test public void createDateStringFromIntegerInput_whenDateHasThreeDigitYear_returnsEmpty() { assertEquals("", DateUtils.createDateStringFromIntegerInput(12, 101)); } |
### Question:
DateUtils { @Size(2) @NonNull static String[] separateDateStringParts(@NonNull @Size(max = 4) String expiryInput) { String[] parts = new String[2]; if (expiryInput.length() >= 2) { parts[0] = expiryInput.substring(0, 2); parts[1] = expiryInput.substring(2); } else { parts[0] = expiryInput; parts[1] = ""; } return parts; } }### Answer:
@Test public void separateDateStringParts_withValidDate_properlySeparatesString() { String[] parts = DateUtils.separateDateStringParts("1234"); String[] expected = {"12", "34"}; assertArrayEquals(expected, parts); }
@Test public void separateDateStringParts_withPartialDate_properlySeparatesString() { String[] parts = DateUtils.separateDateStringParts("123"); String[] expected = {"12", "3"}; assertArrayEquals(expected, parts); }
@Test public void separateDateStringParts_withLessThanHalfOfDate_properlySeparatesString() { String[] parts = DateUtils.separateDateStringParts("1"); String[] expected = {"1", ""}; assertArrayEquals(expected, parts); }
@Test public void separateDateStringParts_withEmptyInput_returnsNonNullEmptyOutput() { String[] parts = DateUtils.separateDateStringParts(""); String[] expected = {"", ""}; assertArrayEquals(expected, parts); } |
### Question:
DateUtils { static boolean isValidMonth(@Nullable String monthString) { if (monthString == null) { return false; } try { int monthInt = Integer.parseInt(monthString); return monthInt > 0 && monthInt <= 12; } catch (NumberFormatException numEx) { return false; } } }### Answer:
@Test public void isValidMonth_forProperMonths_returnsTrue() { String[] validMonths = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"}; for (int i = 0; i < validMonths.length; i++) { assertTrue(DateUtils.isValidMonth(validMonths[i])); } }
@Test public void isValidMonth_forInvalidNumericInput_returnsFalse() { assertFalse(DateUtils.isValidMonth("15")); assertFalse(DateUtils.isValidMonth("0")); assertFalse(DateUtils.isValidMonth("-08")); }
@Test public void isValidMonth_forNullInput_returnsFalse() { assertFalse(DateUtils.isValidMonth(null)); }
@Test public void isValidMonth_forNonNumericInput_returnsFalse() { assertFalse(DateUtils.isValidMonth(" ")); assertFalse(DateUtils.isValidMonth("abc")); assertFalse(DateUtils.isValidMonth("January")); assertFalse(DateUtils.isValidMonth("\n")); } |
### Question:
CountryAdapter extends ArrayAdapter { @NonNull @Override public Filter getFilter() { return mFilter; } CountryAdapter(Context context, List<String> countries); @Override int getCount(); @Override String getItem(int i); @Override long getItemId(int i); @Override View getView(int i, View view, ViewGroup viewGroup); @NonNull @Override Filter getFilter(); }### Answer:
@Test public void filter_whenCountryInputNoMatch_showsAllResults() { Filter filter = mCountryAdapter.getFilter(); filter.filter("NONEXISTANT COUNTRY"); int countryLength = mCountryAdapter.mCountries.size(); assertEquals(mCountryAdapter.mSuggestions.size(), countryLength); }
@Test public void filter_whenCountryInputMatches_filters() { Filter filter = mCountryAdapter.getFilter(); int countryLength = mCountryAdapter.mCountries.size(); filter.filter("a"); assertTrue(mCountryAdapter.mSuggestions.size() < countryLength); for (String suggestedCountry: mCountryAdapter.mSuggestions) { assertTrue(suggestedCountry.toLowerCase().startsWith("a")); } }
@Test public void filter_whenCountryInputMatchesExactly_showsAllResults() { Filter filter = mCountryAdapter.getFilter(); int countryLength = mCountryAdapter.mCountries.size(); filter.filter("Uganda"); assertEquals(mCountryAdapter.mSuggestions.size(), countryLength); } |
### Question:
ViewUtils { static TypedValue getThemeAccentColor(Context context) { int colorAttr; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { colorAttr = android.R.attr.colorAccent; } else { colorAttr = context .getResources() .getIdentifier("colorAccent", "attr", context.getPackageName()); } TypedValue outValue = new TypedValue(); context.getTheme().resolveAttribute(colorAttr, outValue, true); return outValue; } }### Answer:
@Test public void getThemeAccentColor_whenOnPostLollipopConfig_getsNonzeroColor() { @ColorInt int color = ViewUtils.getThemeAccentColor(mActivityController.get()).data; assertTrue(Color.alpha(color) > 0); }
@Test @Config(sdk = 16) public void getThemeAccentColor_whenOnPreKitKatConfig_getsNonzeroColor() { @ColorInt int color = ViewUtils.getThemeAccentColor(mActivityController.get()).data; assertTrue(Color.alpha(color) > 0); } |
### Question:
ViewUtils { static TypedValue getThemeColorControlNormal(Context context) { int colorAttr; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { colorAttr = android.R.attr.colorControlNormal; } else { colorAttr = context .getResources() .getIdentifier("colorControlNormal", "attr", context.getPackageName()); } TypedValue outValue = new TypedValue(); context.getTheme().resolveAttribute(colorAttr, outValue, true); return outValue; } }### Answer:
@Test public void getThemeColorControlNormal_whenOnPostLollipopConfig_getsNonzeroColor() { @ColorInt int color = ViewUtils.getThemeColorControlNormal(mActivityController.get()).data; assertTrue(Color.alpha(color) > 0); }
@Test @Config(sdk = 16) public void getThemeColorControlNormal_whenOnPreKitKatConfig_getsNonzeroColor() { @ColorInt int color = ViewUtils.getThemeColorControlNormal(mActivityController.get()).data; assertTrue(Color.alpha(color) > 0); } |
### Question:
ViewUtils { static boolean isColorTransparent(@ColorInt int color) { return Color.alpha(color) < 0x10; } }### Answer:
@Test public void isColorTransparent_whenColorIsZero_returnsTrue() { assertTrue(ViewUtils.isColorTransparent(0)); }
@Test public void isColorTransparent_whenColorIsNonzeroButHasLowAlpha_returnsTrue() { @ColorInt int invisibleBlue = 0x050000ff; @ColorInt int invisibleRed = 0x0bff0000; assertTrue(ViewUtils.isColorTransparent(invisibleBlue)); assertTrue(ViewUtils.isColorTransparent(invisibleRed)); }
@Test public void isColorTransparent_whenColorIsNotCloseToTransparent_returnsFalse() { @ColorInt int brightWhite = 0xffffffff; @ColorInt int completelyBlack = 0xff000000; assertFalse(ViewUtils.isColorTransparent(brightWhite)); assertFalse(ViewUtils.isColorTransparent(completelyBlack)); } |
### Question:
StripeJsonUtils { @Nullable static Map<String, String> jsonObjectToStringMap(@Nullable JSONObject jsonObject) { if (jsonObject == null) { return null; } Map<String, String> map = new HashMap<>(); Iterator<String> keyIterator = jsonObject.keys(); while (keyIterator.hasNext()) { String key = keyIterator.next(); Object value = jsonObject.opt(key); if (NULL.equals(value) || value == null) { continue; } map.put(key, value.toString()); } return map; } }### Answer:
@Test public void jsonObjectToStringMap_forSimpleObjects_returnsExpectedMap() { Map<String, String> expectedMap = new HashMap<>(); expectedMap.put("akey", "avalue"); expectedMap.put("bkey", "bvalue"); expectedMap.put("boolkey", "true"); expectedMap.put("numkey", "123"); try { JSONObject testJsonObject = new JSONObject(SIMPLE_JSON_TEST_OBJECT); Map<String, String> mappedObject = StripeJsonUtils.jsonObjectToStringMap(testJsonObject); JsonTestUtils.assertMapEquals(expectedMap, mappedObject); } catch (JSONException jsonException) { fail("Test data failure " + jsonException.getLocalizedMessage()); } }
@Test public void jsonObjectToStringMap_forNestedObjects_returnsExpectedFlatMap() { Map<String, String> expectedMap = new HashMap<>(); expectedMap.put("top_key", "{\"first_inner_key\":{\"innermost_key\":1000," + "\"second_innermost_key\":\"second_inner_value\"}," + "\"second_inner_key\":\"just a value\"}"); expectedMap.put("second_outer_key", "{\"another_inner_key\":false}"); try { JSONObject testJsonObject = new JSONObject(NESTED_JSON_TEST_OBJECT); Map<String, String> mappedObject = StripeJsonUtils.jsonObjectToStringMap(testJsonObject); JsonTestUtils.assertMapEquals(expectedMap, mappedObject); } catch (JSONException jsonException) { fail("Test data failure " + jsonException.getLocalizedMessage()); } } |
### Question:
ViewUtils { static boolean isColorDark(@ColorInt int color){ double luminescence = 0.299* Color.red(color) + 0.587*Color.green(color) + 0.114* Color.blue(color); double luminescencePercentage = luminescence / 255; return luminescencePercentage <= 0.5; } }### Answer:
@Test public void isColorDark_forExampleLightColors_returnsFalse() { @ColorInt int middleGray = 0x888888; @ColorInt int offWhite = 0xfaebd7; @ColorInt int lightCyan = 0x8feffb; @ColorInt int lightYellow = 0xfcf4b2; @ColorInt int lightBlue = 0x9cdbff; assertFalse(ViewUtils.isColorDark(middleGray)); assertFalse(ViewUtils.isColorDark(offWhite)); assertFalse(ViewUtils.isColorDark(lightCyan)); assertFalse(ViewUtils.isColorDark(lightYellow)); assertFalse(ViewUtils.isColorDark(lightBlue)); assertFalse(ViewUtils.isColorDark(Color.WHITE)); }
@Test public void isColorDark_forExampleDarkColors_returnsTrue() { @ColorInt int logoBlue = 0x6772e5; @ColorInt int slate = 0x525f7f; @ColorInt int darkPurple = 0x6b3791; @ColorInt int darkishRed = 0x9e2146; assertTrue(ViewUtils.isColorDark(logoBlue)); assertTrue(ViewUtils.isColorDark(slate)); assertTrue(ViewUtils.isColorDark(darkPurple)); assertTrue(ViewUtils.isColorDark(darkishRed)); assertTrue(ViewUtils.isColorDark(Color.BLACK)); } |
### Question:
PaymentUtils { static String formatPriceStringUsingFree(long amount, @NonNull Currency currency, String free) { if (amount == 0) { return free; } NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(); DecimalFormatSymbols decimalFormatSymbols = ((java.text.DecimalFormat) currencyFormat).getDecimalFormatSymbols(); decimalFormatSymbols.setCurrencySymbol(currency.getSymbol(Locale.getDefault())); ((java.text.DecimalFormat) currencyFormat).setDecimalFormatSymbols(decimalFormatSymbols); return formatPriceString(amount, currency); } }### Answer:
@Test public void formatPriceStringUsingFree_whenZero_rendersFree() { assertEquals( PaymentUtils.formatPriceStringUsingFree( 0, Currency.getInstance("USD"), "Free"), "Free"); } |
### Question:
ShippingInfoWidget extends LinearLayout { public void setHiddenFields(@Nullable List<String> hiddenAddressFields) { if (hiddenAddressFields != null) { mHiddenShippingInfoFields = hiddenAddressFields; } else { mHiddenShippingInfoFields = new ArrayList<>(); } renderLabels(); renderCountrySpecificLabels(mCountryAutoCompleteTextView.getSelectedCountryCode()); } ShippingInfoWidget(Context context); ShippingInfoWidget(Context context, AttributeSet attrs); ShippingInfoWidget(Context context, AttributeSet attrs, int defStyleAttr); void setOptionalFields(@Nullable List<String> optionalAddressFields); void setHiddenFields(@Nullable List<String> hiddenAddressFields); ShippingInformation getShippingInformation(); void populateShippingInfo(@Nullable ShippingInformation shippingInformation); boolean validateAllFields(); static final String ADDRESS_LINE_ONE_FIELD; static final String ADDRESS_LINE_TWO_FIELD; static final String CITY_FIELD; static final String POSTAL_CODE_FIELD; static final String STATE_FIELD; static final String PHONE_FIELD; }### Answer:
@Test public void shippingInfoWidget_whenFieldsHidden_renderedHidden() { assertEquals(mNameTextInputLayout.getVisibility(), View.VISIBLE); assertEquals(mPostalCodeTextInputLayout.getVisibility(), View.VISIBLE); List<String> hiddenFields = new ArrayList<>(); hiddenFields.add(ShippingInfoWidget.POSTAL_CODE_FIELD); mShippingInfoWidget.setHiddenFields(hiddenFields); assertEquals(mPostalCodeTextInputLayout.getVisibility(), View.GONE); mCountryAutoCompleteTextView.updateUIForCountryEntered(Locale.CANADA.getDisplayCountry()); assertEquals(mPostalCodeTextInputLayout.getVisibility(), View.GONE); } |
### Question:
CountryAutoCompleteTextView extends FrameLayout { String getSelectedCountryCode() { return mCountrySelected; } CountryAutoCompleteTextView(Context context); CountryAutoCompleteTextView(Context context, AttributeSet attrs); CountryAutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr); }### Answer:
@Test public void countryAutoCompleteTextView_whenInitialized_displaysDefaultLocaleDisplayName() { assertEquals(Locale.US.getCountry(), mCountryAutoCompleteTextView.getSelectedCountryCode()); assertEquals(Locale.US.getDisplayCountry(), mAutoCompleteTextView.getText().toString()); } |
### Question:
CountryUtils { static boolean doesCountryUsePostalCode(@NonNull String countryCode) { return !NO_POSTAL_CODE_COUNTRIES_SET.contains(countryCode); } }### Answer:
@Test public void postalCodeCountryTest() { assertTrue(CountryUtils.doesCountryUsePostalCode("US")); assertTrue(CountryUtils.doesCountryUsePostalCode("UK")); assertTrue(CountryUtils.doesCountryUsePostalCode("CA")); assertFalse(CountryUtils.doesCountryUsePostalCode("DM")); } |
### Question:
CountryUtils { static boolean isUSZipCodeValid(@NonNull String zipCode) { return Pattern.matches("^[0-9]{5}(?:-[0-9]{4})?$", zipCode); } }### Answer:
@Test public void usZipCodeTest() { assertTrue(CountryUtils.isUSZipCodeValid("94107")); assertTrue(CountryUtils.isUSZipCodeValid("94107-1234")); assertFalse(CountryUtils.isUSZipCodeValid("941071234")); assertFalse(CountryUtils.isUSZipCodeValid("9410a1234")); assertFalse(CountryUtils.isUSZipCodeValid("94107-")); assertFalse(CountryUtils.isUSZipCodeValid("9410&")); assertFalse(CountryUtils.isUSZipCodeValid("K1A 0B1")); assertFalse(CountryUtils.isUSZipCodeValid("")); } |
### Question:
CountryUtils { static boolean isCanadianPostalCodeValid(@NonNull String postalCode) { return Pattern.matches("^(?!.*[DFIOQU])[A-VXY][0-9][A-Z] ?[0-9][A-Z][0-9]$", postalCode); } }### Answer:
@Test public void canadianPostalCodeTest() { assertTrue(CountryUtils.isCanadianPostalCodeValid("K1A 0B1")); assertTrue(CountryUtils.isCanadianPostalCodeValid("B1Z 0B9")); assertFalse(CountryUtils.isCanadianPostalCodeValid("K1A 0D1")); assertFalse(CountryUtils.isCanadianPostalCodeValid("94107")); assertFalse(CountryUtils.isCanadianPostalCodeValid("94107-1234")); assertFalse(CountryUtils.isCanadianPostalCodeValid("W1A 0B1")); assertFalse(CountryUtils.isCanadianPostalCodeValid("123")); assertFalse(CountryUtils.isCanadianPostalCodeValid("")); } |
### Question:
CountryUtils { static boolean isUKPostcodeValid(@NonNull String postcode) { return Pattern.matches("^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$", postcode); } }### Answer:
@Test public void ukPostalCodeTest() { assertTrue(CountryUtils.isUKPostcodeValid("L1 8JQ")); assertTrue(CountryUtils.isUKPostcodeValid("GU16 7HF")); assertTrue(CountryUtils.isUKPostcodeValid("PO16 7GZ")); assertFalse(CountryUtils.isUKPostcodeValid("94107")); assertFalse(CountryUtils.isUKPostcodeValid("94107-1234")); assertFalse(CountryUtils.isUKPostcodeValid("!1A 0B1")); assertFalse(CountryUtils.isUKPostcodeValid("Z1A 0B1")); assertFalse(CountryUtils.isUKPostcodeValid("123")); } |
### Question:
CardInputWidget extends LinearLayout { public void setCardNumber(String cardNumber) { mCardNumberEditText.setText(cardNumber); setCardNumberIsViewed(!mCardNumberEditText.isCardNumberValid()); } CardInputWidget(Context context); CardInputWidget(Context context, AttributeSet attrs); CardInputWidget(Context context, AttributeSet attrs, int defStyleAttr); @Nullable Card getCard(); void setCardInputListener(@Nullable CardInputListener listener); void setCardNumber(String cardNumber); void setExpiryDate(
@IntRange(from = 1, to = 12) int month,
@IntRange(from = 0, to = 9999) int year); void setCvcCode(String cvcCode); void clear(); void setEnabled(boolean isEnabled); @Override boolean isEnabled(); @Override boolean onInterceptTouchEvent(MotionEvent ev); @Override void onWindowFocusChanged(boolean hasWindowFocus); }### Answer:
@Test public void setCardNumber_withIncompleteNumber_doesNotValidateCard() { mCardInputWidget.setCardNumber("123456"); assertFalse(mCardNumberEditText.isCardNumberValid()); assertTrue(mCardNumberEditText.hasFocus()); } |
### Question:
StripeJsonUtils { @Nullable static JSONObject stringHashToJsonObject(@Nullable Map<String, String> stringStringMap) { if (stringStringMap == null) { return null; } JSONObject jsonObject = new JSONObject(); for (String key : stringStringMap.keySet()) { try { jsonObject.put(key, stringStringMap.get(key)); } catch (JSONException jsonException) { } } return jsonObject; } }### Answer:
@Test public void stringHashToJsonObject_returnsExpectedObject() { Map<String, String> stringHash = new HashMap<>(); stringHash.put("akey", "avalue"); stringHash.put("bkey", "bvalue"); stringHash.put("ckey", "cvalue"); stringHash.put("dkey", "dvalue"); try { JSONObject expectedObject = new JSONObject(SIMPLE_JSON_HASH_OBJECT); JsonTestUtils.assertJsonEquals(expectedObject, StripeJsonUtils.stringHashToJsonObject(stringHash)); } catch (JSONException jsonException) { fail("Test data failure " + jsonException.getLocalizedMessage()); } } |
### Question:
Customer extends StripeJsonModel { @Nullable public static Customer fromString(String jsonString) { if (jsonString == null) { return null; } try { return fromJson(new JSONObject(jsonString)); } catch (JSONException ignored) { return null; } } private Customer(); String getId(); String getDefaultSource(); ShippingInformation getShippingInformation(); List<CustomerSource> getSources(); Boolean getHasMore(); Integer getTotalCount(); String getUrl(); @Nullable CustomerSource getSourceById(@NonNull String sourceId); @NonNull @Override JSONObject toJson(); @NonNull @Override Map<String, Object> toMap(); @Nullable static Customer fromString(String jsonString); @Nullable static Customer fromJson(JSONObject jsonObject); }### Answer:
@Test public void fromString_whenStringIsNull_returnsNull() { assertNull(Customer.fromString(null)); }
@Test public void fromJson_whenNotACustomer_returnsNull() { assertNull(Customer.fromString(NON_CUSTOMER_OBJECT)); } |
### Question:
CardInputWidget extends LinearLayout { public void setExpiryDate( @IntRange(from = 1, to = 12) int month, @IntRange(from = 0, to = 9999) int year) { mExpiryDateEditText.setText(DateUtils.createDateStringFromIntegerInput(month, year)); } CardInputWidget(Context context); CardInputWidget(Context context, AttributeSet attrs); CardInputWidget(Context context, AttributeSet attrs, int defStyleAttr); @Nullable Card getCard(); void setCardInputListener(@Nullable CardInputListener listener); void setCardNumber(String cardNumber); void setExpiryDate(
@IntRange(from = 1, to = 12) int month,
@IntRange(from = 0, to = 9999) int year); void setCvcCode(String cvcCode); void clear(); void setEnabled(boolean isEnabled); @Override boolean isEnabled(); @Override boolean onInterceptTouchEvent(MotionEvent ev); @Override void onWindowFocusChanged(boolean hasWindowFocus); }### Answer:
@Test public void setExpirationDate_withValidData_setsCorrectValues() { mCardInputWidget.setExpiryDate(12, 79); assertEquals("12/79", mExpiryEditText.getText().toString()); } |
### Question:
CardInputWidget extends LinearLayout { public void setCvcCode(String cvcCode) { mCvcNumberEditText.setText(cvcCode); } CardInputWidget(Context context); CardInputWidget(Context context, AttributeSet attrs); CardInputWidget(Context context, AttributeSet attrs, int defStyleAttr); @Nullable Card getCard(); void setCardInputListener(@Nullable CardInputListener listener); void setCardNumber(String cardNumber); void setExpiryDate(
@IntRange(from = 1, to = 12) int month,
@IntRange(from = 0, to = 9999) int year); void setCvcCode(String cvcCode); void clear(); void setEnabled(boolean isEnabled); @Override boolean isEnabled(); @Override boolean onInterceptTouchEvent(MotionEvent ev); @Override void onWindowFocusChanged(boolean hasWindowFocus); }### Answer:
@Test public void setCvcCode_withValidData_setsValue() { mCardInputWidget.setCvcCode("123"); assertEquals("123", mCvcEditText.getText().toString()); }
@Test public void setCvcCode_withLongString_truncatesValue() { mCardInputWidget.setCvcCode("1234"); assertEquals("123", mCvcEditText.getText().toString()); } |
### Question:
Address extends StripeJsonModel implements Parcelable { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); putStringIfNotNull(jsonObject, FIELD_CITY, mCity); putStringIfNotNull(jsonObject, FIELD_COUNTRY, mCountry); putStringIfNotNull(jsonObject, FIELD_LINE_1, mLine1); putStringIfNotNull(jsonObject, FIELD_LINE_2, mLine2); putStringIfNotNull(jsonObject, FIELD_POSTAL_CODE, mPostalCode); putStringIfNotNull(jsonObject, FIELD_STATE, mState); return jsonObject; } Address(
String city,
String country,
String line1,
String line2,
String postalCode,
String state); Address(Builder addressBuilder); protected Address(Parcel in); @Nullable String getCity(); @Deprecated void setCity(String city); @Nullable String getCountry(); @Deprecated void setCountry(String country); @Nullable String getLine1(); @Deprecated void setLine1(String line1); @Nullable String getLine2(); @Deprecated void setLine2(String line2); @Nullable String getPostalCode(); @Deprecated void setPostalCode(String postalCode); @Nullable String getState(); @Deprecated void setState(String state); @NonNull @Override Map<String, Object> toMap(); @NonNull @Override JSONObject toJson(); @Nullable static Address fromString(@Nullable String jsonString); @Nullable static Address fromJson(@Nullable JSONObject jsonObject); @Override void writeToParcel(Parcel out, int flags); @Override int describeContents(); static final Parcelable.Creator<Address> CREATOR; }### Answer:
@Test public void fromJsonString_backToJson_createsIdenticalElement() { try { JSONObject rawConversion = new JSONObject(EXAMPLE_JSON_ADDRESS); assertJsonEquals(rawConversion, mAddress.toJson()); } catch (JSONException jsonException) { fail("Test Data failure: " + jsonException.getLocalizedMessage()); } } |
### Question:
StripeApiHandler { @VisibleForTesting static String getApiUrl() { return String.format(Locale.ENGLISH, "%s/v1/%s", LIVE_API_BASE, TOKENS); } }### Answer:
@Test public void testGetApiUrl() { String tokensApi = StripeApiHandler.getApiUrl(); assertEquals("https: } |
### Question:
StripeApiHandler { @VisibleForTesting static String getSourcesUrl() { return String.format(Locale.ENGLISH, "%s/v1/%s", LIVE_API_BASE, SOURCES); } }### Answer:
@Test public void testGetSourcesUrl() { String sourcesUrl = StripeApiHandler.getSourcesUrl(); assertEquals("https: } |
### Question:
StripeApiHandler { @VisibleForTesting static String getRetrieveSourceApiUrl(@NonNull String sourceId) { return String.format(Locale.ENGLISH, "%s/%s", getSourcesUrl(), sourceId); } }### Answer:
@Test public void testGetRetrieveSourceUrl() { String sourceUrlWithId = StripeApiHandler.getRetrieveSourceApiUrl("abc123"); assertEquals("https: } |
### Question:
StripeApiHandler { @VisibleForTesting static String getRetrieveTokenApiUrl(@NonNull String tokenId) { return String.format("%s/%s", getApiUrl(), tokenId); } }### Answer:
@Test public void testGetRequestTokenApiUrl() { String tokenId = "tok_sample"; String requestApi = StripeApiHandler.getRetrieveTokenApiUrl(tokenId); assertEquals("https: } |
### Question:
StripeApiHandler { @VisibleForTesting static String getRetrieveCustomerUrl(@NonNull String customerId) { return String.format(Locale.ENGLISH, "%s/%s", getCustomersUrl(), customerId); } }### Answer:
@Test public void testGetRetrieveCustomerUrl() { String customerId = "cus_123abc"; String customerRequestUrl = StripeApiHandler.getRetrieveCustomerUrl(customerId); assertEquals("https: } |
### Question:
StripeApiHandler { @VisibleForTesting static String getAddCustomerSourceUrl(@NonNull String customerId) { return String.format(Locale.ENGLISH, "%s/%s", getRetrieveCustomerUrl(customerId), SOURCES); } }### Answer:
@Test public void testGetAddCustomerSourceUrl() { String customerId = "cus_123abc"; String addSourceUrl = StripeApiHandler.getAddCustomerSourceUrl(customerId); assertEquals("https: addSourceUrl); } |
### Question:
Address extends StripeJsonModel implements Parcelable { @NonNull @Override public Map<String, Object> toMap() { Map<String, Object> hashMap = new HashMap<>(); hashMap.put(FIELD_CITY, mCity); hashMap.put(FIELD_COUNTRY, mCountry); hashMap.put(FIELD_LINE_1, mLine1); hashMap.put(FIELD_LINE_2, mLine2); hashMap.put(FIELD_POSTAL_CODE, mPostalCode); hashMap.put(FIELD_STATE, mState); return hashMap; } Address(
String city,
String country,
String line1,
String line2,
String postalCode,
String state); Address(Builder addressBuilder); protected Address(Parcel in); @Nullable String getCity(); @Deprecated void setCity(String city); @Nullable String getCountry(); @Deprecated void setCountry(String country); @Nullable String getLine1(); @Deprecated void setLine1(String line1); @Nullable String getLine2(); @Deprecated void setLine2(String line2); @Nullable String getPostalCode(); @Deprecated void setPostalCode(String postalCode); @Nullable String getState(); @Deprecated void setState(String state); @NonNull @Override Map<String, Object> toMap(); @NonNull @Override JSONObject toJson(); @Nullable static Address fromString(@Nullable String jsonString); @Nullable static Address fromJson(@Nullable JSONObject jsonObject); @Override void writeToParcel(Parcel out, int flags); @Override int describeContents(); static final Parcelable.Creator<Address> CREATOR; }### Answer:
@Test public void fromJsonString_toMap_createsExpectedMap() { assertMapEquals(EXAMPLE_MAP_ADDRESS, mAddress.toMap()); } |
### Question:
StripeApiHandler { static String createQuery(Map<String, Object> params) throws UnsupportedEncodingException, InvalidRequestException { StringBuilder queryStringBuffer = new StringBuilder(); List<Parameter> flatParams = flattenParams(params); Iterator<Parameter> it = flatParams.iterator(); while (it.hasNext()) { if (queryStringBuffer.length() > 0) { queryStringBuffer.append("&"); } Parameter param = it.next(); queryStringBuffer.append(urlEncodePair(param.key, param.value)); } return queryStringBuffer.toString(); } }### Answer:
@Test public void createQuery_withCardData_createsProperQueryString() { Card card = new Card.Builder("4242424242424242", 8, 2019, "123").build(); Map<String, Object> cardMap = StripeNetworkUtils.hashMapFromCard( RuntimeEnvironment.application, card); String expectedValue = "product_usage=&card%5Bnumber%5D=4242424242424242&card%5B" + "cvc%5D=123&card%5Bexp_month%5D=8&card%5Bexp_year%5D=2019"; try { String query = StripeApiHandler.createQuery(cardMap); assertEquals(expectedValue, query); } catch (UnsupportedEncodingException unsupportedCodingException) { fail("Encoding error with card object"); } catch (InvalidRequestException invalidRequest) { fail("Invalid request error when encoding card query: " + invalidRequest.getLocalizedMessage()); } } |
### Question:
SourceRedirect extends StripeJsonModel { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); putStringIfNotNull(jsonObject, FIELD_RETURN_URL, mReturnUrl); putStringIfNotNull(jsonObject, FIELD_STATUS, mStatus); putStringIfNotNull(jsonObject, FIELD_URL, mUrl); return jsonObject; } SourceRedirect(String returnUrl, @Status String status, String url); String getReturnUrl(); void setReturnUrl(String returnUrl); @Status String getStatus(); void setStatus(@Status String status); String getUrl(); void setUrl(String url); @NonNull @Override Map<String, Object> toMap(); @NonNull @Override JSONObject toJson(); @Nullable static SourceRedirect fromString(@Nullable String jsonString); @Nullable static SourceRedirect fromJson(@Nullable JSONObject jsonObject); static final String PENDING; static final String SUCCEEDED; static final String FAILED; }### Answer:
@Test public void fromJsonString_backToJson_createsIdenticalElement() { try { JSONObject rawConversion = new JSONObject(EXAMPLE_JSON_REDIRECT); assertJsonEquals(rawConversion, mSourceRedirect.toJson()); } catch (JSONException jsonException) { fail("Test Data failure: " + jsonException.getLocalizedMessage()); } } |
### Question:
EphemeralKeyManager { @Nullable @VisibleForTesting EphemeralKey getEphemeralKey() { return mEphemeralKey; } EphemeralKeyManager(
@NonNull EphemeralKeyProvider ephemeralKeyProvider,
@NonNull KeyManagerListener keyManagerListener,
long timeBufferInSeconds,
@Nullable Calendar overrideCalendar); }### Answer:
@Test @SuppressWarnings("unchecked") public void createKeyManager_updatesEphemeralKey_notifiesListener() { EphemeralKey testKey = EphemeralKey.fromString(FIRST_SAMPLE_KEY_RAW); assertNotNull(testKey); mTestEphemeralKeyProvider.setNextRawEphemeralKey(FIRST_SAMPLE_KEY_RAW); EphemeralKeyManager keyManager = new EphemeralKeyManager( mTestEphemeralKeyProvider, mKeyManagerListener, TEST_SECONDS_BUFFER, null); verify(mKeyManagerListener, times(1)).onKeyUpdate( any(EphemeralKey.class), (String) isNull(), (Map<String, Object>) isNull()); assertNotNull(keyManager.getEphemeralKey()); assertEquals(testKey.getId(), keyManager.getEphemeralKey().getId()); } |
### Question:
SourceRedirect extends StripeJsonModel { @NonNull @Override public Map<String, Object> toMap() { Map<String, Object> hashMap = new HashMap<>(); hashMap.put(FIELD_RETURN_URL, mReturnUrl); hashMap.put(FIELD_STATUS, mStatus); hashMap.put(FIELD_URL, mUrl); removeNullAndEmptyParams(hashMap); return hashMap; } SourceRedirect(String returnUrl, @Status String status, String url); String getReturnUrl(); void setReturnUrl(String returnUrl); @Status String getStatus(); void setStatus(@Status String status); String getUrl(); void setUrl(String url); @NonNull @Override Map<String, Object> toMap(); @NonNull @Override JSONObject toJson(); @Nullable static SourceRedirect fromString(@Nullable String jsonString); @Nullable static SourceRedirect fromJson(@Nullable JSONObject jsonObject); static final String PENDING; static final String SUCCEEDED; static final String FAILED; }### Answer:
@Test public void fromJsonString_toMap_createsExpectedMap() { assertMapEquals(EXAMPLE_MAP_REDIRECT, mSourceRedirect.toMap()); } |
### Question:
StripeJsonModel { @Override public int hashCode() { return this.toString().hashCode(); } @NonNull abstract Map<String, Object> toMap(); @NonNull abstract JSONObject toJson(); @Override String toString(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void hashCode_whenEquals_returnsSameValue() { assertTrue(StripeJsonModel.class.isAssignableFrom(Card.class)); Card firstCard = Card.fromString(CardTest.JSON_CARD); Card secondCard = Card.fromString(CardTest.JSON_CARD); assertNotNull(firstCard); assertNotNull(secondCard); assertEquals(firstCard.hashCode(), secondCard.hashCode()); } |
### Question:
PaymentConfiguration { @NonNull public static PaymentConfiguration getInstance() { if (mInstance == null) { throw new IllegalStateException( "Attempted to get instance of PaymentConfiguration without initialization."); } return mInstance; } private PaymentConfiguration(@NonNull String publishableKey); @NonNull static PaymentConfiguration getInstance(); static void init(@NonNull String publishableKey); @NonNull String getPublishableKey(); @Address.RequiredBillingAddressFields int getRequiredBillingAddressFields(); @NonNull PaymentConfiguration setRequiredBillingAddressFields(
@Address.RequiredBillingAddressFields int requiredBillingAddressFields); boolean getShouldUseSourcesForCards(); @NonNull PaymentConfiguration setShouldUseSourcesForCards(boolean shouldUseSourcesForCards); }### Answer:
@Test(expected = IllegalStateException.class) public void getInstance_beforeInit_throwsRuntimeException() { PaymentConfiguration.getInstance(); fail("Should not be able to get a payment configuration before it has been initialized."); } |
### Question:
StripeTextUtils { static boolean hasAnyPrefix(String number, String... prefixes) { if (number == null) { return false; } for (String prefix : prefixes) { if (number.startsWith(prefix)) { return true; } } return false; } @Nullable static String nullIfBlank(@Nullable String value); static boolean isBlank(@Nullable String value); @Nullable static String removeSpacesAndHyphens(@Nullable String cardNumberWithSpaces); }### Answer:
@Test public void hasAnyPrefixShouldFailIfNull() { assertFalse(StripeTextUtils.hasAnyPrefix(null)); }
@Test public void hasAnyPrefixShouldFailIfEmpty() { assertFalse(StripeTextUtils.hasAnyPrefix("")); }
@Test public void hasAnyPrefixShouldFailWithNullAndEmptyPrefix() { assertFalse(StripeTextUtils.hasAnyPrefix(null, "")); }
@Test public void hasAnyPrefixShouldFailWithNullAndSomePrefix() { assertFalse(StripeTextUtils.hasAnyPrefix(null, "1")); }
@Test public void hasAnyPrefixShouldMatch() { assertTrue(StripeTextUtils.hasAnyPrefix("1234", "12")); }
@Test public void hasAnyPrefixShouldMatchMultiple() { assertTrue(StripeTextUtils.hasAnyPrefix("1234", "12", "1")); }
@Test public void hasAnyPrefixShouldMatchSome() { assertTrue(StripeTextUtils.hasAnyPrefix("abcd", "bc", "ab")); }
@Test public void hasAnyPrefixShouldNotMatch() { assertFalse(StripeTextUtils.hasAnyPrefix("1234", "23")); }
@Test public void hasAnyPrefixShouldNotMatchWithSpace() { assertFalse(StripeTextUtils.hasAnyPrefix("xyz", " x")); } |
### Question:
StripeJsonModel { static void putStripeJsonModelListIfNotNull( @NonNull Map<String, Object> upperLevelMap, @NonNull @Size(min = 1) String key, @Nullable List<? extends StripeJsonModel> jsonModelList) { if (jsonModelList == null) { return; } List<Map<String, Object>> mapList = new ArrayList<>(); for (int i = 0; i < jsonModelList.size(); i++) { mapList.add(jsonModelList.get(i).toMap()); } upperLevelMap.put(key, mapList); } @NonNull abstract Map<String, Object> toMap(); @NonNull abstract JSONObject toJson(); @Override String toString(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void putStripeJsonModelListIfNotNull_forMapsWhenNull_doesNothing() { Map<String, Object> sampleMap = new HashMap<>(); StripeJsonModel.putStripeJsonModelListIfNotNull(sampleMap, "mapkey", null); assertTrue(sampleMap.isEmpty()); }
@Test public void putStripeJsonModelListIfNotNull_forJsonWhenNull_doesNothing() { JSONObject jsonObject = new JSONObject(); StripeJsonModel.putStripeJsonModelListIfNotNull(jsonObject, "jsonkey", null); assertFalse(jsonObject.has("jsonkey")); } |
### Question:
StripeTextUtils { @Nullable public static String nullIfBlank(@Nullable String value) { if (isBlank(value)) { return null; } return value; } @Nullable static String nullIfBlank(@Nullable String value); static boolean isBlank(@Nullable String value); @Nullable static String removeSpacesAndHyphens(@Nullable String cardNumberWithSpaces); }### Answer:
@Test public void testNullIfBlankNullShouldBeNull() { assertEquals(null, StripeTextUtils.nullIfBlank(null)); }
@Test public void testNullIfBlankEmptyShouldBeNull() { assertEquals(null, StripeTextUtils.nullIfBlank("")); }
@Test public void testNullIfBlankSpaceShouldBeNull() { assertEquals(null, StripeTextUtils.nullIfBlank(" ")); }
@Test public void testNullIfBlankSpacesShouldBeNull() { assertEquals(null, StripeTextUtils.nullIfBlank(" ")); }
@Test public void testNullIfBlankTabShouldBeNull() { assertEquals(null, StripeTextUtils.nullIfBlank(" ")); }
@Test public void testNullIfBlankNumbersShouldNotBeNull() { assertEquals("0", StripeTextUtils.nullIfBlank("0")); }
@Test public void testNullIfBlankLettersShouldNotBeNull() { assertEquals("abc", StripeTextUtils.nullIfBlank("abc")); } |
### Question:
StripeTextUtils { public static boolean isBlank(@Nullable String value) { return value == null || value.trim().length() == 0; } @Nullable static String nullIfBlank(@Nullable String value); static boolean isBlank(@Nullable String value); @Nullable static String removeSpacesAndHyphens(@Nullable String cardNumberWithSpaces); }### Answer:
@Test public void isBlankShouldPassIfNull() { assertTrue(StripeTextUtils.isBlank(null)); }
@Test public void isBlankShouldPassIfEmpty() { assertTrue(StripeTextUtils.isBlank("")); }
@Test public void isBlankShouldPassIfSpace() { assertTrue(StripeTextUtils.isBlank(" ")); }
@Test public void isBlankShouldPassIfSpaces() { assertTrue(StripeTextUtils.isBlank(" ")); }
@Test public void isBlankShouldPassIfTab() { assertTrue(StripeTextUtils.isBlank(" ")); }
@Test public void isBlankShouldFailIfNumber() { assertFalse(StripeTextUtils.isBlank("0")); }
@Test public void isBlankShouldFailIfLetters() { assertFalse(StripeTextUtils.isBlank("abc")); } |
### Question:
StripeTextUtils { @Nullable static String shaHashInput(@Nullable String toHash) { if (StripeTextUtils.isBlank(toHash)) { return null; } String hash; try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); byte[] bytes = toHash.getBytes("UTF-8"); digest.update(bytes, 0, bytes.length); bytes = digest.digest(); hash = bytesToHex(bytes); } catch(NoSuchAlgorithmException noSuchAlgorithm) { return null; } catch (UnsupportedEncodingException unsupportedCoding) { return null; } return hash; } @Nullable static String nullIfBlank(@Nullable String value); static boolean isBlank(@Nullable String value); @Nullable static String removeSpacesAndHyphens(@Nullable String cardNumberWithSpaces); }### Answer:
@Test public void shaHashInput_withNullInput_returnsNull() { assertNull(StripeTextUtils.shaHashInput(" ")); }
@Test public void shaHashInput_withText_returnsDifferentText() { String unhashedText = "iamtheverymodelofamodernmajorgeneral"; String hashedText = StripeTextUtils.shaHashInput(unhashedText); assertNotEquals(unhashedText, hashedText); } |
### Question:
StripeNetworkUtils { @SuppressWarnings("HardwareIds") static void addUidParams( @Nullable UidProvider provider, @NonNull Context context, @NonNull Map<String, Object> params) { String guid = provider == null ? Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID) : provider.getUid(); if (StripeTextUtils.isBlank(guid)) { return; } String hashGuid = StripeTextUtils.shaHashInput(guid); String muid = provider == null ? context.getApplicationContext().getPackageName() + guid : provider.getPackageName() + guid; String hashMuid = StripeTextUtils.shaHashInput(muid); if (!StripeTextUtils.isBlank(hashGuid)) { params.put(GUID, hashGuid); } if (!StripeTextUtils.isBlank(hashMuid)) { params.put(MUID, hashMuid); } } @SuppressWarnings("unchecked") static void removeNullAndEmptyParams(@NonNull Map<String, Object> mapToEdit); }### Answer:
@Test public void addUidParams_addsParams() { Map<String, Object> existingMap = new HashMap<>(); StripeNetworkUtils.UidProvider provider = new StripeNetworkUtils.UidProvider() { @Override public String getUid() { return "abc123"; } @Override public String getPackageName() { return "com.example.main"; } }; StripeNetworkUtils.addUidParams(provider, RuntimeEnvironment.application, existingMap); assertEquals(2, existingMap.size()); assertTrue(existingMap.containsKey("muid")); assertTrue(existingMap.containsKey("guid")); } |
### Question:
LineItemBuilder { static boolean isWholeNumber(BigDecimal number) { return number.remainder(BigDecimal.ONE).compareTo(BigDecimal.ZERO) == 0; } LineItemBuilder(); LineItemBuilder(String currencyCode); LineItemBuilder setCurrencyCode(String currencyCode); LineItemBuilder setUnitPrice(long unitPrice); LineItemBuilder setTotalPrice(long totalPrice); LineItemBuilder setQuantity(BigDecimal quantity); LineItemBuilder setQuantity(double quantity); LineItemBuilder setDescription(String description); LineItemBuilder setRole(int role); LineItem build(); static final Set<Integer> VALID_ROLES; }### Answer:
@Test public void isWholeNumber_whenBigDecimalFromInteger_returnsTrue() { assertTrue(LineItemBuilder.isWholeNumber(BigDecimal.ZERO)); assertTrue(LineItemBuilder.isWholeNumber(BigDecimal.valueOf(555))); }
@Test public void isWholeNumber_whenBigDecimalDoubleWithoutDecimalPart_returnsTrue() { assertTrue(LineItemBuilder.isWholeNumber(BigDecimal.valueOf(1.0000))); }
@Test public void isWholeNumber_whenBigDecimalDoubleWithDecimalPart_returnsFalse() { assertFalse(LineItemBuilder.isWholeNumber(BigDecimal.valueOf(1.5))); assertFalse(LineItemBuilder.isWholeNumber(BigDecimal.valueOf(2.07))); } |
### Question:
PaymentUtils { public static boolean matchesCurrencyPatternOrEmpty(@Nullable String priceString) { if (TextUtils.isEmpty(priceString)) { return true; } Pattern pattern = Pattern.compile("^-?[0-9]+(\\.[0-9][0-9])?"); return pattern.matcher(priceString).matches(); } static boolean matchesCurrencyPatternOrEmpty(@Nullable String priceString); static boolean matchesQuantityPatternOrEmpty(@Nullable String quantityString); @NonNull static List<CartError> validateLineItemList(
List<LineItem> lineItems,
@NonNull String currencyCode); static CartError searchLineItemForErrors(LineItem lineItem); @NonNull static String getPriceString(long price); @NonNull static List<CartError> removeErrorType(
@NonNull List<CartError> errors,
@NonNull @CartError.CartErrorType String errorType); @NonNull static String getPriceString(Long price, @NonNull Currency currency); static IsReadyToPayRequest getStripeIsReadyToPayRequest(); }### Answer:
@Test public void matchesCurrencyPattern_whenValid_returnsTrue() { assertTrue(matchesCurrencyPatternOrEmpty(null)); assertTrue(matchesCurrencyPatternOrEmpty("")); assertTrue(matchesCurrencyPatternOrEmpty("10.00")); assertTrue(matchesCurrencyPatternOrEmpty("01.11")); assertTrue(matchesCurrencyPatternOrEmpty("5000.05")); assertTrue(matchesCurrencyPatternOrEmpty("100")); assertTrue(matchesCurrencyPatternOrEmpty("-5")); }
@Test public void matchesCurrencyPattern_whenInvalid_returnsFalse() { assertFalse(matchesCurrencyPatternOrEmpty(".99")); assertFalse(matchesCurrencyPatternOrEmpty("0.123")); assertFalse(matchesCurrencyPatternOrEmpty("1.")); } |
### Question:
PaymentUtils { public static boolean matchesQuantityPatternOrEmpty(@Nullable String quantityString) { if (TextUtils.isEmpty(quantityString)) { return true; } Pattern pattern = Pattern.compile("[0-9]+(\\.[0-9])?"); return pattern.matcher(quantityString).matches(); } static boolean matchesCurrencyPatternOrEmpty(@Nullable String priceString); static boolean matchesQuantityPatternOrEmpty(@Nullable String quantityString); @NonNull static List<CartError> validateLineItemList(
List<LineItem> lineItems,
@NonNull String currencyCode); static CartError searchLineItemForErrors(LineItem lineItem); @NonNull static String getPriceString(long price); @NonNull static List<CartError> removeErrorType(
@NonNull List<CartError> errors,
@NonNull @CartError.CartErrorType String errorType); @NonNull static String getPriceString(Long price, @NonNull Currency currency); static IsReadyToPayRequest getStripeIsReadyToPayRequest(); }### Answer:
@Test public void matchesQuantityPattern_whenValid_returnsTrue() { assertTrue(matchesQuantityPatternOrEmpty(null)); assertTrue(matchesQuantityPatternOrEmpty("")); assertTrue(matchesQuantityPatternOrEmpty("10.1")); assertTrue(matchesQuantityPatternOrEmpty("01")); assertTrue(matchesQuantityPatternOrEmpty("500000000000")); assertTrue(matchesQuantityPatternOrEmpty("100")); }
@Test public void matchesQuantityPattern_whenInvalid_returnsFalse() { assertFalse(matchesQuantityPatternOrEmpty("1.23")); assertFalse(matchesQuantityPatternOrEmpty(".99")); assertFalse(matchesQuantityPatternOrEmpty("0.123")); assertFalse(matchesQuantityPatternOrEmpty("1.")); assertFalse(matchesQuantityPatternOrEmpty("-5")); } |
### Question:
PaymentUtils { public static IsReadyToPayRequest getStripeIsReadyToPayRequest() { return IsReadyToPayRequest.newBuilder() .addAllowedCardNetwork(WalletConstants.CardNetwork.AMEX) .addAllowedCardNetwork(WalletConstants.CardNetwork.DISCOVER) .addAllowedCardNetwork(WalletConstants.CardNetwork.JCB) .addAllowedCardNetwork(WalletConstants.CardNetwork.MASTERCARD) .addAllowedCardNetwork(WalletConstants.CardNetwork.VISA) .build(); } static boolean matchesCurrencyPatternOrEmpty(@Nullable String priceString); static boolean matchesQuantityPatternOrEmpty(@Nullable String quantityString); @NonNull static List<CartError> validateLineItemList(
List<LineItem> lineItems,
@NonNull String currencyCode); static CartError searchLineItemForErrors(LineItem lineItem); @NonNull static String getPriceString(long price); @NonNull static List<CartError> removeErrorType(
@NonNull List<CartError> errors,
@NonNull @CartError.CartErrorType String errorType); @NonNull static String getPriceString(Long price, @NonNull Currency currency); static IsReadyToPayRequest getStripeIsReadyToPayRequest(); }### Answer:
@Test public void getIsReadyToPayRequest_hasExpectedCardNetworks() { IsReadyToPayRequest isReadyToPayRequest = getStripeIsReadyToPayRequest(); Set<Integer> allowedNetworks = new HashSet<>(); allowedNetworks.addAll(isReadyToPayRequest.getAllowedCardNetworks()); assertEquals(5, allowedNetworks.size()); assertTrue(allowedNetworks.contains(WalletConstants.CardNetwork.VISA)); assertTrue(allowedNetworks.contains(WalletConstants.CardNetwork.AMEX)); assertTrue(allowedNetworks.contains(WalletConstants.CardNetwork.MASTERCARD)); assertTrue(allowedNetworks.contains(WalletConstants.CardNetwork.JCB)); assertTrue(allowedNetworks.contains(WalletConstants.CardNetwork.DISCOVER)); } |
### Question:
CartManager { public Long calculateTax() { if (mLineItemTax == null) { return 0L; } if (!mCurrency.getCurrencyCode().equals(mLineItemTax.getCurrencyCode())) { return null; } return PaymentUtils.getPriceLong(mLineItemTax.getTotalPrice(), mCurrency); } CartManager(); CartManager(String currencyCode); CartManager(@NonNull Cart oldCart); CartManager(@NonNull Cart oldCart, boolean shouldKeepShipping, boolean shouldKeepTax); @Nullable String addLineItem(@NonNull @Size(min = 1) String description, long totalPrice); @Nullable String addLineItem(@NonNull @Size(min = 1) String description,
double quantity,
long unitPrice); @Nullable String addShippingLineItem(@NonNull @Size(min = 1) String description, long totalPrice); @Nullable String addShippingLineItem(@NonNull @Size(min = 1) String description,
double quantity,
long unitPrice); @Nullable Long calculateRegularItemTotal(); @Nullable Long calculateShippingItemTotal(); Long calculateTax(); void setTaxLineItem(@NonNull @Size(min = 1) String description, long totalPrice); void setTotalPrice(@Nullable Long totalPrice); void setTaxLineItem(@Nullable LineItem item); @Nullable LineItem removeLineItem(@NonNull @Size(min = 1) String itemId); @Nullable String addLineItem(@NonNull LineItem item); @NonNull Cart buildCart(); @Nullable Long getTotalPrice(); @NonNull Currency getCurrency(); @NonNull String getCurrencyCode(); @NonNull LinkedHashMap<String, LineItem> getLineItemsRegular(); @NonNull LinkedHashMap<String, LineItem> getLineItemsShipping(); @Nullable LineItem getLineItemTax(); }### Answer:
@Test public void calculateTax_whenItemNotPresent_returnsZero() { AndroidPayConfiguration.getInstance().setCurrencyCode("KRW"); CartManager manager = new CartManager("KRW"); assertEquals(Long.valueOf(0L), manager.calculateTax()); } |
### Question:
ShippingMethod extends StripeJsonModel implements Parcelable { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); putLongIfNotNull(jsonObject, FIELD_AMOUNT, mAmount); putStringIfNotNull(jsonObject, FIELD_CURRENCY_CODE, mCurrencyCode); putStringIfNotNull(jsonObject, FIELD_DETAIL, mDetail); putStringIfNotNull(jsonObject, FIELD_IDENTIFIER, mIdentifier); putStringIfNotNull(jsonObject, FIELD_LABEL, mLabel); return jsonObject; } ShippingMethod(@NonNull String label,
@NonNull String identifier,
@NonNull long amount,
@NonNull @Size(min=0, max=3) String currencyCode); ShippingMethod(@NonNull String label,
@NonNull String identifier,
@Nullable String detail,
@NonNull long amount,
@NonNull @Size(min=0, max=3) String currencyCode); private ShippingMethod(Parcel in); @NonNull Currency getCurrency(); long getAmount(); @NonNull String getLabel(); @Nullable String getDetail(); @NonNull String getIdentifier(); @NonNull @Override JSONObject toJson(); @NonNull @Override Map<String, Object> toMap(); @Override int describeContents(); @Override void writeToParcel(Parcel parcel, int i); static final Parcelable.Creator<ShippingMethod> CREATOR; }### Answer:
@Test public void testJSONConversion() { try { JSONObject rawConversion = new JSONObject(EXAMPLE_JSON_SHIPPING_ADDRESS); assertJsonEquals(mShippingMethod.toJson(), rawConversion); } catch (JSONException jsonException) { fail("Test Data failure: " + jsonException.getLocalizedMessage()); } } |
### Question:
ShippingMethod extends StripeJsonModel implements Parcelable { @NonNull @Override public Map<String, Object> toMap() { Map<String, Object> map = new HashMap<>(); map.put(FIELD_AMOUNT, mAmount); map.put(FIELD_CURRENCY_CODE, mCurrencyCode); map.put(FIELD_DETAIL, mDetail); map.put(FIELD_IDENTIFIER, mIdentifier); map.put(FIELD_LABEL, mLabel); return map; } ShippingMethod(@NonNull String label,
@NonNull String identifier,
@NonNull long amount,
@NonNull @Size(min=0, max=3) String currencyCode); ShippingMethod(@NonNull String label,
@NonNull String identifier,
@Nullable String detail,
@NonNull long amount,
@NonNull @Size(min=0, max=3) String currencyCode); private ShippingMethod(Parcel in); @NonNull Currency getCurrency(); long getAmount(); @NonNull String getLabel(); @Nullable String getDetail(); @NonNull String getIdentifier(); @NonNull @Override JSONObject toJson(); @NonNull @Override Map<String, Object> toMap(); @Override int describeContents(); @Override void writeToParcel(Parcel parcel, int i); static final Parcelable.Creator<ShippingMethod> CREATOR; }### Answer:
@Test public void testMapCreation() { assertMapEquals(mShippingMethod.toMap(), EXAMPLE_MAP_SHIPPING_ADDRESS); } |
### Question:
StripeJsonUtils { @Nullable static String nullIfNullOrEmpty(@Nullable String possibleNull) { return NULL.equals(possibleNull) || EMPTY.equals(possibleNull) ? null : possibleNull; } }### Answer:
@Test public void nullIfNullOrEmpty_returnsNullForNull() { assertNull(StripeJsonUtils.nullIfNullOrEmpty("null")); }
@Test public void nullIfNullOrEmpty_returnsNullForEmpty() { assertNull(StripeJsonUtils.nullIfNullOrEmpty("")); }
@Test public void nullIfNullOrEmpty_returnsInputIfNotNull() { final String notANull = "notANull"; assertEquals(notANull, StripeJsonUtils.nullIfNullOrEmpty(notANull)); } |
### Question:
Token implements StripePaymentSource { @Nullable public static Token fromString(@Nullable String jsonString) { try { JSONObject tokenObject = new JSONObject(jsonString); return fromJson(tokenObject); } catch (JSONException exception) { return null; } } Token(
String id,
boolean livemode,
Date created,
Boolean used,
Card card); Token(
String id,
boolean livemode,
Date created,
Boolean used,
BankAccount bankAccount); Token(
String id,
boolean livemode,
Date created,
Boolean used
); Date getCreated(); @Override String getId(); boolean getLivemode(); boolean getUsed(); @TokenType String getType(); Card getCard(); BankAccount getBankAccount(); @Nullable static Token fromString(@Nullable String jsonString); @Nullable static Token fromJson(@Nullable JSONObject jsonObject); static final String TYPE_CARD; static final String TYPE_BANK_ACCOUNT; static final String TYPE_PII; }### Answer:
@Test public void parseToken_withoutId_returnsNull() { Token token = Token.fromString(RAW_TOKEN_NO_ID); assertNull(token); }
@Test public void parseToken_withoutType_returnsNull() { Token token = Token.fromString(RAW_BANK_TOKEN_NO_TYPE); assertNull(token); } |
### Question:
DragAndDropQuestion extends AbstractQuestion { public Element asXML() { Element element = new Element("DragAndDropQuestion"); element.setAttribute("reuseFragments", Boolean.toString(reuseFragments)); ReadableElement questionTextElement = new ReadableElement("QuestionText"); questionTextElement.setText(questionText); ReadableElement explanationTextElement = new ReadableElement("ExplanationText"); explanationTextElement.setText(explanationText); Element fragmentListElement = new Element("ExtraFragments"); for (String fragment : extraFragments) { ReadableElement fragmentElement = new ReadableElement("Fragment"); fragmentElement.setText(fragment); fragmentListElement.addContent(fragmentElement); } element.addContent(questionTextElement); element.addContent(fragmentListElement); element.addContent(explanationTextElement); return element; } DragAndDropQuestion(String questionText, String explanationText, List<String> extraFragments,
boolean reuseFragments); DragAndDropQuestion(Element element); @Override String getQuestionTypeName(); Element asXML(); List<String> getFragments(); List<String> getExtraFragments(); List<String> getCorrectFragments(); boolean canReuseFragments(); int largestFragmentWidth(); @Override int hashCode(); @Override boolean equals(Object obj); boolean isAnswered(Answer generalAnswer); Answer initialAnswer(); boolean isCorrect(Answer answer); }### Answer:
@Test public void toXmlAndBackAgainShouldProduceSameQuestion() throws Exception { List<String> extraFragments = Arrays.asList("Wibble", "Wobble"); String questionText = "Question <slot>foo</slot> more question <slot>bar</slot>"; String explanationText = "Explanation <slot>foo</slot> more question <slot>bar</slot>"; boolean reuseFragments = false; DragAndDropQuestion dragAndDropQuestion = new DragAndDropQuestion(questionText, explanationText, extraFragments, reuseFragments); assertEquals(dragAndDropQuestion, new DragAndDropQuestion(dragAndDropQuestion.asXML())); } |
### Question:
Option implements Serializable { public Element asXML() { ReadableElement element = new ReadableElement(XML_TAG_OPTION); element.setAttribute(XML_ATTRIBUTE_CORRECT, Boolean.toString(correct)); element.setText(optionText); return element; } Option(String optionText, boolean correct, int id); Option(Element element, int id); Element asXML(); String getOptionText(); boolean isCorrect(); int getId(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer:
@Test public void toXmlAndBackAgainShouldProduceSameOption() throws Exception { assertEquals(optionTrue, new Option(optionTrue.asXML(), 1)); assertEquals(optionFalse, new Option(optionFalse.asXML(), 2)); } |
### Question:
MultipleChoiceQuestion extends AbstractQuestion { public int numberOfCorrectOptions() { int count = countCorrectOptions(options); return count; } MultipleChoiceQuestion(String questionText, String explanationText, List<Option> options,
boolean shufflable, boolean singleOptionMode); List<Option> getOptions(); int numberOfCorrectOptions(); static int countCorrectOptions(List<Option> localOptions); int numberOfOptions(); boolean isShufflable(); boolean isSingleOptionMode(); boolean isCorrect(Answer generalAnswer); boolean isAnswered(Answer generalAnswer, boolean numberOfOptionsNeededIsShown); @Override String getQuestionTypeName(); @Override int hashCode(); @Override boolean equals(Object obj); MultipleChoiceAnswer initialAnswer(); }### Answer:
@Test public void shouldReturnCorrectNumberOfOptions() { assertEquals(2, multipleOptionModeQuestion.numberOfCorrectOptions()); } |
### Question:
AbstractQuestion implements Serializable, Question { public String getSubstitutedExplanationText() { return substituteExplanationText(questionText, explanationText); } protected AbstractQuestion(String questionText, String explanationText); protected AbstractQuestion(); static String removeCopyToExplanationBlocks(String questionText); String getQuestionText(); String getSubstitutedQuestionText(); String getExplanationText(); abstract String getQuestionTypeName(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); String getSubstitutedExplanationText(); static String substituteExplanationText(String questionText, String explanationText); }### Answer:
@Test public void shouldCopyAcrossFromQuestionToExplanation() throws Exception { String substitutedExplanationText = exampleQuestion.getSubstitutedExplanationText(); assertEquals("Explanation stuff to copy end of explanation", substitutedExplanationText); } |
### Question:
PlacesClient extends AbstractClient { public Request searchAsync(@NonNull PlacesQuery params, @NonNull CompletionHandler completionHandler) { final PlacesQuery paramsCopy = new PlacesQuery(params); return new AsyncTaskRequest(completionHandler) { @Override protected @NonNull JSONObject run() throws AlgoliaException { return search(paramsCopy); } }.start(); } PlacesClient(@NonNull String applicationID, @NonNull String apiKey); PlacesClient(); Request searchAsync(@NonNull PlacesQuery params, @NonNull CompletionHandler completionHandler); JSONObject getByObjectID(@NonNull String objectID); }### Answer:
@Test public void searchAsync() throws Exception { PlacesQuery query = new PlacesQuery(); query.setQuery("Paris"); query.setType(PlacesQuery.Type.CITY); query.setHitsPerPage(10); query.setAroundLatLngViaIP(false); query.setAroundLatLng(new PlacesQuery.LatLng(32.7767, -96.7970)); query.setLanguage("en"); query.setCountries("fr", "us"); places.searchAsync(query, new AssertCompletionHandler() { @Override public void doRequestCompleted(JSONObject content, AlgoliaException error) { if (error != null) { fail(error.getMessage()); } assertNotNull(content); assertNotNull(content.optJSONArray("hits")); assertTrue(content.optJSONArray("hits").length() > 0); } }); } |
### Question:
PlacesClient extends AbstractClient { public JSONObject getByObjectID(@NonNull String objectID) throws AlgoliaException { return getRequest("/1/places/" + objectID, null, false, null) ; } PlacesClient(@NonNull String applicationID, @NonNull String apiKey); PlacesClient(); Request searchAsync(@NonNull PlacesQuery params, @NonNull CompletionHandler completionHandler); JSONObject getByObjectID(@NonNull String objectID); }### Answer:
@Test public void getByObjectIDValid() throws Exception { final JSONObject rivoli = places.getByObjectID(OBJECT_ID_RUE_RIVOLI); assertNotNull(rivoli); assertEquals(OBJECT_ID_RUE_RIVOLI, rivoli.getString("objectID")); }
@Test(expected = AlgoliaException.class) public void getByObjectIDInvalid() throws Exception { places.getByObjectID("4242424242"); } |
### Question:
UriBuilder { public static String buildUriString(String tokenContractAddress, String iabContractAddress, BigDecimal amount, String developerAddress, String skuId, int networkId) { StringBuilder stringBuilder = new StringBuilder(4); try (Formatter formatter = new Formatter(stringBuilder)) { formatter.format("ethereum:%s@%d/buy?uint256=%s&address=%s&data=%s&iabContractAddress=%s", tokenContractAddress, networkId, amount.toString(), developerAddress, "0x" + Hex.toHexString(skuId.getBytes("UTF-8")), iabContractAddress); } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 not supported!", e); } return stringBuilder.toString(); } private UriBuilder(); static String buildUriString(String tokenContractAddress, String iabContractAddress,
BigDecimal amount, String developerAddress, String skuId, int networkId); }### Answer:
@Test public void buildUriString() { String uriString = UriBuilder. buildUriString(tokenContractAddress, iabContractAddress, new BigDecimal("1000000000000000000"), developerAddress, "com.cenas.product", 3); Assert.assertThat(uriString, is("ethereum:0xab949343E6C369C6B17C7ae302c1dEbD4B7B61c3@3/buy?uint256=1000000000000000000&address=0x4fbcc5ce88493c3d9903701c143af65f54481119&data=0x636f6d2e63656e61732e70726f64756374&iabContractAddress=0xb015D9bBabc472BBfC990ED6A0C961a90a482C57")); } |
### Question:
TransactionFactory { static String extractValueFromEthGetTransactionReceipt(String data) { if (data.startsWith("0x")) { data = data.substring(2); } return decodeInt(Hex.decode(data), 0).toString(); } private TransactionFactory(); static Transaction fromEthGetTransactionReceipt(
EthGetTransactionReceipt ethGetTransactionReceipt); static Transaction fromEthTransaction(EthTransaction ethTransaction, Status status); static BigInteger decodeInt(byte[] encoded, int offset); }### Answer:
@Test public void extractValueFromEthGetTransactionReceipt() { String s = TransactionFactory.extractValueFromEthGetTransactionReceipt(valueHex); assertThat(s, is("1000000000000000000")); } |
### Question:
ByteUtils { public static byte[] prependZeros(byte[] arr, int size) { if (arr.length > size) { throw new IllegalArgumentException("Size cannot be bigger than array size!"); } byte[] bytes = new byte[size]; System.arraycopy(arr, 0, bytes, (bytes.length - arr.length), arr.length); return bytes; } private ByteUtils(); static byte[] prependZeros(byte[] arr, int size); static byte[] concat(byte[]... arrays); }### Answer:
@Test public void prependZeros() { byte[] bytes = new byte[2]; bytes[0] = 'a'; bytes[1] = 'b'; byte[] expected = new byte[8]; expected[6] = 'a'; expected[7] = 'b'; assertArrayEquals(expected, ByteUtils.prependZeros(bytes, 8)); } |
### Question:
ByteUtils { public static byte[] concat(byte[]... arrays) { int count = 0; for (byte[] array : arrays) { count += array.length; } byte[] mergedArray = new byte[count]; int start = 0; for (byte[] array : arrays) { System.arraycopy(array, 0, mergedArray, start, array.length); start += array.length; } return mergedArray; } private ByteUtils(); static byte[] prependZeros(byte[] arr, int size); static byte[] concat(byte[]... arrays); }### Answer:
@Test public void concat() { byte[] b1 = "a".getBytes(); byte[] b2 = "b".getBytes(); byte[] expected = "ab".getBytes(); assertArrayEquals(expected, ByteUtils.concat(b1, b2)); } |
### Question:
Address extends ByteArray { public static Address from(byte[] address) { return new Address(new ByteArray(address)); } Address(ByteArray byteArray); static Address from(byte[] address); static Address from(String address); @Override String toString(); }### Answer:
@Test public void from() { String hexStr = "795c64c6eee9164539d679354f349779a04f57cb"; byte[] addressBytes = new BigInteger( "111100101011100011001001100011011101110111010010001011001000101001110011101011001111001001101010100111100110100100101110111100110100000010011110101011111001011", 2).toByteArray(); Address address; address = Address.from(hexStr); assertThat(address.toHexString(), is(hexStr)); address = Address.from(addressBytes); assertThat(address.toHexString(), is(hexStr)); } |
### Question:
ByteArray { public static ByteArray from(String hex) { if (hex.startsWith("0x")) { return new ByteArray(Hex.decode(hex.substring(2))); } else { return new ByteArray(Hex.decode(hex)); } } ByteArray(byte[] bytes); static ByteArray from(String hex); final String toHexString(); final String toHexString(boolean withPrefix); final byte[] getBytes(); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object o); }### Answer:
@Test public void from() { ByteArray from = ByteArray.from("795c64c6eee9164539d679354f349779a04f57cb"); assertThat(from, is(byteArray)); } |
### Question:
ByteArray { public final String toHexString() { return toHexString(false); } ByteArray(byte[] bytes); static ByteArray from(String hex); final String toHexString(); final String toHexString(boolean withPrefix); final byte[] getBytes(); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object o); }### Answer:
@Test public void toHexString() { assertThat(byteArray.toHexString(), is("795c64c6eee9164539d679354f349779a04f57cb")); }
@Test public void toHexStringWithFlag() { assertThat(byteArray.toHexString(true), is("0x795c64c6eee9164539d679354f349779a04f57cb")); assertThat(byteArray.toHexString(false), is("795c64c6eee9164539d679354f349779a04f57cb")); } |
### Question:
ByteArray { public final byte[] getBytes() { return bytes; } ByteArray(byte[] bytes); static ByteArray from(String hex); final String toHexString(); final String toHexString(boolean withPrefix); final byte[] getBytes(); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object o); }### Answer:
@Test public void getBytes() { assertThat(byteArray.getBytes(), is(bytes)); } |
### Question:
TransactionFactory { static String extractValueFromEthTransaction(String input) { String valueHex = input.substring(input.length() - ((256 >> 2))); BigInteger value = decodeInt(Hex.decode(valueHex), 0); return value.toString(); } private TransactionFactory(); static Transaction fromEthGetTransactionReceipt(
EthGetTransactionReceipt ethGetTransactionReceipt); static Transaction fromEthTransaction(EthTransaction ethTransaction, Status status); static BigInteger decodeInt(byte[] encoded, int offset); }### Answer:
@Test public void extractValueFromEthTransaction() { String s = TransactionFactory.extractValueFromEthTransaction(input); assertThat(s, is(Long.toString((long) (1 * Math.pow(10, 18))))); } |
### Question:
TransactionFactory { static String extractToFromEthTransaction(String input) { String valueHex = input.substring(10, input.length() - ((256 >> 2))); Address address = new Address(decodeInt(Hex.decode(valueHex), 0)); return address.toString(); } private TransactionFactory(); static Transaction fromEthGetTransactionReceipt(
EthGetTransactionReceipt ethGetTransactionReceipt); static Transaction fromEthTransaction(EthTransaction ethTransaction, Status status); static BigInteger decodeInt(byte[] encoded, int offset); }### Answer:
@Test public void extractToFromEthTransaction() { String s = TransactionFactory.extractToFromEthTransaction(input); assertThat(s, is(address)); } |
### Question:
GenerateMojo extends AbstractMojo { List<String> getPackages() { return packages; } void execute(); }### Answer:
@Test public void testBasic() throws Exception { File basedir = resources.getBasedir("basic"); GenerateMojo generate = (GenerateMojo) maven.lookupConfiguredMojo(maven.newMavenSession(maven.readMavenProject(basedir)), maven.newMojoExecution("generate")); assertThat(generate.getPackages()).containsOnly("com.test.model"); }
@Test public void testFull() throws Exception { File basedir = resources.getBasedir("full"); GenerateMojo generate = (GenerateMojo) maven.lookupConfiguredMojo(maven.newMavenSession(maven.readMavenProject(basedir)), maven.newMojoExecution("generate")); assertThat(generate.getPackages()).containsOnly("com.test.model", "com.test.entities"); } |
### Question:
FileResolver { static List<Path> resolveExistingMigrations(File migrationsDir, boolean reversed, boolean onlySchemaMigrations) { if (!migrationsDir.exists()) { migrationsDir.mkdirs(); } File[] files = migrationsDir.listFiles(); if (files == null) { return Collections.emptyList(); } Comparator<Path> pathComparator = Comparator.comparingLong(FileResolver::compareVersionedMigrations); if (reversed) { pathComparator = pathComparator.reversed(); } return Arrays.stream(files) .map(File::toPath) .filter(path -> !onlySchemaMigrations || SCHEMA_FILENAME_PATTERN.matcher(path.getFileName().toString()).matches()) .sorted(pathComparator) .collect(Collectors.toList()); } }### Answer:
@Test public void shouldReturnExistingMigrations() throws Exception { File migrationsDir = tempFolder.newFolder(); Path first = migrationsDir.toPath().resolve("v1__jpa2ddl_init.sql"); first.toFile().createNewFile(); Path second = migrationsDir.toPath().resolve("v2__my_description.sql"); second.toFile().createNewFile(); Path third = migrationsDir.toPath().resolve("v3__jpa2ddl.sql"); third.toFile().createNewFile(); List<Path> file = FileResolver.resolveExistingMigrations(migrationsDir, false, true); assertThat(file).containsSequence( first, third ); } |
### Question:
FileResolver { static File resolveNextMigrationFile(File migrationDir) { Optional<Path> lastFile = resolveExistingMigrations(migrationDir, true, false) .stream() .findFirst(); Long fileIndex = lastFile.map((Path input) -> FILENAME_PATTERN.matcher(input.getFileName().toString())) .map(matcher -> { if (matcher.find()) { return Long.valueOf(matcher.group(1)); } else { return 0L; } }).orElse(0L); return migrationDir.toPath().resolve("v" + ++fileIndex + "__jpa2ddl.sql").toFile(); } }### Answer:
@Test public void shouldResolveFirstMigration() throws Exception { File migrationsDir = tempFolder.newFolder(); File file = FileResolver.resolveNextMigrationFile(migrationsDir); assertThat(file.toPath()).isEqualTo(migrationsDir.toPath().resolve("v1__jpa2ddl.sql")); }
@Test public void shouldResolveNextMigration() throws Exception { File migrationsDir = tempFolder.newFolder(); migrationsDir.toPath().resolve("v1__jpa2ddl.sql").toFile().createNewFile(); migrationsDir.toPath().resolve("v2__my_description.sql").toFile().createNewFile(); File file = FileResolver.resolveNextMigrationFile(migrationsDir); assertThat(file.toPath()).isEqualTo(migrationsDir.toPath().resolve("v3__jpa2ddl.sql")); } |
### Question:
IPNMessageParser { public IPNMessage parse() { IPNMessage.Builder builder = new IPNMessage.Builder(nvp); if(validated) builder.validated(); for(Map.Entry<String, String> param : nvp.entrySet()) { addVariable(builder, param); } return builder.build(); } IPNMessageParser(Map<String, String> nvp, boolean validated); IPNMessage parse(); }### Answer:
@Test public void testUnknownTransactionType() throws Exception { final Map<String, String> nvp = new HashMap<String, String>(); nvp.put("txn_type", "unknown"); parser = new IPNMessageParser(nvp, true); final IPNMessage message = parser.parse(); assertThat(message.getTransactionType(), nullValue()); } |
### Question:
Urls { @Nonnull public static URI createURI(@Nonnull String fullUrl) { String escaped = escape(fullUrl); try { return new URI(escaped); } catch (URISyntaxException e) { throw new AssertionError(e); } } private Urls(); @Nonnull static URI createURI(@Nonnull String fullUrl); @Nonnull static String escape(@Nonnull String url); static UrlBuilder http(String host); static UrlBuilder https(String host); @Nonnull static Url parse(String url); }### Answer:
@Test public void createURI() { assertEquals("http: assertEquals("http: assertEquals("http: assertEquals("http: assertEquals("https: assertEquals("https: assertEquals("https: assertEquals("http: assertEquals("http: assertEquals("http: assertEquals("http: }
@Test public void createURIHost() { String expected = "http: String input = "http: assertEquals(expected, Urls.createURI(input).toString()); assertEquals("http: assertEquals("http: assertEquals("http: assertEquals("http: assertEquals("http: assertEquals("http: assertEquals("http: assertEquals("http: }
@Test public void createURIBackSlashes() { assertEquals("http: Urls.createURI("http:\\\\host\\path\\?q=\\#\\").toString()); }
@Test public void createURIPort() { assertEquals("http: }
@Test public void createURIPath() { assertEquals("http: assertEquals("http: } |
### Question:
PercentDecoder { public static String decodeAll(String str) { return decode(str, CodepointMatcher.ALL); } private PercentDecoder(); static String decodeAll(String str); static String decodeUnreserved(String str); }### Answer:
@Test public void allAscii() { StringBuilder expected = new StringBuilder(); StringBuilder encoded = new StringBuilder(); for (char c = 0; c < 0x80; c++) { expected.append(c); encoded.append(percentEncode(c)); } assertEquals(expected.toString(), PercentDecoder.decodeAll(encoded.toString())); }
@Test public void decodingSafelyHandlesMalformedPercents() { assertSame("%zz", PercentDecoder.decodeAll("%zz")); assertSame("%3", PercentDecoder.decodeAll("%3")); assertSame("%3z", PercentDecoder.decodeAll("%3z")); assertSame("%", PercentDecoder.decodeAll("%")); assertSame("%%2", PercentDecoder.decodeAll("%%2")); assertSame("%2%", PercentDecoder.decodeAll("%2%")); } |
### Question:
PercentDecoder { public static String decodeUnreserved(String str) { return decode(str, CodepointMatcher.UNRESERVED); } private PercentDecoder(); static String decodeAll(String str); static String decodeUnreserved(String str); }### Answer:
@Test public void allAsciiUnreserved() { StringBuilder expected = new StringBuilder(); StringBuilder encoded = new StringBuilder(); for (char c = 0; c < 0x80; c++) { String percent = percentEncode(c); if (".-_~".indexOf(c) > -1 || CodepointMatcher.ALPHANUMERIC.matches(c)) { expected.append(c); } else { expected.append(percent); } encoded.append(percent); } assertEquals(expected.toString(), PercentDecoder.decodeUnreserved(encoded.toString())); } |
### Question:
Strings { public static int[] codePoints(String s) { int length = s.length(); int arrayPointer = 0; int stringPointer = 0; int[] codepoints = new int[length]; while (stringPointer < length) { int codepoint = s.codePointAt(stringPointer); codepoints[arrayPointer++] = codepoint; stringPointer += Character.charCount(codepoint); } return arrayPointer == stringPointer ? codepoints : Arrays.copyOf(codepoints, arrayPointer); } private Strings(); static int[] codePoints(String s); static boolean isNullOrEmpty(String s); static String nullToEmpty(String value); static String sanitizeWhitespace(String str); }### Answer:
@Test public void codepoints() { assertArrayEquals(new int[]{65536}, Strings.codePoints("\uD800\uDC00")); assertArrayEquals(new int[]{9731}, Strings.codePoints("☃")); } |
### Question:
Strings { public static boolean isNullOrEmpty(String s) { return s == null || s.isEmpty(); } private Strings(); static int[] codePoints(String s); static boolean isNullOrEmpty(String s); static String nullToEmpty(String value); static String sanitizeWhitespace(String str); }### Answer:
@Test public void isNullOrEmpty() { assertTrue(Strings.isNullOrEmpty(null)); assertTrue(Strings.isNullOrEmpty("")); assertFalse(Strings.isNullOrEmpty("a")); } |
### Question:
Ip4 implements Host { @Nullable static Ip4 parse(String hostname) { String[] segments = hostname.split("\\."); if (segments.length != 4) { return null; } byte[] addr = new byte[4]; for (int i = 0; i < segments.length; i++) { int val; String segment = segments[i]; if (segment.length() > 1 && segment.startsWith("0")) { return null; } try { val = Integer.parseInt(segment); } catch (NumberFormatException e) { return null; } if (val < 0 || val > 255) { return null; } addr[i] = (byte) val; } return fromAddress(addr); } }### Answer:
@Test public void removeTrailingPeriod() { assertEquals("255.255.255.255", Hosts.parse("255.255.255.255.").name()); }
@Test public void percentDecodeBeforeParsing() { assertEquals("1.1.1.1", Hosts.parse("%31.%31.%31.%31").name()); assertEquals("1.1.1.1", Hosts.parse("1%2e1%2e1%2e1").name()); }
@Test public void disambiguateUnicodeFirst() { assertEquals("1.1.1.1", Hosts.parse("1。1。1。1").name()); }
@Test public void ipv4() { assertEquals("1.1.1.1", Hosts.parse("1.1.1.1").name()); assertEquals("0.0.0.1", Hosts.parse("0.0.0.1").name()); assertEquals("0.0.0.0", Hosts.parse("0.0.0.0").name()); assertEquals("255.255.255.255", Hosts.parse("255.255.255.255").name()); } |
### Question:
Authority { public static Authority split(String authority) { int lastColon = -1; int numColons = 0; int start = authority.length(); int end = authority.length(); int port = -1; while (--start >= 0) { char b = authority.charAt(start); if (b == '@') { break; } else if (b == ':') { if (numColons++ == 0) { lastColon = start; } } } start++; if (start == end || start == lastColon) { throw new IllegalArgumentException("URL missing host. Input: " + authority); } if (numColons == 1) { port = parseAndValidatePort(authority, lastColon); end = lastColon; } else if (numColons > 1) { if (authority.charAt(lastColon - 1) == ']') { port = parseAndValidatePort(authority, lastColon); end = lastColon; } } return new AutoValue_Authority(port, Hosts.parse(authority.substring(start, end))); } abstract int port(); abstract Host host(); static Authority split(String authority); @Override String toString(); }### Answer:
@Test public void supportUnicodePeriods() { assertEquals("host.com", Authority.split("host。com").host().display()); assertEquals("host.com", Authority.split("host.com").host().display()); assertEquals("host.com", Authority.split("host。com").host().display()); } |
### Question:
Dns implements Host { static Dns parse(String hostname) { int lastDot = -1; for (int i = 0; i < hostname.length(); i++) { char c = hostname.charAt(i); if (!DNS.matches(c)) { throw new InvalidHostException(hostname, i); } else if (c == '.') { if (lastDot == i - 1) { throw new InvalidHostException(hostname, i); } lastDot = i; } } String lower = hostname.toLowerCase(Locale.US); return new AutoValue_Dns(lower, IDN.toUnicode(lower)); } }### Answer:
@Test public void convertToLowerCase() { assertEquals(Dns.parse("example.com"), Dns.parse("EXAMPLE.com")); } |
### Question:
Hosts { @Nonnull static Host parse(String hostname) { String ascii = validateAndConvertToAscii(hostname); Host host; if (Ip6.isIpv6(ascii)) { host = Ip6.parse(ascii); } else { if (ascii.endsWith(".")) { ascii = ascii.substring(0, ascii.length() - 1); } if (Ip4.isIpv4(ascii)) { host = Ip4.parse(ascii); } else { host = Dns.parse(ascii); } } if (host == null) { throw new IllegalArgumentException("Invalid hostname: " + hostname); } return host; } }### Answer:
@Test public void allowTrailingDot() { assertEquals(Hosts.parse("example.com"), Hosts.parse("example.com.")); assertEquals(Hosts.parse("example"), Hosts.parse("example.")); assertEquals(Hosts.parse("1.1.1.1"), Hosts.parse("1.1.1.1.")); }
@Test public void convertToLowerCase() { assertEquals(Hosts.parse("example.com"), Hosts.parse("Example.com")); assertEquals(Hosts.parse("ökonom.de"), Hosts.parse("Ökonom.de")); assertEquals(Hosts.parse("ли.ru"), Hosts.parse("Ли.ru")); } |
### Question:
OpenIBANValidationClient extends RestGatewaySupport implements IBANValidationClient { @Override public IBANValidationResult validate(String iban) { return getRestTemplate().getForObject(URL_TEMPLATE, IBANValidationResult.class, iban); } @Override IBANValidationResult validate(String iban); }### Answer:
@Test public void validIban() { mockRestServiceServer .expect(requestTo("https: .andRespond(withSuccess(new ClassPathResource("NL87TRIO0396451440-result.json"), MediaType.APPLICATION_JSON)); IBANValidationResult result = client.validate("NL87TRIO0396451440"); assertTrue(result.isValid()); }
@Test public void invalidIban() { mockRestServiceServer .expect(requestTo("https: .andRespond(withSuccess(new ClassPathResource("NL28XXXX389242218-result.json"), MediaType.APPLICATION_JSON)); IBANValidationResult result = client.validate("NL28XXXX389242218"); assertFalse(result.isValid()); } |
### Question:
CliRScriptEngine extends AbstractScriptEngine { @Override public Object eval (String script, ScriptContext context) throws ScriptException { return eval (new StringReader (script), context); } @Override Object eval(String script, ScriptContext context); @Override Object eval(Reader reader, ScriptContext context); @Override Bindings createBindings(); @Override ScriptEngineFactory getFactory(); }### Answer:
@Test public void helloWorld () throws ScriptException { r.eval ("cat('hello world\\n')"); } |
### Question:
DataSubset extends AbstractDataset implements Dataset { @Override public Values values () { return new ValuesSubset (parent.values (), columns.keys (), rows.keys (), false); } @SneakyThrows(value = {InvalidDimensionTypeException.class}) DataSubset(String name, Dataset parent, List<String> columns, List<String> rows); @SneakyThrows({InvalidDimensionTypeException.class}) DataSubset(Dataset parent, List<String> columns, List<String> rows); @Override Values values(); @Override Dimension dimension(Type type); @Override void set(Dimension dimension); @Override Analyses analyses(); @Override void exportSelection(String name,
Type dimension,
String selection,
Workspace workspace,
DatasetBuilder datasetBuilder); @Override void close(); }### Answer:
@Test public void testValues () throws InvalidCoordinateException { assertThat(subset.values ().get ("g2", "sb"), equalTo (2.2)); assertThat(subset.values ().get ("g2", "sc"), equalTo (2.3)); assertThat(subset.values ().get ("g3", "sb"), equalTo (3.2)); assertThat(subset.values ().get ("g3", "sc"), equalTo (3.3)); assertThat(subset.values ().skipJson (), equalTo(false)); thrown.expect (InvalidCoordinateException.class); subset.values ().get ("g1", "sa"); thrown.expect (InvalidCoordinateException.class); subset.values ().get ("g1", "sd"); thrown.expect (InvalidCoordinateException.class); subset.values ().get ("g2", "sa"); thrown.expect (InvalidCoordinateException.class); subset.values ().get ("g2", "sd"); thrown.expect (InvalidCoordinateException.class); subset.values ().get ("g3", "sa"); thrown.expect (InvalidCoordinateException.class); subset.values ().get ("g3", "sd"); thrown.expect (InvalidCoordinateException.class); subset.values ().get ("g4", "sa"); thrown.expect (InvalidCoordinateException.class); subset.values ().get ("g4", "sd"); } |
### Question:
GremlinQueryEngine implements QueryEngine<Object> { @Override public QueryResult<Object> query(String statement, Map<String, Object> params) { try { Iterable<Object> result = gremlinExecutor.query(statement, params); return new QueryResultBuilder<Object>(result,resultConverter); } catch (Exception e) { throw new InvalidDataAccessResourceUsageException("Error executing statement " + statement, e); } } GremlinQueryEngine(GraphDatabaseService graphDatabaseService); GremlinQueryEngine(GraphDatabaseService graphDatabaseService, ResultConverter resultConverter); @Override QueryResult<Object> query(String statement, Map<String, Object> params); }### Answer:
@Test @Transactional public void testQueryList() throws Exception { final String queryString = "t = new Table(); [g.v(michael),g.v(david)].each{ n -> n.as('person.name').as('person.age').table(t,['person.name','person.age']){ it.age }{ it.name } >> -1}; t;" ; final Collection<Object> result = IteratorUtil.asCollection(queryEngine.query(queryString, MapUtil.map("michael", idFor(michael), "david", idFor(testTeam.david)))); assertEquals(asList(testTeam.simpleRowFor(michael, "person"), testTeam.simpleRowFor(testTeam.david, "person")), result); } |
### Question:
EntityMapper implements PathMapper<T> { public abstract T mapPath(EntityPath<S,E> entityPath); protected EntityMapper(GraphDatabaseContext graphDatabaseContext); abstract T mapPath(EntityPath<S,E> entityPath); @Override T mapPath(Path path); }### Answer:
@Test @Transactional public void entityMapperShouldForwardEntityPath() throws Exception { Person michael = new Person("Michael", 36).persist(); EntityMapper<Person, Person, String> mapper = new EntityMapper<Person, Person, String>(ctx) { @Override public String mapPath(EntityPath<Person, Person> entityPath) { return entityPath.<Person>startEntity().getName(); } }; String name = mapper.mapPath(new NodePath(michael.getPersistentState())); Assert.assertEquals(michael.getName(), name); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.