src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
Pop3Folder extends Folder<Pop3Message> { @Override public synchronized void open(int mode) throws MessagingException { if (isOpen()) { return; } if (!name.equalsIgnoreCase(pop3Store.getConfig().getInboxFolderId())) { throw new MessagingException("Folder does not exist"); } connection = pop3Store.createConnection(); Str... | @Test(expected = MessagingException.class) public void open_withoutInboxFolder_shouldThrow() throws Exception { Pop3Folder folder = new Pop3Folder(mockStore, "TestFolder"); folder.open(Folder.OPEN_MODE_RW); }
@Test public void open_withoutInboxFolder_shouldNotTryAndCreateConnection() throws Exception { Pop3Folder folde... |
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(); @Ov... | @Test public void close_onNonOpenedFolder_succeeds() throws MessagingException { folder.close(); } |
Pop3Connection { InputStream getInputStream() { return in; } Pop3Connection(Pop3Settings settings,
TrustedSocketFactory trustedSocketFactory); } | @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(Aut... |
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... | @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 createU... |
WebDavStore extends RemoteStore { @Override public void checkSettings() throws MessagingException { authenticate(); } WebDavStore(StoreConfig storeConfig, QMailHttpClientFactory clientFactory); static WebDavStoreSettings decodeUri(String uri); static String createUri(ServerSettings server); @Override void checkSettings... | @Test public void checkSettings_withHttpPrefixedServerName_shouldUseInsecureConnection() throws Exception { WebDavStore webDavStore = createWebDavStore("webdav: configureHttpResponses(UNAUTHORIZED_401_RESPONSE, OK_200_RESPONSE); webDavStore.checkSettings(); assertHttpClientUsesHttps(false); }
@Test public void checkSet... |
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 cli... | @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 Except... |
WebDavStore extends RemoteStore { @Override @NonNull public List<? extends Folder> getFolders(boolean forceListAll) throws MessagingException { List<Folder> folderList = new LinkedList<>(); getHttpClient(); Map<String, String> headers = new HashMap<>(); headers.put("Depth", "0"); headers.put("Brief", "t"); DataSet data... | @Test public void getPersonalNamespaces_shouldRequestSpecialFolders() throws Exception { StoreConfig storeConfig = createStoreConfig("webdav: WebDavStore webDavStore = new WebDavStore(storeConfig, mockHttpClientFactory); configureHttpResponses(UNAUTHORIZED_401_RESPONSE, OK_200_RESPONSE, createOkPropfindResponse(), crea... |
WebDavFolder extends Folder<WebDavMessage> { @Override public void fetch(List<WebDavMessage> messages, FetchProfile fp, MessageRetrievalListener<WebDavMessage> listener) throws MessagingException { if (messages == null || messages.isEmpty()) { return; } if (fp.contains(FetchProfile.Item.ENVELOPE)) { fetchEnvelope(messa... | @Test public void folder_can_fetch_less_than_10_envelopes() throws MessagingException { when(mockStore.processRequest(anyString(), anyString(), anyString(), anyMapOf(String.class, String.class))) .thenReturn(mockDataSet); List<WebDavMessage> messages = new ArrayList<>(); for (int i = 0; i < 5; i++) { WebDavMessage mock... |
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, ... | @Test public void folder_does_not_start_open() throws MessagingException { assertFalse(folder.isOpen()); } |
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> ... | @Test public void exists_is_always_true() throws Exception { assertTrue(folder.exists()); } |
WebDavFolder extends Folder<WebDavMessage> { private int getMessageCount(boolean read) throws MessagingException { String isRead; int messageCount = 0; Map<String, String> headers = new HashMap<String, String>(); String messageBody; if (read) { isRead = "True"; } else { isRead = "False"; } messageBody = store.getMessag... | @Test public void can_fetch_message_count() throws Exception { int messageCount = 23; HashMap<String, String> headers = new HashMap<>(); headers.put("Brief", "t"); String messageCountXml = "<xml>MessageCountXml</xml>"; when(mockStore.getMessageCountXml("True")).thenReturn(messageCountXml); when(mockStore.processRequest... |
WebDavFolder extends Folder<WebDavMessage> { @Override public List<WebDavMessage> getMessages(int start, int end, Date earliestDate, MessageRetrievalListener<WebDavMessage> listener) throws MessagingException { List<WebDavMessage> messages = new ArrayList<WebDavMessage>(); String[] uids; Map<String, String> headers = n... | @Test public void getMessages_should_request_message_search() throws MessagingException { int totalMessages = 23; int messageStart = 1; int messageEnd = 11; setupFolderWithMessages(totalMessages); String messagesXml = "<xml>MessagesXml</xml>"; buildSearchResponse(mockDataSet); when(mockStore.getMessagesXml()).thenRetur... |
WebDavFolder extends Folder<WebDavMessage> { @Override public Map<String, String> moveMessages(List<? extends Message> messages, Folder folder) throws MessagingException { moveOrCopyMessages(messages, folder.getId(), true); return null; } WebDavFolder(WebDavStore nStore, String id); void setUrl(String url); @Override v... | @Test public void moveMessages_should_requestMoveXml() throws Exception { setupMoveOrCopy(); folder.moveMessages(messages, destinationFolder); verify(mockStore).getMoveOrCopyMessagesReadXml(eq(new String[]{"url1"}), eq(true)); }
@Test public void moveMessages_should_send_move_command() throws Exception { setupMoveOrCop... |
WebDavFolder extends Folder<WebDavMessage> { @Override public Map<String, String> copyMessages(List<? extends Message> messages, Folder folder) throws MessagingException { moveOrCopyMessages(messages, folder.getId(), false); return null; } WebDavFolder(WebDavStore nStore, String id); void setUrl(String url); @Override ... | @Test public void copyMessages_should_requestCopyXml() throws Exception { setupMoveOrCopy(); folder.copyMessages(messages, destinationFolder); verify(mockStore).getMoveOrCopyMessagesReadXml(eq(new String[]{"url1"}), eq(false)); }
@Test public void copyMessages_should_send_copy_command() throws Exception { setupMoveOrCo... |
WebDavFolder extends Folder<WebDavMessage> { public List<? extends Message> appendWebDavMessages(List<? extends Message> messages) throws MessagingException { List<Message> retMessages = new ArrayList<Message>(messages.size()); QMailHttpClient httpclient = store.getHttpClient(); for (Message message : messages) { HttpG... | @Test public void appendWebDavMessages_replaces_messages_with_WebDAV_versions() throws MessagingException, IOException { List<Message> existingMessages = new ArrayList<>(); Message existingMessage = mock(Message.class); existingMessages.add(existingMessage); String messageUid = "testMessageUid"; when(existingMessage.ge... |
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(tra... | @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); } |
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 (h... | @Test public void setNewHeaders_updates_size() throws MessagingException { ParsedMessageEnvelope parsedMessageEnvelope = new ParsedMessageEnvelope(); parsedMessageEnvelope.addHeader("getcontentlength", "1024"); message.setNewHeaders(parsedMessageEnvelope); assertEquals(1024, message.getSize()); } |
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 ... | @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); } |
CopyUidResponse { public static CopyUidResponse parse(ImapResponse response) { if (!response.isTagged() || response.size() < 2 || !equalsIgnoreCase(response.get(0), Responses.OK) || !response.isList(1)) { return null; } ImapList responseTextList = response.getList(1); if (responseTextList.size() < 4 || !equalsIgnoreCas... | @Test public void parse_withUntaggedResponse_shouldReturnNull() throws Exception { ImapResponse imapResponse = createImapResponse("* OK [COPYUID 1 1,3:5 7:10] Success"); CopyUidResponse result = CopyUidResponse.parse(imapResponse); assertNull(result); }
@Test public void parse_withTooShortResponse_shouldReturnNull() th... |
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 S... | @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_withoutResp... |
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 NamespaceRe... | @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"); asser... |
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> parseL... | @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 (\\NoInfe... |
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> parseL... | @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... |
ImapConnection { public void open() throws IOException, MessagingException { if (open) { return; } else if (stacktraceForClose != null) { throw new IllegalStateException("open() called after close(). " + "Check wrapped exception to see where close() was called.", stacktraceForClose); } open = true; boolean authSuccess ... | @Test public void open_withNoCapabilitiesInInitialResponse_shouldIssuePreAuthCapabilitiesCommand() throws Exception { settings.setAuthType(AuthType.PLAIN); MockImapServer server = new MockImapServer(); server.output("* OK example.org server"); server.expect("1 CAPABILITY"); server.output("* CAPABILITY IMAP4 IMAP4REV1 A... |
ImapConnection { public boolean isConnected() { return inputStream != null && outputStream != null && socket != null && socket.isConnected() && !socket.isClosed(); } ImapConnection(ImapSettings settings, TrustedSocketFactory socketFactory,
ConnectivityManager connectivityManager, OAuth2TokenProvider oauthTo... | @Test public void isConnected_withoutPreviousOpen_shouldReturnFalse() throws Exception { ImapConnection imapConnection = createImapConnection( settings, socketFactory, connectivityManager, oAuth2TokenProvider); boolean result = imapConnection.isConnected(); assertFalse(result); }
@Test public void isConnected_afterOpen... |
ImapConnection { public void close() { open = false; stacktraceForClose = new Exception(); untagQuietly(socket); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); IOUtils.closeQuietly(socket); inputStream = null; outputStream = null; socket = null; } ImapConnection(ImapSettings settings, TrustedSoc... | @Test public void close_withoutOpen_shouldNotThrow() throws Exception { ImapConnection imapConnection = createImapConnection( settings, socketFactory, connectivityManager, oAuth2TokenProvider); imapConnection.close(); }
@Test public void close_afterOpen_shouldCloseConnection() throws Exception { MockImapServer server =... |
ImapConnection { protected boolean isIdleCapable() { if (K9MailLib.isDebug()) { Timber.v("Connection %s has %d capabilities", getLogId(), capabilities.size()); } return capabilities.contains(Capabilities.IDLE); } ImapConnection(ImapSettings settings, TrustedSocketFactory socketFactory,
ConnectivityManager c... | @Test public void isIdleCapable_withoutIdleCapability() throws Exception { MockImapServer server = new MockImapServer(); ImapConnection imapConnection = simpleOpen(server); boolean result = imapConnection.isIdleCapable(); assertFalse(result); server.shutdown(); }
@Test public void isIdleCapable_withIdleCapability() thr... |
ImapConnection { public void sendContinuation(String continuation) throws IOException { outputStream.write(continuation.getBytes()); outputStream.write('\r'); outputStream.write('\n'); outputStream.flush(); if (K9MailLib.isDebug() && DEBUG_PROTOCOL_IMAP) { Timber.v("%s>>> %s", getLogId(), continuation); } } ImapConnect... | @Test public void sendContinuation() throws Exception { settings.setAuthType(AuthType.PLAIN); MockImapServer server = new MockImapServer(); simpleOpenDialog(server, "IDLE"); server.expect("4 IDLE"); server.output("+ idling"); server.expect("DONE"); ImapConnection imapConnection = startServerAndCreateImapConnection(serv... |
ImapConnection { public List<ImapResponse> executeSimpleCommand(String command) throws IOException, MessagingException { return executeSimpleCommand(command, false); } ImapConnection(ImapSettings settings, TrustedSocketFactory socketFactory,
ConnectivityManager connectivityManager, OAuth2TokenProvider oauth... | @Test public void executeSingleCommand_withOkResponse_shouldReturnResult() throws Exception { MockImapServer server = new MockImapServer(); simpleOpenDialog(server, ""); server.expect("4 CREATE Folder"); server.output("4 OK Folder created"); ImapConnection imapConnection = startServerAndCreateImapConnection(server); Li... |
FolderNameCodec { public String encode(String folderName) { ByteBuffer byteBuffer = modifiedUtf7Charset.encode(folderName); byte[] bytes = new byte[byteBuffer.limit()]; byteBuffer.get(bytes); return new String(bytes, asciiCharset); } private FolderNameCodec(); static FolderNameCodec newInstance(); String encode(String... | @Test public void encode_withAsciiArgument_shouldReturnInput() throws Exception { String folderName = "ASCII"; String result = folderNameCode.encode(folderName); assertEquals(folderName, result); }
@Test public void encode_withNonAsciiArgument_shouldReturnEncodedString() throws Exception { String folderName = "über"; S... |
FolderNameCodec { public String decode(String encodedFolderName) throws CharacterCodingException { CharsetDecoder decoder = modifiedUtf7Charset.newDecoder().onMalformedInput(CodingErrorAction.REPORT); ByteBuffer byteBuffer = ByteBuffer.wrap(encodedFolderName.getBytes(asciiCharset)); CharBuffer charBuffer = decoder.deco... | @Test public void decode_withEncodedArgument_shouldReturnDecodedString() throws Exception { String encodedFolderName = "&ANw-bergr&APYA3w-entr&AOQ-ger"; String result = folderNameCode.decode(encodedFolderName); assertEquals("Übergrößenträger", result); }
@Test public void decode_withInvalidEncodedArgument_shouldThrow()... |
ImapStore extends RemoteStore { @Override @NonNull public ImapFolder getFolder(String folderId) { ImapFolder folder; synchronized (folderCache) { folder = folderCache.get(folderId); if (folder == null) { folder = new ImapFolder(this, folderId); folderCache.put(folderId, folder); } } return folder; } ImapStore(StoreConf... | @Test public void getFolder_shouldReturnImapFolderInstance() throws Exception { Folder result = imapStore.getFolder("INBOX"); assertEquals(ImapFolder.class, result.getClass()); }
@Test public void getFolder_calledTwice_shouldReturnFirstInstance() throws Exception { String folderName = "Trash"; Folder imapFolder = imapS... |
ImapStore extends RemoteStore { @Override public void checkSettings() throws MessagingException { try { ImapConnection connection = createImapConnection(); connection.open(); autoconfigureFolders(connection); connection.close(); } catch (IOException ioe) { throw new MessagingException("Unable to connect", ioe); } } Ima... | @Test public void checkSettings_shouldCreateImapConnectionAndCallOpen() throws Exception { ImapConnection imapConnection = mock(ImapConnection.class); imapStore.enqueueImapConnection(imapConnection); imapStore.checkSettings(); verify(imapConnection).open(); }
@Test public void checkSettings_withOpenThrowing_shouldThrow... |
ImapStore extends RemoteStore { void autoconfigureFolders(final ImapConnection connection) throws IOException, MessagingException { if (!connection.hasCapability(Capabilities.SPECIAL_USE)) { if (K9MailLib.isDebug()) { Timber.d("No detected folder auto-configuration methods."); } return; } if (K9MailLib.isDebug()) { Tim... | @Test public void autoconfigureFolders_withSpecialUseCapability_shouldSetSpecialFolders() throws Exception { ImapConnection imapConnection = mock(ImapConnection.class); when(imapConnection.hasCapability(Capabilities.SPECIAL_USE)).thenReturn(true); List<ImapResponse> imapResponses = Arrays.asList( createImapResponse("* ... |
ImapStore extends RemoteStore { @Override @NonNull public List<ImapFolder> getFolders(boolean forceListAll) throws MessagingException { return getPersonalNamespaces(forceListAll); } ImapStore(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory,
ConnectivityManager connectivityManager, OAuth2T... | @Test public void getPersonalNamespaces_withForceListAll() throws Exception { when(storeConfig.subscribedFoldersOnly()).thenReturn(true); ImapConnection imapConnection = mock(ImapConnection.class); List<ImapResponse> imapResponses = Arrays.asList( createImapResponse("* LIST (\\HasNoChildren) \".\" \"INBOX\""), createIm... |
ImapStore extends RemoteStore { ImapConnection getConnection() throws MessagingException { ImapConnection connection; while ((connection = pollConnection()) != null) { try { connection.executeSimpleCommand(Commands.NOOP); break; } catch (IOException ioe) { connection.close(); } } if (connection == null) { connection = ... | @Test public void getConnection_shouldCreateImapConnection() throws Exception { ImapConnection imapConnection = mock(ImapConnection.class); imapStore.enqueueImapConnection(imapConnection); ImapConnection result = imapStore.getConnection(); assertSame(imapConnection, result); }
@Test public void getConnection_calledTwic... |
ImapUtility { public static List<String> getImapSequenceValues(String set) { List<String> list = new ArrayList<String>(); if (set != null) { String[] setItems = set.split(","); for (String item : setItems) { if (item.indexOf(':') == -1) { if (isNumberValid(item)) { list.add(item); } } else { list.addAll(getImapRangeVal... | @Test public void testGetImapSequenceValues() { String[] expected; List<String> actual; expected = new String[] {"1"}; actual = ImapUtility.getImapSequenceValues("1"); assertArrayEquals(expected, actual.toArray()); expected = new String[] {"2147483648"}; actual = ImapUtility.getImapSequenceValues("2147483648"); assertA... |
ImapUtility { public static List<String> getImapRangeValues(String range) { List<String> list = new ArrayList<String>(); try { if (range != null) { int colonPos = range.indexOf(':'); if (colonPos > 0) { long first = Long.parseLong(range.substring(0, colonPos)); long second = Long.parseLong(range.substring(colonPos + 1)... | @Test public void testGetImapRangeValues() { String[] expected; List<String> actual; expected = new String[] {"1", "2", "3"}; actual = ImapUtility.getImapRangeValues("1:3"); assertArrayEquals(expected, actual.toArray()); expected = new String[] {"16", "15", "14"}; actual = ImapUtility.getImapRangeValues("16:14"); asser... |
ImapPushState { public static ImapPushState parse(String pushState) { if (pushState == null || !pushState.startsWith(PUSH_STATE_PREFIX)) { return createDefaultImapPushState(); } String value = pushState.substring(PUSH_STATE_PREFIX_LENGTH); try { long newUidNext = Long.parseLong(value); return new ImapPushState(newUidNe... | @Test public void parse_withValidArgument() throws Exception { ImapPushState result = ImapPushState.parse("uidNext=42"); assertNotNull(result); assertEquals(42L, result.uidNext); }
@Test public void parse_withNullArgument_shouldReturnUidNextOfMinusOne() throws Exception { ImapPushState result = ImapPushState.parse(null... |
HtmlConverter { public static String textToHtml(String text) { if (text.length() > MAX_SMART_HTMLIFY_MESSAGE_LENGTH) { return simpleTextToHtml(text); } StringBuilder buff = new StringBuilder(text.length() + TEXT_TO_HTML_EXTRA_BUFFER_LENGTH); boolean isStartOfLine = true; int spaces = 0; int quoteDepth = 0; int quotesTh... | @Test public void testTextQuoteToHtmlBlockquote() { String message = "Panama!\r\n" + "\r\n" + "Bob Barker <bob@aol.com> wrote:\r\n" + "> a canal\r\n" + ">\r\n" + "> Dorothy Jo Gideon <dorothy@aol.com> espoused:\r\n" + "> >A man, a plan...\r\n" + "> Too easy!\r\n" + "\r\n" + "Nice job :)\r\n" + ">> Guess!"; String resul... |
ImapPushState { @Override public String toString() { return "uidNext=" + uidNext; } ImapPushState(long uidNext); static ImapPushState parse(String pushState); @Override String toString(); final long uidNext; } | @Test public void toString_shouldReturnExpectedResult() throws Exception { ImapPushState imapPushState = new ImapPushState(23L); String result = imapPushState.toString(); assertEquals("uidNext=23", result); } |
AlertResponse { public static String getAlertText(ImapResponse response) { if (response.size() < 3 || !response.isList(1)) { return null; } ImapList responseTextCode = response.getList(1); if (responseTextCode.size() != 1 || !equalsIgnoreCase(responseTextCode.get(0), ALERT_RESPONSE_CODE)) { return null; } return respon... | @Test public void getAlertText_withProperAlertResponse() throws Exception { ImapResponse imapResponse = createImapResponse("x NO [ALERT] Please don't do that"); String result = AlertResponse.getAlertText(imapResponse); assertEquals("Please don't do that", result); }
@Test public void getAlertText_withoutResponseCodeTex... |
CapabilityResponse { public static CapabilityResponse parse(List<ImapResponse> responses) { for (ImapResponse response : responses) { CapabilityResponse result; if (!response.isEmpty() && equalsIgnoreCase(response.get(0), Responses.OK) && response.isList(1)) { ImapList capabilityList = response.getList(1); result = par... | @Test public void parse_withTaggedResponse_shouldReturnNull() throws Exception { CapabilityResponse result = parse("1 OK"); assertNull(result); }
@Test public void parse_withoutOkResponse_shouldReturnNull() throws Exception { CapabilityResponse result = parse("* BAD Go Away"); assertNull(result); }
@Test public void pa... |
PermanentFlagsResponse { public static PermanentFlagsResponse parse(ImapResponse response) { if (response.isTagged() || !equalsIgnoreCase(response.get(0), Responses.OK) || !response.isList(1)) { return null; } ImapList responseTextList = response.getList(1); if (responseTextList.size() < 2 || !equalsIgnoreCase(response... | @Test public void parse_withTaggedResponse_shouldReturnNull() throws Exception { ImapResponse response = createImapResponse("1 OK [PERMANENTFLAGS (\\Deleted \\Seen)] Flags permitted."); PermanentFlagsResponse result = PermanentFlagsResponse.parse(response); assertNull(result); }
@Test public void parse_withoutOkRespons... |
ImapResponseParser { public ImapResponse readResponse() throws IOException { return readResponse(null); } ImapResponseParser(PeekableInputStream in); ImapResponse readResponse(); ImapResponse readResponse(ImapResponseCallback callback); } | @Test public void testSimpleOkResponse() throws IOException { ImapResponseParser parser = createParser("* OK\r\n"); ImapResponse response = parser.readResponse(); assertNotNull(response); assertEquals(1, response.size()); assertEquals("OK", response.get(0)); }
@Test public void testOkResponseWithText() throws IOExcepti... |
ImapResponseParser { List<ImapResponse> readStatusResponse(String tag, String commandToLog, String logId, UntaggedHandler untaggedHandler) throws IOException, NegativeImapResponseException { List<ImapResponse> responses = new ArrayList<ImapResponse>(); ImapResponse response; do { response = readResponse(); if (K9MailLi... | @Test public void testReadStatusResponseWithOKResponse() throws Exception { ImapResponseParser parser = createParser("* COMMAND BAR\tBAZ\r\n" + "TAG OK COMMAND completed\r\n"); List<ImapResponse> responses = parser.readStatusResponse("TAG", null, null, null); assertEquals(2, responses.size()); assertEquals(asList("COMM... |
ImapResponseParser { private Object parseLiteral() throws IOException { expect('{'); int size = Integer.parseInt(readStringUntil('}')); expect('\r'); expect('\n'); if (size == 0) { return ""; } if (response.getCallback() != null) { FixedLengthInputStream fixed = new FixedLengthInputStream(inputStream, size); Exception ... | @Test public void testParseLiteral() throws Exception { ImapResponseParser parser = createParser("* {4}\r\ntest\r\n"); ImapResponse response = parser.readResponse(); assertEquals(1, response.size()); assertEquals("test", response.getString(0)); } |
ImapResponseParser { private String parseQuoted() throws IOException { expect('"'); StringBuilder sb = new StringBuilder(); int ch; boolean escape = false; while ((ch = inputStream.read()) != -1) { if (!escape && ch == '\\') { escape = true; } else if (!escape && ch == '"') { return sb.toString(); } else { sb.append((c... | @Test public void testParseQuoted() throws Exception { ImapResponseParser parser = createParser("* \"qu\\\"oted\"\r\n"); ImapResponse response = parser.readResponse(); assertEquals(1, response.size()); assertEquals("qu\"oted", response.getString(0)); } |
ImapPusher implements Pusher { @Override public void start(List<String> folderNames) { synchronized (folderPushers) { stop(); setLastRefresh(currentTimeMillis()); for (String folderName : folderNames) { ImapFolderPusher pusher = createImapFolderPusher(folderName); folderPushers.add(pusher); pusher.start(); } } } ImapPu... | @Test public void start_withSingleFolderName_shouldCreateImapFolderPusherAndCallStartOnIt() throws Exception { List<String> folderNames = Collections.singletonList("INBOX"); imapPusher.start(folderNames); List<ImapFolderPusher> imapFolderPushers = imapPusher.getImapFolderPushers(); assertEquals(1, imapFolderPushers.siz... |
ImapPusher implements Pusher { @Override public void stop() { if (K9MailLib.isDebug()) { Timber.i("Requested stop of IMAP pusher"); } synchronized (folderPushers) { for (ImapFolderPusher folderPusher : folderPushers) { try { if (K9MailLib.isDebug()) { Timber.i("Requesting stop of IMAP folderPusher %s", folderPusher.get... | @Test public void stop_withoutStartBeingCalled_shouldNotCreateAnyImapFolderPushers() throws Exception { imapPusher.stop(); List<ImapFolderPusher> imapFolderPushers = imapPusher.getImapFolderPushers(); assertEquals(0, imapFolderPushers.size()); } |
ImapPusher implements Pusher { @Override public int getRefreshInterval() { return (store.getStoreConfig().getIdleRefreshMinutes() * 60 * 1000); } ImapPusher(ImapStore store, PushReceiver pushReceiver); @Override void start(List<String> folderNames); @Override void refresh(); @Override void stop(); @Override int getRefr... | @Test public void getRefreshInterval() throws Exception { StoreConfig storeConfig = mock(StoreConfig.class); when(storeConfig.getIdleRefreshMinutes()).thenReturn(23); when(imapStore.getStoreConfig()).thenReturn(storeConfig); int result = imapPusher.getRefreshInterval(); assertEquals(23 * 60 * 1000, result); } |
ImapPusher implements Pusher { @Override public long getLastRefresh() { return lastRefresh; } ImapPusher(ImapStore store, PushReceiver pushReceiver); @Override void start(List<String> folderNames); @Override void refresh(); @Override void stop(); @Override int getRefreshInterval(); @Override long getLastRefresh(); @Ove... | @Test public void getLastRefresh_shouldBeMinusOneInitially() throws Exception { long result = imapPusher.getLastRefresh(); assertEquals(-1L, result); } |
ImapList extends ArrayList<Object> { public boolean containsKey(String key) { if (key == null) { return false; } for (int i = 0, count = size() - 1; i < count; i++) { if (ImapResponseParser.equalsIgnoreCase(get(i), key)) { return true; } } return false; } ImapList getList(int index); boolean isList(int index); Object ... | @Test public void containsKey_returnsTrueForKeys() throws IOException { ImapList list = buildSampleList(); assertTrue(list.containsKey("ONE")); assertTrue(list.containsKey("TWO")); assertFalse(list.containsKey("THREE")); assertFalse(list.containsKey("nonexistent")); }
@Test public void containsKey_returnsFalseForString... |
ImapList extends ArrayList<Object> { public Object getKeyedValue(String key) { for (int i = 0, count = size() - 1; i < count; i++) { if (ImapResponseParser.equalsIgnoreCase(get(i), key)) { return get(i + 1); } } return null; } ImapList getList(int index); boolean isList(int index); Object getObject(int index); String ... | @Test public void getKeyedValue_providesCorrespondingValues() { ImapList list = buildSampleList(); assertEquals("TWO", list.getKeyedValue("ONE")); assertEquals("THREE", list.getKeyedValue("TWO")); assertNull(list.getKeyedValue("THREE")); assertNull(list.getKeyedValue("nonexistent")); } |
ImapList extends ArrayList<Object> { public int getKeyIndex(String key) { for (int i = 0, count = size() - 1; i < count; i++) { if (ImapResponseParser.equalsIgnoreCase(get(i), key)) { return i; } } throw new IllegalArgumentException("getKeyIndex() only works for keys that are in the collection."); } ImapList getList(i... | @Test public void getKeyIndex_providesIndexForKeys() { ImapList list = buildSampleList(); assertEquals(0, list.getKeyIndex("ONE")); assertEquals(1, list.getKeyIndex("TWO")); }
@Test(expected = IllegalArgumentException.class) public void getKeyIndex_throwsExceptionForValue() { ImapList list = buildSampleList(); list.get... |
ImapList extends ArrayList<Object> { public Date getDate(int index) throws MessagingException { return getDate(getString(index)); } ImapList getList(int index); boolean isList(int index); Object getObject(int index); String getString(int index); boolean isString(int index); long getLong(int index); int getNumber(int i... | @Test public void getDate_returnsCorrectDateForValidString() throws MessagingException { ImapList list = new ImapList(); list.add("INTERNALDATE"); list.add("10-Mar-2000 12:02:01 GMT"); Calendar c = Calendar.getInstance(); c.setTime(list.getDate(1)); assertEquals(2000, c.get(Calendar.YEAR)); assertEquals(Calendar.MARCH,... |
ImapList extends ArrayList<Object> { public Date getKeyedDate(String key) throws MessagingException { return getDate(getKeyedString(key)); } ImapList getList(int index); boolean isList(int index); Object getObject(int index); String getString(int index); boolean isString(int index); long getLong(int index); int getNum... | @Test public void getKeyedDate_returnsCorrectDateForValidString() throws MessagingException { ImapList list = new ImapList(); list.add("INTERNALDATE"); list.add("10-Mar-2000 12:02:01 GMT"); Calendar c = Calendar.getInstance(); c.setTime(list.getKeyedDate("INTERNALDATE")); assertEquals(2000, c.get(Calendar.YEAR)); asser... |
SelectOrExamineResponse { public static SelectOrExamineResponse parse(ImapResponse response) { if (!response.isTagged() || !equalsIgnoreCase(response.get(0), Responses.OK)) { return null; } if (!response.isList(1)) { return noOpenModeInResponse(); } ImapList responseTextList = response.getList(1); if (!responseTextList... | @Test public void parse_withUntaggedResponse_shouldReturnNull() throws Exception { ImapResponse imapResponse = createImapResponse("* OK [READ-WRITE] Select completed."); SelectOrExamineResponse result = SelectOrExamineResponse.parse(imapResponse); assertNull(result); }
@Test public void parse_withoutOkResponse_shouldRe... |
ImapFolder extends Folder<ImapMessage> { @Override public void open(int mode) throws MessagingException { internalOpen(mode); if (messageCount == -1) { throw new MessagingException("Did not find message count during open"); } } ImapFolder(ImapStore store, String id); ImapFolder(ImapStore store, String id, FolderNameC... | @Test public void open_calledTwice_shouldReuseSameImapConnection() throws Exception { ImapFolder imapFolder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); imapFolder.open(OPEN_MODE_RW); imapFolder.open(OPEN_MODE_RW); verify(imapStore, times(1)).getConnection(); } |
ImapFolder extends Folder<ImapMessage> { private boolean exists(String escapedFolderName) throws MessagingException { try { connection.executeSimpleCommand(String.format("STATUS %s (RECENT)", escapedFolderName)); return true; } catch (IOException ioe) { throw ioExceptionHandler(connection, ioe); } catch (NegativeImapRe... | @Test public void exists_withoutNegativeImapResponse_shouldReturnTrue() throws Exception { ImapFolder imapFolder = createFolder("Folder"); when(imapStore.getConnection()).thenReturn(imapConnection); boolean folderExists = imapFolder.exists(); assertTrue(folderExists); } |
ImapFolder extends Folder<ImapMessage> { @Override public boolean create(FolderType type) throws MessagingException { ImapConnection connection; synchronized (this) { if (this.connection == null) { connection = store.getConnection(); } else { connection = this.connection; } } try { String encodedFolderName = folderName... | @Test public void create_withoutNegativeImapResponse_shouldReturnTrue() throws Exception { ImapFolder imapFolder = createFolder("Folder"); when(imapStore.getConnection()).thenReturn(imapConnection); boolean success = imapFolder.create(FolderType.HOLDS_MESSAGES); assertTrue(success); } |
ImapFolder extends Folder<ImapMessage> { @Override public Map<String, String> copyMessages(List<? extends Message> messages, Folder folder) throws MessagingException { if (!(folder instanceof ImapFolder)) { throw new MessagingException("ImapFolder.copyMessages passed non-ImapFolder"); } if (messages.isEmpty()) { return... | @Test public void copyMessages_withEmptyMessageList_shouldReturnNull() throws Exception { ImapFolder sourceFolder = createFolder("Source"); ImapFolder destinationFolder = createFolder("Destination"); List<ImapMessage> messages = Collections.emptyList(); Map<String, String> uidMapping = sourceFolder.copyMessages(message... |
ImapFolder extends Folder<ImapMessage> { @Override public Map<String, String> moveMessages(List<? extends Message> messages, Folder folder) throws MessagingException { if (messages.isEmpty()) { return null; } Map<String, String> uidMapping = copyMessages(messages, folder); setFlags(messages, Collections.singleton(Flag.... | @Test public void moveMessages_withEmptyMessageList_shouldReturnNull() throws Exception { ImapFolder sourceFolder = createFolder("Source"); ImapFolder destinationFolder = createFolder("Destination"); List<ImapMessage> messages = Collections.emptyList(); Map<String, String> uidMapping = sourceFolder.moveMessages(message... |
ImapFolder extends Folder<ImapMessage> { @Override public void delete(List<? extends Message> messages, String trashFolderName) throws MessagingException { if (messages.isEmpty()) { return; } if (trashFolderName == null || getId().equalsIgnoreCase(trashFolderName)) { setFlags(messages, Collections.singleton(Flag.DELETE... | @Test public void delete_withEmptyMessageList_shouldNotInteractWithImapConnection() throws Exception { ImapFolder folder = createFolder("Source"); List<ImapMessage> messages = Collections.emptyList(); folder.delete(messages, "Trash"); verifyNoMoreInteractions(imapConnection); }
@Test(expected = Error.class) public void... |
ImapFolder extends Folder<ImapMessage> { @Override public int getUnreadMessageCount() throws MessagingException { return getRemoteMessageCount("UNSEEN NOT DELETED"); } ImapFolder(ImapStore store, String id); ImapFolder(ImapStore store, String id, FolderNameCodec folderNameCodec); @Override void open(int mode); @Overr... | @Test public void getUnreadMessageCount_withClosedFolder_shouldThrow() throws Exception { ImapFolder folder = createFolder("Folder"); when(imapStore.getConnection()).thenReturn(imapConnection); try { folder.getUnreadMessageCount(); fail("Expected exception"); } catch (MessagingException e) { assertCheckOpenErrorMessage... |
ImapFolder extends Folder<ImapMessage> { @Override public int getFlaggedMessageCount() throws MessagingException { return getRemoteMessageCount("FLAGGED NOT DELETED"); } ImapFolder(ImapStore store, String id); ImapFolder(ImapStore store, String id, FolderNameCodec folderNameCodec); @Override void open(int mode); @Ove... | @Test public void getFlaggedMessageCount_withClosedFolder_shouldThrow() throws Exception { ImapFolder folder = createFolder("Folder"); when(imapStore.getConnection()).thenReturn(imapConnection); try { folder.getFlaggedMessageCount(); fail("Expected exception"); } catch (MessagingException e) { assertCheckOpenErrorMessa... |
ImapFolder extends Folder<ImapMessage> { protected long getHighestUid() throws MessagingException { try { String command = "UID SEARCH *:*"; List<ImapResponse> responses = executeSimpleCommand(command); SearchResponse searchResponse = SearchResponse.parse(responses); return extractHighestUid(searchResponse); } catch (N... | @Test public void getHighestUid() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); List<ImapResponse> imapResponses = singletonList(createImapResponse("* SEARCH 42")); when(imapConnection.executeSimpleCommand("UID SEARCH *:*")).thenReturn(imapResponses); folder.open... |
ImapFolder extends Folder<ImapMessage> { @Override public List<ImapMessage> getMessages(int start, int end, Date earliestDate, MessageRetrievalListener<ImapMessage> listener) throws MessagingException { return getMessages(start, end, earliestDate, false, listener); } ImapFolder(ImapStore store, String id); ImapFolder... | @Test public void getMessages_withClosedFolder_shouldThrow() throws Exception { ImapFolder folder = createFolder("Folder"); when(imapStore.getConnection()).thenReturn(imapConnection); try { folder.getMessages(1, 5, null, null); fail("Expected exception"); } catch (MessagingException e) { assertCheckOpenErrorMessage("Fo... |
ImapFolder extends Folder<ImapMessage> { protected List<ImapMessage> getMessagesFromUids(final List<String> mesgUids) throws MessagingException { ImapSearcher searcher = new ImapSearcher() { @Override public List<ImapResponse> search() throws IOException, MessagingException { String command = String.format("UID SEARCH ... | @Test public void getMessagesFromUids_withClosedFolder_shouldThrow() throws Exception { ImapFolder folder = createFolder("Folder"); when(imapStore.getConnection()).thenReturn(imapConnection); try { folder.getMessagesFromUids(asList("11", "22", "25")); fail("Expected exception"); } catch (MessagingException e) { assertC... |
ImapFolder extends Folder<ImapMessage> { @Override public boolean areMoreMessagesAvailable(int indexOfOldestMessage, Date earliestDate) throws IOException, MessagingException { checkOpen(); if (indexOfOldestMessage == 1) { return false; } String dateSearchString = getDateSearchString(earliestDate); int endIndex = index... | @Test public void areMoreMessagesAvailable_withClosedFolder_shouldThrow() throws Exception { ImapFolder folder = createFolder("Folder"); when(imapStore.getConnection()).thenReturn(imapConnection); try { folder.areMoreMessagesAvailable(10, new Date()); fail("Expected exception"); } catch (MessagingException e) { assertC... |
ImapFolder extends Folder<ImapMessage> { @Override public void fetch(List<ImapMessage> messages, FetchProfile fetchProfile, MessageRetrievalListener<ImapMessage> listener) throws MessagingException { if (messages == null || messages.isEmpty()) { return; } checkOpen(); List<String> uids = new ArrayList<>(messages.size()... | @Test public void fetch_withNullMessageListArgument_shouldDoNothing() throws Exception { ImapFolder folder = createFolder("Folder"); FetchProfile fetchProfile = createFetchProfile(); folder.fetch(null, fetchProfile, null); verifyNoMoreInteractions(imapConnection); }
@Test public void fetch_withEmptyMessageListArgument_... |
ImapFolder extends Folder<ImapMessage> { @Override public String getUidFromMessageId(Message message) throws MessagingException { try { String[] messageIdHeader = message.getHeader("Message-ID"); if (messageIdHeader.length == 0) { if (K9MailLib.isDebug()) { Timber.d("Did not get a message-id in order to search for UID ... | @Test public void getUidFromMessageId_withoutMessageIdHeader_shouldReturnNull() throws Exception { ImapFolder folder = createFolder("Folder"); ImapMessage message = createImapMessage("2"); when(message.getHeader("Message-ID")).thenReturn(new String[0]); String uid = folder.getUidFromMessageId(message); assertNull(uid);... |
ImapFolder extends Folder<ImapMessage> { @Override public String getNewPushState(String oldSerializedPushState, Message message) { try { String uid = message.getUid(); long messageUid = Long.parseLong(uid); ImapPushState oldPushState = ImapPushState.parse(oldSerializedPushState); if (messageUid >= oldPushState.uidNext)... | @Test public void getNewPushState_withNewerUid_shouldReturnNewPushState() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); ImapMessage message = createImapMessage("2"); String newPushState = folder.getNewPushState("uidNext=2", message); assertEquals("uidNext=3", new... |
ImapFolder extends Folder<ImapMessage> { @Override public ImapMessage getMessage(String uid) throws MessagingException { return new ImapMessage(uid, this); } ImapFolder(ImapStore store, String id); ImapFolder(ImapStore store, String id, FolderNameCodec folderNameCodec); @Override void open(int mode); @Override boolea... | @Test public void getMessageByUid_returnsNewImapMessageWithUidInFolder() throws Exception { ImapFolder folder = createFolder("Folder"); ImapMessage message = folder.getMessage("uid"); assertEquals("uid", message.getUid()); assertEquals(folder, message.getFolder()); } |
BoundaryGenerator { public String generateBoundary() { StringBuilder builder = new StringBuilder(4 + BOUNDARY_CHARACTER_COUNT); builder.append("----"); for (int i = 0; i < BOUNDARY_CHARACTER_COUNT; i++) { builder.append(BASE36_MAP[random.nextInt(36)]); } return builder.toString(); } @VisibleForTesting BoundaryGenerato... | @Test public void generateBoundary_allZeros() throws Exception { Random random = createRandom(0); BoundaryGenerator boundaryGenerator = new BoundaryGenerator(random); String result = boundaryGenerator.generateBoundary(); assertEquals("----000000000000000000000000000000", result); }
@Test public void generateBoundary() ... |
Message implements Part, Body { @Override public boolean equals(Object o) { if (o == null || !(o instanceof Message)) { return false; } Message other = (Message)o; return (getUid().equals(other.getUid()) && getFolder().getId().equals(other.getFolder().getId())); } boolean olderThan(Date earliestDate); @Override boolea... | @Test public void equals_whenFolderIdDifferent_isFalse() { SimpleFolder folder1 = new SimpleFolder(); folder1.id = "1"; SimpleFolder folder2 = new SimpleFolder(); folder2.id = "2"; String uid = "uid"; Message m1 = new StoredMimeMessage(folder1, uid); Message m2 = new StoredMimeMessage(folder2, uid); boolean result = m1... |
HttpUriParser implements UriParser { @Override public int linkifyUri(String text, int startPos, StringBuffer outputBuffer) { int currentPos = startPos; String shortScheme = text.substring(currentPos, Math.min(currentPos + 7, text.length())); String longScheme = text.substring(currentPos, Math.min(currentPos + 8, text.l... | @Test public void domainWithTrailingSpace() { String text = "http: int endPos = parser.linkifyUri(text, 0, outputBuffer); assertLinkOnly("http: assertEquals(text.length() - 1, endPos); }
@Test public void domainWithTrailingNewline() { String text = "http: int endPos = parser.linkifyUri(text, 0, outputBuffer); assertLin... |
StringCalculator { public int add(String input) { if ("".equals(input)) { return 0; } String numbers = extractNumbers(input); String delimiter = extractDelimiter(input); return stringSum(numbers, delimiter); } int add(String input); } | @Test public void TestEmptyStringReturnZero() { Assert.assertEquals(0, stringCalculator.add("")); }
@Test public void TestNumberStringReturnValue() { Assert.assertEquals(1, stringCalculator.add("1")); Assert.assertEquals(2, stringCalculator.add("2")); }
@Test public void TestTwoNumbersStringReturnSum() { Assert.assertE... |
StringCalculator { public int add(String input) { if ("".equals(input)) return 0; String delimiter = extractDelimiter(input); String[] numberArray = extractNumbers(input, delimiter); return sumNumberArray(numberArray); } int add(String input); } | @Test public void comma_or_return_line_separated_numbers_return_sum() { Assert.assertEquals(6, this.calculator.add("1\n2,3")); }
@Test public void any_delimited_numbers_return_sum() { Assert.assertEquals(3, this.calculator.add(" }
@Test public void negative_number_throw_exception() { this.exception.expect(RuntimeExcept... |
StringCalculator { public int add(String input) { if (input.isEmpty()) return 0; String delimiter = getDelimiter(input); String numbers = getNumbers(input); return calculateSum(numbers.split(delimiter)); } int add(String input); } | @Test public void emptyStringReturnsZero() { assertEquals(0, this.stringCalculator.add("")); }
@Test public void numberStringReturnsNumber() { assertEquals(1, this.stringCalculator.add("1")); }
@Test public void stringNumbersCommaDelimitedReturnsSum() { assertEquals(3, this.stringCalculator.add("1,2")); }
@Test public ... |
RockPaper { public final int play(final String playerOne, final String playerTwo) { int response = DRAW; if (isDraw(playerOne, playerTwo)) { response = DRAW; } else if (PAPER.equals(playerOne)) { return checkPaperRulesPlayerOne(playerTwo); } else if (ROCK.equals(playerOne) && PAPER.equals(playerTwo)) { response = WINPL... | @Test public final void sameMovesReturnDraw() { Assert.assertEquals(RockPaper.DRAW, this.GAME.play(RockPaper.SCISSORS, RockPaper.SCISSORS)); Assert.assertEquals(RockPaper.DRAW, this.GAME.play(RockPaper.PAPER, RockPaper.PAPER)); Assert.assertEquals(RockPaper.DRAW, this.GAME.play(RockPaper.ROCK, RockPaper.ROCK)); Assert.... |
PageAnalyzer { public static HtmlAnalysisResult analyze(Map<String, String> config, String url) { try { String userAgent = config.getOrDefault(CONFIG_USER_AGENT, DEFAULT_USER_AGENT); HttpResponse<String> response = Unirest.get(url) .header("User-Agent", userAgent) .asString(); return analyze(config, url, response.getBo... | @Test public void headersAndStatus() { Map<String, List<String>> headers = Maps.newHashMap(); headers.put("Etag", Lists.newArrayList("c1dc8d7be85325149", "ed5fc4d62b84752")); headers.put("Date", Lists.newArrayList("Wed, 11 Jan 2017 13:00:18 GMT")); HashMap<String, String> config = Maps.newHashMap(); HtmlAnalysisResult ... |
DateParser { public static MatchedDate parse(MatchedDate matchedText, HttpSource source) { String value = Strings.nullToEmpty(matchedText.getValue()).trim(); for (String regexp : source.getDateRegexps()) { Pattern pattern = Pattern.compile(regexp); Matcher matcher = pattern.matcher(value); if (matcher.matches() && matc... | @Test public void formats() { MatchedDate matchedDate = new MatchedDate("2017-01-16 01:45:05 -0500", null); MatchedDate parse = DateParser.parse(matchedDate, new HttpSource()); assertEquals("2017-01-16T06:45:05", DataUtils.formatInUTC(parse.getDate())); matchedDate = new MatchedDate("Jan 17, 2017 06:08AM ET", null); pa... |
DateParser { private static MatchedDate parseWithTimewords(MatchedDate matchedText, HttpSource source) { Timewords timewords = new Timewords(); try { Date parse = timewords.parse(matchedText.getValue(), new Date(), source.getLanguage()); if (parse != null) { matchedText.setDate(new DateTime(parse)); matchedText.setPatt... | @Test public void parseWithTimewords() { MatchedDate matchedDate = new MatchedDate("Wed Feb 24 2016 00:01 UTC+1201", null); MatchedDate parse = DateParser.parse(matchedDate, new HttpSource()); assertEquals("2016-02-24T00:01:00", DataUtils.formatInUTC(parse.getDate())); assertEquals("TIMEWORDS", parse.getPattern()); ass... |
DataUtils implements Serializable { public static List<String> parseStringList(Object object) { if (object == null) { return null; } return Splitter.onPattern("(?:\r?\n)+") .splitToList(object.toString()) .stream() .map(String::trim) .filter(s -> !s.isEmpty()) .collect(Collectors.toList()); } static Integer tryParseIn... | @Test public void normalizerSplitter() { assertEquals(Lists.newArrayList("\\?.*$-->>", "a-->>b"), DataUtils.parseStringList("\\?.*$-->>\na-->>b\r\r\n\n")); } |
DataUtils implements Serializable { public static String formatInUTC(DateTime date) { return date != null ? FORMATTER.print(date.toDateTime(DateTimeZone.UTC)) : null; } static Integer tryParseInteger(Object object); static Long tryParseLong(Object object); static List<String> parseStringList(Object object); static Str... | @Test public void dateFormatInUTC() { Long DATE_2017_01_04_12_26_00 = 1483532760805L; assertEquals("2017-01-04T12:26:00", DataUtils.formatInUTC(new DateTime(DATE_2017_01_04_12_26_00))); } |
EsHttpSourceOperations extends BaseElasticOps { public PageableList<HttpSource> filter(String text) { return filter(text, 0); } protected EsHttpSourceOperations(ElasticConnection connection, String index, String type); static EsHttpSourceOperations getInstance(ElasticConnection connection, String index, String type); ... | @Test @Ignore public void test() { ElasticConnection connection = ElasticConnection.getConnection("localhost", 9200, "http"); EsHttpSourceOperations esHttpSourceOperations = new EsHttpSourceOperations(connection, "demo-http_sources", "http_source"); PageableList<HttpSource> data = esHttpSourceOperations.filter(null); f... |
ElasticConnection { public static Builder builder() { return new Builder(); } private ElasticConnection(BulkProcessor processor, RestHighLevelClient restHighLevelClient, RestClientBuilder restClient); static Builder builder(); RestHighLevelClient getRestHighLevelClient(); BulkProcessor getProcessor(); static ElasticCo... | @Test public void testBuilder() { BulkProcessor.Listener listener = new BulkProcessor.Listener() { @Override public void afterBulk(long executionId, BulkRequest request, BulkResponse response) { for (BulkItemResponse item : response.getItems()) { if (item.isFailed()) { LOG.error("Bulk item failure: '{}' for request '{}... |
TextProfileSignature { public TextProfileSignature() { this.quantRate = 0.01f; this.minTokenLen = 2; try { this.digester = MessageDigest.getInstance("MD5"); } catch (Exception e) { LOG.error("Failed to initialize Media digest algorithm"); throw new RuntimeException("Failed to initialize Media digest algorithm", e); } }... | @Test public void testTextProfileSignature() { TextProfileSignature textProfileSignature = new TextProfileSignature(); String text1 = "This is a test"; String text2 = "This is e test"; String text3 = "This is a very test"; assertEquals(text1, text1); assertTrue(textProfileSignature.getSignature(text1) .equalsIgnoreCase... |
QueryParser { public static List<String> parseQuery(String query) { List<String> result = Lists.newArrayList(); if (!Strings.isNullOrEmpty(query)) { query = query.replaceAll("(\\s*[+-]\\s*)", "#SPLIT#$1"); return Arrays.stream(query.split("(#SPLIT#| )")) .map(String::trim) .filter(s -> !s.isEmpty()) .collect(Collectors... | @Test public void parseQuery() { List<String> parts = QueryParser.parseQuery("+Turkey-Inflation"); assertEquals(Lists.newArrayList("+Turkey", "-Inflation"), parts); parts = QueryParser.parseQuery("+Turkey -Inflation"); assertEquals(Lists.newArrayList("+Turkey", "-Inflation"), parts); parts = QueryParser.parseQuery("Tur... |
UrlExtractor { private static Set<String> extract(Document document) { Set<String> canonicalUrls = new HashSet<>(); if (document == null) { return canonicalUrls; } Elements elements = document.select("meta[property=og:url]"); elements.forEach(element -> { String attr = element.attr("content"); if (attr != null) { canon... | @Test public void testExtraction00() throws Exception { String html = loadArticle("aljazeera1"); String url = "https: Document document = Jsoup.parse(html); assertEquals(url, UrlExtractor.extract(url, document)); assertEquals("https: }
@Test public void testExtraction01() throws Exception { String html = loadArticle("k... |
JsonUtil { public static Map<String, String> getJsonPathsForTemplating(Set<Map.Entry<String, JsonElement>> root) { Map<String, String> paths = new HashMap<>(); searchJsonForTemplate(root, paths, "$"); return paths; } private JsonUtil(/* empty */); static boolean updateField(JsonElement json, String field, JsonElement ... | @Test public void simple_shallow() { String template = "{ \"a\" : \"{{value}}\", \"b\": \"b\"}"; JsonObject document = (JsonObject) new JsonParser().parse(template); Map<String, String> paths = JsonUtil.getJsonPathsForTemplating(document); assertEquals(1, paths.size()); Object value = paths.get("$.a"); assertNotNull(va... |
HazelcastMapMetricsReporter extends AbstractReportingTask { boolean isValid(ObjectName name, Set<String> mapNames, String clusterName) { if (!"com.hazelcast".equals(name.getDomain())) { return false; } String propertyName = name.getKeyProperty("name"); if (!mapNames.isEmpty() && !mapNames.contains(propertyName)) { retu... | @Test public void testIsValid() throws MalformedObjectNameException { ObjectName o = new ObjectName("domain", "key", "value"); Set<String> mapNames = ImmutableSet.of("foo"); HazelcastMapMetricsReporter hazelcastMapMetricsReporter = new HazelcastMapMetricsReporter(); boolean isValid = hazelcastMapMetricsReporter.isValid... |
InfluxNiFiClusterMetricsReporter extends AbstractNiFiClusterMetricsReporter { void collectMeasurements(long now, SystemMetricsSnapshot snapshot, BatchPoints points) { collectMemoryMetrics(now, snapshot, points); collectJvmMetrics(now, snapshot, points); collectDiskUsageMetrics(now, snapshot, points); collectProcessGrou... | @Test public void testCollectMeasurements() throws InitializationException { InfluxNiFiClusterMetricsReporter metricsInfluxDbReporter = new InfluxNiFiClusterMetricsReporter(); ProcessGroupStatusMetric processGroupStatusMetric = new ProcessGroupStatusMetric() .setId("id") .setProcessGroupName("root") .setActiveThreadCou... |
CloudwatchNiFiClusterMetricsReporter extends AbstractNiFiClusterMetricsReporter { List<MetricDatum> collectMeasurements(Date now, SystemMetricsSnapshot snapshot, List<Dimension> dimensions) { List<MetricDatum> toCloudwatch = new ArrayList<>(); if (collectsMemory) { getMetrics("System Memory", snapshot.getMachineMemory(... | @Test public void testCollectMeasurements() throws InitializationException { CloudwatchNiFiClusterMetricsReporter metricsCloudwatchReporter = new CloudwatchNiFiClusterMetricsReporter(); ProcessGroupStatusMetric processGroupStatusMetric = new ProcessGroupStatusMetric() .setId("id") .setProcessGroupName("root") .setActiv... |
ByteCode { public static void printOpCode(InstructionHandle insHandle, ConstantPoolGen cpg) { System.out.print("[" + String.format("%02d", insHandle.getPosition()) + "] "); printOpCode(insHandle.getInstruction(),cpg); } static void printOpCode(InstructionHandle insHandle, ConstantPoolGen cpg); static void printOpCode(... | @Test public void probeByteCodeDebug() { PrintStream sysOut = mock(PrintStream.class); System.out.println("Sysout hijack!"); PrintStream oldPrintStream = System.out; try { System.setOut(sysOut); InvokeInstruction ins = mock(InvokeInstruction.class); ConstantPoolGen cpg = mock(ConstantPoolGen.class); when(ins.getClassNa... |
DoubleLinkedCountingSet { public void increment(int key) { int index = sparse[key]; if (index < elementsCount && dense[index] == key) { counts[index]++; } else { index = elementsCount++; sparse[key] = index; dense[index] = key; counts[index] = 1; } } DoubleLinkedCountingSet(int maxValue, int maxValues); void increment(... | @Test public void testSimple() { DoubleLinkedCountingSet s = new DoubleLinkedCountingSet(10, 5); assertEquals(0, s.elementsCount); s.increment(3); assertEquals(1, s.elementsCount); assertEquals(1, s.counts[0]); assertEquals(3, s.dense[0]); s.increment(10); assertEquals(2, s.elementsCount); assertEquals(1, s.counts[1]);... |
LangIdV3 implements ILangIdClassifier { @Override public DetectedLanguage classify(CharSequence str, boolean normalizeConfidence) { reset(); append(str); return classify(normalizeConfidence); } LangIdV3(); LangIdV3(Model model); @Override DetectedLanguage classify(CharSequence str, boolean normalizeConfidence); @Overr... | @Test public void testSanity() { LangIdV3 langid = new LangIdV3(); for (String [] langString : new String [][] { {"en", "Mike McCandless rocks the boat."}, {"pl", "W Szczebrzeszynie chrząszcz brzmi w trzcinie"}, {"it", "Piano italiano per la crescita: negoziato in Europa sugli investimenti «virtuosi»"} }) { DetectedLan... |
Model { public static Model detectOnly(Set<String> langCodes) { final Model source = defaultModel(); Set<String> newClasses = new LinkedHashSet<String>(Arrays.asList(source.langClasses)); newClasses.retainAll(langCodes); if (newClasses.size() < 2) { throw new IllegalArgumentException("A model must contain at least two ... | @Test @Seeds(value = { @Seed, @Seed("deadbeef") }) public void testSameResultWithTrimmedLanguages() { final Set<String> allowed = Sets.newHashSet("en", "de", "es", "fr", "it", "pl"); LangIdV3 v1 = new LangIdV3(); LangIdV3 v2 = new LangIdV3(Model.detectOnly(allowed)); for (int i = 0; i < 10000; i++) { String in = random... |
UserService { public User create(String name, String currency) { final User user = new User(name, currency); return userRepository.save(user); } @Autowired UserService(UserRepository userRepository, UserManagementProperties userManagementProperties); List<User> list(); User create(String name, String currency); User g... | @Test public void shouldCreateUser() throws Exception { when(userRepositoryMock.save(isA(User.class))).thenAnswer(invocation -> invocation.getArgument(0)); final User user = testSubject.create("Clark", "$"); assertThat(user.getName()).isEqualTo("Clark"); assertThat(user.getCurrency()).isEqualTo("$"); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.