method2testcases
stringlengths
118
3.08k
### Question: BreakpointSQLiteHelper extends SQLiteOpenHelper { public List<Integer> loadDirtyFileList() { final List<Integer> dirtyFileList = new ArrayList<>(); Cursor cursor = null; try { cursor = getWritableDatabase().rawQuery("SELECT * FROM " + TASK_FILE_DIRTY_TABLE_NAME, null); while (cursor.moveToNext()) { dirtyFileList.add(cursor.getInt(cursor.getColumnIndex(ID))); } } finally { if (cursor != null) cursor.close(); } return dirtyFileList; } BreakpointSQLiteHelper(Context context); @Override void onOpen(SQLiteDatabase db); @Override void onCreate(SQLiteDatabase db); @Override void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion); @Override void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion); void markFileDirty(int id); void markFileClear(int id); List<Integer> loadDirtyFileList(); SparseArray<BreakpointInfo> loadToCache(); HashMap<String, String> loadResponseFilenameToMap(); void updateFilename(@NonNull String url, @NonNull String filename); void insert(@NonNull BreakpointInfo info); void updateBlockIncrease(@NonNull BreakpointInfo info, int blockIndex, long newCurrentOffset); void updateInfo(@NonNull BreakpointInfo info); void removeInfo(int id); void removeBlock(int breakpointId); }### Answer: @Test public void loadDirtyFileList() { doReturn(db).when(helper).getWritableDatabase(); Cursor cursor = mock(Cursor.class); doReturn(cursor).when(db).rawQuery("SELECT * FROM " + TASK_FILE_DIRTY_TABLE_NAME, null); doReturn(true, true, false).when(cursor).moveToNext(); doReturn(1, 2).when(cursor).getInt(anyInt()); assertThat(helper.loadDirtyFileList()).containsExactly(1, 2); }
### Question: BreakpointSQLiteHelper extends SQLiteOpenHelper { public void updateBlockIncrease(@NonNull BreakpointInfo info, int blockIndex, long newCurrentOffset) { final ContentValues values = new ContentValues(); values.put(CURRENT_OFFSET, newCurrentOffset); getWritableDatabase().update(BLOCK_TABLE_NAME, values, HOST_ID + " = ? AND " + BLOCK_INDEX + " = ?", new String[]{Integer.toString(info.id), Integer.toString(blockIndex)}); } BreakpointSQLiteHelper(Context context); @Override void onOpen(SQLiteDatabase db); @Override void onCreate(SQLiteDatabase db); @Override void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion); @Override void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion); void markFileDirty(int id); void markFileClear(int id); List<Integer> loadDirtyFileList(); SparseArray<BreakpointInfo> loadToCache(); HashMap<String, String> loadResponseFilenameToMap(); void updateFilename(@NonNull String url, @NonNull String filename); void insert(@NonNull BreakpointInfo info); void updateBlockIncrease(@NonNull BreakpointInfo info, int blockIndex, long newCurrentOffset); void updateInfo(@NonNull BreakpointInfo info); void removeInfo(int id); void removeBlock(int breakpointId); }### Answer: @Test public void updateBlockIncrease() { assertThat(insertedInfo2.getBlock(1).getCurrentOffset()).isEqualTo(10); helper.updateBlockIncrease(insertedInfo2, 1, 15); BreakpointInfo info2 = helper.loadToCache().get(insertedInfo2.id); assertThat(info2.getBlock(1).getCurrentOffset()).isEqualTo(15); }
### Question: BreakpointSQLiteHelper extends SQLiteOpenHelper { public void updateInfo(@NonNull BreakpointInfo info) throws IOException { final SQLiteDatabase db = getWritableDatabase(); Cursor cursor = null; db.beginTransaction(); try { cursor = getWritableDatabase().rawQuery( "SELECT " + ID + " FROM " + BREAKPOINT_TABLE_NAME + " WHERE " + ID + " =" + info.id + " LIMIT 1", null); if (!cursor.moveToNext()) return; removeInfo(info.id); insert(info); db.setTransactionSuccessful(); } finally { if (cursor != null) cursor.close(); db.endTransaction(); } } BreakpointSQLiteHelper(Context context); @Override void onOpen(SQLiteDatabase db); @Override void onCreate(SQLiteDatabase db); @Override void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion); @Override void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion); void markFileDirty(int id); void markFileClear(int id); List<Integer> loadDirtyFileList(); SparseArray<BreakpointInfo> loadToCache(); HashMap<String, String> loadResponseFilenameToMap(); void updateFilename(@NonNull String url, @NonNull String filename); void insert(@NonNull BreakpointInfo info); void updateBlockIncrease(@NonNull BreakpointInfo info, int blockIndex, long newCurrentOffset); void updateInfo(@NonNull BreakpointInfo info); void removeInfo(int id); void removeBlock(int breakpointId); }### Answer: @Test public void updateInfo() throws IOException { BreakpointInfo info1 = helper.loadToCache().get(insertedInfo1.id); assertThat(info1.getEtag()).isNull(); info1.setEtag("new-etag"); helper.updateInfo(info1); info1 = helper.loadToCache().get(info1.id); assertThat(info1.getEtag()).isEqualTo("new-etag"); }
### Question: DownloadUrlConnection implements DownloadConnection, DownloadConnection.Connected { @Override public Connected execute() throws IOException { final Map<String, List<String>> headerProperties = getRequestProperties(); connection.connect(); redirectHandler.handleRedirect(this, this, headerProperties); return this; } DownloadUrlConnection(URLConnection connection); DownloadUrlConnection(URLConnection connection, IRedirectHandler redirectHandler); DownloadUrlConnection(String originUrl, Configuration configuration); DownloadUrlConnection(URL url, Configuration configuration); DownloadUrlConnection( URL url, Configuration configuration, IRedirectHandler redirectHandler); DownloadUrlConnection(String originUrl); @Override void addHeader(String name, String value); @Override Connected execute(); @Override int getResponseCode(); @Override InputStream getInputStream(); @Override boolean setRequestMethod(@NonNull String method); @Override Map<String, List<String>> getResponseHeaderFields(); @Override String getResponseHeaderField(String name); @Override String getRedirectLocation(); @Override void release(); @Override Map<String, List<String>> getRequestProperties(); @Override String getRequestProperty(String key); }### Answer: @Test public void execute() throws Exception { doNothing().when(redirectHandler).handleRedirect(any(DownloadConnection.class), any(DownloadConnection.Connected.class), ArgumentMatchers.<String, List<String>>anyMap()); downloadUrlConnection.execute(); verify(urlConnection).connect(); }
### Question: BreakpointSQLiteHelper extends SQLiteOpenHelper { public void removeInfo(int id) { getWritableDatabase().delete(BREAKPOINT_TABLE_NAME, ID + " = ?", new String[]{String.valueOf(id)}); removeBlock(id); } BreakpointSQLiteHelper(Context context); @Override void onOpen(SQLiteDatabase db); @Override void onCreate(SQLiteDatabase db); @Override void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion); @Override void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion); void markFileDirty(int id); void markFileClear(int id); List<Integer> loadDirtyFileList(); SparseArray<BreakpointInfo> loadToCache(); HashMap<String, String> loadResponseFilenameToMap(); void updateFilename(@NonNull String url, @NonNull String filename); void insert(@NonNull BreakpointInfo info); void updateBlockIncrease(@NonNull BreakpointInfo info, int blockIndex, long newCurrentOffset); void updateInfo(@NonNull BreakpointInfo info); void removeInfo(int id); void removeBlock(int breakpointId); }### Answer: @Test public void removeInfo() { helper = spy(helper); helper.removeInfo(insertedInfo2.id); final SparseArray<BreakpointInfo> infoSparseArray = helper.loadToCache(); assertThat(infoSparseArray.size()).isEqualTo(1); assertThat(infoSparseArray.get(infoSparseArray.keyAt(0)).id).isEqualTo(insertedInfo1.id); verify(helper).removeBlock(insertedInfo2.id); }
### Question: BreakpointSQLiteHelper extends SQLiteOpenHelper { public void removeBlock(int breakpointId) { getWritableDatabase().delete(BLOCK_TABLE_NAME, HOST_ID + " = ?", new String[]{String.valueOf(breakpointId)}); } BreakpointSQLiteHelper(Context context); @Override void onOpen(SQLiteDatabase db); @Override void onCreate(SQLiteDatabase db); @Override void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion); @Override void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion); void markFileDirty(int id); void markFileClear(int id); List<Integer> loadDirtyFileList(); SparseArray<BreakpointInfo> loadToCache(); HashMap<String, String> loadResponseFilenameToMap(); void updateFilename(@NonNull String url, @NonNull String filename); void insert(@NonNull BreakpointInfo info); void updateBlockIncrease(@NonNull BreakpointInfo info, int blockIndex, long newCurrentOffset); void updateInfo(@NonNull BreakpointInfo info); void removeInfo(int id); void removeBlock(int breakpointId); }### Answer: @Test public void removeBlock() { assertThat(insertedInfo2.getBlockCount()).isEqualTo(2); helper.removeBlock(insertedInfo2.id); assertThat(helper.loadToCache().get(insertedInfo2.id).getBlockCount()).isZero(); }
### Question: RemitSyncExecutor implements Handler.Callback { void shutdown() { this.handler.getLooper().quit(); } RemitSyncExecutor(@NonNull RemitAgent agent); RemitSyncExecutor(@NonNull RemitAgent agent, @Nullable Handler handler, @NonNull Set<Integer> freeToDBIdList); void postSyncInfoDelay(int id, long delayMillis); void postSync(int id); void postSync(List<Integer> idList); void postRemoveInfo(int id); void postRemoveFreeIds(List<Integer> idList); void postRemoveFreeId(int id); boolean handleMessage(Message msg); }### Answer: @Test public void shutdown() { executor.shutdown(); verify(handler.getLooper()).quit(); }
### Question: RemitSyncExecutor implements Handler.Callback { boolean isFreeToDatabase(int id) { return freeToDBIdList.contains(id); } RemitSyncExecutor(@NonNull RemitAgent agent); RemitSyncExecutor(@NonNull RemitAgent agent, @Nullable Handler handler, @NonNull Set<Integer> freeToDBIdList); void postSyncInfoDelay(int id, long delayMillis); void postSync(int id); void postSync(List<Integer> idList); void postRemoveInfo(int id); void postRemoveFreeIds(List<Integer> idList); void postRemoveFreeId(int id); boolean handleMessage(Message msg); }### Answer: @Test public void isFreeToDatabase() { freeToDBIdList.add(1); assertThat(executor.isFreeToDatabase(1)).isTrue(); freeToDBIdList.remove(1); assertThat(executor.isFreeToDatabase(1)).isFalse(); }
### Question: RemitSyncExecutor implements Handler.Callback { public void postSyncInfoDelay(int id, long delayMillis) { handler.sendEmptyMessageDelayed(id, delayMillis); } RemitSyncExecutor(@NonNull RemitAgent agent); RemitSyncExecutor(@NonNull RemitAgent agent, @Nullable Handler handler, @NonNull Set<Integer> freeToDBIdList); void postSyncInfoDelay(int id, long delayMillis); void postSync(int id); void postSync(List<Integer> idList); void postRemoveInfo(int id); void postRemoveFreeIds(List<Integer> idList); void postRemoveFreeId(int id); boolean handleMessage(Message msg); }### Answer: @Test public void postSyncInfoDelay() { executor.postSyncInfoDelay(1, 10); verify(handler).sendEmptyMessageDelayed(eq(1), eq(10L)); }
### Question: RemitSyncExecutor implements Handler.Callback { public void postSync(int id) { handler.sendEmptyMessage(id); } RemitSyncExecutor(@NonNull RemitAgent agent); RemitSyncExecutor(@NonNull RemitAgent agent, @Nullable Handler handler, @NonNull Set<Integer> freeToDBIdList); void postSyncInfoDelay(int id, long delayMillis); void postSync(int id); void postSync(List<Integer> idList); void postRemoveInfo(int id); void postRemoveFreeIds(List<Integer> idList); void postRemoveFreeId(int id); boolean handleMessage(Message msg); }### Answer: @Test public void postSync() { executor.postSync(1); verify(handler).sendEmptyMessage(eq(1)); executor.postSync(idList); verify(handler).sendMessage(messageCaptor.capture()); final Message message = messageCaptor.getValue(); assertThat(message.obj).isEqualTo(idList); assertThat(message.what).isEqualTo(WHAT_SYNC_BUNCH_ID); }
### Question: RemitSyncExecutor implements Handler.Callback { public void postRemoveInfo(int id) { Message message = handler.obtainMessage(WHAT_REMOVE_INFO); message.arg1 = id; handler.sendMessage(message); } RemitSyncExecutor(@NonNull RemitAgent agent); RemitSyncExecutor(@NonNull RemitAgent agent, @Nullable Handler handler, @NonNull Set<Integer> freeToDBIdList); void postSyncInfoDelay(int id, long delayMillis); void postSync(int id); void postSync(List<Integer> idList); void postRemoveInfo(int id); void postRemoveFreeIds(List<Integer> idList); void postRemoveFreeId(int id); boolean handleMessage(Message msg); }### Answer: @Test public void postRemoveInfo() { executor.postRemoveInfo(1); verify(handler).sendMessage(messageCaptor.capture()); final Message message = messageCaptor.getValue(); assertThat(message.arg1).isEqualTo(1); assertThat(message.what).isEqualTo(WHAT_REMOVE_INFO); }
### Question: RemitSyncExecutor implements Handler.Callback { public void postRemoveFreeIds(List<Integer> idList) { final Message message = handler.obtainMessage(WHAT_REMOVE_FREE_BUNCH_ID); message.obj = idList; handler.sendMessage(message); } RemitSyncExecutor(@NonNull RemitAgent agent); RemitSyncExecutor(@NonNull RemitAgent agent, @Nullable Handler handler, @NonNull Set<Integer> freeToDBIdList); void postSyncInfoDelay(int id, long delayMillis); void postSync(int id); void postSync(List<Integer> idList); void postRemoveInfo(int id); void postRemoveFreeIds(List<Integer> idList); void postRemoveFreeId(int id); boolean handleMessage(Message msg); }### Answer: @Test public void postRemoveFreeIds() { executor.postRemoveFreeIds(idList); verify(handler).sendMessage(messageCaptor.capture()); final Message message = messageCaptor.getValue(); assertThat(message.obj).isEqualTo(idList); assertThat(message.what).isEqualTo(WHAT_REMOVE_FREE_BUNCH_ID); }
### Question: RemitSyncExecutor implements Handler.Callback { public void postRemoveFreeId(int id) { final Message message = handler.obtainMessage(WHAT_REMOVE_FREE_ID); message.arg1 = id; handler.sendMessage(message); } RemitSyncExecutor(@NonNull RemitAgent agent); RemitSyncExecutor(@NonNull RemitAgent agent, @Nullable Handler handler, @NonNull Set<Integer> freeToDBIdList); void postSyncInfoDelay(int id, long delayMillis); void postSync(int id); void postSync(List<Integer> idList); void postRemoveInfo(int id); void postRemoveFreeIds(List<Integer> idList); void postRemoveFreeId(int id); boolean handleMessage(Message msg); }### Answer: @Test public void postRemoveFreeId() { executor.postRemoveFreeId(1); verify(handler).sendMessage(messageCaptor.capture()); final Message message = messageCaptor.getValue(); assertThat(message.arg1).isEqualTo(1); assertThat(message.what).isEqualTo(WHAT_REMOVE_FREE_ID); }
### Question: RemitSyncExecutor implements Handler.Callback { void removePostWithId(int id) { handler.removeMessages(id); } RemitSyncExecutor(@NonNull RemitAgent agent); RemitSyncExecutor(@NonNull RemitAgent agent, @Nullable Handler handler, @NonNull Set<Integer> freeToDBIdList); void postSyncInfoDelay(int id, long delayMillis); void postSync(int id); void postSync(List<Integer> idList); void postRemoveInfo(int id); void postRemoveFreeIds(List<Integer> idList); void postRemoveFreeId(int id); boolean handleMessage(Message msg); }### Answer: @Test public void removePostWithId() { executor.removePostWithId(1); verify(handler).removeMessages(eq(1)); }
### Question: DownloadUrlConnection implements DownloadConnection, DownloadConnection.Connected { @Override public int getResponseCode() throws IOException { if (connection instanceof HttpURLConnection) { return ((HttpURLConnection) connection).getResponseCode(); } return DownloadConnection.NO_RESPONSE_CODE; } DownloadUrlConnection(URLConnection connection); DownloadUrlConnection(URLConnection connection, IRedirectHandler redirectHandler); DownloadUrlConnection(String originUrl, Configuration configuration); DownloadUrlConnection(URL url, Configuration configuration); DownloadUrlConnection( URL url, Configuration configuration, IRedirectHandler redirectHandler); DownloadUrlConnection(String originUrl); @Override void addHeader(String name, String value); @Override Connected execute(); @Override int getResponseCode(); @Override InputStream getInputStream(); @Override boolean setRequestMethod(@NonNull String method); @Override Map<String, List<String>> getResponseHeaderFields(); @Override String getResponseHeaderField(String name); @Override String getRedirectLocation(); @Override void release(); @Override Map<String, List<String>> getRequestProperties(); @Override String getRequestProperty(String key); }### Answer: @Test public void getResponseCode() throws Exception { assertThat(downloadUrlConnection.getResponseCode()) .isEqualTo(DownloadConnection.NO_RESPONSE_CODE); }
### Question: RemitSyncExecutor implements Handler.Callback { void removePostWithIds(int[] ids) { for (int id : ids) { handler.removeMessages(id); } } RemitSyncExecutor(@NonNull RemitAgent agent); RemitSyncExecutor(@NonNull RemitAgent agent, @Nullable Handler handler, @NonNull Set<Integer> freeToDBIdList); void postSyncInfoDelay(int id, long delayMillis); void postSync(int id); void postSync(List<Integer> idList); void postRemoveInfo(int id); void postRemoveFreeIds(List<Integer> idList); void postRemoveFreeId(int id); boolean handleMessage(Message msg); }### Answer: @Test public void removePostWithIds() { final int[] ids = new int[3]; ids[0] = 1; ids[1] = 2; ids[2] = 3; executor.removePostWithIds(ids); verify(handler).removeMessages(eq(1)); verify(handler).removeMessages(eq(2)); verify(handler).removeMessages(eq(3)); }
### Question: RemitStoreOnSQLite implements RemitSyncExecutor.RemitAgent, DownloadStore { @Override public void onTaskStart(int id) { onSQLiteWrapper.onTaskStart(id); remitHelper.onTaskStart(id); } RemitStoreOnSQLite(@NonNull BreakpointStoreOnSQLite sqlite); RemitStoreOnSQLite(@NonNull RemitSyncToDBHelper helper, @NonNull BreakpointStoreOnSQLite sqlite, @NonNull DownloadStore sqliteCache, @NonNull BreakpointSQLiteHelper sqLiteHelper); @Nullable @Override BreakpointInfo get(int id); @NonNull @Override BreakpointInfo createAndInsert(@NonNull DownloadTask task); @Override void onTaskStart(int id); @Override void onSyncToFilesystemSuccess(@NonNull BreakpointInfo info, int blockIndex, long increaseLength); @Override boolean update(@NonNull BreakpointInfo info); @Override void onTaskEnd(int id, @NonNull EndCause cause, @Nullable Exception exception); @Nullable @Override BreakpointInfo getAfterCompleted(int id); @Override boolean markFileDirty(int id); @Override boolean markFileClear(int id); @Override void remove(int id); @Override int findOrCreateId(@NonNull DownloadTask task); @Nullable @Override BreakpointInfo findAnotherInfoFromCompare(@NonNull DownloadTask task, @NonNull BreakpointInfo ignored); @Override boolean isOnlyMemoryCache(); @Override boolean isFileDirty(int id); @Nullable @Override String getResponseFilename(String url); @Override void syncCacheToDB(List<Integer> idList); @Override void syncCacheToDB(int id); @Override void removeInfo(int id); static void setRemitToDBDelayMillis(int delayMillis); }### Answer: @Test public void onTaskStart() { store.onTaskStart(1); verify(remitHelper).onTaskStart(eq(1)); }
### Question: DownloadUrlConnection implements DownloadConnection, DownloadConnection.Connected { @Override public InputStream getInputStream() throws IOException { return connection.getInputStream(); } DownloadUrlConnection(URLConnection connection); DownloadUrlConnection(URLConnection connection, IRedirectHandler redirectHandler); DownloadUrlConnection(String originUrl, Configuration configuration); DownloadUrlConnection(URL url, Configuration configuration); DownloadUrlConnection( URL url, Configuration configuration, IRedirectHandler redirectHandler); DownloadUrlConnection(String originUrl); @Override void addHeader(String name, String value); @Override Connected execute(); @Override int getResponseCode(); @Override InputStream getInputStream(); @Override boolean setRequestMethod(@NonNull String method); @Override Map<String, List<String>> getResponseHeaderFields(); @Override String getResponseHeaderField(String name); @Override String getRedirectLocation(); @Override void release(); @Override Map<String, List<String>> getRequestProperties(); @Override String getRequestProperty(String key); }### Answer: @Test public void getInputStream() throws Exception { when(urlConnection.getInputStream()).thenReturn(inputStream); assertThat(downloadUrlConnection.getInputStream()).isEqualTo(inputStream); }
### Question: RemitStoreOnSQLite implements RemitSyncExecutor.RemitAgent, DownloadStore { @Override public void remove(int id) { sqliteCache.remove(id); remitHelper.discard(id); } RemitStoreOnSQLite(@NonNull BreakpointStoreOnSQLite sqlite); RemitStoreOnSQLite(@NonNull RemitSyncToDBHelper helper, @NonNull BreakpointStoreOnSQLite sqlite, @NonNull DownloadStore sqliteCache, @NonNull BreakpointSQLiteHelper sqLiteHelper); @Nullable @Override BreakpointInfo get(int id); @NonNull @Override BreakpointInfo createAndInsert(@NonNull DownloadTask task); @Override void onTaskStart(int id); @Override void onSyncToFilesystemSuccess(@NonNull BreakpointInfo info, int blockIndex, long increaseLength); @Override boolean update(@NonNull BreakpointInfo info); @Override void onTaskEnd(int id, @NonNull EndCause cause, @Nullable Exception exception); @Nullable @Override BreakpointInfo getAfterCompleted(int id); @Override boolean markFileDirty(int id); @Override boolean markFileClear(int id); @Override void remove(int id); @Override int findOrCreateId(@NonNull DownloadTask task); @Nullable @Override BreakpointInfo findAnotherInfoFromCompare(@NonNull DownloadTask task, @NonNull BreakpointInfo ignored); @Override boolean isOnlyMemoryCache(); @Override boolean isFileDirty(int id); @Nullable @Override String getResponseFilename(String url); @Override void syncCacheToDB(List<Integer> idList); @Override void syncCacheToDB(int id); @Override void removeInfo(int id); static void setRemitToDBDelayMillis(int delayMillis); }### Answer: @Test public void remove() { store.remove(1); verify(onCache).remove(eq(1)); verify(remitHelper).discard(eq(1)); }
### Question: RemitStoreOnSQLite implements RemitSyncExecutor.RemitAgent, DownloadStore { @Override public void removeInfo(int id) { sqLiteHelper.removeInfo(id); } RemitStoreOnSQLite(@NonNull BreakpointStoreOnSQLite sqlite); RemitStoreOnSQLite(@NonNull RemitSyncToDBHelper helper, @NonNull BreakpointStoreOnSQLite sqlite, @NonNull DownloadStore sqliteCache, @NonNull BreakpointSQLiteHelper sqLiteHelper); @Nullable @Override BreakpointInfo get(int id); @NonNull @Override BreakpointInfo createAndInsert(@NonNull DownloadTask task); @Override void onTaskStart(int id); @Override void onSyncToFilesystemSuccess(@NonNull BreakpointInfo info, int blockIndex, long increaseLength); @Override boolean update(@NonNull BreakpointInfo info); @Override void onTaskEnd(int id, @NonNull EndCause cause, @Nullable Exception exception); @Nullable @Override BreakpointInfo getAfterCompleted(int id); @Override boolean markFileDirty(int id); @Override boolean markFileClear(int id); @Override void remove(int id); @Override int findOrCreateId(@NonNull DownloadTask task); @Nullable @Override BreakpointInfo findAnotherInfoFromCompare(@NonNull DownloadTask task, @NonNull BreakpointInfo ignored); @Override boolean isOnlyMemoryCache(); @Override boolean isFileDirty(int id); @Nullable @Override String getResponseFilename(String url); @Override void syncCacheToDB(List<Integer> idList); @Override void syncCacheToDB(int id); @Override void removeInfo(int id); static void setRemitToDBDelayMillis(int delayMillis); }### Answer: @Test public void removeInfo() { store.removeInfo(1); verify(helper).removeInfo(eq(1)); }
### Question: DownloadUrlConnection implements DownloadConnection, DownloadConnection.Connected { @Override public Map<String, List<String>> getResponseHeaderFields() { return connection.getHeaderFields(); } DownloadUrlConnection(URLConnection connection); DownloadUrlConnection(URLConnection connection, IRedirectHandler redirectHandler); DownloadUrlConnection(String originUrl, Configuration configuration); DownloadUrlConnection(URL url, Configuration configuration); DownloadUrlConnection( URL url, Configuration configuration, IRedirectHandler redirectHandler); DownloadUrlConnection(String originUrl); @Override void addHeader(String name, String value); @Override Connected execute(); @Override int getResponseCode(); @Override InputStream getInputStream(); @Override boolean setRequestMethod(@NonNull String method); @Override Map<String, List<String>> getResponseHeaderFields(); @Override String getResponseHeaderField(String name); @Override String getRedirectLocation(); @Override void release(); @Override Map<String, List<String>> getRequestProperties(); @Override String getRequestProperty(String key); }### Answer: @Test public void getResponseHeaderFields() throws Exception { when(urlConnection.getHeaderFields()).thenReturn(headerFields); assertThat(downloadUrlConnection.getResponseHeaderFields()).isEqualTo(headerFields); }
### Question: RemitStoreOnSQLite implements RemitSyncExecutor.RemitAgent, DownloadStore { @Nullable @Override public BreakpointInfo getAfterCompleted(int id) { return null; } RemitStoreOnSQLite(@NonNull BreakpointStoreOnSQLite sqlite); RemitStoreOnSQLite(@NonNull RemitSyncToDBHelper helper, @NonNull BreakpointStoreOnSQLite sqlite, @NonNull DownloadStore sqliteCache, @NonNull BreakpointSQLiteHelper sqLiteHelper); @Nullable @Override BreakpointInfo get(int id); @NonNull @Override BreakpointInfo createAndInsert(@NonNull DownloadTask task); @Override void onTaskStart(int id); @Override void onSyncToFilesystemSuccess(@NonNull BreakpointInfo info, int blockIndex, long increaseLength); @Override boolean update(@NonNull BreakpointInfo info); @Override void onTaskEnd(int id, @NonNull EndCause cause, @Nullable Exception exception); @Nullable @Override BreakpointInfo getAfterCompleted(int id); @Override boolean markFileDirty(int id); @Override boolean markFileClear(int id); @Override void remove(int id); @Override int findOrCreateId(@NonNull DownloadTask task); @Nullable @Override BreakpointInfo findAnotherInfoFromCompare(@NonNull DownloadTask task, @NonNull BreakpointInfo ignored); @Override boolean isOnlyMemoryCache(); @Override boolean isFileDirty(int id); @Nullable @Override String getResponseFilename(String url); @Override void syncCacheToDB(List<Integer> idList); @Override void syncCacheToDB(int id); @Override void removeInfo(int id); static void setRemitToDBDelayMillis(int delayMillis); }### Answer: @Test public void getAfterCompleted() { assertThat(store.getAfterCompleted(1)).isNull(); }
### Question: RemitStoreOnSQLite implements RemitSyncExecutor.RemitAgent, DownloadStore { @Override public boolean markFileDirty(int id) { return onSQLiteWrapper.markFileDirty(id); } RemitStoreOnSQLite(@NonNull BreakpointStoreOnSQLite sqlite); RemitStoreOnSQLite(@NonNull RemitSyncToDBHelper helper, @NonNull BreakpointStoreOnSQLite sqlite, @NonNull DownloadStore sqliteCache, @NonNull BreakpointSQLiteHelper sqLiteHelper); @Nullable @Override BreakpointInfo get(int id); @NonNull @Override BreakpointInfo createAndInsert(@NonNull DownloadTask task); @Override void onTaskStart(int id); @Override void onSyncToFilesystemSuccess(@NonNull BreakpointInfo info, int blockIndex, long increaseLength); @Override boolean update(@NonNull BreakpointInfo info); @Override void onTaskEnd(int id, @NonNull EndCause cause, @Nullable Exception exception); @Nullable @Override BreakpointInfo getAfterCompleted(int id); @Override boolean markFileDirty(int id); @Override boolean markFileClear(int id); @Override void remove(int id); @Override int findOrCreateId(@NonNull DownloadTask task); @Nullable @Override BreakpointInfo findAnotherInfoFromCompare(@NonNull DownloadTask task, @NonNull BreakpointInfo ignored); @Override boolean isOnlyMemoryCache(); @Override boolean isFileDirty(int id); @Nullable @Override String getResponseFilename(String url); @Override void syncCacheToDB(List<Integer> idList); @Override void syncCacheToDB(int id); @Override void removeInfo(int id); static void setRemitToDBDelayMillis(int delayMillis); }### Answer: @Test public void markFileDirty() { doReturn(true).when(storeOnSQLite).markFileDirty(1); assertThat(store.markFileDirty(1)).isTrue(); doReturn(false).when(storeOnSQLite).markFileDirty(1); assertThat(store.markFileDirty(1)).isFalse(); }
### Question: RemitStoreOnSQLite implements RemitSyncExecutor.RemitAgent, DownloadStore { @Override public boolean markFileClear(int id) { return onSQLiteWrapper.markFileClear(id); } RemitStoreOnSQLite(@NonNull BreakpointStoreOnSQLite sqlite); RemitStoreOnSQLite(@NonNull RemitSyncToDBHelper helper, @NonNull BreakpointStoreOnSQLite sqlite, @NonNull DownloadStore sqliteCache, @NonNull BreakpointSQLiteHelper sqLiteHelper); @Nullable @Override BreakpointInfo get(int id); @NonNull @Override BreakpointInfo createAndInsert(@NonNull DownloadTask task); @Override void onTaskStart(int id); @Override void onSyncToFilesystemSuccess(@NonNull BreakpointInfo info, int blockIndex, long increaseLength); @Override boolean update(@NonNull BreakpointInfo info); @Override void onTaskEnd(int id, @NonNull EndCause cause, @Nullable Exception exception); @Nullable @Override BreakpointInfo getAfterCompleted(int id); @Override boolean markFileDirty(int id); @Override boolean markFileClear(int id); @Override void remove(int id); @Override int findOrCreateId(@NonNull DownloadTask task); @Nullable @Override BreakpointInfo findAnotherInfoFromCompare(@NonNull DownloadTask task, @NonNull BreakpointInfo ignored); @Override boolean isOnlyMemoryCache(); @Override boolean isFileDirty(int id); @Nullable @Override String getResponseFilename(String url); @Override void syncCacheToDB(List<Integer> idList); @Override void syncCacheToDB(int id); @Override void removeInfo(int id); static void setRemitToDBDelayMillis(int delayMillis); }### Answer: @Test public void markFileClear() { doReturn(true).when(storeOnSQLite).markFileClear(1); assertThat(store.markFileClear(1)).isTrue(); doReturn(false).when(storeOnSQLite).markFileClear(1); assertThat(store.markFileClear(1)).isFalse(); }
### Question: RemitStoreOnSQLite implements RemitSyncExecutor.RemitAgent, DownloadStore { @Override public boolean isFileDirty(int id) { return onSQLiteWrapper.isFileDirty(id); } RemitStoreOnSQLite(@NonNull BreakpointStoreOnSQLite sqlite); RemitStoreOnSQLite(@NonNull RemitSyncToDBHelper helper, @NonNull BreakpointStoreOnSQLite sqlite, @NonNull DownloadStore sqliteCache, @NonNull BreakpointSQLiteHelper sqLiteHelper); @Nullable @Override BreakpointInfo get(int id); @NonNull @Override BreakpointInfo createAndInsert(@NonNull DownloadTask task); @Override void onTaskStart(int id); @Override void onSyncToFilesystemSuccess(@NonNull BreakpointInfo info, int blockIndex, long increaseLength); @Override boolean update(@NonNull BreakpointInfo info); @Override void onTaskEnd(int id, @NonNull EndCause cause, @Nullable Exception exception); @Nullable @Override BreakpointInfo getAfterCompleted(int id); @Override boolean markFileDirty(int id); @Override boolean markFileClear(int id); @Override void remove(int id); @Override int findOrCreateId(@NonNull DownloadTask task); @Nullable @Override BreakpointInfo findAnotherInfoFromCompare(@NonNull DownloadTask task, @NonNull BreakpointInfo ignored); @Override boolean isOnlyMemoryCache(); @Override boolean isFileDirty(int id); @Nullable @Override String getResponseFilename(String url); @Override void syncCacheToDB(List<Integer> idList); @Override void syncCacheToDB(int id); @Override void removeInfo(int id); static void setRemitToDBDelayMillis(int delayMillis); }### Answer: @Test public void isFileDirty() { doReturn(true).when(storeOnSQLite).isFileDirty(1); assertThat(store.isFileDirty(1)).isTrue(); doReturn(false).when(storeOnSQLite).isFileDirty(1); assertThat(store.isFileDirty(1)).isFalse(); }
### Question: RemitSyncToDBHelper { void shutdown() { this.executor.shutdown(); } RemitSyncToDBHelper(@NonNull final RemitSyncExecutor.RemitAgent agent); RemitSyncToDBHelper(@NonNull final RemitSyncExecutor executor); }### Answer: @Test public void shutdown() { helper.shutdown(); verify(executor).shutdown(); }
### Question: RemitSyncToDBHelper { boolean isNotFreeToDatabase(int id) { return !executor.isFreeToDatabase(id); } RemitSyncToDBHelper(@NonNull final RemitSyncExecutor.RemitAgent agent); RemitSyncToDBHelper(@NonNull final RemitSyncExecutor executor); }### Answer: @Test public void isNotFreeToDatabase() { when(executor.isFreeToDatabase(1)).thenReturn(true); assertThat(helper.isNotFreeToDatabase(1)).isFalse(); when(executor.isFreeToDatabase(1)).thenReturn(false); assertThat(helper.isNotFreeToDatabase(1)).isTrue(); }
### Question: RemitSyncToDBHelper { void onTaskStart(int id) { executor.removePostWithId(id); executor.postSyncInfoDelay(id, delayMillis); } RemitSyncToDBHelper(@NonNull final RemitSyncExecutor.RemitAgent agent); RemitSyncToDBHelper(@NonNull final RemitSyncExecutor executor); }### Answer: @Test public void onTaskStart() { helper.onTaskStart(1); verify(executor).removePostWithId(eq(1)); verify(executor).postSyncInfoDelay(eq(1), eq(helper.delayMillis)); }
### Question: RemitSyncToDBHelper { void endAndEnsureToDB(int id) { executor.removePostWithId(id); try { if (executor.isFreeToDatabase(id)) return; executor.postSync(id); } finally { executor.postRemoveFreeId(id); } } RemitSyncToDBHelper(@NonNull final RemitSyncExecutor.RemitAgent agent); RemitSyncToDBHelper(@NonNull final RemitSyncExecutor executor); }### Answer: @Test public void endAndEnsureToDB() { when(executor.isFreeToDatabase(1)).thenReturn(true); helper.endAndEnsureToDB(1); verify(executor).removePostWithId(eq(1)); verify(executor).postRemoveFreeId(eq(1)); verify(executor, never()).postSync(eq(1)); when(executor.isFreeToDatabase(2)).thenReturn(false); helper.endAndEnsureToDB(2); verify(executor).postSync(eq(2)); verify(executor).postRemoveFreeId(eq(2)); }
### Question: RemitSyncToDBHelper { void discard(int id) { executor.removePostWithId(id); executor.postRemoveInfo(id); } RemitSyncToDBHelper(@NonNull final RemitSyncExecutor.RemitAgent agent); RemitSyncToDBHelper(@NonNull final RemitSyncExecutor executor); }### Answer: @Test public void discard() { helper.discard(1); verify(executor).removePostWithId(eq(1)); verify(executor).postRemoveInfo(eq(1)); }
### Question: DownloadUrlConnection implements DownloadConnection, DownloadConnection.Connected { @Override public String getResponseHeaderField(String name) { return connection.getHeaderField(name); } DownloadUrlConnection(URLConnection connection); DownloadUrlConnection(URLConnection connection, IRedirectHandler redirectHandler); DownloadUrlConnection(String originUrl, Configuration configuration); DownloadUrlConnection(URL url, Configuration configuration); DownloadUrlConnection( URL url, Configuration configuration, IRedirectHandler redirectHandler); DownloadUrlConnection(String originUrl); @Override void addHeader(String name, String value); @Override Connected execute(); @Override int getResponseCode(); @Override InputStream getInputStream(); @Override boolean setRequestMethod(@NonNull String method); @Override Map<String, List<String>> getResponseHeaderFields(); @Override String getResponseHeaderField(String name); @Override String getRedirectLocation(); @Override void release(); @Override Map<String, List<String>> getRequestProperties(); @Override String getRequestProperty(String key); }### Answer: @Test public void getResponseHeaderField() throws Exception { when(urlConnection.getHeaderField("key1")).thenReturn("value1"); assertThat(downloadUrlConnection.getResponseHeaderField("key1")).isEqualTo("value1"); }
### Question: DownloadUrlConnection implements DownloadConnection, DownloadConnection.Connected { @Override public void release() { try { final InputStream inputStream = connection.getInputStream(); if (inputStream != null) inputStream.close(); } catch (IOException ignored) { } } DownloadUrlConnection(URLConnection connection); DownloadUrlConnection(URLConnection connection, IRedirectHandler redirectHandler); DownloadUrlConnection(String originUrl, Configuration configuration); DownloadUrlConnection(URL url, Configuration configuration); DownloadUrlConnection( URL url, Configuration configuration, IRedirectHandler redirectHandler); DownloadUrlConnection(String originUrl); @Override void addHeader(String name, String value); @Override Connected execute(); @Override int getResponseCode(); @Override InputStream getInputStream(); @Override boolean setRequestMethod(@NonNull String method); @Override Map<String, List<String>> getResponseHeaderFields(); @Override String getResponseHeaderField(String name); @Override String getRedirectLocation(); @Override void release(); @Override Map<String, List<String>> getRequestProperties(); @Override String getRequestProperty(String key); }### Answer: @Test public void release() throws Exception { when(urlConnection.getInputStream()).thenReturn(inputStream); downloadUrlConnection.release(); verify(inputStream).close(); }
### Question: DownloadUrlConnection implements DownloadConnection, DownloadConnection.Connected { @Override public Map<String, List<String>> getRequestProperties() { return connection.getRequestProperties(); } DownloadUrlConnection(URLConnection connection); DownloadUrlConnection(URLConnection connection, IRedirectHandler redirectHandler); DownloadUrlConnection(String originUrl, Configuration configuration); DownloadUrlConnection(URL url, Configuration configuration); DownloadUrlConnection( URL url, Configuration configuration, IRedirectHandler redirectHandler); DownloadUrlConnection(String originUrl); @Override void addHeader(String name, String value); @Override Connected execute(); @Override int getResponseCode(); @Override InputStream getInputStream(); @Override boolean setRequestMethod(@NonNull String method); @Override Map<String, List<String>> getResponseHeaderFields(); @Override String getResponseHeaderField(String name); @Override String getRedirectLocation(); @Override void release(); @Override Map<String, List<String>> getRequestProperties(); @Override String getRequestProperty(String key); }### Answer: @Test public void getRequestProperties() throws Exception { when(urlConnection.getRequestProperties()).thenReturn(headerFields); assertThat(downloadUrlConnection.getRequestProperties()).isEqualTo(headerFields); }
### Question: DownloadUrlConnection implements DownloadConnection, DownloadConnection.Connected { @Override public String getRequestProperty(String key) { return connection.getRequestProperty(key); } DownloadUrlConnection(URLConnection connection); DownloadUrlConnection(URLConnection connection, IRedirectHandler redirectHandler); DownloadUrlConnection(String originUrl, Configuration configuration); DownloadUrlConnection(URL url, Configuration configuration); DownloadUrlConnection( URL url, Configuration configuration, IRedirectHandler redirectHandler); DownloadUrlConnection(String originUrl); @Override void addHeader(String name, String value); @Override Connected execute(); @Override int getResponseCode(); @Override InputStream getInputStream(); @Override boolean setRequestMethod(@NonNull String method); @Override Map<String, List<String>> getResponseHeaderFields(); @Override String getResponseHeaderField(String name); @Override String getRedirectLocation(); @Override void release(); @Override Map<String, List<String>> getRequestProperties(); @Override String getRequestProperty(String key); }### Answer: @Test public void getRequestProperty() throws Exception { when(urlConnection.getRequestProperty("key1")).thenReturn("value1"); assertThat(downloadUrlConnection.getRequestProperty("key1")).isEqualTo("value1"); }
### Question: DownloadUrlConnection implements DownloadConnection, DownloadConnection.Connected { @Override public boolean setRequestMethod(@NonNull String method) throws ProtocolException { if (connection instanceof HttpURLConnection) { ((HttpURLConnection) connection).setRequestMethod(method); return true; } return false; } DownloadUrlConnection(URLConnection connection); DownloadUrlConnection(URLConnection connection, IRedirectHandler redirectHandler); DownloadUrlConnection(String originUrl, Configuration configuration); DownloadUrlConnection(URL url, Configuration configuration); DownloadUrlConnection( URL url, Configuration configuration, IRedirectHandler redirectHandler); DownloadUrlConnection(String originUrl); @Override void addHeader(String name, String value); @Override Connected execute(); @Override int getResponseCode(); @Override InputStream getInputStream(); @Override boolean setRequestMethod(@NonNull String method); @Override Map<String, List<String>> getResponseHeaderFields(); @Override String getResponseHeaderField(String name); @Override String getRedirectLocation(); @Override void release(); @Override Map<String, List<String>> getRequestProperties(); @Override String getRequestProperty(String key); }### Answer: @Test public void setRequestMethod() throws ProtocolException { final HttpURLConnection httpURLConnection = mock(HttpURLConnection.class); final DownloadUrlConnection connection = new DownloadUrlConnection(httpURLConnection); assertThat(connection.setRequestMethod("HEAD")).isTrue(); verify(httpURLConnection).setRequestMethod(eq("HEAD")); assertThat(downloadUrlConnection.setRequestMethod("GET")).isFalse(); }
### Question: DownloadUrlConnection implements DownloadConnection, DownloadConnection.Connected { @Override public String getRedirectLocation() { return redirectHandler.getRedirectLocation(); } DownloadUrlConnection(URLConnection connection); DownloadUrlConnection(URLConnection connection, IRedirectHandler redirectHandler); DownloadUrlConnection(String originUrl, Configuration configuration); DownloadUrlConnection(URL url, Configuration configuration); DownloadUrlConnection( URL url, Configuration configuration, IRedirectHandler redirectHandler); DownloadUrlConnection(String originUrl); @Override void addHeader(String name, String value); @Override Connected execute(); @Override int getResponseCode(); @Override InputStream getInputStream(); @Override boolean setRequestMethod(@NonNull String method); @Override Map<String, List<String>> getResponseHeaderFields(); @Override String getResponseHeaderField(String name); @Override String getRedirectLocation(); @Override void release(); @Override Map<String, List<String>> getRequestProperties(); @Override String getRequestProperty(String key); }### Answer: @Test public void getRedirectLocation() { final String redirectLocation = "http: redirectHandler.redirectLocation = redirectLocation; assertThat(downloadUrlConnection.getRedirectLocation()).isEqualTo(redirectLocation); }
### Question: DownloadSerialQueue extends DownloadListener2 implements Runnable { public synchronized void resume() { if (!paused) { Util.w(TAG, "require resume this queue(remain " + taskList.size() + "), but it is" + " still running"); return; } paused = false; if (!taskList.isEmpty() && !looping) { looping = true; startNewLooper(); } } DownloadSerialQueue(); DownloadSerialQueue(DownloadListener listener, ArrayList<DownloadTask> taskList); DownloadSerialQueue(DownloadListener listener); void setListener(DownloadListener listener); synchronized void enqueue(DownloadTask task); synchronized void pause(); synchronized void resume(); int getWorkingTaskId(); int getWaitingTaskCount(); synchronized DownloadTask[] shutdown(); @Override void run(); @Override void taskStart(@NonNull DownloadTask task); @Override synchronized void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause); }### Answer: @Test public void resume() { serialQueue.paused = true; serialQueue.looping = false; doNothing().when(serialQueue).startNewLooper(); taskList.add(mock(DownloadTask.class)); serialQueue.resume(); verify(serialQueue).startNewLooper(); assertThat(serialQueue.paused).isFalse(); assertThat(serialQueue.looping).isTrue(); }
### Question: DownloadSerialQueue extends DownloadListener2 implements Runnable { public int getWorkingTaskId() { return runningTask != null ? runningTask.getId() : ID_INVALID; } DownloadSerialQueue(); DownloadSerialQueue(DownloadListener listener, ArrayList<DownloadTask> taskList); DownloadSerialQueue(DownloadListener listener); void setListener(DownloadListener listener); synchronized void enqueue(DownloadTask task); synchronized void pause(); synchronized void resume(); int getWorkingTaskId(); int getWaitingTaskCount(); synchronized DownloadTask[] shutdown(); @Override void run(); @Override void taskStart(@NonNull DownloadTask task); @Override synchronized void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause); }### Answer: @Test public void getWorkingTaskId() { assertThat(serialQueue.getWorkingTaskId()).isEqualTo(DownloadSerialQueue.ID_INVALID); when(task1.getId()).thenReturn(1); serialQueue.runningTask = task1; assertThat(serialQueue.getWorkingTaskId()).isEqualTo(1); }
### Question: DownloadSerialQueue extends DownloadListener2 implements Runnable { public int getWaitingTaskCount() { return taskList.size(); } DownloadSerialQueue(); DownloadSerialQueue(DownloadListener listener, ArrayList<DownloadTask> taskList); DownloadSerialQueue(DownloadListener listener); void setListener(DownloadListener listener); synchronized void enqueue(DownloadTask task); synchronized void pause(); synchronized void resume(); int getWorkingTaskId(); int getWaitingTaskCount(); synchronized DownloadTask[] shutdown(); @Override void run(); @Override void taskStart(@NonNull DownloadTask task); @Override synchronized void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause); }### Answer: @Test public void getWaitingTaskCount() { assertThat(serialQueue.getWaitingTaskCount()).isZero(); taskList.add(task1); assertThat(serialQueue.getWaitingTaskCount()).isEqualTo(1); }
### Question: BreakpointInterceptor implements Interceptor.Connect, Interceptor.Fetch { @IntRange(from = -1) static long getRangeRightFromContentRange(@NonNull String contentRange) { Matcher m = CONTENT_RANGE_RIGHT_VALUE.matcher(contentRange); if (m.find()) { return Long.parseLong(m.group(1)); } return -1; } @NonNull @Override DownloadConnection.Connected interceptConnect(DownloadChain chain); @Override long interceptFetch(DownloadChain chain); }### Answer: @Test public void getRangeRightFromContentRange() { assertThat(BreakpointInterceptor.getRangeRightFromContentRange("bytes 1-111/222")) .isEqualTo(111L); assertThat(BreakpointInterceptor.getRangeRightFromContentRange("bytes 1 -111/222")) .isEqualTo(111L); assertThat(BreakpointInterceptor.getRangeRightFromContentRange("bytes 1 - 111/222")) .isEqualTo(111L); assertThat(BreakpointInterceptor.getRangeRightFromContentRange("bytes 1 - 111 /222")) .isEqualTo(111L); assertThat(BreakpointInterceptor.getRangeRightFromContentRange("bytes 1 - 111 / 222")) .isEqualTo(111L); }
### Question: BreakpointInterceptor implements Interceptor.Connect, Interceptor.Fetch { @IntRange(from = -1) long getExactContentLengthRangeFrom0(@NonNull DownloadConnection.Connected connected) { final String contentRangeField = connected.getResponseHeaderField(CONTENT_RANGE); long contentLength = -1; if (!Util.isEmpty(contentRangeField)) { final long rightRange = getRangeRightFromContentRange(contentRangeField); if (rightRange > 0) contentLength = rightRange + 1; } if (contentLength < 0) { final String contentLengthField = connected.getResponseHeaderField(CONTENT_LENGTH); if (!Util.isEmpty(contentLengthField)) { contentLength = Long.parseLong(contentLengthField); } } return contentLength; } @NonNull @Override DownloadConnection.Connected interceptConnect(DownloadChain chain); @Override long interceptFetch(DownloadChain chain); }### Answer: @Test public void getExactContentLength_contentRange() { when(connected.getResponseHeaderField(CONTENT_RANGE)).thenReturn("bytes 0-111/222"); assertThat(interceptor.getExactContentLengthRangeFrom0(connected)).isEqualTo(112L); } @Test public void getExactContentLength_contentLength() { when(connected.getResponseHeaderField(CONTENT_LENGTH)).thenReturn("123"); assertThat(interceptor.getExactContentLengthRangeFrom0(connected)).isEqualTo(123L); }
### Question: FetchDataInterceptor implements Interceptor.Fetch { @Override public long interceptFetch(DownloadChain chain) throws IOException { if (chain.getCache().isInterrupt()) { throw InterruptException.SIGNAL; } OkDownload.with().downloadStrategy().inspectNetworkOnWifi(chain.getTask()); int fetchLength = inputStream.read(readBuffer); if (fetchLength == -1) { return fetchLength; } outputStream.write(blockIndex, readBuffer, fetchLength); chain.increaseCallbackBytes(fetchLength); if (this.dispatcher.isFetchProcessMoment(task)) { chain.flushNoCallbackIncreaseBytes(); } return fetchLength; } FetchDataInterceptor(int blockIndex, @NonNull InputStream inputStream, @NonNull MultiPointOutputStream outputStream, DownloadTask task); @Override long interceptFetch(DownloadChain chain); }### Answer: @Test public void interceptFetch() throws IOException { final CallbackDispatcher dispatcher = OkDownload.with().callbackDispatcher(); doReturn(10).when(inputStream).read(any(byte[].class)); doReturn(true).when(dispatcher).isFetchProcessMoment(task); interceptor.interceptFetch(chain); final DownloadStrategy downloadStrategy = OkDownload.with().downloadStrategy(); verify(downloadStrategy).inspectNetworkOnWifi(eq(task)); verify(chain).increaseCallbackBytes(10L); verify(chain).flushNoCallbackIncreaseBytes(); verify(outputStream).write(eq(0), any(byte[].class), eq(10)); }
### Question: CallServerInterceptor implements Interceptor.Connect { @NonNull @Override public DownloadConnection.Connected interceptConnect(DownloadChain chain) throws IOException { OkDownload.with().downloadStrategy().inspectNetworkOnWifi(chain.getTask()); OkDownload.with().downloadStrategy().inspectNetworkAvailable(); return chain.getConnectionOrCreate().execute(); } @NonNull @Override DownloadConnection.Connected interceptConnect(DownloadChain chain); }### Answer: @Test public void interceptConnect() throws Exception { serverInterceptor.interceptConnect(chain); final DownloadStrategy downloadStrategy = OkDownload.with().downloadStrategy(); verify(downloadStrategy).inspectNetworkOnWifi(eq(task)); verify(downloadStrategy).inspectNetworkAvailable(); }
### Question: DownloadSerialQueue extends DownloadListener2 implements Runnable { public synchronized DownloadTask[] shutdown() { shutedDown = true; if (runningTask != null) runningTask.cancel(); final DownloadTask[] tasks = new DownloadTask[taskList.size()]; taskList.toArray(tasks); taskList.clear(); return tasks; } DownloadSerialQueue(); DownloadSerialQueue(DownloadListener listener, ArrayList<DownloadTask> taskList); DownloadSerialQueue(DownloadListener listener); void setListener(DownloadListener listener); synchronized void enqueue(DownloadTask task); synchronized void pause(); synchronized void resume(); int getWorkingTaskId(); int getWaitingTaskCount(); synchronized DownloadTask[] shutdown(); @Override void run(); @Override void taskStart(@NonNull DownloadTask task); @Override synchronized void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause); }### Answer: @Test public void shutdown() { taskList.add(task1); serialQueue.runningTask = task2; final DownloadTask[] tasks = serialQueue.shutdown(); verify(task2).cancel(); assertThat(serialQueue.shutedDown).isTrue(); assertThat(tasks).containsExactly(task1); }
### Question: RetryInterceptor implements Interceptor.Connect, Interceptor.Fetch { @Override public long interceptFetch(DownloadChain chain) throws IOException { try { return chain.processFetch(); } catch (IOException e) { chain.getCache().catchException(e); throw e; } } @NonNull @Override DownloadConnection.Connected interceptConnect(DownloadChain chain); @Override long interceptFetch(DownloadChain chain); }### Answer: @Test public void interceptFetch_failedRelease() throws IOException { final MultiPointOutputStream outputStream = mock(MultiPointOutputStream.class); when(chain.getOutputStream()).thenReturn(outputStream); doThrow(IOException.class).when(chain).processFetch(); thrown.expect(IOException.class); interceptor.interceptFetch(chain); verify(cache).catchException(any(IOException.class)); verify(outputStream).catchBlockConnectException(anyInt()); }
### Question: DownloadSerialQueue extends DownloadListener2 implements Runnable { @Override public void run() { while (!shutedDown) { final DownloadTask nextTask; synchronized (this) { if (taskList.isEmpty() || paused) { runningTask = null; looping = false; break; } nextTask = taskList.remove(0); } nextTask.execute(listenerBunch); } } DownloadSerialQueue(); DownloadSerialQueue(DownloadListener listener, ArrayList<DownloadTask> taskList); DownloadSerialQueue(DownloadListener listener); void setListener(DownloadListener listener); synchronized void enqueue(DownloadTask task); synchronized void pause(); synchronized void resume(); int getWorkingTaskId(); int getWaitingTaskCount(); synchronized DownloadTask[] shutdown(); @Override void run(); @Override void taskStart(@NonNull DownloadTask task); @Override synchronized void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause); }### Answer: @Test public void run() { serialQueue.looping = true; serialQueue.run(); assertThat(serialQueue.looping).isFalse(); serialQueue.looping = true; taskList.add(task1); taskList.add(task2); serialQueue.paused = true; serialQueue.run(); verify(task1, never()).execute(any(DownloadListener.class)); verify(task2, never()).execute(any(DownloadListener.class)); verify(taskList, never()).remove(anyInt()); assertThat(serialQueue.looping).isFalse(); serialQueue.looping = true; serialQueue.paused = false; serialQueue.run(); verify(task1).execute(any(DownloadListener.class)); verify(task2).execute(any(DownloadListener.class)); verify(taskList, times(2)).remove(eq(0)); assertThat(serialQueue.looping).isFalse(); }
### Question: BreakpointStoreOnCache implements DownloadStore { @Nullable @Override public BreakpointInfo getAfterCompleted(int id) { return null; } BreakpointStoreOnCache(); BreakpointStoreOnCache(SparseArray<BreakpointInfo> storedInfos, List<Integer> fileDirtyList, HashMap<String, String> responseFilenameMap, SparseArray<IdentifiedTask> unStoredTasks, List<Integer> sortedOccupiedIds, KeyToIdMap keyToIdMap); BreakpointStoreOnCache(SparseArray<BreakpointInfo> storedInfos, List<Integer> fileDirtyList, HashMap<String, String> responseFilenameMap); @Override BreakpointInfo get(int id); @NonNull @Override BreakpointInfo createAndInsert(@NonNull DownloadTask task); @Override void onTaskStart(int id); @Override void onSyncToFilesystemSuccess(@NonNull BreakpointInfo info, int blockIndex, long increaseLength); @Override boolean update(@NonNull BreakpointInfo breakpointInfo); @Override void onTaskEnd(int id, @NonNull EndCause cause, @Nullable Exception exception); @Nullable @Override BreakpointInfo getAfterCompleted(int id); @Override boolean markFileDirty(int id); @Override boolean markFileClear(int id); @Override synchronized void remove(int id); @Override synchronized int findOrCreateId(@NonNull DownloadTask task); @Override BreakpointInfo findAnotherInfoFromCompare(@NonNull DownloadTask task, @NonNull BreakpointInfo ignored); @Override boolean isOnlyMemoryCache(); @Override boolean isFileDirty(int id); @Nullable @Override String getResponseFilename(String url); static final int FIRST_ID; }### Answer: @Test public void getAfterCompleted() { assertThat(storeOnCache.getAfterCompleted(1)).isNull(); }
### Question: KeyToIdMap { @Nullable public Integer get(@NonNull DownloadTask task) { final Integer candidate = keyToIdMap.get(generateKey(task)); if (candidate != null) return candidate; return null; } KeyToIdMap(); KeyToIdMap(@NonNull HashMap<String, Integer> keyToIdMap, @NonNull SparseArray<String> idToKeyMap); @Nullable Integer get(@NonNull DownloadTask task); void remove(int id); void add(@NonNull DownloadTask task, int id); }### Answer: @Test public void get() { assertThat(map.get(task)).isNull(); keyToIdMap.put(map.generateKey(task), 1); assertThat(map.get(task)).isEqualTo(1); }
### Question: DownloadSerialQueue extends DownloadListener2 implements Runnable { @Override public void taskStart(@NonNull DownloadTask task) { this.runningTask = task; } DownloadSerialQueue(); DownloadSerialQueue(DownloadListener listener, ArrayList<DownloadTask> taskList); DownloadSerialQueue(DownloadListener listener); void setListener(DownloadListener listener); synchronized void enqueue(DownloadTask task); synchronized void pause(); synchronized void resume(); int getWorkingTaskId(); int getWaitingTaskCount(); synchronized DownloadTask[] shutdown(); @Override void run(); @Override void taskStart(@NonNull DownloadTask task); @Override synchronized void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause); }### Answer: @Test public void taskStart() { serialQueue.taskStart(task1); assertThat(serialQueue.runningTask).isEqualTo(task1); }
### Question: GsonProvider implements MessageBodyReader<T>, MessageBodyWriter<T> { @Override public long getSize( T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType ) { return -1; } GsonProvider(); @Override long getSize( T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType ); @Override boolean isWriteable( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType ); @Override void writeTo( T object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream ); @Override boolean isReadable( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType ); @Override T readFrom( Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream ); }### Answer: @Test public void testGetSize() { GsonProvider<TestObject> testObjectProvider = new GsonProvider<TestObject>(); long size = testObjectProvider.getSize( mock( TestObject.class ), null, null, null, null ); assertThat( size ).isEqualTo( -1 ); }
### Question: GsonProvider implements MessageBodyReader<T>, MessageBodyWriter<T> { @Override public boolean isWriteable( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType ) { return true; } GsonProvider(); @Override long getSize( T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType ); @Override boolean isWriteable( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType ); @Override void writeTo( T object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream ); @Override boolean isReadable( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType ); @Override T readFrom( Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream ); }### Answer: @Test public void testIsWritableWithTestObject() { GsonProvider<TestObject> testObjectProvider = new GsonProvider<TestObject>(); boolean writeable = testObjectProvider.isWriteable( TestObject.class, null, null, null ); assertTrue( writeable ); }
### Question: GsonProvider implements MessageBodyReader<T>, MessageBodyWriter<T> { @Override public boolean isReadable( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType ) { return true; } GsonProvider(); @Override long getSize( T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType ); @Override boolean isWriteable( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType ); @Override void writeTo( T object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream ); @Override boolean isReadable( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType ); @Override T readFrom( Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream ); }### Answer: @Test public void testIsReadableWithTestObject() { GsonProvider<TestObject> testObjectProvider = new GsonProvider<TestObject>(); boolean readable = testObjectProvider.isReadable( TestObject.class, null, null, null ); assertTrue( readable ); }
### Question: ColorService { @GET @Path("/{id}") public Response getColor(@PathParam("id") String id) { Response response = null; UUID uuid = null; ColoredLamp lamp = null; logRequest("", id); response = ElisResponseBuilder.buildBadRequestResponse(); try { uuid = UUID.fromString(id); } catch (Exception e) { log(LogService.LOG_WARNING, "Bad UUID"); } if (userService != null && storage != null && uuid != null) { if (storage.objectExists(uuid)) { try { lamp = (ColoredLamp) storage.readData(uuid); ColorBean bean = new ColorBean(); bean.device = uuid; bean.color = toJsonHex(lamp.getColor()); response = ElisResponseBuilder.buildOKResponse(bean); } catch (StorageException | ClassCastException e) { log(LogService.LOG_INFO, "Tried to perform a getPowerstate on a non-power switch object: " + uuid); response = ElisResponseBuilder.buildMethodNotAllowedResponse(); } catch (ActuatorFailedException e) { log(LogService.LOG_WARNING, "Couldn't read device status from: " + uuid); response = ElisResponseBuilder.buildServiceUnavailableResponse(); } } else { response = ElisResponseBuilder.buildNotFoundResponse(); } } return response; } ColorService(); ColorService(UserService us, Storage storage, EndpointUtils utils); @GET @Path("/{id}") Response getColor(@PathParam("id") String id); @PUT @Path("/{id}") Response setColor(@PathParam("id") String id, ColorBean bean); }### Answer: @Test public void testGetColor() { final String deviceResponse = target("/color/" + DID + "/").request().get(String.class); EnvelopeBean envelope = gson.fromJson(deviceResponse, EnvelopeBean.class); ColorBean bean = gson.fromJson(gson.toJson(envelope.response), ColorBean.class); assertEquals(DID, bean.device); assertEquals(COLOR_IN_HEX, bean.color); }
### Question: ClassUtils { public static String classNameToResource(String className) { return classNameToInternalClassName(className) + ".class"; } private ClassUtils(); static String classNameToInternalClassName(String className); static String classNameToResource(String className); @SuppressWarnings("unchecked") static Class<T> getExistingClass(ClassLoader classLoader, String className); @SuppressWarnings("deprecation") static T newInstance(Class<T> clazz); }### Answer: @Test public void testClassNameToResource() { String actual = ClassUtils.classNameToResource(className); assertEquals("org/objenesis/EmptyClassBis.class", actual); }
### Question: ClassUtils { @SuppressWarnings("unchecked") public static <T> Class<T> getExistingClass(ClassLoader classLoader, String className) { try { return (Class<T>) Class.forName(className, true, classLoader); } catch (ClassNotFoundException e) { return null; } } private ClassUtils(); static String classNameToInternalClassName(String className); static String classNameToResource(String className); @SuppressWarnings("unchecked") static Class<T> getExistingClass(ClassLoader classLoader, String className); @SuppressWarnings("deprecation") static T newInstance(Class<T> clazz); }### Answer: @Test public void testGetExistingClass_existing() { Class<?> actual = ClassUtils.getExistingClass(getClass().getClassLoader(), getClass().getName()); assertSame(actual, getClass()); } @Test public void testGetExistingClass_notExisting() { Class<?> actual = ClassUtils.getExistingClass(getClass().getClassLoader(), getClass().getName() + "$$$1"); assertNull(actual); }
### Question: ClassUtils { @SuppressWarnings("deprecation") public static <T> T newInstance(Class<T> clazz) { try { return clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new ObjenesisException(e); } } private ClassUtils(); static String classNameToInternalClassName(String className); static String classNameToResource(String className); @SuppressWarnings("unchecked") static Class<T> getExistingClass(ClassLoader classLoader, String className); @SuppressWarnings("deprecation") static T newInstance(Class<T> clazz); }### Answer: @Test public void testNewInstance_noArgsConstructorPresent() { ArrayList<?> i = ClassUtils.newInstance(ArrayList.class); assertTrue(i.isEmpty()); } @Test public void testNewInstance_noArgsConstructorAbsent() { try { ClassUtils.newInstance(Integer.class); fail("No arg constructor. It should fail"); } catch(ObjenesisException e) { assertEquals(InstantiationException.class, e.getCause().getClass()); } }
### Question: ProxyingInstantiator implements ObjectInstantiator<T> { public T newInstance() { return ClassUtils.newInstance(newType); } ProxyingInstantiator(Class<T> type); T newInstance(); }### Answer: @Test public void testNewInstance() { ObjectInstantiator<EmptyClass> inst = new ProxyingInstantiator<>(EmptyClass.class); EmptyClass c = inst.newInstance(); assertEquals("org.objenesis.EmptyClass$$$Objenesis", c.getClass().getName()); } @Test public void testJavaLangInstance() { ObjectInstantiator<Object> inst = new ProxyingInstantiator<>(Object.class); Object c = inst.newInstance(); assertEquals("org.objenesis.subclasses.java.lang.Object$$$Objenesis", c.getClass().getName()); }
### Question: MagicInstantiator implements ObjectInstantiator<T> { public T newInstance() { return instantiator.newInstance(); } MagicInstantiator(Class<T> type); ObjectInstantiator<T> getInstantiator(); T newInstance(); }### Answer: @Test public void testNewInstance() { ObjectInstantiator<EmptyClass> o1 = new MagicInstantiator<>(EmptyClass.class); assertEquals(EmptyClass.class, o1.newInstance().getClass()); ObjectInstantiator<EmptyClass> o2 = new MagicInstantiator<>(EmptyClass.class); assertEquals(EmptyClass.class, o2.newInstance().getClass()); }
### Question: AbstractLoader { public void loadFromResource(String resource, Candidate.CandidateType type) throws IOException { InputStream candidatesConfig = classloader.getResourceAsStream(resource); if(candidatesConfig == null) { throw new IOException("Resource '" + resource + "' not found"); } try { loadFrom(candidatesConfig, type); } finally { candidatesConfig.close(); } } AbstractLoader(ClassLoader classloader, ErrorHandler errorHandler); void loadFrom(InputStream inputStream, final Candidate.CandidateType type); void loadFromResource(String resource, Candidate.CandidateType type); }### Answer: @Test public void testLoadsFromResourceInClassPath() throws IOException { loader.loadFromResource("org/objenesis/tck/CandidateLoaderTest-sample.properties", Candidate.CandidateType.STANDARD); assertEquals("" + "registerCandidate('class org.objenesis.tck.AbstractLoaderTest$A', 'A candidate')\n" + "registerCandidate('class org.objenesis.tck.AbstractLoaderTest$B', 'B candidate')\n", recordedEvents.toString()); } @Test public void testThrowsIOExceptionIfResourceNotInClassPath() { try { loader.loadFromResource( "Blatantly-Bogus.properties", Candidate.CandidateType.STANDARD); fail("Expected exception"); } catch(IOException expectedException) { } }
### Question: PlatformDescription { public static boolean isThisJVM(String name) { return JVM_NAME.startsWith(name); } private PlatformDescription(); static String describePlatform(); static boolean isThisJVM(String name); static boolean isAndroidOpenJDK(); static boolean isAfterJigsaw(); static boolean isAfterJava11(); static boolean isGoogleAppEngine(); static final String GNU; static final String HOTSPOT; @Deprecated static final String SUN; static final String OPENJDK; static final String PERC; static final String DALVIK; static final String SPECIFICATION_VERSION; static final String VM_VERSION; static final String VM_INFO; static final String VENDOR_VERSION; static final String VENDOR; static final String JVM_NAME; static final int ANDROID_VERSION; static final boolean IS_ANDROID_OPENJDK; static final String GAE_VERSION; }### Answer: @Test public void isJvmName() { PlatformDescription.isThisJVM(PlatformDescription.HOTSPOT); } @Test public void test() { if(!PlatformDescription.isThisJVM(PlatformDescription.DALVIK)) { assertEquals(0, PlatformDescription.ANDROID_VERSION); } }
### Question: PlatformDescription { public static boolean isAfterJigsaw() { String version = PlatformDescription.SPECIFICATION_VERSION; return version.indexOf('.') < 0; } private PlatformDescription(); static String describePlatform(); static boolean isThisJVM(String name); static boolean isAndroidOpenJDK(); static boolean isAfterJigsaw(); static boolean isAfterJava11(); static boolean isGoogleAppEngine(); static final String GNU; static final String HOTSPOT; @Deprecated static final String SUN; static final String OPENJDK; static final String PERC; static final String DALVIK; static final String SPECIFICATION_VERSION; static final String VM_VERSION; static final String VM_INFO; static final String VENDOR_VERSION; static final String VENDOR; static final String JVM_NAME; static final int ANDROID_VERSION; static final boolean IS_ANDROID_OPENJDK; static final String GAE_VERSION; }### Answer: @Test public void isAfterJigsaw() { PlatformDescription.isAfterJigsaw(); }
### Question: PlatformDescription { public static boolean isAfterJava11() { if(!isAfterJigsaw()) { return false; } int version = Integer.parseInt(PlatformDescription.SPECIFICATION_VERSION); return version >= 11; } private PlatformDescription(); static String describePlatform(); static boolean isThisJVM(String name); static boolean isAndroidOpenJDK(); static boolean isAfterJigsaw(); static boolean isAfterJava11(); static boolean isGoogleAppEngine(); static final String GNU; static final String HOTSPOT; @Deprecated static final String SUN; static final String OPENJDK; static final String PERC; static final String DALVIK; static final String SPECIFICATION_VERSION; static final String VM_VERSION; static final String VM_INFO; static final String VENDOR_VERSION; static final String VENDOR; static final String JVM_NAME; static final int ANDROID_VERSION; static final boolean IS_ANDROID_OPENJDK; static final String GAE_VERSION; }### Answer: @Test public void isAfterJava11() { PlatformDescription.isAfterJava11(); }
### Question: ClassDefinitionUtils { @SuppressWarnings("unchecked") public static <T> Class<T> defineClass(String className, byte[] b, Class<?> neighbor, ClassLoader loader) throws Exception { Class<T> c = (Class<T>) DefineClassHelper.defineClass(className, b, 0, b.length, neighbor, loader, PROTECTION_DOMAIN); Class.forName(className, true, loader); return c; } private ClassDefinitionUtils(); @SuppressWarnings("unchecked") static Class<T> defineClass(String className, byte[] b, Class<?> neighbor, ClassLoader loader); static byte[] readClass(String className); static void writeClass(String fileName, byte[] bytes); static final byte OPS_aload_0; static final byte OPS_invokespecial; static final byte OPS_return; static final byte OPS_new; static final byte OPS_dup; static final byte OPS_areturn; static final int CONSTANT_Utf8; static final int CONSTANT_Integer; static final int CONSTANT_Float; static final int CONSTANT_Long; static final int CONSTANT_Double; static final int CONSTANT_Class; static final int CONSTANT_String; static final int CONSTANT_Fieldref; static final int CONSTANT_Methodref; static final int CONSTANT_InterfaceMethodref; static final int CONSTANT_NameAndType; static final int CONSTANT_MethodHandle; static final int CONSTANT_MethodType; static final int CONSTANT_InvokeDynamic; static final int ACC_PUBLIC; static final int ACC_FINAL; static final int ACC_SUPER; static final int ACC_INTERFACE; static final int ACC_ABSTRACT; static final int ACC_SYNTHETIC; static final int ACC_ANNOTATION; static final int ACC_ENUM; static final byte[] MAGIC; static final byte[] VERSION; }### Answer: @Test public void testDefineClass() throws Exception { byte[] b = ClassDefinitionUtils.readClass(className); Class<?> c = ClassDefinitionUtils.defineClass(className, b, Objenesis.class, getClass().getClassLoader()); assertEquals(c.getName(), className); }
### Question: ClassUtils { public static String classNameToInternalClassName(String className) { return className.replace('.', '/'); } private ClassUtils(); static String classNameToInternalClassName(String className); static String classNameToResource(String className); @SuppressWarnings("unchecked") static Class<T> getExistingClass(ClassLoader classLoader, String className); @SuppressWarnings("deprecation") static T newInstance(Class<T> clazz); }### Answer: @Test public void testClassNameToInternalClassName() { String actual = ClassUtils.classNameToInternalClassName(className); assertEquals("org/objenesis/EmptyClassBis", actual); }
### Question: ScriptCompilerPluginSpec { public Set<Path> getRuntimeResources() { return runtimeResources; } protected ScriptCompilerPluginSpec(String pluginId, Set<ModuleId> moduleDependencies, Set<Path> runtimeResources, String pluginClassName, Map<String, String> pluginMetadata, Map<String, Object> compilerParams); String getPluginId(); Set<Path> getRuntimeResources(); Set<ModuleId> getModuleDependencies(); Map<String, String> getPluginMetadata(); Map<String, Object> getCompilerParams(); String getPluginClassName(); }### Answer: @Test public void testAddRuntimeResources() throws IOException { ScriptCompilerPluginSpec pluginSpec = new ScriptCompilerPluginSpec.Builder(PLUGIN_ID) .addRuntimeResources(ImmutableSet.of( Paths.get(rootPath.toString(), files[0]), Paths.get(rootPath.toString(), files[1]), Paths.get(rootPath.toString(), files[2]) )) .build(); assertEquals(3, pluginSpec.getRuntimeResources().size()); pluginSpec = new ScriptCompilerPluginSpec.Builder(PLUGIN_ID) .addRuntimeResources(rootPath, Collections.singleton("jar"), true) .build(); assertEquals(4, pluginSpec.getRuntimeResources().size()); pluginSpec = new ScriptCompilerPluginSpec.Builder(PLUGIN_ID) .addRuntimeResources(rootPath, Collections.singleton("txt"), false) .build(); assertEquals(1, pluginSpec.getRuntimeResources().size()); assertTrue(pluginSpec.getRuntimeResources().iterator().next().endsWith("file0.txt")); pluginSpec = new ScriptCompilerPluginSpec.Builder(PLUGIN_ID) .addRuntimeResources(rootPath, ImmutableSet.of("txt", "json"), true) .build(); assertEquals(4, pluginSpec.getRuntimeResources().size()); }
### Question: ClassPathUtils { public static Set<String> scanClassPathWithIncludes(final String classPath, final Set<String> excludeJarSet, final Set<String> includePrefixes) { final Set<String> pathSet = new HashSet<String>(); __JDKPaths.processClassPathItem(classPath, excludeJarSet, pathSet); return filterPathSet(pathSet, Collections.<String>emptySet(), includePrefixes); } static Set<String> getJdkPaths(); @Nullable static Path findRootPathForResource(String resourceName, ClassLoader classLoader); @Nullable static Path findRootPathForClass(Class<?> clazz); static Path getJarPathFromUrl(URL jarUrl); static Set<Path> getDirectoriesFromJar(Path pathToJarFile); static String classToResourceName(Class<?> clazz); static String classNameToResourceName(String className); static Set<String> scanClassPath(final String classPath, final Set<String> excludeJarSet); static Set<String> scanClassPath(final String classPath, final Set<String> excludeJarSet, final Set<String> excludePrefixes, final Set<String> includePrefixes); static Set<String> scanClassPathWithExcludes(final String classPath, final Set<String> excludeJarSet, final Set<String> excludePrefixes); static Set<String> scanClassPathWithIncludes(final String classPath, final Set<String> excludeJarSet, final Set<String> includePrefixes); }### Answer: @Test public void testScanClassPathWithIncludes() throws Exception { Set<String> includePrefixes = new HashSet<String>(); Collections.addAll(includePrefixes, "com/netflix/foo"); Set<String> pkgPaths = ClassPathUtils.scanClassPathWithIncludes(classPathStr, Collections.<String>emptySet(), includePrefixes); Set<String> expected = new HashSet<String>(); Collections.addAll(expected, "com/netflix/foo", "com/netflix/foo/bar"); assertTrue(pkgPaths.equals(expected)); }
### Question: ScriptModuleLoader { @Nullable public ClassLoader getCompilerPluginClassLoader(String pluginModuleId) { return compilerClassLoaders.get(pluginModuleId); } protected ScriptModuleLoader(final Set<ScriptCompilerPluginSpec> pluginSpecs, final ClassLoader appClassLoader, final Set<String> appPackagePaths, final Set<ScriptModuleListener> listeners, final Path compilationRootDir); synchronized void updateScriptArchives(Set<? extends ScriptArchive> candidateArchives); synchronized void addCompilerPlugin(ScriptCompilerPluginSpec pluginSpec); synchronized void removeScriptModule(ModuleId scriptModuleId); @Nullable ScriptModule getScriptModule(String scriptModuleId); @Nullable ClassLoader getCompilerPluginClassLoader(String pluginModuleId); @Nullable ScriptModule getScriptModule(ModuleId scriptModuleId); Map<ModuleId, ScriptModule> getAllScriptModules(); void addListeners(Set<ScriptModuleListener> listeners); }### Answer: @Test public void testCompilerPluginClassloader() throws ModuleLoadException, IOException, ClassNotFoundException { ScriptModuleLoader moduleLoader = new ScriptModuleLoader.Builder() .addPluginSpec(new ScriptCompilerPluginSpec.Builder("mockPlugin") .withPluginClassName(MockScriptCompilerPlugin.class.getName()).build()) .build(); ClassLoader classLoader = moduleLoader.getCompilerPluginClassLoader("mockPlugin"); assertNotNull(classLoader); Class<?> pluginClass = classLoader.loadClass(MockScriptCompilerPlugin.class.getName()); assertNotNull(pluginClass); }
### Question: CassandraArchiveRepository implements ArchiveRepository { @Override public RepositoryView getView(String view) { throw new UnsupportedOperationException(); } CassandraArchiveRepository(CassandraArchiveRepositoryConfig config); CassandraArchiveRepository(CassandraArchiveRepositoryConfig config, RepositoryView defaultView); @Override String getRepositoryId(); @Override RepositoryView getDefaultView(); @Override RepositoryView getView(String view); @Override void insertArchive(JarScriptArchive jarScriptArchive); @Override void insertArchive(JarScriptArchive jarScriptArchive, Map<String, Object> initialDeploySpecs); @Override Set<ScriptArchive> getScriptArchives(Set<ModuleId> moduleIds); @Override void deleteArchive(ModuleId moduleId); CassandraArchiveRepositoryConfig getConfig(); }### Answer: @Test(expectedExceptions=UnsupportedOperationException.class) public void testGetView() throws IOException { repository.getView(""); }
### Question: CassandraArchiveRepository implements ArchiveRepository { @Override public void deleteArchive(ModuleId moduleId) throws IOException { Objects.requireNonNull(moduleId, "moduleId"); cassandra.deleteRow(moduleId.toString()); } CassandraArchiveRepository(CassandraArchiveRepositoryConfig config); CassandraArchiveRepository(CassandraArchiveRepositoryConfig config, RepositoryView defaultView); @Override String getRepositoryId(); @Override RepositoryView getDefaultView(); @Override RepositoryView getView(String view); @Override void insertArchive(JarScriptArchive jarScriptArchive); @Override void insertArchive(JarScriptArchive jarScriptArchive, Map<String, Object> initialDeploySpecs); @Override Set<ScriptArchive> getScriptArchives(Set<ModuleId> moduleIds); @Override void deleteArchive(ModuleId moduleId); CassandraArchiveRepositoryConfig getConfig(); }### Answer: @Test public void testDeleteArchive() throws IllegalArgumentException, IOException { repository.deleteArchive(ModuleId.fromString("testModule.v3")); verify(gateway).deleteRow("testModule.v3"); }
### Question: CloudJobFacade implements JobFacade { @Override public JobRootConfiguration loadJobRootConfiguration(final boolean fromCache) { return jobConfig; } @Override JobRootConfiguration loadJobRootConfiguration(final boolean fromCache); @Override void checkJobExecutionEnvironment(); @Override void failoverIfNecessary(); @Override void registerJobBegin(final ShardingContexts shardingContexts); @Override void registerJobCompleted(final ShardingContexts shardingContexts); ShardingContexts getShardingContexts(); @Override boolean misfireIfRunning(final Collection<Integer> shardingItems); @Override void clearMisfire(final Collection<Integer> shardingItems); @Override boolean isExecuteMisfired(final Collection<Integer> shardingItems); @Override boolean isEligibleForJobRunning(); @Override boolean isNeedSharding(); @Override void beforeJobExecuted(final ShardingContexts shardingContexts); @Override void afterJobExecuted(final ShardingContexts shardingContexts); @Override void postJobExecutionEvent(final JobExecutionEvent jobExecutionEvent); @Override void postJobStatusTraceEvent(final String taskId, final JobStatusTraceEvent.State state, final String message); }### Answer: @Test public void assertLoadJobRootConfiguration() { assertThat(jobFacade.loadJobRootConfiguration(true), is((JobRootConfiguration) jobConfig)); }
### Question: JobEventRdbConfiguration extends JobEventRdbIdentity implements JobEventConfiguration, Serializable { @Override public JobEventListener createJobEventListener() throws JobEventListenerConfigurationException { try { return new JobEventRdbListener(dataSource); } catch (final SQLException ex) { throw new JobEventListenerConfigurationException(ex); } } @Override JobEventListener createJobEventListener(); }### Answer: @Test public void assertCreateJobEventListenerSuccess() throws JobEventListenerConfigurationException { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(org.h2.Driver.class.getName()); dataSource.setUrl("jdbc:h2:mem:job_event_storage"); dataSource.setUsername("sa"); dataSource.setPassword(""); Assert.assertThat(new JobEventRdbConfiguration(dataSource).createJobEventListener(), CoreMatchers.instanceOf(JobEventRdbListener.class)); } @Test(expected = JobEventListenerConfigurationException.class) public void assertCreateJobEventListenerFailure() throws JobEventListenerConfigurationException { new JobEventRdbConfiguration(new BasicDataSource()).createJobEventListener(); }
### Question: JobEventRdbIdentity implements JobEventIdentity { @Override public String getIdentity() { return "rdb"; } @Override String getIdentity(); }### Answer: @Test public void assertGetIdentity() { Assert.assertThat(new JobEventRdbIdentity().getIdentity(), Is.is("rdb")); }
### Question: CloudJobFacade implements JobFacade { @Override public boolean isEligibleForJobRunning() { return jobConfig.getTypeConfig() instanceof DataflowJobConfiguration && ((DataflowJobConfiguration) jobConfig.getTypeConfig()).isStreamingProcess(); } @Override JobRootConfiguration loadJobRootConfiguration(final boolean fromCache); @Override void checkJobExecutionEnvironment(); @Override void failoverIfNecessary(); @Override void registerJobBegin(final ShardingContexts shardingContexts); @Override void registerJobCompleted(final ShardingContexts shardingContexts); ShardingContexts getShardingContexts(); @Override boolean misfireIfRunning(final Collection<Integer> shardingItems); @Override void clearMisfire(final Collection<Integer> shardingItems); @Override boolean isExecuteMisfired(final Collection<Integer> shardingItems); @Override boolean isEligibleForJobRunning(); @Override boolean isNeedSharding(); @Override void beforeJobExecuted(final ShardingContexts shardingContexts); @Override void afterJobExecuted(final ShardingContexts shardingContexts); @Override void postJobExecutionEvent(final JobExecutionEvent jobExecutionEvent); @Override void postJobStatusTraceEvent(final String taskId, final JobStatusTraceEvent.State state, final String message); }### Answer: @Test public void assertIsEligibleForJobRunningWhenIsDataflowJobAndIsNotStreamingProcess() { assertFalse(new CloudJobFacade(shardingContexts, new JobConfigurationContext(getJobConfigurationMap(JobType.DATAFLOW, false)), new JobEventBus()).isEligibleForJobRunning()); } @Test public void assertIsEligibleForJobRunningWhenIsDataflowJobAndIsStreamingProcess() { assertTrue(new CloudJobFacade(shardingContexts, new JobConfigurationContext(getJobConfigurationMap(JobType.DATAFLOW, true)), new JobEventBus()).isEligibleForJobRunning()); } @Test public void assertIsEligibleForJobRunningWhenIsNotDataflowJob() { assertFalse(jobFacade.isEligibleForJobRunning()); }
### Question: JobRunningStatisticJob extends AbstractStatisticJob { @Override public JobDetail buildJobDetail() { return JobBuilder.newJob(this.getClass()).withIdentity(getJobName()).build(); } JobRunningStatisticJob(final CoordinatorRegistryCenter registryCenter, final StatisticRdbRepository rdbRepository); @Override JobDetail buildJobDetail(); @Override Trigger buildTrigger(); @Override Map<String, Object> getDataMap(); @Override void execute(final JobExecutionContext context); }### Answer: @Test public void assertBuildJobDetail() { Assert.assertThat(jobRunningStatisticJob.buildJobDetail().getKey().getName(), Is.is(JobRunningStatisticJob.class.getSimpleName())); } @Test public void assertBuildJobDetail() { assertThat(jobRunningStatisticJob.buildJobDetail().getKey().getName(), is(JobRunningStatisticJob.class.getSimpleName())); }
### Question: JobRunningStatisticJob extends AbstractStatisticJob { @Override public Trigger buildTrigger() { return TriggerBuilder.newTrigger() .withIdentity(getTriggerName()) .withSchedule(CronScheduleBuilder.cronSchedule(EXECUTE_INTERVAL.getCron()) .withMisfireHandlingInstructionDoNothing()).build(); } JobRunningStatisticJob(final CoordinatorRegistryCenter registryCenter, final StatisticRdbRepository rdbRepository); @Override JobDetail buildJobDetail(); @Override Trigger buildTrigger(); @Override Map<String, Object> getDataMap(); @Override void execute(final JobExecutionContext context); }### Answer: @Test public void assertBuildTrigger() throws SchedulerException { Trigger trigger = jobRunningStatisticJob.buildTrigger(); Assert.assertThat(trigger.getKey().getName(), Is.is(JobRunningStatisticJob.class.getSimpleName() + "Trigger")); } @Test public void assertBuildTrigger() { Trigger trigger = jobRunningStatisticJob.buildTrigger(); assertThat(trigger.getKey().getName(), is(JobRunningStatisticJob.class.getSimpleName() + "Trigger")); }
### Question: CloudJobFacade implements JobFacade { @Override public boolean isNeedSharding() { return false; } @Override JobRootConfiguration loadJobRootConfiguration(final boolean fromCache); @Override void checkJobExecutionEnvironment(); @Override void failoverIfNecessary(); @Override void registerJobBegin(final ShardingContexts shardingContexts); @Override void registerJobCompleted(final ShardingContexts shardingContexts); ShardingContexts getShardingContexts(); @Override boolean misfireIfRunning(final Collection<Integer> shardingItems); @Override void clearMisfire(final Collection<Integer> shardingItems); @Override boolean isExecuteMisfired(final Collection<Integer> shardingItems); @Override boolean isEligibleForJobRunning(); @Override boolean isNeedSharding(); @Override void beforeJobExecuted(final ShardingContexts shardingContexts); @Override void afterJobExecuted(final ShardingContexts shardingContexts); @Override void postJobExecutionEvent(final JobExecutionEvent jobExecutionEvent); @Override void postJobStatusTraceEvent(final String taskId, final JobStatusTraceEvent.State state, final String message); }### Answer: @Test public void assertIsNeedSharding() { assertFalse(jobFacade.isNeedSharding()); }
### Question: JobRunningStatisticJob extends AbstractStatisticJob { @Override public Map<String, Object> getDataMap() { Map<String, Object> result = new HashMap<>(2); result.put("runningService", runningService); result.put("repository", repository); return result; } JobRunningStatisticJob(final CoordinatorRegistryCenter registryCenter, final StatisticRdbRepository rdbRepository); @Override JobDetail buildJobDetail(); @Override Trigger buildTrigger(); @Override Map<String, Object> getDataMap(); @Override void execute(final JobExecutionContext context); }### Answer: @Test public void assertGetDataMap() throws SchedulerException { Assert.assertThat((RunningService) jobRunningStatisticJob.getDataMap().get("runningService"), Is.is(runningService)); Assert.assertThat((StatisticRdbRepository) jobRunningStatisticJob.getDataMap().get("repository"), Is.is(repository)); } @Test public void assertGetDataMap() { assertThat(jobRunningStatisticJob.getDataMap().get("runningService"), is(runningService)); assertThat(jobRunningStatisticJob.getDataMap().get("repository"), is(repository)); }
### Question: TaskResultStatisticJob extends AbstractStatisticJob { @Override public Trigger buildTrigger() { return TriggerBuilder.newTrigger() .withIdentity(getTriggerName() + "_" + statisticInterval) .withSchedule(CronScheduleBuilder.cronSchedule(statisticInterval.getCron()) .withMisfireHandlingInstructionDoNothing()).build(); } @Override JobDetail buildJobDetail(); @Override Trigger buildTrigger(); @Override Map<String, Object> getDataMap(); @Override void execute(final JobExecutionContext context); }### Answer: @Test public void assertBuildTrigger() throws SchedulerException { for (StatisticInterval each : StatisticInterval.values()) { taskResultStatisticJob.setStatisticInterval(each); Trigger trigger = taskResultStatisticJob.buildTrigger(); assertThat(trigger.getKey().getName(), is(TaskResultStatisticJob.class.getSimpleName() + "Trigger" + "_" + each)); } } @Test public void assertBuildTrigger() { for (StatisticInterval each : StatisticInterval.values()) { taskResultStatisticJob.setStatisticInterval(each); Trigger trigger = taskResultStatisticJob.buildTrigger(); assertThat(trigger.getKey().getName(), is(TaskResultStatisticJob.class.getSimpleName() + "Trigger" + "_" + each)); } }
### Question: TaskResultStatisticJob extends AbstractStatisticJob { @Override public Map<String, Object> getDataMap() { Map<String, Object> result = new HashMap<>(3); result.put("statisticInterval", statisticInterval); result.put("sharedData", sharedData); result.put("repository", repository); return result; } @Override JobDetail buildJobDetail(); @Override Trigger buildTrigger(); @Override Map<String, Object> getDataMap(); @Override void execute(final JobExecutionContext context); }### Answer: @Test public void assertGetDataMap() throws SchedulerException { assertThat((StatisticInterval) taskResultStatisticJob.getDataMap().get("statisticInterval"), is(statisticInterval)); assertThat((TaskResultMetaData) taskResultStatisticJob.getDataMap().get("sharedData"), is(sharedData)); assertThat((StatisticRdbRepository) taskResultStatisticJob.getDataMap().get("repository"), is(repository)); } @Test public void assertGetDataMap() { assertThat(taskResultStatisticJob.getDataMap().get("statisticInterval"), is(statisticInterval)); assertThat(taskResultStatisticJob.getDataMap().get("sharedData"), is(sharedData)); assertThat(taskResultStatisticJob.getDataMap().get("repository"), is(repository)); }
### Question: RegisteredJobStatisticJob extends AbstractStatisticJob { @Override public Trigger buildTrigger() { return TriggerBuilder.newTrigger() .withIdentity(getTriggerName()) .withSchedule(CronScheduleBuilder.cronSchedule(execInterval.getCron()) .withMisfireHandlingInstructionDoNothing()).build(); } @Override JobDetail buildJobDetail(); @Override Trigger buildTrigger(); @Override Map<String, Object> getDataMap(); @Override void execute(final JobExecutionContext context); }### Answer: @Test public void assertBuildTrigger() throws SchedulerException { Trigger trigger = registeredJobStatisticJob.buildTrigger(); assertThat(trigger.getKey().getName(), is(RegisteredJobStatisticJob.class.getSimpleName() + "Trigger")); } @Test public void assertBuildTrigger() { Trigger trigger = registeredJobStatisticJob.buildTrigger(); assertThat(trigger.getKey().getName(), is(RegisteredJobStatisticJob.class.getSimpleName() + "Trigger")); }
### Question: CloudJobFacade implements JobFacade { @Override public void beforeJobExecuted(final ShardingContexts shardingContexts) { } @Override JobRootConfiguration loadJobRootConfiguration(final boolean fromCache); @Override void checkJobExecutionEnvironment(); @Override void failoverIfNecessary(); @Override void registerJobBegin(final ShardingContexts shardingContexts); @Override void registerJobCompleted(final ShardingContexts shardingContexts); ShardingContexts getShardingContexts(); @Override boolean misfireIfRunning(final Collection<Integer> shardingItems); @Override void clearMisfire(final Collection<Integer> shardingItems); @Override boolean isExecuteMisfired(final Collection<Integer> shardingItems); @Override boolean isEligibleForJobRunning(); @Override boolean isNeedSharding(); @Override void beforeJobExecuted(final ShardingContexts shardingContexts); @Override void afterJobExecuted(final ShardingContexts shardingContexts); @Override void postJobExecutionEvent(final JobExecutionEvent jobExecutionEvent); @Override void postJobStatusTraceEvent(final String taskId, final JobStatusTraceEvent.State state, final String message); }### Answer: @Test public void assertBeforeJobExecuted() { jobFacade.beforeJobExecuted(null); }
### Question: RegisteredJobStatisticJob extends AbstractStatisticJob { @Override public Map<String, Object> getDataMap() { Map<String, Object> result = new HashMap<>(2); result.put("configurationService", configurationService); result.put("repository", repository); return result; } @Override JobDetail buildJobDetail(); @Override Trigger buildTrigger(); @Override Map<String, Object> getDataMap(); @Override void execute(final JobExecutionContext context); }### Answer: @Test public void assertGetDataMap() throws SchedulerException { assertThat((CloudJobConfigurationService) registeredJobStatisticJob.getDataMap().get("configurationService"), is(configurationService)); assertThat((StatisticRdbRepository) registeredJobStatisticJob.getDataMap().get("repository"), is(repository)); } @Test public void assertGetDataMap() { assertThat(registeredJobStatisticJob.getDataMap().get("configurationService"), is(configurationService)); assertThat(registeredJobStatisticJob.getDataMap().get("repository"), is(repository)); }
### Question: RegisteredJobStatisticJob extends AbstractStatisticJob { @Override public void execute(final JobExecutionContext context) throws JobExecutionException { Optional<JobRegisterStatistics> latestOne = repository.findLatestJobRegisterStatistics(); if (latestOne.isPresent()) { fillBlankIfNeeded(latestOne.get()); } int registeredCount = configurationService.loadAll().size(); JobRegisterStatistics jobRegisterStatistics = new JobRegisterStatistics(registeredCount, StatisticTimeUtils.getCurrentStatisticTime(execInterval)); log.debug("Add jobRegisterStatistics, registeredCount is:{}", registeredCount); repository.add(jobRegisterStatistics); } @Override JobDetail buildJobDetail(); @Override Trigger buildTrigger(); @Override Map<String, Object> getDataMap(); @Override void execute(final JobExecutionContext context); }### Answer: @Test public void assertExecuteWhenRepositoryIsEmpty() throws SchedulerException { Optional<JobRegisterStatistics> latestOne = Optional.absent(); when(repository.findLatestJobRegisterStatistics()).thenReturn(latestOne); when(repository.add(any(JobRegisterStatistics.class))).thenReturn(true); when(configurationService.loadAll()).thenReturn(Lists.newArrayList(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job"))); registeredJobStatisticJob.execute(null); verify(repository).findLatestJobRegisterStatistics(); verify(repository).add(any(JobRegisterStatistics.class)); verify(configurationService).loadAll(); } @Test public void assertExecute() throws SchedulerException { Optional<JobRegisterStatistics> latestOne = Optional.of(new JobRegisterStatistics(0, StatisticTimeUtils.getStatisticTime(StatisticInterval.DAY, -3))); when(repository.findLatestJobRegisterStatistics()).thenReturn(latestOne); when(repository.add(any(JobRegisterStatistics.class))).thenReturn(true); when(configurationService.loadAll()).thenReturn(Lists.newArrayList(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job"))); registeredJobStatisticJob.execute(null); verify(repository).findLatestJobRegisterStatistics(); verify(repository, times(3)).add(any(JobRegisterStatistics.class)); verify(configurationService).loadAll(); }
### Question: StatisticManager { public static StatisticManager getInstance(final CoordinatorRegistryCenter regCenter, final Optional<JobEventRdbConfiguration> jobEventRdbConfiguration) { if (null == instance) { synchronized (StatisticManager.class) { if (null == instance) { Map<StatisticInterval, TaskResultMetaData> statisticData = new HashMap<>(); statisticData.put(StatisticInterval.MINUTE, new TaskResultMetaData()); statisticData.put(StatisticInterval.HOUR, new TaskResultMetaData()); statisticData.put(StatisticInterval.DAY, new TaskResultMetaData()); instance = new StatisticManager(regCenter, jobEventRdbConfiguration, new StatisticsScheduler(), statisticData); init(); } } } return instance; } private StatisticManager(final CoordinatorRegistryCenter registryCenter, final Optional<JobEventRdbConfiguration> jobEventRdbConfiguration, final StatisticsScheduler scheduler, final Map<StatisticInterval, TaskResultMetaData> statisticData); static StatisticManager getInstance(final CoordinatorRegistryCenter regCenter, final Optional<JobEventRdbConfiguration> jobEventRdbConfiguration); void startup(); void shutdown(); void taskRunSuccessfully(); void taskRunFailed(); TaskResultStatistics getTaskResultStatisticsWeekly(); TaskResultStatistics getTaskResultStatisticsSinceOnline(); TaskResultStatistics findLatestTaskResultStatistics(final StatisticInterval statisticInterval); List<TaskResultStatistics> findTaskResultStatisticsDaily(); JobTypeStatistics getJobTypeStatistics(); JobExecutionTypeStatistics getJobExecutionTypeStatistics(); List<TaskRunningStatistics> findTaskRunningStatisticsWeekly(); List<JobRunningStatistics> findJobRunningStatisticsWeekly(); List<JobRegisterStatistics> findJobRegisterStatisticsSinceOnline(); }### Answer: @Test public void assertGetInstance() { Assert.assertThat(statisticManager, Is.is(StatisticManager.getInstance(regCenter, jobEventRdbConfiguration))); }
### Question: StatisticManager { public void startup() { if (null != rdbRepository) { scheduler.start(); scheduler.register(new TaskResultStatisticJob(StatisticInterval.MINUTE, statisticData.get(StatisticInterval.MINUTE), rdbRepository)); scheduler.register(new TaskResultStatisticJob(StatisticInterval.HOUR, statisticData.get(StatisticInterval.HOUR), rdbRepository)); scheduler.register(new TaskResultStatisticJob(StatisticInterval.DAY, statisticData.get(StatisticInterval.DAY), rdbRepository)); scheduler.register(new JobRunningStatisticJob(registryCenter, rdbRepository)); scheduler.register(new RegisteredJobStatisticJob(configurationService, rdbRepository)); } } private StatisticManager(final CoordinatorRegistryCenter registryCenter, final Optional<JobEventRdbConfiguration> jobEventRdbConfiguration, final StatisticsScheduler scheduler, final Map<StatisticInterval, TaskResultMetaData> statisticData); static StatisticManager getInstance(final CoordinatorRegistryCenter regCenter, final Optional<JobEventRdbConfiguration> jobEventRdbConfiguration); void startup(); void shutdown(); void taskRunSuccessfully(); void taskRunFailed(); TaskResultStatistics getTaskResultStatisticsWeekly(); TaskResultStatistics getTaskResultStatisticsSinceOnline(); TaskResultStatistics findLatestTaskResultStatistics(final StatisticInterval statisticInterval); List<TaskResultStatistics> findTaskResultStatisticsDaily(); JobTypeStatistics getJobTypeStatistics(); JobExecutionTypeStatistics getJobExecutionTypeStatistics(); List<TaskRunningStatistics> findTaskRunningStatisticsWeekly(); List<JobRunningStatistics> findJobRunningStatisticsWeekly(); List<JobRegisterStatistics> findJobRegisterStatisticsSinceOnline(); }### Answer: @Test public void assertStartupWhenRdbIsNotConfigured() throws NoSuchFieldException { ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", null); statisticManager.startup(); } @Test public void assertStartupWhenRdbIsConfigured() throws NoSuchFieldException { ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", rdbRepository); statisticManager.startup(); }
### Question: StatisticManager { public void shutdown() { scheduler.shutdown(); } private StatisticManager(final CoordinatorRegistryCenter registryCenter, final Optional<JobEventRdbConfiguration> jobEventRdbConfiguration, final StatisticsScheduler scheduler, final Map<StatisticInterval, TaskResultMetaData> statisticData); static StatisticManager getInstance(final CoordinatorRegistryCenter regCenter, final Optional<JobEventRdbConfiguration> jobEventRdbConfiguration); void startup(); void shutdown(); void taskRunSuccessfully(); void taskRunFailed(); TaskResultStatistics getTaskResultStatisticsWeekly(); TaskResultStatistics getTaskResultStatisticsSinceOnline(); TaskResultStatistics findLatestTaskResultStatistics(final StatisticInterval statisticInterval); List<TaskResultStatistics> findTaskResultStatisticsDaily(); JobTypeStatistics getJobTypeStatistics(); JobExecutionTypeStatistics getJobExecutionTypeStatistics(); List<TaskRunningStatistics> findTaskRunningStatisticsWeekly(); List<JobRunningStatistics> findJobRunningStatisticsWeekly(); List<JobRegisterStatistics> findJobRegisterStatisticsSinceOnline(); }### Answer: @Test public void assertShutdown() throws NoSuchFieldException { ReflectionUtils.setFieldValue(statisticManager, "scheduler", scheduler); statisticManager.shutdown(); Mockito.verify(scheduler).shutdown(); }
### Question: StatisticManager { public List<TaskRunningStatistics> findTaskRunningStatisticsWeekly() { if (!isRdbConfigured()) { return Collections.emptyList(); } return rdbRepository.findTaskRunningStatistics(StatisticTimeUtils.getStatisticTime(StatisticInterval.DAY, -7)); } private StatisticManager(final CoordinatorRegistryCenter registryCenter, final Optional<JobEventRdbConfiguration> jobEventRdbConfiguration, final StatisticsScheduler scheduler, final Map<StatisticInterval, TaskResultMetaData> statisticData); static StatisticManager getInstance(final CoordinatorRegistryCenter regCenter, final Optional<JobEventRdbConfiguration> jobEventRdbConfiguration); void startup(); void shutdown(); void taskRunSuccessfully(); void taskRunFailed(); TaskResultStatistics getTaskResultStatisticsWeekly(); TaskResultStatistics getTaskResultStatisticsSinceOnline(); TaskResultStatistics findLatestTaskResultStatistics(final StatisticInterval statisticInterval); List<TaskResultStatistics> findTaskResultStatisticsDaily(); JobTypeStatistics getJobTypeStatistics(); JobExecutionTypeStatistics getJobExecutionTypeStatistics(); List<TaskRunningStatistics> findTaskRunningStatisticsWeekly(); List<JobRunningStatistics> findJobRunningStatisticsWeekly(); List<JobRegisterStatistics> findJobRegisterStatisticsSinceOnline(); }### Answer: @Test public void assertFindTaskRunningStatisticsWhenRdbIsNotConfigured() throws NoSuchFieldException { ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", null); Assert.assertTrue(statisticManager.findTaskRunningStatisticsWeekly().isEmpty()); } @Test public void assertFindTaskRunningStatisticsWhenRdbIsConfigured() throws NoSuchFieldException { ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", rdbRepository); Mockito.when(rdbRepository.findTaskRunningStatistics(Mockito.any(Date.class))) .thenReturn(Lists.newArrayList(new TaskRunningStatistics(10, new Date()))); Assert.assertThat(statisticManager.findTaskRunningStatisticsWeekly().size(), Is.is(1)); Mockito.verify(rdbRepository).findTaskRunningStatistics(Mockito.any(Date.class)); }
### Question: CloudJobFacade implements JobFacade { @Override public void afterJobExecuted(final ShardingContexts shardingContexts) { } @Override JobRootConfiguration loadJobRootConfiguration(final boolean fromCache); @Override void checkJobExecutionEnvironment(); @Override void failoverIfNecessary(); @Override void registerJobBegin(final ShardingContexts shardingContexts); @Override void registerJobCompleted(final ShardingContexts shardingContexts); ShardingContexts getShardingContexts(); @Override boolean misfireIfRunning(final Collection<Integer> shardingItems); @Override void clearMisfire(final Collection<Integer> shardingItems); @Override boolean isExecuteMisfired(final Collection<Integer> shardingItems); @Override boolean isEligibleForJobRunning(); @Override boolean isNeedSharding(); @Override void beforeJobExecuted(final ShardingContexts shardingContexts); @Override void afterJobExecuted(final ShardingContexts shardingContexts); @Override void postJobExecutionEvent(final JobExecutionEvent jobExecutionEvent); @Override void postJobStatusTraceEvent(final String taskId, final JobStatusTraceEvent.State state, final String message); }### Answer: @Test public void assertAfterJobExecuted() { jobFacade.afterJobExecuted(null); }
### Question: StatisticManager { public List<JobRunningStatistics> findJobRunningStatisticsWeekly() { if (!isRdbConfigured()) { return Collections.emptyList(); } return rdbRepository.findJobRunningStatistics(StatisticTimeUtils.getStatisticTime(StatisticInterval.DAY, -7)); } private StatisticManager(final CoordinatorRegistryCenter registryCenter, final Optional<JobEventRdbConfiguration> jobEventRdbConfiguration, final StatisticsScheduler scheduler, final Map<StatisticInterval, TaskResultMetaData> statisticData); static StatisticManager getInstance(final CoordinatorRegistryCenter regCenter, final Optional<JobEventRdbConfiguration> jobEventRdbConfiguration); void startup(); void shutdown(); void taskRunSuccessfully(); void taskRunFailed(); TaskResultStatistics getTaskResultStatisticsWeekly(); TaskResultStatistics getTaskResultStatisticsSinceOnline(); TaskResultStatistics findLatestTaskResultStatistics(final StatisticInterval statisticInterval); List<TaskResultStatistics> findTaskResultStatisticsDaily(); JobTypeStatistics getJobTypeStatistics(); JobExecutionTypeStatistics getJobExecutionTypeStatistics(); List<TaskRunningStatistics> findTaskRunningStatisticsWeekly(); List<JobRunningStatistics> findJobRunningStatisticsWeekly(); List<JobRegisterStatistics> findJobRegisterStatisticsSinceOnline(); }### Answer: @Test public void assertFindJobRunningStatisticsWhenRdbIsNotConfigured() throws NoSuchFieldException { ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", null); Assert.assertTrue(statisticManager.findJobRunningStatisticsWeekly().isEmpty()); } @Test public void assertFindJobRunningStatisticsWhenRdbIsConfigured() throws NoSuchFieldException { ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", rdbRepository); Mockito.when(rdbRepository.findJobRunningStatistics(Mockito.any(Date.class))) .thenReturn(Lists.newArrayList(new JobRunningStatistics(10, new Date()))); Assert.assertThat(statisticManager.findJobRunningStatisticsWeekly().size(), Is.is(1)); Mockito.verify(rdbRepository).findJobRunningStatistics(Mockito.any(Date.class)); }
### Question: StatisticManager { public List<JobRegisterStatistics> findJobRegisterStatisticsSinceOnline() { if (!isRdbConfigured()) { return Collections.emptyList(); } return rdbRepository.findJobRegisterStatistics(getOnlineDate()); } private StatisticManager(final CoordinatorRegistryCenter registryCenter, final Optional<JobEventRdbConfiguration> jobEventRdbConfiguration, final StatisticsScheduler scheduler, final Map<StatisticInterval, TaskResultMetaData> statisticData); static StatisticManager getInstance(final CoordinatorRegistryCenter regCenter, final Optional<JobEventRdbConfiguration> jobEventRdbConfiguration); void startup(); void shutdown(); void taskRunSuccessfully(); void taskRunFailed(); TaskResultStatistics getTaskResultStatisticsWeekly(); TaskResultStatistics getTaskResultStatisticsSinceOnline(); TaskResultStatistics findLatestTaskResultStatistics(final StatisticInterval statisticInterval); List<TaskResultStatistics> findTaskResultStatisticsDaily(); JobTypeStatistics getJobTypeStatistics(); JobExecutionTypeStatistics getJobExecutionTypeStatistics(); List<TaskRunningStatistics> findTaskRunningStatisticsWeekly(); List<JobRunningStatistics> findJobRunningStatisticsWeekly(); List<JobRegisterStatistics> findJobRegisterStatisticsSinceOnline(); }### Answer: @Test public void assertFindJobRegisterStatisticsWhenRdbIsNotConfigured() throws NoSuchFieldException { ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", null); Assert.assertTrue(statisticManager.findJobRegisterStatisticsSinceOnline().isEmpty()); } @Test public void assertFindJobRegisterStatisticsWhenRdbIsConfigured() throws NoSuchFieldException { ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", rdbRepository); Mockito.when(rdbRepository.findJobRegisterStatistics(Mockito.any(Date.class))) .thenReturn(Lists.newArrayList(new JobRegisterStatistics(10, new Date()))); Assert.assertThat(statisticManager.findJobRegisterStatisticsSinceOnline().size(), Is.is(1)); Mockito.verify(rdbRepository).findJobRegisterStatistics(Mockito.any(Date.class)); }
### Question: FrameworkIDService { public Optional<String> fetch() { String frameworkId = regCenter.getDirectly(HANode.FRAMEWORK_ID_NODE); return Strings.isNullOrEmpty(frameworkId) ? Optional.<String>absent() : Optional.of(frameworkId); } Optional<String> fetch(); void save(final String id); }### Answer: @Test public void assertFetch() throws Exception { when(registryCenter.getDirectly(HANode.FRAMEWORK_ID_NODE)).thenReturn("1"); Optional<String> frameworkIDOptional = frameworkIDService.fetch(); assertTrue(frameworkIDOptional.isPresent()); assertThat(frameworkIDOptional.get(), is("1")); verify(registryCenter).getDirectly(HANode.FRAMEWORK_ID_NODE); }
### Question: CloudJobFacade implements JobFacade { @Override public void postJobExecutionEvent(final JobExecutionEvent jobExecutionEvent) { jobEventBus.post(jobExecutionEvent); } @Override JobRootConfiguration loadJobRootConfiguration(final boolean fromCache); @Override void checkJobExecutionEnvironment(); @Override void failoverIfNecessary(); @Override void registerJobBegin(final ShardingContexts shardingContexts); @Override void registerJobCompleted(final ShardingContexts shardingContexts); ShardingContexts getShardingContexts(); @Override boolean misfireIfRunning(final Collection<Integer> shardingItems); @Override void clearMisfire(final Collection<Integer> shardingItems); @Override boolean isExecuteMisfired(final Collection<Integer> shardingItems); @Override boolean isEligibleForJobRunning(); @Override boolean isNeedSharding(); @Override void beforeJobExecuted(final ShardingContexts shardingContexts); @Override void afterJobExecuted(final ShardingContexts shardingContexts); @Override void postJobExecutionEvent(final JobExecutionEvent jobExecutionEvent); @Override void postJobStatusTraceEvent(final String taskId, final JobStatusTraceEvent.State state, final String message); }### Answer: @Test public void assertPostJobExecutionEvent() { JobExecutionEvent jobExecutionEvent = new JobExecutionEvent("fake_task_id", "test_job", JobExecutionEvent.ExecutionSource.NORMAL_TRIGGER, 0); jobFacade.postJobExecutionEvent(jobExecutionEvent); verify(eventBus).post(jobExecutionEvent); }
### Question: FrameworkIDService { public void save(final String id) { if (!regCenter.isExisted(HANode.FRAMEWORK_ID_NODE)) { regCenter.persist(HANode.FRAMEWORK_ID_NODE, id); } } Optional<String> fetch(); void save(final String id); }### Answer: @Test public void assertSave() throws Exception { when(registryCenter.isExisted(HANode.FRAMEWORK_ID_NODE)).thenReturn(false); frameworkIDService.save("1"); verify(registryCenter).isExisted(HANode.FRAMEWORK_ID_NODE); verify(registryCenter).persist(HANode.FRAMEWORK_ID_NODE, "1"); } @Test public void assertSave() { when(registryCenter.isExisted(HANode.FRAMEWORK_ID_NODE)).thenReturn(false); frameworkIDService.save("1"); verify(registryCenter).isExisted(HANode.FRAMEWORK_ID_NODE); verify(registryCenter).persist(HANode.FRAMEWORK_ID_NODE, "1"); }
### Question: RunningService { public Collection<TaskContext> getRunningTasks(final String jobName) { Set<TaskContext> taskContexts = new CopyOnWriteArraySet<>(); Collection<TaskContext> result = RUNNING_TASKS.putIfAbsent(jobName, taskContexts); return null == result ? taskContexts : result; } RunningService(final CoordinatorRegistryCenter regCenter); void start(); void add(final TaskContext taskContext); void updateIdle(final TaskContext taskContext, final boolean isIdle); void remove(final String jobName); void remove(final TaskContext taskContext); boolean isJobRunning(final String jobName); boolean isTaskRunning(final TaskContext.MetaInfo metaInfo); Collection<TaskContext> getRunningTasks(final String jobName); Map<String, Set<TaskContext>> getAllRunningTasks(); Set<TaskContext> getAllRunningDaemonTasks(); void addMapping(final String taskId, final String hostname); String popMapping(final String taskId); void clear(); }### Answer: @Test public void assertAddWithoutData() { Assert.assertThat(runningService.getRunningTasks("test_job").size(), Is.is(1)); Assert.assertThat(runningService.getRunningTasks("test_job").iterator().next(), Is.is(taskContext)); Assert.assertThat(runningService.getRunningTasks("test_job_t").size(), Is.is(1)); Assert.assertThat(runningService.getRunningTasks("test_job_t").iterator().next(), Is.is(taskContextT)); }
### Question: RunningService { public boolean isJobRunning(final String jobName) { return !getRunningTasks(jobName).isEmpty(); } RunningService(final CoordinatorRegistryCenter regCenter); void start(); void add(final TaskContext taskContext); void updateIdle(final TaskContext taskContext, final boolean isIdle); void remove(final String jobName); void remove(final TaskContext taskContext); boolean isJobRunning(final String jobName); boolean isTaskRunning(final TaskContext.MetaInfo metaInfo); Collection<TaskContext> getRunningTasks(final String jobName); Map<String, Set<TaskContext>> getAllRunningTasks(); Set<TaskContext> getAllRunningDaemonTasks(); void addMapping(final String taskId, final String hostname); String popMapping(final String taskId); void clear(); }### Answer: @Test public void assertIsJobRunning() { Assert.assertTrue(runningService.isJobRunning("test_job")); }
### Question: RunningService { public boolean isTaskRunning(final TaskContext.MetaInfo metaInfo) { for (TaskContext each : getRunningTasks(metaInfo.getJobName())) { if (each.getMetaInfo().equals(metaInfo)) { return true; } } return false; } RunningService(final CoordinatorRegistryCenter regCenter); void start(); void add(final TaskContext taskContext); void updateIdle(final TaskContext taskContext, final boolean isIdle); void remove(final String jobName); void remove(final TaskContext taskContext); boolean isJobRunning(final String jobName); boolean isTaskRunning(final TaskContext.MetaInfo metaInfo); Collection<TaskContext> getRunningTasks(final String jobName); Map<String, Set<TaskContext>> getAllRunningTasks(); Set<TaskContext> getAllRunningDaemonTasks(); void addMapping(final String taskId, final String hostname); String popMapping(final String taskId); void clear(); }### Answer: @Test public void assertIsTaskRunning() { Assert.assertTrue(runningService.isTaskRunning(TaskContext.MetaInfo.from(TaskNode.builder().build().getTaskNodePath()))); } @Test public void assertIsTaskNotRunning() { Assert.assertFalse(runningService.isTaskRunning(TaskContext.MetaInfo.from(TaskNode.builder().shardingItem(2).build().getTaskNodePath()))); }
### Question: RunningNode { static String getRunningJobNodePath(final String jobName) { return String.format(RUNNING_JOB, jobName); } }### Answer: @Test public void assertGetRunningJobNodePath() { Assert.assertThat(RunningNode.getRunningJobNodePath("test_job"), Is.is("/state/running/test_job")); } @Test public void assertGetRunningJobNodePath() { assertThat(RunningNode.getRunningJobNodePath("test_job"), is("/state/running/test_job")); }
### Question: RunningNode { static String getRunningTaskNodePath(final String taskMetaInfo) { return String.format(RUNNING_TASK, TaskContext.MetaInfo.from(taskMetaInfo).getJobName(), taskMetaInfo); } }### Answer: @Test public void assertGetRunningTaskNodePath() { String nodePath = TaskNode.builder().build().getTaskNodePath(); Assert.assertThat(RunningNode.getRunningTaskNodePath(nodePath), Is.is("/state/running/test_job/" + nodePath)); }
### Question: DisableAppNode { static String getDisableAppNodePath(final String appName) { return String.format(DISABLE_APP, appName); } }### Answer: @Test public void assertGetDisableAppNodePath() { Assert.assertThat(DisableAppNode.getDisableAppNodePath("test_app0000000001"), Is.is("/state/disable/app/test_app0000000001")); } @Test public void assertGetDisableAppNodePath() { assertThat(DisableAppNode.getDisableAppNodePath("test_app0000000001"), is("/state/disable/app/test_app0000000001")); }
### Question: DisableAppService { public void add(final String appName) { if (regCenter.getNumChildren(DisableAppNode.ROOT) > env.getFrameworkConfiguration().getJobStateQueueSize()) { log.warn("Cannot add disable app, caused by read state queue size is larger than {}.", env.getFrameworkConfiguration().getJobStateQueueSize()); return; } String disableAppNodePath = DisableAppNode.getDisableAppNodePath(appName); if (!regCenter.isExisted(disableAppNodePath)) { regCenter.persist(disableAppNodePath, appName); } } DisableAppService(final CoordinatorRegistryCenter regCenter); void add(final String appName); void remove(final String appName); boolean isDisabled(final String appName); }### Answer: @Test public void assertAdd() { disableAppService.add("test_app"); Mockito.verify(regCenter).isExisted("/state/disable/app/test_app"); Mockito.verify(regCenter).persist("/state/disable/app/test_app", "test_app"); } @Test public void assertAdd() { disableAppService.add("test_app"); verify(regCenter).isExisted("/state/disable/app/test_app"); verify(regCenter).persist("/state/disable/app/test_app", "test_app"); }