method2testcases
stringlengths
118
3.08k
### Question: OAuthClientResponseFactory { public static OAuthClientResponse createJSONTokenResponse(String body, String contentType, int responseCode) throws OAuthProblemException { OAuthJSONAccessTokenResponse resp = new OAuthJSONAccessTokenResponse(); resp.init(body, contentType, responseCode); return resp; } static OAuthClientResponse createGitHubTokenResponse(String body, String contentType, int responseCode); static OAuthClientResponse createJSONTokenResponse(String body, String contentType, int responseCode); static T createCustomResponse(String body, String contentType, int responseCode, Map<String, List<String>> headers, Class<T> clazz); static T createCustomResponse(InputStream body, String contentType, int responseCode, Map<String, List<String>> headers, Class<T> clazz); }### Answer: @Test public void testCreateJSONTokenResponse() throws Exception { OAuthClientResponse jsonTokenResponse = OAuthClientResponseFactory .createJSONTokenResponse("{\"access_token\":\"123\"}", OAuth.ContentType.JSON, 200); assertNotNull(jsonTokenResponse); }
### Question: OAuthClientResponseFactory { public static <T extends OAuthClientResponse> T createCustomResponse(String body, String contentType, int responseCode, Map<String, List<String>> headers, Class<T> clazz) throws OAuthSystemException, OAuthProblemException { OAuthClientResponse resp = OAuthUtils .instantiateClassWithParameters(clazz, null, null); resp.init(body, contentType, responseCode, headers); return (T) resp; } static OAuthClientResponse createGitHubTokenResponse(String body, String contentType, int responseCode); static OAuthClientResponse createJSONTokenResponse(String body, String contentType, int responseCode); static T createCustomResponse(String body, String contentType, int responseCode, Map<String, List<String>> headers, Class<T> clazz); static T createCustomResponse(InputStream body, String contentType, int responseCode, Map<String, List<String>> headers, Class<T> clazz); }### Answer: @Test public void testCreateCustomResponse() throws Exception { }
### Question: OAuthJSONAccessTokenResponse extends OAuthAccessTokenResponse { @Override public String getAccessToken() { return getParam(OAuth.OAUTH_ACCESS_TOKEN); } OAuthJSONAccessTokenResponse(); @Override String getAccessToken(); @Override String getTokenType(); @Override Long getExpiresIn(); String getScope(); OAuthToken getOAuthToken(); String getRefreshToken(); }### Answer: @Test public void testGetAccessToken() throws Exception { OAuthJSONAccessTokenResponse r = null; try { r = new OAuthJSONAccessTokenResponse(); r.init(TestUtils.VALID_JSON_RESPONSE, OAuth.ContentType.JSON, 200); } catch (OAuthProblemException e) { fail("Exception not expected"); } Assert.assertEquals(TestUtils.ACCESS_TOKEN, r.getAccessToken()); try { r = new OAuthJSONAccessTokenResponse(); r.init(TestUtils.ERROR_JSON_BODY, OAuth.ContentType.JSON, 200); fail("Exception expected"); } catch (OAuthProblemException e) { Assert.assertNotNull(e.getError()); } }
### Question: OAuthJSONAccessTokenResponse extends OAuthAccessTokenResponse { @Override public String getTokenType() { return getParam(OAuth.OAUTH_TOKEN_TYPE); } OAuthJSONAccessTokenResponse(); @Override String getAccessToken(); @Override String getTokenType(); @Override Long getExpiresIn(); String getScope(); OAuthToken getOAuthToken(); String getRefreshToken(); }### Answer: @Test public void testGetTokenType() throws Exception { OAuthJSONAccessTokenResponse r = null; try { r = new OAuthJSONAccessTokenResponse(); r.init(TestUtils.VALID_JSON_RESPONSE, OAuth.ContentType.JSON, 200); } catch (OAuthProblemException e) { fail("Exception not expected"); } Assert.assertEquals(TestUtils.TOKEN_TYPE, r.getTokenType()); try { r = new OAuthJSONAccessTokenResponse(); r.init(TestUtils.ERROR_JSON_BODY, OAuth.ContentType.JSON, 200); fail("Exception expected"); } catch (OAuthProblemException e) { Assert.assertNotNull(e.getError()); } }
### Question: OAuthJSONAccessTokenResponse extends OAuthAccessTokenResponse { @Override public Long getExpiresIn() { String value = getParam(OAuth.OAUTH_EXPIRES_IN); return value == null? null: Long.valueOf(value); } OAuthJSONAccessTokenResponse(); @Override String getAccessToken(); @Override String getTokenType(); @Override Long getExpiresIn(); String getScope(); OAuthToken getOAuthToken(); String getRefreshToken(); }### Answer: @Test public void testGetExpiresIn() throws Exception { OAuthJSONAccessTokenResponse r = null; try { r = new OAuthJSONAccessTokenResponse(); r.init(TestUtils.VALID_JSON_RESPONSE, OAuth.ContentType.JSON, 200); } catch (OAuthProblemException e) { fail("Exception not expected"); } Assert.assertEquals(TestUtils.EXPIRES_IN, r.getExpiresIn()); initAndAssertError(r); }
### Question: OAuthJSONAccessTokenResponse extends OAuthAccessTokenResponse { public String getScope() { return getParam(OAuth.OAUTH_SCOPE); } OAuthJSONAccessTokenResponse(); @Override String getAccessToken(); @Override String getTokenType(); @Override Long getExpiresIn(); String getScope(); OAuthToken getOAuthToken(); String getRefreshToken(); }### Answer: @Test public void testGetScope() throws Exception { OAuthJSONAccessTokenResponse r = null; try { r = new OAuthJSONAccessTokenResponse(); r.init(TestUtils.VALID_JSON_RESPONSE, OAuth.ContentType.JSON, 200); } catch (OAuthProblemException e) { fail("Exception not expected"); } Assert.assertEquals(TestUtils.SCOPE, r.getScope()); initAndAssertError(r); }
### Question: OAuthJSONAccessTokenResponse extends OAuthAccessTokenResponse { public String getRefreshToken() { return getParam(OAuth.OAUTH_REFRESH_TOKEN); } OAuthJSONAccessTokenResponse(); @Override String getAccessToken(); @Override String getTokenType(); @Override Long getExpiresIn(); String getScope(); OAuthToken getOAuthToken(); String getRefreshToken(); }### Answer: @Test public void testGetRefreshToken() throws Exception { OAuthJSONAccessTokenResponse r = null; try { r = new OAuthJSONAccessTokenResponse(); r.init(TestUtils.VALID_JSON_RESPONSE, OAuth.ContentType.JSON, 200); } catch (OAuthProblemException e) { fail("Exception not expected"); } Assert.assertEquals(TestUtils.REFRESH_TOKEN, r.getRefreshToken()); initAndAssertError(r); }
### Question: OAuthJSONAccessTokenResponse extends OAuthAccessTokenResponse { protected void setBody(String body) throws OAuthProblemException { try { this.body = body; parameters = JSONUtils.parseJSON(body); } catch (Throwable e) { throw OAuthProblemException.error(OAuthError.CodeResponse.UNSUPPORTED_RESPONSE_TYPE, "Invalid response! Response body is not " + OAuth.ContentType.JSON + " encoded"); } } OAuthJSONAccessTokenResponse(); @Override String getAccessToken(); @Override String getTokenType(); @Override Long getExpiresIn(); String getScope(); OAuthToken getOAuthToken(); String getRefreshToken(); }### Answer: @Test public void testSetBody() throws Exception { OAuthJSONAccessTokenResponse r = null; try { r = new OAuthJSONAccessTokenResponse(); r.init(TestUtils.VALID_JSON_RESPONSE, OAuth.ContentType.JSON, 200); } catch (OAuthProblemException e) { fail("Exception not expected"); } String accessToken = r.getAccessToken(); Long expiresIn = r.getExpiresIn(); Assert.assertEquals(TestUtils.EXPIRES_IN, expiresIn); Assert.assertEquals(TestUtils.ACCESS_TOKEN, accessToken); try { new OAuthJSONAccessTokenResponse(); r.init(TestUtils.ERROR_JSON_BODY, OAuth.ContentType.JSON, 200); fail("Exception expected"); } catch (OAuthProblemException e) { Assert.assertEquals(OAuthError.TokenResponse.INVALID_REQUEST, e.getError()); } }
### Question: GitHubTokenResponse extends OAuthAccessTokenResponse { @Override public String getAccessToken() { return getParam(OAuth.OAUTH_ACCESS_TOKEN); } @Override String getAccessToken(); @Override String getTokenType(); @Override Long getExpiresIn(); @Override String getRefreshToken(); @Override String getScope(); @Override OAuthToken getOAuthToken(); }### Answer: @Test public void testGetAccessToken() throws Exception { }
### Question: GitHubTokenResponse extends OAuthAccessTokenResponse { @Override public Long getExpiresIn() { String value = getParam(OAuth.OAUTH_EXPIRES_IN); return value == null? null: Long.valueOf(value); } @Override String getAccessToken(); @Override String getTokenType(); @Override Long getExpiresIn(); @Override String getRefreshToken(); @Override String getScope(); @Override OAuthToken getOAuthToken(); }### Answer: @Test public void testGetExpiresIn() throws Exception { }
### Question: GitHubTokenResponse extends OAuthAccessTokenResponse { @Override public String getRefreshToken() { return getParam(OAuth.OAUTH_REFRESH_TOKEN); } @Override String getAccessToken(); @Override String getTokenType(); @Override Long getExpiresIn(); @Override String getRefreshToken(); @Override String getScope(); @Override OAuthToken getOAuthToken(); }### Answer: @Test public void testGetRefreshToken() throws Exception { }
### Question: GitHubTokenResponse extends OAuthAccessTokenResponse { @Override public String getScope() { return getParam(OAuth.OAUTH_SCOPE); } @Override String getAccessToken(); @Override String getTokenType(); @Override Long getExpiresIn(); @Override String getRefreshToken(); @Override String getScope(); @Override OAuthToken getOAuthToken(); }### Answer: @Test public void testGetScope() throws Exception { }
### Question: OpenIdConnectResponse extends OAuthJSONAccessTokenResponse { public boolean checkId(String issuer, String audience) { if (idToken.getClaimsSet().getIssuer().equals(issuer) && idToken.getClaimsSet().getAudience().equals(audience) && idToken.getClaimsSet().getExpirationTime() < System .currentTimeMillis()) { return true; } return false; } final JWT getIdToken(); boolean checkId(String issuer, String audience); }### Answer: @Test public void testCheckId() throws NoSuchFieldException{ JWT idToken = new JWTReader().read(JWT); OpenIdConnectResponse openIdConnectResponse= new OpenIdConnectResponse(); PrivateAccessor.setField(openIdConnectResponse, "idToken", idToken); assertTrue(openIdConnectResponse.checkId("accounts.google.com", "788732372078.apps.googleusercontent.com")); assertFalse(openIdConnectResponse.checkId("wrongaccounts.google.com", "788732372078.apps.googleusercontent.com")); assertFalse(openIdConnectResponse.checkId("wrongaccounts.google.com", "notexists788732372078.apps.googleusercontent.com")); }
### Question: BitcoinUriParser implements UriParser { @Override public int linkifyUri(String text, int startPos, StringBuffer outputBuffer) { Matcher matcher = BITCOIN_URI_PATTERN.matcher(text); if (!matcher.find(startPos) || matcher.start() != startPos) { return startPos; } String bitcoinUri = matcher.group(); outputBuffer.append("<a href=\"") .append(bitcoinUri) .append("\">") .append(bitcoinUri) .append("</a>"); return matcher.end(); } @Override int linkifyUri(String text, int startPos, StringBuffer outputBuffer); }### Answer: @Test public void uriInMiddleOfInput() throws Exception { String prefix = "prefix "; String uri = "bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu?amount=1.2"; String text = prefix + uri; parser.linkifyUri(text, prefix.length(), outputBuffer); assertLinkOnly(uri, outputBuffer); }
### Question: AccountCreator { public static DeletePolicy getDefaultDeletePolicy(Type type) { switch (type) { case IMAP: { return DeletePolicy.ON_DELETE; } case POP3: { return DeletePolicy.NEVER; } case WebDAV: { return DeletePolicy.ON_DELETE; } case EWS: { return DeletePolicy.ON_DELETE; } case SMTP: { throw new IllegalStateException("Delete policy doesn't apply to SMTP"); } } throw new AssertionError("Unhandled case: " + type); } static DeletePolicy getDefaultDeletePolicy(Type type); static int getDefaultPort(ConnectionSecurity securityType, Type storeType); }### Answer: @Test public void getDefaultDeletePolicy_withImap_shouldReturn_ON_DELETE() { DeletePolicy result = AccountCreator.getDefaultDeletePolicy(Type.IMAP); assertEquals(DeletePolicy.ON_DELETE, result); } @Test public void getDefaultDeletePolicy_withPop3_shouldReturn_NEVER() { DeletePolicy result = AccountCreator.getDefaultDeletePolicy(Type.POP3); assertEquals(DeletePolicy.NEVER, result); } @Test public void getDefaultDeletePolicy_withWebDav_shouldReturn_ON_DELETE() { DeletePolicy result = AccountCreator.getDefaultDeletePolicy(Type.WebDAV); assertEquals(DeletePolicy.ON_DELETE, result); }
### Question: AccountCreator { public static int getDefaultPort(ConnectionSecurity securityType, Type storeType) { switch (securityType) { case NONE: case STARTTLS_REQUIRED: { return storeType.defaultPort; } case SSL_TLS_REQUIRED: { return storeType.defaultTlsPort; } } throw new AssertionError("Unhandled ConnectionSecurity type encountered: " + securityType); } static DeletePolicy getDefaultDeletePolicy(Type type); static int getDefaultPort(ConnectionSecurity securityType, Type storeType); }### Answer: @Test public void getDefaultPort_withNoConnectionSecurityAndImap_shouldReturnDefaultPort() { int result = AccountCreator.getDefaultPort(ConnectionSecurity.NONE, Type.IMAP); assertEquals(Type.IMAP.defaultPort, result); } @Test public void getDefaultPort_withStartTlsAndImap_shouldReturnDefaultPort() { int result = AccountCreator.getDefaultPort(ConnectionSecurity.STARTTLS_REQUIRED, Type.IMAP); assertEquals(Type.IMAP.defaultPort, result); } @Test public void getDefaultPort_withTlsAndImap_shouldReturnDefaultTlsPort() { int result = AccountCreator.getDefaultPort(ConnectionSecurity.SSL_TLS_REQUIRED, Type.IMAP); assertEquals(Type.IMAP.defaultTlsPort, result); }
### Question: MessageDecryptVerifier { @VisibleForTesting static boolean isPartPgpInlineEncryptedOrSigned(Part part) { if (!part.isMimeType(TEXT_PLAIN) && !part.isMimeType(APPLICATION_PGP)) { return false; } String text = MessageExtractor.getTextFromPart(part, TEXT_LENGTH_FOR_INLINE_CHECK); if (TextUtils.isEmpty(text)) { return false; } text = text.trim(); return text.startsWith(PGP_INLINE_START_MARKER) || text.startsWith(PGP_INLINE_SIGNED_START_MARKER); } static Part findPrimaryEncryptedOrSignedPart(Part part, List<Part> outputExtraParts); static List<Part> findEncryptedParts(Part startPart); static List<Part> findSignedParts(Part startPart, MessageCryptoAnnotations messageCryptoAnnotations); static List<Part> findPgpInlineParts(Part startPart); static byte[] getSignatureData(Part part); static boolean isPgpMimeEncryptedOrSignedPart(Part part); static boolean isSMimeEncryptedOrSignedPart(Part part); static boolean isPartPgpInlineEncrypted(@Nullable Part part); }### Answer: @Test public void isPartPgpInlineEncryptedOrSigned__withSignedData__shouldReturnTrue() throws Exception { String pgpInlineData = "-----BEGIN PGP SIGNED MESSAGE-----\n" + "Header: Value\n" + "\n" + "-----BEGIN PGP SIGNATURE-----\n" + "Header: Value\n" + "\n" + "base64base64base64base64\n" + "-----END PGP SIGNED MESSAGE-----\n"; MimeMessage message = new MimeMessage(); message.setBody(new TextBody(pgpInlineData)); assertTrue(MessageDecryptVerifier.isPartPgpInlineEncryptedOrSigned(message)); }
### Question: DeferredFileBody implements RawDataBody, SizeAware { @Override public long getSize() { if (file != null) { return file.length(); } if (data != null) { return data.length; } throw new IllegalStateException("Data must be fully written before it can be read!"); } DeferredFileBody(FileFactory fileFactory, String transferEncoding); @VisibleForTesting DeferredFileBody(int memoryBackedThreshold, FileFactory fileFactory, String transferEncoding); OutputStream getOutputStream(); @Override InputStream getInputStream(); @Override long getSize(); File getFile(); @Override void setEncoding(String encoding); @Override void writeTo(OutputStream out); @Override String getEncoding(); static final int DEFAULT_MEMORY_BACKED_THRESHOLD; }### Answer: @Test public void withShortData__getLength__shouldReturnWrittenLength() throws Exception { writeShortTestData(); assertNull(createdFile); assertEquals(TEST_DATA_SHORT.length, deferredFileBody.getSize()); } @Test public void withLongData__getLength__shouldReturnWrittenLength() throws Exception { writeLongTestData(); assertNotNull(createdFile); assertEquals(TEST_DATA_LONG.length, deferredFileBody.getSize()); }
### Question: DeferredFileBody implements RawDataBody, SizeAware { @Override public InputStream getInputStream() throws MessagingException { try { if (file != null) { Timber.d("Decrypted data is file-backed."); return new BufferedInputStream(new FileInputStream(file)); } if (data != null) { Timber.d("Decrypted data is memory-backed."); return new ByteArrayInputStream(data); } throw new IllegalStateException("Data must be fully written before it can be read!"); } catch (IOException ioe) { throw new MessagingException("Unable to open body", ioe); } } DeferredFileBody(FileFactory fileFactory, String transferEncoding); @VisibleForTesting DeferredFileBody(int memoryBackedThreshold, FileFactory fileFactory, String transferEncoding); OutputStream getOutputStream(); @Override InputStream getInputStream(); @Override long getSize(); File getFile(); @Override void setEncoding(String encoding); @Override void writeTo(OutputStream out); @Override String getEncoding(); static final int DEFAULT_MEMORY_BACKED_THRESHOLD; }### Answer: @Test public void withShortData__shouldReturnData() throws Exception { writeShortTestData(); InputStream inputStream = deferredFileBody.getInputStream(); byte[] data = IOUtils.toByteArray(inputStream); assertNull(createdFile); assertArrayEquals(TEST_DATA_SHORT, data); } @Test public void withLongData__shouldReturnData() throws Exception { writeLongTestData(); InputStream inputStream = deferredFileBody.getInputStream(); byte[] data = IOUtils.toByteArray(inputStream); InputStream fileInputStream = new FileInputStream(createdFile); byte[] dataFromFile = IOUtils.toByteArray(fileInputStream); assertArrayEquals(TEST_DATA_LONG, data); assertArrayEquals(TEST_DATA_LONG, dataFromFile); }
### Question: DeferredFileBody implements RawDataBody, SizeAware { public File getFile() throws IOException { if (file == null) { writeMemoryToFile(); } return file; } DeferredFileBody(FileFactory fileFactory, String transferEncoding); @VisibleForTesting DeferredFileBody(int memoryBackedThreshold, FileFactory fileFactory, String transferEncoding); OutputStream getOutputStream(); @Override InputStream getInputStream(); @Override long getSize(); File getFile(); @Override void setEncoding(String encoding); @Override void writeTo(OutputStream out); @Override String getEncoding(); static final int DEFAULT_MEMORY_BACKED_THRESHOLD; }### Answer: @Test public void withShortData__getFile__shouldWriteDataToFile() throws Exception { writeShortTestData(); File returnedFile = deferredFileBody.getFile(); InputStream fileInputStream = new FileInputStream(returnedFile); byte[] dataFromFile = IOUtils.toByteArray(fileInputStream); assertSame(createdFile, returnedFile); assertArrayEquals(TEST_DATA_SHORT, dataFromFile); } @Test public void withLongData__getFile__shouldReturnCreatedFile() throws Exception { writeLongTestData(); File returnedFile = deferredFileBody.getFile(); assertSame(createdFile, returnedFile); }
### Question: DeferredFileBody implements RawDataBody, SizeAware { @Override public void writeTo(OutputStream out) throws IOException, MessagingException { InputStream inputStream = getInputStream(); IOUtils.copy(inputStream, out); } DeferredFileBody(FileFactory fileFactory, String transferEncoding); @VisibleForTesting DeferredFileBody(int memoryBackedThreshold, FileFactory fileFactory, String transferEncoding); OutputStream getOutputStream(); @Override InputStream getInputStream(); @Override long getSize(); File getFile(); @Override void setEncoding(String encoding); @Override void writeTo(OutputStream out); @Override String getEncoding(); static final int DEFAULT_MEMORY_BACKED_THRESHOLD; }### Answer: @Test public void withShortData__writeTo__shouldWriteData() throws Exception { writeShortTestData(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); deferredFileBody.writeTo(baos); assertArrayEquals(TEST_DATA_SHORT, baos.toByteArray()); }
### Question: DeferredFileBody implements RawDataBody, SizeAware { @Override public void setEncoding(String encoding) throws MessagingException { throw new UnsupportedOperationException("Cannot re-encode a DecryptedTempFileBody!"); } DeferredFileBody(FileFactory fileFactory, String transferEncoding); @VisibleForTesting DeferredFileBody(int memoryBackedThreshold, FileFactory fileFactory, String transferEncoding); OutputStream getOutputStream(); @Override InputStream getInputStream(); @Override long getSize(); File getFile(); @Override void setEncoding(String encoding); @Override void writeTo(OutputStream out); @Override String getEncoding(); static final int DEFAULT_MEMORY_BACKED_THRESHOLD; }### Answer: @Test(expected = UnsupportedOperationException.class) public void setEncoding__shouldThrow() throws Exception { deferredFileBody.setEncoding("anything"); }
### Question: DeferredFileBody implements RawDataBody, SizeAware { @Override public String getEncoding() { return encoding; } DeferredFileBody(FileFactory fileFactory, String transferEncoding); @VisibleForTesting DeferredFileBody(int memoryBackedThreshold, FileFactory fileFactory, String transferEncoding); OutputStream getOutputStream(); @Override InputStream getInputStream(); @Override long getSize(); File getFile(); @Override void setEncoding(String encoding); @Override void writeTo(OutputStream out); @Override String getEncoding(); static final int DEFAULT_MEMORY_BACKED_THRESHOLD; }### Answer: @Test public void getEncoding__shouldReturnEncoding() throws Exception { assertEquals(TEST_ENCODING, deferredFileBody.getEncoding()); }
### Question: StoreSchemaDefinition implements LockableDatabase.SchemaDefinition { @Override public int getVersion() { return LocalStore.DB_VERSION; } StoreSchemaDefinition(LocalStore localStore); @Override int getVersion(); @Override void doDbUpgrade(final SQLiteDatabase db); }### Answer: @Test public void getVersion_shouldReturnCurrentDatabaseVersion() { int version = storeSchemaDefinition.getVersion(); assertEquals(LocalStore.DB_VERSION, version); }
### Question: StoreSchemaDefinition implements LockableDatabase.SchemaDefinition { @Override public void doDbUpgrade(final SQLiteDatabase db) { try { upgradeDatabase(db); } catch (Exception e) { if (BuildConfig.DEBUG) { throw new Error("Exception while upgrading database", e); } Timber.e(e, "Exception while upgrading database. Resetting the DB to v0"); db.setVersion(0); upgradeDatabase(db); } } StoreSchemaDefinition(LocalStore localStore); @Override int getVersion(); @Override void doDbUpgrade(final SQLiteDatabase db); }### Answer: @Test public void doDbUpgrade_withBadDatabase_shouldThrowInDebugBuild() { if (BuildConfig.DEBUG) { SQLiteDatabase database = SQLiteDatabase.create(null); database.setVersion(29); try { storeSchemaDefinition.doDbUpgrade(database); fail("Expected Error"); } catch (Error e) { assertEquals("Exception while upgrading database", e.getMessage()); } } } @Test public void doDbUpgrade_withV29() { SQLiteDatabase database = createV29Database(); insertMessageWithSubject(database, "Test Email"); storeSchemaDefinition.doDbUpgrade(database); assertMessageWithSubjectExists(database, "Test Email"); } @Test public void doDbUpgrade_fromV29_shouldResultInSameTables() { SQLiteDatabase newDatabase = createNewDatabase(); SQLiteDatabase upgradedDatabase = createV29Database(); storeSchemaDefinition.doDbUpgrade(upgradedDatabase); assertDatabaseTablesEquals(newDatabase, upgradedDatabase); } @Test public void doDbUpgrade_fromV29_shouldResultInSameTriggers() { SQLiteDatabase newDatabase = createNewDatabase(); SQLiteDatabase upgradedDatabase = createV29Database(); storeSchemaDefinition.doDbUpgrade(upgradedDatabase); assertDatabaseTriggersEquals(newDatabase, upgradedDatabase); } @Test public void doDbUpgrade_fromV29_shouldResultInSameIndexes() { SQLiteDatabase newDatabase = createNewDatabase(); SQLiteDatabase upgradedDatabase = createV29Database(); storeSchemaDefinition.doDbUpgrade(upgradedDatabase); assertDatabaseIndexesEquals(newDatabase, upgradedDatabase); }
### Question: MigrationTo60 { static void migratePendingCommands(SQLiteDatabase db) { List<PendingCommand> pendingCommands = new ArrayList<>(); if (columnExists(db, "pending_commands", "arguments")) { for (OldPendingCommand oldPendingCommand : getPendingCommands(db)) { PendingCommand newPendingCommand = migratePendingCommand(oldPendingCommand); pendingCommands.add(newPendingCommand); } db.execSQL("DROP TABLE IF EXISTS pending_commands"); db.execSQL("CREATE TABLE pending_commands (" + "id INTEGER PRIMARY KEY, " + "command TEXT, " + "data TEXT" + ")"); PendingCommandSerializer pendingCommandSerializer = PendingCommandSerializer.getInstance(); for (PendingCommand pendingCommand : pendingCommands) { ContentValues cv = new ContentValues(); cv.put("command", pendingCommand.getCommandName()); cv.put("data", pendingCommandSerializer.serialize(pendingCommand)); db.insert("pending_commands", "command", cv); } } } }### Answer: @Test public void migratePendingCommands_shouldChangeTableStructure() { SQLiteDatabase database = createV59Table(); MigrationTo60.migratePendingCommands(database); List<String> columns = getColumnList(database, "pending_commands"); assertEquals(asList("id", "command", "data"), columns); } @Test public void migratePendingCommands_withMultipleRuns_shouldNotThrow() { SQLiteDatabase database = createV59Table(); MigrationTo60.migratePendingCommands(database); MigrationTo60.migratePendingCommands(database); }
### Question: EmailProviderCache { public static synchronized EmailProviderCache getCache(String accountUuid, Context context) { if (sContext == null) { sContext = context.getApplicationContext(); } EmailProviderCache instance = sInstances.get(accountUuid); if (instance == null) { instance = new EmailProviderCache(accountUuid); sInstances.put(accountUuid, instance); } return instance; } private EmailProviderCache(String accountUuid); static synchronized EmailProviderCache getCache(String accountUuid, Context context); String getValueForMessage(Long messageId, String columnName); String getValueForThread(Long threadRootId, String columnName); void setValueForMessages(List<Long> messageIds, String columnName, String value); void setValueForThreads(List<Long> threadRootIds, String columnName, String value); void removeValueForMessages(List<Long> messageIds, String columnName); void removeValueForThreads(List<Long> threadRootIds, String columnName); void hideMessages(List<LocalMessage> messages); boolean isMessageHidden(Long messageId, long folderId); void unhideMessages(List<? extends Message> messages); static final String ACTION_CACHE_UPDATED; }### Answer: @Test public void getCache_returnsDifferentCacheForEachUUID() { EmailProviderCache cache = EmailProviderCache.getCache("u001", RuntimeEnvironment.application); EmailProviderCache cache2 = EmailProviderCache.getCache("u002", RuntimeEnvironment.application); assertNotEquals(cache, cache2); } @Test public void getCache_returnsSameCacheForAUUID() { EmailProviderCache cache = EmailProviderCache.getCache("u001", RuntimeEnvironment.application); EmailProviderCache cache2 = EmailProviderCache.getCache("u001", RuntimeEnvironment.application); assertSame(cache, cache2); }
### Question: EmailProviderCache { public String getValueForMessage(Long messageId, String columnName) { synchronized (mMessageCache) { Map<String, String> map = mMessageCache.get(messageId); return (map == null) ? null : map.get(columnName); } } private EmailProviderCache(String accountUuid); static synchronized EmailProviderCache getCache(String accountUuid, Context context); String getValueForMessage(Long messageId, String columnName); String getValueForThread(Long threadRootId, String columnName); void setValueForMessages(List<Long> messageIds, String columnName, String value); void setValueForThreads(List<Long> threadRootIds, String columnName, String value); void removeValueForMessages(List<Long> messageIds, String columnName); void removeValueForThreads(List<Long> threadRootIds, String columnName); void hideMessages(List<LocalMessage> messages); boolean isMessageHidden(Long messageId, long folderId); void unhideMessages(List<? extends Message> messages); static final String ACTION_CACHE_UPDATED; }### Answer: @Test public void getValueForUnknownMessage_returnsNull() { String result = cache.getValueForMessage(1L, "subject"); assertNull(result); }
### Question: EmailProviderCache { public String getValueForThread(Long threadRootId, String columnName) { synchronized (mThreadCache) { Map<String, String> map = mThreadCache.get(threadRootId); return (map == null) ? null : map.get(columnName); } } private EmailProviderCache(String accountUuid); static synchronized EmailProviderCache getCache(String accountUuid, Context context); String getValueForMessage(Long messageId, String columnName); String getValueForThread(Long threadRootId, String columnName); void setValueForMessages(List<Long> messageIds, String columnName, String value); void setValueForThreads(List<Long> threadRootIds, String columnName, String value); void removeValueForMessages(List<Long> messageIds, String columnName); void removeValueForThreads(List<Long> threadRootIds, String columnName); void hideMessages(List<LocalMessage> messages); boolean isMessageHidden(Long messageId, long folderId); void unhideMessages(List<? extends Message> messages); static final String ACTION_CACHE_UPDATED; }### Answer: @Test public void getValueForUnknownThread_returnsNull() { String result = cache.getValueForThread(1L, "subject"); assertNull(result); }
### Question: EmailProviderCache { public boolean isMessageHidden(Long messageId, long folderId) { synchronized (mHiddenMessageCache) { Long hiddenInFolder = mHiddenMessageCache.get(messageId); return (hiddenInFolder != null && hiddenInFolder.longValue() == folderId); } } private EmailProviderCache(String accountUuid); static synchronized EmailProviderCache getCache(String accountUuid, Context context); String getValueForMessage(Long messageId, String columnName); String getValueForThread(Long threadRootId, String columnName); void setValueForMessages(List<Long> messageIds, String columnName, String value); void setValueForThreads(List<Long> threadRootIds, String columnName, String value); void removeValueForMessages(List<Long> messageIds, String columnName); void removeValueForThreads(List<Long> threadRootIds, String columnName); void hideMessages(List<LocalMessage> messages); boolean isMessageHidden(Long messageId, long folderId); void unhideMessages(List<? extends Message> messages); static final String ACTION_CACHE_UPDATED; }### Answer: @Test public void isMessageHidden_returnsFalseForUnknownMessage() { boolean result = cache.isMessageHidden(localMessageId, localMessageFolderId); assertFalse(result); }
### Question: K9AlarmManager { public void set(int type, long triggerAtMillis, PendingIntent operation) { if (dozeChecker.isDeviceIdleModeSupported() && dozeChecker.isAppWhitelisted()) { setAndAllowWhileIdle(type, triggerAtMillis, operation); } else { alarmManager.set(type, triggerAtMillis, operation); } } @VisibleForTesting K9AlarmManager(AlarmManager alarmManager, DozeChecker dozeChecker); static K9AlarmManager getAlarmManager(Context context); void set(int type, long triggerAtMillis, PendingIntent operation); void cancel(PendingIntent operation); }### Answer: @Test public void set_withoutDozeSupport_shouldCallSetOnAlarmManager() throws Exception { configureDozeSupport(false); alarmManager.set(TIMER_TYPE, TIMEOUT, PENDING_INTENT); verify(systemAlarmManager).set(TIMER_TYPE, TIMEOUT, PENDING_INTENT); } @Test public void set_withDozeSupportAndNotWhiteListed_shouldCallSetOnAlarmManager() throws Exception { configureDozeSupport(true); alarmManager.set(TIMER_TYPE, TIMEOUT, PENDING_INTENT); verify(systemAlarmManager).set(TIMER_TYPE, TIMEOUT, PENDING_INTENT); }
### Question: K9AlarmManager { public void cancel(PendingIntent operation) { alarmManager.cancel(operation); } @VisibleForTesting K9AlarmManager(AlarmManager alarmManager, DozeChecker dozeChecker); static K9AlarmManager getAlarmManager(Context context); void set(int type, long triggerAtMillis, PendingIntent operation); void cancel(PendingIntent operation); }### Answer: @Test public void cancel_shouldCallCancelOnAlarmManager() throws Exception { configureDozeSupport(true); addAppToBatteryOptimizationWhitelist(); alarmManager.cancel(PENDING_INTENT); verify(systemAlarmManager).cancel(PENDING_INTENT); }
### Question: Utility { public static String stripNewLines(String multiLineString) { return multiLineString.replaceAll("[\\r\\n]", ""); } static boolean arrayContains(Object[] a, Object o); static boolean isAnyMimeType(String o, String... a); static boolean arrayContainsAny(Object[] a, Object... o); static String combine(Object[] parts, char separator); static String combine(Iterable<?> parts, char separator); static boolean requiredFieldValid(TextView view); static boolean requiredFieldValid(Editable s); static boolean domainFieldValid(EditText view); static void setCompoundDrawablesAlpha(TextView view, int alpha); static String wrap(String str, int wrapLength); static String wrap(String str, int wrapLength, String newLineStr, boolean wrapLongWords); static String stripSubject(final String subject); static String stripNewLines(String multiLineString); static boolean hasExternalImages(final String message); static void closeQuietly(final Cursor cursor); static boolean hasConnectivity(final Context context); static List<String> extractMessageIds(final String text); static String extractMessageId(final String text); static Handler getMainThreadHandler(); static void setContactForBadge(ContactBadge contactBadge, Address address); }### Answer: @Test public void stripNewLines_removesLeadingCarriageReturns() { String result = Utility.stripNewLines("\r\rTest"); assertEquals("Test", result); } @Test public void stripNewLines_removesLeadingLineFeeds() { String result = Utility.stripNewLines("\n\nTest\n\n"); assertEquals("Test", result); } @Test public void stripNewLines_removesTrailingCarriageReturns() { String result = Utility.stripNewLines("Test\r\r"); assertEquals("Test", result); } @Test public void stripNewLines_removesMidCarriageReturns() { String result = Utility.stripNewLines("Test\rTest"); assertEquals("TestTest", result); } @Test public void stripNewLines_removesMidLineFeeds() { String result = Utility.stripNewLines("Test\nTest"); assertEquals("TestTest", result); }
### Question: MailTo { public static boolean isMailTo(Uri uri) { return uri != null && MAILTO_SCHEME.equals(uri.getScheme()); } private MailTo(Address[] toAddresses, Address[] ccAddresses, Address[] bccAddresses, String subject, String body); static boolean isMailTo(Uri uri); static MailTo parse(Uri uri); Address[] getTo(); Address[] getCc(); Address[] getBcc(); String getSubject(); String getBody(); }### Answer: @SuppressWarnings("ConstantConditions") @Test public void testIsMailTo_nullArgument() { Uri uri = null; boolean result = MailTo.isMailTo(uri); assertFalse(result); }
### Question: MailTo { public String getSubject() { return subject; } private MailTo(Address[] toAddresses, Address[] ccAddresses, Address[] bccAddresses, String subject, String body); static boolean isMailTo(Uri uri); static MailTo parse(Uri uri); Address[] getTo(); Address[] getCc(); Address[] getBcc(); String getSubject(); String getBody(); }### Answer: @Test public void testGetSubject() { Uri uri = Uri.parse("mailto:?subject=Hello"); MailTo mailToHelper = MailTo.parse(uri); String subject = mailToHelper.getSubject(); assertEquals(subject, "Hello"); }
### Question: MailTo { public String getBody() { return body; } private MailTo(Address[] toAddresses, Address[] ccAddresses, Address[] bccAddresses, String subject, String body); static boolean isMailTo(Uri uri); static MailTo parse(Uri uri); Address[] getTo(); Address[] getCc(); Address[] getBcc(); String getSubject(); String getBody(); }### Answer: @Test public void testGetBody() { Uri uri = Uri.parse("mailto:?body=Test%20Body&something=else"); MailTo mailToHelper = MailTo.parse(uri); String subject = mailToHelper.getBody(); assertEquals(subject, "Test Body"); }
### Question: EmailHelper { public static String getDomainFromEmailAddress(String email) { int separatorIndex = email.lastIndexOf('@'); if (separatorIndex == -1 || separatorIndex + 1 == email.length()) { return null; } return email.substring(separatorIndex + 1); } private EmailHelper(); static String getDomainFromEmailAddress(String email); }### Answer: @Test public void getDomainFromEmailAddress_withRegularEmail_shouldReturnsDomain() { String result = EmailHelper.getDomainFromEmailAddress("[email protected]"); assertEquals("domain.com", result); } @Test public void getDomainFromEmailAddress_withInvalidEmail_shouldReturnNull() { String result = EmailHelper.getDomainFromEmailAddress("user"); assertNull(result); } @Test public void getDomainFromEmailAddress_withTLD_shouldReturnDomain() { String result = EmailHelper.getDomainFromEmailAddress("user@domain"); assertEquals("domain", result); }
### Question: ReplyToParser { public ReplyToAddresses getRecipientsToReplyListTo(Message message, Account account) { Address[] candidateAddress; Address[] listPostAddresses = ListHeaders.getListPostAddresses(message); Address[] replyToAddresses = message.getReplyTo(); Address[] fromAddresses = message.getFrom(); if (listPostAddresses.length > 0) { candidateAddress = listPostAddresses; } else if (replyToAddresses.length > 0) { candidateAddress = replyToAddresses; } else { candidateAddress = fromAddresses; } boolean replyToAddressIsUserIdentity = account.isAnIdentity(candidateAddress); if (replyToAddressIsUserIdentity) { candidateAddress = message.getRecipients(RecipientType.TO); } return new ReplyToAddresses(candidateAddress); } ReplyToAddresses getRecipientsToReplyTo(Message message, Account account); ReplyToAddresses getRecipientsToReplyListTo(Message message, Account account); ReplyToAddresses getRecipientsToReplyAllTo(Message message, Account account); }### Answer: @Test public void getRecipientsToReplyListTo_should_prefer_listPost_over_from_field() throws Exception { when(message.getReplyTo()).thenReturn(EMPTY_ADDRESSES); when(message.getHeader(ListHeaders.LIST_POST_HEADER)).thenReturn(LIST_POST_HEADER_VALUES); when(message.getFrom()).thenReturn(FROM_ADDRESSES); ReplyToAddresses result = replyToParser.getRecipientsToReplyListTo(message, account); assertArrayEquals(LIST_POST_ADDRESSES, result.to); assertArrayEquals(EMPTY_ADDRESSES, result.cc); verify(account).isAnIdentity(result.to); }
### Question: MessageReference { public String toIdentityString() { StringBuilder refString = new StringBuilder(); refString.append(IDENTITY_VERSION_1); refString.append(IDENTITY_SEPARATOR); refString.append(Base64.encode(accountUuid)); refString.append(IDENTITY_SEPARATOR); refString.append(Base64.encode(folderId)); refString.append(IDENTITY_SEPARATOR); refString.append(Base64.encode(uid)); if (flag != null) { refString.append(IDENTITY_SEPARATOR); refString.append(flag.name()); } return refString.toString(); } MessageReference(String accountUuid, String folderId, String uid, Flag flag); @Nullable static MessageReference parse(String identity); String toIdentityString(); @Override boolean equals(Object o); boolean equals(String accountUuid, String folderId, String uid); @Override int hashCode(); @Override String toString(); String getAccountUuid(); String getFolderId(); String getUid(); Flag getFlag(); MessageReference withModifiedUid(String newUid); MessageReference withModifiedFlag(Flag newFlag); }### Answer: @Test public void checkIdentityStringFromMessageReferenceWithoutFlag() { MessageReference messageReference = createMessageReference("o hai!", "folder", "10101010"); assertEquals("!:byBoYWkh:Zm9sZGVy:MTAxMDEwMTA=", messageReference.toIdentityString()); } @Test public void checkIdentityStringFromMessageReferenceWithFlag() { MessageReference messageReference = createMessageReferenceWithFlag("o hai!", "folder", "10101010", Flag.ANSWERED); assertEquals("!:byBoYWkh:Zm9sZGVy:MTAxMDEwMTA=:ANSWERED", messageReference.toIdentityString()); }
### Question: MessageReference { @Nullable public static MessageReference parse(String identity) { if (identity == null || identity.length() < 1 || identity.charAt(0) != IDENTITY_VERSION_1) { return null; } StringTokenizer tokens = new StringTokenizer(identity.substring(2), IDENTITY_SEPARATOR, false); if (tokens.countTokens() < 3) { return null; } String accountUuid = Base64.decode(tokens.nextToken()); String folderId = Base64.decode(tokens.nextToken()); String uid = Base64.decode(tokens.nextToken()); if (!tokens.hasMoreTokens()) { return new MessageReference(accountUuid, folderId, uid, null); } Flag flag; try { flag = Flag.valueOf(tokens.nextToken()); } catch (IllegalArgumentException e) { return null; } return new MessageReference(accountUuid, folderId, uid, flag); } MessageReference(String accountUuid, String folderId, String uid, Flag flag); @Nullable static MessageReference parse(String identity); String toIdentityString(); @Override boolean equals(Object o); boolean equals(String accountUuid, String folderId, String uid); @Override int hashCode(); @Override String toString(); String getAccountUuid(); String getFolderId(); String getUid(); Flag getFlag(); MessageReference withModifiedUid(String newUid); MessageReference withModifiedFlag(Flag newFlag); }### Answer: @Test public void parseIdentityStringContainingBadVersionNumber() { MessageReference messageReference = MessageReference.parse("@:byBoYWkh:Zm9sZGVy:MTAxMDEwMTA=:ANSWERED"); assertNull(messageReference); } @Test public void parseNullIdentityString() { MessageReference messageReference = MessageReference.parse(null); assertNull(messageReference); } @Test public void parseIdentityStringWithCorruptFlag() { MessageReference messageReference = MessageReference.parse("!:%^&%^*$&$by&(BYWkh:Zm9%^@sZGVy:MT-35#$AxMDEwMTA=:ANSWE!RED"); assertNull(messageReference); }
### Question: BaseNotifications { protected NotificationCompat.Builder createAndInitializeNotificationBuilder(Account account) { return controller.createNotificationBuilder() .setSmallIcon(getNewMailNotificationIcon()) .setColor(account.getChipColor()) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setCategory(NotificationCompat.CATEGORY_EMAIL); } protected BaseNotifications(NotificationController controller, NotificationActionCreator actionCreator); }### Answer: @Test public void testCreateAndInitializeNotificationBuilder() throws Exception { Account account = createFakeAccount(); Builder builder = notifications.createAndInitializeNotificationBuilder(account); verify(builder).setSmallIcon(R.drawable.notification_icon_new_mail); verify(builder).setColor(ACCOUNT_COLOR); verify(builder).setAutoCancel(true); }
### Question: BaseNotifications { protected boolean isDeleteActionEnabled() { NotificationQuickDelete deleteOption = QMail.getNotificationQuickDeleteBehaviour(); return deleteOption == NotificationQuickDelete.ALWAYS || deleteOption == NotificationQuickDelete.FOR_SINGLE_MSG; } protected BaseNotifications(NotificationController controller, NotificationActionCreator actionCreator); }### Answer: @Test public void testIsDeleteActionEnabled_NotificationQuickDelete_ALWAYS() throws Exception { QMail.setNotificationQuickDeleteBehaviour(NotificationQuickDelete.ALWAYS); boolean result = notifications.isDeleteActionEnabled(); assertTrue(result); } @Test public void testIsDeleteActionEnabled_NotificationQuickDelete_FOR_SINGLE_MSG() throws Exception { QMail.setNotificationQuickDeleteBehaviour(NotificationQuickDelete.FOR_SINGLE_MSG); boolean result = notifications.isDeleteActionEnabled(); assertTrue(result); } @Test public void testIsDeleteActionEnabled_NotificationQuickDelete_NEVER() throws Exception { QMail.setNotificationQuickDeleteBehaviour(NotificationQuickDelete.NEVER); boolean result = notifications.isDeleteActionEnabled(); assertFalse(result); }
### Question: BaseNotifications { protected NotificationCompat.Builder createBigTextStyleNotification(Account account, NotificationHolder holder, int notificationId) { String accountName = controller.getAccountName(account); NotificationContent content = holder.content; String groupKey = NotificationGroupKeys.getGroupKey(account); NotificationCompat.Builder builder = createAndInitializeNotificationBuilder(account) .setTicker(content.summary) .setGroup(groupKey) .setContentTitle(content.sender) .setContentText(content.subject) .setSubText(accountName); NotificationCompat.BigTextStyle style = createBigTextStyle(builder); style.bigText(content.preview); builder.setStyle(style); PendingIntent contentIntent = actionCreator.createViewMessagePendingIntent( content.messageReference, notificationId); builder.setContentIntent(contentIntent); return builder; } protected BaseNotifications(NotificationController controller, NotificationActionCreator actionCreator); }### Answer: @Test public void testCreateBigTextStyleNotification() throws Exception { Account account = createFakeAccount(); int notificationId = 23; NotificationHolder holder = createNotificationHolder(notificationId); Builder builder = notifications.createBigTextStyleNotification(account, holder, notificationId); verify(builder).setTicker(NOTIFICATION_SUMMARY); verify(builder).setGroup("newMailNotifications-" + ACCOUNT_NUMBER); verify(builder).setContentTitle(SENDER); verify(builder).setContentText(SUBJECT); verify(builder).setSubText(ACCOUNT_NAME); BigTextStyle bigTextStyle = notifications.bigTextStyle; verify(bigTextStyle).bigText(NOTIFICATION_PREVIEW); verify(builder).setStyle(bigTextStyle); }
### Question: AuthenticationErrorNotifications { public void showAuthenticationErrorNotification(Account account, boolean incoming) { int notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, incoming); Context context = controller.getContext(); PendingIntent editServerSettingsPendingIntent = createContentIntent(context, account, incoming); String title = context.getString(R.string.notification_authentication_error_title); String text = context.getString(R.string.notification_authentication_error_text, account.getDescription()); NotificationCompat.Builder builder = controller.createNotificationBuilder() .setSmallIcon(R.drawable.notification_icon_warning) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setTicker(title) .setContentTitle(title) .setContentText(text) .setContentIntent(editServerSettingsPendingIntent) .setStyle(new BigTextStyle().bigText(text)) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_ERROR); controller.configureNotification(builder, null, null, NOTIFICATION_LED_FAILURE_COLOR, NOTIFICATION_LED_BLINK_FAST, true); getNotificationManager().notify(notificationId, builder.build()); } AuthenticationErrorNotifications(NotificationController controller); void showAuthenticationErrorNotification(Account account, boolean incoming); void clearAuthenticationErrorNotification(Account account, boolean incoming); }### Answer: @Test public void showAuthenticationErrorNotification_withIncomingServer_shouldCreateNotification() throws Exception { int notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, INCOMING); authenticationErrorNotifications.showAuthenticationErrorNotification(account, INCOMING); verify(notificationManager).notify(eq(notificationId), any(Notification.class)); assertAuthenticationErrorNotificationContents(); } @Test public void showAuthenticationErrorNotification_withOutgoingServer_shouldCreateNotification() throws Exception { int notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, OUTGOING); authenticationErrorNotifications.showAuthenticationErrorNotification(account, OUTGOING); verify(notificationManager).notify(eq(notificationId), any(Notification.class)); assertAuthenticationErrorNotificationContents(); }
### Question: AuthenticationErrorNotifications { public void clearAuthenticationErrorNotification(Account account, boolean incoming) { int notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, incoming); getNotificationManager().cancel(notificationId); } AuthenticationErrorNotifications(NotificationController controller); void showAuthenticationErrorNotification(Account account, boolean incoming); void clearAuthenticationErrorNotification(Account account, boolean incoming); }### Answer: @Test public void clearAuthenticationErrorNotification_withIncomingServer_shouldCancelNotification() throws Exception { int notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, INCOMING); authenticationErrorNotifications.clearAuthenticationErrorNotification(account, INCOMING); verify(notificationManager).cancel(notificationId); } @Test public void clearAuthenticationErrorNotification_withOutgoingServer_shouldCancelNotification() throws Exception { int notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, OUTGOING); authenticationErrorNotifications.clearAuthenticationErrorNotification(account, OUTGOING); verify(notificationManager).cancel(notificationId); }
### Question: LockScreenNotification { String createCommaSeparatedListOfSenders(List<NotificationContent> contents) { Set<CharSequence> senders = new LinkedHashSet<CharSequence>(MAX_NUMBER_OF_SENDERS_IN_LOCK_SCREEN_NOTIFICATION); for (NotificationContent content : contents) { senders.add(content.sender); if (senders.size() == MAX_NUMBER_OF_SENDERS_IN_LOCK_SCREEN_NOTIFICATION) { break; } } return TextUtils.join(", ", senders); } LockScreenNotification(NotificationController controller); static LockScreenNotification newInstance(NotificationController controller); void configureLockScreenNotification(Builder builder, NotificationData notificationData); }### Answer: @Test public void createCommaSeparatedListOfSenders_withMoreSendersThanShouldBeDisplayed() throws Exception { NotificationContent content1 = createNotificationContent("[email protected]"); NotificationContent content2 = createNotificationContent("[email protected]"); NotificationContent content3 = createNotificationContent("[email protected]"); NotificationContent content4 = createNotificationContent("[email protected]"); NotificationContent content5 = createNotificationContent("[email protected]"); NotificationContent content6 = createNotificationContent("[email protected]"); String result = lockScreenNotification.createCommaSeparatedListOfSenders( Arrays.asList(content1, content2, content3, content4, content5, content6)); assertEquals( "[email protected], [email protected], [email protected], [email protected], [email protected]", result); }
### Question: NotificationIds { public static int getNewMailSummaryNotificationId(Account account) { return getBaseNotificationId(account) + OFFSET_NEW_MAIL_SUMMARY; } static int getNewMailSummaryNotificationId(Account account); static int getNewMailStackedNotificationId(Account account, int index); static int getFetchingMailNotificationId(Account account); static int getSendFailedNotificationId(Account account); static int getCertificateErrorNotificationId(Account account, boolean incoming); static int getAuthenticationErrorNotificationId(Account account, boolean incoming); }### Answer: @Test public void getNewMailSummaryNotificationId_withDefaultAccount() throws Exception { Account account = createMockAccountWithAccountNumber(0); int notificationId = NotificationIds.getNewMailSummaryNotificationId(account); assertEquals(6, notificationId); } @Test public void getNewMailSummaryNotificationId_withSecondAccount() throws Exception { Account account = createMockAccountWithAccountNumber(1); int notificationId = NotificationIds.getNewMailSummaryNotificationId(account); assertEquals(21, notificationId); }
### Question: NotificationIds { public static int getNewMailStackedNotificationId(Account account, int index) { if (index < 0 || index >= NUMBER_OF_STACKED_NOTIFICATIONS) { throw new IndexOutOfBoundsException("Invalid value: " + index); } return getBaseNotificationId(account) + OFFSET_NEW_MAIL_STACKED + index; } static int getNewMailSummaryNotificationId(Account account); static int getNewMailStackedNotificationId(Account account, int index); static int getFetchingMailNotificationId(Account account); static int getSendFailedNotificationId(Account account); static int getCertificateErrorNotificationId(Account account, boolean incoming); static int getAuthenticationErrorNotificationId(Account account, boolean incoming); }### Answer: @Test public void getNewMailStackedNotificationId_withDefaultAccount() throws Exception { Account account = createMockAccountWithAccountNumber(0); int notificationIndex = 0; int notificationId = NotificationIds.getNewMailStackedNotificationId(account, notificationIndex); assertEquals(7, notificationId); } @Test(expected = IndexOutOfBoundsException.class) public void getNewMailStackedNotificationId_withTooLowIndex() throws Exception { Account account = createMockAccountWithAccountNumber(0); NotificationIds.getNewMailStackedNotificationId(account, -1); } @Test(expected = IndexOutOfBoundsException.class) public void getNewMailStackedNotificationId_withTooLargeIndex() throws Exception { Account account = createMockAccountWithAccountNumber(0); NotificationIds.getNewMailStackedNotificationId(account, 8); } @Test public void getNewMailStackedNotificationId_withSecondAccount() throws Exception { Account account = createMockAccountWithAccountNumber(1); int notificationIndex = 7; int notificationId = NotificationIds.getNewMailStackedNotificationId(account, notificationIndex); assertEquals(29, notificationId); }
### Question: NotificationIds { public static int getFetchingMailNotificationId(Account account) { return getBaseNotificationId(account) + OFFSET_FETCHING_MAIL; } static int getNewMailSummaryNotificationId(Account account); static int getNewMailStackedNotificationId(Account account, int index); static int getFetchingMailNotificationId(Account account); static int getSendFailedNotificationId(Account account); static int getCertificateErrorNotificationId(Account account, boolean incoming); static int getAuthenticationErrorNotificationId(Account account, boolean incoming); }### Answer: @Test public void getFetchingMailNotificationId_withDefaultAccount() throws Exception { Account account = createMockAccountWithAccountNumber(0); int notificationId = NotificationIds.getFetchingMailNotificationId(account); assertEquals(5, notificationId); } @Test public void getFetchingMailNotificationId_withSecondAccount() throws Exception { Account account = createMockAccountWithAccountNumber(1); int notificationId = NotificationIds.getFetchingMailNotificationId(account); assertEquals(20, notificationId); }
### Question: NotificationIds { public static int getSendFailedNotificationId(Account account) { return getBaseNotificationId(account) + OFFSET_SEND_FAILED_NOTIFICATION; } static int getNewMailSummaryNotificationId(Account account); static int getNewMailStackedNotificationId(Account account, int index); static int getFetchingMailNotificationId(Account account); static int getSendFailedNotificationId(Account account); static int getCertificateErrorNotificationId(Account account, boolean incoming); static int getAuthenticationErrorNotificationId(Account account, boolean incoming); }### Answer: @Test public void getSendFailedNotificationId_withDefaultAccount() throws Exception { Account account = createMockAccountWithAccountNumber(0); int notificationId = NotificationIds.getSendFailedNotificationId(account); assertEquals(0, notificationId); } @Test public void getSendFailedNotificationId_withSecondAccount() throws Exception { Account account = createMockAccountWithAccountNumber(1); int notificationId = NotificationIds.getSendFailedNotificationId(account); assertEquals(15, notificationId); }
### Question: NotificationIds { public static int getCertificateErrorNotificationId(Account account, boolean incoming) { int offset = incoming ? OFFSET_CERTIFICATE_ERROR_INCOMING : OFFSET_CERTIFICATE_ERROR_OUTGOING; return getBaseNotificationId(account) + offset; } static int getNewMailSummaryNotificationId(Account account); static int getNewMailStackedNotificationId(Account account, int index); static int getFetchingMailNotificationId(Account account); static int getSendFailedNotificationId(Account account); static int getCertificateErrorNotificationId(Account account, boolean incoming); static int getAuthenticationErrorNotificationId(Account account, boolean incoming); }### Answer: @Test public void getCertificateErrorNotificationId_forIncomingServerWithDefaultAccount() throws Exception { Account account = createMockAccountWithAccountNumber(0); int notificationId = NotificationIds.getCertificateErrorNotificationId(account, INCOMING); assertEquals(1, notificationId); } @Test public void getCertificateErrorNotificationId_forIncomingServerWithSecondAccount() throws Exception { Account account = createMockAccountWithAccountNumber(1); int notificationId = NotificationIds.getCertificateErrorNotificationId(account, INCOMING); assertEquals(16, notificationId); } @Test public void getCertificateErrorNotificationId_forOutgoingServerWithDefaultAccount() throws Exception { Account account = createMockAccountWithAccountNumber(0); int notificationId = NotificationIds.getCertificateErrorNotificationId(account, OUTGOING); assertEquals(2, notificationId); } @Test public void getCertificateErrorNotificationId_forOutgoingServerWithSecondAccount() throws Exception { Account account = createMockAccountWithAccountNumber(1); int notificationId = NotificationIds.getCertificateErrorNotificationId(account, OUTGOING); assertEquals(17, notificationId); }
### Question: NotificationIds { public static int getAuthenticationErrorNotificationId(Account account, boolean incoming) { int offset = incoming ? OFFSET_AUTHENTICATION_ERROR_INCOMING : OFFSET_AUTHENTICATION_ERROR_OUTGOING; return getBaseNotificationId(account) + offset; } static int getNewMailSummaryNotificationId(Account account); static int getNewMailStackedNotificationId(Account account, int index); static int getFetchingMailNotificationId(Account account); static int getSendFailedNotificationId(Account account); static int getCertificateErrorNotificationId(Account account, boolean incoming); static int getAuthenticationErrorNotificationId(Account account, boolean incoming); }### Answer: @Test public void getAuthenticationErrorNotificationId_forIncomingServerWithDefaultAccount() throws Exception { Account account = createMockAccountWithAccountNumber(0); int notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, INCOMING); assertEquals(3, notificationId); } @Test public void getAuthenticationErrorNotificationId_forIncomingServerWithSecondAccount() throws Exception { Account account = createMockAccountWithAccountNumber(1); int notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, INCOMING); assertEquals(18, notificationId); } @Test public void getAuthenticationErrorNotificationId_forOutgoingServerWithDefaultAccount() throws Exception { Account account = createMockAccountWithAccountNumber(0); int notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, OUTGOING); assertEquals(4, notificationId); } @Test public void getAuthenticationErrorNotificationId_forOutgoingServerWithSecondAccount() throws Exception { Account account = createMockAccountWithAccountNumber(1); int notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, OUTGOING); assertEquals(19, notificationId); }
### Question: SyncNotifications { public void clearSendingNotification(Account account) { int notificationId = NotificationIds.getFetchingMailNotificationId(account); getNotificationManager().cancel(notificationId); } SyncNotifications(NotificationController controller, NotificationActionCreator actionBuilder); void showSendingNotification(Account account); void clearSendingNotification(Account account); void showFetchingMailNotification(Account account, Folder folder); void clearFetchingMailNotification(Account account); }### Answer: @Test public void testClearSendingNotification() throws Exception { int notificationId = NotificationIds.getFetchingMailNotificationId(account); syncNotifications.clearSendingNotification(account); verify(notificationManager).cancel(notificationId); }
### Question: SyncNotifications { public void clearFetchingMailNotification(Account account) { int notificationId = NotificationIds.getFetchingMailNotificationId(account); getNotificationManager().cancel(notificationId); } SyncNotifications(NotificationController controller, NotificationActionCreator actionBuilder); void showSendingNotification(Account account); void clearSendingNotification(Account account); void showFetchingMailNotification(Account account, Folder folder); void clearFetchingMailNotification(Account account); }### Answer: @Test public void testClearSendFailedNotification() throws Exception { int notificationId = NotificationIds.getFetchingMailNotificationId(account); syncNotifications.clearFetchingMailNotification(account); verify(notificationManager).cancel(notificationId); }
### Question: SendFailedNotifications { public void showSendFailedNotification(Account account, Exception exception) { Context context = controller.getContext(); String title = context.getString(R.string.send_failure_subject); String text = ExceptionHelper.getRootCauseMessage(exception); int notificationId = NotificationIds.getSendFailedNotificationId(account); PendingIntent folderListPendingIntent = actionBuilder.createViewFolderListPendingIntent( account, notificationId); NotificationCompat.Builder builder = controller.createNotificationBuilder() .setSmallIcon(getSendFailedNotificationIcon()) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setTicker(title) .setContentTitle(title) .setContentText(text) .setContentIntent(folderListPendingIntent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_ERROR); controller.configureNotification(builder, null, null, NOTIFICATION_LED_FAILURE_COLOR, NOTIFICATION_LED_BLINK_FAST, true); getNotificationManager().notify(notificationId, builder.build()); } SendFailedNotifications(NotificationController controller, NotificationActionCreator actionBuilder); void showSendFailedNotification(Account account, Exception exception); void clearSendFailedNotification(Account account); }### Answer: @Test public void testShowSendFailedNotification() throws Exception { Exception exception = new Exception(); sendFailedNotifications.showSendFailedNotification(account, exception); verify(notificationManager).notify(eq(notificationId), any(Notification.class)); verify(builder).setSmallIcon(R.drawable.notification_icon_new_mail); verify(builder).setTicker("Failed to send some messages"); verify(builder).setContentTitle("Failed to send some messages"); verify(builder).setContentText("Exception"); verify(builder).setContentIntent(contentIntent); verify(builder).setVisibility(NotificationCompat.VISIBILITY_PUBLIC); }
### Question: SendFailedNotifications { public void clearSendFailedNotification(Account account) { int notificationId = NotificationIds.getSendFailedNotificationId(account); getNotificationManager().cancel(notificationId); } SendFailedNotifications(NotificationController controller, NotificationActionCreator actionBuilder); void showSendFailedNotification(Account account, Exception exception); void clearSendFailedNotification(Account account); }### Answer: @Test public void testClearSendFailedNotification() throws Exception { sendFailedNotifications.clearSendFailedNotification(account); verify(notificationManager).cancel(notificationId); }
### Question: NotificationData { public RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference) { NotificationHolder holder = getNotificationHolderForMessage(messageReference); if (holder == null) { return RemoveNotificationResult.unknownNotification(); } activeNotifications.remove(holder); int notificationId = holder.notificationId; markNotificationIdAsFree(notificationId); if (!additionalNotifications.isEmpty()) { NotificationContent newContent = additionalNotifications.removeFirst(); NotificationHolder replacement = createNotificationHolder(notificationId, newContent); activeNotifications.addLast(replacement); return RemoveNotificationResult.createNotification(replacement); } return RemoveNotificationResult.cancelNotification(notificationId); } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }### Answer: @Test public void testRemoveNotificationForMessage() throws Exception { NotificationContent content = createNotificationContent("1"); notificationData.addNotificationContent(content); RemoveNotificationResult result = notificationData.removeNotificationForMessage(content.messageReference); assertFalse(result.isUnknownNotification()); assertEquals(NotificationIds.getNewMailStackedNotificationId(account, 0), result.getNotificationId()); assertFalse(result.shouldCreateNotification()); }
### Question: NotificationData { public boolean containsStarredMessages() { for (NotificationHolder holder : activeNotifications) { if (holder.content.starred) { return true; } } for (NotificationContent content : additionalNotifications) { if (content.starred) { return true; } } return false; } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }### Answer: @Test public void testContainsStarredMessages() throws Exception { assertFalse(notificationData.containsStarredMessages()); notificationData.addNotificationContent(createNotificationContentForStarredMessage()); assertTrue(notificationData.containsStarredMessages()); }
### Question: NotificationData { public boolean isSingleMessageNotification() { return activeNotifications.size() == 1; } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }### Answer: @Test public void testIsSingleMessageNotification() throws Exception { assertFalse(notificationData.isSingleMessageNotification()); notificationData.addNotificationContent(createNotificationContent("1")); assertTrue(notificationData.isSingleMessageNotification()); notificationData.addNotificationContent(createNotificationContent("2")); assertFalse(notificationData.isSingleMessageNotification()); }
### Question: NotificationData { public List<NotificationContent> getContentForSummaryNotification() { int size = calculateNumberOfMessagesForSummaryNotification(); List<NotificationContent> result = new ArrayList<NotificationContent>(size); Iterator<NotificationHolder> iterator = activeNotifications.iterator(); int notificationCount = 0; while (iterator.hasNext() && notificationCount < MAX_NUMBER_OF_MESSAGES_FOR_SUMMARY_NOTIFICATION) { NotificationHolder holder = iterator.next(); result.add(holder.content); notificationCount++; } return result; } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }### Answer: @Test public void testGetContentForSummaryNotification() throws Exception { notificationData.addNotificationContent(createNotificationContent("1")); NotificationContent content4 = createNotificationContent("2"); notificationData.addNotificationContent(content4); NotificationContent content3 = createNotificationContent("3"); notificationData.addNotificationContent(content3); NotificationContent content2 = createNotificationContent("4"); notificationData.addNotificationContent(content2); NotificationContent content1 = createNotificationContent("5"); notificationData.addNotificationContent(content1); NotificationContent content0 = createNotificationContent("6"); notificationData.addNotificationContent(content0); List<NotificationContent> contents = notificationData.getContentForSummaryNotification(); assertEquals(5, contents.size()); assertEquals(content0, contents.get(0)); assertEquals(content1, contents.get(1)); assertEquals(content2, contents.get(2)); assertEquals(content3, contents.get(3)); assertEquals(content4, contents.get(4)); }
### Question: NotificationData { public int[] getActiveNotificationIds() { int size = activeNotifications.size(); int[] notificationIds = new int[size]; for (int i = 0; i < size; i++) { NotificationHolder holder = activeNotifications.get(i); notificationIds[i] = holder.notificationId; } return notificationIds; } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }### Answer: @Test public void testGetActiveNotificationIds() throws Exception { notificationData.addNotificationContent(createNotificationContent("1")); notificationData.addNotificationContent(createNotificationContent("2")); int[] notificationIds = notificationData.getActiveNotificationIds(); assertEquals(2, notificationIds.length); assertEquals(NotificationIds.getNewMailStackedNotificationId(account, 1), notificationIds[0]); assertEquals(NotificationIds.getNewMailStackedNotificationId(account, 0), notificationIds[1]); }
### Question: NotificationData { public Account getAccount() { return account; } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }### Answer: @Test public void testGetAccount() throws Exception { assertEquals(account, notificationData.getAccount()); }
### Question: NewMailNotifications { public void clearNewMailNotifications(Account account) { NotificationData notificationData; synchronized (lock) { notificationData = removeNotificationData(account); } if (notificationData == null) { return; } for (int notificationId : notificationData.getActiveNotificationIds()) { cancelNotification(notificationId); } int notificationId = NotificationIds.getNewMailSummaryNotificationId(account); cancelNotification(notificationId); } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); static NewMailNotifications newInstance(NotificationController controller, NotificationActionCreator actionCreator); void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount); void removeNewMailNotification(Account account, MessageReference messageReference); void clearNewMailNotifications(Account account); }### Answer: @Test public void testClearNewMailNotificationsWithoutNotificationData() throws Exception { newMailNotifications.clearNewMailNotifications(account); verify(notificationManager, never()).cancel(anyInt()); } @Test public void testClearNewMailNotifications() throws Exception { int notificationIndex = 0; int notificationId = NotificationIds.getNewMailStackedNotificationId(account, notificationIndex); LocalMessage message = createLocalMessage(); NotificationContent content = createNotificationContent(); NotificationHolder holder = createNotificationHolder(content, notificationIndex); addToNotificationContentCreator(message, content); setActiveNotificationIds(notificationId); whenAddingContentReturn(content, AddNotificationResult.newNotification(holder)); newMailNotifications.addNewMailNotification(account, message, 3); newMailNotifications.clearNewMailNotifications(account); verify(notificationManager).cancel(notificationId); verify(notificationManager).cancel(NotificationIds.getNewMailSummaryNotificationId(account)); }
### Question: CertificateErrorNotifications { public void showCertificateErrorNotification(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); Context context = controller.getContext(); PendingIntent editServerSettingsPendingIntent = createContentIntent(context, account, incoming); String title = context.getString(R.string.notification_certificate_error_title, account.getDescription()); String text = context.getString(R.string.notification_certificate_error_text); NotificationCompat.Builder builder = controller.createNotificationBuilder() .setSmallIcon(getCertificateErrorNotificationIcon()) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setTicker(title) .setContentTitle(title) .setContentText(text) .setContentIntent(editServerSettingsPendingIntent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_ERROR); controller.configureNotification(builder, null, null, NOTIFICATION_LED_FAILURE_COLOR, NOTIFICATION_LED_BLINK_FAST, true); getNotificationManager().notify(notificationId, builder.build()); } CertificateErrorNotifications(NotificationController controller); void showCertificateErrorNotification(Account account, boolean incoming); void clearCertificateErrorNotifications(Account account, boolean incoming); }### Answer: @Test public void testShowCertificateErrorNotificationForIncomingServer() throws Exception { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, INCOMING); certificateErrorNotifications.showCertificateErrorNotification(account, INCOMING); verify(notificationManager).notify(eq(notificationId), any(Notification.class)); assertCertificateErrorNotificationContents(); } @Test public void testShowCertificateErrorNotificationForOutgoingServer() throws Exception { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, OUTGOING); certificateErrorNotifications.showCertificateErrorNotification(account, OUTGOING); verify(notificationManager).notify(eq(notificationId), any(Notification.class)); assertCertificateErrorNotificationContents(); }
### Question: CertificateErrorNotifications { public void clearCertificateErrorNotifications(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); getNotificationManager().cancel(notificationId); } CertificateErrorNotifications(NotificationController controller); void showCertificateErrorNotification(Account account, boolean incoming); void clearCertificateErrorNotifications(Account account, boolean incoming); }### Answer: @Test public void testClearCertificateErrorNotificationsForIncomingServer() throws Exception { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, INCOMING); certificateErrorNotifications.clearCertificateErrorNotifications(account, INCOMING); verify(notificationManager).cancel(notificationId); } @Test public void testClearCertificateErrorNotificationsForOutgoingServer() throws Exception { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, OUTGOING); certificateErrorNotifications.clearCertificateErrorNotifications(account, OUTGOING); verify(notificationManager).cancel(notificationId); }
### Question: ServerNameSuggester { public String suggestServerName(Type serverType, String domainPart) { switch (serverType) { case IMAP: { return "imap." + domainPart; } case SMTP: { return "smtp." + domainPart; } case EWS: return "outlook.office365.com"; case WebDAV: { return "exchange." + domainPart; } case POP3: { return "pop3." + domainPart; } } throw new AssertionError("Missed case: " + serverType); } String suggestServerName(Type serverType, String domainPart); }### Answer: @Test public void suggestServerName_forImapServer() throws Exception { Type serverType = Type.IMAP; String domainPart = "example.org"; String result = serverNameSuggester.suggestServerName(serverType, domainPart); assertEquals("imap.example.org", result); } @Test public void suggestServerName_forPop3Server() throws Exception { Type serverType = Type.POP3; String domainPart = "example.org"; String result = serverNameSuggester.suggestServerName(serverType, domainPart); assertEquals("pop3.example.org", result); } @Test public void suggestServerName_forWebDavServer() throws Exception { Type serverType = Type.WebDAV; String domainPart = "example.org"; String result = serverNameSuggester.suggestServerName(serverType, domainPart); assertEquals("exchange.example.org", result); } @Test public void suggestServerName_forSmtpServer() throws Exception { Type serverType = Type.SMTP; String domainPart = "example.org"; String result = serverNameSuggester.suggestServerName(serverType, domainPart); assertEquals("smtp.example.org", result); }
### Question: TransportUris { public static String createTransportUri(ServerSettings server) { if (Type.SMTP == server.type) { return createSmtpUri(server); } else if (Type.WebDAV == server.type) { return createWebDavUri(server); } else if (Type.EWS == server.type) { return createEwsUri(server); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }### Answer: @Test public void createTransportUri_canEncodeSmtpSslUri() { ServerSettings serverSettings = new ServerSettings( ServerSettings.Type.SMTP, "server", 123456, ConnectionSecurity.SSL_TLS_REQUIRED, AuthType.EXTERNAL, "user", "password", "clientCert"); String result = TransportUris.createTransportUri(serverSettings); assertEquals("smtp+ssl+: } @Test public void createTransportUri_canEncodeSmtpTlsUri() { ServerSettings serverSettings = new ServerSettings( ServerSettings.Type.SMTP, "server", 123456, ConnectionSecurity.STARTTLS_REQUIRED, AuthType.PLAIN, "user", "password", "clientCert"); String result = TransportUris.createTransportUri(serverSettings); assertEquals("smtp+tls+: } @Test public void createTransportUri_canEncodeSmtpUri() { ServerSettings serverSettings = new ServerSettings( ServerSettings.Type.SMTP, "server", 123456, ConnectionSecurity.NONE, AuthType.CRAM_MD5, "user", "password", "clientCert"); String result = TransportUris.createTransportUri(serverSettings); assertEquals("smtp: }
### Question: MessageCryptoStructureDetector { @VisibleForTesting static boolean isPartPgpInlineEncryptedOrSigned(Part part) { if (!part.isMimeType(TEXT_PLAIN) && !part.isMimeType(APPLICATION_PGP)) { return false; } String text = MessageExtractor.getTextFromPart(part, TEXT_LENGTH_FOR_INLINE_CHECK); if (TextUtils.isEmpty(text)) { return false; } text = text.trim(); return text.startsWith(PGP_INLINE_START_MARKER) || text.startsWith(PGP_INLINE_SIGNED_START_MARKER); } static Part findPrimaryEncryptedOrSignedPart(Part part, List<Part> outputExtraParts); static List<Part> findMultipartEncryptedParts(Part startPart); static List<Part> findMultipartSignedParts(Part startPart, MessageCryptoAnnotations messageCryptoAnnotations); static List<Part> findPgpInlineParts(Part startPart); static byte[] getSignatureData(Part part); static boolean isPartMultipartEncrypted(Part part); static boolean isMultipartEncryptedOpenPgpProtocol(Part part); static boolean isMultipartSignedOpenPgpProtocol(Part part); static boolean isMultipartEncryptedSMimeProtocol(Part part); static boolean isMultipartSignedSMimeProtocol(Part part); static boolean isPartPgpInlineEncrypted(@Nullable Part part); }### Answer: @Test public void isPartPgpInlineEncryptedOrSigned__withSignedData__shouldReturnTrue() throws Exception { String pgpInlineData = "-----BEGIN PGP SIGNED MESSAGE-----\n" + "Header: Value\n" + "\n" + "-----BEGIN PGP SIGNATURE-----\n" + "Header: Value\n" + "\n" + "base64base64base64base64\n" + "-----END PGP SIGNED MESSAGE-----\n"; MimeMessage message = new MimeMessage(); message.setBody(new TextBody(pgpInlineData)); assertTrue(MessageCryptoStructureDetector.isPartPgpInlineEncryptedOrSigned(message)); }
### Question: OpenPgpApiHelper { public static String buildUserId(Identity identity) { StringBuilder sb = new StringBuilder(); String name = identity.getName(); if (!TextUtils.isEmpty(name)) { sb.append(name).append(" "); } sb.append("<").append(identity.getEmail()).append(">"); return sb.toString(); } static String buildUserId(Identity identity); }### Answer: @Test public void buildUserId_withName_shouldCreateOpenPgpAccountName() { Identity identity = new Identity(); identity.setEmail("[email protected]"); identity.setName("Name"); String result = OpenPgpApiHelper.buildUserId(identity); assertEquals("Name <[email protected]>", result); } @Test public void buildUserId_withoutName_shouldCreateOpenPgpAccountName() { Identity identity = new Identity(); identity.setEmail("[email protected]"); String result = OpenPgpApiHelper.buildUserId(identity); assertEquals("<[email protected]>", result); }
### Question: MessageIdGenerator { public String generateMessageId(Message message) { String hostname = null; Address[] from = message.getFrom(); if (from != null && from.length >= 1) { hostname = from[0].getHostname(); } if (hostname == null) { Address[] replyTo = message.getReplyTo(); if (replyTo != null && replyTo.length >= 1) { hostname = replyTo[0].getHostname(); } } if (hostname == null) { hostname = "email.android.com"; } String uuid = generateUuid(); return "<" + uuid + "@" + hostname + ">"; } @VisibleForTesting MessageIdGenerator(); static MessageIdGenerator getInstance(); String generateMessageId(Message message); }### Answer: @Test public void generateMessageId_withFromAndReplyToAddress() throws Exception { Message message = new MimeMessage(); message.setFrom(new Address("[email protected]")); message.setReplyTo(Address.parse("[email protected]")); String result = messageIdGenerator.generateMessageId(message); assertEquals("<[email protected]>", result); } @Test public void generateMessageId_withReplyToAddress() throws Exception { Message message = new MimeMessage(); message.setReplyTo(Address.parse("[email protected]")); String result = messageIdGenerator.generateMessageId(message); assertEquals("<[email protected]>", result); } @Test public void generateMessageId_withoutRelevantHeaders() throws Exception { Message message = new MimeMessage(); String result = messageIdGenerator.generateMessageId(message); assertEquals("<[email protected]>", result); }
### Question: TextSignatureRemover { public static String stripSignature(String content) { if (DASH_SIGNATURE_PLAIN.matcher(content).find()) { content = DASH_SIGNATURE_PLAIN.matcher(content).replaceFirst("\r\n"); } return content; } static String stripSignature(String content); }### Answer: @Test public void shouldStripSignature() throws Exception { String text = "This is the body text\r\n" + "\r\n" + "-- \r\n" + "Sent from my Android device with K-9 Mail. Please excuse my brevity."; String withoutSignature = TextSignatureRemover.stripSignature(text); assertEquals("This is the body text\r\n\r\n", withoutSignature); }
### Question: FlowedMessageUtils { static boolean isFormatFlowed(String contentType) { String mimeType = getHeaderParameter(contentType, null); if (isSameMimeType(TEXT_PLAIN, mimeType)) { String formatParameter = getHeaderParameter(contentType, HEADER_PARAM_FORMAT); return HEADER_FORMAT_FLOWED.equalsIgnoreCase(formatParameter); } return false; } }### Answer: @Test public void isFormatFlowed_withTextPlainFormatFlowed_shouldReturnTrue() throws Exception { assertTrue(isFormatFlowed("text/plain; format=flowed")); } @Test public void isFormatFlowed_withTextPlain_shouldReturnFalse() throws Exception { assertFalse(isFormatFlowed("text/plain")); } @Test public void isFormatFlowed_withTextHtmlFormatFlowed_shouldReturnFalse() throws Exception { assertFalse(isFormatFlowed("text/html; format=flowed")); }
### Question: FlowedMessageUtils { static boolean isDelSp(String contentType) { if (isFormatFlowed(contentType)) { String delSpParameter = getHeaderParameter(contentType, HEADER_PARAM_DELSP); return HEADER_DELSP_YES.equalsIgnoreCase(delSpParameter); } return false; } }### Answer: @Test public void isDelSp_withFormatFlowed_shouldReturnTrue() throws Exception { assertTrue(isDelSp("text/plain; format=flowed; delsp=yes")); } @Test public void isDelSp_withTextPlainFormatFlowed_shoulReturnFalse() throws Exception { assertFalse(isDelSp("text/plain; format=flowed")); } @Test public void isDelSp_withoutFormatFlowed_shouldReturnFalse() throws Exception { assertFalse(isDelSp("text/plain; delsp=yes")); } @Test public void idDelSp_withTextHtmlFormatFlowed_shouldReturnFalse() throws Exception { assertFalse(isDelSp("text/html; format=flowed; delsp=yes")); }
### Question: MimeUtility { public static boolean isMultipart(String mimeType) { return mimeType != null && mimeType.toLowerCase(Locale.US).startsWith("multipart/"); } static String unfold(String s); static String unfoldAndDecode(String s); static String unfoldAndDecode(String s, Message message); static String foldAndEncode(String s); static String getHeaderParameter(String headerValue, String parameterName); static Map<String,String> getAllHeaderParameters(String headerValue); static Part findFirstPartByMimeType(Part part, String mimeType); static boolean mimeTypeMatches(String mimeType, String matchAgainst); static boolean isDefaultMimeType(String mimeType); static InputStream decodeBody(Body body); static void closeInputStreamWithoutDeletingTemporaryFiles(InputStream rawInputStream); static String getMimeTypeByExtension(String filename); static String getExtensionByMimeType(@NonNull String mimeType); static String getEncodingforType(String type); static boolean isMultipart(String mimeType); static boolean isMessage(String mimeType); static boolean isSameMimeType(String mimeType, String otherMimeType); static final String DEFAULT_ATTACHMENT_MIME_TYPE; static final String K9_SETTINGS_MIME_TYPE; }### Answer: @Test public void isMultipart_withLowerCaseMultipart_shouldReturnTrue() throws Exception { assertTrue(MimeUtility.isMultipart("multipart/mixed")); } @Test public void isMultipart_withUpperCaseMultipart_shouldReturnTrue() throws Exception { assertTrue(MimeUtility.isMultipart("MULTIPART/ALTERNATIVE")); } @Test public void isMultipart_withMixedCaseMultipart_shouldReturnTrue() throws Exception { assertTrue(MimeUtility.isMultipart("Multipart/Alternative")); } @Test public void isMultipart_withoutMultipart_shouldReturnFalse() throws Exception { assertFalse(MimeUtility.isMultipart("message/rfc822")); } @Test public void isMultipart_withNullArgument_shouldReturnFalse() throws Exception { assertFalse(MimeUtility.isMultipart(null)); }
### Question: SmtpDataStuffing extends FilterOutputStream { @Override public void write(int oneByte) throws IOException { if (oneByte == '\r') { state = STATE_CR; } else if ((state == STATE_CR) && (oneByte == '\n')) { state = STATE_CRLF; } else if ((state == STATE_CRLF) && (oneByte == '.')) { super.write('.'); state = STATE_NORMAL; } else { state = STATE_NORMAL; } super.write(oneByte); } SmtpDataStuffing(OutputStream out); @Override void write(int oneByte); }### Answer: @Test public void dotAtStartOfLine() throws IOException { smtpDataStuffing.write(bytesFor("Hello dot\r\n.")); assertEquals("Hello dot\r\n..", buffer.readUtf8()); } @Test public void dotAtStartOfStream() throws IOException { smtpDataStuffing.write(bytesFor(".Hello dots")); assertEquals("..Hello dots", buffer.readUtf8()); } @Test public void linesNotStartingWithDot() throws IOException { smtpDataStuffing.write(bytesFor("Hello\r\nworld\r\n")); assertEquals("Hello\r\nworld\r\n", buffer.readUtf8()); } @Test public void dotsThatNeedStuffingMixedWithOnesThatDoNot() throws IOException { smtpDataStuffing.write(bytesFor("\r\n.Hello . dots.\r\n..\r\n.\r\n...")); assertEquals("\r\n..Hello . dots.\r\n...\r\n..\r\n....", buffer.readUtf8()); }
### Question: FixedLengthInputStream extends InputStream { @Override public int available() throws IOException { return mLength - mCount; } FixedLengthInputStream(InputStream in, int length); @Override int available(); @Override int read(); @Override int read(byte[] b, int offset, int length); @Override int read(byte[] b); @Override long skip(long n); @Override String toString(); void skipRemaining(); }### Answer: @Test public void available_atStartOfStream() throws Exception { FixedLengthInputStream fixedLengthInputStream = new FixedLengthInputStream(inputStream("Hello World"), 5); int available = fixedLengthInputStream.available(); assertEquals(5, available); } @Test public void available_afterPartialReadArray() throws Exception { FixedLengthInputStream fixedLengthInputStream = new FixedLengthInputStream(inputStream("Hello World"), 5); consumeBytes(fixedLengthInputStream, 2); int available = fixedLengthInputStream.available(); assertEquals(3, available); } @Test public void available_afterStreamHasBeenExhausted() throws Exception { FixedLengthInputStream fixedLengthInputStream = new FixedLengthInputStream(inputStream("Hello World"), 5); exhaustStream(fixedLengthInputStream); int available = fixedLengthInputStream.available(); assertEquals(0, available); } @Test public void available_afterSkip() throws Exception { FixedLengthInputStream fixedLengthInputStream = new FixedLengthInputStream(inputStream("Hello World"), 5); guaranteedSkip(fixedLengthInputStream, 2); int available = fixedLengthInputStream.available(); assertEquals(3, available); }
### Question: FixedLengthInputStream extends InputStream { public void skipRemaining() throws IOException { while (available() > 0) { skip(available()); } } FixedLengthInputStream(InputStream in, int length); @Override int available(); @Override int read(); @Override int read(byte[] b, int offset, int length); @Override int read(byte[] b); @Override long skip(long n); @Override String toString(); void skipRemaining(); }### Answer: @Test public void skipRemaining_shouldExhaustStream() throws IOException { FixedLengthInputStream fixedLengthInputStream = new FixedLengthInputStream(inputStream("Hello World"), 5); fixedLengthInputStream.skipRemaining(); assertInputStreamExhausted(fixedLengthInputStream); } @Test public void skipRemaining_shouldNotConsumeMoreThanLimitFromUnderlyingInputStream() throws IOException { InputStream inputStream = inputStream("Hello World"); FixedLengthInputStream fixedLengthInputStream = new FixedLengthInputStream(inputStream, 6); fixedLengthInputStream.skipRemaining(); assertRemainingInputStreamEquals("World", inputStream); }
### Question: SignSafeOutputStream extends FilterOutputStream { public SignSafeOutputStream(OutputStream out) { super(out); outBuffer = new byte[DEFAULT_BUFFER_SIZE]; } SignSafeOutputStream(OutputStream out); void encode(byte next); @Override void write(int b); @Override void write(byte[] b, int off, int len); @Override void flush(); @Override void close(); }### Answer: @Test public void testSignSafeOutputStream() throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); OutputStream output = new SignSafeOutputStream(byteArrayOutputStream); output.write(INPUT_STRING.getBytes("US-ASCII")); output.close(); assertEquals(EXPECTED_SIGNSAFE, new String(byteArrayOutputStream.toByteArray(), "US-ASCII")); }
### Question: Address implements Serializable { @VisibleForTesting static String quoteString(String s) { if (s == null) { return null; } if (!s.matches("^\".*\"$")) { return "\"" + s + "\""; } else { return s; } } Address(Address address); Address(String address, String personal); Address(String address); private Address(String address, String personal, boolean parse); String getAddress(); String getHostname(); void setAddress(String address); String getPersonal(); void setPersonal(String newPersonal); static Address[] parseUnencoded(String addressList); static Address[] parse(String addressList); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static String toString(Address[] addresses); String toEncodedString(); static String toEncodedString(Address[] addresses); static Address[] unpack(String addressList); static String pack(Address[] addresses); static String quoteAtoms(final String text); }### Answer: @Test public void stringQuotationShouldCorrectlyQuote() { assertEquals("\"sample\"", Address.quoteString("sample")); assertEquals("\"\"sample\"\"", Address.quoteString("\"\"sample\"\"")); assertEquals("\"sample\"", Address.quoteString("\"sample\"")); assertEquals("\"sa\"mp\"le\"", Address.quoteString("sa\"mp\"le")); assertEquals("\"sa\"mp\"le\"", Address.quoteString("\"sa\"mp\"le\"")); assertEquals("\"\"\"", Address.quoteString("\"")); }
### Question: Pop3Store extends RemoteStore { @Override @NonNull public List <Pop3Folder> getFolders(boolean forceListAll) throws MessagingException { List<Pop3Folder> folders = new LinkedList<>(); folders.add(getFolder(mStoreConfig.getInboxFolderId())); return folders; } Pop3Store(StoreConfig storeConfig, TrustedSocketFactory socketFactory); static ServerSettings decodeUri(String uri); static String createUri(ServerSettings server); @Override @NonNull Pop3Folder getFolder(String name); @Override @NonNull List <Pop3Folder> getFolders(boolean forceListAll); @NonNull @Override List<? extends Folder> getSubFolders(String parentFolderId, boolean forceListAll); @Override void checkSettings(); @Override boolean isSeenFlagSupported(); Pop3Connection createConnection(); }### Answer: @Test public void getPersonalNamespace_shouldReturnListConsistingOfInbox() throws Exception { List<Pop3Folder> folders = store.getFolders(true); assertEquals(1, folders.size()); assertEquals("Inbox", folders.get(0).getId()); }
### Question: EthereumUriParser implements UriParser { @Override public int linkifyUri(String text, int startPos, StringBuffer outputBuffer) { Matcher matcher = ETHEREUM_URI_PATTERN.matcher(text); if (!matcher.find(startPos) || matcher.start() != startPos) { return startPos; } String ethereumURI = matcher.group(); outputBuffer.append("<a href=\"") .append(ethereumURI) .append("\">") .append(ethereumURI) .append("</a>"); return matcher.end(); } @Override int linkifyUri(String text, int startPos, StringBuffer outputBuffer); }### Answer: @Test public void uriInMiddleOfInput() throws Exception { String prefix = "prefix "; String uri = "ethereum:0xfdf1210fc262c73d0436236a0e07be419babbbc4?value=42"; String text = prefix + uri; parser.linkifyUri(text, prefix.length(), outputBuffer); assertLinkOnly(uri, outputBuffer); }
### Question: Pop3Store extends RemoteStore { @Override public boolean isSeenFlagSupported() { return false; } Pop3Store(StoreConfig storeConfig, TrustedSocketFactory socketFactory); static ServerSettings decodeUri(String uri); static String createUri(ServerSettings server); @Override @NonNull Pop3Folder getFolder(String name); @Override @NonNull List <Pop3Folder> getFolders(boolean forceListAll); @NonNull @Override List<? extends Folder> getSubFolders(String parentFolderId, boolean forceListAll); @Override void checkSettings(); @Override boolean isSeenFlagSupported(); Pop3Connection createConnection(); }### Answer: @Test public void isSeenFlagSupported_shouldReturnFalse() throws Exception { boolean result = store.isSeenFlagSupported(); assertFalse(result); }
### Question: Pop3Capabilities { @Override public String toString() { return String.format("CRAM-MD5 %b, PLAIN %b, STLS %b, TOP %b, UIDL %b, EXTERNAL %b", cramMD5, authPlain, stls, top, uidl, external); } @Override String toString(); }### Answer: @Test public void toString_producesReadableOutput() { String result = new Pop3Capabilities().toString(); assertEquals( "CRAM-MD5 false, PLAIN false, STLS false, TOP false, UIDL false, EXTERNAL false", result); }
### Question: Pop3Folder extends Folder<Pop3Message> { @Override public boolean create(FolderType type) throws MessagingException { return false; } Pop3Folder(Pop3Store pop3Store, String name); @Override String getParentId(); @Override synchronized void open(int mode); @Override boolean isOpen(); @Override int getMode(); @Override void close(); @Override String getId(); @Override String getName(); @Override boolean create(FolderType type); @Override boolean exists(); @Override boolean canHaveSubFolders(); @Override int getMessageCount(); @Override int getUnreadMessageCount(); @Override int getFlaggedMessageCount(); @Override Pop3Message getMessage(String uid); @Override List<Pop3Message> getMessages(int start, int end, Date earliestDate, MessageRetrievalListener<Pop3Message> listener); @Override boolean areMoreMessagesAvailable(int indexOfOldestMessage, Date earliestDate); @Override void fetch(List<Pop3Message> messages, FetchProfile fp, MessageRetrievalListener<Pop3Message> listener); @Override Map<String, String> appendMessages(List<? extends Message> messages); @Override void delete(boolean recurse); @Override void delete(List<? extends Message> msgs, String trashFolderName); @Override String getUidFromMessageId(Message message); @Override void setFlags(final Set<Flag> flags, boolean value); @Override void setFlags(List<? extends Message> messages, final Set<Flag> flags, boolean value); @Override boolean isFlagSupported(Flag flag); @Override boolean supportsFetchingFlags(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void create_withHoldsFoldersArgument_shouldDoNothing() throws Exception { Pop3Folder folder = new Pop3Folder(mockStore, "TestFolder"); boolean result = folder.create(FolderType.HOLDS_FOLDERS); assertFalse(result); verifyZeroInteractions(mockConnection); } @Test public void create_withHoldsMessagesArgument_shouldDoNothing() throws Exception { Pop3Folder folder = new Pop3Folder(mockStore, "TestFolder"); boolean result = folder.create(FolderType.HOLDS_MESSAGES); assertFalse(result); verifyZeroInteractions(mockConnection); }
### Question: Pop3Folder extends Folder<Pop3Message> { @Override public boolean exists() throws MessagingException { return name.equalsIgnoreCase(pop3Store.getConfig().getInboxFolderId()); } Pop3Folder(Pop3Store pop3Store, String name); @Override String getParentId(); @Override synchronized void open(int mode); @Override boolean isOpen(); @Override int getMode(); @Override void close(); @Override String getId(); @Override String getName(); @Override boolean create(FolderType type); @Override boolean exists(); @Override boolean canHaveSubFolders(); @Override int getMessageCount(); @Override int getUnreadMessageCount(); @Override int getFlaggedMessageCount(); @Override Pop3Message getMessage(String uid); @Override List<Pop3Message> getMessages(int start, int end, Date earliestDate, MessageRetrievalListener<Pop3Message> listener); @Override boolean areMoreMessagesAvailable(int indexOfOldestMessage, Date earliestDate); @Override void fetch(List<Pop3Message> messages, FetchProfile fp, MessageRetrievalListener<Pop3Message> listener); @Override Map<String, String> appendMessages(List<? extends Message> messages); @Override void delete(boolean recurse); @Override void delete(List<? extends Message> msgs, String trashFolderName); @Override String getUidFromMessageId(Message message); @Override void setFlags(final Set<Flag> flags, boolean value); @Override void setFlags(List<? extends Message> messages, final Set<Flag> flags, boolean value); @Override boolean isFlagSupported(Flag flag); @Override boolean supportsFetchingFlags(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void exists_withInbox_shouldReturnTrue() throws Exception { boolean result = folder.exists(); assertTrue(result); } @Test public void exists_withNonInboxFolder_shouldReturnFalse() throws Exception { folder = new Pop3Folder(mockStore, "TestFolder"); boolean result = folder.exists(); assertFalse(result); }
### Question: Pop3Folder extends Folder<Pop3Message> { @Override public int getUnreadMessageCount() throws MessagingException { return -1; } Pop3Folder(Pop3Store pop3Store, String name); @Override String getParentId(); @Override synchronized void open(int mode); @Override boolean isOpen(); @Override int getMode(); @Override void close(); @Override String getId(); @Override String getName(); @Override boolean create(FolderType type); @Override boolean exists(); @Override boolean canHaveSubFolders(); @Override int getMessageCount(); @Override int getUnreadMessageCount(); @Override int getFlaggedMessageCount(); @Override Pop3Message getMessage(String uid); @Override List<Pop3Message> getMessages(int start, int end, Date earliestDate, MessageRetrievalListener<Pop3Message> listener); @Override boolean areMoreMessagesAvailable(int indexOfOldestMessage, Date earliestDate); @Override void fetch(List<Pop3Message> messages, FetchProfile fp, MessageRetrievalListener<Pop3Message> listener); @Override Map<String, String> appendMessages(List<? extends Message> messages); @Override void delete(boolean recurse); @Override void delete(List<? extends Message> msgs, String trashFolderName); @Override String getUidFromMessageId(Message message); @Override void setFlags(final Set<Flag> flags, boolean value); @Override void setFlags(List<? extends Message> messages, final Set<Flag> flags, boolean value); @Override boolean isFlagSupported(Flag flag); @Override boolean supportsFetchingFlags(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void getUnreadMessageCount_shouldBeMinusOne() throws Exception { int result = folder.getUnreadMessageCount(); assertEquals(-1, result); }
### Question: Pop3Folder extends Folder<Pop3Message> { @Override public int getFlaggedMessageCount() throws MessagingException { return -1; } Pop3Folder(Pop3Store pop3Store, String name); @Override String getParentId(); @Override synchronized void open(int mode); @Override boolean isOpen(); @Override int getMode(); @Override void close(); @Override String getId(); @Override String getName(); @Override boolean create(FolderType type); @Override boolean exists(); @Override boolean canHaveSubFolders(); @Override int getMessageCount(); @Override int getUnreadMessageCount(); @Override int getFlaggedMessageCount(); @Override Pop3Message getMessage(String uid); @Override List<Pop3Message> getMessages(int start, int end, Date earliestDate, MessageRetrievalListener<Pop3Message> listener); @Override boolean areMoreMessagesAvailable(int indexOfOldestMessage, Date earliestDate); @Override void fetch(List<Pop3Message> messages, FetchProfile fp, MessageRetrievalListener<Pop3Message> listener); @Override Map<String, String> appendMessages(List<? extends Message> messages); @Override void delete(boolean recurse); @Override void delete(List<? extends Message> msgs, String trashFolderName); @Override String getUidFromMessageId(Message message); @Override void setFlags(final Set<Flag> flags, boolean value); @Override void setFlags(List<? extends Message> messages, final Set<Flag> flags, boolean value); @Override boolean isFlagSupported(Flag flag); @Override boolean supportsFetchingFlags(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void getFlaggedMessageCount_shouldBeMinusOne() throws Exception { int result = folder.getFlaggedMessageCount(); assertEquals(-1, result); }
### Question: Pop3Folder extends Folder<Pop3Message> { @Override public void close() { try { if (isOpen()) { connection.executeSimpleCommand(QUIT_COMMAND); } } catch (Exception e) { } if (connection != null) { connection.close(); connection = null; } } Pop3Folder(Pop3Store pop3Store, String name); @Override String getParentId(); @Override synchronized void open(int mode); @Override boolean isOpen(); @Override int getMode(); @Override void close(); @Override String getId(); @Override String getName(); @Override boolean create(FolderType type); @Override boolean exists(); @Override boolean canHaveSubFolders(); @Override int getMessageCount(); @Override int getUnreadMessageCount(); @Override int getFlaggedMessageCount(); @Override Pop3Message getMessage(String uid); @Override List<Pop3Message> getMessages(int start, int end, Date earliestDate, MessageRetrievalListener<Pop3Message> listener); @Override boolean areMoreMessagesAvailable(int indexOfOldestMessage, Date earliestDate); @Override void fetch(List<Pop3Message> messages, FetchProfile fp, MessageRetrievalListener<Pop3Message> listener); @Override Map<String, String> appendMessages(List<? extends Message> messages); @Override void delete(boolean recurse); @Override void delete(List<? extends Message> msgs, String trashFolderName); @Override String getUidFromMessageId(Message message); @Override void setFlags(final Set<Flag> flags, boolean value); @Override void setFlags(List<? extends Message> messages, final Set<Flag> flags, boolean value); @Override boolean isFlagSupported(Flag flag); @Override boolean supportsFetchingFlags(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void close_onNonOpenedFolder_succeeds() throws MessagingException { folder.close(); }
### Question: Pop3Connection { InputStream getInputStream() { return in; } Pop3Connection(Pop3Settings settings, TrustedSocketFactory trustedSocketFactory); }### Answer: @Test public void withTLS_connectsToSocket() throws Exception { String response = INITIAL_RESPONSE + AUTH_HANDLE_RESPONSE + CAPA_RESPONSE + AUTH_PLAIN_AUTHENTICATED_RESPONSE; when(mockSocket.getInputStream()).thenReturn(new ByteArrayInputStream(response.getBytes())); setSettingsForMockSocket(); settings.setAuthType(AuthType.PLAIN); new Pop3Connection(settings, mockTrustedSocketFactory); assertEquals(AUTH + CAPA + AUTH_PLAIN_WITH_LOGIN, new String(outputStream.toByteArray())); }
### Question: WebDavStore extends RemoteStore { public static String createUri(ServerSettings server) { return WebDavStoreUriCreator.create(server); } WebDavStore(StoreConfig storeConfig, QMailHttpClientFactory clientFactory); static WebDavStoreSettings decodeUri(String uri); static String createUri(ServerSettings server); @Override void checkSettings(); @Override @NonNull List<? extends Folder> getFolders(boolean forceListAll); @NonNull @Override List<? extends Folder> getSubFolders(String parentFolderId, boolean forceListAll); @Override @NonNull WebDavFolder getFolder(String name); @Override boolean isMoveCapable(); @Override boolean isCopyCapable(); CookieStore getAuthCookies(); String getAlias(); String getUrl(); QMailHttpClient getHttpClient(); String getAuthString(); @Override boolean isSendCapable(); @Override void sendMessages(List<? extends Message> messages); }### Answer: @Test public void createUri_withSetting_shouldProvideUri() { ServerSettings serverSettings = new ServerSettings(Type.WebDAV, "example.org", 123456, ConnectionSecurity.NONE, AuthType.PLAIN, "user", "password", null); String result = WebDavStore.createUri(serverSettings); assertEquals("webdav: } @Test public void createUri_withSettingsWithTLS_shouldProvideSSLUri() { ServerSettings serverSettings = new ServerSettings(Type.WebDAV, "example.org", 123456, ConnectionSecurity.SSL_TLS_REQUIRED, AuthType.PLAIN, "user", "password", null); String result = WebDavStore.createUri(serverSettings); assertEquals("webdav+ssl+: }
### Question: WebDavStore extends RemoteStore { @Override @NonNull public WebDavFolder getFolder(String name) { WebDavFolder folder = this.folderList.get(name); if (folder == null) { folder = new WebDavFolder(this, name); folderList.put(name, folder); } return folder; } WebDavStore(StoreConfig storeConfig, QMailHttpClientFactory clientFactory); static WebDavStoreSettings decodeUri(String uri); static String createUri(ServerSettings server); @Override void checkSettings(); @Override @NonNull List<? extends Folder> getFolders(boolean forceListAll); @NonNull @Override List<? extends Folder> getSubFolders(String parentFolderId, boolean forceListAll); @Override @NonNull WebDavFolder getFolder(String name); @Override boolean isMoveCapable(); @Override boolean isCopyCapable(); CookieStore getAuthCookies(); String getAlias(); String getUrl(); QMailHttpClient getHttpClient(); String getAuthString(); @Override boolean isSendCapable(); @Override void sendMessages(List<? extends Message> messages); }### Answer: @Test public void getFolder_shouldReturnWebDavFolderInstance() throws Exception { WebDavStore webDavStore = createDefaultWebDavStore(); Folder result = webDavStore.getFolder("INBOX"); assertEquals(WebDavFolder.class, result.getClass()); } @Test public void getFolder_calledTwice_shouldReturnFirstInstance() throws Exception { WebDavStore webDavStore = createDefaultWebDavStore(); String folderName = "Trash"; Folder webDavFolder = webDavStore.getFolder(folderName); Folder result = webDavStore.getFolder(folderName); assertSame(webDavFolder, result); }
### Question: WebDavFolder extends Folder<WebDavMessage> { @Override public boolean isOpen() { return this.mIsOpen; } WebDavFolder(WebDavStore nStore, String id); void setUrl(String url); @Override void open(int mode); @Override Map<String, String> copyMessages(List<? extends Message> messages, Folder folder); @Override Map<String, String> moveMessages(List<? extends Message> messages, Folder folder); @Override void delete(List<? extends Message> msgs, String trashFolderName); @Override int getMessageCount(); @Override int getUnreadMessageCount(); @Override int getFlaggedMessageCount(); @Override boolean isOpen(); @Override int getMode(); @Override String getId(); @Override String getParentId(); @Override String getName(); @Override boolean exists(); @Override boolean canHaveSubFolders(); @Override void close(); @Override boolean create(FolderType type); @Override void delete(boolean recursive); @Override WebDavMessage getMessage(String uid); @Override List<WebDavMessage> getMessages(int start, int end, Date earliestDate, MessageRetrievalListener<WebDavMessage> listener); @Override boolean areMoreMessagesAvailable(int indexOfOldestMessage, Date earliestDate); @Override void fetch(List<WebDavMessage> messages, FetchProfile fp, MessageRetrievalListener<WebDavMessage> listener); @Override void setFlags(List<? extends Message> messages, final Set<Flag> flags, boolean value); @Override Map<String, String> appendMessages(List<? extends Message> messages); List<? extends Message> appendWebDavMessages(List<? extends Message> messages); @Override boolean equals(Object o); @Override String getUidFromMessageId(Message message); @Override void setFlags(final Set<Flag> flags, boolean value); String getUrl(); }### Answer: @Test public void folder_does_not_start_open() throws MessagingException { assertFalse(folder.isOpen()); }
### Question: WebDavFolder extends Folder<WebDavMessage> { @Override public boolean exists() { return true; } WebDavFolder(WebDavStore nStore, String id); void setUrl(String url); @Override void open(int mode); @Override Map<String, String> copyMessages(List<? extends Message> messages, Folder folder); @Override Map<String, String> moveMessages(List<? extends Message> messages, Folder folder); @Override void delete(List<? extends Message> msgs, String trashFolderName); @Override int getMessageCount(); @Override int getUnreadMessageCount(); @Override int getFlaggedMessageCount(); @Override boolean isOpen(); @Override int getMode(); @Override String getId(); @Override String getParentId(); @Override String getName(); @Override boolean exists(); @Override boolean canHaveSubFolders(); @Override void close(); @Override boolean create(FolderType type); @Override void delete(boolean recursive); @Override WebDavMessage getMessage(String uid); @Override List<WebDavMessage> getMessages(int start, int end, Date earliestDate, MessageRetrievalListener<WebDavMessage> listener); @Override boolean areMoreMessagesAvailable(int indexOfOldestMessage, Date earliestDate); @Override void fetch(List<WebDavMessage> messages, FetchProfile fp, MessageRetrievalListener<WebDavMessage> listener); @Override void setFlags(List<? extends Message> messages, final Set<Flag> flags, boolean value); @Override Map<String, String> appendMessages(List<? extends Message> messages); List<? extends Message> appendWebDavMessages(List<? extends Message> messages); @Override boolean equals(Object o); @Override String getUidFromMessageId(Message message); @Override void setFlags(final Set<Flag> flags, boolean value); String getUrl(); }### Answer: @Test public void exists_is_always_true() throws Exception { assertTrue(folder.exists()); }
### Question: WebDavMessage extends MimeMessage { @Override public void delete(String trashFolderName) throws MessagingException { WebDavFolder wdFolder = (WebDavFolder) getFolder(); Timber.i("Deleting message by moving to %s", trashFolderName); wdFolder.moveMessages(Collections.singletonList(this), wdFolder.getStore().getFolder(trashFolderName)); } WebDavMessage(String uid, Folder folder); void setUrl(String url); String getUrl(); void setSize(int size); void setFlagInternal(Flag flag, boolean set); void setNewHeaders(ParsedMessageEnvelope envelope); @Override void delete(String trashFolderName); @Override void setFlag(Flag flag, boolean set); }### Answer: @Test public void delete_asks_folder_to_delete_message() throws MessagingException { when(mockFolder.getStore()).thenReturn(mockStore); when(mockStore.getFolder("Trash")).thenReturn(mockTrashFolder); message.delete("Trash"); verify(mockFolder).moveMessages(Collections.singletonList(message), mockTrashFolder); }
### Question: WebDavMessage extends MimeMessage { public void setNewHeaders(ParsedMessageEnvelope envelope) throws MessagingException { String[] headers = envelope.getHeaderList(); Map<String, String> messageHeaders = envelope.getMessageHeaders(); for (String header : headers) { String headerValue = messageHeaders.get(header); if (header.equals("Content-Length")) { int size = Integer.parseInt(headerValue); this.setSize(size); } if (headerValue != null && !headerValue.equals("")) { this.addHeader(header, headerValue); } } } WebDavMessage(String uid, Folder folder); void setUrl(String url); String getUrl(); void setSize(int size); void setFlagInternal(Flag flag, boolean set); void setNewHeaders(ParsedMessageEnvelope envelope); @Override void delete(String trashFolderName); @Override void setFlag(Flag flag, boolean set); }### Answer: @Test public void setNewHeaders_updates_size() throws MessagingException { ParsedMessageEnvelope parsedMessageEnvelope = new ParsedMessageEnvelope(); parsedMessageEnvelope.addHeader("getcontentlength", "1024"); message.setNewHeaders(parsedMessageEnvelope); assertEquals(1024, message.getSize()); }
### Question: WebDavMessage extends MimeMessage { @Override public void setFlag(Flag flag, boolean set) throws MessagingException { super.setFlag(flag, set); mFolder.setFlags(Collections.singletonList(this), Collections.singleton(flag), set); } WebDavMessage(String uid, Folder folder); void setUrl(String url); String getUrl(); void setSize(int size); void setFlagInternal(Flag flag, boolean set); void setNewHeaders(ParsedMessageEnvelope envelope); @Override void delete(String trashFolderName); @Override void setFlag(Flag flag, boolean set); }### Answer: @Test public void setFlag_asks_folder_to_set_flag() throws MessagingException { message.setFlag(Flag.FLAGGED, true); verify(mockFolder).setFlags(Collections.singletonList(message), Collections.singleton(Flag.FLAGGED), true); }
### Question: ResponseCodeExtractor { public static String getResponseCode(ImapResponse response) { if (response.size() < 2 || !response.isList(1)) { return null; } ImapList responseTextCode = response.getList(1); return responseTextCode.size() != 1 ? null : responseTextCode.getString(0); } private ResponseCodeExtractor(); static String getResponseCode(ImapResponse response); static final String AUTHENTICATION_FAILED; }### Answer: @Test public void getResponseCode_withResponseCode() throws Exception { ImapResponse imapResponse = createImapResponse("x NO [AUTHENTICATIONFAILED] No sir"); String result = ResponseCodeExtractor.getResponseCode(imapResponse); assertEquals("AUTHENTICATIONFAILED", result); } @Test public void getResponseCode_withoutResponseCode() throws Exception { ImapResponse imapResponse = createImapResponse("x NO Authentication failed"); String result = ResponseCodeExtractor.getResponseCode(imapResponse); assertNull(result); } @Test public void getResponseCode_withoutSingleItemResponse() throws Exception { ImapResponse imapResponse = createImapResponse("x NO"); String result = ResponseCodeExtractor.getResponseCode(imapResponse); assertNull(result); }
### Question: NamespaceResponse { public static NamespaceResponse parse(List<ImapResponse> responses) { for (ImapResponse response : responses) { NamespaceResponse prefix = parse(response); if (prefix != null) { return prefix; } } return null; } private NamespaceResponse(String prefix, String hierarchyDelimiter); static NamespaceResponse parse(List<ImapResponse> responses); String getPrefix(); String getHierarchyDelimiter(); }### Answer: @Test public void parse_withoutNamespaceResponse_shouldReturnNull() throws Exception { NamespaceResponse result = parse("* OK Some text here"); assertNull(result); } @Test public void parse_withTooShortNamespaceResponse_shouldReturnNull() throws Exception { NamespaceResponse result = parse("* NAMESPACE NIL NIL"); assertNull(result); } @Test public void parse_withPersonalNamespacesNotPresent_shouldReturnNull() throws Exception { NamespaceResponse result = parse("* NAMESPACE NIL NIL NIL"); assertNull(result); } @Test public void parse_withEmptyListForPersonalNamespaces_shouldReturnNull() throws Exception { NamespaceResponse result = parse("* NAMESPACE () NIL NIL"); assertNull(result); } @Test public void parse_withEmptyListForFirstPersonalNamespace_shouldReturnNull() throws Exception { NamespaceResponse result = parse("* NAMESPACE (()) NIL NIL"); assertNull(result); } @Test public void parse_withIncompleteFirstPersonalNamespace_shouldReturnNull() throws Exception { NamespaceResponse result = parse("* NAMESPACE ((\"\")) NIL NIL"); assertNull(result); } @Test public void parse_withEmptyResponseList() throws Exception { NamespaceResponse result = NamespaceResponse.parse(Collections.<ImapResponse>emptyList()); assertNull(result); }
### Question: ListResponse { public static List<ListResponse> parseList(List<ImapResponse> responses) { return parse(responses, Responses.LIST); } private ListResponse(List<String> attributes, String hierarchyDelimiter, String name); static List<ListResponse> parseList(List<ImapResponse> responses); static List<ListResponse> parseLsub(List<ImapResponse> responses); List<String> getAttributes(); boolean hasAttribute(String attribute); @Nullable String getHierarchyDelimiter(); String getName(); }### Answer: @Test public void parseList_withValidResponses_shouldReturnListResponses() throws Exception { List<ImapResponse> responses = asList( createImapResponse("* LIST () \"/\" blurdybloop"), createImapResponse("* LIST (\\Noselect) \"/\" foo"), createImapResponse("* LIST () \"/\" foo/bar"), createImapResponse("* LIST (\\NoInferiors) NIL INBOX"), createImapResponse("X OK LIST completed") ); List<ListResponse> result = ListResponse.parseList(responses); assertEquals(4, result.size()); assertListResponseEquals(noAttributes(), "/", "blurdybloop", result.get(0)); assertListResponseEquals(singletonList("\\Noselect"), "/", "foo", result.get(1)); assertListResponseEquals(noAttributes(), "/", "foo/bar", result.get(2)); assertListResponseEquals(singletonList("\\NoInferiors"), null, "INBOX", result.get(3)); }
### Question: ListResponse { public static List<ListResponse> parseLsub(List<ImapResponse> responses) { return parse(responses, Responses.LSUB); } private ListResponse(List<String> attributes, String hierarchyDelimiter, String name); static List<ListResponse> parseList(List<ImapResponse> responses); static List<ListResponse> parseLsub(List<ImapResponse> responses); List<String> getAttributes(); boolean hasAttribute(String attribute); @Nullable String getHierarchyDelimiter(); String getName(); }### Answer: @Test public void parseLsub_withValidResponse_shouldReturnListResponse() throws Exception { List<ImapResponse> responses = singletonList(createImapResponse("* LSUB () \".\" \"Folder\"")); List<ListResponse> result = ListResponse.parseLsub(responses); assertEquals(1, result.size()); assertListResponseEquals(noAttributes(), ".", "Folder", result.get(0)); }