method2testcases
stringlengths 118
6.63k
|
---|
### 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 isCvcMaximalLength( @NonNull @Card.CardBrand String cardBrand, @Nullable String cvcText) { if (cvcText == null) { return false; } if (Card.AMERICAN_EXPRESS.equals(cardBrand)) { return cvcText.trim().length() == CVC_LENGTH_AMERICAN_EXPRESS; } else { return cvcText.trim().length() == CVC_LENGTH_COMMON; } } }### Answer:
@Test public void isCvcMaximalLength_whenThreeDigitsAndNotAmEx_returnsTrue() { assertTrue(ViewUtils.isCvcMaximalLength(Card.VISA, "123")); assertTrue(ViewUtils.isCvcMaximalLength(Card.MASTERCARD, "345")); assertTrue(ViewUtils.isCvcMaximalLength(Card.JCB, "678")); assertTrue(ViewUtils.isCvcMaximalLength(Card.DINERS_CLUB, "910")); assertTrue(ViewUtils.isCvcMaximalLength(Card.DISCOVER, "234")); assertTrue(ViewUtils.isCvcMaximalLength(Card.UNKNOWN, "333")); }
@Test public void isCvcMaximalLength_whenThreeDigitsAndIsAmEx_returnsFalse() { assertFalse(ViewUtils.isCvcMaximalLength(Card.AMERICAN_EXPRESS, "123")); }
@Test public void isCvcMaximalLength_whenFourDigitsAndIsAmEx_returnsTrue() { assertTrue(ViewUtils.isCvcMaximalLength(Card.AMERICAN_EXPRESS, "1234")); }
@Test public void isCvcMaximalLength_whenTooManyDigits_returnsFalse() { assertFalse(ViewUtils.isCvcMaximalLength(Card.AMERICAN_EXPRESS, "12345")); assertFalse(ViewUtils.isCvcMaximalLength(Card.VISA, "1234")); assertFalse(ViewUtils.isCvcMaximalLength(Card.MASTERCARD, "123456")); assertFalse(ViewUtils.isCvcMaximalLength(Card.DINERS_CLUB, "1234567")); assertFalse(ViewUtils.isCvcMaximalLength(Card.DISCOVER, "12345678")); assertFalse(ViewUtils.isCvcMaximalLength(Card.JCB, "123456789012345")); }
@Test public void isCvcMaximalLength_whenNotEnoughDigits_returnsFalse() { assertFalse(ViewUtils.isCvcMaximalLength(Card.AMERICAN_EXPRESS, "")); assertFalse(ViewUtils.isCvcMaximalLength(Card.VISA, "1")); assertFalse(ViewUtils.isCvcMaximalLength(Card.MASTERCARD, "12")); assertFalse(ViewUtils.isCvcMaximalLength(Card.DINERS_CLUB, "")); assertFalse(ViewUtils.isCvcMaximalLength(Card.DISCOVER, "8")); assertFalse(ViewUtils.isCvcMaximalLength(Card.JCB, "1")); }
@Test public void isCvcMaximalLength_whenWhitespaceAndNotEnoughDigits_returnsFalse() { assertFalse(ViewUtils.isCvcMaximalLength(Card.AMERICAN_EXPRESS, " ")); assertFalse(ViewUtils.isCvcMaximalLength(Card.VISA, " 1")); }
@Test public void isCvcMaximalLength_whenNull_returnsFalse() { assertFalse(ViewUtils.isCvcMaximalLength(Card.AMERICAN_EXPRESS, null)); } |
### 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:
PaymentUtils { static String formatPriceString(double amount, @NonNull Currency currency) { double majorUnitAmount = amount / Math.pow(10, currency.getDefaultFractionDigits()); NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(); DecimalFormatSymbols decimalFormatSymbols = ((java.text.DecimalFormat) currencyFormat).getDecimalFormatSymbols(); decimalFormatSymbols.setCurrencySymbol(currency.getSymbol(Locale.getDefault())); ((java.text.DecimalFormat) currencyFormat).setDecimalFormatSymbols(decimalFormatSymbols); return currencyFormat.format(majorUnitAmount); } }### Answer:
@Test public void formatPriceString_whenUSLocale_rendersCorrectSymbols() { Locale.setDefault(Locale.US); assertEquals(PaymentUtils.formatPriceString(12300, Currency.getInstance("USD")), "$123.00"); Currency euro = Currency.getInstance(Locale.GERMANY); assertEquals(PaymentUtils.formatPriceString(12300, euro), "EUR123.00"); Currency canadianDollar = Currency.getInstance(Locale.CANADA); assertEquals(PaymentUtils.formatPriceString(12300, canadianDollar), "CAD123.00"); Currency britishPound = Currency.getInstance(Locale.UK); assertEquals(PaymentUtils.formatPriceString(10000, britishPound), "GBP100.00"); }
@Test public void formatPriceString_whenInternationalLocale_rendersCorrectSymbols() { Locale.setDefault(Locale.GERMANY); Currency euro = Currency.getInstance(Locale.GERMANY); assertEquals(PaymentUtils.formatPriceString(10000, euro), "100,00 €"); Locale.setDefault(Locale.JAPAN); Currency yen = Currency.getInstance(Locale.JAPAN); assertEquals(PaymentUtils.formatPriceString(100, yen), "¥100"); Locale.setDefault(new Locale("ar", "JO")); Currency jordanianDinar = Currency.getInstance("JOD"); assertEquals(PaymentUtils.formatPriceString(100123, jordanianDinar), jordanianDinar.getSymbol() + " 100.123"); Locale.setDefault(Locale.UK); Currency britishPound = Currency.getInstance(Locale.UK); assertEquals(PaymentUtils.formatPriceString(10000, britishPound), "£100.00"); Locale.setDefault(Locale.CANADA); Currency canadianDollar = Currency.getInstance(Locale.CANADA); assertEquals(PaymentUtils.formatPriceString(12300, canadianDollar), "$123.00"); }
@Test public void formatPriceString_whenDecimalAmounts_rendersCorrectDigits() { assertEquals(PaymentUtils.formatPriceString(10012, Currency.getInstance("USD")), "$100.12"); assertEquals(PaymentUtils.formatPriceString(12, Currency.getInstance("USD")), "$0.12"); } |
### Question:
ShippingInfoWidget extends LinearLayout { public void setOptionalFields(@Nullable List<String> optionalAddressFields) { if (optionalAddressFields != null) { mOptionalShippingInfoFields = optionalAddressFields; } else { mOptionalShippingInfoFields = 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_whenFieldsOptional_markedAsOptional(){ assertEquals(mPostalCodeTextInputLayout.getHint().toString(), mShippingInfoWidget.getResources().getString(R.string.address_label_zip_code)); assertEquals(mNameTextInputLayout.getHint().toString(), mShippingInfoWidget.getResources().getString(R.string.address_label_name)); List<String> optionalFields = new ArrayList<>(); optionalFields.add(ShippingInfoWidget.POSTAL_CODE_FIELD); mShippingInfoWidget.setOptionalFields(optionalFields); assertEquals(mPostalCodeTextInputLayout.getHint().toString(), mShippingInfoWidget.getResources().getString(R.string.address_label_zip_code_optional)); assertEquals(mNameTextInputLayout.getHint().toString(), mShippingInfoWidget.getResources().getString(R.string.address_label_name)); mCountryAutoCompleteTextView.updateUIForCountryEntered(Locale.CANADA.getDisplayCountry()); assertEquals(mStateTextInputLayout.getHint().toString(), mShippingInfoWidget.getResources().getString(R.string.address_label_province)); optionalFields.add(ShippingInfoWidget.STATE_FIELD); mShippingInfoWidget.setOptionalFields(optionalFields); assertEquals(mStateTextInputLayout.getHint().toString(), mShippingInfoWidget.getResources().getString(R.string.address_label_province_optional)); } |
### 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:
ShippingInfoWidget extends LinearLayout { public ShippingInformation getShippingInformation() { if (!validateAllFields()) { return null; } Address address = new Address.Builder() .setCity(mCityEditText.getText().toString()) .setCountry(mCountryAutoCompleteTextView.getSelectedCountryCode()) .setLine1(mAddressEditText.getText().toString()) .setLine2(mAddressEditText2.getText().toString()) .setPostalCode(mPostalCodeEditText.getText().toString()) .setState(mStateEditText.getText().toString()).build(); ShippingInformation shippingInformation = new ShippingInformation(address,mNameEditText.getText().toString(), mPhoneNumberEditText.getText().toString() ); return shippingInformation; } 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 getShippingInfo_whenShippingInfoInvalid_returnsNull() { assertNull(mShippingInfoWidget.getShippingInformation()); }
@Test public void getShippingInfo_whenShippingInfoValid_returnsExpected() { mStateEditText.setText("CA"); mCityEditText.setText("San Francisco"); mAddressLine1EditText.setText("185 Berry St"); mAddressLine2EditText.setText("10th Floor"); mNameEditText.setText("Fake Name"); mPhoneEditText.setText("(123) 456 - 7890"); mPostalEditText.setText("12345"); mCountryAutoCompleteTextView.updateUIForCountryEntered(Locale.US.getDisplayCountry()); ShippingInformation inputShippingInfo = mShippingInfoWidget.getShippingInformation(); assertEquals(inputShippingInfo.toMap(), mShippingInfo.toMap()); } |
### Question:
ShippingInfoWidget extends LinearLayout { public void populateShippingInfo(@Nullable ShippingInformation shippingInformation) { if (shippingInformation == null) { return; } Address address = shippingInformation.getAddress(); if (address != null) { mCityEditText.setText(address.getCity()); if (address.getCountry() != null && !address.getCountry().isEmpty()) { mCountryAutoCompleteTextView.setCountrySelected(address.getCountry()); } mAddressEditText.setText(address.getLine1()); mAddressEditText2.setText(address.getLine2()); mPostalCodeEditText.setText(address.getPostalCode()); mStateEditText.setText(address.getState()); } mNameEditText.setText(shippingInformation.getName()); mPhoneNumberEditText.setText(shippingInformation.getPhone()); } 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 populateShippingInfo_whenShippingInfoProvided_populates() { mShippingInfoWidget.populateShippingInfo(mShippingInfo); assertEquals(mStateEditText.getText().toString(), "CA"); assertEquals(mCityEditText.getText().toString(), "San Francisco"); assertEquals(mAddressLine1EditText.getText().toString(), "185 Berry St"); assertEquals(mAddressLine2EditText.getText().toString(), "10th Floor"); assertEquals(mPhoneEditText.getText().toString(), "(123) 456 - 7890"); assertEquals(mPostalEditText.getText().toString(), "12345"); assertEquals(mNameEditText.getText().toString(), "Fake Name"); assertEquals(mCountryAutoCompleteTextView.getSelectedCountryCode(), "US"); } |
### 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 setCardInputListener(@Nullable CardInputListener listener) { mCardInputListener = listener; } 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 onCompleteCardNumber_whenValid_shiftsFocusToExpiryDate() { mCardInputWidget.setCardInputListener(mCardInputListener); mCardNumberEditText.setText(VALID_VISA_WITH_SPACES); verify(mCardInputListener, times(1)).onCardComplete(); verify(mCardInputListener, times(1)).onFocusChange(FOCUS_EXPIRY); assertEquals(R.id.et_card_number, mOnGlobalFocusChangeListener.getOldFocusId()); assertEquals(R.id.et_expiry_date, mOnGlobalFocusChangeListener.getNewFocusId()); }
@Test public void onDeleteFromExpiryDate_whenEmpty_shiftsFocusToCardNumberAndDeletesDigit() { mCardInputWidget.setCardInputListener(mCardInputListener); mCardNumberEditText.setText(VALID_VISA_WITH_SPACES); assertTrue(mExpiryEditText.hasFocus()); reset(mCardInputListener); ViewTestUtils.sendDeleteKeyEvent(mExpiryEditText); verify(mCardInputListener, times(1)).onFocusChange(FOCUS_CARD); assertEquals(R.id.et_expiry_date, mOnGlobalFocusChangeListener.getOldFocusId()); assertEquals(R.id.et_card_number, mOnGlobalFocusChangeListener.getNewFocusId()); String subString = VALID_VISA_WITH_SPACES.substring(0, VALID_VISA_WITH_SPACES.length() - 1); assertEquals(subString, mCardNumberEditText.getText().toString()); assertEquals(subString.length(), mCardNumberEditText.getSelectionStart()); }
@Test public void onDeleteFromCvcDate_whenEmpty_shiftsFocusToExpiryAndDeletesDigit() { assertTrue(Calendar.getInstance().get(Calendar.YEAR) < 2080); mCardInputWidget.setCardInputListener(mCardInputListener); mCardNumberEditText.setText(VALID_VISA_WITH_SPACES); verify(mCardInputListener).onCardComplete(); verify(mCardInputListener).onFocusChange(FOCUS_EXPIRY); mExpiryEditText.append("12"); mExpiryEditText.append("79"); verify(mCardInputListener).onExpirationComplete(); verify(mCardInputListener).onFocusChange(FOCUS_CVC); assertTrue(mCvcEditText.hasFocus()); reset(mCardInputListener); ViewTestUtils.sendDeleteKeyEvent(mCvcEditText); verify(mCardInputListener).onFocusChange(FOCUS_EXPIRY); assertEquals(R.id.et_cvc_number, mOnGlobalFocusChangeListener.getOldFocusId()); assertEquals(R.id.et_expiry_date, mOnGlobalFocusChangeListener.getNewFocusId()); String expectedResult = "12/7"; assertEquals(expectedResult, mExpiryEditText.getText().toString()); assertEquals(expectedResult.length(), mExpiryEditText.getSelectionStart()); } |
### Question:
CardInputWidget extends LinearLayout { @NonNull @VisibleForTesting PlacementParameters getPlacementParameters() { return mPlacementParameters; } 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 updateToInitialSizes_returnsExpectedValues() { CardInputWidget.PlacementParameters initialParameters = mCardInputWidget.getPlacementParameters(); assertEquals(190, initialParameters.cardWidth); assertEquals(50, initialParameters.dateWidth); assertEquals(260, initialParameters.cardDateSeparation); assertEquals(380, initialParameters.cardTouchBufferLimit); assertEquals(510, initialParameters.dateStartPosition); }
@Test public void addValidVisaCard_scrollsOver_andSetsExpectedDisplayValues() { mCardNumberEditText.setText(VALID_VISA_WITH_SPACES); CardInputWidget.PlacementParameters shiftedParameters = mCardInputWidget.getPlacementParameters(); assertEquals(40, shiftedParameters.peekCardWidth); assertEquals(185, shiftedParameters.cardDateSeparation); assertEquals(50, shiftedParameters.dateWidth); assertEquals(195, shiftedParameters.dateCvcSeparation); assertEquals(30, shiftedParameters.cvcWidth); }
@Test public void addValidAmExCard_scrollsOver_andSetsExpectedDisplayValues() { mCardNumberEditText.setText(VALID_AMEX_WITH_SPACES); CardInputWidget.PlacementParameters shiftedParameters = mCardInputWidget.getPlacementParameters(); assertEquals(50, shiftedParameters.peekCardWidth); assertEquals(175, shiftedParameters.cardDateSeparation); assertEquals(50, shiftedParameters.dateWidth); assertEquals(185, shiftedParameters.dateCvcSeparation); assertEquals(40, shiftedParameters.cvcWidth); }
@Test public void addDinersClubCard_scrollsOver_andSetsExpectedDisplayValues() { mCardNumberEditText.setText(VALID_DINERS_CLUB_WITH_SPACES); CardInputWidget.PlacementParameters shiftedParameters = mCardInputWidget.getPlacementParameters(); assertEquals(20, shiftedParameters.peekCardWidth); assertEquals(205, shiftedParameters.cardDateSeparation); assertEquals(50, shiftedParameters.dateWidth); assertEquals(195, shiftedParameters.dateCvcSeparation); assertEquals(30, shiftedParameters.cvcWidth); } |
### Question:
CardInputWidget extends LinearLayout { @VisibleForTesting @Nullable StripeEditText getFocusRequestOnTouch(int touchX) { int frameStart = mFrameLayout.getLeft(); if (mCardNumberIsViewed) { if (touchX < frameStart + mPlacementParameters.cardWidth) { return null; } else if (touchX < mPlacementParameters.cardTouchBufferLimit){ return mCardNumberEditText; } else if (touchX < mPlacementParameters.dateStartPosition) { return mExpiryDateEditText; } else { return null; } } else { if (touchX < frameStart + mPlacementParameters.peekCardWidth) { return null; } else if( touchX < mPlacementParameters.cardTouchBufferLimit) { return mCardNumberEditText; } else if (touchX < mPlacementParameters.dateStartPosition) { return mExpiryDateEditText; } else if (touchX < mPlacementParameters.dateStartPosition + mPlacementParameters.dateWidth) { return null; } else if (touchX < mPlacementParameters.dateRightTouchBufferLimit) { return mExpiryDateEditText; } else if (touchX < mPlacementParameters.cvcStartPosition) { return mCvcNumberEditText; } else { return null; } } } 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 getFocusRequestOnTouch_whenTouchOnImage_returnsNull() { assertNull(mCardInputWidget.getFocusRequestOnTouch(30)); }
@Test public void getFocusRequestOnTouch_whenTouchActualCardWidget_returnsNull() { assertNull(mCardInputWidget.getFocusRequestOnTouch(200)); }
@Test public void getFocusRequestOnTouch_whenTouchInCardEditorSlop_returnsCardEditor() { StripeEditText focusRequester = mCardInputWidget.getFocusRequestOnTouch(300); assertNotNull(focusRequester); assertEquals(mCardNumberEditText, focusRequester); }
@Test public void getFocusRequestOnTouch_whenTouchInDateSlop_returnsDateEditor() { StripeEditText focusRequester = mCardInputWidget.getFocusRequestOnTouch(390); assertNotNull(focusRequester); assertEquals(mExpiryEditText, focusRequester); }
@Test public void getFocusRequestOnTouch_whenTouchInDateEditor_returnsNull() { assertNull(mCardInputWidget.getFocusRequestOnTouch(530)); } |
### 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:
CardInputWidget extends LinearLayout { @VisibleForTesting static boolean shouldIconShowBrand( @NonNull @Card.CardBrand String brand, boolean cvcHasFocus, @Nullable String cvcText) { if (!cvcHasFocus) { return true; } return ViewUtils.isCvcMaximalLength(brand, cvcText); } 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 shouldIconShowBrand_whenCvcNotFocused_isAlwaysTrue() { assertTrue(shouldIconShowBrand(Card.AMERICAN_EXPRESS, false, "1234")); assertTrue(shouldIconShowBrand(Card.AMERICAN_EXPRESS, false, "")); assertTrue(shouldIconShowBrand(Card.VISA, false, "333")); assertTrue(shouldIconShowBrand(Card.DINERS_CLUB, false, "12")); assertTrue(shouldIconShowBrand(Card.DISCOVER, false, null)); assertTrue(shouldIconShowBrand(Card.JCB, false, "7")); }
@Test public void shouldIconShowBrand_whenAmexAndCvCStringLengthNotFour_isFalse() { assertFalse(shouldIconShowBrand(Card.AMERICAN_EXPRESS, true, "")); assertFalse(shouldIconShowBrand(Card.AMERICAN_EXPRESS, true, "1")); assertFalse(shouldIconShowBrand(Card.AMERICAN_EXPRESS, true, "22")); assertFalse(shouldIconShowBrand(Card.AMERICAN_EXPRESS, true, "333")); }
@Test public void shouldIconShowBrand_whenAmexAndCvcStringLengthIsFour_isTrue() { assertTrue(shouldIconShowBrand(Card.AMERICAN_EXPRESS, true, "1234")); }
@Test public void shouldIconShowBrand_whenNotAmexAndCvcStringLengthIsNotThree_isFalse() { assertFalse(shouldIconShowBrand(Card.VISA, true, "")); assertFalse(shouldIconShowBrand(Card.DISCOVER, true, "12")); assertFalse(shouldIconShowBrand(Card.JCB, true, "55")); assertFalse(shouldIconShowBrand(Card.MASTERCARD, true, "9")); assertFalse(shouldIconShowBrand(Card.DINERS_CLUB, true, null)); assertFalse(shouldIconShowBrand(Card.UNKNOWN, true, "12")); }
@Test public void shouldIconShowBrand_whenNotAmexAndCvcStringLengthIsThree_isTrue() { assertTrue(shouldIconShowBrand(Card.VISA, true, "999")); assertTrue(shouldIconShowBrand(Card.DISCOVER, true, "123")); assertTrue(shouldIconShowBrand(Card.JCB, true, "555")); assertTrue(shouldIconShowBrand(Card.MASTERCARD, true, "919")); assertTrue(shouldIconShowBrand(Card.DINERS_CLUB, true, "415")); assertTrue(shouldIconShowBrand(Card.UNKNOWN, true, "212")); } |
### 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:
EphemeralKeyManager { static boolean shouldRefreshKey( @Nullable EphemeralKey key, long bufferInSeconds, @Nullable Calendar proxyCalendar) { if (key == null) { return true; } Calendar now = proxyCalendar == null ? Calendar.getInstance() : proxyCalendar; long nowInSeconds = TimeUnit.MILLISECONDS.toSeconds(now.getTimeInMillis()); long nowPlusBuffer = nowInSeconds + bufferInSeconds; return key.getExpires() < nowPlusBuffer; } EphemeralKeyManager(
@NonNull EphemeralKeyProvider ephemeralKeyProvider,
@NonNull KeyManagerListener keyManagerListener,
long timeBufferInSeconds,
@Nullable Calendar overrideCalendar); }### Answer:
@Test public void shouldRefreshKey_whenKeyIsNullAndTimeIsInFuture_returnsTrue() { Calendar futureCalendar = Calendar.getInstance(); futureCalendar.add(Calendar.YEAR, 1); futureCalendar.getTimeInMillis(); assertTrue(EphemeralKeyManager.shouldRefreshKey(null, TEST_SECONDS_BUFFER, futureCalendar)); }
@Test public void shouldRefreshKey_whenKeyIsNullAndTimeIsInPast_returnsTrue() { Calendar pastCalendar = Calendar.getInstance(); pastCalendar.add(Calendar.YEAR, -1); pastCalendar.getTimeInMillis(); assertTrue(EphemeralKeyManager.shouldRefreshKey(null, TEST_SECONDS_BUFFER, pastCalendar)); }
@Test public void shouldRefreshKey_whenKeyExpiryIsAfterBufferFromPresent_returnsFalse() { Calendar fixedCalendar = Calendar.getInstance(); EphemeralKey key = EphemeralKey.fromString(FIRST_SAMPLE_KEY_RAW); assertNotNull(key); long expiryTimeInSeconds = key.getExpires(); long sufficientBufferTime = 2*TEST_SECONDS_BUFFER; key.setExpires(expiryTimeInSeconds + sufficientBufferTime); long expiryTimeInMilliseconds = TimeUnit.SECONDS.toMillis(expiryTimeInSeconds); fixedCalendar.setTimeInMillis(expiryTimeInMilliseconds); assertEquals(expiryTimeInMilliseconds, fixedCalendar.getTimeInMillis()); assertFalse(EphemeralKeyManager.shouldRefreshKey(key, TEST_SECONDS_BUFFER, fixedCalendar)); }
@Test public void shouldRefreshKey_whenKeyExpiryIsInThePast_returnsTrue() { Calendar fixedCalendar = Calendar.getInstance(); EphemeralKey key = EphemeralKey.fromString(FIRST_SAMPLE_KEY_RAW); assertNotNull(key); long currentTimeInMillis = fixedCalendar.getTimeInMillis(); long timeAgoInMillis = currentTimeInMillis - 100L; key.setExpires(TimeUnit.MILLISECONDS.toSeconds(timeAgoInMillis)); assertTrue(EphemeralKeyManager.shouldRefreshKey(key, TEST_SECONDS_BUFFER, fixedCalendar)); }
@Test public void shouldRefreshKey_whenKeyExpiryIsInFutureButWithinBuffer_returnsTrue() { Calendar fixedCalendar = Calendar.getInstance(); EphemeralKey key = EphemeralKey.fromString(FIRST_SAMPLE_KEY_RAW); assertNotNull(key); long parsedExpiryTimeInMillis = TimeUnit.SECONDS.toMillis(key.getExpires()); long bufferTimeInMillis = TimeUnit.SECONDS.toMillis(TEST_SECONDS_BUFFER); long notFarEnoughInTheFuture = parsedExpiryTimeInMillis + bufferTimeInMillis / 2; fixedCalendar.setTimeInMillis(notFarEnoughInTheFuture); assertEquals(notFarEnoughInTheFuture, fixedCalendar.getTimeInMillis()); assertTrue(EphemeralKeyManager.shouldRefreshKey(key, TEST_SECONDS_BUFFER, fixedCalendar)); } |
### 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:
EphemeralKeyManager { void retrieveEphemeralKey(@Nullable String actionString, Map<String, Object> arguments) { if (shouldRefreshKey( mEphemeralKey, mTimeBufferInSeconds, mOverrideCalendar)) { mEphemeralKeyProvider.createEphemeralKey( StripeApiHandler.API_VERSION, new ClientKeyUpdateListener(this, actionString, arguments)); } else { mListener.onKeyUpdate(mEphemeralKey, actionString, arguments); } } EphemeralKeyManager(
@NonNull EphemeralKeyProvider ephemeralKeyProvider,
@NonNull KeyManagerListener keyManagerListener,
long timeBufferInSeconds,
@Nullable Calendar overrideCalendar); }### Answer:
@Test @SuppressWarnings("unchecked") public void retrieveEphemeralKey_whenUpdateNecessary_returnsUpdateAndArguments() { EphemeralKey testKey = EphemeralKey.fromString(FIRST_SAMPLE_KEY_RAW); assertNotNull(testKey); Calendar fixedCalendar = Calendar.getInstance(); long currentTimeInMillis = fixedCalendar.getTimeInMillis(); long timeAgoInMillis = currentTimeInMillis - 100L; testKey.setExpires(TimeUnit.MILLISECONDS.toSeconds(timeAgoInMillis)); mTestEphemeralKeyProvider.setNextRawEphemeralKey(FIRST_SAMPLE_KEY_RAW); EphemeralKeyManager keyManager = new EphemeralKeyManager( mTestEphemeralKeyProvider, mKeyManagerListener, TEST_SECONDS_BUFFER, fixedCalendar); reset(mKeyManagerListener); final String ACTION_STRING = "action"; final Map<String, Object> ACTION_ARGS = new HashMap<>(); ACTION_ARGS.put("key", "value"); keyManager.retrieveEphemeralKey(ACTION_STRING, ACTION_ARGS); ArgumentCaptor<EphemeralKey> keyArgumentCaptor = ArgumentCaptor.forClass(EphemeralKey.class); ArgumentCaptor<String> stringArgumentCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<Map<String, Object>> mapArgumentCaptor = ArgumentCaptor.forClass(Map.class); verify(mKeyManagerListener, times(1)).onKeyUpdate( keyArgumentCaptor.capture(), stringArgumentCaptor.capture(), mapArgumentCaptor.capture()); Map<String, Object> capturedMap = mapArgumentCaptor.getValue(); assertNotNull(capturedMap); assertNotNull(keyArgumentCaptor.getValue()); assertEquals(1, capturedMap.size()); assertEquals("value", capturedMap.get("key")); assertEquals(ACTION_STRING, stringArgumentCaptor.getValue()); } |
### Question:
Stripe { public void setDefaultPublishableKey(@NonNull @Size(min = 1) String publishableKey) { validateKey(publishableKey); mDefaultPublishableKey = publishableKey; } Stripe(@NonNull Context context); Stripe(@NonNull Context context, String publishableKey); void createBankAccountToken(
@NonNull final BankAccount bankAccount,
@NonNull final TokenCallback callback); void createBankAccountToken(
@NonNull final BankAccount bankAccount,
@NonNull @Size(min = 1) final String publishableKey,
@Nullable final Executor executor,
@NonNull final TokenCallback callback); void createPiiToken(
@NonNull final String personalId,
@NonNull final TokenCallback callback); void createPiiToken(
@NonNull final String personalId,
@NonNull @Size(min = 1) final String publishableKey,
@Nullable final Executor executor,
@NonNull final TokenCallback callback); Token createBankAccountTokenSynchronous(final BankAccount bankAccount); Token createBankAccountTokenSynchronous(
final BankAccount bankAccount,
String publishableKey); void createSource(@NonNull SourceParams sourceParams, @NonNull SourceCallback callback); void createSource(
@NonNull SourceParams sourceParams,
@NonNull SourceCallback callback,
@Nullable String publishableKey,
@Nullable Executor executor); void createToken(@NonNull final Card card, @NonNull final TokenCallback callback); void createToken(
@NonNull final Card card,
@NonNull final String publishableKey,
@NonNull final TokenCallback callback); void createToken(
@NonNull final Card card,
@NonNull final Executor executor,
@NonNull final TokenCallback callback); void createToken(
@NonNull final Card card,
@NonNull @Size(min = 1) final String publishableKey,
@Nullable final Executor executor,
@NonNull final TokenCallback callback); @Nullable Source createSourceSynchronous(@NonNull SourceParams params); Source createSourceSynchronous(
@NonNull SourceParams params,
@Nullable String publishableKey); Token createTokenSynchronous(final Card card); Token createTokenSynchronous(final Card card, String publishableKey); Token createPiiTokenSynchronous(@NonNull String personalId); Token createPiiTokenSynchronous(@NonNull String personalId, String publishableKey); void logEventSynchronous(
@NonNull List<String> productUsageTokens,
@NonNull StripePaymentSource paymentSource); Source retrieveSourceSynchronous(
@NonNull @Size(min = 1) String sourceId,
@NonNull @Size(min = 1) String clientSecret); Source retrieveSourceSynchronous(
@NonNull @Size(min = 1) String sourceId,
@NonNull @Size(min = 1) String clientSecret,
@Nullable String publishableKey); void setDefaultPublishableKey(@NonNull @Size(min = 1) String publishableKey); void setStripeAccount(@NonNull @Size(min = 1) String stripeAccount); }### Answer:
@Test(expected = IllegalArgumentException.class) public void setDefaultPublishableKeyShouldFailWhenNull() throws AuthenticationException { Stripe stripe = new Stripe(mContext); stripe.setDefaultPublishableKey(null); }
@Test(expected = IllegalArgumentException.class) public void setDefaultPublishableKeyShouldFailWhenEmpty() throws AuthenticationException { Stripe stripe = new Stripe(mContext); stripe.setDefaultPublishableKey(""); }
@Test(expected = IllegalArgumentException.class) public void setDefaultPublishableKeyShouldFailWithSecretKey() throws AuthenticationException { Stripe stripe = new Stripe(mContext); stripe.setDefaultPublishableKey(DEFAULT_SECRET_KEY); } |
### 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:
Stripe { public Token createBankAccountTokenSynchronous(final BankAccount bankAccount) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return createBankAccountTokenSynchronous(bankAccount, mDefaultPublishableKey); } Stripe(@NonNull Context context); Stripe(@NonNull Context context, String publishableKey); void createBankAccountToken(
@NonNull final BankAccount bankAccount,
@NonNull final TokenCallback callback); void createBankAccountToken(
@NonNull final BankAccount bankAccount,
@NonNull @Size(min = 1) final String publishableKey,
@Nullable final Executor executor,
@NonNull final TokenCallback callback); void createPiiToken(
@NonNull final String personalId,
@NonNull final TokenCallback callback); void createPiiToken(
@NonNull final String personalId,
@NonNull @Size(min = 1) final String publishableKey,
@Nullable final Executor executor,
@NonNull final TokenCallback callback); Token createBankAccountTokenSynchronous(final BankAccount bankAccount); Token createBankAccountTokenSynchronous(
final BankAccount bankAccount,
String publishableKey); void createSource(@NonNull SourceParams sourceParams, @NonNull SourceCallback callback); void createSource(
@NonNull SourceParams sourceParams,
@NonNull SourceCallback callback,
@Nullable String publishableKey,
@Nullable Executor executor); void createToken(@NonNull final Card card, @NonNull final TokenCallback callback); void createToken(
@NonNull final Card card,
@NonNull final String publishableKey,
@NonNull final TokenCallback callback); void createToken(
@NonNull final Card card,
@NonNull final Executor executor,
@NonNull final TokenCallback callback); void createToken(
@NonNull final Card card,
@NonNull @Size(min = 1) final String publishableKey,
@Nullable final Executor executor,
@NonNull final TokenCallback callback); @Nullable Source createSourceSynchronous(@NonNull SourceParams params); Source createSourceSynchronous(
@NonNull SourceParams params,
@Nullable String publishableKey); Token createTokenSynchronous(final Card card); Token createTokenSynchronous(final Card card, String publishableKey); Token createPiiTokenSynchronous(@NonNull String personalId); Token createPiiTokenSynchronous(@NonNull String personalId, String publishableKey); void logEventSynchronous(
@NonNull List<String> productUsageTokens,
@NonNull StripePaymentSource paymentSource); Source retrieveSourceSynchronous(
@NonNull @Size(min = 1) String sourceId,
@NonNull @Size(min = 1) String clientSecret); Source retrieveSourceSynchronous(
@NonNull @Size(min = 1) String sourceId,
@NonNull @Size(min = 1) String clientSecret,
@Nullable String publishableKey); void setDefaultPublishableKey(@NonNull @Size(min = 1) String publishableKey); void setStripeAccount(@NonNull @Size(min = 1) String stripeAccount); }### Answer:
@Test public void createBankAccountTokenSynchronous_withValidBankAccount_returnsToken() { try { Stripe stripe = getNonLoggingStripe(mContext, FUNCTIONAL_PUBLISHABLE_KEY); Token token = stripe.createBankAccountTokenSynchronous(mBankAccount); assertNotNull(token); assertEquals(Token.TYPE_BANK_ACCOUNT, token.getType()); assertNull(token.getCard()); BankAccount returnedBankAccount = token.getBankAccount(); String expectedLast4 = TEST_BANK_ACCOUNT_NUMBER .substring(TEST_BANK_ACCOUNT_NUMBER.length() - 4); assertEquals(expectedLast4, returnedBankAccount.getLast4()); assertEquals(mBankAccount.getCountryCode(), returnedBankAccount.getCountryCode()); assertEquals(mBankAccount.getCurrency(), returnedBankAccount.getCurrency()); assertEquals(mBankAccount.getRoutingNumber(), returnedBankAccount.getRoutingNumber()); } catch (AuthenticationException authEx) { fail("Unexpected error: " + authEx.getLocalizedMessage()); } catch (StripeException stripeEx) { fail("Unexpected error when connecting to Stripe API: " + stripeEx.getLocalizedMessage()); } } |
### 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:
SourceOwner extends StripeJsonModel { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); JSONObject jsonAddressObject = mAddress == null ? null : mAddress.toJson(); JSONObject jsonVerifiedAddressObject = mVerifiedAddress == null ? null : mVerifiedAddress.toJson(); try { if (jsonAddressObject != null && jsonAddressObject.length() > 0) { jsonObject.put(FIELD_ADDRESS, jsonAddressObject); } putStringIfNotNull(jsonObject, FIELD_EMAIL, mEmail); putStringIfNotNull(jsonObject, FIELD_NAME, mName); putStringIfNotNull(jsonObject, FIELD_PHONE, mPhone); if (jsonVerifiedAddressObject != null && jsonVerifiedAddressObject.length() > 0) { jsonObject.put(FIELD_VERIFIED_ADDRESS, jsonVerifiedAddressObject); } putStringIfNotNull(jsonObject, FIELD_VERIFIED_EMAIL, mVerifiedEmail); putStringIfNotNull(jsonObject, FIELD_VERIFIED_NAME, mVerifiedName); putStringIfNotNull(jsonObject, FIELD_VERIFIED_PHONE, mVerifiedPhone); } catch (JSONException ignored) { } return jsonObject; } SourceOwner(
Address address,
String email,
String name,
String phone,
Address verifiedAddress,
String verifiedEmail,
String verifiedName,
String verifiedPhone); Address getAddress(); String getEmail(); String getName(); String getPhone(); Address getVerifiedAddress(); String getVerifiedEmail(); String getVerifiedName(); String getVerifiedPhone(); @NonNull @Override Map<String, Object> toMap(); @NonNull @Override JSONObject toJson(); @Nullable static SourceOwner fromString(@Nullable String jsonString); @Nullable static SourceOwner fromJson(@Nullable JSONObject jsonObject); }### Answer:
@Test public void fromJsonStringWithoutNulls_backToJson_createsIdenticalElement() { try { JSONObject rawConversion = new JSONObject(EXAMPLE_JSON_OWNER_WITHOUT_NULLS); assertJsonEquals(rawConversion, mSourceOwner.toJson()); } catch (JSONException jsonException) { fail("Test Data failure: " + jsonException.getLocalizedMessage()); } } |
### Question:
StripeTextUtils { @Nullable public static String removeSpacesAndHyphens(@Nullable String cardNumberWithSpaces) { if (isBlank(cardNumberWithSpaces)) { return null; } return cardNumberWithSpaces.replaceAll("\\s|-", ""); } @Nullable static String nullIfBlank(@Nullable String value); static boolean isBlank(@Nullable String value); @Nullable static String removeSpacesAndHyphens(@Nullable String cardNumberWithSpaces); }### Answer:
@Test public void removeSpacesAndHyphens_withSpacesInInterior_returnsSpacelessNumber() { String testCardNumber = "4242 4242 4242 4242"; assertEquals("4242424242424242", StripeTextUtils.removeSpacesAndHyphens(testCardNumber)); }
@Test public void removeSpacesAndHyphens_withExcessiveSpacesInInterior_returnsSpacelessNumber() { String testCardNumber = "4 242 4 242 4 242 42 4 2"; assertEquals("4242424242424242", StripeTextUtils.removeSpacesAndHyphens(testCardNumber)); }
@Test public void removeSpacesAndHyphens_withSpacesOnExterior_returnsSpacelessNumber() { String testCardNumber = " 42424242 4242 4242 "; assertEquals("4242424242424242", StripeTextUtils.removeSpacesAndHyphens(testCardNumber)); }
@Test public void removeSpacesAndHyphens_whenEmpty_returnsNull () { assertNull(StripeTextUtils.removeSpacesAndHyphens(" ")); }
@Test public void removeSpacesAndHyphens_whenNull_returnsNull() { assertNull(StripeTextUtils.removeSpacesAndHyphens(null)); }
@Test public void removeSpacesAndHyphens_withHyphenatedCardNumber_returnsCardNumber() { assertEquals("4242424242424242", StripeTextUtils.removeSpacesAndHyphens("4242-4242-4242-4242")); }
@Test public void removeSpacesAndHyphens_removesMultipleSpacesAndHyphens() { assertEquals("123", StripeTextUtils.removeSpacesAndHyphens(" - 1- --- 2 3- - - -------- ")); } |
### 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("unchecked") public static void removeNullAndEmptyParams(@NonNull Map<String, Object> mapToEdit) { for (String key : new HashSet<>(mapToEdit.keySet())) { if (mapToEdit.get(key) == null) { mapToEdit.remove(key); } if (mapToEdit.get(key) instanceof CharSequence) { CharSequence sequence = (CharSequence) mapToEdit.get(key); if (TextUtils.isEmpty(sequence)) { mapToEdit.remove(key); } } if (mapToEdit.get(key) instanceof Map) { Map<String, Object> stringObjectMap = (Map<String, Object>) mapToEdit.get(key); removeNullAndEmptyParams(stringObjectMap); } } } @SuppressWarnings("unchecked") static void removeNullAndEmptyParams(@NonNull Map<String, Object> mapToEdit); }### Answer:
@Test public void removeNullAndEmptyParams_removesNullParams() { Map<String, Object> testMap = new HashMap<>(); testMap.put("a", null); testMap.put("b", "not null"); StripeNetworkUtils.removeNullAndEmptyParams(testMap); assertEquals(1, testMap.size()); assertTrue(testMap.containsKey("b")); }
@Test public void removeNullAndEmptyParams_removesEmptyStringParams() { Map<String, Object> testMap = new HashMap<>(); testMap.put("a", "fun param"); testMap.put("b", "not null"); testMap.put("c", ""); StripeNetworkUtils.removeNullAndEmptyParams(testMap); assertEquals(2, testMap.size()); assertTrue(testMap.containsKey("a")); assertTrue(testMap.containsKey("b")); }
@Test public void removeNullAndEmptyParams_removesNestedEmptyParams() { Map<String, Object> testMap = new HashMap<>(); Map<String, Object> firstNestedMap = new HashMap<>(); Map<String, Object> secondNestedMap = new HashMap<>(); testMap.put("a", "fun param"); testMap.put("b", "not null"); firstNestedMap.put("1a", "something"); firstNestedMap.put("1b", null); secondNestedMap.put("2a", ""); secondNestedMap.put("2b", "hello world"); firstNestedMap.put("1c", secondNestedMap); testMap.put("c", firstNestedMap); StripeNetworkUtils.removeNullAndEmptyParams(testMap); assertEquals(3, testMap.size()); assertTrue(testMap.containsKey("a")); assertTrue(testMap.containsKey("b")); assertTrue(testMap.containsKey("c")); assertEquals(2, firstNestedMap.size()); assertTrue(firstNestedMap.containsKey("1a")); assertTrue(firstNestedMap.containsKey("1c")); assertEquals(1, secondNestedMap.size()); assertTrue(secondNestedMap.containsKey("2b")); } |
### 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:
AndroidPayConfiguration { @Nullable public PaymentMethodTokenizationParameters getPaymentMethodTokenizationParameters() { if (TextUtils.isEmpty(mPublicApiKey)) { return null; } return PaymentMethodTokenizationParameters.newBuilder() .setPaymentMethodTokenizationType(PAYMENT_GATEWAY) .addParameter("gateway", "stripe") .addParameter("stripe:publishableKey", mPublicApiKey) .addParameter("stripe:version", com.stripe.android.BuildConfig.VERSION_NAME) .build(); } @VisibleForTesting AndroidPayConfiguration(
@NonNull String publicApiKey,
@NonNull Currency currency,
boolean shouldUseSources); @NonNull static AndroidPayConfiguration getInstance(); static AndroidPayConfiguration init(
@NonNull @Size(min = 5) String publicApiKey,
@NonNull String currencyCode,
boolean shouldUseSources); static AndroidPayConfiguration init(
@NonNull @Size(min = 5) String publicApiKey,
@NonNull String currencyCode); static AndroidPayConfiguration init(
@NonNull @Size(min = 5) String publicApiKey,
@NonNull Currency currency); void addAllowedCardNetworks(@WalletConstants.CardNetwork Integer... networks); void addAllowedShippingCountries(@NonNull String... countrySpecifications); void addAllowedShippingCountries(
@NonNull CountrySpecification... countrySpecifications); @Nullable PaymentMethodTokenizationParameters getPaymentMethodTokenizationParameters(); @Nullable MaskedWalletRequest generateMaskedWalletRequest(@Nullable Cart cart); @NonNull static FullWalletRequest generateFullWalletRequest(
@NonNull String googleTransactionId,
@NonNull Cart cart); @Nullable MaskedWalletRequest generateMaskedWalletRequest(
@Nullable Cart cart,
boolean isPhoneNumberRequired,
boolean isShippingAddressRequired,
@Nullable String currencyCode); @NonNull Currency getCurrency(); @Nullable String getCountryCode(); @NonNull String getCurrencyCode(); @NonNull AndroidPayConfiguration setCurrency(@NonNull Currency currency); @NonNull AndroidPayConfiguration setCurrencyCode(@NonNull String currencyCode); @NonNull AndroidPayConfiguration setCountryCode(@Nullable String countryCode); boolean isPhoneNumberRequired(); AndroidPayConfiguration setPhoneNumberRequired(boolean phoneNumberRequired); boolean isShippingAddressRequired(); AndroidPayConfiguration setShippingAddressRequired(boolean shippingAddressRequired); String getMerchantName(); AndroidPayConfiguration setMerchantName(String merchantName); String getPublicApiKey(); AndroidPayConfiguration setPublicApiKey(String publicApiKey); boolean getUsesSources(); }### Answer:
@Test public void getPaymentMethodTokenizationParameters_whenApiKeyIsNotNull_returnsExpectedObject() { PaymentMethodTokenizationParameters params = mAndroidPayConfiguration.getPaymentMethodTokenizationParameters(); assertNotNull(params); assertEquals(PaymentMethodTokenizationType.PAYMENT_GATEWAY, params.getPaymentMethodTokenizationType()); Bundle bundle = params.getParameters(); assertNotNull(bundle); assertEquals("pk_test_abc123", bundle.getString("stripe:publishableKey")); assertEquals("stripe", bundle.getString("gateway")); assertEquals(com.stripe.android.BuildConfig.VERSION_NAME, bundle.getString("stripe:version")); } |
### Question:
AndroidPayConfiguration { @NonNull public static FullWalletRequest generateFullWalletRequest( @NonNull String googleTransactionId, @NonNull Cart cart) { return FullWalletRequest.newBuilder() .setGoogleTransactionId(googleTransactionId) .setCart(cart) .build(); } @VisibleForTesting AndroidPayConfiguration(
@NonNull String publicApiKey,
@NonNull Currency currency,
boolean shouldUseSources); @NonNull static AndroidPayConfiguration getInstance(); static AndroidPayConfiguration init(
@NonNull @Size(min = 5) String publicApiKey,
@NonNull String currencyCode,
boolean shouldUseSources); static AndroidPayConfiguration init(
@NonNull @Size(min = 5) String publicApiKey,
@NonNull String currencyCode); static AndroidPayConfiguration init(
@NonNull @Size(min = 5) String publicApiKey,
@NonNull Currency currency); void addAllowedCardNetworks(@WalletConstants.CardNetwork Integer... networks); void addAllowedShippingCountries(@NonNull String... countrySpecifications); void addAllowedShippingCountries(
@NonNull CountrySpecification... countrySpecifications); @Nullable PaymentMethodTokenizationParameters getPaymentMethodTokenizationParameters(); @Nullable MaskedWalletRequest generateMaskedWalletRequest(@Nullable Cart cart); @NonNull static FullWalletRequest generateFullWalletRequest(
@NonNull String googleTransactionId,
@NonNull Cart cart); @Nullable MaskedWalletRequest generateMaskedWalletRequest(
@Nullable Cart cart,
boolean isPhoneNumberRequired,
boolean isShippingAddressRequired,
@Nullable String currencyCode); @NonNull Currency getCurrency(); @Nullable String getCountryCode(); @NonNull String getCurrencyCode(); @NonNull AndroidPayConfiguration setCurrency(@NonNull Currency currency); @NonNull AndroidPayConfiguration setCurrencyCode(@NonNull String currencyCode); @NonNull AndroidPayConfiguration setCountryCode(@Nullable String countryCode); boolean isPhoneNumberRequired(); AndroidPayConfiguration setPhoneNumberRequired(boolean phoneNumberRequired); boolean isShippingAddressRequired(); AndroidPayConfiguration setShippingAddressRequired(boolean shippingAddressRequired); String getMerchantName(); AndroidPayConfiguration setMerchantName(String merchantName); String getPublicApiKey(); AndroidPayConfiguration setPublicApiKey(String publicApiKey); boolean getUsesSources(); }### Answer:
@Test public void generateFullWalletRequest_createsExpectedFullWalletRequest() { FullWalletRequest request = AndroidPayConfiguration.generateFullWalletRequest("123abc", mCart); assertEquals("123abc", request.getGoogleTransactionId()); assertNotNull(request.getCart()); assertEquals("10.00", request.getCart().getTotalPrice()); } |
### Question:
AndroidPayConfiguration { @Nullable public MaskedWalletRequest generateMaskedWalletRequest(@Nullable Cart cart) { return generateMaskedWalletRequest( cart, mIsPhoneNumberRequired, mIsShippingAddressRequired, mCurrency.getCurrencyCode()); } @VisibleForTesting AndroidPayConfiguration(
@NonNull String publicApiKey,
@NonNull Currency currency,
boolean shouldUseSources); @NonNull static AndroidPayConfiguration getInstance(); static AndroidPayConfiguration init(
@NonNull @Size(min = 5) String publicApiKey,
@NonNull String currencyCode,
boolean shouldUseSources); static AndroidPayConfiguration init(
@NonNull @Size(min = 5) String publicApiKey,
@NonNull String currencyCode); static AndroidPayConfiguration init(
@NonNull @Size(min = 5) String publicApiKey,
@NonNull Currency currency); void addAllowedCardNetworks(@WalletConstants.CardNetwork Integer... networks); void addAllowedShippingCountries(@NonNull String... countrySpecifications); void addAllowedShippingCountries(
@NonNull CountrySpecification... countrySpecifications); @Nullable PaymentMethodTokenizationParameters getPaymentMethodTokenizationParameters(); @Nullable MaskedWalletRequest generateMaskedWalletRequest(@Nullable Cart cart); @NonNull static FullWalletRequest generateFullWalletRequest(
@NonNull String googleTransactionId,
@NonNull Cart cart); @Nullable MaskedWalletRequest generateMaskedWalletRequest(
@Nullable Cart cart,
boolean isPhoneNumberRequired,
boolean isShippingAddressRequired,
@Nullable String currencyCode); @NonNull Currency getCurrency(); @Nullable String getCountryCode(); @NonNull String getCurrencyCode(); @NonNull AndroidPayConfiguration setCurrency(@NonNull Currency currency); @NonNull AndroidPayConfiguration setCurrencyCode(@NonNull String currencyCode); @NonNull AndroidPayConfiguration setCountryCode(@Nullable String countryCode); boolean isPhoneNumberRequired(); AndroidPayConfiguration setPhoneNumberRequired(boolean phoneNumberRequired); boolean isShippingAddressRequired(); AndroidPayConfiguration setShippingAddressRequired(boolean shippingAddressRequired); String getMerchantName(); AndroidPayConfiguration setMerchantName(String merchantName); String getPublicApiKey(); AndroidPayConfiguration setPublicApiKey(String publicApiKey); boolean getUsesSources(); }### Answer:
@Test public void generateMaskedWalletRequest_withoutCart_returnsNull() { assertNull(mAndroidPayConfiguration.generateMaskedWalletRequest(null)); }
@Test public void generateMaskedWalletRequest_whenCartHasNoTotalPrice_returnsNull() { Cart noPriceCart = Cart.newBuilder().build(); assertNull(mAndroidPayConfiguration.generateMaskedWalletRequest(noPriceCart)); } |
### Question:
LineItemBuilder { public LineItem build() { LineItem.Builder androidPayBuilder = LineItem.newBuilder(); androidPayBuilder.setCurrencyCode(mCurrency.getCurrencyCode()).setRole(mRole); if (mTotalPrice != null) { androidPayBuilder.setTotalPrice(PaymentUtils.getPriceString(mTotalPrice, mCurrency)); } if (mUnitPrice != null) { androidPayBuilder.setUnitPrice(PaymentUtils.getPriceString(mUnitPrice, mCurrency)); } if (mQuantity != null) { if (isWholeNumber(mQuantity)) { androidPayBuilder.setQuantity(mQuantity.toBigInteger().toString()); } else { androidPayBuilder.setQuantity(mQuantity.toString()); } } if (mTotalPrice == null && mQuantity != null && mUnitPrice != null) { mTotalPrice = mQuantity.multiply( BigDecimal.valueOf(mUnitPrice), MathContext.DECIMAL64).longValue(); androidPayBuilder.setTotalPrice(PaymentUtils.getPriceString(mTotalPrice, mCurrency)); } else { if (!isPriceBreakdownConsistent(mUnitPrice, mQuantity, mTotalPrice)) { Log.w(TAG, String.format(Locale.ENGLISH, "Price breakdown of %d * %.1f = %d is off by more than 1 percent", mUnitPrice, mQuantity.floatValue(), mTotalPrice)); } } if (mRole != LineItem.Role.REGULAR) { androidPayBuilder.setRole(mRole); } if (!TextUtils.isEmpty(mDescription)) { androidPayBuilder.setDescription(mDescription); } return androidPayBuilder.build(); } 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 setCurrency_withLowerCaseString_stillSetsCurrency() { LineItemBuilder builder = new LineItemBuilder("eur"); LineItem item = builder.build(); assertEquals("EUR", item.getCurrencyCode()); }
@Test(expected = RuntimeException.class) public void setCurrencyCode_whenInvalid_throwsRuntimeException() { new LineItemBuilder("notacurrency").build(); fail("Can't create a LineItemBuilder with an illegal currency."); } |
### 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:
LineItemBuilder { static boolean isPriceBreakdownConsistent( Long unitPrice, BigDecimal quantity, Long totalPrice) { if (unitPrice == null || quantity == null || totalPrice == null) { return true; } BigDecimal expectedPrice = quantity.multiply(BigDecimal.valueOf(unitPrice)); BigDecimal actualPrice = BigDecimal.valueOf(totalPrice); if (expectedPrice.compareTo(BigDecimal.ZERO) == 0) { return totalPrice == 0; } double ratio = actualPrice.divide( expectedPrice, CONSISTENCY_SCALE, BigDecimal.ROUND_HALF_EVEN).doubleValue(); return Math.abs(ratio - 1.0) < CONSISTENCY_THRESHOLD; } 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 isPriceBreakdownConsistent_whenItemsMultiplyClosely_returnsTrue() { assertTrue(isPriceBreakdownConsistent(1000L, BigDecimal.TEN, 10000L)); }
@Test public void isPriceBreakdownConsistent_whenAnyItemIsNull_returnsTrue() { assertTrue(isPriceBreakdownConsistent(null, BigDecimal.TEN, 1234L)); assertTrue(isPriceBreakdownConsistent(55L, null, 8888L)); assertTrue(isPriceBreakdownConsistent(33L, BigDecimal.ONE, null)); }
@Test public void isPriceBreakdownConsistent_whenItemsAreOffByALot_returnsFalse() { assertFalse(isPriceBreakdownConsistent(55L, BigDecimal.ONE, 56L)); }
@Test public void isPriceBreakdownConsistent_whenItemsAreOffByOnlyALittle_returnsTrue() { assertTrue(isPriceBreakdownConsistent(199L, BigDecimal.ONE, 200L)); } |
### 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 CartError searchLineItemForErrors(LineItem lineItem) { if (lineItem == null) { return null; } if (!matchesCurrencyPatternOrEmpty(lineItem.getUnitPrice())) { return new CartError(CartError.LINE_ITEM_PRICE, String.format(Locale.ENGLISH, "Invalid price string: %s does not match required pattern of %s", lineItem.getUnitPrice(), CURRENCY_REGEX), lineItem); } if (!matchesQuantityPatternOrEmpty(lineItem.getQuantity())) { return new CartError(CartError.LINE_ITEM_QUANTITY, String.format(Locale.ENGLISH, "Invalid quantity string: %s does not match required pattern of %s", lineItem.getQuantity(), QUANTITY_REGEX), lineItem); } if (!matchesCurrencyPatternOrEmpty(lineItem.getTotalPrice())) { return new CartError(CartError.LINE_ITEM_PRICE, String.format(Locale.ENGLISH, "Invalid price string: %s does not match required pattern of %s", lineItem.getTotalPrice(), CURRENCY_REGEX), lineItem); } return null; } 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 searchLineItemForErrors_whenNoFieldsEntered_returnsNull() { assertNull(searchLineItemForErrors(LineItem.newBuilder().build())); }
@Test public void searchLineItemForErrors_whenNull_returnsNull() { assertNull(searchLineItemForErrors(null)); }
@Test public void searchLineItemForErrors_withAllNumericFieldsCorrect_returnsNull() { assertNull(searchLineItemForErrors(LineItem.newBuilder() .setTotalPrice("10.00") .setQuantity("1.3") .setUnitPrice("1.50") .build())); }
@Test public void searchLineItemForErrors_whenJustOneIncorrectField_returnsExpectedError() { LineItem badTotalPriceItem = LineItem.newBuilder() .setTotalPrice("10.999") .setQuantity("1.3") .setUnitPrice("1.50") .build(); CartError totalPriceError = searchLineItemForErrors(badTotalPriceItem); assertNotNull(totalPriceError); assertEquals(CartError.LINE_ITEM_PRICE, totalPriceError.getErrorType()); assertEquals(getExpectedErrorStringForPrice("10.999"), totalPriceError.getMessage()); assertEquals(badTotalPriceItem, totalPriceError.getLineItem()); LineItem badQuantityItem = LineItem.newBuilder() .setTotalPrice("10.99") .setQuantity("1.33") .setUnitPrice("1.50") .build(); CartError quantityError = searchLineItemForErrors(badQuantityItem); assertNotNull(quantityError); assertEquals(CartError.LINE_ITEM_QUANTITY, quantityError.getErrorType()); assertEquals(getExpectedErrorStringForQuantity("1.33"), quantityError.getMessage()); assertEquals(badQuantityItem, quantityError.getLineItem()); LineItem badUnitPriceItem = LineItem.newBuilder() .setTotalPrice("10.99") .setQuantity("1.3") .setUnitPrice(".50") .build(); CartError unitPriceError = searchLineItemForErrors(badUnitPriceItem); assertNotNull(unitPriceError); assertEquals(CartError.LINE_ITEM_PRICE, unitPriceError.getErrorType()); assertEquals(getExpectedErrorStringForPrice(".50"), unitPriceError.getMessage()); assertEquals(badUnitPriceItem, unitPriceError.getLineItem()); }
@Test public void searchLineItemForErrors_withOneCorrectFieldAndOthersNull_returnsNull() { assertNull(searchLineItemForErrors(LineItem.newBuilder() .setTotalPrice("10.00") .build())); } |
### 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:
PaymentUtils { @NonNull public static List<CartError> removeErrorType( @NonNull List<CartError> errors, @NonNull @CartError.CartErrorType String errorType) { List<CartError> filteredErrors = new ArrayList<>(); for (CartError error : errors) { if (errorType.equals(error.getErrorType())) { continue; } filteredErrors.add(error); } return filteredErrors; } 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 removeErrorType_whenListContainsErrorsOfType_returnsListWithoutThoseErrors() { final CartError error1 = new CartError(CartError.DUPLICATE_TAX, "Dupe Tax"); final CartError error2 = new CartError(CartError.LINE_ITEM_CURRENCY, "Bad line item"); final CartError error3 = new CartError(CartError.LINE_ITEM_PRICE, "Bad price on line item"); final CartError error4 = new CartError(CartError.LINE_ITEM_QUANTITY, "Bad quantity"); final CartError error5 = new CartError(CartError.DUPLICATE_TAX, "Dupe Tax"); List<CartError> errorList = new ArrayList<CartError>() {{ add(error1); add(error2); add(error3); add(error4); add(error5); }}; List<CartError> filteredErrorList = PaymentUtils.removeErrorType(errorList, CartError.DUPLICATE_TAX); assertEquals(3, filteredErrorList.size()); assertEquals(CartError.LINE_ITEM_CURRENCY, filteredErrorList.get(0).getErrorType()); assertEquals(CartError.LINE_ITEM_PRICE, filteredErrorList.get(1).getErrorType()); assertEquals(CartError.LINE_ITEM_QUANTITY, filteredErrorList.get(2).getErrorType()); }
@Test public void removeErrorType_whenListHasNoErrorsOfType_returnsOriginalList() { final CartError error1 = new CartError(CartError.DUPLICATE_TAX, "Dupe Tax"); final CartError error2 = new CartError(CartError.CART_CURRENCY, "Bad line item"); List<CartError> errorList = new ArrayList<CartError>() {{ add(error1); add(error2); }}; List<CartError> filteredErrorList = PaymentUtils.removeErrorType(errorList, CartError.LINE_ITEM_CURRENCY); assertEquals(2, filteredErrorList.size()); assertEquals(CartError.DUPLICATE_TAX, filteredErrorList.get(0).getErrorType()); assertEquals(CartError.CART_CURRENCY, filteredErrorList.get(1).getErrorType()); }
@Test public void removeErrorType_onEmptyList_returnsEmptyList() { assertEmpty(PaymentUtils.removeErrorType(new ArrayList<CartError>(), CartError.LINE_ITEM_QUANTITY)); } |
### Question:
CartManager { @NonNull public String getCurrencyCode() { return mCurrency.getCurrencyCode(); } 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 createCartManager_withoutCurrencyArgument_usesAndroidPayConfiguration() { AndroidPayConfiguration.getInstance().setCurrencyCode("JPY"); CartManager cartManager = new CartManager(); assertEquals("JPY", cartManager.getCurrencyCode()); }
@Test public void createCartManager_withCurrencyDifferentFromConfiguration_changesConfigAndLogs() { ShadowLog.stream = System.out; AndroidPayConfiguration.getInstance().setCurrencyCode("KRW"); String expectedWarning = "Cart created with currency code GBP, which differs from " + "current AndroidPayConfiguration currency, KRW. Changing configuration to GBP"; new CartManager("GBP"); assertEquals("GBP", AndroidPayConfiguration.getInstance().getCurrencyCode()); List<ShadowLog.LogItem> logItems = ShadowLog.getLogsForTag(CartManager.TAG); assertFalse(logItems.isEmpty()); assertEquals(1, logItems.size()); assertEquals(expectedWarning, logItems.get(0).msg); assertEquals(Log.WARN, logItems.get(0).type); } |
### Question:
CartManager { @NonNull static String generateUuidForRole(int role) { String baseId = UUID.randomUUID().toString(); String base = null; if (role == LineItem.Role.REGULAR) { base = REGULAR_ID; } else if (role == LineItem.Role.SHIPPING) { base = SHIPPING_ID; } StringBuilder builder = new StringBuilder(); if (base != null) { return builder.append(base) .append('-') .append(baseId.substring(base.length())) .toString(); } return baseId; } 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 generateUuidForRole_beginsWithAppropriatePrefix() { String regularUuid = CartManager.generateUuidForRole(LineItem.Role.REGULAR); String shippingUuid = CartManager.generateUuidForRole(LineItem.Role.SHIPPING); assertTrue(regularUuid.startsWith(CartManager.REGULAR_ID)); assertTrue(shippingUuid.startsWith(CartManager.SHIPPING_ID)); } |
### 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:
CartManager { @Nullable public Long getTotalPrice() { if (mCachedTotalPrice != null) { return mCachedTotalPrice; } Long[] sectionPrices = new Long[3]; sectionPrices[0] = calculateRegularItemTotal(); sectionPrices[1] = calculateShippingItemTotal(); sectionPrices[2] = calculateTax(); Long totalPrice = null; for (int i = 0 ; i < sectionPrices.length; i++) { if (sectionPrices[i] == null) { return null; } if (totalPrice == null) { totalPrice = sectionPrices[i]; } else { totalPrice += sectionPrices[i]; } } mCachedTotalPrice = totalPrice; return totalPrice; } 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 getTotalPrice_whenSomeSectionsAreNull_returnsExpectedValue() { AndroidPayConfiguration.getInstance().setCurrencyCode("JPY"); Cart oldCart = generateCartWithAllItems("JPY"); CartManager manager = new CartManager(oldCart); assertEquals(Long.valueOf(7000L), manager.getTotalPrice()); } |
### 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:
Card extends StripeJsonModel implements StripePaymentSource { public boolean validateExpiryDate() { return validateExpiryDate(Calendar.getInstance()); } Card(
String number,
Integer expMonth,
Integer expYear,
String cvc,
String name,
String addressLine1,
String addressLine2,
String addressCity,
String addressState,
String addressZip,
String addressCountry,
String brand,
@Size(4) String last4,
String fingerprint,
String funding,
String country,
String currency,
String id); Card(
String number,
Integer expMonth,
Integer expYear,
String cvc,
String name,
String addressLine1,
String addressLine2,
String addressCity,
String addressState,
String addressZip,
String addressCountry,
String currency); Card(
String number,
Integer expMonth,
Integer expYear,
String cvc); private Card(Builder builder); @Nullable @CardBrand static String asCardBrand(@Nullable String possibleCardType); @Nullable @FundingType static String asFundingType(@Nullable String possibleFundingType); @Nullable static Card fromString(String jsonString); @Nullable static Card fromJson(JSONObject jsonObject); boolean validateCard(); boolean validateNumber(); boolean validateExpiryDate(); boolean validateCVC(); boolean validateExpMonth(); String getNumber(); @NonNull List<String> getLoggingTokens(); @NonNull Card addLoggingToken(@NonNull String loggingToken); @Deprecated void setNumber(String number); String getCVC(); @Deprecated void setCVC(String cvc); @Nullable @IntRange(from = 1, to = 12) Integer getExpMonth(); @Deprecated void setExpMonth(@Nullable @IntRange(from = 1, to = 12) Integer expMonth); Integer getExpYear(); @Deprecated void setExpYear(Integer expYear); String getName(); void setName(String name); String getAddressLine1(); void setAddressLine1(String addressLine1); String getAddressLine2(); void setAddressLine2(String addressLine2); String getAddressCity(); void setAddressCity(String addressCity); String getAddressZip(); void setAddressZip(String addressZip); String getAddressState(); void setAddressState(String addressState); String getAddressCountry(); void setAddressCountry(String addressCountry); String getCurrency(); void setCurrency(String currency); String getLast4(); @Deprecated @CardBrand String getType(); @CardBrand String getBrand(); String getFingerprint(); @Nullable @FundingType String getFunding(); String getCountry(); @Override String getId(); @Nullable String getAddressLine1Check(); @Nullable String getAddressZipCheck(); @Nullable String getCustomerId(); @Nullable String getCvcCheck(); @NonNull @Override JSONObject toJson(); @NonNull @Override Map<String, Object> toMap(); static final String AMERICAN_EXPRESS; static final String DISCOVER; static final String JCB; static final String DINERS_CLUB; static final String VISA; static final String MASTERCARD; static final String UNKNOWN; static final int CVC_LENGTH_AMERICAN_EXPRESS; static final int CVC_LENGTH_COMMON; static final String FUNDING_CREDIT; static final String FUNDING_DEBIT; static final String FUNDING_PREPAID; static final String FUNDING_UNKNOWN; static final Map<String , Integer> BRAND_RESOURCE_MAP; static final String[] PREFIXES_AMERICAN_EXPRESS; static final String[] PREFIXES_DISCOVER; static final String[] PREFIXES_JCB; static final String[] PREFIXES_DINERS_CLUB; static final String[] PREFIXES_VISA; static final String[] PREFIXES_MASTERCARD; static final int MAX_LENGTH_STANDARD; static final int MAX_LENGTH_AMERICAN_EXPRESS; static final int MAX_LENGTH_DINERS_CLUB; }### Answer:
@Test public void shouldFailValidateExpiryDateIfNullYear() { Card card = new Card(null, 1, null, null); assertFalse(card.validateExpiryDate(calendar)); } |
### Question:
Card extends StripeJsonModel implements StripePaymentSource { @Nullable public static Card fromString(String jsonString) { try { JSONObject jsonObject = new JSONObject(jsonString); return fromJson(jsonObject); } catch (JSONException ignored) { return null; } } Card(
String number,
Integer expMonth,
Integer expYear,
String cvc,
String name,
String addressLine1,
String addressLine2,
String addressCity,
String addressState,
String addressZip,
String addressCountry,
String brand,
@Size(4) String last4,
String fingerprint,
String funding,
String country,
String currency,
String id); Card(
String number,
Integer expMonth,
Integer expYear,
String cvc,
String name,
String addressLine1,
String addressLine2,
String addressCity,
String addressState,
String addressZip,
String addressCountry,
String currency); Card(
String number,
Integer expMonth,
Integer expYear,
String cvc); private Card(Builder builder); @Nullable @CardBrand static String asCardBrand(@Nullable String possibleCardType); @Nullable @FundingType static String asFundingType(@Nullable String possibleFundingType); @Nullable static Card fromString(String jsonString); @Nullable static Card fromJson(JSONObject jsonObject); boolean validateCard(); boolean validateNumber(); boolean validateExpiryDate(); boolean validateCVC(); boolean validateExpMonth(); String getNumber(); @NonNull List<String> getLoggingTokens(); @NonNull Card addLoggingToken(@NonNull String loggingToken); @Deprecated void setNumber(String number); String getCVC(); @Deprecated void setCVC(String cvc); @Nullable @IntRange(from = 1, to = 12) Integer getExpMonth(); @Deprecated void setExpMonth(@Nullable @IntRange(from = 1, to = 12) Integer expMonth); Integer getExpYear(); @Deprecated void setExpYear(Integer expYear); String getName(); void setName(String name); String getAddressLine1(); void setAddressLine1(String addressLine1); String getAddressLine2(); void setAddressLine2(String addressLine2); String getAddressCity(); void setAddressCity(String addressCity); String getAddressZip(); void setAddressZip(String addressZip); String getAddressState(); void setAddressState(String addressState); String getAddressCountry(); void setAddressCountry(String addressCountry); String getCurrency(); void setCurrency(String currency); String getLast4(); @Deprecated @CardBrand String getType(); @CardBrand String getBrand(); String getFingerprint(); @Nullable @FundingType String getFunding(); String getCountry(); @Override String getId(); @Nullable String getAddressLine1Check(); @Nullable String getAddressZipCheck(); @Nullable String getCustomerId(); @Nullable String getCvcCheck(); @NonNull @Override JSONObject toJson(); @NonNull @Override Map<String, Object> toMap(); static final String AMERICAN_EXPRESS; static final String DISCOVER; static final String JCB; static final String DINERS_CLUB; static final String VISA; static final String MASTERCARD; static final String UNKNOWN; static final int CVC_LENGTH_AMERICAN_EXPRESS; static final int CVC_LENGTH_COMMON; static final String FUNDING_CREDIT; static final String FUNDING_DEBIT; static final String FUNDING_PREPAID; static final String FUNDING_UNKNOWN; static final Map<String , Integer> BRAND_RESOURCE_MAP; static final String[] PREFIXES_AMERICAN_EXPRESS; static final String[] PREFIXES_DISCOVER; static final String[] PREFIXES_JCB; static final String[] PREFIXES_DINERS_CLUB; static final String[] PREFIXES_VISA; static final String[] PREFIXES_MASTERCARD; static final int MAX_LENGTH_STANDARD; static final int MAX_LENGTH_AMERICAN_EXPRESS; static final int MAX_LENGTH_DINERS_CLUB; }### Answer:
@Test public void fromString_whenStringIsBadJson_returnsNull() { assertNull(Card.fromString(BAD_JSON)); } |
### 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:
NativeQuestionSetImporter extends AbstractQuestionSetImporter { @Override public QuestionSet processDocument( Document doc ) throws ParseException { Element root = doc.getRootElement(); if ( !root.getName().equalsIgnoreCase( "QuestionSet" ) ) throw new ParseException( "QuestionSet: Root not <QuestionSet>", 0 ); String versionString = root.getAttributeValue( "version" ); if ( versionString == null ) { LOGGER.warning( "No `version' attribute on <QuestionSet> element" ); } else { try { int version = Integer.parseInt( versionString ); if ( version == 1 || version == 2 || version == 3 ) { LOGGER.warning( "QuestionSet version " + version + " is no longer " + "supported: proceeding anyway, but errors may be present." ); } else if ( version == 4 ) { } else { LOGGER.warning( "QuestionSet format version (" + version + ") is newer than this software and may not be handled correctly." ); } } catch ( NumberFormatException e ) { LOGGER.log( Level.WARNING, "Cannot parse version number: " + versionString, e ); } } List<?> topElements = root.getChildren(); String name = null; String description = null; int recommendedTimePerQuestion = -1; String category = ""; List<Question> questions = new ArrayList<Question>(); for ( Object object : topElements ) { Element topElement = (Element) object; String tagName = topElement.getName(); if ( tagName.equalsIgnoreCase( "Name" ) ) { name = topElement.getText(); } else if ( tagName.equalsIgnoreCase( "Description" ) ) { description = topElement.getText(); } else if ( tagName.equalsIgnoreCase( "RecommendedTimePerQuestion" ) ) { recommendedTimePerQuestion = Integer.parseInt( topElement.getText() ); } else if ( tagName.equalsIgnoreCase( "Category" ) ) { category = topElement.getText(); } else if ( tagName.equalsIgnoreCase( "Questions" ) ) { for ( Object object2 : topElement.getChildren() ) { Element questionElement = (Element) object2; String name2 = questionElement.getName(); try { if ( name2.equalsIgnoreCase( "MultipleChoiceQuestion" ) ) { questions.add( new XmlQuestionSetParser().parseMultipleChoiceQuestion( questionElement, new ParsingProblemRecorder() ) ); } else if ( name2.equalsIgnoreCase( "DragAndDropQuestion" ) ) { questions.add( new DragAndDropQuestion( questionElement ) ); } else { LOGGER.warning( "Unrecognised tag: " + name2 ); } } catch ( ParseException e ) { LOGGER.log( Level.WARNING, "Error parsing Question, skipping", e ); continue; } } } else { LOGGER.warning( "Unrecognised tag: " + tagName ); } } if ( questions.size() == 0 ) throw new ParseException( "No valid questions found in QuestionSet", 0 ); if ( name == null ) { LOGGER.warning( "no <Name> provided" ); name = "No name given"; } if ( recommendedTimePerQuestion == -1 ) { LOGGER.warning( "no <RecommendedTimePerQuestion> provided" ); recommendedTimePerQuestion = 120; } if ( category == "" ) { LOGGER.warning( "No category listed for this question set" ); } if ( description == null ) { LOGGER.warning( "no <Description> provided" ); description = "No description given"; } return new QuestionSet( name, description, recommendedTimePerQuestion, category, questions ); } @Override QuestionSet processDocument( Document doc ); }### Answer:
@Test public void toAndFromXmlShouldHaveNoEffect() throws Exception { Collection<QuestionSet> bundledQuestionSets = QuestionSetManager.loadBundledQuestionSets(); NativeQuestionSetImporter questionSetImporter = new NativeQuestionSetImporter(); XmlQuestionSetParser questionSetParser = new XmlQuestionSetParser(); for (QuestionSet questionSet : bundledQuestionSets) { Document xmlDocument = questionSetParser.asXmlDocument(questionSet); QuestionSet reparsedQuestionSet = questionSetImporter.processDocument(xmlDocument); assertEquals(questionSet, reparsedQuestionSet); } } |
### 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:
Client extends AbstractClient { public @NonNull Index getIndex(@NonNull String indexName) { Index index = null; WeakReference<Object> existingIndex = indices.get(indexName); if (existingIndex != null) { index = (Index) existingIndex.get(); } if (index == null) { index = new Index(this, indexName); indices.put(indexName, new WeakReference<Object>(index)); } return index; } Client(@NonNull String applicationID, @NonNull String apiKey); Client(@NonNull String applicationID, @NonNull String apiKey, @Nullable String[] hosts); @NonNull String getApplicationID(); Index initIndex(@NonNull String indexName); @NonNull Index getIndex(@NonNull String indexName); Request listIndexesAsync(@Nullable final RequestOptions requestOptions, @NonNull CompletionHandler completionHandler); Request listIndexesAsync(@NonNull CompletionHandler completionHandler); Request deleteIndexAsync(final @NonNull String indexName, @Nullable final RequestOptions requestOptions, CompletionHandler completionHandler); Request deleteIndexAsync(final @NonNull String indexName, CompletionHandler completionHandler); Request moveIndexAsync(final @NonNull String srcIndexName, final @NonNull String dstIndexName, @Nullable final RequestOptions requestOptions, CompletionHandler completionHandler); Request moveIndexAsync(final @NonNull String srcIndexName, final @NonNull String dstIndexName, CompletionHandler completionHandler); Request copyIndexAsync(final @NonNull String srcIndexName, final @NonNull String dstIndexName, @Nullable final RequestOptions requestOptions, CompletionHandler completionHandler); Request copyIndexAsync(final @NonNull String srcIndexName, final @NonNull String dstIndexName, CompletionHandler completionHandler); Request multipleQueriesAsync(final @NonNull List<IndexQuery> queries, final MultipleQueriesStrategy strategy, @Nullable final RequestOptions requestOptions, @NonNull CompletionHandler completionHandler); Request multipleQueriesAsync(final @NonNull List<IndexQuery> queries, final MultipleQueriesStrategy strategy, @NonNull CompletionHandler completionHandler); Request batchAsync(final @NonNull JSONArray operations, @Nullable final RequestOptions requestOptions, CompletionHandler completionHandler); Request batchAsync(final @NonNull JSONArray operations, CompletionHandler completionHandler); }### Answer:
@Test public void testIndexReuse() throws Exception { Map<String, WeakReference<Index>> indices = (Map<String, WeakReference<Index>>) Whitebox.getInternalState(client, "indices"); final String indexName = "name"; assertEquals(0, indices.size()); Index index1 = client.getIndex(indexName); assertEquals(1, indices.size()); Index index2 = client.getIndex(indexName); assertEquals(index1, index2); assertEquals(1, indices.size()); } |
### 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 { public static UrlBuilder http(String host) { return new UrlBuilder(Scheme.HTTP, host); } 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 uriInteropHash() { Url url = Urls.http("host.com") .path("/c#") .query("q", "#!") .fragment("#fragment#") .create(); URI uri = url.uri(); assertEquals("/c#", uri.getPath()); assertEquals("q=#!", uri.getQuery()); assertEquals("#fragment#", uri.getFragment()); }
@Test public void uriInteropIpv6() { Url url = Urls.http("[ff::00]") .create(); URI uri = url.uri(); assertEquals("[ff::]", uri.getHost()); }
@Test public void emptyPathIsAlwaysForwardSlash() { Url expected = Urls.http("host").path("/").create(); assertEquals(expected, Urls.http("host").create()); assertEquals(expected, Urls.http("host").path("").create()); assertEquals(expected, Urls.http("host").path("\\").create()); }
@Test public void host() throws Exception { Url url = Urls.http("host").create(); assertEquals("host", url.host().display()); url = Urls.http("10.10.0.1:9000").create(); assertEquals("10.10.0.1", url.host().display()); url = Urls.http("2001:0db8:0000:0000:0000:8a2e:0370:7334").create(); assertEquals("2001:db8::8a2e:370:7334", url.host().display()); url = Urls.http("[2001:db8::8a2e:370:7334]").create(); assertEquals("2001:db8::8a2e:370:7334", url.host().display()); url = Urls.http("[::A]:9000").create(); assertEquals("::a", url.host().display()); assertEquals(9000, url.port()); }
@Test public void host_removesUserInfo() { Url url = Urls.http("user:[email protected]").create(); assertEquals("host.com", url.host().display()); url = Urls.http("[email protected]:[email protected]").create(); assertEquals("host.com", url.host().display()); }
@Test public void host_convertCharactersToLowerCase() { assertEquals("abcd", Urls.http("ABCD").create().host().display()); assertEquals("σ", Urls.http("Σ").create().host().display()); }
@Test public void host_idnEncodedAsPunycode() { Url url = Urls.http("bücher").create(); assertEquals("xn--bcher-kva", url.host().name()); assertEquals("bücher", url.host().display()); }
@Test public void host_builderTakesPunycodeOrUnicode() { Url unicode = Urls.http("bücher").create(); Url punycode = Urls.http("xn--bcher-kva").create(); assertEquals(unicode, punycode); assertEquals(unicode.hashCode(), punycode.hashCode()); }
@Test public void fragment() { Url url = Urls.http("host") .fragment("\uD83D\uDC36") .create(); assertEquals("\uD83D\uDC36", url.fragment()); }
@Test public void uriInteropAllCodepoints() { for (char point = 0; point < 0x100; point++) { String input = "" + point; Url url = Urls.http("host.com") .path("/" + input) .query(input, input) .fragment(input) .create(); assertEquals(url.toString(), url.uri().toString()); } } |
### Question:
Urls { @Nonnull public static String escape(@Nonnull String url) { String trim = Strings.sanitizeWhitespace(url); SplitUrl split = SplitUrl.split(trim); if (split.urlType() != Type.FULL) { throw new IllegalArgumentException( "Not a full URL: " + url); } StringBuilder sb = new StringBuilder(); if (split.scheme() != null) { String scheme = split.scheme().toLowerCase(Locale.US); if (scheme.equals("http") || scheme.equals("https")) { sb.append(scheme).append(':'); } else { throw new IllegalArgumentException( "Only http and https schemes are supported. Input: " + url); } } if (split.authority() != null) { sb.append(" } if (split.path() != null) { sb.append(PercentEncoder.reEncodePath(split.path()).replace('\\', '/')); } if (split.query() != null) { sb.append('?').append(PercentEncoder.reEncodeQuery(split.query())); } if (split.fragment() != null) { sb.append('#').append(PercentEncoder.reEncodeFragment(split.fragment())); } return sb.toString(); } 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 minimalEscapeTrimsWhitespace() { String expected = "http: assertEquals(expected, Urls.escape(" http: assertEquals(expected, Urls.escape(" http: assertEquals(expected, Urls.escape(" http: assertEquals(expected, Urls.escape("\thttp: assertEquals(expected, Urls.escape("\fhttp: assertEquals(expected, Urls.escape("\fhttp: }
@Test public void minimalEscapeRemovesLineBreaks() { String expected = "http: assertEquals(expected, Urls.escape("http: assertEquals(expected, Urls.escape("http: assertEquals(expected, Urls.escape("http: assertEquals(expected, Urls.escape("http: assertEquals(expected, Urls.escape("http: }
@Test public void minimalEncodeToLowerCase() { assertEquals("http: }
@Test public void minimalEncodeHostname() { assertEquals("http: assertEquals("http: assertEquals("http: assertEquals("http: assertEquals("http: assertEquals("http: assertEquals("http: }
@Test public void minimalEncodeChecksAuthority() { try { Urls.escape("http: fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { assertThat(expected.getMessage(), containsString("Invalid hostname:")); } }
@Test public void minimalEncodeFixColonSlashSlash() { String expected = "http: assertEquals(expected, Urls.escape("http: assertEquals(expected, Urls.escape("http:/host")); assertEquals(expected, Urls.escape("http:\\host")); assertEquals(expected, Urls.escape("http:\\\\host")); }
@Test public void minimalEscape_retainPlusInPath() { assertEquals("http: }
@Test public void minimalEscape_retainPlusInQiuery() { assertEquals("http: } |
### 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:
Paths { public static Path parse(String path) { return path.isEmpty() ? ImmutablePath.EMPTY : ImmutablePath.create(new PathBuilder().splitAndAdd(path, true)); } static Path of(String... segments); static Path parse(String path); static Path empty(); }### Answer:
@Test public void resolve() { assertEquals(Paths.parse("/home/file.pdf"), Paths.parse("/home/dir").resolve("file.pdf")); assertEquals(Paths.parse("/home/dir/file.pdf"), Paths.parse("/home/dir/").resolve("file.pdf")); }
@Test public void resolve_rfc3986() { Path base = Paths.parse("/b/c/d;p"); assertEquals(Paths.parse("/b/c/g"), base.resolve("g")); assertEquals(Paths.parse("/b/c/g"), base.resolve("./g")); assertEquals(Paths.parse("/b/c/g/"), base.resolve("g/")); assertEquals(Paths.parse("/g"), base.resolve("/g")); assertEquals(Paths.parse("/b/c/d;p"), base.resolve("")); assertEquals(Paths.parse("/b/c/"), base.resolve(".")); assertEquals(Paths.parse("/b/c/"), base.resolve("./")); assertEquals(Paths.parse("/b/"), base.resolve("..")); assertEquals(Paths.parse("/b/"), base.resolve("../")); assertEquals(Paths.parse("/b/g"), base.resolve("../g")); assertEquals(Paths.parse("/"), base.resolve("../..")); assertEquals(Paths.parse("/"), base.resolve("../../")); assertEquals(Paths.parse("/"), base.resolve("../../..")); assertEquals(Paths.parse("/g"), base.resolve("../../../g")); assertEquals(Paths.parse("/g"), base.resolve("/./g")); assertEquals(Paths.parse("/g"), base.resolve("/../g")); assertEquals(Paths.parse("/b/c/g."), base.resolve("g.")); assertEquals(Paths.parse("/b/c/.g"), base.resolve(".g")); assertEquals(Paths.parse("/b/c/..g"), base.resolve("..g")); assertEquals(Paths.parse("/b/c/g.."), base.resolve("g..")); assertEquals(Paths.parse("/b/g"), base.resolve("./../g")); assertEquals(Paths.parse("/b/c/g/"), base.resolve("./g/.")); assertEquals(Paths.parse("/b/c/g/h"), base.resolve("g/./h")); assertEquals(Paths.parse("/b/c/h"), base.resolve("g/../h")); assertEquals(Paths.parse("/b/c/g;x=1/y"), base.resolve("g;x=1/./y")); assertEquals(Paths.parse("/b/c/y"), base.resolve("g;x=1/../y")); } |
### Question:
Paths { public static Path of(String... segments) { if (segments.length == 0) { return ImmutablePath.EMPTY; } PathBuilder pathBuilder = new PathBuilder(); for (String segment : segments) { pathBuilder.splitAndAdd(segment, false); } return ImmutablePath.create(pathBuilder); } static Path of(String... segments); static Path parse(String path); static Path empty(); }### Answer:
@Test public void pathIsAlwaysAbsolute() { Path expected = Paths.of("/a"); assertEquals(expected, Paths.of("a")); assertEquals(expected, Paths.of("./a")); assertEquals(expected, Paths.of("../a")); }
@Test public void emptySegmentsAreRemoved() { assertEquals(Paths.of("/a/b/c/"), Paths.of("a/", "/b", " }
@Test public void isDir() { assertTrue(Paths.of("/a", "").isDirectory()); assertTrue(Paths.of("/a/").isDirectory()); assertFalse(Paths.of("/a").isDirectory()); assertFalse(Paths.of("a").isDirectory()); }
@Test public void cleanIncorrectSlashes() { assertEquals(Paths.of("/"), Paths.of("\\")); assertEquals(Paths.of("/path"), Paths.of("\\path")); assertEquals(Paths.of("/path/"), Paths.of("\\path\\")); }
@Test public void removeDotSegments() { assertEquals(Arrays.asList(), Paths.of(".").segments()); assertEquals(Arrays.asList(), Paths.of("..").segments()); assertEquals(Arrays.asList(), Paths.of("/parent/..").segments()); assertEquals(Arrays.asList("parent"), Paths.of("/parent/.").segments()); assertEquals(Arrays.asList("parent"), Paths.of("/parent/%2e").segments()); assertEquals(Arrays.asList("parent"), Paths.of("/parent/%2e/").segments()); assertEquals(Arrays.asList("parent", "dir"), Paths.of("/parent/%2e/dir").segments()); assertEquals(Arrays.asList("dir"), Paths.of("/parent/%2e%2E/dir").segments()); }
@Test public void segmentsIncludeFilename() { assertEquals(Arrays.asList("a"), Paths.of("/a").segments()); assertEquals(Arrays.asList("a"), Paths.of("/a/").segments()); assertEquals(Arrays.asList("a", "b"), Paths.of("/a/b").segments()); assertEquals(Arrays.asList("a", "b"), Paths.of("/a/b/").segments()); assertEquals(Arrays.asList("a", "b", "c"), Paths.of("/a/b/c").segments()); }
@Test public void filenameDefaultsToEmptyString() { assertEquals("", Paths.of("/lib/").filename()); }
@Test public void equalsAndHashcode() { Path a1 = Paths.of("a", "b", "c/"); Path a2 = Paths.of("/a/", "/b/", "/c/"); Path a3 = Paths.of("/a", "b", "c", ""); assertEquals(a1, a2); assertEquals(a2, a3); assertEquals(a1, a3); assertEquals(a1.hashCode(), a2.hashCode()); assertEquals(a2.hashCode(), a3.hashCode()); assertEquals(a1.hashCode(), a3.hashCode()); Path b1 = Paths.of("a"); assertNotEquals(a1, b1); assertNotEquals(a2, b1); assertNotEquals(a3, b1); assertNotEquals(a1.hashCode(), b1.hashCode()); assertNotEquals(a2.hashCode(), b1.hashCode()); assertNotEquals(a3.hashCode(), b1.hashCode()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.