src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
ForwardSecrecyUtil { public static void init() { hexToIdentifier = new ConcurrentHashMap<String, ForwardSecrecyBlackList>(); ForwardSecrecyBlackList[] list = ForwardSecrecyBlackList.class.getEnumConstants(); for(ForwardSecrecyBlackList item : list) { hexToIdentifier.put(item.toString(), item); } } static void init(); static boolean containsKey(String cipherHex); static ForwardSecrecyBlackList getCipherIdentifier(String cipherHex); }
@Test public void testInit() { ForwardSecrecyUtil.init(); }
ImageHelper { public static BufferedImage getImageFromByte(byte[] array){ InputStream instream = new ByteArrayInputStream(array); String imageType = getImageType(array); ImageDecoder dec = ImageCodec.createImageDecoder(imageType, instream, null); BufferedImage image = null; FileOutputStream fos=null; try { File logFile = new File(Util.getVideoOptimizerLibrary() + Util.FILE_SEPARATOR +THIRDP_LOG); logFile.createNewFile(); fos = new FileOutputStream(logFile,false); } catch (IOException ioe) { Logger.error("Failed to create a log file", ioe); } System.setErr(new PrintStream(fos)); try { RenderedImage renderedImg; renderedImg = dec.decodeAsRenderedImage(0); RenderedImage rendering = new NullOpImage(renderedImg, null, null, OpImage.OP_IO_BOUND); image = convertRenderedImage(rendering); } catch (ImagingException exp) { setImageDecoderStatus(false); } catch (EOFException eof) { setImageDecoderStatus(false); } catch (IOException ioe) { setImageDecoderStatus(false); } System.setErr(System.err); return image; } static void convertImage(RawImage rawImage, BufferedImage image); static BufferedImage resize(BufferedImage image, int targetWidth, int targetHeight); static BufferedImage getImageFromByte(byte[] array); static String getImageType(byte[] array); static BufferedImage convertRenderedImage(RenderedImage img); static BufferedImage rorateImage(BufferedImage image, int angle); static BufferedImage rotate90DegreeRight(BufferedImage img); static BufferedImage createImage(int width, int height); static String extractFullNameFromRRInfo(HttpRequestResponseInfo hrri); static boolean isImageDecoderStatus(); static void setImageDecoderStatus(boolean imageDecoderStatus); static boolean imageDecoderStatus; }
@Test public void testGetImageFromByte() throws IOException{ BufferedImage image = ImageHelper.getImageFromByte(imagedata); assertEquals(10, image.getWidth()); assertEquals(10, image.getWidth()); }
ImageHelper { public static BufferedImage resize(BufferedImage image, int targetWidth, int targetHeight){ int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage result = image; BufferedImage tmp = new BufferedImage(targetWidth, targetHeight, imageType); Object hint = RenderingHints.VALUE_INTERPOLATION_BILINEAR; Graphics2D g2 = tmp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint); g2.drawImage(image, 0, 0, targetWidth, targetHeight, 0, 0, image.getWidth(), image.getHeight(), null); g2.dispose(); result = tmp; return result; } static void convertImage(RawImage rawImage, BufferedImage image); static BufferedImage resize(BufferedImage image, int targetWidth, int targetHeight); static BufferedImage getImageFromByte(byte[] array); static String getImageType(byte[] array); static BufferedImage convertRenderedImage(RenderedImage img); static BufferedImage rorateImage(BufferedImage image, int angle); static BufferedImage rotate90DegreeRight(BufferedImage img); static BufferedImage createImage(int width, int height); static String extractFullNameFromRRInfo(HttpRequestResponseInfo hrri); static boolean isImageDecoderStatus(); static void setImageDecoderStatus(boolean imageDecoderStatus); static boolean imageDecoderStatus; }
@Test public void resizeTest(){ BufferedImage img = new BufferedImage(256, 128, BufferedImage.TYPE_INT_ARGB); BufferedImage newimg = ImageHelper.resize(img, 50, 40); assertEquals(50, newimg.getWidth()); assertEquals(40, newimg.getHeight()); }
ImageHelper { public static BufferedImage rorateImage(BufferedImage image, int angle){ AffineTransform tx = new AffineTransform(); int x = image.getWidth() / 2; int y = image.getHeight() / 2; tx.translate(y, x); tx.rotate(Math.toRadians(angle)); tx.translate(-x, -y); AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR); image = op.filter(image, null); return image; } static void convertImage(RawImage rawImage, BufferedImage image); static BufferedImage resize(BufferedImage image, int targetWidth, int targetHeight); static BufferedImage getImageFromByte(byte[] array); static String getImageType(byte[] array); static BufferedImage convertRenderedImage(RenderedImage img); static BufferedImage rorateImage(BufferedImage image, int angle); static BufferedImage rotate90DegreeRight(BufferedImage img); static BufferedImage createImage(int width, int height); static String extractFullNameFromRRInfo(HttpRequestResponseInfo hrri); static boolean isImageDecoderStatus(); static void setImageDecoderStatus(boolean imageDecoderStatus); static boolean imageDecoderStatus; }
@Test public void rorateImageTest(){ BufferedImage img = new BufferedImage(256, 128, BufferedImage.TYPE_INT_ARGB); BufferedImage newimg = ImageHelper.rorateImage(img, 90); assertEquals(128, newimg.getWidth()); assertEquals(256, newimg.getHeight()); }
ImageHelper { public static BufferedImage rotate90DegreeRight(BufferedImage img) { int w = img.getWidth(); int h = img.getHeight(); BufferedImage rot = new BufferedImage(h, w, BufferedImage.TYPE_INT_RGB); double theta = Math.PI / 2; AffineTransform xform = new AffineTransform(); xform.translate(0.5*h, 0.5*w); xform.rotate(theta); xform.translate(-0.5*w, -0.5*h); Graphics2D g = (Graphics2D) rot.createGraphics(); g.drawImage(img, xform, null); g.dispose(); return rot; } static void convertImage(RawImage rawImage, BufferedImage image); static BufferedImage resize(BufferedImage image, int targetWidth, int targetHeight); static BufferedImage getImageFromByte(byte[] array); static String getImageType(byte[] array); static BufferedImage convertRenderedImage(RenderedImage img); static BufferedImage rorateImage(BufferedImage image, int angle); static BufferedImage rotate90DegreeRight(BufferedImage img); static BufferedImage createImage(int width, int height); static String extractFullNameFromRRInfo(HttpRequestResponseInfo hrri); static boolean isImageDecoderStatus(); static void setImageDecoderStatus(boolean imageDecoderStatus); static boolean imageDecoderStatus; }
@Test public void rorate90ImageTest(){ BufferedImage img = new BufferedImage(256, 128, BufferedImage.TYPE_INT_ARGB); BufferedImage newimg = ImageHelper.rotate90DegreeRight(img); assertEquals(128, newimg.getWidth()); assertEquals(256, newimg.getHeight()); }
ImageHelper { public static BufferedImage convertRenderedImage(RenderedImage img) { if (img instanceof BufferedImage) { return (BufferedImage)img; } ColorModel cm = img.getColorModel(); int width = img.getWidth(); int height = img.getHeight(); WritableRaster raster = cm.createCompatibleWritableRaster(width, height); boolean isAlphaPremultiplied = cm.isAlphaPremultiplied(); Hashtable<String, Object> properties = new Hashtable<>(); String[] keys = img.getPropertyNames(); if (keys!=null) { for (int i = 0; i < keys.length; i++) { properties.put(keys[i], img.getProperty(keys[i])); } } BufferedImage result = new BufferedImage(cm, raster, isAlphaPremultiplied, properties); img.copyData(raster); return result; } static void convertImage(RawImage rawImage, BufferedImage image); static BufferedImage resize(BufferedImage image, int targetWidth, int targetHeight); static BufferedImage getImageFromByte(byte[] array); static String getImageType(byte[] array); static BufferedImage convertRenderedImage(RenderedImage img); static BufferedImage rorateImage(BufferedImage image, int angle); static BufferedImage rotate90DegreeRight(BufferedImage img); static BufferedImage createImage(int width, int height); static String extractFullNameFromRRInfo(HttpRequestResponseInfo hrri); static boolean isImageDecoderStatus(); static void setImageDecoderStatus(boolean imageDecoderStatus); static boolean imageDecoderStatus; }
@Test public void convertRenderedImageTest(){ RenderedImage renderimage = new BufferedImage(100,100,BufferedImage.TYPE_INT_ARGB); BufferedImage newimage = ImageHelper.convertRenderedImage(renderimage); assertTrue(newimage instanceof BufferedImage); }
RootedAndroidCollectorImpl implements IDataCollector, IVideoImageSubscriber { @Override public StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, String password) { return this.startCollector(isCommandLine, folderToSaveTrace, videoOption, true, null, null, password); } int getMilliSecondsForTimeout(); @Override String getName(); @Override void addDeviceStatusSubscriber(IDeviceStatus devicestatus); @Override void addVideoImageSubscriber(IVideoImageSubscriber subscriber); @Override int getMajorVersion(); @Override String getMinorVersion(); @Override DataCollectorType getType(); @Override boolean isRunning(); @Override String[] getLog(); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, String password); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, boolean isLiveViewVideo, String deviceId, Hashtable<String, Object> extraParams, String password); @Override void timeOutShutdown(); @Override void haltCollectorInDevice(); @Override boolean isTrafficCaptureRunning(int seconds); void startVideoCapture(); @Override StatusResult stopCollector(); @Override void receiveImage(BufferedImage videoimage); @Override String getPassword(); @Override boolean setPassword(String requestPassword); @Override String[] getDeviceSerialNumber(StatusResult status); @Override IAroDevice[] getDevices(StatusResult status); @Override boolean isDeviceDataPulled(); }
@Test public void teststartCollector_returnIsErrorCode200() throws Exception { when(filemanager.directoryExist(any(String.class))).thenReturn(true); when(adbservice.getConnectedDevices()).thenThrow(new IOException("AndroidDebugBridge failed to start")); StatusResult testResult = rootedAndroidCollectorImpl.startCollector(true, "", VideoOption.NONE, null); assertEquals(200, testResult.getError().getCode()); } @Ignore @Test public void teststartCollector_returnIsErrorCode201() { when(filemanager.directoryExist(any(String.class))).thenReturn(true); IDevice mockDevice = mock(IDevice.class); when(mockDevice.isEmulator()).thenReturn(false); IDevice[] devlist = { mockDevice }; when(mockDevice.getSerialNumber()).thenReturn("abc"); try { when(adbservice.getConnectedDevices()).thenReturn(devlist); } catch (Exception e) { e.printStackTrace(); } try { when(androidev.isAndroidRooted(any(IDevice.class))).thenReturn(true); } catch (Exception e) { e.printStackTrace(); } when(android.checkPackageExist(any(IDevice.class), any(String.class))).thenReturn(false); StatusResult testResult = rootedAndroidCollectorImpl.startCollector(true, "", VideoOption.NONE, false, "abc", null, null); assertEquals(201, testResult.getError().getCode()); } @Test public void teststartCollector_returnIsErrorCode203() { when(filemanager.directoryExist(any(String.class))).thenReturn(true); IDevice[] devlist = {}; try { when(adbservice.getConnectedDevices()).thenReturn(devlist); } catch (Exception e) { e.printStackTrace(); } StatusResult testResult = rootedAndroidCollectorImpl.startCollector(true, "", VideoOption.NONE, false, "abc", null, null); assertEquals(203, testResult.getError().getCode()); } @Test public void teststartCollector_returnIsErrorCode204() { when(filemanager.directoryExist(any(String.class))).thenReturn(true); IDevice mockDevice = mock(IDevice.class); IDevice[] devlist = { mockDevice }; when(mockDevice.getSerialNumber()).thenReturn("abc"); try { when(adbservice.getConnectedDevices()).thenReturn(devlist); } catch (Exception e) { e.printStackTrace(); } StatusResult testResult = rootedAndroidCollectorImpl.startCollector(true, "", VideoOption.NONE, false, "cde", null, null); assertEquals(204, testResult.getError().getCode()); } @Ignore @Test public void teststartCollector_resultIsErrorCode205() { when(filemanager.directoryExist(any(String.class))).thenReturn(true); IDevice mockDevice = mock(IDevice.class); when(mockDevice.isEmulator()).thenReturn(true); IDevice[] devlist = { mockDevice }; when(mockDevice.getSerialNumber()).thenReturn("abc"); try { when(adbservice.getConnectedDevices()).thenReturn(devlist); } catch (Exception e) { e.printStackTrace(); } try { when(androidev.isAndroidRooted(any(IDevice.class))).thenReturn(true); } catch (Exception e) { e.printStackTrace(); } when(android.isSDCardEnoughSpace(any(IDevice.class), any(long.class))).thenReturn(false); StatusResult testResult = rootedAndroidCollectorImpl.startCollector(true, "", VideoOption.NONE, false, "abc", null, null); assertEquals(205, testResult.getError().getCode()); } @Ignore @Test public void teststartCollector_returnIsErrorCode206() { when(filemanager.directoryExist(any(String.class))).thenReturn(true); IDevice mockDevice = mock(IDevice.class); IDevice[] devlist = { mockDevice }; when(mockDevice.getSerialNumber()).thenReturn("abc"); try { when(adbservice.getConnectedDevices()).thenReturn(devlist); } catch (Exception e) { e.printStackTrace(); } try { when(androidev.isAndroidRooted(any(IDevice.class))).thenReturn(true); } catch (Exception e) { e.printStackTrace(); } when(android.checkTcpDumpRunning(any(IDevice.class))).thenReturn(true); StatusResult testResult = rootedAndroidCollectorImpl.startCollector(true, "", VideoOption.NONE, false, "abc", null, null); assertEquals(206, testResult.getError().getCode()); } @Test public void teststartCollector_returnIsErrorCode207() { when(filemanager.directoryExist(any(String.class))).thenReturn(false); StatusResult testResult = rootedAndroidCollectorImpl.startCollector(true, "", VideoOption.NONE, false, "abc", null, null); assertEquals(207, testResult.getError().getCode()); } @Ignore @Test public void teststartCollector_returnIsErrorCode209() { when(filemanager.directoryExist(any(String.class))).thenReturn(true); IDevice mockDevice = mock(IDevice.class); when(mockDevice.isEmulator()).thenReturn(true); IDevice[] devlist = { mockDevice }; when(mockDevice.getSerialNumber()).thenReturn("abc"); try { when(adbservice.getConnectedDevices()).thenReturn(devlist); } catch (Exception e) { e.printStackTrace(); } try { when(androidev.isAndroidRooted(any(IDevice.class))).thenReturn(true); } catch (Exception e) { e.printStackTrace(); } when(android.isSDCardEnoughSpace(any(IDevice.class), any(long.class))).thenReturn(true); when(filemanager.fileExist(any(String.class))).thenReturn(true); when(android.pushFile(any(IDevice.class), any(String.class), any(String.class))).thenReturn(false); StatusResult testResult = rootedAndroidCollectorImpl.startCollector(true, "", VideoOption.NONE, false, "abc", null, null); assertEquals(209, testResult.getError().getCode()); } @Ignore @Test public void teststartCollector_returnIsErrorCode210() { when(filemanager.directoryExist(any(String.class))).thenReturn(true); IDevice mockDevice = mock(IDevice.class); when(mockDevice.isEmulator()).thenReturn(false); IDevice[] devlist = { mockDevice }; when(mockDevice.getSerialNumber()).thenReturn("abc"); try { when(adbservice.getConnectedDevices()).thenReturn(devlist); } catch (Exception e) { e.printStackTrace(); } try { when(androidev.isAndroidRooted(any(IDevice.class))).thenReturn(true); } catch (Exception e) { e.printStackTrace(); } when(android.checkPackageExist(any(IDevice.class), any(String.class))).thenReturn(true); when(filemanager.fileExist(any(String.class))).thenReturn(true); String[] testarray = { "does not exist" }; when(android.getShellReturn(any(IDevice.class), any(String.class))).thenReturn(testarray); StatusResult testResult = rootedAndroidCollectorImpl.startCollector(true, "", VideoOption.NONE, false, "abc", null, null); assertEquals(210, testResult.getError().getCode()); } @Ignore @Test public void teststartCollector_returnIsErrorCode212() { when(filemanager.directoryExist(any(String.class))).thenReturn(true); IDevice mockDevice = mock(IDevice.class); when(mockDevice.isEmulator()).thenReturn(true); IDevice[] devlist = { mockDevice }; when(mockDevice.getSerialNumber()).thenReturn("abc"); try { when(adbservice.getConnectedDevices()).thenReturn(devlist); } catch (Exception e) { e.printStackTrace(); } try { when(androidev.isAndroidRooted(any(IDevice.class))).thenReturn(true); } catch (Exception e) { e.printStackTrace(); } when(android.isSDCardEnoughSpace(any(IDevice.class), any(long.class))).thenReturn(true); when(filemanager.fileExist(any(String.class))).thenReturn(true); when(extractor.extractFiles(any(String.class), any(String.class), any(ClassLoader.class))).thenReturn(true); when(android.pushFile(any(IDevice.class), any(String.class), any(String.class))).thenReturn(true); when(android.setExecutePermission(any(IDevice.class), any(String.class))).thenReturn(false); StatusResult testResult = rootedAndroidCollectorImpl.startCollector(true, "", VideoOption.NONE, false, "abc", null, null); assertEquals(212, testResult.getError().getCode()); } @Ignore @Test public void teststartCollector_returnIsErrorCode213() { when(filemanager.directoryExist(any(String.class))).thenReturn(true); IDevice mockDevice = mock(IDevice.class); IDevice[] devlist = { mockDevice }; when(mockDevice.getSerialNumber()).thenReturn("abc"); try { when(adbservice.getConnectedDevices()).thenReturn(devlist); } catch (Exception e) { e.printStackTrace(); } StatusResult testResult = rootedAndroidCollectorImpl.startCollector(true, "", VideoOption.NONE, false, "abc", null, null); assertEquals(213, testResult.getError().getCode()); } @Ignore @Test public void teststartCollector_returnIsSuccess() { when(filemanager.directoryExist(any(String.class))).thenReturn(true); IDevice mockDevice = mock(IDevice.class); when(mockDevice.isEmulator()).thenReturn(true); IDevice[] devlist = { mockDevice }; when(mockDevice.getSerialNumber()).thenReturn("abc"); try { when(adbservice.getConnectedDevices()).thenReturn(devlist); } catch (Exception e) { e.printStackTrace(); } try { when(androidev.isAndroidRooted(any(IDevice.class))).thenReturn(true); } catch (Exception e) { e.printStackTrace(); } when(android.isSDCardEnoughSpace(any(IDevice.class), any(long.class))).thenReturn(true); when(filemanager.fileExist(any(String.class))).thenReturn(true); when(extractor.extractFiles(any(String.class), any(String.class), any(ClassLoader.class))).thenReturn(true); when(android.pushFile(any(IDevice.class), any(String.class), any(String.class))).thenReturn(true); when(android.setExecutePermission(any(IDevice.class), any(String.class))).thenReturn(true); when(android.checkTcpDumpRunning(any(IDevice.class))).thenReturn(false).thenReturn(true); StatusResult testResult = rootedAndroidCollectorImpl.startCollector(true, "", VideoOption.NONE, false, "abc", null, null); assertEquals(true, testResult.isSuccess()); } @Ignore @Test public void teststartCollector_ThrowException() throws TimeoutException, AdbCommandRejectedException, IOException { when(filemanager.directoryExist(any(String.class))).thenReturn(true); IDevice mockDevice = mock(IDevice.class); IDevice[] devlist = { mockDevice }; when(mockDevice.getSerialNumber()).thenReturn("abc"); doThrow(new TimeoutException()).when(mockDevice).createForward(any(int.class), any(int.class)); try { when(adbservice.getConnectedDevices()).thenReturn(devlist); } catch (Exception e) { e.printStackTrace(); } try { when(androidev.isAndroidRooted(any(IDevice.class))).thenReturn(true); } catch (Exception e) { e.printStackTrace(); } StatusResult testResult = rootedAndroidCollectorImpl.startCollector(true, "", VideoOption.NONE, false, "abc", null, null); assertEquals(201, testResult.getError().getCode()); } @Test public void testdirectoryExists() { when(filemanager.directoryExist(any(String.class))).thenReturn(true); when(filemanager.directoryExistAndNotEmpty(any(String.class))).thenReturn(true); StatusResult result = rootedAndroidCollectorImpl.startCollector(true, "", VideoOption.LREZ, false, "abc", null, null); assertEquals(false, result.isSuccess()); }
ImageHelper { public static BufferedImage createImage(int width, int height) { BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); return bimage; } static void convertImage(RawImage rawImage, BufferedImage image); static BufferedImage resize(BufferedImage image, int targetWidth, int targetHeight); static BufferedImage getImageFromByte(byte[] array); static String getImageType(byte[] array); static BufferedImage convertRenderedImage(RenderedImage img); static BufferedImage rorateImage(BufferedImage image, int angle); static BufferedImage rotate90DegreeRight(BufferedImage img); static BufferedImage createImage(int width, int height); static String extractFullNameFromRRInfo(HttpRequestResponseInfo hrri); static boolean isImageDecoderStatus(); static void setImageDecoderStatus(boolean imageDecoderStatus); static boolean imageDecoderStatus; }
@Test public void createImageTest(){ BufferedImage newimage = ImageHelper.createImage(10, 10); assertEquals(10, newimage.getWidth()); assertEquals(10, newimage.getWidth()); }
WeakCipherUtil { public static boolean containsKey(String cipherHex) { return hexToIdentifier.containsKey(cipherHex); } static void init(); static boolean containsKey(String cipherHex); static WeakCipherBlackList getCipherIdentifier(String cipherHex); }
@Test public void testContainsKey() { assertTrue(WeakCipherUtil.containsKey("0x0006")); } @Test public void testNotContainsKey() { assertNotEquals(true, WeakCipherUtil.containsKey("0x0004")); }
WeakCipherUtil { public static WeakCipherBlackList getCipherIdentifier(String cipherHex) { return hexToIdentifier.get(cipherHex); } static void init(); static boolean containsKey(String cipherHex); static WeakCipherBlackList getCipherIdentifier(String cipherHex); }
@Test public void testGetCipherIdentifier() { WeakCipherBlackList weakCipher = WeakCipherUtil.getCipherIdentifier("0x0006"); assertEquals(WeakCipherBlackList.RSA_EXPORT_WITH_RC2_CBC_40_MD5, weakCipher); }
WeakCipherUtil { public static void init() { hexToIdentifier = new ConcurrentHashMap<String, WeakCipherBlackList>(); WeakCipherBlackList[] list = WeakCipherBlackList.class.getEnumConstants(); for(WeakCipherBlackList weakCipher : list) { hexToIdentifier.put(weakCipher.toString(), weakCipher); } } static void init(); static boolean containsKey(String cipherHex); static WeakCipherBlackList getCipherIdentifier(String cipherHex); }
@Test public void testInit() { WeakCipherUtil.init(); }
StringParse implements IStringParse { public static String findLabeledDataFromString(String fieldSearch, String sData) { String value = ""; int pos = sData.indexOf(fieldSearch); if (pos != -1) { value = new Scanner(sData.substring(pos + fieldSearch.length())).useDelimiter("[^\\d]+").next(); } return value; } static Double findLabeledDoubleFromString(String fieldSearch, byte[] data); static String findLabeledDataFromString(String fieldSearch, String sData); static String findLabeledDataFromString(String fieldSearch, String delimeter, String sData); static String findLabeledDataFromString(String fieldSearch, byte[] data); static String findLabeledDataFromString(String fieldSearch, String delimeter, byte[] data); static Double findLabeledDoubleFromString(String fieldSearch, String sData); static Double findLabeledDoubleFromString(String fieldSearch, String delimeter, String sData); static Double stringToDouble(String sValue); static Double stringToDouble(String strValue, double defaultValue); static String subString(String name, char mark1, char mark2); @Override String[] parse(String targetString, String regex); @Override String[] parse(String targetString, Pattern pattern); static int[] getStringPositions(String inputStr, String matchStr); }
@Test public void testFindLabeledDataFromString_whenNoDelimiter_thenReturnsValue() throws Exception { Assertions.assertThat(StringParse.findLabeledDataFromString("EXTINF:", " 6: #EXTINF:9.002666, no desc")) .isEqualTo("9") ; }
StringParse implements IStringParse { public static Double findLabeledDoubleFromString(String fieldSearch, byte[] data) { return findLabeledDoubleFromString(fieldSearch, new String(data)); } static Double findLabeledDoubleFromString(String fieldSearch, byte[] data); static String findLabeledDataFromString(String fieldSearch, String sData); static String findLabeledDataFromString(String fieldSearch, String delimeter, String sData); static String findLabeledDataFromString(String fieldSearch, byte[] data); static String findLabeledDataFromString(String fieldSearch, String delimeter, byte[] data); static Double findLabeledDoubleFromString(String fieldSearch, String sData); static Double findLabeledDoubleFromString(String fieldSearch, String delimeter, String sData); static Double stringToDouble(String sValue); static Double stringToDouble(String strValue, double defaultValue); static String subString(String name, char mark1, char mark2); @Override String[] parse(String targetString, String regex); @Override String[] parse(String targetString, Pattern pattern); static int[] getStringPositions(String inputStr, String matchStr); }
@Test public void testFindLabeledDoubleFromString() throws Exception { Assertions.assertThat(StringParse.findLabeledDoubleFromString("EXTINF:", ",", " 6: #EXTINF:9.002665, no desc")) .isEqualTo(9.002665) ; }
Compressor implements Runnable { public String encode(String zipPath) throws IOException { String zip64 = zipPath + "64"; Encoder encoder = Base64.getEncoder(); try (FileOutputStream fos = new FileOutputStream(zip64); FileInputStream fis = new FileInputStream(new File(zipPath))) { int size; final int capacity = 3 * 1024 * 1024; byte[] buffer = new byte[capacity]; while ((size = fis.read(buffer)) != -1) { if(size < capacity) { fos.write(encoder.encode(Arrays.copyOfRange(buffer, 0, size))); } else { fos.write(encoder.encode(buffer)); } } fos.flush(); } return zip64; } void prepare(IResultSubscriber subscriber, String targetFolder, String[] exclude, String fileName); @Override void run(); void setSubscriber(IResultSubscriber subscriber); String zipBase64(); String encode(String zipPath); String zipFolder(String targetFolder, String[] exclude, String zippedName); }
@Test public void testEncode() throws Exception { Files.write(TEMP_FILE, new byte[] {'1', '2', '3', '4', '5', '6'}); String zipPath = TEMP_FILE.toString(); String z64Path = zipPath + "64"; compressor.encode(zipPath); assertEquals("MTIzNDU2", Files.readAllLines(Paths.get(z64Path)).get(0)); } @Test public void testEncodeEmpty() throws Exception { Files.write(TEMP_FILE, new byte[] {}); String zipPath = TEMP_FILE.toString(); String z64Path = zipPath + "64"; compressor.encode(zipPath); assertEquals(0, Files.readAllLines(Paths.get(z64Path)).size()); }
PeriodicTransferImpl implements IBestPractice { @Override public AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata) { periodicCount = 0; diffPeriodicCount = 0; minimumPeriodicRepeatTime = 0.0; PeriodicTransferResult result = new PeriodicTransferResult(); diagnosisPeriodicRequest(tracedata.getSessionlist(), tracedata.getBurstCollectionAnalysisData().getBurstCollection(), tracedata.getProfile()); calculatePeriodicRepeatTime(tracedata.getBurstCollectionAnalysisData().getBurstCollection()); if(this.minimumPeriodicRepeatTime == 0.0){ result.setResultType(BPResultType.PASS); result.setResultText(textResultPass); }else{ result.setResultType(BPResultType.FAIL); String text = MessageFormat.format( diffPeriodicCount > 1 ? this.textResults : this.textResult, this.diffPeriodicCount, this.periodicCount, this.minimumPeriodicRepeatTime); result.setResultText(text); } result.setDiffPeriodicCount(diffPeriodicCount); result.setPeriodicCount(periodicCount); result.setMinimumPeriodicRepeatTime(minimumPeriodicRepeatTime); result.setAboutText(aboutText); result.setDetailTitle(detailTitle); result.setLearnMoreUrl(learnMoreUrl); result.setOverviewTitle(overviewTitle); result.setSelfTest(false); result.setExportAllIneffConnDesc(exportAllIneffConnDesc); result.setExportAllIneffConnRptDesc(exportAllIneffConnRptDesc); result.setExportAllIneffConnTimeDesc(exportAllIneffConnTimeDesc); return result; } @Override AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata); }
@Test public void runTest_AresultIsPass() { PacketAnalyzerResult tracedata01 = new PacketAnalyzerResult(); Date date = new Date(); List<Burst> burstCollection = new ArrayList<Burst>(); BurstCollectionAnalysisData burstcollectionAnalysisData = new BurstCollectionAnalysisData(); InetAddress remoteIP = null; InetAddress localIP = null; try { localIP = InetAddress.getLocalHost(); remoteIP = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } int remotePort = 80; int localPort = 80; byte[] d1 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 8, 0, 69, 0, 0, 52, -99, -87, 64, 0, 64, 6, -27, -25, 10, -27, 77, 114, 74, 125, 20, 95, -90, 2, 1, -69, -108, -18, 20, 87, -4, -110, -105, -88, -128, 16, 6, 88, 51, 24, 0, 0, 1, 1, 8, 10, -1, -1, -87, 50, 101, -15, -111, -73 }; Packet packet01 = new Packet(1, 1418242722L, 324000, 66, d1); byte[] d2 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 8, 0, 69, 0, 0, 52, 0, 0, 64, 0, 64, 6, -125, -111, 74, 125, 20, 95, 10, -27, 77, 114, 1, -69, -90, 2, 0, 0, 0, 0, -108, -18, 20, 87, -128, 4, 0, 0, 119, -98, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; Packet packet02 = new Packet(1, 1418242722L, 325000, 63, d2); PacketInfo packetInfo01 = new PacketInfo(packet01); PacketInfo packetInfo02 = new PacketInfo(packet02); packetInfo01.setTcpInfo(TcpInfo.TCP_ESTABLISH); packetInfo01.setTimestamp((double) date.getTime()); packetInfo02.setTcpInfo(TcpInfo.TCP_ACK); List<PacketInfo> packetlist = new ArrayList<PacketInfo>(); packetlist.add(packetInfo01); packetlist.add(packetInfo02); Burst burst01 = new Burst(packetlist); burst01.setFirstUplinkDataPacket(packetInfo01); burst01.setBurstInfo(BurstCategory.CLIENT_APP); burstCollection.add(burst01); Session session01 = new Session(localIP, remoteIP, remotePort, localPort, ""); session01.setUdpOnly(false); session01.setPackets(packetlist); HttpRequestResponseInfo httpRequestResponseInfo01 = new HttpRequestResponseInfo(); httpRequestResponseInfo01.setFirstDataPacket(packetInfo01); httpRequestResponseInfo01.setDirection(HttpDirection.REQUEST); httpRequestResponseInfo01.setHostName("yahoo.com"); httpRequestResponseInfo01.setObjName(""); List<HttpRequestResponseInfo> httpRequestResponseInfolist = new ArrayList<HttpRequestResponseInfo>(); httpRequestResponseInfolist.add(httpRequestResponseInfo01); session01.setRequestResponseInfo(httpRequestResponseInfolist); List<Session> sessionlist = new ArrayList<Session>(); sessionlist.add(session01); ProfileLTE profileLTE = new ProfileLTE(); profileLTE.setPeriodMinCycle(10.0); profileLTE.setPeriodCycleTol(1.0); profileLTE.setPeriodMinSamples(3); profileLTE.setCloseSpacedBurstThreshold(0.0); burstcollectionAnalysisData.setBurstCollection(burstCollection); tracedata01.setSessionlist(sessionlist); tracedata01.setBurstCollectionAnalysisData(burstcollectionAnalysisData); tracedata01.setProfile(profileLTE); AbstractBestPracticeResult result01 = periodicTransferImpl.runTest(tracedata01); assertEquals(BPResultType.PASS, result01.getResultType()); } @Test public void runTest_resultIsFail() { PacketAnalyzerResult tracedata = new PacketAnalyzerResult(); Profile3G profile3g = new Profile3G(); profile3g.setPeriodMinCycle(10.0); profile3g.setPeriodCycleTol(1.0); profile3g.setPeriodMinSamples(3); profile3g.setCloseSpacedBurstThreshold(-50.0); InetAddress remoteIP = null; InetAddress localIP = null; try { localIP = InetAddress.getLocalHost(); remoteIP = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } InetAddress remoteIP01 = null; try { remoteIP01 = InetAddress.getByName("google.com"); } catch (UnknownHostException e) { e.printStackTrace(); } int remotePort = 80; int localPort = 80; Session session01 = new Session(localIP, remoteIP, remotePort, localPort, ""); Session session02 = new Session(localIP, remoteIP01, remotePort, localPort, ""); byte[] d1 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 8, 0, 69, 0, 0, 52, -87, -63, 64, 0, 64, 6, 76, -121, 10, 120, 0, 1, 74, 125, -17, -123, -104, 53, 1, -69, 91, 8, 7, 120, 25, -21, 51, -84, -128, 16, 5, 123, 105, -6, 0, 0, 1, 1, 8, 10, -1, -1, -86, -80, 53, -38, -104, 57, 5, 7, 0, 6, 7 }; Packet packet01 = new Packet(1, 1418242726L, 234000, 50, d1); byte[] d2 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 8, 0, 69, 0, 0, 52, 0, 0, 64, 0, 64, 6, -125, -111, 74, 125, 20, 95, 10, -27, 77, 114, 1, -69, -90, 2, 0, 0, 0, 0, -108, -18, 20, 87, -128, 4, 0, 0, 119, -98, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; Packet packet02 = new Packet(1, 1418242722L, 325000, 50, d2); byte[] d3 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 8, 0, 69, 0, 0, 52, -97, 67, 64, 0, 64, 6, -28, 77, 10, -27, 77, 114, 74, 125, 20, 95, -58, -91, 1, -69, 22, 2, 7, 25, -69, -41, -92, -13, -128, 17, 8, 86, -98, -14, 0, 0, 1, 1, 8, 10, -1, -1, -87, 51, 96, 102, -56, 95 }; Packet packet03 = new Packet(1, 1418242722L, 325000, 50, d3); byte[] d4 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 8, 0, 69, 0, 0, 52, -97, 68, 64, 0, 64, 6, -28, 76, 10, -27, 77, 114, 74, 125, 20, 95, -58, -91, 1, -69, 22, 2, 7, 25, -69, -41, -92, -13, -128, 17, 8, 86, -98, -43, 0, 0, 1, 1, 8, 10, -1, -1, -87, 80, 96, 102, -56, 95 }; Packet packet04 = new Packet(1, 1418242722L, 625000, 50, d4); byte[] d5 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 8, 0, 69, 0, 0, 52, -97, 69, 64, 0, 64, 6, -28, 75, 10, -27, 77, 114, 74, 125, 20, 95, -58, -91, 1, -69, 22, 2, 7, 25, -69, -41, -92, -13, -128, 17, 8, 86, -98, -101, 0, 0, 1, 1, 8, 10, -1, -1, -87, -118, 96, 102, -56, 95 }; Packet packet05 = new Packet(1, 1418242723L, 226000, 50, d5); byte[] d6 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 8, 0, 69, 0, 0, 52, -97, 70, 64, 0, 64, 6, -28, 74, 10, -27, 77, 114, 74, 125, 20, 95, -58, -91, 1, -69, 22, 2, 7, 25, -69, -41, -92, -13, -128, 17, 8, 86, -98, 39, 0, 0, 1, 1, 8, 10, -1, -1, -87, -2, 96, 102, -56, 95 }; Packet packet06 = new Packet(1, 1418242724L, 328000, 50, d6); byte[] d7 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 8, 0, 69, 0, 0, 60, -87, -69, 64, 0, 64, 6, 76, -123, 10, 120, 0, 1, 74, 125, -17, -123, -104, 53, 1, -69, 91, 8, 3, -57, 0, 0, 0, 0, -96, 2, -1, -1, 96, 73, 0, 0, 2, 4, 5, -76, 4, 2, 8, 10, -1, -1, -86, 124, 0, 0, 0, 0, 1, 3, 3, 6 }; Packet packet07 = new Packet(1, 1418242725L, 730000, 50, d7); byte[] d8 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 8, 0, 69, 0, 0, 60, 0, 0, 64, 0, 64, 6, -10, 64, 74, 125, -17, -123, 10, 120, 0, 1, 1, -69, -104, 53, 25, -21, 49, 103, 91, 8, 3, -56, -96, 18, -1, -1, 72, 11, 0, 0, 2, 4, 5, -76, 4, 2, 8, 10, 53, -38, -105, 0, -1, -1, -86, 124, 1, 3, 3, 6 }; Packet packet08 = new Packet(1, 1418242725L, 731000, 50, d8); byte[] d9 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 8, 0, 69, 0, 0, 52, -87, -68, 64, 0, 64, 6, 76, -116, 10, 120, 0, 1, 74, 125, -17, -123, -104, 53, 1, -69, 91, 8, 3, -56, 25, -21, 49, 104, -128, 16, 5, 89, 113, 119, 0, 0, 1, 1, 8, 10, -1, -1, -86, -126, 53, -38, -105, 0 }; Packet packet09 = new Packet(1, 1418242725L, 731000, 50, d9); PacketInfo packetInfo01 = new PacketInfo(packet01); PacketInfo packetInfo02 = new PacketInfo(packet02); PacketInfo packetInfo03 = new PacketInfo(packet03); PacketInfo packetInfo04 = new PacketInfo(packet04); PacketInfo packetInfo05 = new PacketInfo(packet05); PacketInfo packetInfo06 = new PacketInfo(packet06); PacketInfo packetInfo07 = new PacketInfo(packet07); PacketInfo packetInfo08 = new PacketInfo(packet08); PacketInfo packetInfo09 = new PacketInfo(packet09); List<PacketInfo> packetlist01 = new ArrayList<PacketInfo>(); List<PacketInfo> packetlist02 = new ArrayList<PacketInfo>(); packetInfo01.setTcpInfo(TcpInfo.TCP_ESTABLISH); packetInfo02.setTcpInfo(TcpInfo.TCP_ACK); packetInfo01.setDir(PacketDirection.UPLINK); packetInfo02.setDir(PacketDirection.UPLINK); packetInfo03.setDir(PacketDirection.UPLINK); packetInfo04.setDir(PacketDirection.UPLINK); packetInfo05.setDir(PacketDirection.UPLINK); packetInfo06.setDir(PacketDirection.UPLINK); packetInfo07.setDir(PacketDirection.UPLINK); packetInfo08.setDir(PacketDirection.UPLINK); packetInfo01.setTimestamp(0.0); packetInfo02.setTimestamp(10.0); packetInfo03.setTimestamp(20.0); packetInfo04.setTimestamp(30.0); packetInfo05.setTimestamp(10.0); packetInfo06.setTimestamp(20.0); packetInfo07.setTimestamp(30.0); packetInfo08.setTimestamp(40.0); packetInfo09.setTimestamp(50.0); packetlist01.add(packetInfo01); packetlist01.add(packetInfo02); packetlist01.add(packetInfo03); packetlist01.add(packetInfo04); packetlist02.add(packetInfo05); packetlist02.add(packetInfo06); packetlist02.add(packetInfo07); packetlist02.add(packetInfo08); packetlist02.add(packetInfo09); session01.setUdpOnly(false); session01.setPackets(packetlist01); session02.setUdpOnly(false); session02.setPackets(packetlist02); HttpRequestResponseInfo httpRequestResponseInfo01 = new HttpRequestResponseInfo(); httpRequestResponseInfo01.setFirstDataPacket(packetInfo01); httpRequestResponseInfo01.setDirection(HttpDirection.REQUEST); httpRequestResponseInfo01.setHostName("yahoo.com"); httpRequestResponseInfo01.setObjName(""); HttpRequestResponseInfo httpRequestResponseInfo02 = new HttpRequestResponseInfo(); httpRequestResponseInfo02.setFirstDataPacket(packetInfo02); httpRequestResponseInfo02.setDirection(HttpDirection.REQUEST); httpRequestResponseInfo02.setHostName("google.com"); httpRequestResponseInfo02.setObjName(""); HttpRequestResponseInfo httpRequestResponseInfo03 = new HttpRequestResponseInfo(); httpRequestResponseInfo03.setFirstDataPacket(packetInfo04); httpRequestResponseInfo03.setDirection(HttpDirection.REQUEST); httpRequestResponseInfo03.setHostName("cnn.com"); httpRequestResponseInfo03.setObjName(""); List<HttpRequestResponseInfo> httpRequestResponseInfolist = new ArrayList<HttpRequestResponseInfo>(); httpRequestResponseInfolist.add(httpRequestResponseInfo01); httpRequestResponseInfolist.add(httpRequestResponseInfo02); httpRequestResponseInfolist.add(httpRequestResponseInfo02); httpRequestResponseInfolist.add(httpRequestResponseInfo03); session01.setRequestResponseInfo(httpRequestResponseInfolist); Burst burst01 = new Burst(packetlist01); burst01.setFirstUplinkDataPacket(packetInfo01); burst01.setBurstInfo(BurstCategory.CLIENT_APP); Burst burst02 = new Burst(packetlist01); burst02.setFirstUplinkDataPacket(packetInfo01); burst02.setBurstInfo(BurstCategory.PERIODICAL); Burst burst03 = new Burst(packetlist02); burst03.setFirstUplinkDataPacket(packetInfo02); burst03.setBurstInfo(BurstCategory.CLIENT_APP); Burst burst04 = new Burst(packetlist02); burst04.setFirstUplinkDataPacket(packetInfo02); burst04.setBurstInfo(BurstCategory.PERIODICAL); Burst burst05 = new Burst(packetlist02); burst05.setFirstUplinkDataPacket(packetInfo02); burst05.setBurstInfo(BurstCategory.CLIENT_APP); Burst burst06 = new Burst(packetlist01); burst06.setFirstUplinkDataPacket(packetInfo03); burst06.setBurstInfo(BurstCategory.PERIODICAL); Burst burst07 = new Burst(packetlist01); burst07.setBurstInfo(BurstCategory.CLIENT_APP); Burst burst08 = new Burst(packetlist02); burst08.setBurstInfo(BurstCategory.PERIODICAL); Burst burst09 = new Burst(packetlist02); burst09.setBurstInfo(BurstCategory.CLIENT_APP); Burst burst10 = new Burst(packetlist01); burst10.setBurstInfo(BurstCategory.PERIODICAL); List<Burst> burstCollection = new ArrayList<Burst>(); burstCollection.add(burst01); burstCollection.add(burst02); burstCollection.add(burst03); burstCollection.add(burst04); burstCollection.add(burst06); burstCollection.add(burst07); burstCollection.add(burst08); burstCollection.add(burst09); burstCollection.add(burst10); BurstCollectionAnalysisData burstcollectionAnalysisData = new BurstCollectionAnalysisData(); burstcollectionAnalysisData.setBurstCollection(burstCollection); List<Session> sessionlist = new ArrayList<Session>(); sessionlist.add(session01); sessionlist.add(session02); sessionlist.add(session01); sessionlist.add(session01); sessionlist.add(session01); sessionlist.add(session01); sessionlist.add(session01); sessionlist.add(session02); sessionlist.add(session01); tracedata.setSessionlist(sessionlist); tracedata.setBurstCollectionAnalysisData(burstcollectionAnalysisData); tracedata.setProfile(profile3g); AbstractBestPracticeResult result = periodicTransferImpl.runTest(tracedata); assertEquals(BPResultType.FAIL, result.getResultType()); }
ScreenRotationImpl implements IBestPractice { @Override public AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata) { ScreenRotationResult result = new ScreenRotationResult(); boolean passScreenRotation = true; double screenRotationBurstTime = 0.0; for(Burst burst:tracedata.getBurstCollectionAnalysisData().getBurstCollection()){ if(burst.getBurstCategory() == BurstCategory.SCREEN_ROTATION){ passScreenRotation = false; screenRotationBurstTime = burst.getBeginTime(); break; } } result.setScreenRotationBurstTime(screenRotationBurstTime); if(passScreenRotation){ result.setResultType(BPResultType.PASS); result.setResultText(textResultPass); }else{ result.setResultType(BPResultType.FAIL); result.setResultText(textResults); } result.setScreenRotationBurstTime(screenRotationBurstTime); result.setAboutText(aboutText); result.setDetailTitle(detailTitle); result.setLearnMoreUrl(learnMoreUrl); result.setOverviewTitle(overviewTitle); result.setExportAllScreenRotationDescPass(exportAllScreenRotationDescPass); result.setExportAllScreenRotationFailed(exportAllScreenRotationFailed); return result; } @Override AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata); }
@Test public void runTest_resIsNoErr_Fail() { tracedata = Mockito.mock(PacketAnalyzerResult.class); burstCollectionAnalysisData = Mockito.mock(BurstCollectionAnalysisData.class); burst01 = mock(Burst.class); Mockito.when(burst01.getBurstCategory()).thenReturn(BurstCategory.SCREEN_ROTATION); Mockito.when(burst01.getBeginTime()).thenReturn(1.0); List<Burst> burstCollection = new ArrayList<Burst>(); burstCollection.add(burst01); Mockito.when(tracedata.getBurstCollectionAnalysisData()).thenReturn(burstCollectionAnalysisData); Mockito.when(burstCollectionAnalysisData.getBurstCollection()).thenReturn(burstCollection); screenRotationImpl = (ScreenRotationImpl) context.getBean("screenRotation"); AbstractBestPracticeResult result = screenRotationImpl.runTest(tracedata); assertEquals(BPResultType.FAIL, result.getResultType()); } @Test public void runTest_resIsNoErr_Pass() { tracedata = Mockito.mock(PacketAnalyzerResult.class); burstCollectionAnalysisData = Mockito.mock(BurstCollectionAnalysisData.class); burst01 = mock(Burst.class); Mockito.when(burst01.getBurstCategory()).thenReturn(BurstCategory.UNKNOWN); Mockito.when(burst01.getBeginTime()).thenReturn(1.0); List<Burst> burstCollection = new ArrayList<Burst>(); burstCollection.add(burst01); Mockito.when(tracedata.getBurstCollectionAnalysisData()).thenReturn(burstCollectionAnalysisData); Mockito.when(burstCollectionAnalysisData.getBurstCollection()).thenReturn(burstCollection); screenRotationImpl = (ScreenRotationImpl) context.getBean("screenRotation"); AbstractBestPracticeResult result = screenRotationImpl.runTest(tracedata); assertEquals(BPResultType.PASS, result.getResultType()); }
ConnectionClosingImpl implements IBestPractice { @Override public AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata) { double wastedBurstEnergy = 0.0; boolean conClosingProbPassed = true; double tcpControlEnergy = 0; double tcpControlEnergyRatio = 0; double largestEnergyTime = 0.0; double maxEnergy = 0.0; double currentEnergy; if(tracedata.getBurstCollectionAnalysisData().getTotalEnergy() > 0){ for(Burst burst : tracedata.getBurstCollectionAnalysisData().getBurstCollection()){ if(burst.getBurstCategory() == BurstCategory.TCP_PROTOCOL){ currentEnergy = burst.getEnergy(); wastedBurstEnergy += burst.getEnergy(); if (currentEnergy > maxEnergy) { maxEnergy = currentEnergy; largestEnergyTime = burst.getBeginTime(); } } } double percentageWasted = wastedBurstEnergy / tracedata.getBurstCollectionAnalysisData().getTotalEnergy(); conClosingProbPassed = percentageWasted < 0.05; tcpControlEnergy = wastedBurstEnergy; tcpControlEnergyRatio = percentageWasted; } ConnectionClosingResult result = new ConnectionClosingResult(); if(!conClosingProbPassed){ result.setResultType(BPResultType.FAIL); NumberFormat nfo = NumberFormat.getInstance(); nfo.setMaximumFractionDigits(1); String text = MessageFormat.format(textResults, ApplicationConfig.getInstance().getAppShortName(), nfo.format(tcpControlEnergy), nfo.format(tcpControlEnergyRatio*100)); result.setResultText(text); }else{ result.setResultType(BPResultType.PASS); result.setResultText(textResultPass); } result.setWastedBurstEnergy(wastedBurstEnergy); result.setConClosingProb(conClosingProbPassed); result.setTcpControlEnergy(tcpControlEnergy); result.setTcpControlEnergyRatio(tcpControlEnergyRatio); result.setLargestEnergyTime(largestEnergyTime); result.setAboutText(aboutText); result.setDetailTitle(detailTitle); result.setLearnMoreUrl(learnMoreUrl); result.setOverviewTitle(overviewTitle); result.setExportAllConnClosingDesc(exportAllConnClosingDesc); return result; } @Override AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata); }
@Test public void runTest_resIsNoErrTypeIsFail(){ Mockito.when(burst01.getBurstCategory()).thenReturn(BurstCategory.TCP_PROTOCOL); Mockito.when(burst01.getEnergy()).thenReturn(1.0); Mockito.when(burst01.getBeginTime()).thenReturn(2.0); List<Burst> burstCollection = new ArrayList<Burst>(); burstCollection.add(burst01); Mockito.when(burstCollectionAnalysisData.getBurstCollection()).thenReturn(burstCollection); Mockito.when(burstCollectionAnalysisData.getTotalEnergy()).thenReturn(1.0); Mockito.when(tracedata.getBurstCollectionAnalysisData()).thenReturn(burstCollectionAnalysisData); connClsImpl = (ConnectionClosingImpl)context.getBean("connectionClosing"); AbstractBestPracticeResult result = connClsImpl.runTest(tracedata); assertEquals(BPResultType.FAIL, result.getResultType()); } @Test public void runTest_resIsNoErrTypeIsPass(){ Mockito.when(burstCollectionAnalysisData.getTotalEnergy()).thenReturn(0.0); Mockito.when(tracedata.getBurstCollectionAnalysisData()).thenReturn(burstCollectionAnalysisData); connClsImpl = (ConnectionClosingImpl)context.getBean("connectionClosing"); AbstractBestPracticeResult result = connClsImpl.runTest(tracedata); assertEquals(BPResultType.PASS, result.getResultType()); }
UsingCacheImpl implements IBestPractice { @Override public AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata) { UsingCacheResult result = new UsingCacheResult(); if(tracedata.getCacheAnalysis() == null){ return null; } double cacheHeaderRatio = 0.0; boolean usingCache = false; int validCount = 0; int noCacheHeadersCount = 0; PacketInfo noCacheHeaderFirstPacket = null; for(CacheEntry entry: tracedata.getCacheAnalysis().getDiagnosisResults()){ if(entry.getDiagnosis() != Diagnosis.CACHING_DIAG_REQUEST_NOT_FOUND && entry.getDiagnosis() != Diagnosis.CACHING_DIAG_INVALID_OBJ_NAME && entry.getDiagnosis() != Diagnosis.CACHING_DIAG_INVALID_REQUEST && entry.getDiagnosis() != Diagnosis.CACHING_DIAG_INVALID_RESPONSE ){ ++validCount; if (!entry.hasCacheHeaders()) { if (noCacheHeadersCount == 0) { noCacheHeaderFirstPacket = entry.getSessionFirstPacket(); } ++noCacheHeadersCount; } } } cacheHeaderRatio = validCount > 0 ? (100.0 * noCacheHeadersCount) / validCount : 0.0; usingCache = cacheHeaderRatio <= 10.0; if(usingCache){ result.setResultType(BPResultType.PASS); result.setResultText(textResultPass); }else{ result.setResultType(BPResultType.WARNING); String text = MessageFormat.format(textResults, ApplicationConfig.getInstance().getAppShortName(), NumberFormat.getIntegerInstance().format(cacheHeaderRatio)); result.setResultText(text); } result.setCacheHeaderRatio(cacheHeaderRatio); result.setNoCacheHeaderFirstPacket(noCacheHeaderFirstPacket); result.setAboutText(aboutText); result.setDetailTitle(detailTitle); result.setLearnMoreUrl(learnMoreUrl); result.setOverviewTitle(overviewTitle); result.setExportAllCacheConPct(exportAllCacheConPct); return result; } @Override AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata); }
@Test public void runTest_(){ List<CacheEntry> diagnosisResults = new ArrayList<CacheEntry>(); Mockito.when(entryArray[0].getDiagnosis()).thenReturn(Diagnosis.CACHING_DIAG_REQUEST_NOT_FOUND); Mockito.when(entryArray[1].getDiagnosis()).thenReturn(Diagnosis.CACHING_DIAG_INVALID_OBJ_NAME); Mockito.when(entryArray[2].getDiagnosis()).thenReturn(Diagnosis.CACHING_DIAG_INVALID_REQUEST); Mockito.when(entryArray[3].getDiagnosis()).thenReturn(Diagnosis.CACHING_DIAG_INVALID_RESPONSE); for(int i = 0; i < 4; i++){ diagnosisResults.add(entryArray[i]); } Mockito.when(cacheAnalysis.getDiagnosisResults()).thenReturn(diagnosisResults); Mockito.when(tracedata.getCacheAnalysis()).thenReturn(cacheAnalysis); AbstractBestPracticeResult testResult = usingCacheImpl.runTest(tracedata); assertEquals(BPResultType.PASS, testResult.getResultType()); } @Test public void runTest_Fail(){ List<CacheEntry> diagnosisResults = new ArrayList<CacheEntry>(); Mockito.when(entryArray[0].getDiagnosis()).thenReturn(Diagnosis.CACHING_DIAG_NOT_CACHABLE); Mockito.when(entryArray[0].hasCacheHeaders()).thenReturn(true); Mockito.when(entryArray[1].getDiagnosis()).thenReturn(Diagnosis.CACHING_DIAG_CACHE_MISSED); Mockito.when(entryArray[1].hasCacheHeaders()).thenReturn(false); Mockito.when(entryArray[1].getSessionFirstPacket()).thenReturn(pktInfo01); Mockito.when(entryArray[2].getDiagnosis()).thenReturn(Diagnosis.CACHING_DIAG_NOT_EXPIRED_DUP_PARTIALHIT); Mockito.when(entryArray[2].hasCacheHeaders()).thenReturn(true); Mockito.when(entryArray[3].getDiagnosis()).thenReturn(Diagnosis.CACHING_DIAG_NOT_EXPIRED_DUP); Mockito.when(entryArray[3].hasCacheHeaders()).thenReturn(true); Mockito.when(entryArray[4].getDiagnosis()).thenReturn(Diagnosis.CACHING_DIAG_OBJ_NOT_CHANGED_304); Mockito.when(entryArray[4].hasCacheHeaders()).thenReturn(false); for(int i = 0; i < 5; i++){ diagnosisResults.add(entryArray[i]); } Mockito.when(cacheAnalysis.getDiagnosisResults()).thenReturn(diagnosisResults); Mockito.when(tracedata.getCacheAnalysis()).thenReturn(cacheAnalysis); AbstractBestPracticeResult testResult = usingCacheImpl.runTest(tracedata); assertEquals(BPResultType.WARNING, testResult.getResultType()); } @Test public void runTest_returnIsNull(){ Mockito.when(tracedata.getCacheAnalysis()).thenReturn(null); AbstractBestPracticeResult testResult = usingCacheImpl.runTest(tracedata); assertNull(testResult); }
UnsecureSSLVersionImpl implements IBestPractice { @Override public AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata) { Set<UnsecureSSLVersionEntry> entries = new HashSet<>(); try { List<Session> sessions = tracedata.getSessionlist(); for(Session session : sessions) { Set<String> unsecureSSLVersions = getUnsecureSSLVersionsInSession(session); if (!unsecureSSLVersions.isEmpty()) { String unsecureSSLVersionsStr = stringifyUnsecureSSLVersions(unsecureSSLVersions); UnsecureSSLVersionEntry entry = populateEntry(session, unsecureSSLVersionsStr); entries.add(entry); } } } catch(Exception e) { LOGGER.error("Error happened when running unsecure SSL Versions test :: Caused by: " + e.getMessage()); } return getTestResult(entries); } @Override AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata); }
@Test public void testEmptyUnsecureSSLVersions() { Set<String> unsecureSSLVersions = new HashSet<>(); packetAnalyzerResult = getPacketAnalyzerResult(unsecureSSLVersions); result = (UnsecureSSLVersionResult) ((UnsecureSSLVersionImpl) bestPractice).runTest(packetAnalyzerResult); assertEquals(0, result.getResults().size()); } @Test public void testNonEmptyUnsecureSSLVersions() { Set<String> unsecureSSLVersions = new HashSet<>(); unsecureSSLVersions.add("3.0"); packetAnalyzerResult = getPacketAnalyzerResult(unsecureSSLVersions); result = (UnsecureSSLVersionResult) ((UnsecureSSLVersionImpl) bestPractice).runTest(packetAnalyzerResult); assertEquals(1, result.getResults().size()); assertEquals("3.0", result.getResults().get(0).getUnsecureSSLVersions()); }
RootedAndroidCollectorImpl implements IDataCollector, IVideoImageSubscriber { @Override public String[] getLog() { return android.getShellReturn(device, "echo ''Android version :'';getprop ro.build.version.release;logcat -d"); } int getMilliSecondsForTimeout(); @Override String getName(); @Override void addDeviceStatusSubscriber(IDeviceStatus devicestatus); @Override void addVideoImageSubscriber(IVideoImageSubscriber subscriber); @Override int getMajorVersion(); @Override String getMinorVersion(); @Override DataCollectorType getType(); @Override boolean isRunning(); @Override String[] getLog(); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, String password); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, boolean isLiveViewVideo, String deviceId, Hashtable<String, Object> extraParams, String password); @Override void timeOutShutdown(); @Override void haltCollectorInDevice(); @Override boolean isTrafficCaptureRunning(int seconds); void startVideoCapture(); @Override StatusResult stopCollector(); @Override void receiveImage(BufferedImage videoimage); @Override String getPassword(); @Override boolean setPassword(String requestPassword); @Override String[] getDeviceSerialNumber(StatusResult status); @Override IAroDevice[] getDevices(StatusResult status); @Override boolean isDeviceDataPulled(); }
@Test public void test_getLog() { String[] logcatResponse = new String[] { "loggy", "last" }; when(android.getShellReturn(any(IDevice.class), any(String.class))).thenReturn(logcatResponse); String[] testResult = rootedAndroidCollectorImpl.getLog(); assertTrue(testResult[0].equals(logcatResponse[0])); }
ConnectionOpeningImpl implements IBestPractice { @Override public AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata) { ConnectionOpeningResult result = new ConnectionOpeningResult(); result.setSelfTest(true); result.setAboutText(aboutText); result.setDetailTitle(detailTitle); result.setLearnMoreUrl(learnMoreUrl); result.setOverviewTitle(overviewTitle); result.setResultText(textResult); result.setResultType(BPResultType.SELF_TEST); return result; } @Override AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata); }
@Test public void runTest_resIsNoError(){ tracedata = Mockito.mock(PacketAnalyzerResult.class); connOpenImpl = (ConnectionOpeningImpl)context.getBean("connectionOpening"); AbstractBestPracticeResult result = connOpenImpl.runTest(tracedata); assertEquals(result.getResultType(), BPResultType.SELF_TEST); }
UnnecessaryConnectionImpl implements IBestPractice { @Override public AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata) { UnnecessaryConnectionResult result = new UnnecessaryConnectionResult(); ucEntryList = new ArrayList<UnnecessaryConnectionEntry>(); validateUnnecessaryConnections(tracedata.getBurstCollectionAnalysisData().getBurstCollection()); if(tightlyCoupledBurstCount < 4){ result.setResultType(BPResultType.PASS); result.setResultText(textResultPass); }else{ result.setResultType(BPResultType.FAIL); String text = MessageFormat.format(this.textResults, this.tightlyCoupledBurstCount); result.setResultText(text); } result.setTightlyCoupledBurstCount(tightlyCoupledBurstCount); result.setTightlyCoupledBurstTime(tightlyCoupledBurstTime); result.setTightlyCoupledBurstsDetails(ucEntryList); result.setSelfTest(false); result.setAboutText(aboutText); result.setDetailTitle(detailTitle); result.setLearnMoreUrl(learnMoreUrl); result.setOverviewTitle(overviewTitle); result.setExportAllMultiConnDesc(exportAllMultiConnDesc); return result; } @Override AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata); }
@Test public void runTest_resTypeIsFail() { Date date = new Date(); for (int j = 0; j < 20; j++) { double timeLine = 0.0; when(burstArray[j].getBurstCategory()).thenReturn(BurstCategory.TCP_LOSS_OR_DUP); when(burstArray[j].getBeginTime()).thenReturn((date.getTime() / 1000) + 4.0 + timeLine); when(burstArray[j].getEndTime()).thenReturn((date.getTime() / 1000) + 10.0 + timeLine); when(burstArray[j + 1].getBurstCategory()).thenReturn(BurstCategory.PERIODICAL); when(burstArray[j + 1].getBeginTime()).thenReturn((date.getTime() / 1000) + 11.0 + timeLine); when(burstArray[j + 1].getEndTime()).thenReturn((date.getTime() / 1000) + 23.0 + timeLine); when(burstArray[j + 2].getBurstCategory()).thenReturn(BurstCategory.LONG); when(burstArray[j + 2].getBeginTime()).thenReturn((date.getTime() / 1000) + 25.0 + timeLine); when(burstArray[j + 2].getEndTime()).thenReturn((date.getTime() / 1000) + 40.0 + timeLine); when(burstArray[j + 3].getBurstCategory()).thenReturn(BurstCategory.CPU); when(burstArray[j + 3].getBeginTime()).thenReturn((date.getTime() / 1000) + 41.0 + timeLine); when(burstArray[j + 3].getEndTime()).thenReturn((date.getTime() / 1000) + 50.0 + timeLine); when(burstArray[j + 4].getBurstCategory()).thenReturn(BurstCategory.SERVER_NET_DELAY); when(burstArray[j + 4].getBeginTime()).thenReturn((date.getTime() / 1000) + 51.0 + timeLine); when(burstArray[j + 4].getEndTime()).thenReturn((date.getTime() / 1000) + 65.0 + timeLine); j = j + 5; timeLine = timeLine + 20.0; } List<Burst> burstCollection = new ArrayList<Burst>(); for (int i = 0; i < 26; i++) { burstCollection.add(burstArray[i]); } Mockito.when(burstCollectionAnalysisData.getBurstCollection()).thenReturn(burstCollection); Mockito.when(tracedata.getBurstCollectionAnalysisData()).thenReturn(burstCollectionAnalysisData); unConnImpl = (UnnecessaryConnectionImpl) context.getBean("unnecessaryConnection"); unConnImpl.runTest(tracedata); AbstractBestPracticeResult result = unConnImpl.runTest(tracedata); assertEquals(BPResultType.FAIL, result.getResultType()); } @Test public void runTest_resTypeIsPass() { when(burstArray[0].getBurstCategory()).thenReturn(BurstCategory.SCREEN_ROTATION); when(burstArray[0].getBeginTime()).thenReturn(1.0); when(burstArray[0].getEndTime()).thenReturn(5.0); when(burstArray[1].getBurstCategory()).thenReturn(BurstCategory.CPU); when(burstArray[1].getEndTime()).thenReturn(6.0); List<Burst> burstCollection = new ArrayList<Burst>(); burstCollection.add(burstArray[0]); burstCollection.add(burstArray[1]); Mockito.when(burstCollectionAnalysisData.getBurstCollection()).thenReturn(burstCollection); Mockito.when(tracedata.getBurstCollectionAnalysisData()).thenReturn(burstCollectionAnalysisData); unConnImpl = (UnnecessaryConnectionImpl) context.getBean("unnecessaryConnection"); unConnImpl.runTest(tracedata); AbstractBestPracticeResult result = unConnImpl.runTest(tracedata); assertEquals(BPResultType.PASS, result.getResultType()); }
HttpsUsageImpl implements IBestPractice { @Override public AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata) { totalNumConnectionsCurrentTrace = 0; totalNumHttpConnectionsCurrentTrace = 0; List<Session> sessions = tracedata.getSessionlist(); Map<InetAddress, List<Session>> ipSessionsMap = buildIpSessionsMap(sessions); List<HttpsUsageEntry> httpsUsageEntries = buildHttpsUsageEntry(ipSessionsMap); int httpConnectionsPercentageCurrentTrace = getHttpConnectionsPercentage(totalNumHttpConnectionsCurrentTrace, totalNumConnectionsCurrentTrace); HttpsUsageResult result = new HttpsUsageResult(); String testResultText = ""; if (passTest()) { result.setResultType(BPResultType.PASS); testResultText = MessageFormat.format(testResultPassText, ApplicationConfig.getInstance().getAppShortName(), totalNumHttpConnectionsCurrentTrace); } else if (failTest(httpsUsageEntries, httpConnectionsPercentageCurrentTrace)) { result.setResultType(BPResultType.FAIL); testResultText = MessageFormat.format(testResultAnyText, ApplicationConfig.getInstance().getAppShortName(), totalNumHttpConnectionsCurrentTrace, httpConnectionsPercentageCurrentTrace); } else { result.setResultType(BPResultType.WARNING); testResultText = MessageFormat.format(testResultAnyText, ApplicationConfig.getInstance().getAppShortName(), totalNumHttpConnectionsCurrentTrace, httpConnectionsPercentageCurrentTrace); } result.setOverviewTitle(overviewTitle); result.setDetailTitle(detailedTitle); result.setLearnMoreUrl(learnMoreUrl); result.setAboutText(aboutText); result.setResults(httpsUsageEntries); result.setResultText(testResultText); result.setExportAll(exportAll); return result; } @Override AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata); }
@Test public void testParentDomainNameUsed_DifferentSubdomains() { pktAnalyzerResult = domainNameTestSetup("157.56.19.80", "216.58.194.196", "www.gstatic.com", "ssl.gstatic.com", "www.arotest.com"); httpsUsageResult = (HttpsUsageResult) httpsUsageImpl.runTest(pktAnalyzerResult); httpsUsageEntries = httpsUsageResult.getResults(); domainNameTestVerification(httpsUsageEntries); } @Test public void testParentDomainNameUsed_MultiLevelDomainNames() { pktAnalyzerResult = domainNameTestSetup("157.56.19.80", "216.58.194.196", "bogusa.bogusb.gstatic.com", "bogusa.gstatic.com", "www.arotest.com"); httpsUsageResult = (HttpsUsageResult) httpsUsageImpl.runTest(pktAnalyzerResult); httpsUsageEntries = httpsUsageResult.getResults(); domainNameTestVerification(httpsUsageEntries); } @Test public void testParentDomainNameUsed_IPDomainNameMix() { pktAnalyzerResult = domainNameTestSetup("157.56.19.80", "216.58.194.196", "157.56.19.80", "www.gstatic.com", "www.arotest.com"); httpsUsageResult = (HttpsUsageResult) httpsUsageImpl.runTest(pktAnalyzerResult); httpsUsageEntries = httpsUsageResult.getResults(); domainNameTestVerification(httpsUsageEntries); } @Test public void testDomainNameNoSeparator() { String domainNameUnderTest = "bzsvdcwfxtqfy"; pktAnalyzerResult = domainNameTestSetup("157.56.19.80", "216.58.194.196", "157.56.19.80", "www.gstatic.com", domainNameUnderTest); httpsUsageResult = (HttpsUsageResult) httpsUsageImpl.runTest(pktAnalyzerResult); httpsUsageEntries = httpsUsageResult.getResults(); domainNameTestVerification(httpsUsageEntries, domainNameUnderTest); } @Test public void testNullDomainName() { String domainNameUnderTest = null; pktAnalyzerResult = domainNameTestSetup("157.56.19.80", "216.58.194.196", "157.56.19.80", "www.gstatic.com", domainNameUnderTest); httpsUsageResult = (HttpsUsageResult) httpsUsageImpl.runTest(pktAnalyzerResult); httpsUsageEntries = httpsUsageResult.getResults(); domainNameTestVerification(httpsUsageEntries, ""); } @Test public void testEmptyDomainName() { String domainNameUnderTest = ""; pktAnalyzerResult = domainNameTestSetup("157.56.19.80", "216.58.194.196", "157.56.19.80", "www.gstatic.com", domainNameUnderTest); httpsUsageResult = (HttpsUsageResult) httpsUsageImpl.runTest(pktAnalyzerResult); httpsUsageEntries = httpsUsageResult.getResults(); domainNameTestVerification(httpsUsageEntries, domainNameUnderTest); } @Test public void testUDPSessionNotConsidered() { Session session1 = mock(Session.class); Session session2 = mock(Session.class); InetAddress ipAddr = mock(InetAddress.class); when(ipAddr.getHostAddress()).thenReturn("157.56.19.80"); when(session1.isUdpOnly()).thenReturn(true); when(session2.getRemoteIP()).thenReturn(ipAddr); when(session2.getDomainName()).thenReturn("www.hotmail.com"); TCPPacket tcpPacket1 = mock(TCPPacket.class); TCPPacket tcpPacket2 = mock(TCPPacket.class); when(tcpPacket1.containsSSLRecord()).thenReturn(false); when(tcpPacket2.containsSSLRecord()).thenReturn(false); PacketInfo packetInfo_tcp1 = mock(PacketInfo.class); PacketInfo packetInfo_tcp2 = mock(PacketInfo.class); when(packetInfo_tcp1.getPayloadLen()).thenReturn(1); when(packetInfo_tcp1.getPacket()).thenReturn(tcpPacket1); when(packetInfo_tcp2.getPayloadLen()).thenReturn(1); when(packetInfo_tcp2.getPacket()).thenReturn(tcpPacket2); List<PacketInfo> packetsInfo = new ArrayList<PacketInfo>(); packetsInfo.add(packetInfo_tcp1); packetsInfo.add(packetInfo_tcp2); when(session2.getPackets()).thenReturn(packetsInfo); List<Session> sessions = new ArrayList<Session>(); sessions.add(session1); sessions.add(session2); pktAnalyzerResult.setSessionlist(sessions); httpsUsageResult = (HttpsUsageResult) httpsUsageImpl.runTest(pktAnalyzerResult); httpsUsageEntries = httpsUsageResult.getResults(); assertEquals(1, httpsUsageEntries.size()); } @Test public void testNonSSLSessionNoPayload() { PacketAnalyzerResult pktAnalyzerResult = sessionPacketsPayloadTestSetup(0, 0, 0, 0); httpsUsageResult = (HttpsUsageResult) httpsUsageImpl.runTest(pktAnalyzerResult); httpsUsageEntries = httpsUsageResult.getResults(); assertEquals(0, httpsUsageEntries.size()); } @Test public void testNonSSLSessionHasPayload() { PacketAnalyzerResult pktAnalyzerResult = sessionPacketsPayloadTestSetup(1, 0, 1, 1); httpsUsageResult = (HttpsUsageResult) httpsUsageImpl.runTest(pktAnalyzerResult); httpsUsageEntries = httpsUsageResult.getResults(); assertEquals(2, httpsUsageEntries.size()); } @Test public void testConnectionsGroupedByIP() { pktAnalyzerResult = resultTestSetup(8); httpsUsageResult = (HttpsUsageResult) httpsUsageImpl.runTest(pktAnalyzerResult); httpsUsageEntries = httpsUsageResult.getResults(); assertEquals(3, httpsUsageEntries.size()); } @Test public void testNumHttpConnections() { pktAnalyzerResult = resultTestSetup(5); httpsUsageResult = (HttpsUsageResult) httpsUsageImpl.runTest(pktAnalyzerResult); httpsUsageEntries = httpsUsageResult.getResults(); assertEquals(2, httpsUsageEntries.size()); if (httpsUsageEntries.get(0).getIPAddress().equals("157.56.19.80")) { assertEquals(3, httpsUsageEntries.get(0).getTotalNumHttpConnections()); assertEquals(2, httpsUsageEntries.get(1).getTotalNumHttpConnections()); } else { assertEquals(2, httpsUsageEntries.get(0).getTotalNumHttpConnections()); assertEquals(3, httpsUsageEntries.get(1).getTotalNumHttpConnections()); } } @Test public void testNumConnections() { pktAnalyzerResult = resultTestSetup(5); httpsUsageResult = (HttpsUsageResult) httpsUsageImpl.runTest(pktAnalyzerResult); httpsUsageEntries = httpsUsageResult.getResults(); assertEquals(2, httpsUsageEntries.size()); if (httpsUsageEntries.get(0).getIPAddress().equals("157.56.19.80")) { assertEquals(3, httpsUsageEntries.get(0).getTotalNumConnections()); assertEquals(4, httpsUsageEntries.get(1).getTotalNumConnections()); } else { assertEquals(4, httpsUsageEntries.get(0).getTotalNumConnections()); assertEquals(3, httpsUsageEntries.get(1).getTotalNumConnections()); } } @Test public void testHttpTrafficSize() { pktAnalyzerResult = resultTestSetup(5); httpsUsageResult = (HttpsUsageResult) httpsUsageImpl.runTest(pktAnalyzerResult); httpsUsageEntries = httpsUsageResult.getResults(); assertEquals(2, httpsUsageEntries.size()); if (httpsUsageEntries.get(0).getIPAddress().equals("157.56.19.80")) { assertEquals("0.293", httpsUsageEntries.get(0).getTotalHttpTrafficInKB()); assertEquals("0.098", httpsUsageEntries.get(1).getTotalHttpTrafficInKB()); } else { assertEquals("0.098", httpsUsageEntries.get(0).getTotalHttpTrafficInKB()); assertEquals("0.293", httpsUsageEntries.get(1).getTotalHttpTrafficInKB()); } } @Test public void testTrafficSize() { pktAnalyzerResult = resultTestSetup(5); httpsUsageResult = (HttpsUsageResult) httpsUsageImpl.runTest(pktAnalyzerResult); httpsUsageEntries = httpsUsageResult.getResults(); assertEquals(2, httpsUsageEntries.size()); if (httpsUsageEntries.get(0).getIPAddress().equals("157.56.19.80")) { assertEquals("0.293", httpsUsageEntries.get(0).getTotalTrafficInKB()); assertEquals("0.391", httpsUsageEntries.get(1).getTotalTrafficInKB()); } else { assertEquals("0.391", httpsUsageEntries.get(0).getTotalTrafficInKB()); assertEquals("0.293", httpsUsageEntries.get(1).getTotalTrafficInKB()); } } @Test public void testHttpTrafficPercentage() { PacketAnalyzerResult pktAnalyzerResult = resultTestSetup(5); HttpsUsageResult httpsUsageResult = (HttpsUsageResult) httpsUsageImpl.runTest(pktAnalyzerResult); List<HttpsUsageEntry> httpsUsageEntries = httpsUsageResult.getResults(); assertEquals(2, httpsUsageEntries.size()); if (httpsUsageEntries.get(0).getIPAddress().equals("157.56.19.80")) { assertEquals("100", String.valueOf(httpsUsageEntries.get(0).getTotalHttpTrafficPercentage())); assertEquals("25", String.valueOf(httpsUsageEntries.get(1).getTotalHttpTrafficPercentage())); } else { assertEquals("25", String.valueOf(httpsUsageEntries.get(0).getTotalHttpTrafficPercentage())); assertEquals("100", String.valueOf(httpsUsageEntries.get(1).getTotalHttpTrafficPercentage())); } } @Test public void testResultPass() { pktAnalyzerResult = resultTestSetup(0); httpsUsageResult = (HttpsUsageResult) httpsUsageImpl.runTest(pktAnalyzerResult); httpsUsageEntries = httpsUsageResult.getResults(); assertEquals(0, httpsUsageEntries.size()); assertEquals(BPResultType.PASS, httpsUsageResult.getResultType()); assertEquals( ApplicationConfig.getInstance().getAppShortName() + " discovered 0 non-HTTPS connection and it passes the test.", httpsUsageResult.getResultText()); } @Test public void testResultWarn() { pktAnalyzerResult = resultTestSetup(1); httpsUsageResult = (HttpsUsageResult) httpsUsageImpl.runTest(pktAnalyzerResult); httpsUsageEntries = httpsUsageResult.getResults(); assertEquals(1, httpsUsageEntries.size()); assertEquals(BPResultType.WARNING, httpsUsageResult.getResultType()); assertEquals( ApplicationConfig.getInstance().getAppShortName() + " discovered 1 non-HTTPS connections, which is 13% of all the TCP sessions.", httpsUsageResult.getResultText()); } @Test public void testResultFail_NumHttpConnThree() { pktAnalyzerResult = resultTestSetup(3); httpsUsageResult = (HttpsUsageResult) httpsUsageImpl.runTest(pktAnalyzerResult); httpsUsageEntries = httpsUsageResult.getResults(); assertEquals(1, httpsUsageEntries.size()); assertEquals(BPResultType.WARNING, httpsUsageResult.getResultType()); assertEquals( ApplicationConfig.getInstance().getAppShortName() + " discovered 3 non-HTTPS connections, which is 38% of all the TCP sessions.", httpsUsageResult.getResultText()); } @Test public void testResultFail_NumHttpConnMoreThanThree() { pktAnalyzerResult = resultTestSetup(4); httpsUsageResult = (HttpsUsageResult) httpsUsageImpl.runTest(pktAnalyzerResult); httpsUsageEntries = httpsUsageResult.getResults(); assertEquals(2, httpsUsageEntries.size()); assertEquals(BPResultType.WARNING, httpsUsageResult.getResultType()); assertEquals( ApplicationConfig.getInstance().getAppShortName() + " discovered 4 non-HTTPS connections, which is 50% of all the TCP sessions.", httpsUsageResult.getResultText()); } @Test public void testResultFail_HttpConnGreaterThanTwentyFivePercent() { pktAnalyzerResult = resultTestSetup(3); httpsUsageResult = (HttpsUsageResult) httpsUsageImpl.runTest(pktAnalyzerResult); httpsUsageEntries = httpsUsageResult.getResults(); assertEquals(1, httpsUsageEntries.size()); assertEquals(BPResultType.WARNING, httpsUsageResult.getResultType()); assertEquals( ApplicationConfig.getInstance().getAppShortName() + " discovered 3 non-HTTPS connections, which is 38% of all the TCP sessions.", httpsUsageResult.getResultText()); }
RootedAndroidCollectorImpl implements IDataCollector, IVideoImageSubscriber { public void startVideoCapture() { String videopath = this.localTraceFolder + Util.FILE_SEPARATOR + "video.mov"; try { Integer api = 0; try { api = Integer.valueOf(aroDevice.getApi()); } catch (NumberFormatException e1) { log.error("unable to obtain api:"+e1.getMessage()); } if (isVideo() && !videoOption.equals(VideoOption.LREZ) && api >= 21) { screenRecorder.init(aroDevice, this.localTraceFolder, videoOption); threadexecutor.execute(screenRecorder); } videocapture.init(device, videopath); threadexecutor.execute(videocapture); } catch (IOException e) { log.error(e.getMessage()); } } int getMilliSecondsForTimeout(); @Override String getName(); @Override void addDeviceStatusSubscriber(IDeviceStatus devicestatus); @Override void addVideoImageSubscriber(IVideoImageSubscriber subscriber); @Override int getMajorVersion(); @Override String getMinorVersion(); @Override DataCollectorType getType(); @Override boolean isRunning(); @Override String[] getLog(); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, String password); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, boolean isLiveViewVideo, String deviceId, Hashtable<String, Object> extraParams, String password); @Override void timeOutShutdown(); @Override void haltCollectorInDevice(); @Override boolean isTrafficCaptureRunning(int seconds); void startVideoCapture(); @Override StatusResult stopCollector(); @Override void receiveImage(BufferedImage videoimage); @Override String getPassword(); @Override boolean setPassword(String requestPassword); @Override String[] getDeviceSerialNumber(StatusResult status); @Override IAroDevice[] getDevices(StatusResult status); @Override boolean isDeviceDataPulled(); }
@Ignore @Test public void test_captureVideo() throws Exception { doNothing().when(videocapture).init(any(IDevice.class), any(String.class)); @SuppressWarnings("unchecked") List<IVideoImageSubscriber> videoImageSubscribers = mock(List.class); when(videoImageSubscribers.isEmpty()).thenReturn(false); doNothing().when(threadexecutor).execute(any(Runnable.class)); rootedAndroidCollectorImpl.startVideoCapture(); assertTrue(true); }
WeakCipherImpl implements IBestPractice { @Override public AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata) { Set<WeakCipherEntry> entries = new HashSet<>(); List<Session> sessions = tracedata.getSessionlist(); for(Session session : sessions) { Set<String> weakCiphers = getWeakCiphersInSession(session); for(String weakCipher : weakCiphers) { entries.add(populateEntry(session, weakCipher)); } } return getTestResult(entries); } @Override AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata); }
@Test public void testEmptyWeakCipherSuites() { Set<String> weakCipherSuites = new HashSet<>(); packetAnalyzerResult = getPacketAnalyzerResult(weakCipherSuites); result = (WeakCipherResult) ((WeakCipherImpl) bestPractice).runTest(packetAnalyzerResult); assertEquals(0, result.getResults().size()); } @Test public void testNonEmptyWeakCipherSuites() { Set<String> weakCipherSuites = new HashSet<>(); weakCipherSuites.add("0x0002"); weakCipherSuites.add("0x000e"); packetAnalyzerResult = getPacketAnalyzerResult(weakCipherSuites); result = (WeakCipherResult) ((WeakCipherImpl) bestPractice).runTest(packetAnalyzerResult); assertEquals(2, result.getResults().size()); }
ForwardSecrecyImpl implements IBestPractice { @Override public AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata) { Set<ForwardSecrecyEntry> entries = new HashSet<>(); List<Session> sessions = tracedata.getSessionlist(); for(Session session : sessions) { String selectedCipher = getSelectedCipherInSession(session); if (selectedCipher != null) { entries.add(populateEntry(session, selectedCipher)); } } return getTestResult(entries); } @Override AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata); }
@Test public void testCipherSuiteNotSupportForwardSecrecy() { String cipherSuite = null; packetAnalyzerResult = getPacketAnalyzerResult(cipherSuite); result = (ForwardSecrecyResult) ((ForwardSecrecyImpl) bestPractice).runTest(packetAnalyzerResult); assertEquals(0, result.getResults().size()); } @Test public void testCipherSuiteSupportForwardSecrecy() { String cipherSuite = "0x0005"; packetAnalyzerResult = getPacketAnalyzerResult(cipherSuite); result = (ForwardSecrecyResult) ((ForwardSecrecyImpl) bestPractice).runTest(packetAnalyzerResult); assertEquals(1, result.getResults().size()); }
DuplicateContentImpl implements IBestPractice { @Override public AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata) { DuplicateContentResult result = new DuplicateContentResult(); CacheAnalysis cacheAnalysis = tracedata.getCacheAnalysis(); result.setDuplicateContentBytes(cacheAnalysis.getDuplicateContentBytes()); result.setDuplicateContentBytesRatio(cacheAnalysis.getDuplicateContentBytesRatio()); int duplicateContentsize = cacheAnalysis.getDuplicateContent().size(); result.setDuplicateContentsize(duplicateContentsize); int totalTCPBytes = 0; if (tracedata.getStatistic() != null) { totalTCPBytes = tracedata.getStatistic().getTotalTCPBytes(); } result.setTotalContentBytes(totalTCPBytes); List<CacheEntry> caUResult = cacheAnalysis.getDuplicateContent(); result.setDuplicateContentList(caUResult); int duplicateContentSizeOfUniqueItems = caUResult.size(); result.setDuplicateContentSizeOfUniqueItems(duplicateContentSizeOfUniqueItems); if (duplicateContentsize <= 3) { result.setResultType(BPResultType.PASS); result.setResultText(textResultPass); } else { result.setResultType(BPResultType.FAIL); DecimalFormat numf = new DecimalFormat("#.##"); NumberFormat numf2 = NumberFormat.getInstance(); numf2.setMaximumFractionDigits(3); String text = MessageFormat.format(textResults, numf.format(result.getDuplicateContentBytes() * 100.0 / result.getTotalContentBytes()), result.getDuplicateContentSizeOfUniqueItems(), numf2.format(((double) result.getDuplicateContentBytes()) / DUPLICATE_CONTENT_DENOMINATOR), numf2.format(((double) result.getTotalContentBytes()) / DUPLICATE_CONTENT_DENOMINATOR)); result.setResultText(text); } result.setAboutText(aboutText); result.setDetailTitle(detailTitle); result.setLearnMoreUrl(learnMoreUrl); result.setOverviewTitle(overviewTitle); result.setExportAllFiles(exportAllFiles); result.setExportAllPct(exportAllPct); result.setStaticsUnitsMbytes(staticsUnitsMbytes); return result; } @Override AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata); }
@Test public void runTest_resTypeIsPass() { List<CacheEntry> duplicateContent = new ArrayList<CacheEntry>(); for (int i = 0; i < 2; i++) { duplicateContent.add(entryArray[i]); } Mockito.when(cacheAnalysis.getDuplicateContentBytes()).thenReturn(value); Mockito.when(cacheAnalysis.getDuplicateContentBytesRatio()).thenReturn(0.1); Mockito.when(cacheAnalysis.getTotalBytesDownloaded()).thenReturn(value); Mockito.when(cacheAnalysis.getDuplicateContent()).thenReturn(duplicateContent); Mockito.when(tracedata.getCacheAnalysis()).thenReturn(cacheAnalysis); duplicateContentImpl = (DuplicateContentImpl) context.getBean("duplicateContent"); AbstractBestPracticeResult testResult = duplicateContentImpl.runTest(tracedata); assertEquals(BPResultType.PASS, testResult.getResultType()); } @Test public void runTest_resTypeIsFail() { List<CacheEntry> duplicateContent = new ArrayList<CacheEntry>(); for (int i = 0; i < 5; i++) { duplicateContent.add(entryArray[i]); } Mockito.when(cacheAnalysis.getDuplicateContentBytes()).thenReturn(value); Mockito.when(cacheAnalysis.getDuplicateContentBytesRatio()).thenReturn(1.0); Mockito.when(cacheAnalysis.getDuplicateContent()).thenReturn(duplicateContent); Mockito.when(tracedata.getCacheAnalysis()).thenReturn(cacheAnalysis); duplicateContentImpl = (DuplicateContentImpl) context.getBean("duplicateContent"); AbstractBestPracticeResult testResult = duplicateContentImpl.runTest(tracedata); assertEquals(BPResultType.FAIL, testResult.getResultType()); }
CombineCsJssImpl implements IBestPractice { @Override public AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata) { CombineCsJssResult result = new CombineCsJssResult(); List<CsJssFilesDetails> fileDetails = new ArrayList<CsJssFilesDetails>(); int inefficientCssRequests = 0; PacketInfo consecutiveCssJsFirstPacket = null; int inefficientJsRequests = 0; double cssLastTimeStamp = 0.0; double jsLastTimeStamp = 0.0; String contentType = ""; for(Session session: tracedata.getSessionlist()){ HttpRequestResponseInfo lastRequestObj = null; for(HttpRequestResponseInfo httpreq: session.getRequestResponseInfo()){ if(httpreq.getDirection() == HttpDirection.REQUEST){ lastRequestObj = httpreq; } if(httpreq.getDirection() == HttpDirection.RESPONSE && httpreq.getContentType() != null){ PacketInfo pktInfo = httpreq.getFirstDataPacket(); if(pktInfo != null){ contentType = httpreq.getContentType().toLowerCase().trim(); if(contentType.equalsIgnoreCase("text/css")){ if (cssLastTimeStamp == 0.0) { cssLastTimeStamp = pktInfo.getTimeStamp(); continue; } else { if ((pktInfo.getTimeStamp() - cssLastTimeStamp) <= 2.0) { inefficientCssRequests++; CsJssFilesDetails cssFileDetails = new CsJssFilesDetails(); cssFileDetails.setTimeStamp(pktInfo.getTimeStamp()); if(httpreq.getObjName() != null){ cssFileDetails.setFileName(httpreq.getObjName()); } else { if(lastRequestObj != null){ cssFileDetails.setFileName(lastRequestObj.getObjName()); } } cssFileDetails.setSize(httpreq.getContentLength()); fileDetails.add(cssFileDetails); if (consecutiveCssJsFirstPacket == null) { consecutiveCssJsFirstPacket = pktInfo; } } cssLastTimeStamp = pktInfo.getTimeStamp(); } }else if(contentType.equalsIgnoreCase("text/javascript") || contentType.equalsIgnoreCase("application/x-javascript") || contentType.equalsIgnoreCase("application/javascript")){ if (jsLastTimeStamp == 0.0) { jsLastTimeStamp = pktInfo.getTimeStamp(); continue; } else { if ((pktInfo.getTimeStamp() - jsLastTimeStamp) < 2.0) { inefficientJsRequests++; CsJssFilesDetails jsFileDetails = new CsJssFilesDetails(); jsFileDetails.setTimeStamp(pktInfo.getTimeStamp()); if(httpreq.getObjName() != null){ jsFileDetails.setFileName(httpreq.getObjName()); } else{ if(lastRequestObj != null){ jsFileDetails.setFileName(lastRequestObj.getObjName()); } } jsFileDetails.setSize(httpreq.getContentLength()); fileDetails.add(jsFileDetails); if (consecutiveCssJsFirstPacket == null) { consecutiveCssJsFirstPacket = pktInfo; } } jsLastTimeStamp = pktInfo.getTimeStamp(); } } } } } } result.setConsecutiveCssJsFirstPacket(consecutiveCssJsFirstPacket); result.setInefficientCssRequests(inefficientCssRequests); result.setInefficientJsRequests(inefficientJsRequests); if(inefficientCssRequests < 1 && inefficientJsRequests < 1){ result.setResultType(BPResultType.PASS); result.setResultText(MessageFormat.format(textResultPass, ApplicationConfig.getInstance().getAppShortName())); }else{ result.setResultType(BPResultType.FAIL); result.setResultText(textResults); result.setFilesDetails(fileDetails); } result.setAboutText(aboutText); result.setDetailTitle(detailTitle); result.setLearnMoreUrl(learnMoreUrl); result.setOverviewTitle(overviewTitle); result.setExportAllInefficientCssRequest(exportAllInefficientCssRequest); result.setExportAllInefficientJsRequest(exportAllInefficientJsRequest); return result; } @Override AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata); }
@Test public void runTest_resIsNoErrResultTypeIsFail(){ Mockito.when(pktInfo01.getTimeStamp()).thenReturn(1.0); Mockito.when(pktInfo02.getTimeStamp()).thenReturn(2.0); httpRequestInfo01 = Mockito.mock(HttpRequestResponseInfo.class); Mockito.when(httpRequestInfo01.getDirection()).thenReturn(HttpDirection.RESPONSE); Mockito.when(httpRequestInfo01.getContentType()).thenReturn("text/css"); Mockito.when(httpRequestInfo01.getFirstDataPacket()).thenReturn(pktInfo01); Mockito.when(httpRequestInfo01.getObjName()).thenReturn("test1.css"); httpRequestInfo02 = Mockito.mock(HttpRequestResponseInfo.class); Mockito.when(httpRequestInfo02.getDirection()).thenReturn(HttpDirection.RESPONSE); Mockito.when(httpRequestInfo02.getContentType()).thenReturn("text/javascript"); Mockito.when(httpRequestInfo02.getFirstDataPacket()).thenReturn(pktInfo02); List<HttpRequestResponseInfo> value = new ArrayList<HttpRequestResponseInfo>(); value.add(httpRequestInfo01); value.add(httpRequestInfo02); Mockito.when(session01.getRequestResponseInfo()).thenReturn(value); Mockito.when(session02.getRequestResponseInfo()).thenReturn(value); List<Session> sessionList = new ArrayList<Session>(); sessionList.add(session01); sessionList.add(session02); Mockito.when(tracedata.getSessionlist()).thenReturn(sessionList); csjsImpl = (CombineCsJssImpl) context.getBean("combineCsJss"); AbstractBestPracticeResult result = csjsImpl.runTest(tracedata); assertEquals(BPResultType.FAIL,result.getResultType() ); } @Test public void runTest_resIsNoErrResultTypeIsFailConsCssJsFirstPacket(){ Mockito.when(pktInfo01.getTimeStamp()).thenReturn(1.0); Mockito.when(pktInfo02.getTimeStamp()).thenReturn(2.0); httpRequestInfo01 = Mockito.mock(HttpRequestResponseInfo.class); Mockito.when(httpRequestInfo01.getDirection()).thenReturn(HttpDirection.RESPONSE); Mockito.when(httpRequestInfo01.getContentType()).thenReturn("text/javascript"); Mockito.when(httpRequestInfo01.getFirstDataPacket()).thenReturn(pktInfo01); Mockito.when(httpRequestInfo01.getObjName()).thenReturn("test2.css"); httpRequestInfo02 = Mockito.mock(HttpRequestResponseInfo.class); Mockito.when(httpRequestInfo02.getDirection()).thenReturn(HttpDirection.RESPONSE); Mockito.when(httpRequestInfo02.getContentType()).thenReturn("application/x-javascript"); Mockito.when(httpRequestInfo02.getFirstDataPacket()).thenReturn(pktInfo02); Mockito.when(httpRequestInfo02.getObjName()).thenReturn("test3.css"); List<HttpRequestResponseInfo> value = new ArrayList<HttpRequestResponseInfo>(); value.add(httpRequestInfo01); value.add(httpRequestInfo02); Mockito.when(session01.getRequestResponseInfo()).thenReturn(value); Mockito.when(session02.getRequestResponseInfo()).thenReturn(value); List<Session> sessionList = new ArrayList<Session>(); sessionList.add(session01); sessionList.add(session02); Mockito.when(tracedata.getSessionlist()).thenReturn(sessionList); csjsImpl = (CombineCsJssImpl) context.getBean("combineCsJss"); AbstractBestPracticeResult result = csjsImpl.runTest(tracedata); assertEquals(BPResultType.FAIL,result.getResultType() ); } @Test public void runTest_resIsNoErrResultTypeIsPass(){ Mockito.when(pktInfo01.getTimeStamp()).thenReturn(1.0); Mockito.when(pktInfo02.getTimeStamp()).thenReturn(2.0); httpRequestInfo01 = Mockito.mock(HttpRequestResponseInfo.class); Mockito.when(httpRequestInfo01.getDirection()).thenReturn(HttpDirection.REQUEST); Mockito.when(httpRequestInfo01.getFirstDataPacket()).thenReturn(pktInfo01); List<HttpRequestResponseInfo> value = new ArrayList<HttpRequestResponseInfo>(); value.add(httpRequestInfo01); Mockito.when(session01.getRequestResponseInfo()).thenReturn(value); Mockito.when(session02.getRequestResponseInfo()).thenReturn(value); List<Session> sessionList = new ArrayList<Session>(); sessionList.add(session01); sessionList.add(session02); Mockito.when(tracedata.getSessionlist()).thenReturn(sessionList); csjsImpl = (CombineCsJssImpl) context.getBean("combineCsJss"); AbstractBestPracticeResult result = csjsImpl.runTest(tracedata); assertEquals(BPResultType.PASS,result.getResultType() ); }
ImageSizeImpl implements IBestPractice { @Override public AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata) { mImageFoundInHtmlOrCss = false; ImageSizeResult result = new ImageSizeResult(); List<ImageSizeEntry> entrylist = new ArrayList<ImageSizeEntry>(); int deviceScreenSizeX = 528; int deviceScreenSizeY = 880; if (tracedata.getTraceresult().getTraceResultType() == TraceResultType.TRACE_DIRECTORY) { TraceDirectoryResult dirdata = (TraceDirectoryResult) tracedata.getTraceresult(); deviceScreenSizeX = (dirdata.getDeviceScreenSizeX() * 110) / 100; deviceScreenSizeY = (dirdata.getDeviceScreenSizeY() * 110) / 100; } for (Session session : tracedata.getSessionlist()) { HttpRequestResponseInfo lastReq = null; for (HttpRequestResponseInfo req : session.getRequestResponseInfo()) { if (req.getDirection() == HttpDirection.REQUEST) { lastReq = req; } if (req.getDirection() == HttpDirection.RESPONSE && req.getContentType() != null && req.getContentType().contains("image/")) { boolean isBigSize = false; List<HtmlImage> htmlImageList = checkThisImageInAllHTMLOrCSS(session, req); if (mImageFoundInHtmlOrCss) { mImageFoundInHtmlOrCss = false; if (!htmlImageList.isEmpty()) { for (int index = 0; index < htmlImageList.size(); index++) { HtmlImage htmlImage = htmlImageList.get(index); isBigSize = compareDownloadedImgSizeWithStdImageSize(req, htmlImage, deviceScreenSizeX, deviceScreenSizeY, session); if (isBigSize) { break; } } } else { isBigSize = compareDownloadedImgSizeWithStdImageSize(req, null, deviceScreenSizeX, deviceScreenSizeY, session); } if (isBigSize) { entrylist.add(new ImageSizeEntry(req, lastReq, session.getDomainName())); } } } } } result.setDeviceScreenSizeRangeX(deviceScreenSizeX); result.setDeviceScreenSizeRangeY(deviceScreenSizeY); result.setResults(entrylist); String text = ""; if (entrylist.isEmpty()) { result.setResultType(BPResultType.PASS); text = MessageFormat.format(textResultPass, entrylist.size()); result.setResultText(text); } else { result.setResultType(BPResultType.FAIL); text = MessageFormat.format(textResults, ApplicationConfig.getInstance().getAppShortName(), entrylist.size()); result.setResultText(text); } result.setAboutText(aboutText); result.setDetailTitle(detailTitle); result.setLearnMoreUrl(learnMoreUrl); result.setOverviewTitle(overviewTitle); result.setExportNumberOfLargeImages(exportNumberOfLargeImages); return result; } @Autowired void setReqhelper(IHttpRequestResponseHelper helper); @Override AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata); }
@Test public void runTest_1() { List<Session> sessionlist; Session session_1; session_1 = mock(Session.class); sessionlist = new ArrayList<Session>(); sessionlist.add(session_1); Mockito.when((TraceDirectoryResult) tracedata.getTraceresult()).thenReturn(dirdata); Mockito.when(dirdata.getTraceResultType()).thenReturn(TraceResultType.TRACE_DIRECTORY); Mockito.when(dirdata.getDeviceScreenSizeX()).thenReturn(480); Mockito.when(dirdata.getDeviceScreenSizeY()).thenReturn(800); ImageSizeImpl = (ImageSizeImpl) context.getBean("imageSize"); result = ImageSizeImpl.runTest(tracedata); assertEquals( "Images that are not correctly sized for mobile can cause extreme delays in rendering. Before delivering content to a mobile, resize it to fit the available area.", result.getAboutText()); assertEquals("Resize Images for Mobile", result.getDetailTitle()); assertEquals("File Download: Resize Images for Mobile", result.getOverviewTitle()); assertEquals( "Your trace passes. There are no image files that are 110% larger than the area specified for them.", result.getResultText()); assertEquals("IMAGE_SIZE", result.getBestPracticeType().toString()); assertEquals("PASS", result.getResultType().toString()); }
Http10UsageImpl implements IBestPractice { @Override public AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata) { Http10UsageResult result = new Http10UsageResult(); int http10HeaderCount = 0; Session http10Session = null; for(Session session: tracedata.getSessionlist()){ for(HttpRequestResponseInfo httpreq: session.getRequestResponseInfo()){ if(HttpRequestResponseInfo.HTTP10.equals(httpreq.getVersion())){ ++http10HeaderCount; if(http10Session == null){ http10Session = session; } } } } result.setHttp10Session(http10Session); result.setHttp10HeaderCount(http10HeaderCount); if(http10HeaderCount == 0){ result.setResultType(BPResultType.PASS); result.setResultText(MessageFormat.format(textResultPass, ApplicationConfig.getInstance().getAppShortName(), http10HeaderCount)); }else{ result.setResultType(BPResultType.WARNING); result.setResultText(MessageFormat.format(textResults, ApplicationConfig.getInstance().getAppShortName(), http10HeaderCount)); } result.setAboutText(aboutText); result.setDetailTitle(detailTitle); result.setLearnMoreUrl(learnMoreUrl); result.setOverviewTitle(overviewTitle); result.setExportAllHttpHeaderDesc(exportAllHttpHeaderDesc); return result; } @Override AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata); }
@Test public void runTest_resTypeIsPass() { Mockito.when(httpRequestInfo01.getVersion()).thenReturn(HttpRequestResponseInfo.HTTP11); List<HttpRequestResponseInfo> value = new ArrayList<HttpRequestResponseInfo>(); value.add(httpRequestInfo01); Mockito.when(session01.getRequestResponseInfo()).thenReturn(value); List<Session> sessionList = new ArrayList<Session>(); sessionList.add(session01); Mockito.when(tracedata.getSessionlist()).thenReturn(sessionList); httpUsageImpl = (Http10UsageImpl) context.getBean("http10Usage"); AbstractBestPracticeResult result = httpUsageImpl.runTest(tracedata); assertEquals(BPResultType.PASS, result.getResultType()); } @Test public void runTest_resTypeIsFail() { Mockito.when(httpRequestInfo01.getVersion()).thenReturn(HttpRequestResponseInfo.HTTP10); Mockito.when(httpRequestInfo02.getVersion()).thenReturn(HttpRequestResponseInfo.HTTP10); List<HttpRequestResponseInfo> value = new ArrayList<HttpRequestResponseInfo>(); value.add(httpRequestInfo01); value.add(httpRequestInfo02); Mockito.when(session01.getRequestResponseInfo()).thenReturn(value); List<Session> sessionList = new ArrayList<Session>(); sessionList.add(session01); Mockito.when(tracedata.getSessionlist()).thenReturn(sessionList); httpUsageImpl = (Http10UsageImpl) context.getBean("http10Usage"); AbstractBestPracticeResult result = httpUsageImpl.runTest(tracedata); assertEquals(BPResultType.WARNING, result.getResultType()); }
AccessingPeripheralImpl implements IBestPractice { @Override public AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata) { AccessingPeripheralResult result = new AccessingPeripheralResult(); AbstractTraceResult traceResult = tracedata.getTraceresult(); TraceDirectoryResult trresult = null; if (traceResult != null && traceResult instanceof TraceDirectoryResult) { trresult = (TraceDirectoryResult) traceResult; } if (trresult != null && isPeripheralDataAvailable(trresult)) { double activeGPSRatio = 0.0; double activeBluetoothRatio = 0.0; double activeCameraRatio = 0.0; double gpsActiveDuration = 0.0; double bluetoothActiveDuration = 0.0; double cameraActiveDuration = 0.0; double duration = 0.0; boolean accessingPeripherals = true; TimeRange timeRange = null; if (tracedata.getFilter() != null) { timeRange = tracedata.getFilter().getTimeRange(); } if (tracedata.getTraceresult().getTraceResultType() == TraceResultType.TRACE_DIRECTORY) { gpsActiveDuration = trresult.getGpsActiveDuration(); bluetoothActiveDuration = trresult.getBluetoothActiveDuration(); cameraActiveDuration = trresult.getCameraActiveDuration(); } if (timeRange != null) { duration = timeRange.getEndTime() - timeRange.getBeginTime(); } else { duration = tracedata.getTraceresult().getTraceDuration(); } activeGPSRatio = (gpsActiveDuration * 100) / duration; activeBluetoothRatio = (bluetoothActiveDuration * 100) / duration; activeCameraRatio = (cameraActiveDuration * 100) / duration; result.setActiveBluetoothRatio(activeBluetoothRatio); result.setActiveCameraRatio(activeCameraRatio); result.setActiveGPSRatio(activeGPSRatio); result.setActiveBluetoothDuration(bluetoothActiveDuration); result.setActiveCameraDuration(cameraActiveDuration); result.setActiveGPSDuration(gpsActiveDuration); if (activeGPSRatio > PERIPHERAL_ACTIVE_LIMIT || activeBluetoothRatio > PERIPHERAL_ACTIVE_LIMIT || activeCameraRatio > PERIPHERAL_ACTIVE_LIMIT) { accessingPeripherals = false; } String cameraPer = "0"; NumberFormat nfor = NumberFormat.getIntegerInstance(); if (cameraActiveDuration != 0.0) { if (activeCameraRatio < 1.0) { cameraPer = Util.percentageFormat(activeCameraRatio); } else { cameraPer = nfor.format(activeCameraRatio); } } String key = ""; if (accessingPeripherals) { result.setResultType(BPResultType.PASS); key = this.textResultPass; } else { result.setResultType(BPResultType.WARNING); key = this.textResults; } String text = MessageFormat.format(key, activeGPSRatio, activeBluetoothRatio, cameraPer); result.setResultText(text); } else { result.setResultText(noData); result.setResultType(BPResultType.NO_DATA); } result.setAboutText(aboutText); result.setDetailTitle(detailTitle); result.setLearnMoreUrl(learnMoreUrl); result.setOverviewTitle(overviewTitle); result.setExportAllBTDesc(exportAllBTDesc); result.setExportAllCamDesc(exportAllCamDesc); result.setExportAllGPSDesc(exportAllGPSDesc); return result; } @Override AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata); }
@Test public void runTest_resIsNoErrResultTypeIsPass() { Mockito.when(tracedata.getFilter()).thenReturn(analysisFilter); Mockito.when(traceResult.getTraceResultType()).thenReturn(TraceResultType.TRACE_FILE); Mockito.when((TraceDirectoryResult) tracedata.getTraceresult()).thenReturn(traceResult); acPrphlImpl = (AccessingPeripheralImpl) context.getBean("accessingPeripheral"); AbstractBestPracticeResult testResult = acPrphlImpl.runTest(tracedata); assertEquals(BPResultType.NO_DATA, testResult.getResultType()); } @Test public void runTest_resIsNoErrResultTypeIsFail() { Mockito.when(tracedata.getFilter()).thenReturn(analysisFilter); Mockito.when(timeRange.getBeginTime()).thenReturn(0.0); Mockito.when(timeRange.getEndTime()).thenReturn(100.0); Mockito.when(traceResult.getCameraActiveDuration()).thenReturn(10.0); Mockito.when(traceResult.getBluetoothActiveDuration()).thenReturn(10.0); Mockito.when(traceResult.getGpsActiveDuration()).thenReturn(10.0); Mockito.when(traceResult.getTraceResultType()).thenReturn(TraceResultType.TRACE_DIRECTORY); Mockito.when((TraceDirectoryResult) tracedata.getTraceresult()).thenReturn(traceResult); Mockito.when(analysisFilter.getTimeRange()).thenReturn(timeRange); acPrphlImpl = (AccessingPeripheralImpl) context.getBean("accessingPeripheral"); AbstractBestPracticeResult testResult = acPrphlImpl.runTest(tracedata); assertEquals(BPResultType.NO_DATA, testResult.getResultType()); }
FileCompressionImpl implements IBestPractice { @Override public AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata) { FileCompressionResult result = new FileCompressionResult(); List<TextFileCompressionEntry> resultlist = new ArrayList<TextFileCompressionEntry>(); int uncompressedCounter = 0; int compressedCounter = 0; int totalUncompressBytes = 0; int totalDownloadedBytes = 0; for(Session session: tracedata.getSessionlist()){ HttpRequestResponseInfo lastRequestObj = null; for(HttpRequestResponseInfo req:session.getRequestResponseInfo()){ if(req.getDirection() == HttpDirection.REQUEST){ lastRequestObj = req; } if(req.getPacketDirection() == PacketDirection.DOWNLINK && req.getContentLength() > 0 && req.getContentType() != null && isTextContent(req.getContentType())){ totalDownloadedBytes += req.getContentLength(); if(req.getContentEncoding() == null || req.getContentEncoding().contains("identity")){ if(req.getContentLength() > FILE_SIZE_THRESHOLD_BYTES){ uncompressedCounter++; totalUncompressBytes += req.getContentLength(); TextFileCompressionEntry tfcEntry = new TextFileCompressionEntry(req, lastRequestObj, session.getDomainName()); tfcEntry.setSavingsTextPercentage(calculateSavingForTextBasedOnGzip(req, session)); resultlist.add(tfcEntry); }else{ compressedCounter++; } }else{ compressedCounter++; } } } } result.setNoOfCompressedFiles(compressedCounter); result.setNoOfUncompressedFiles(uncompressedCounter); result.setTotalUncompressedSize(totalUncompressBytes); result.setResults(resultlist); String text = ""; if(uncompressedCounter == 0){ result.setResultType(BPResultType.PASS); }else if(totalUncompressBytes >= UNCOMPRESSED_SIZE_FAILED_THRESHOLD){ result.setResultType(BPResultType.FAIL); }else{ result.setResultType(BPResultType.WARNING); } if(result.getResultType() == BPResultType.PASS){ text = MessageFormat.format(textResultPass, ApplicationConfig.getInstance().getAppShortName(), FILE_SIZE_THRESHOLD_BYTES, FILE_SIZE_THRESHOLD_BYTES); }else{ String percentageSaving = String .valueOf(Math.round(((double) totalUncompressBytes / totalDownloadedBytes) * 100)); text = MessageFormat.format(textResults, ApplicationConfig.getInstance().getAppShortName(), totalUncompressBytes / 1024, FILE_SIZE_THRESHOLD_BYTES, percentageSaving, (totalDownloadedBytes / 1024)); } result.setResultText(text); result.setAboutText(aboutText); result.setDetailTitle(detailTitle); result.setLearnMoreUrl(learnMoreUrl); result.setOverviewTitle(overviewTitle); result.setExportAll(exportAll); result.setExportAllKb(exportAllKb); return result; } @Autowired void setHttpRequestResponseHelper(IHttpRequestResponseHelper reqhelper); @Override AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata); boolean isTextContent(String contentType); int calculateSavingForTextBasedOnGzip(HttpRequestResponseInfo req, Session session); static final int FILE_SIZE_THRESHOLD_BYTES; static final int UNCOMPRESSED_SIZE_FAILED_THRESHOLD; }
@Test public void runTest_1(){ tracedata = mock(PacketAnalyzerResult.class); session = mock(Session.class); sessionlist = new ArrayList<Session>(); sessionlist.add(session); req = mock(HttpRequestResponseInfo.class); req.setDirection(HttpDirection.REQUEST); List<HttpRequestResponseInfo> reqList = new ArrayList<HttpRequestResponseInfo>(); reqList.add(req); Mockito.when(session.getRequestResponseInfo()).thenReturn(reqList); Mockito.when(session.getDomainName()).thenReturn("mock.domain.name"); Mockito.when(tracedata.getSessionlist()).thenReturn(sessionlist); Mockito.when(req.getDirection()).thenReturn(HttpDirection.REQUEST); Mockito.when(req.getObjName()).thenReturn("mock.obj.name"); Mockito.when(req.getPacketDirection()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(req.getContentLength()).thenReturn(1001024); Mockito.when(req.getContentType()).thenReturn("message/http"); Mockito.when(req.getContentEncoding()).thenReturn("identity"); FileCompressionImpl = (FileCompressionImpl)context.getBean("textFileCompression"); AbstractBestPracticeResult result = FileCompressionImpl.runTest(tracedata); result = FileCompressionImpl.runTest(tracedata); assertEquals("Sending compressed files over the network will speed delivery, and unzipping files on a device is a very low overhead operation. Ensure that all your text files are compressed while being sent over the network.",result.getAboutText()); assertEquals("FILE_COMPRESSION", result.getBestPracticeType().toString()); assertEquals("Text File Compression",result.getDetailTitle()); assertEquals("File Download: Text File Compression",result.getOverviewTitle()); assertEquals(ApplicationConfig.getInstance().getAppShortName() + " detected 100% (977KB of 977KB) of text files were sent without compression. Adding compression will speed the delivery of your content to your customers. (Note: Only files larger than 850 bytes are flagged.)",result.getResultText()); assertEquals("FAIL",result.getResultType().toString()); } @Test public void runTest_2(){ tracedata = mock(PacketAnalyzerResult.class); session = mock(Session.class); sessionlist = new ArrayList<Session>(); sessionlist.add(session); req = mock(HttpRequestResponseInfo.class); req.setDirection(HttpDirection.REQUEST); List<HttpRequestResponseInfo> reqList = new ArrayList<HttpRequestResponseInfo>(); reqList.add(req); Mockito.when(session.getRequestResponseInfo()).thenReturn(reqList); Mockito.when(session.getDomainName()).thenReturn("mock.domain.name"); Mockito.when(tracedata.getSessionlist()).thenReturn(sessionlist); Mockito.when(req.getDirection()).thenReturn(HttpDirection.REQUEST); Mockito.when(req.getObjName()).thenReturn("mock.obj.name"); Mockito.when(req.getPacketDirection()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(req.getContentLength()).thenReturn(1); Mockito.when(req.getContentType()).thenReturn("application/.something.xml"); Mockito.when(req.getContentEncoding()).thenReturn("identity"); FileCompressionImpl = (FileCompressionImpl)context.getBean("textFileCompression"); AbstractBestPracticeResult result = FileCompressionImpl.runTest(tracedata); assertEquals("Sending compressed files over the network will speed delivery, and unzipping files on a device is a very low overhead operation. Ensure that all your text files are compressed while being sent over the network.",result.getAboutText()); assertEquals("FILE_COMPRESSION", result.getBestPracticeType().toString()); assertEquals("Text File Compression",result.getDetailTitle()); assertEquals("File Download: Text File Compression",result.getOverviewTitle()); assertEquals(ApplicationConfig.getInstance().getAppShortName() + " detected 0 text files above 850 bytes were sent without compression. Adding compression will speed the delivery of your content to your customers. (Note: Only files larger than 850 bytes are flagged.)",result.getResultText()); assertEquals("PASS",result.getResultType().toString()); } @Test public void runTest_3(){ tracedata = mock(PacketAnalyzerResult.class); session = mock(Session.class); sessionlist = new ArrayList<Session>(); sessionlist.add(session); req = mock(HttpRequestResponseInfo.class); req.setDirection(HttpDirection.REQUEST); List<HttpRequestResponseInfo> reqList = new ArrayList<HttpRequestResponseInfo>(); reqList.add(req); Mockito.when(session.getRequestResponseInfo()).thenReturn(reqList); Mockito.when(session.getDomainName()).thenReturn("mock.domain.name"); Mockito.when(tracedata.getSessionlist()).thenReturn(sessionlist); Mockito.when(req.getDirection()).thenReturn(HttpDirection.REQUEST); Mockito.when(req.getObjName()).thenReturn("mock.obj.name"); Mockito.when(req.getPacketDirection()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(req.getContentLength()).thenReturn(900); Mockito.when(req.getContentType()).thenReturn("application/.something.xml"); Mockito.when(req.getContentEncoding()).thenReturn("identity"); FileCompressionImpl = (FileCompressionImpl)context.getBean("textFileCompression"); AbstractBestPracticeResult result = FileCompressionImpl.runTest(tracedata); assertEquals("Sending compressed files over the network will speed delivery, and unzipping files on a device is a very low overhead operation. Ensure that all your text files are compressed while being sent over the network.",result.getAboutText()); assertEquals("FILE_COMPRESSION", result.getBestPracticeType().toString()); assertEquals("Text File Compression",result.getDetailTitle()); assertEquals("File Download: Text File Compression",result.getOverviewTitle()); assertEquals(ApplicationConfig.getInstance().getAppShortName() + " detected 100% (0KB of 0KB) of text files were sent without compression. Adding compression will speed the delivery of your content to your customers. (Note: Only files larger than 850 bytes are flagged.)",result.getResultText()); assertEquals("WARNING",result.getResultType().toString()); }
MinificationImpl implements IBestPractice { @Override public AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata) { htmlCompressor = null; MinificationResult result = new MinificationResult(); initHtmlCompressor(); List<MinificationEntry> minificationEntryList = new ArrayList<MinificationEntry>(); String contentType = null; int totalSavingInBytes = 0; int totalBytes= 0; final ExecutorService executorService = Executors.newFixedThreadPool(50); Collection<Worker> workers = new ArrayList<Worker>(); for (Session session : tracedata.getSessionlist()) { HttpRequestResponseInfo lastRequestObj = null; for (HttpRequestResponseInfo req : session.getRequestResponseInfo()) { if (req.getDirection() == HttpDirection.REQUEST) { lastRequestObj = req; } contentType = req.getContentType(); if (req.getDirection() == HttpDirection.RESPONSE && req.getContentLength() > 0 && contentType != null) { workers.add(new Worker(contentType, req, lastRequestObj, session)); } } } try { List<Future<MinificationEntry>> list = executorService.invokeAll(workers); for (Future<MinificationEntry> future: list){ if (future != null && future.get()!=null) { totalSavingInBytes += future.get().getSavingsSizeInByte(); totalBytes += future.get().getOriginalSizeInByte(); minificationEntryList.add(future.get()); } } } catch(InterruptedException | ExecutionException ee){ LOGGER.error(ee.getMessage(), ee); } executorService.shutdown(); int savingInKb = totalSavingInBytes / 1024; result.setTotalSavingsInKb(savingInKb); result.setTotalSavingsInByte(totalSavingInBytes); result.setMinificationEntryList(minificationEntryList); int numberOfFiles = minificationEntryList.size(); String text = ""; if (minificationEntryList.isEmpty()) { result.setResultType(BPResultType.PASS); text = MessageFormat.format(textResultPass, numberOfFiles, savingInKb); result.setResultText(text); } else if (savingInKb < 1) { result.setResultType(BPResultType.FAIL); text = MessageFormat.format(textResultFail, ApplicationConfig.getInstance().getAppShortName(), numberOfFiles); result.setResultText(text); } else { result.setResultType(BPResultType.FAIL); String percentageSaving = String.valueOf(Math.round(((double) totalSavingInBytes / totalBytes) * 100)); text = MessageFormat.format(textResults, ApplicationConfig.getInstance().getAppShortName(), numberOfFiles, savingInKb, percentageSaving); result.setResultText(text); } result.setAboutText(aboutText); result.setDetailTitle(detailTitle); result.setLearnMoreUrl(learnMoreUrl); result.setOverviewTitle(overviewTitle); result.setExportAllNumberOfMinifyFiles(exportAllNumberOfMinifyFiles); return result; } @Autowired void setHttpRequestResponseHelper(IHttpRequestResponseHelper reqhelper); @Override AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata); MinificationEntry calculateSavingMinifiedHtml(HttpRequestResponseInfo req, HttpRequestResponseInfo lastRequestObj, Session session); MinificationEntry calculateSavingMinifiedCss(HttpRequestResponseInfo req, HttpRequestResponseInfo lastRequestObj, Session session); String minifyCss(String content); MinificationEntry calculateSavingMinifiedJavascript(HttpRequestResponseInfo req, HttpRequestResponseInfo lastRequestObj, Session session); String minifyJavascript(String content); MinificationEntry calculateSavingMinifiedJson(HttpRequestResponseInfo req, HttpRequestResponseInfo lastRequestObj, Session session); String minifyJson(String jsonString); }
@Test public void runTest_1() { List<Session> sessionlist; Session session_1; session_1 = mock(Session.class); sessionlist = new ArrayList<Session>(); sessionlist.add(session_1); MinificationImpl = (MinificationImpl) context.getBean("minify"); result = MinificationImpl.runTest(tracedata); assertEquals( "Many text files contain excess whitespace to allow for better human coding. Run these files through a minifier to remove the whitespace in order to reduce file size.", result.getAboutText()); assertEquals("Minify CSS, JS and HTML", result.getDetailTitle()); assertEquals("File Download: Minify CSS, JS and HTML", result.getOverviewTitle()); assertEquals("Your trace passes.", result.getResultText()); assertEquals("MINIFICATION", result.getBestPracticeType().toString()); assertEquals("PASS", result.getResultType().toString()); }
Http4xx5xxImpl implements IBestPractice { @Override public AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata) { Http4xx5xxResult result = new Http4xx5xxResult(); Map<Integer, HttpRequestResponseInfo> firstErrorRespMap4XX = new HashMap<Integer, HttpRequestResponseInfo>(); SortedMap<Integer, Integer> httpErrorCounts4XX = new TreeMap<Integer, Integer>(); List<Http4xx5xxStatusResponseCodesEntry> httpResCodelist = new ArrayList<Http4xx5xxStatusResponseCodesEntry>(); HttpRequestResponseInfo lastRequestObj = null; for(Session session: tracedata.getSessionlist()){ lastRequestObj = null; for(HttpRequestResponseInfo req: session.getRequestResponseInfo()){ if(req.getDirection() == HttpDirection.REQUEST){ lastRequestObj = req; } if(req.getDirection() == HttpDirection.RESPONSE && HttpRequestResponseInfo.HTTP_SCHEME.equals(req.getScheme()) && req.getStatusCode() >= 400 && req.getStatusCode() < 600){ Integer code = req.getStatusCode(); Integer count = httpErrorCounts4XX.get(code); if(count != null){ httpErrorCounts4XX.put(code, count + 1); }else{ httpErrorCounts4XX.put(code, 1); firstErrorRespMap4XX.put(code, req); } httpResCodelist.add(new Http4xx5xxStatusResponseCodesEntry(req, lastRequestObj, session.getDomainName())); } } } if(httpErrorCounts4XX.isEmpty()){ result.setResultType(BPResultType.PASS); result.setResultText(textResultPass); }else{ result.setResultType(BPResultType.FAIL); result.setResultText(Http3xx4xxHelper.createFailResult(httpErrorCounts4XX, textResults, errorPlural, errorSingular)); } result.setAboutText(aboutText); result.setDetailTitle(detailTitle); result.setLearnMoreUrl(learnMoreUrl); result.setOverviewTitle(overviewTitle); result.setExportAllHttpError(exportAllHttpError); result.setFirstErrorRespMap4XX(firstErrorRespMap4XX); result.setHttpErrorCounts4XX(httpErrorCounts4XX); result.setHttpResCodelist(httpResCodelist); return result; } @Override AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata); }
@Test public void runTest_resTypeIsPass(){ Mockito.when(httpRequestInfo01.getDirection()).thenReturn(HttpDirection.RESPONSE); Mockito.when(httpRequestInfo01.getScheme()).thenReturn(HttpRequestResponseInfo.HTTP_SCHEME); Mockito.when(httpRequestInfo01.getStatusCode()).thenReturn(200); Mockito.when(httpRequestInfo02.getDirection()).thenReturn(HttpDirection.REQUEST); List<HttpRequestResponseInfo> value = new ArrayList<HttpRequestResponseInfo>(); value.add(httpRequestInfo01); value.add(httpRequestInfo02); Mockito.when(session01.getRequestResponseInfo()).thenReturn(value); Mockito.when(session01.getDomainName()).thenReturn("www.google.com"); List<Session> sessionList = new ArrayList<Session>(); sessionList.add(session01); Mockito.when(tracedata.getSessionlist()).thenReturn(sessionList); http4xx5xxImpl = (Http4xx5xxImpl) context.getBean("http4xx5xx"); AbstractBestPracticeResult result = http4xx5xxImpl.runTest(tracedata); assertEquals(BPResultType.PASS,result.getResultType() ); } @Test public void runTest_resTypeIsFail(){ Mockito.when(httpRequestInfo01.getDirection()).thenReturn(HttpDirection.RESPONSE); Mockito.when(httpRequestInfo01.getScheme()).thenReturn(HttpRequestResponseInfo.HTTP_SCHEME); Mockito.when(httpRequestInfo01.getStatusCode()).thenReturn(404); Mockito.when(httpRequestInfo01.getObjName()).thenReturn(""); Mockito.when(httpRequestInfo02.getDirection()).thenReturn(HttpDirection.REQUEST); Mockito.when(httpRequestInfo02.getObjName()).thenReturn(""); Mockito.when(httpRequestInfo03.getDirection()).thenReturn(HttpDirection.RESPONSE); Mockito.when(httpRequestInfo03.getScheme()).thenReturn(HttpRequestResponseInfo.HTTP_SCHEME); Mockito.when(httpRequestInfo03.getStatusCode()).thenReturn(505); Mockito.when(httpRequestInfo03.getObjName()).thenReturn(""); Mockito.when(httpRequestInfo04.getDirection()).thenReturn(HttpDirection.REQUEST); Mockito.when(httpRequestInfo04.getObjName()).thenReturn(""); List<HttpRequestResponseInfo> value = new ArrayList<HttpRequestResponseInfo>(); value.add(httpRequestInfo01); value.add(httpRequestInfo02); value.add(httpRequestInfo03); value.add(httpRequestInfo04); value.add(httpRequestInfo03); Mockito.when(session01.getRequestResponseInfo()).thenReturn(value); Mockito.when(session01.getDomainName()).thenReturn("www.google.com"); List<Session> sessionList = new ArrayList<Session>(); sessionList.add(session01); Mockito.when(tracedata.getSessionlist()).thenReturn(sessionList); http4xx5xxImpl = (Http4xx5xxImpl) context.getBean("http4xx5xx"); AbstractBestPracticeResult result = http4xx5xxImpl.runTest(tracedata); assertEquals(BPResultType.FAIL,result.getResultType() ); }
CacheControlImpl implements IBestPractice { @Override public AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata) { CacheControlResult result = new CacheControlResult(); if(tracedata.getCacheAnalysis() == null){ return null; } int hitNotExpiredDup = 0; int hitExpired304 = 0; for(CacheEntry entry: tracedata.getCacheAnalysis().getDiagnosisResults()){ if(entry.getDiagnosis() == Diagnosis.CACHING_DIAG_NOT_EXPIRED_DUP || entry.getDiagnosis() == Diagnosis.CACHING_DIAG_NOT_EXPIRED_DUP_PARTIALHIT){ hitNotExpiredDup++; }else if(entry.getDiagnosis() == Diagnosis.CACHING_DIAG_OBJ_NOT_CHANGED_304){ hitExpired304++; } } boolean cacheControl = (hitNotExpiredDup > hitExpired304 ? false : true); if(cacheControl){ result.setResultType(BPResultType.PASS); result.setResultText(textResultPass); }else{ result.setResultType(BPResultType.WARNING); String text = MessageFormat.format(textResults, hitNotExpiredDup,hitExpired304); result.setResultText(text); } result.setHitExpired304Count(hitExpired304); result.setHitNotExpiredDupCount(hitNotExpiredDup); result.setAboutText(aboutText); result.setDetailTitle(detailTitle); result.setLearnMoreUrl(learnMoreUrl); result.setOverviewTitle(overviewTitle); result.setExportAllCacheCon304Desc(exportAllCacheCon304Desc); result.setExportAllCacheConNExpDesc(exportAllCacheConNExpDesc); return result; } @Override AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata); }
@Test public void runTest_resTypeIsPass() { List<CacheEntry> diagnosisResults = new ArrayList<CacheEntry>(); Mockito.when(entryArray[0].getDiagnosis()).thenReturn(Diagnosis.CACHING_DIAG_CACHE_MISSED); diagnosisResults.add(entryArray[0]); Mockito.when(cacheAnalysis.getDiagnosisResults()).thenReturn(diagnosisResults); Mockito.when(tracedata.getCacheAnalysis()).thenReturn(cacheAnalysis); cacheControlImpl = (CacheControlImpl) context.getBean("cacheControl"); AbstractBestPracticeResult testResult = cacheControlImpl.runTest(tracedata); assertEquals(BPResultType.PASS, testResult.getResultType()); } @Test public void runTest_resTypeIsFail() { List<CacheEntry> diagnosisResults = new ArrayList<CacheEntry>(); Mockito.when(entryArray[0].getDiagnosis()).thenReturn(Diagnosis.CACHING_DIAG_NOT_EXPIRED_DUP); Mockito.when(entryArray[1].getDiagnosis()).thenReturn(Diagnosis.CACHING_DIAG_NOT_EXPIRED_DUP_PARTIALHIT); Mockito.when(entryArray[2].getDiagnosis()).thenReturn(Diagnosis.CACHING_DIAG_OBJ_NOT_CHANGED_304); Mockito.when(entryArray[3].getDiagnosis()).thenReturn(Diagnosis.CACHING_DIAG_NOT_EXPIRED_DUP_PARTIALHIT); Mockito.when(entryArray[4].getDiagnosis()).thenReturn(Diagnosis.CACHING_DIAG_OBJ_NOT_CHANGED_304); for (int i = 0; i < 5; i++) { diagnosisResults.add(entryArray[i]); } Mockito.when(cacheAnalysis.getDiagnosisResults()).thenReturn(diagnosisResults); Mockito.when(tracedata.getCacheAnalysis()).thenReturn(cacheAnalysis); cacheControlImpl = (CacheControlImpl) context.getBean("cacheControl"); AbstractBestPracticeResult testResult = cacheControlImpl.runTest(tracedata); assertEquals(BPResultType.WARNING, testResult.getResultType()); } @Test public void runTest_returnIsNull() { Mockito.when(tracedata.getCacheAnalysis()).thenReturn(null); cacheControlImpl = (CacheControlImpl) context.getBean("cacheControl"); AbstractBestPracticeResult testResult = cacheControlImpl.runTest(tracedata); assertNull(testResult); }
SpriteImageImpl implements IBestPractice { @Override public AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata) { SpriteImageResult result = new SpriteImageResult(); List<SpriteImageEntry> analysisResults = new ArrayList<SpriteImageEntry>(); for(Session session:tracedata.getSessionlist()){ double lastTimeStamp = 0.0; HttpRequestResponseInfo lastReqRessInfo = null; HttpRequestResponseInfo secondReqRessInfo = null; boolean thirdOccurrenceTriggered = false; for(HttpRequestResponseInfo req:session.getRequestResponseInfo()){ if(req.getDirection() == HttpDirection.RESPONSE && req.getContentType() != null && req.getFirstDataPacket() != null && req.getContentType().contains("image/") && req.getContentLength() < IMAGE_SIZE_LIMIT){ PacketInfo pktInfo = req.getFirstDataPacket(); if (lastTimeStamp == 0.0) { lastTimeStamp = pktInfo.getTimeStamp(); lastReqRessInfo = req; continue; } else{ if ((pktInfo.getTimeStamp() - lastTimeStamp) <= 5.0) { if (!thirdOccurrenceTriggered) { secondReqRessInfo = req; thirdOccurrenceTriggered = true; continue; } else { analysisResults.add(new SpriteImageEntry(lastReqRessInfo)); analysisResults.add(new SpriteImageEntry(secondReqRessInfo)); analysisResults.add(new SpriteImageEntry(req)); lastTimeStamp = 0.0; lastReqRessInfo = null; secondReqRessInfo = null; thirdOccurrenceTriggered = false; } } lastTimeStamp = pktInfo.getTimeStamp(); lastReqRessInfo = req; secondReqRessInfo = null; thirdOccurrenceTriggered = false; } } } } result.setAnalysisResults(analysisResults); String text = ""; if(analysisResults.isEmpty()){ result.setResultType(BPResultType.PASS); text = MessageFormat.format(textResultPass, analysisResults.size()); result.setResultText(text); }else{ result.setResultType(BPResultType.FAIL); text = MessageFormat.format(textResults, ApplicationConfig.getInstance().getAppShortName(), analysisResults.size()); result.setResultText(text); } result.setAboutText(aboutText); result.setDetailTitle(detailTitle); result.setLearnMoreUrl(learnMoreUrl); result.setOverviewTitle(overviewTitle); result.setExportAllNumberOfSpriteFiles(exportAllNumberOfSpriteFiles); return result; } @Override AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata); }
@Test public void runTest_resIsPass(){ Mockito.when(httpRequestInfo01.getDirection()).thenReturn(HttpDirection.RESPONSE); Mockito.when(httpRequestInfo01.getContentType()).thenReturn("abc"); Mockito.when(httpRequestInfo01.getContentLength()).thenReturn(6145); Mockito.when(httpRequestInfo02.getDirection()).thenReturn(HttpDirection.REQUEST); Mockito.when(httpRequestInfo03.getDirection()).thenReturn(HttpDirection.RESPONSE); Mockito.when(httpRequestInfo04.getDirection()).thenReturn(HttpDirection.RESPONSE); List<HttpRequestResponseInfo> value = new ArrayList<HttpRequestResponseInfo>(); value.add(httpRequestInfo01); value.add(httpRequestInfo02); value.add(httpRequestInfo03); value.add(httpRequestInfo04); Mockito.when(session01.getRequestResponseInfo()).thenReturn(value); List<Session> sessionList = new ArrayList<Session>(); Mockito.when(session01.getDomainName()).thenReturn("www.google.com"); sessionList.add(session01); Mockito.when(tracedata.getSessionlist()).thenReturn(sessionList); AbstractBestPracticeResult testResult = spriteImageImpl.runTest(tracedata); assertEquals(BPResultType.PASS,testResult.getResultType() ); } @Test public void runTest_resIsFail(){ Date date = new Date(); Mockito.when(httpRequestInfo01.getDirection()).thenReturn(HttpDirection.RESPONSE); Mockito.when(httpRequestInfo01.getFirstDataPacket()).thenReturn(pktInfo01); Mockito.when(httpRequestInfo01.getContentType()).thenReturn("image/"); Mockito.when(httpRequestInfo01.getContentLength()).thenReturn(1); Mockito.when(httpRequestInfo02.getDirection()).thenReturn(HttpDirection.REQUEST); Mockito.when(httpRequestInfo02.getContentType()).thenReturn(null); Mockito.when(httpRequestInfo02.getContentLength()).thenReturn(0); Mockito.when(httpRequestInfo03.getDirection()).thenReturn(HttpDirection.RESPONSE); Mockito.when(httpRequestInfo03.getFirstDataPacket()).thenReturn(pktInfo02); Mockito.when(httpRequestInfo03.getContentType()).thenReturn("image/"); Mockito.when(httpRequestInfo03.getContentLength()).thenReturn(2); Mockito.when(httpRequestInfo04.getDirection()).thenReturn(HttpDirection.RESPONSE); Mockito.when(httpRequestInfo04.getFirstDataPacket()).thenReturn(pktInfo01); Mockito.when(httpRequestInfo04.getContentType()).thenReturn("image/"); Mockito.when(httpRequestInfo04.getContentLength()).thenReturn(3); Mockito.when(pktInfo01.getTimeStamp()).thenReturn((date.getTime())/1000+0.0); Mockito.when(pktInfo02.getTimeStamp()).thenReturn((date.getTime()/1000)+1.0); List<HttpRequestResponseInfo> value = new ArrayList<HttpRequestResponseInfo>(); value.add(httpRequestInfo01); value.add(httpRequestInfo02); value.add(httpRequestInfo03); value.add(httpRequestInfo04); Mockito.when(session01.getRequestResponseInfo()).thenReturn(value); List<Session> sessionList = new ArrayList<Session>(); Mockito.when(session01.getDomainName()).thenReturn("www.google.com"); sessionList.add(session01); Mockito.when(tracedata.getSessionlist()).thenReturn(sessionList); AbstractBestPracticeResult testResult = spriteImageImpl.runTest(tracedata); assertEquals(BPResultType.FAIL,testResult.getResultType() ); }
Http3xxCodeImpl implements IBestPractice { @Override public AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata) { Http3xxCodeResult result = new Http3xxCodeResult(); SortedMap<Integer, Integer> httpRedirectCounts3XX = new TreeMap<Integer, Integer>(); Map<Integer, HttpRequestResponseInfo> firstResMap = new HashMap<Integer, HttpRequestResponseInfo>(); List<HttpCode3xxEntry> httprescodelist = new ArrayList<HttpCode3xxEntry>(); HttpRequestResponseInfo lastRequestObj = null; for(Session session: tracedata.getSessionlist()){ lastRequestObj = null; for(HttpRequestResponseInfo req: session.getRequestResponseInfo()){ if(req.getDirection() == HttpDirection.REQUEST){ lastRequestObj = req; } if(req.getDirection() == HttpDirection.RESPONSE && HttpRequestResponseInfo.HTTP_SCHEME.equals(req.getScheme()) && req.getStatusCode() >= 300 && req.getStatusCode() < 400){ Integer code = req.getStatusCode(); Integer count = httpRedirectCounts3XX.get(code); if(count != null){ httpRedirectCounts3XX.put(code, count + 1); }else{ httpRedirectCounts3XX.put(code, 1); firstResMap.put(code, req); } httprescodelist.add(new HttpCode3xxEntry(req, lastRequestObj, session.getDomainName())); } } } if(httpRedirectCounts3XX.isEmpty()){ result.setResultType(BPResultType.PASS); result.setResultText(textResultPass); }else{ result.setResultType(BPResultType.FAIL); result.setResultText(Http3xx4xxHelper.createFailResult(httpRedirectCounts3XX, textResults, errorPlural, errorSingular)); } result.setAboutText(aboutText); result.setDetailTitle(detailTitle); result.setLearnMoreUrl(learnMoreUrl); result.setOverviewTitle(overviewTitle); result.setExportAllHttpError(exportAllHttpError); result.setHttp3xxResCode(httprescodelist); result.setHttpRedirectCounts3XX(httpRedirectCounts3XX); result.setFirstResMap(firstResMap); return result; } @Override AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata); }
@Test public void runTest_resTypeIsPass() { Mockito.when(httpRequestInfo01.getDirection()).thenReturn(HttpDirection.RESPONSE); Mockito.when(httpRequestInfo01.getScheme()).thenReturn(HttpRequestResponseInfo.HTTP_SCHEME); Mockito.when(httpRequestInfo01.getStatusCode()).thenReturn(200); Mockito.when(httpRequestInfo02.getDirection()).thenReturn(HttpDirection.REQUEST); List<HttpRequestResponseInfo> value = new ArrayList<HttpRequestResponseInfo>(); value.add(httpRequestInfo01); value.add(httpRequestInfo02); Mockito.when(session01.getRequestResponseInfo()).thenReturn(value); Mockito.when(session01.getDomainName()).thenReturn("www.google.com"); List<Session> sessionList = new ArrayList<Session>(); sessionList.add(session01); Mockito.when(tracedata.getSessionlist()).thenReturn(sessionList); http3xxCodeImpl = (Http3xxCodeImpl) context.getBean("http3xx"); AbstractBestPracticeResult result = http3xxCodeImpl.runTest(tracedata); assertEquals(BPResultType.PASS, result.getResultType()); } @Test public void runTest_resTypeIsFail() { Mockito.when(httpRequestInfo01.getDirection()).thenReturn(HttpDirection.RESPONSE); Mockito.when(httpRequestInfo01.getScheme()).thenReturn(HttpRequestResponseInfo.HTTP_SCHEME); Mockito.when(httpRequestInfo01.getStatusCode()).thenReturn(304); Mockito.when(httpRequestInfo01.getObjName()).thenReturn(""); Mockito.when(httpRequestInfo02.getDirection()).thenReturn(HttpDirection.REQUEST); Mockito.when(httpRequestInfo02.getObjName()).thenReturn(""); Mockito.when(httpRequestInfo03.getDirection()).thenReturn(HttpDirection.RESPONSE); Mockito.when(httpRequestInfo03.getScheme()).thenReturn(HttpRequestResponseInfo.HTTP_SCHEME); Mockito.when(httpRequestInfo03.getStatusCode()).thenReturn(304); Mockito.when(httpRequestInfo03.getObjName()).thenReturn(""); Mockito.when(httpRequestInfo04.getDirection()).thenReturn(HttpDirection.REQUEST); Mockito.when(httpRequestInfo04.getObjName()).thenReturn(""); List<HttpRequestResponseInfo> value = new ArrayList<HttpRequestResponseInfo>(); value.add(httpRequestInfo01); value.add(httpRequestInfo02); value.add(httpRequestInfo03); value.add(httpRequestInfo04); Mockito.when(session01.getRequestResponseInfo()).thenReturn(value); Mockito.when(session01.getDomainName()).thenReturn("www.google.com"); List<Session> sessionList = new ArrayList<Session>(); sessionList.add(session01); Mockito.when(tracedata.getSessionlist()).thenReturn(sessionList); http3xxCodeImpl = (Http3xxCodeImpl) context.getBean("http3xx"); AbstractBestPracticeResult result = http3xxCodeImpl.runTest(tracedata); assertEquals(BPResultType.FAIL, result.getResultType()); }
AdbServiceImpl implements IAdbService { @Override public boolean installPayloadFile(IAroDevice aroDevice, String tempFolder, String payloadFileName, String remotepath) { return installPayloadFile((IDevice)aroDevice.getDevice(), tempFolder, payloadFileName, remotepath); } @Autowired void setAndroid(IAndroid android); @Autowired void setExternalProcessRunner(IExternalProcessRunner runner); @Autowired void setFileExtactor(IReadWriteFileExtractor extractor); @Autowired void setFileManager(IFileManager fileManager); @Autowired void setAROConfigFile(Settings configFile); @Override boolean hasADBpath(); @Override String getAdbPath(); @Override String getAdbPath(boolean unfiltered); @Override boolean isAdbFileExist(); @Override AndroidDebugBridge initCreateBridge(String adbPath); @Override AndroidDebugBridge ensureADBServiceStarted(); @Override IDevice[] getConnectedDevices(); @Override FileEntry locate(IDevice device, FileEntry rootPath, String path); boolean pullFile(SyncService service, String remotePath, String file, String localFolder); @Override boolean installPayloadFile(IAroDevice aroDevice, String tempFolder, String payloadFileName, String remotepath); @Override boolean installPayloadFile(IDevice device, String tempFolder, String payloadFileName, String remotepath); @Override String[] getApplicationList(String id); }
@Test public void installPayloadFile() throws Exception { IAroDevice aroDevice = Mockito.mock(IAroDevice.class); Mockito.when(aroDevice.getDevice()).thenReturn(device); Mockito.when(extractor.extractFiles(Mockito.anyString(), Mockito.anyString(), Mockito.any(ClassLoader.class))).thenReturn(true); Mockito.when(android.pushFile(Mockito.any(IDevice.class), Mockito.anyString(), Mockito.anyString())).thenReturn(true); Mockito.when(fileManager.deleteFile(Mockito.anyString())).thenReturn(true); boolean success = adbService.installPayloadFile(aroDevice, "local", "file", "remote"); assertTrue(success); }
AdbServiceImpl implements IAdbService { public boolean pullFile(SyncService service, String remotePath, String file, String localFolder) { try { service.pullFile( remotePath + file , localFolder + "/" + file , SyncService.getNullProgressMonitor()); } catch (SyncException | TimeoutException | IOException e) { LOGGER.error("pull " + file + ":" + e.getMessage()); return false; } return true; } @Autowired void setAndroid(IAndroid android); @Autowired void setExternalProcessRunner(IExternalProcessRunner runner); @Autowired void setFileExtactor(IReadWriteFileExtractor extractor); @Autowired void setFileManager(IFileManager fileManager); @Autowired void setAROConfigFile(Settings configFile); @Override boolean hasADBpath(); @Override String getAdbPath(); @Override String getAdbPath(boolean unfiltered); @Override boolean isAdbFileExist(); @Override AndroidDebugBridge initCreateBridge(String adbPath); @Override AndroidDebugBridge ensureADBServiceStarted(); @Override IDevice[] getConnectedDevices(); @Override FileEntry locate(IDevice device, FileEntry rootPath, String path); boolean pullFile(SyncService service, String remotePath, String file, String localFolder); @Override boolean installPayloadFile(IAroDevice aroDevice, String tempFolder, String payloadFileName, String remotepath); @Override boolean installPayloadFile(IDevice device, String tempFolder, String payloadFileName, String remotepath); @Override String[] getApplicationList(String id); }
@Test public void pullFile() throws Exception { SyncService syncservice = Mockito.mock(SyncService.class); Mockito.doNothing().when(syncservice).pullFile(Mockito.anyString(), Mockito.anyString(), (ISyncProgressMonitor) Mockito.any()); boolean success = adbService.pullFile(syncservice, "remote", "file", "local"); assertTrue(success); } @SuppressWarnings("rawtypes") @Test public void fail_pullFile() throws Exception { SyncService syncservice = Mockito.mock(SyncService.class); Mockito.doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { throw new IOException("its Mocking!"); } }).when(syncservice).pullFile(Mockito.anyString(), Mockito.anyString(), (ISyncProgressMonitor) Mockito.any()); boolean success = adbService.pullFile(syncservice, "remote", "file", "local"); assertTrue(!success); }
AdbServiceImpl implements IAdbService { @Override public boolean hasADBpath() { boolean result = false; String adbPath = getAROConfigFileLocation(); if (adbPath != null && adbPath.length() > 3) { result = true; } return result; } @Autowired void setAndroid(IAndroid android); @Autowired void setExternalProcessRunner(IExternalProcessRunner runner); @Autowired void setFileExtactor(IReadWriteFileExtractor extractor); @Autowired void setFileManager(IFileManager fileManager); @Autowired void setAROConfigFile(Settings configFile); @Override boolean hasADBpath(); @Override String getAdbPath(); @Override String getAdbPath(boolean unfiltered); @Override boolean isAdbFileExist(); @Override AndroidDebugBridge initCreateBridge(String adbPath); @Override AndroidDebugBridge ensureADBServiceStarted(); @Override IDevice[] getConnectedDevices(); @Override FileEntry locate(IDevice device, FileEntry rootPath, String path); boolean pullFile(SyncService service, String remotePath, String file, String localFolder); @Override boolean installPayloadFile(IAroDevice aroDevice, String tempFolder, String payloadFileName, String remotepath); @Override boolean installPayloadFile(IDevice device, String tempFolder, String payloadFileName, String remotepath); @Override String[] getApplicationList(String id); }
@Test public void hasADBpath() { Mockito.when(getADBAttribute()).thenReturn(adbPath); boolean result = adbService.hasADBpath(); assertTrue(result); Mockito.when(getADBAttribute()).thenReturn(null); result = adbService.hasADBpath(); assertTrue(!result); Mockito.when(getADBAttribute()).thenReturn("adb"); assertTrue(!adbService.hasADBpath()); }
AdbServiceImpl implements IAdbService { @Override public String getAdbPath() { return verifyAdbPath(getAROConfigFileLocation(), false); } @Autowired void setAndroid(IAndroid android); @Autowired void setExternalProcessRunner(IExternalProcessRunner runner); @Autowired void setFileExtactor(IReadWriteFileExtractor extractor); @Autowired void setFileManager(IFileManager fileManager); @Autowired void setAROConfigFile(Settings configFile); @Override boolean hasADBpath(); @Override String getAdbPath(); @Override String getAdbPath(boolean unfiltered); @Override boolean isAdbFileExist(); @Override AndroidDebugBridge initCreateBridge(String adbPath); @Override AndroidDebugBridge ensureADBServiceStarted(); @Override IDevice[] getConnectedDevices(); @Override FileEntry locate(IDevice device, FileEntry rootPath, String path); boolean pullFile(SyncService service, String remotePath, String file, String localFolder); @Override boolean installPayloadFile(IAroDevice aroDevice, String tempFolder, String payloadFileName, String remotepath); @Override boolean installPayloadFile(IDevice device, String tempFolder, String payloadFileName, String remotepath); @Override String[] getApplicationList(String id); }
@Test public void getAdbPath() { Mockito.when(getADBAttribute()).thenReturn(adbPath); String path = adbService.getAdbPath(); assertTrue(path == null); }
AdbServiceImpl implements IAdbService { @Override public boolean isAdbFileExist() { return fileManager.fileExist(getAROConfigFileLocation()); } @Autowired void setAndroid(IAndroid android); @Autowired void setExternalProcessRunner(IExternalProcessRunner runner); @Autowired void setFileExtactor(IReadWriteFileExtractor extractor); @Autowired void setFileManager(IFileManager fileManager); @Autowired void setAROConfigFile(Settings configFile); @Override boolean hasADBpath(); @Override String getAdbPath(); @Override String getAdbPath(boolean unfiltered); @Override boolean isAdbFileExist(); @Override AndroidDebugBridge initCreateBridge(String adbPath); @Override AndroidDebugBridge ensureADBServiceStarted(); @Override IDevice[] getConnectedDevices(); @Override FileEntry locate(IDevice device, FileEntry rootPath, String path); boolean pullFile(SyncService service, String remotePath, String file, String localFolder); @Override boolean installPayloadFile(IAroDevice aroDevice, String tempFolder, String payloadFileName, String remotepath); @Override boolean installPayloadFile(IDevice device, String tempFolder, String payloadFileName, String remotepath); @Override String[] getApplicationList(String id); }
@Test public void isAdbFileExist() throws Exception { Mockito.when(fileManager.fileExist(Mockito.anyString())).thenReturn(true); boolean adbExists = adbService.isAdbFileExist(); assertTrue(adbExists); Mockito.when(fileManager.fileExist(Mockito.anyString())).thenReturn(false); adbExists = adbService.isAdbFileExist(); assertTrue(!adbExists); }
AdbServiceImpl implements IAdbService { @Override public AndroidDebugBridge ensureADBServiceStarted() { AndroidDebugBridge adb = null; adb = AndroidDebugBridge.getBridge(); if (adb != null && adb.isConnected()) { return adb; } String adbPath = getAdbPath(true); if (adbPath != null && adbPath.length() > 3) { adb = initCreateBridge(adbPath); if (adb != null) { int attempt = 1; while (attempt-- > 0 && !checkAdb(adb)) { adb = AndroidDebugBridge.createBridge(adbPath, true); } if (adb == null || !adb.hasInitialDeviceList()) { LOGGER.error("ADB bridge not working or failed to connect."); adb = null; } } else { LOGGER.info("Failed to create ADB Bridge, unable to connect."); } } else { LOGGER.info("No ADB path found, failed to create ADB Bridge."); } return adb; } @Autowired void setAndroid(IAndroid android); @Autowired void setExternalProcessRunner(IExternalProcessRunner runner); @Autowired void setFileExtactor(IReadWriteFileExtractor extractor); @Autowired void setFileManager(IFileManager fileManager); @Autowired void setAROConfigFile(Settings configFile); @Override boolean hasADBpath(); @Override String getAdbPath(); @Override String getAdbPath(boolean unfiltered); @Override boolean isAdbFileExist(); @Override AndroidDebugBridge initCreateBridge(String adbPath); @Override AndroidDebugBridge ensureADBServiceStarted(); @Override IDevice[] getConnectedDevices(); @Override FileEntry locate(IDevice device, FileEntry rootPath, String path); boolean pullFile(SyncService service, String remotePath, String file, String localFolder); @Override boolean installPayloadFile(IAroDevice aroDevice, String tempFolder, String payloadFileName, String remotepath); @Override boolean installPayloadFile(IDevice device, String tempFolder, String payloadFileName, String remotepath); @Override String[] getApplicationList(String id); }
@Test public void XXyensureADBServiceStarted() { Mockito.when(fileManager.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(getADBAttribute()).thenReturn(adbPath); androidDebugBridge = PowerMockito.mock(AndroidDebugBridge.class); PowerMockito.when(androidDebugBridge.hasInitialDeviceList()).thenReturn(false); PowerMockito.mockStatic(AndroidDebugBridge.class, new Answer<AndroidDebugBridge>() { int activated = 0; @Override public AndroidDebugBridge answer(InvocationOnMock invocation) throws Throwable { String method = invocation.getMethod().getName(); Object[] args = invocation.getArguments(); if (method.matches("getBridge")) { if (activated == 1) { PowerMockito.when(androidDebugBridge.hasInitialDeviceList()).thenReturn(true); return androidDebugBridge; } return null; } else if (method.matches("init")) { activated++; return null; } else if (method.matches("createBridge")) { if (args.length == 0) { PowerMockito.when(androidDebugBridge.hasInitialDeviceList()).thenReturn(false); return androidDebugBridge; } else { PowerMockito.when(androidDebugBridge.hasInitialDeviceList()).thenReturn(true); return androidDebugBridge; } } return null; } }); AndroidDebugBridge adb = adbService.ensureADBServiceStarted(); assertTrue(adb != null); } @Test public void ensureADBServiceStarted() { Mockito.when(fileManager.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(getADBAttribute()).thenReturn(adbPath); androidDebugBridge = PowerMockito.mock(AndroidDebugBridge.class); PowerMockito.mockStatic(AndroidDebugBridge.class); PowerMockito.when(androidDebugBridge.hasInitialDeviceList()).thenReturn(false); PowerMockito.mockStatic(AndroidDebugBridge.class, new Answer<AndroidDebugBridge>() { boolean activated = false; @Override public AndroidDebugBridge answer(InvocationOnMock invocation) throws Throwable { String method = invocation.getMethod().getName(); if (method.matches("getBridge")) { if (activated) { PowerMockito.when(androidDebugBridge.hasInitialDeviceList()).thenReturn(true); return androidDebugBridge; } return null; } else if (method.matches("initIfNeeded")) { activated = true; return null; } else if (method.matches("createBridge")) { if (activated) { PowerMockito.when(androidDebugBridge.hasInitialDeviceList()).thenReturn(true); return androidDebugBridge; } else { PowerMockito.when(androidDebugBridge.hasInitialDeviceList()).thenReturn(false); return androidDebugBridge; } } return null; } }); AndroidDebugBridge adb = adbService.ensureADBServiceStarted(); assertTrue(adb != null); } @Test public void _02_ensureADBServiceStarted() { Mockito.when(fileManager.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(getADBAttribute()).thenReturn(adbPath); androidDebugBridge = PowerMockito.mock(AndroidDebugBridge.class); PowerMockito.mockStatic(AndroidDebugBridge.class); PowerMockito.when(AndroidDebugBridge.getBridge()).thenReturn(null); PowerMockito.when(AndroidDebugBridge.createBridge(adbPath, false)).thenReturn(androidDebugBridge); AndroidDebugBridge adb = adbService.ensureADBServiceStarted(); assertTrue(adb == null); } @Test public void Null_ensureADBServiceStarted() { Mockito.when(fileManager.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(getADBAttribute()).thenReturn(adbPath); PowerMockito.mockStatic(AndroidDebugBridge.class); PowerMockito.when(AndroidDebugBridge.getBridge()).thenReturn(null); AndroidDebugBridge adb = adbService.ensureADBServiceStarted(); assertTrue(adb == null); }
AdbServiceImpl implements IAdbService { boolean runAdbCommand() { String lines = ""; try { lines = extrunner.runGetString("adb devices"); } catch (IOException e) { LOGGER.error(e.getMessage()); } if (lines.contains("command not found") || lines.contains("not recognized") || lines.contains("No such file") || lines.contains("Cannot run")) { return false; } if (lines.length() > 0) { return true; } return false; } @Autowired void setAndroid(IAndroid android); @Autowired void setExternalProcessRunner(IExternalProcessRunner runner); @Autowired void setFileExtactor(IReadWriteFileExtractor extractor); @Autowired void setFileManager(IFileManager fileManager); @Autowired void setAROConfigFile(Settings configFile); @Override boolean hasADBpath(); @Override String getAdbPath(); @Override String getAdbPath(boolean unfiltered); @Override boolean isAdbFileExist(); @Override AndroidDebugBridge initCreateBridge(String adbPath); @Override AndroidDebugBridge ensureADBServiceStarted(); @Override IDevice[] getConnectedDevices(); @Override FileEntry locate(IDevice device, FileEntry rootPath, String path); boolean pullFile(SyncService service, String remotePath, String file, String localFolder); @Override boolean installPayloadFile(IAroDevice aroDevice, String tempFolder, String payloadFileName, String remotepath); @Override boolean installPayloadFile(IDevice device, String tempFolder, String payloadFileName, String remotepath); @Override String[] getApplicationList(String id); }
@Test public void runAdbCommandTest() throws IOException { Mockito.when(processRunner.runGetString(Mockito.anyString())).thenReturn("Test Command"); boolean adbCmdFlg = adbService.runAdbCommand(); assertTrue(adbCmdFlg); Mockito.when(processRunner.runGetString(Mockito.anyString())).thenReturn("Cannot run"); boolean adbCmdFlg1 = adbService.runAdbCommand(); assertTrue(!adbCmdFlg1); Mockito.when(processRunner.runGetString(Mockito.anyString())).thenReturn(""); boolean adbCmdFlg2 = adbService.runAdbCommand(); assertTrue(!adbCmdFlg2); }
AdbServiceImpl implements IAdbService { @Override public IDevice[] getConnectedDevices() throws IOException{ AndroidDebugBridge adb = ensureADBServiceStarted(); if (adb == null) { LOGGER.debug("failed to connect to existing bridge, now trying running adb from environment"); throw new IOException("AndroidDebugBridge failed to start"); } int waitcount = 1; while (waitcount <= 20 && !adb.hasInitialDeviceList()) { try { Thread.sleep(100); } catch (InterruptedException ex) { } waitcount++; } return adb.getDevices(); } @Autowired void setAndroid(IAndroid android); @Autowired void setExternalProcessRunner(IExternalProcessRunner runner); @Autowired void setFileExtactor(IReadWriteFileExtractor extractor); @Autowired void setFileManager(IFileManager fileManager); @Autowired void setAROConfigFile(Settings configFile); @Override boolean hasADBpath(); @Override String getAdbPath(); @Override String getAdbPath(boolean unfiltered); @Override boolean isAdbFileExist(); @Override AndroidDebugBridge initCreateBridge(String adbPath); @Override AndroidDebugBridge ensureADBServiceStarted(); @Override IDevice[] getConnectedDevices(); @Override FileEntry locate(IDevice device, FileEntry rootPath, String path); boolean pullFile(SyncService service, String remotePath, String file, String localFolder); @Override boolean installPayloadFile(IAroDevice aroDevice, String tempFolder, String payloadFileName, String remotepath); @Override boolean installPayloadFile(IDevice device, String tempFolder, String payloadFileName, String remotepath); @Override String[] getApplicationList(String id); }
@Test public void getConnectedDevicesTest() { Mockito.when(fileManager.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(getADBAttribute()).thenReturn(adbPath); androidDebugBridge = PowerMockito.mock(AndroidDebugBridge.class); IDevice aDevice1 = Mockito.mock(IDevice.class); IDevice[] devices = { aDevice1 }; PowerMockito.mockStatic(AndroidDebugBridge.class); PowerMockito.when(androidDebugBridge.hasInitialDeviceList()).thenReturn(false); PowerMockito.when(androidDebugBridge.getDevices()).thenReturn(devices); PowerMockito.mockStatic(AndroidDebugBridge.class, new Answer<AndroidDebugBridge>() { boolean activated = false; @Override public AndroidDebugBridge answer(InvocationOnMock invocation) throws Throwable { String method = invocation.getMethod().getName(); System.out.println("invocation:" + method); if (method.matches("getBridge")) { if (activated) { PowerMockito.when(androidDebugBridge.hasInitialDeviceList()).thenReturn(true); return androidDebugBridge; } return null; } else if (method.matches("initIfNeeded")) { activated = true; return null; } else if (method.matches("createBridge")) { if (activated) { PowerMockito.when(androidDebugBridge.hasInitialDeviceList()).thenReturn(true); return androidDebugBridge; } else { PowerMockito.when(androidDebugBridge.hasInitialDeviceList()).thenReturn(false); return androidDebugBridge; } } return null; } }); IDevice[] getDevices = null; try { getDevices = adbService.getConnectedDevices(); } catch (Exception e) { } assertTrue(getDevices == devices); } @Test public void getConnectedDevicesTestFailsConnect() { Mockito.when(fileManager.fileExist(Mockito.anyString())).thenReturn(false); Mockito.when(getADBAttribute()).thenReturn(adbPath); androidDebugBridge = PowerMockito.mock(AndroidDebugBridge.class); IDevice aDevice1 = Mockito.mock(IDevice.class); IDevice[] devices = { aDevice1 }; PowerMockito.mockStatic(AndroidDebugBridge.class); PowerMockito.when(androidDebugBridge.hasInitialDeviceList()).thenReturn(false); PowerMockito.when(androidDebugBridge.getDevices()).thenReturn(devices); PowerMockito.mockStatic(AndroidDebugBridge.class, new Answer<AndroidDebugBridge>() { boolean activated = false; @Override public AndroidDebugBridge answer(InvocationOnMock invocation) throws Throwable { String method = invocation.getMethod().getName(); System.out.println("invocation:" + method); if (method.matches("getBridge")) { if (activated) { PowerMockito.when(androidDebugBridge.hasInitialDeviceList()).thenReturn(true); return androidDebugBridge; } return null; } else if (method.matches("init")) { activated = true; return null; } else if (method.matches("createBridge")) { if (activated) { PowerMockito.when(androidDebugBridge.hasInitialDeviceList()).thenReturn(true); return androidDebugBridge; } else { PowerMockito.when(androidDebugBridge.hasInitialDeviceList()).thenReturn(false); return androidDebugBridge; } } return null; } }); IDevice[] getDevices = null; try { getDevices = adbService.getConnectedDevices(); } catch (Exception e) { } assertTrue(getDevices == null); }
AndroidImpl implements IAndroid { @Override public boolean isEmulator(IDevice device) { return device.isEmulator(); } boolean setExecutePermission(IDevice device, String remotePath); @Override boolean isEmulator(IDevice device); ShellOutputReceiver getShellOutput(); ShellCommandCheckSDCardOutputReceiver getOutputReturn(); @Override boolean pushFile(IDevice emulator, String local, String remote); @Override DeviceState getState(IDevice device); @Override boolean isSDCardAttached(IDevice device); @Override boolean isSDCardEnoughSpace(IDevice device, long kbs); @Override boolean pullTraceFilesFromEmulator(IDevice device, String remoteFilepath, String localFilename); @Override boolean pullTraceFilesFromDevice(IDevice device, String remoteFilepath, String localFilename); @Override boolean makeAROTraceDirectory(IDevice device, String traceName); @Override boolean makeDirectory(IDevice device, String dirpath); @Override String getProperty(IDevice device, String property); @Override SyncService getSyncService(IDevice device); @Override boolean removeEmulatorData(IDevice device, String deviceTracePath); @Override boolean stopTcpDump(IDevice device); Socket getLocalSocket(); @Override boolean checkTcpDumpRunning(IDevice device); @Override boolean startTcpDump(IDevice device, boolean seLinuxEnforced, String traceFolderName); @Override boolean isTraceRunning(); @Override String[] getShellReturn(IDevice device, String arocmd); @Override boolean checkPackageExist(IDevice device, String fullpackageName); @Override boolean runApkInDevice(IDevice device, String cmd); @Override boolean runVpnApkInDevice(IDevice device); }
@Test public void isEmulator_ResultIsTrue() { IDevice device = mock(IDevice.class); when(device.isEmulator()).thenReturn(true); assertTrue(androidImpl.isEmulator(device)); } @Test public void isEmulator_ResultIsFalse() { IDevice device = mock(IDevice.class); when(device.isEmulator()).thenReturn(false); assertFalse(androidImpl.isEmulator(device)); }
AndroidImpl implements IAndroid { @Override public DeviceState getState(IDevice device) { return device.getState(); } boolean setExecutePermission(IDevice device, String remotePath); @Override boolean isEmulator(IDevice device); ShellOutputReceiver getShellOutput(); ShellCommandCheckSDCardOutputReceiver getOutputReturn(); @Override boolean pushFile(IDevice emulator, String local, String remote); @Override DeviceState getState(IDevice device); @Override boolean isSDCardAttached(IDevice device); @Override boolean isSDCardEnoughSpace(IDevice device, long kbs); @Override boolean pullTraceFilesFromEmulator(IDevice device, String remoteFilepath, String localFilename); @Override boolean pullTraceFilesFromDevice(IDevice device, String remoteFilepath, String localFilename); @Override boolean makeAROTraceDirectory(IDevice device, String traceName); @Override boolean makeDirectory(IDevice device, String dirpath); @Override String getProperty(IDevice device, String property); @Override SyncService getSyncService(IDevice device); @Override boolean removeEmulatorData(IDevice device, String deviceTracePath); @Override boolean stopTcpDump(IDevice device); Socket getLocalSocket(); @Override boolean checkTcpDumpRunning(IDevice device); @Override boolean startTcpDump(IDevice device, boolean seLinuxEnforced, String traceFolderName); @Override boolean isTraceRunning(); @Override String[] getShellReturn(IDevice device, String arocmd); @Override boolean checkPackageExist(IDevice device, String fullpackageName); @Override boolean runApkInDevice(IDevice device, String cmd); @Override boolean runVpnApkInDevice(IDevice device); }
@Test public void getState_returnIsState() { IDevice device = mock(IDevice.class); when(device.getState()).thenReturn(DeviceState.ONLINE); assertEquals(DeviceState.ONLINE, androidImpl.getState(device)); }
AndroidImpl implements IAndroid { @Override public boolean removeEmulatorData(IDevice device, String deviceTracePath) { boolean success = false; boolean result1 = executeShellCommand(device, "rm " + deviceTracePath + "/*"); LOGGER.debug("remove files under " + deviceTracePath + ": " + result1); boolean result2 = executeShellCommand(device, "rm -fr " + deviceTracePath); LOGGER.debug("remove dir " + deviceTracePath + ": " + result2); if (result1 && result2) { success = true; } return success; } boolean setExecutePermission(IDevice device, String remotePath); @Override boolean isEmulator(IDevice device); ShellOutputReceiver getShellOutput(); ShellCommandCheckSDCardOutputReceiver getOutputReturn(); @Override boolean pushFile(IDevice emulator, String local, String remote); @Override DeviceState getState(IDevice device); @Override boolean isSDCardAttached(IDevice device); @Override boolean isSDCardEnoughSpace(IDevice device, long kbs); @Override boolean pullTraceFilesFromEmulator(IDevice device, String remoteFilepath, String localFilename); @Override boolean pullTraceFilesFromDevice(IDevice device, String remoteFilepath, String localFilename); @Override boolean makeAROTraceDirectory(IDevice device, String traceName); @Override boolean makeDirectory(IDevice device, String dirpath); @Override String getProperty(IDevice device, String property); @Override SyncService getSyncService(IDevice device); @Override boolean removeEmulatorData(IDevice device, String deviceTracePath); @Override boolean stopTcpDump(IDevice device); Socket getLocalSocket(); @Override boolean checkTcpDumpRunning(IDevice device); @Override boolean startTcpDump(IDevice device, boolean seLinuxEnforced, String traceFolderName); @Override boolean isTraceRunning(); @Override String[] getShellReturn(IDevice device, String arocmd); @Override boolean checkPackageExist(IDevice device, String fullpackageName); @Override boolean runApkInDevice(IDevice device, String cmd); @Override boolean runVpnApkInDevice(IDevice device); }
@Test public void removeEmulatorData() throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException, IOException { IDevice device = mock(IDevice.class); doNothing().when(device).executeShellCommand(any(String.class), any(IShellOutputReceiver.class)); assertTrue(androidImpl.removeEmulatorData(device, Util.getCurrentRunningDir())); }
AndroidImpl implements IAndroid { @Override public boolean startTcpDump(IDevice device, boolean seLinuxEnforced, String traceFolderName) { String tcpName = TCPDUMP_PATH + (seLinuxEnforced ? "_pie" : ""); String strTcpDumpCommand = tcpName + " -w " + traceFolderName + (seLinuxEnforced ? " \"tcp port not 5555\"" : " port not 5555"); LOGGER.info("tcp >> >" + strTcpDumpCommand + ">"); traceRunning = true; boolean result = executeShellCommand(device, strTcpDumpCommand); traceRunning = false; return result; } boolean setExecutePermission(IDevice device, String remotePath); @Override boolean isEmulator(IDevice device); ShellOutputReceiver getShellOutput(); ShellCommandCheckSDCardOutputReceiver getOutputReturn(); @Override boolean pushFile(IDevice emulator, String local, String remote); @Override DeviceState getState(IDevice device); @Override boolean isSDCardAttached(IDevice device); @Override boolean isSDCardEnoughSpace(IDevice device, long kbs); @Override boolean pullTraceFilesFromEmulator(IDevice device, String remoteFilepath, String localFilename); @Override boolean pullTraceFilesFromDevice(IDevice device, String remoteFilepath, String localFilename); @Override boolean makeAROTraceDirectory(IDevice device, String traceName); @Override boolean makeDirectory(IDevice device, String dirpath); @Override String getProperty(IDevice device, String property); @Override SyncService getSyncService(IDevice device); @Override boolean removeEmulatorData(IDevice device, String deviceTracePath); @Override boolean stopTcpDump(IDevice device); Socket getLocalSocket(); @Override boolean checkTcpDumpRunning(IDevice device); @Override boolean startTcpDump(IDevice device, boolean seLinuxEnforced, String traceFolderName); @Override boolean isTraceRunning(); @Override String[] getShellReturn(IDevice device, String arocmd); @Override boolean checkPackageExist(IDevice device, String fullpackageName); @Override boolean runApkInDevice(IDevice device, String cmd); @Override boolean runVpnApkInDevice(IDevice device); }
@Test public void startTcpDump() throws TimeoutException, IOException, AdbCommandRejectedException, ShellCommandUnresponsiveException { IDevice device = mock(IDevice.class); doNothing().when(device).executeShellCommand(any(String.class), any(IShellOutputReceiver.class)); assertTrue(androidImpl.startTcpDump(device, false, Util.getCurrentRunningDir())); }
AndroidImpl implements IAndroid { @Override public boolean stopTcpDump(IDevice device) { try(Socket emulatorSocket = getLocalSocket(); OutputStream out = emulatorSocket.getOutputStream()) { if (out != null) { out.write("STOP".getBytes("ASCII")); out.flush(); } return true; } catch (UnknownHostException e) { LOGGER.error(e.getMessage()); } catch (IOException e) { LOGGER.error(e.getMessage()); } return false; } boolean setExecutePermission(IDevice device, String remotePath); @Override boolean isEmulator(IDevice device); ShellOutputReceiver getShellOutput(); ShellCommandCheckSDCardOutputReceiver getOutputReturn(); @Override boolean pushFile(IDevice emulator, String local, String remote); @Override DeviceState getState(IDevice device); @Override boolean isSDCardAttached(IDevice device); @Override boolean isSDCardEnoughSpace(IDevice device, long kbs); @Override boolean pullTraceFilesFromEmulator(IDevice device, String remoteFilepath, String localFilename); @Override boolean pullTraceFilesFromDevice(IDevice device, String remoteFilepath, String localFilename); @Override boolean makeAROTraceDirectory(IDevice device, String traceName); @Override boolean makeDirectory(IDevice device, String dirpath); @Override String getProperty(IDevice device, String property); @Override SyncService getSyncService(IDevice device); @Override boolean removeEmulatorData(IDevice device, String deviceTracePath); @Override boolean stopTcpDump(IDevice device); Socket getLocalSocket(); @Override boolean checkTcpDumpRunning(IDevice device); @Override boolean startTcpDump(IDevice device, boolean seLinuxEnforced, String traceFolderName); @Override boolean isTraceRunning(); @Override String[] getShellReturn(IDevice device, String arocmd); @Override boolean checkPackageExist(IDevice device, String fullpackageName); @Override boolean runApkInDevice(IDevice device, String cmd); @Override boolean runVpnApkInDevice(IDevice device); }
@Test public void stopTcpDump() throws Exception { Socket tcpDumpSocket = Mockito.mock(Socket.class); OutputStream out = Mockito.mock(OutputStream.class); Mockito.doReturn(tcpDumpSocket).when(androidImpl).getLocalSocket(); Mockito.doReturn(out).when(tcpDumpSocket).getOutputStream(); Mockito.doNothing().when(tcpDumpSocket).close(); Mockito.doNothing().when(out).close(); IDevice device = mock(IDevice.class); boolean res = androidImpl.stopTcpDump(device); assertTrue(res == true); }
LLDBProcessRunnerImpl implements ILLDBProcessRunner { @Override public boolean executeCmds(String cmd1, String cmd2){ OutputStream out; boolean done = false; try { if(lldbProcess != null){ out = lldbProcess.getOutputStream(); out.write(cmd1.getBytes()); out.write(cmd2.getBytes()); out.flush(); out.close(); }else{ lldbProcess = procfactory.create(cmd1); out = lldbProcess.getOutputStream(); out.write(cmd2.getBytes()); out.flush(); } done = true; } catch (IOException e1) { LOG.error("Executing cmds on attached lldb process has failed"); } return done; } @Autowired void setProcessFactory(IProcessFactory factory); @Override boolean executeCmds(String cmd1, String cmd2); }
@SuppressWarnings("unused") @Test public void executeCmdsTest() throws IOException{ Runtime runtime = Mockito.mock(Runtime.class); process = Mockito.mock(Process.class); OutputStream out = Mockito.mock(ByteArrayOutputStream.class); boolean done = true; String cmd2 = "echo Hello"; String cmd1 = "ls -la"; Mockito.when(runtime.exec(cmd1)).thenReturn(process); Mockito.when(process.getOutputStream()).thenReturn(out); Mockito.doNothing().when(out).write(cmd2.getBytes()); Mockito.doNothing().when(out).flush(); boolean result = lldbProcessRunner.executeCmds(cmd1, cmd2); boolean result2 = lldbProcessRunner.executeCmds(cmd1, cmd2); }
NorootedAndroidCollectorImpl implements IDataCollector, IVideoImageSubscriber { @Override public StatusResult stopCollector() { StatusResult result = new StatusResult(); if (!stopAllServices()) { LOG.error("Cannot stop all services, please check services in device Settings->Apps->Running"); } if (!forceStopProcess()) { LOG.error("Cannot force stop VPN Collector"); } if (isAndroidVersionNougatOrHigher(device) == true) cpuTraceCollector.stopCpuTraceCapture(this.device); if (isVideo()) { LOG.debug("stopping video capture"); this.stopCaptureVideo(); } if(this.attnrScriptRun){ attnr.stopAtenuationScript(this.device); } LOG.debug("pulling trace to local dir"); new LogcatCollector(adbService, device.getSerialNumber()).collectLogcat(localTraceFolder, "Logcat.log"); result = pullTrace(this.mDataDeviceCollectortraceFileNames); if(result.isSuccess()) { try { metaDataHelper.initMetaData(localTraceFolder, traceDesc, traceType, targetedApp, appProducer); } catch (Exception e) { e.printStackTrace(); } } GoogleAnalyticsUtil.getGoogleAnalyticsInstance().sendAnalyticsEvents( GoogleAnalyticsUtil.getAnalyticsEvents().getNonRootedCollector(), GoogleAnalyticsUtil.getAnalyticsEvents().getEndTrace()); running = false; return result; } @Autowired void setMetaDataHelper(IMetaDataHelper metaDataHelper); @Autowired void setAndroid(IAndroid android); @Autowired void setExternalProcessRunner(IExternalProcessRunner runner); @Autowired void setFileManager(IFileManager filemanager); void setDevice(IDevice aDevice); @Autowired void setAdbService(IAdbService adbservice); @Autowired void setVideoCapture(IVideoCapture videocapture); @Autowired void setThreadExecutor(IThreadExecutor thread); @Autowired void setFileExtactor(IReadWriteFileExtractor extractor); @Override String getName(); @Override void addDeviceStatusSubscriber(IDeviceStatus subscriber); @Override void addVideoImageSubscriber(IVideoImageSubscriber subscriber); @Override void receiveImage(BufferedImage videoimage); @Override int getMajorVersion(); @Override String getMinorVersion(); @Override DataCollectorType getType(); @Override boolean isRunning(); void stopRunning(); @Override String[] getLog(); @Override StatusResult startCollector(boolean isCommandLine, String tracepath, VideoOption videoOption_deprecated, String password); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_deprecated, boolean isLiveViewVideo, String deviceId, Hashtable<String, Object> extraParams, String password); void cleanARO(); @Override boolean isTrafficCaptureRunning(int milliSeconds); boolean isVpnActivated(); @Override StatusResult stopCollector(); @Override void timeOutShutdown(); @Override void haltCollectorInDevice(); @Override String getPassword(); @Override boolean setPassword(String requestPassword); @Override String[] getDeviceSerialNumber(StatusResult status); @Override IAroDevice[] getDevices(StatusResult status); @Override boolean isDeviceDataPulled(); }
@Ignore @Test public void stopCollector(){ String[] str1 = {}; Mockito.when(android.getShellReturn(Mockito.any(IDevice.class), Mockito.anyString())).thenReturn(str1); String[] str2 = {"some ip "}; Mockito.when(android.getShellReturn(Mockito.any(IDevice.class), Mockito.anyString())).thenReturn(str2); try { Mockito.doNothing().when(fileManager).saveFile(Mockito.any(InputStream.class), Mockito.anyString()); } catch (IOException IOExp) { IOExp.printStackTrace(); } Mockito.doNothing().when(videoCapture).stopRecording(); Mockito.when(android.removeEmulatorData(Mockito.any(IDevice.class), Mockito.anyString())).thenReturn(true); StatusResult sResult= null; SyncService sycService = null; try { Mockito.when(device.getSyncService()).thenReturn(sycService); } catch (TimeoutException e1) { e1.printStackTrace(); } catch (AdbCommandRejectedException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } sResult = nonRootedAndroidCollector.stopCollector(); assertEquals(411, sResult.getError().getCode()); sycService = Mockito.mock(SyncService.class); try { Mockito.when(device.getSyncService()).thenReturn(sycService); } catch (TimeoutException e1) { e1.printStackTrace(); } catch (AdbCommandRejectedException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } try { Mockito.doNothing().when(sycService).pullFile(Mockito.anyString(), Mockito.anyString(), Mockito.any(ISyncProgressMonitor.class)); } catch (SyncException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } sResult = nonRootedAndroidCollector.stopCollector(); assertTrue(sResult.isSuccess()); Hashtable<String, Object> extranalParams = new Hashtable<String, Object>(); Mockito.when(fileManager.directoryExistAndNotEmpty(Mockito.anyString())).thenReturn(false); Mockito.doNothing().when(fileManager).mkDir(Mockito.anyString()); Mockito.when(fileManager.directoryExist(Mockito.anyString())).thenReturn(true); IDevice aDevice1 = Mockito.mock(IDevice.class); Mockito.when(aDevice1.getSerialNumber()).thenReturn("device1"); IDevice[] devices = {aDevice1}; try { Mockito.when(adbService.getConnectedDevices()).thenReturn(devices); } catch (Exception exp) { exp.printStackTrace(); } Mockito.when(fileManager.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(android.runApkInDevice(Mockito.any(IDevice.class), Mockito.anyString())).thenReturn(true); String[] str3 = {"some ip ", "tun0: ip 10. some"}; Mockito.when(android.getShellReturn(Mockito.any(IDevice.class), Mockito.anyString())).thenReturn(str3); try { Mockito.doNothing().when(videoCapture).init(Mockito.any(IDevice.class), Mockito.anyString()); Mockito.doNothing().when(videoCapture).addSubscriber(Mockito.any(IVideoImageSubscriber.class)); Mockito.doNothing().when(threadExecutor).execute(Mockito.any(IVideoCapture.class)); } catch (IOException e) { e.printStackTrace(); } nonRootedAndroidCollector.stopRunning(); Mockito.when(android.getShellReturn(Mockito.any(IDevice.class), Mockito.anyString())).thenReturn(noVpnCon).thenReturn(vpnActive); sResult = nonRootedAndroidCollector.startCollector(true, "test", VideoOption.LREZ, false, "device1", extranalParams, null); assertTrue(sResult.isSuccess()); Date aDate = new Date(); Mockito.when(videoCapture.getVideoStartTime()).thenReturn(aDate); sResult = nonRootedAndroidCollector.stopCollector(); assertEquals(411, sResult.getError().getCode()); }
ExternalProcessRunnerImpl implements IExternalProcessRunner { @Override public String executeCmd(String cmd) { return executeCmd(cmd, true); } ExternalProcessRunnerImpl(); @Autowired void setProcessFactory(IProcessFactory factory); @Autowired void setThreadExecutor(IThreadExecutor threadExecuter); void setProcessWorker(ProcessWorker worker); @Override String executeCmd(String cmd); @Override String executeCmd(String cmd, boolean redirectErrorStream); @Override String executeCmdRunner(String cmd, boolean earlyExit, String msg); @Override String executeCmdRunner(String cmd, boolean earlyExit, String msg, boolean redirectErrorStream); @Override String runCmd(String[] command); @Override String runCmdWithTimeout(String[] command, long timeout); @Override String runGetString(String command); @Override ByteArrayOutputStream run(String command); }
@Test public void executeCmdTest() throws InterruptedException { String results = externalProcessRunner.executeCmd("echo \"Hello\""); assertTrue(results.contains("Hello")); }
ExternalProcessRunnerImpl implements IExternalProcessRunner { @Override public String runCmd(String[] command) throws IOException { Process process = procfactory.create(command); InputStream input = process.getInputStream(); try (ByteArrayOutputStream out = readInputStream(input)) { if (input != null) { input.close(); } if (process != null) { process.destroy(); } String datastr = null; if (out != null) { datastr = out.toString(); } return datastr; } } ExternalProcessRunnerImpl(); @Autowired void setProcessFactory(IProcessFactory factory); @Autowired void setThreadExecutor(IThreadExecutor threadExecuter); void setProcessWorker(ProcessWorker worker); @Override String executeCmd(String cmd); @Override String executeCmd(String cmd, boolean redirectErrorStream); @Override String executeCmdRunner(String cmd, boolean earlyExit, String msg); @Override String executeCmdRunner(String cmd, boolean earlyExit, String msg, boolean redirectErrorStream); @Override String runCmd(String[] command); @Override String runCmdWithTimeout(String[] command, long timeout); @Override String runGetString(String command); @Override ByteArrayOutputStream run(String command); }
@Test public void runCmdTest() throws IOException { process = Mockito.mock(Process.class); String aMessage = "hello"; InputStream stream = new ByteArrayInputStream(aMessage.getBytes()); Mockito.when(process.getInputStream()).thenReturn(stream); Mockito.doNothing().when(process).destroy(); Mockito.when(factory.create(Mockito.any(String[].class))).thenReturn(process); externalProcessRunner.setProcessFactory(factory); cmds[0] = "test"; String res = externalProcessRunner.runCmd(cmds); assertEquals(aMessage, res); }
ExternalProcessRunnerImpl implements IExternalProcessRunner { @Override public String runCmdWithTimeout(String[] command, long timeout) throws IOException { Process process = procfactory.create(command); if (worker == null) { worker = new ProcessWorker(process, timeout); } threadExecuter.execute(worker); InputStream input = process.getInputStream(); try (ByteArrayOutputStream out = readInputStream(input)) { worker.setExit(); worker = null; if (input != null) { input.close(); } if (process != null) { process.destroy(); } String datastr = null; if (out != null) { datastr = out.toString(); } return datastr; } } ExternalProcessRunnerImpl(); @Autowired void setProcessFactory(IProcessFactory factory); @Autowired void setThreadExecutor(IThreadExecutor threadExecuter); void setProcessWorker(ProcessWorker worker); @Override String executeCmd(String cmd); @Override String executeCmd(String cmd, boolean redirectErrorStream); @Override String executeCmdRunner(String cmd, boolean earlyExit, String msg); @Override String executeCmdRunner(String cmd, boolean earlyExit, String msg, boolean redirectErrorStream); @Override String runCmd(String[] command); @Override String runCmdWithTimeout(String[] command, long timeout); @Override String runGetString(String command); @Override ByteArrayOutputStream run(String command); }
@Test public void runCmdWithTimeout() throws Exception { threadExecuter = Mockito.mock(IThreadExecutor.class); Mockito.doNothing().when(threadExecuter).execute(Mockito.any(Runnable.class)); process = Mockito.mock(Process.class); String aMessage = "hello"; InputStream stream = new ByteArrayInputStream(aMessage.getBytes()); Mockito.when(process.getInputStream()).thenReturn(stream); Mockito.doNothing().when(process).destroy(); Mockito.when(factory.create(Mockito.any(String[].class))).thenReturn(process); Mockito.when(factory.create(Mockito.anyString())).thenReturn(process); worker = Mockito.mock(ProcessWorker.class); Mockito.doNothing().when(worker).setExit(); externalProcessRunner.setProcessFactory(factory); externalProcessRunner.setProcessWorker(worker); externalProcessRunner.setThreadExecutor(threadExecuter); cmds[0] = "test"; long timeout = 1; String res = externalProcessRunner.runCmdWithTimeout(cmds, timeout); assertEquals(aMessage, res); }
ExternalProcessReaderImpl implements Runnable, IExternalProcessReader { @Override public void run() { String line = null; try { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); while (!willStop) { line = bufferedReader.readLine(); if (line == null) { break; } else { line = line.trim(); if (line.length() > 0) { out(line); } } } } catch (IOException exception) { out("Error: " + exception.getMessage()); } notifyExit(); } @Override void setInputStream(InputStream stream); @Override void addSubscriber(IExternalProcessReaderSubscriber subscriber); @Override void setStop(); @Override void out(String message); @Override void removeSubscriber(IExternalProcessReaderSubscriber sub); @Override void run(); }
@Test public void run() throws IOException { String aMessage = "helloFromRun"; InputStream stream = new ByteArrayInputStream(aMessage.getBytes()); externalProcessReader = new ExternalProcessReaderImpl(); externalProcessReader.setInputStream(stream); subscriber = Mockito.mock(IExternalProcessReaderSubscriber.class); externalProcessReader.addSubscriber(subscriber); Mockito.doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { String method = invocation.getMethod().getName(); Object[] args = invocation.getArguments(); if (method.equals("newMessage")) { if (args[0] != null) { ExternalProcessReaderImplTest.message += (String) args[0]; } } return null; } }).when(subscriber).newMessage(Mockito.anyString()); externalProcessReader.run(); externalProcessReader.setStop(); assertTrue(ExternalProcessReaderImplTest.message.equals(aMessage)); }
JSonReportImpl implements IReport { @Override public boolean reportGenerator(String resultFilePath, AROTraceData results) { if (resultFilePath == null || results == null) { return false; } ObjectMapper mapper = new ObjectMapper(); mapper.enableDefaultTyping(); try { mapper.writeValue(filereader.createFile(resultFilePath), results); return true; } catch (JsonGenerationException e) { LOGGER.error(e.getMessage()); } catch (JsonMappingException e) { LOGGER.error(e.getMessage()); } catch (IOException e) { LOGGER.error(e.getMessage()); } return false; } @Override boolean reportGenerator(String resultFilePath, AROTraceData results); }
@Test public void reportGenerator_PathIsNullandTraceisNull() { boolean testResult = jsonreport.reportGenerator(null, null); assertFalse(testResult); } @Test public void reportGenerator_NoError() { AROTraceData results = new AROTraceData(); results.setSuccess(true); try { when(filereader.createFile(any(String.class))).thenReturn(folder.newFile("abc.json")); } catch (IOException e) { e.printStackTrace(); } boolean testResult = jsonreport.reportGenerator("abc.json", results); assertTrue(testResult); } @Test public void reportGenerator_IOException() throws IOException { AROTraceData results = new AROTraceData(); results.setSuccess(true); when(filereader.createFile(any(String.class))).thenThrow(IOException.class); boolean testResult = jsonreport.reportGenerator("abc.json", results); assertFalse(testResult); } @Test public void reportGenerator_JsonException() throws JsonGenerationException { AROTraceData results = new AROTraceData(); results.setSuccess(true); when(filereader.createFile(any(String.class))).thenThrow(JsonGenerationException.class); boolean testResult = jsonreport.reportGenerator("abc.json", results); assertFalse(testResult); } @Test public void reportGenerator_JsonMappingException() throws JsonMappingException { AROTraceData results = new AROTraceData(); results.setSuccess(true); when(filereader.createFile(any(String.class))).thenThrow(JsonMappingException.class); boolean testResult = jsonreport.reportGenerator("abc.json", results); assertFalse(testResult); }
HtmlReportImpl implements IReport { @Override public boolean reportGenerator(String resultFilePath, AROTraceData results) { if (results == null) { return false; } PacketAnalyzerResult analyzerResults = results.getAnalyzerResult(); List<AbstractBestPracticeResult> bpResults = results.getBestPracticeResults(); StringBuffer htmlString = new StringBuffer(200); htmlString.append(getHtmlHead()); htmlString.append(" <body>"); htmlString.append(System.getProperty(lineSeperator())); htmlString.append(" <table class='table'>"); htmlString.append(System.getProperty(lineSeperator())); htmlString.append(getTableHeader(analyzerResults)); htmlString.append(getTraceRows(analyzerResults)); htmlString.append(getBPSummaryRows(bpResults)); htmlString.append("<tr><th></th><td></td></tr><tr><th>Best Practices Results</th><td></td></tr>\n"); htmlString.append(getBpRows(bpResults)); htmlString.append(" </table>"); htmlString.append(System.getProperty(lineSeperator())); htmlString.append(System.getProperty(lineSeperator())); htmlString.append(" </body>"); htmlString.append(System.getProperty(lineSeperator())); htmlString.append("</html>"); try { File file = filereader.createFile(resultFilePath); PrintWriter writer = new PrintWriter(file); writer.println(htmlString.toString()); writer.close(); return true; } catch (IOException e) { LOGGER.info("IOException: "+e); } return false; } @Override boolean reportGenerator(String resultFilePath, AROTraceData results); String removeHtmlCharacter(String text ,String htmlCharacter); }
@Test public void reportGenerator_retunrIsTrue(){ AccessingPeripheralResult access = new AccessingPeripheralResult(); access.setResultType(BPResultType.PASS); CacheControlResult cache = new CacheControlResult(); cache.setResultType(BPResultType.FAIL); List<AbstractBestPracticeResult> bpResults = new ArrayList<AbstractBestPracticeResult>(); bpResults.add(access); bpResults.add(cache); File tempFile = null; try { tempFile = folder.newFile("abc.html"); } catch (IOException e) { e.printStackTrace(); } if(tempFile != null) { tempFile.deleteOnExit(); } when(filereader.createFile(any(String.class))).thenReturn(tempFile); AROTraceData results = new AROTraceData(); PacketAnalyzerResult analyzerResult = new PacketAnalyzerResult(); TraceDirectoryResult tracedirresult = new TraceDirectoryResult(); EnergyModel energyModel = new EnergyModel(); Statistic statistic = new Statistic(); statistic.setTotalByte(123); statistic.setTotalHTTPSByte(123); tracedirresult.setTraceDirectory("temp.txt"); analyzerResult.setTraceresult(tracedirresult); analyzerResult.setEnergyModel(energyModel); analyzerResult.setStatistic(statistic); results.setAnalyzerResult(analyzerResult); results.setBestPracticeResults(bpResults); assertTrue(htmlReportImpl.reportGenerator("abc.html", results)); } @Test public void reportGenerator_retunrIsFalse(){ assertFalse(htmlReportImpl.reportGenerator("abc.html", null)); }
WakelockInfoReaderImpl extends PeripheralBase implements IWakelockInfoReader { @Override public List<WakelockInfo> readData(String directory, String osVersion, double dumpsysEpochTimestamp, Date traceDateTime){ List<WakelockInfo> wakelockInfos = new ArrayList<WakelockInfo>(); String filepath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.BATTERYINFO_FILE; String[] lines = null; if (!filereader.fileExist(filepath)) { return wakelockInfos; } if (osVersion != null && osVersion.compareTo("2.3") < 0) { LOGGER.info("OS 2.2(Froyo) or earlier does not has the wakelock timeline"); } try { lines = filereader.readAllLine(filepath); } catch (IOException e1) { LOGGER.error("failed to read Wakelock Info file: "+filepath); } if(lines != null && lines.length > 0){ WakelockState wakelockState; for (String strLineBuf : lines) { int index = strLineBuf.indexOf(TraceDataConst.WAKELOCK_ACQUIRED); if (index < 0) { index = strLineBuf.indexOf(TraceDataConst.WAKELOCK_RELEASED); } if (index > 0) { String actualWakelockstate = strLineBuf.substring(index, index+10); String strFields[] = strLineBuf.trim().split(" "); try { double bTimeStamp = dumpsysEpochTimestamp - Util.convertTime(strFields[0]); if (bTimeStamp > traceDateTime.getTime()) { bTimeStamp = (bTimeStamp - traceDateTime.getTime())/1000; if (TraceDataConst.WAKELOCK_RELEASED.equals(actualWakelockstate)) { wakelockState = WakelockState.WAKELOCK_RELEASED; } else { wakelockState = WakelockState.WAKELOCK_ACQUIRED; } wakelockInfos.add(new WakelockInfo(bTimeStamp, wakelockState)); LOGGER.info("Trace Start: " + traceDateTime.getTime() + "\nWakelock Time: " + bTimeStamp + " Wakelock state: " + actualWakelockstate + " strFields " + Arrays.toString(strFields)); } } catch (Exception e) { LOGGER.warn("Unexpected error parsing wakelock event: " + Arrays.toString(strFields) + " found wakelock in " + index, e); } } } } return wakelockInfos; } @Override List<WakelockInfo> readData(String directory, String osVersion, double dumpsysEpochTimestamp, Date traceDateTime); }
@Test public void readData() throws IOException { Date traceDateTime = new Date((long)1412161675045.0); double dumpsysEpochTimestamp = (new Date((long)1.412361724E12)).getTime(); List<WakelockInfo> wakelockInfos = null; String filepath = "" + Util.FILE_SEPARATOR + TraceDataConst.FileName.BATTERYINFO_FILE; Mockito.when(filereader.fileExist(filepath)).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(getMockedFileData()); traceDataReader.setFileReader(filereader); wakelockInfos = traceDataReader.readData("", "2.2", dumpsysEpochTimestamp, traceDateTime); wakelockInfos = traceDataReader.readData("", "4.2", dumpsysEpochTimestamp, traceDateTime); assertEquals(7, wakelockInfos.size(),0); } @Test public void readData_Exception_readAllLine() throws IOException { Date traceDateTime = new Date((long)1412161675045.0); double dumpsysEpochTimestamp = (new Date((long)1.412361724E12)).getTime(); Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenThrow(new IOException("Exception_readAllLine")); List<WakelockInfo> wakelockInfos = traceDataReader.readData("", "2.2", dumpsysEpochTimestamp, traceDateTime); assertTrue(wakelockInfos.size() == 0); }
VideoTimeReaderImpl extends PeripheralBase implements IVideoTimeReader { @Override public VideoTime readData(String directory, Date traceDateTime) { boolean exVideoFound = false; boolean exVideoTimeFileNotFound = false; double videoStartTime = 0.0; boolean nativeVideo = false; String exVideoDisplayFileName = "exvideo.mov"; String filePath = directory + Util.FILE_SEPARATOR + exVideoDisplayFileName; String nativeVideoDisplayfile = "video.mov"; if (filereader.fileExist(filePath) || isExternalVideoSourceFilePresent(nativeVideoFileOnDevice, nativeVideoDisplayfile, false, directory)) { exVideoFound = true; exVideoTimeFileNotFound = false; filePath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.EXVIDEO_TIME_FILE; if (!filereader.fileExist(filePath)) { exVideoTimeFileNotFound = true; exVideoFound = false; } else { videoStartTime += readVideoStartTime(filePath, traceDateTime); } } else { exVideoFound = false; exVideoTimeFileNotFound = false; nativeVideo = true; filePath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.VIDEO_TIME_FILE; videoStartTime = updateVideoStartTimeForMP4(directory, filePath, traceDateTime); } VideoTime vtime = new VideoTime(); vtime.setExVideoFound(exVideoFound); vtime.setExVideoTimeFileNotFound(exVideoTimeFileNotFound); vtime.setNativeVideo(nativeVideo); vtime.setVideoStartTime(videoStartTime); return vtime; } @Override VideoTime readData(String directory, Date traceDateTime); double updateVideoStartTimeForMP4(String directory, String filepath, Date traceDateTime); double getFfmpegVideoStartTime(String videoPath); void updateVideoTimeFile(double newVideoStartTime, String filePath); }
@Test public void readData0() throws IOException { Date traceDateTime = new Date((long) 1414092264446.0); VideoTime videoTime = null; nativeVideoDisplayfile = makeFile("exvideo.mov", null); videoTime = videoTimeReaderImpl.readData(tracePath, traceDateTime); assertEquals(true, videoTime.isExVideoTimeFileNotFound()); nativeVideoDisplayfile.delete(); nativeVideoDisplayfile = null; } @Test public void readData1() throws IOException { Date traceDateTime = new Date((long) 1414092264446.0); VideoTime videoTime = null; VIDEO_TIME_FILE = makeFile("video_time", new String[] { "1.41409226371E9 1.414092261198E9" }); videoTime = videoTimeReaderImpl.readData(tracePath, traceDateTime); assertEquals(1.4140922669580002E9, videoTime.getVideoStartTime(), 0); assertEquals(true, videoTime.isNativeVideo()); assertEquals(false, videoTime.isExVideoFound()); assertEquals(false, videoTime.isExVideoTimeFileNotFound()); VIDEO_TIME_FILE.delete(); VIDEO_TIME_FILE = null; } @Test public void readData2() throws IOException { Date traceDateTime = new Date((long) 1414092264446.0); VideoTime videoTime = null; nativeVideoDisplayfile = makeFile("video.mov", null); VIDEO_TIME_FILE = makeFile("video_time", new String[] { "1.41409226371E9 1.414092261198E9" }); videoTime = videoTimeReaderImpl.readData(tracePath, traceDateTime); assertEquals(1.4140922669580002E9, videoTime.getVideoStartTime(), 0); assertEquals(true, videoTime.isNativeVideo()); assertEquals(false, videoTime.isExVideoFound()); assertEquals(false, videoTime.isExVideoTimeFileNotFound()); nativeVideoDisplayfile.delete(); nativeVideoDisplayfile = null; VIDEO_TIME_FILE.delete(); VIDEO_TIME_FILE = null; } @Test public void readData5(){ Date traceDateTime = new Date((long) 1414092264446.0); VideoTime videoTime = null; nativeVideoFileOnDevice = makeFile("video.mp4", null); VIDEO_TIME_FILE = makeFile("video_time", new String[] { "1.41409226371E9 1.414092261198E9" }); String result = " Duration: 00:05:53.95, \n creation_time : 2019-01-21 22:24:10" ; String cmd = Util.getFFMPEG() + " -i " + "\"" + nativeVideoFileOnDevice.getAbsolutePath() +"\""; Mockito.when(extRunner.executeCmd(cmd)).thenReturn(result); videoTime = videoTimeReaderImpl.readData(tracePath, traceDateTime); assertEquals(1.54810909605E9, videoTime.getVideoStartTime(), 0); nativeVideoFileOnDevice.delete(); nativeVideoFileOnDevice = null; VIDEO_TIME_FILE.delete(); VIDEO_TIME_FILE = null; }
VideoTimeReaderImpl extends PeripheralBase implements IVideoTimeReader { boolean isExternalVideoSourceFilePresent(String nativeVideoFileOnDevice, String nativeVideoDisplayfile,boolean isPcap, String traceDirectory){ int index =0; String[] matches; if(isPcap){ matches = filereader.list(traceDirectory, new FilenameFilter() { public boolean accept(File dir, String name) { return isVideoFile(name); } }); }else{ matches = filereader.list(traceDirectory, new FilenameFilter() { public boolean accept(File dir, String name) { return isVideoFile(name); } }); } if(matches!= null){ List<String> matchesList = new ArrayList<>(); for (int str = 0; str < matches.length; str++) { if (!matches[str].startsWith("._")) { matchesList.add(matches[str]); } } matches = matchesList.toArray(new String[matchesList.size()]); while(index < matches.length){ if(matches.length == 1){ return (!(nativeVideoFileOnDevice.equals(matches[index]) || nativeVideoDisplayfile.equals(matches[index]))); }else { if((matches.length == 2) && ((index + 1)!=2) && (nativeVideoFileOnDevice.equals(matches[index]) || nativeVideoDisplayfile.equals(matches[index])) && (nativeVideoFileOnDevice.equals(matches[index+1]) || nativeVideoDisplayfile.equals(matches[index+1])) ){ return false; } else{ if(nativeVideoFileOnDevice.equals(matches[index]) || nativeVideoDisplayfile.equals(matches[index])){ return true; } } } index+=1; } } return false; } @Override VideoTime readData(String directory, Date traceDateTime); double updateVideoStartTimeForMP4(String directory, String filepath, Date traceDateTime); double getFfmpegVideoStartTime(String videoPath); void updateVideoTimeFile(double newVideoStartTime, String filePath); }
@Test public void readData4() throws IOException { makeFile("video.dv", null); makeFile("video.qt", null); makeFile("video.mev", null); makeFile("video.m4", null); makeFile("video_time", new String[] { "1.41409226371E9 1.414092261198E9" }); boolean r = videoTimeReaderImpl.isExternalVideoSourceFilePresent("video.mp4", "video.mov", true, tracePath); assertTrue("should not have found \"video.mov\" or \"video.mp4\"", !r); makeFile("video.mov", null); r = videoTimeReaderImpl.isExternalVideoSourceFilePresent("video.mp4", "video.mov", true, tracePath); assertTrue("should have found \"video.mov\"", r); }
RadioInfoReaderImpl extends PeripheralBase implements IRadioInfoReader { @Override public List<RadioInfo> readData(String directory, double startTime) { List<RadioInfo> radioInfos = new ArrayList<RadioInfo>(); String filepath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.RADIO_EVENTS_FILE; String[] lines = null; if (!filereader.fileExist(filepath)) { return radioInfos; } try { lines = filereader.readAllLine(filepath); } catch (IOException e1) { LOGGER.error("failed to read Radio info file: "+filepath); } Double lastDbmValue = null; if(lines != null && lines.length > 0){ for (String strLineBuf : lines) { String[] strFields = strLineBuf.split(" "); try { if (strFields.length == 2) { double timestampVal = Util.normalizeTime(Double.parseDouble(strFields[0]),startTime); double dbmValue = Double.parseDouble(strFields[1]); if (lastDbmValue != null && timestampVal > 0.0 && (dbmValue >= 0.0 || lastDbmValue.doubleValue() >= 0.0) && dbmValue != lastDbmValue.doubleValue()) { radioInfos.add(new RadioInfo(timestampVal, lastDbmValue.doubleValue())); } radioInfos.add(new RadioInfo(timestampVal, dbmValue)); lastDbmValue = dbmValue; } else if (strFields.length == 6) { double timestampVal = Util.normalizeTime(Double.parseDouble(strFields[0]),startTime); RadioInfo radioInformation = new RadioInfo(timestampVal, Integer.parseInt(strFields[1]), Integer.parseInt(strFields[2]), Integer.parseInt(strFields[3]), Integer.parseInt(strFields[4]), Integer.parseInt(strFields[5])); if (lastDbmValue != null && timestampVal > 0.0 && (radioInformation.getSignalStrength() >= 0.0 || lastDbmValue.doubleValue() >= 0.0) && radioInformation.getSignalStrength() != lastDbmValue.doubleValue()) { radioInfos.add(new RadioInfo(timestampVal, lastDbmValue.doubleValue())); } radioInfos.add(radioInformation); lastDbmValue = radioInformation.getSignalStrength(); } else { LOGGER.warn("Invalid radio_events entry: " + strLineBuf); } } catch (Exception e) { LOGGER.warn("Unexpected error parsing radio event: " + strLineBuf, e); } } } return radioInfos; } @Override List<RadioInfo> readData(String directory, double startTime); }
@Test public void readData() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); String[] arr = new String[] { "1.41383675837E9 -42", "1.413836771449E9 -51", "1.413836784233E9 -53", "1.41383678679E9 -50", "1.413836807271E9 -51", "1.413836809831E9 -51", "1.413836822639E9 -51", "1.413836825194E9 -51", "1.413836837992E9 -51", "1.413836840548E9 -51", "1.413836845669E9 -41", "1.41383685336E9 -51", "1.41383685592E9 -51", "1.413836861023E9 -51", "1.413836868708E9 -51", "1.413836871277E9 -36", }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); radioInfoReader.setFileReader(filereader); List<RadioInfo> listRadioInfo = radioInfoReader.readData("/", 0); assertEquals(16, listRadioInfo.size(), 0); assertEquals(-42, listRadioInfo.get(0).getSignalStrength(), 0); assertEquals(-51, listRadioInfo.get(1).getSignalStrength(), 0); assertEquals(-41, listRadioInfo.get(10).getSignalStrength(), 0); assertEquals(-36, listRadioInfo.get(15).getSignalStrength(), 0); assertEquals(1.41383675837E9, listRadioInfo.get(0).getTimeStamp(), 0); assertEquals(1.41383685336E9, listRadioInfo.get(11).getTimeStamp(), 0); assertEquals(1.413836871277E9, listRadioInfo.get(15).getTimeStamp(), 0); Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); arr = new String[] { "1.412720866732E9 25 -86 -6 300 2147483647" ,"1.412720867835E9 25 -87 -7 300 2147483647" ,"1.412720870315E9 23 -92 -7 300 2147483647" ,"1.412720873837E9 21 -94 -7 300 2147483647" ,"1.412720876836E9 21 -95 -7 300 2147483647" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); radioInfoReader.setFileReader(filereader); listRadioInfo = radioInfoReader.readData("/", 0); assertEquals(5, listRadioInfo.size(), 0); Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); arr = new String[] { "1.394754474555E9 -51" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); radioInfoReader.setFileReader(filereader); listRadioInfo = radioInfoReader.readData("/", 0); assertEquals(1, listRadioInfo.size(), 0); Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); arr = new String[] { "1.394754474555E9 0" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); radioInfoReader.setFileReader(filereader); listRadioInfo = radioInfoReader.readData("/", 0); assertEquals(1, listRadioInfo.size(), 0); Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); arr = new String[] { "" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); radioInfoReader.setFileReader(filereader); listRadioInfo = radioInfoReader.readData("/", 0); assertEquals(0, listRadioInfo.size(), 0); Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); arr = new String[] { "1.414601817968E9 0" ,"1.414601897874E9 -99" ,"1.414601903563E9 -99" ,"1.414601916514E9 -105" ,"1.414601920485E9 -105" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); radioInfoReader.setFileReader(filereader); listRadioInfo = radioInfoReader.readData("/", 0); assertEquals(6, listRadioInfo.size(), 0); }
UserEventSorting implements Comparator<UserEvent> { @Override public int compare(UserEvent uEvent1, UserEvent uEvent2) { return Double.valueOf(uEvent1.getPressTime()).compareTo(uEvent2.getPressTime()); } @Override int compare(UserEvent uEvent1, UserEvent uEvent2); }
@Test public void compare() throws IOException { List<UserEvent> userEvents = new ArrayList<UserEvent>(); userEvents.add(new UserEvent(UserEventType.SCREEN_PORTRAIT, 1.1, 1.6)); userEvents.add(new UserEvent(UserEventType.SCREEN_LANDSCAPE, 1.2, 1.7)); userEvents.add(new UserEvent(UserEventType.SCREEN_LANDSCAPE, 1.0, 1.5)); userEvents.add(new UserEvent(UserEventType.KEY_POWER, 0.0, 1.5)); userEvents.add(new UserEvent(UserEventType.KEY_RED, 1.411421287928E2, 1.5)); userEvents.add(new UserEvent(UserEventType.KEY_RED, 1.411421287928E9, 1.5)); userEvents.add(new UserEvent(UserEventType.SCREEN_TOUCH, 1.41142128792812E12, 1.5)); Collections.sort(userEvents, new UserEventSorting()); assertEquals(1.0, userEvents.get(1).getPressTime(), 0); assertEquals(1.1, userEvents.get(2).getPressTime(), 0); assertEquals(1.2, userEvents.get(3).getPressTime(), 0); }
ScreenStateInfoReaderImpl extends PeripheralBase implements IScreenStateInfoReader { @Override public List<ScreenStateInfo> readData(String directory, double startTime, double traceDuration) { List<ScreenStateInfo> screenStateInfos = new ArrayList<ScreenStateInfo>(); String filepath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.SCREEN_STATE_FILE; if (!filereader.fileExist(filepath)) { return screenStateInfos; } double beginTime = 0.0; double endTime = 0.0; ScreenState prevScreenState = null; ScreenState screenState; String prevBrigtness = null; String brightness = null; int prevTimeOut = 0; int timeout = 0; String firstLine; String strLineBuf; String[] lines = null; try { lines = filereader.readAllLine(filepath); } catch (IOException e1) { LOGGER.error("failed to open Screen State info file: "+filepath); } if (lines != null && lines.length > 0) { firstLine = lines[0]; String strFieldsFirstLine[] = firstLine.split(" "); if (strFieldsFirstLine.length >= 2) { try { beginTime = Util.normalizeTime(Double.parseDouble(strFieldsFirstLine[0]),startTime); if (TraceDataConst.SCREEN_ON.equals(strFieldsFirstLine[1])) { prevScreenState = ScreenState.SCREEN_ON; if (strFieldsFirstLine.length >= 4) { prevTimeOut = Integer.parseInt(strFieldsFirstLine[2]); prevBrigtness = strFieldsFirstLine[3]; } } else if (TraceDataConst.SCREEN_OFF.equals(strFieldsFirstLine[1])) { prevScreenState = ScreenState.SCREEN_OFF; } else { LOGGER.warn("Unknown screen state: " + firstLine); prevScreenState = ScreenState.SCREEN_UNKNOWN; } } catch (Exception e) { LOGGER.warn("Unexpected error in screen events: " + firstLine, e); } } else { LOGGER.warn("Unrecognized screen state event: " + firstLine); } for (int i=1;i<lines.length;i++) { strLineBuf = lines[i]; String strFields[] = strLineBuf.split(" "); if (strFields.length >= 2) { try { endTime = Util.normalizeTime(Double.parseDouble(strFields[0]),startTime); brightness = null; timeout = 0; if (TraceDataConst.SCREEN_ON.equals(strFields[1])) { screenState = ScreenState.SCREEN_ON; if (strFields.length >= 4) { timeout = Integer.parseInt(strFields[2]); brightness = strFields[3]; } } else if (TraceDataConst.SCREEN_OFF.equals(strFields[1])) { screenState = ScreenState.SCREEN_OFF; } else { LOGGER.warn("Unknown screen state: " + strLineBuf); screenState = ScreenState.SCREEN_UNKNOWN; } ScreenStateInfo screenInfo = new ScreenStateInfo(beginTime, endTime, prevScreenState, prevBrigtness, prevTimeOut); screenStateInfos.add(screenInfo); prevScreenState = screenState; prevBrigtness = brightness; prevTimeOut = timeout; beginTime = endTime; } catch (Exception e) { LOGGER.warn("Unexpected error in screen events: "+ strLineBuf, e); } } else { LOGGER.warn("Unrecognized screen state event: " + strLineBuf); } } screenStateInfos.add(new ScreenStateInfo(beginTime, traceDuration, prevScreenState, prevBrigtness, prevTimeOut)); } return screenStateInfos; } @Override List<ScreenStateInfo> readData(String directory, double startTime, double traceDuration); }
@Test public void readData() throws IOException { String[] arr; List<ScreenStateInfo> listScreenStateInfo; Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); arr = new String[] { "1.414092110985E9 ON 15 30.0", "1.414092182923E9 OFF", "1.414092195631E9 ON 15 32.0", "1.414092264469E9 ON 15 33.0", "1.414092292153E9 OFF", "1.414092303535E9 ON 15 35.0" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); traceDataReader.setFileReader(filereader); listScreenStateInfo = traceDataReader.readData("/", 0, 0); assertEquals(6, listScreenStateInfo.size(), 0); assertEquals(1.414092110985E9, listScreenStateInfo.get(0).getBeginTimeStamp(), 0); assertEquals("SCREEN_ON", listScreenStateInfo.get(0).getScreenState().toString()); assertEquals(15, listScreenStateInfo.get(0).getScreenTimeout(), 0); assertEquals("30.0", listScreenStateInfo.get(0).getScreenBrightness()); assertEquals(1.414092182923E9, listScreenStateInfo.get(1).getBeginTimeStamp(), 0); assertEquals("SCREEN_OFF", listScreenStateInfo.get(1).getScreenState().toString()); assertEquals(1.414092303535E9, listScreenStateInfo.get(5).getBeginTimeStamp(), 0); assertEquals("SCREEN_ON", listScreenStateInfo.get(5).getScreenState().toString()); assertEquals(15, listScreenStateInfo.get(5).getScreenTimeout(), 0); assertEquals("35.0", listScreenStateInfo.get(5).getScreenBrightness()); Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); arr = new String[] { "1.414092110985E9 OFF", "1.414092182923E9 ON 15 30.0", "1.414092195631E9 ON 15 32.0" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); traceDataReader.setFileReader(filereader); listScreenStateInfo = traceDataReader.readData("/", 0, 0); Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); arr = new String[] { "1.414092110986E9 UNKNOWN", "1.414092182923E9 ON 15 30.0", "1.414092195631E9 ON 15 32.0" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); traceDataReader.setFileReader(filereader); listScreenStateInfo = traceDataReader.readData("/", 0, 0); assertEquals(3, listScreenStateInfo.size(), 0); Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); arr = new String[] { "1.414092110985E9 OFF", "1.414092182923E9 ON 15 30.0", "1.414092264469E9 UNKNOWN", "1.414092292153E9", "1.414092264469E9 blah" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); traceDataReader.setFileReader(filereader); listScreenStateInfo = traceDataReader.readData("/", 0, 0); Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); arr = new String[] { "", "1.414092182923E9 ON 15 30.0", "1.414092264469E9 UNKNOWN", "1.414092292153E9 OFF", "1.414092264469E9 blah" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); traceDataReader.setFileReader(filereader); listScreenStateInfo = traceDataReader.readData("/", 0, 0); Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(false); arr = new String[] { "1.414092110985E9 OFF", "1.414092264469E9 blah" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); traceDataReader.setFileReader(filereader); listScreenStateInfo = traceDataReader.readData("/", 0, 0); assertEquals(0, listScreenStateInfo.size(), 0); }
AlarmDumpsysTimestampReaderImpl extends PeripheralBase implements IAlarmDumpsysTimestampReader { @Override public AlarmDumpsysTimestamp readData(String directory , Date traceDateTime , double traceDuration , String osVersion , double eventTime0) { String filepath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.ALARM_END_FILE; boolean useStartFile = false; double dumpsysEpochTimestamp = 0.0; double dumpsysElapsedTimestamp = 0.0; if (!filereader.fileExist(filepath)) { useStartFile = true; filepath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.ALARM_START_FILE; if (!filereader.fileExist(filepath)) { if (traceDateTime == null) { LOGGER.debug("traceDateTime is null"); } else { LOGGER.debug("traceDuration: " + traceDuration); dumpsysEpochTimestamp = traceDateTime.getTime() + traceDuration * 1000; dumpsysElapsedTimestamp = eventTime0 + traceDuration * 1000; } return null; } } dumpsysEpochTimestamp = 0; String[] lines = null; try { lines = filereader.readAllLine(filepath); } catch (IOException e1) { LOGGER.error("failed to open alarm dumpsys timestamp file: " + filepath); return null; } for (String strLineBuf : lines) { if (dumpsysEpochTimestamp <= 0 && strLineBuf.indexOf("Realtime wakeup") > 0) { String realTime[] = strLineBuf.split("="); if (osVersion != null && osVersion.compareTo("2.3") < 0) { dumpsysEpochTimestamp = Double.parseDouble(realTime[1].trim().substring(0, realTime[1].length() - 2)); } else { DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { dumpsysEpochTimestamp = format.parse(realTime[1].trim().substring(0, realTime[1].length() - 2)).getTime(); } catch (ParseException e) { LOGGER.warn("ParseException ", e); } } } if (strLineBuf.indexOf("Elapsed realtime wakeup") > 0) { String strFields[] = strLineBuf.split("="); if (osVersion != null && osVersion.compareTo("2.3") < 0) { dumpsysElapsedTimestamp = Double.parseDouble(strFields[1].trim().substring(0, strFields[1].length() - 2)); } else { dumpsysElapsedTimestamp = Util.convertTime(strFields[1].trim().substring(1, strFields[1].length() - 2)); } break; } } if (useStartFile) { dumpsysEpochTimestamp += traceDuration * 1000; dumpsysElapsedTimestamp += traceDuration * 1000; } if (osVersion != null) { LOGGER.info("Elapsed realtime : " + dumpsysElapsedTimestamp + "\n\tEPOCH: " + dumpsysEpochTimestamp + "\n\tOS: " + osVersion); } AlarmDumpsysTimestamp time = new AlarmDumpsysTimestamp(); time.setDumpsysElapsedTimestamp(dumpsysElapsedTimestamp); time.setDumpsysEpochTimestamp(dumpsysEpochTimestamp); return time; } @Override AlarmDumpsysTimestamp readData(String directory , Date traceDateTime , double traceDuration , String osVersion , double eventTime0); }
@Test public void readData_alarm_info_end() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); String[] array_alarm_info_end = getMockedFileData2(); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(array_alarm_info_end); AlarmDumpsysTimestamp alarmDumpsysTimestamp = traceDataReader.readData(traceFolder, new Date((long) (1.412361675045E9 * 1000)), 0, "4.0.4", 65524.92); assertEquals(1.412361724E12, alarmDumpsysTimestamp.getDumpsysEpochTimestamp(), 0); assertEquals(6.5574186E7, alarmDumpsysTimestamp.getDumpsysElapsedTimestamp(), 0); } @Test public void readData_alarm_info_end2() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); String[] array_alarm_info_end = getMockedFileData21(); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(array_alarm_info_end); AlarmDumpsysTimestamp alarmDumpsysTimestamp = traceDataReader.readData(traceFolder, new Date((long) 1.269821752138E9 * 1000), 0, "2.1", 65524.92); double x = alarmDumpsysTimestamp.getDumpsysEpochTimestamp(); alarmDumpsysTimestamp.getDumpsysElapsedTimestamp(); assertEquals(1.269821813284E12, x, 0); assertEquals(1.0930327E7, alarmDumpsysTimestamp.getDumpsysElapsedTimestamp(), 0); } @Test public void readData_alarm_info_start() throws IOException { Mockito.when(filereader.fileExist(traceFolder + Util.FILE_SEPARATOR + "alarm_info_end")).thenReturn(false); Mockito.when(filereader.fileExist(traceFolder + Util.FILE_SEPARATOR + "alarm_info_start")).thenReturn(true); String[] array_alarm_info_start = getMockedFileData(); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(array_alarm_info_start); AlarmDumpsysTimestamp alarmDumpsysTimestamp = traceDataReader.readData(traceFolder, new Date((long) (1.412361675045E9 * 1000)), 0, "4.0.4", 65524.92); assertEquals(1.412361727E12, alarmDumpsysTimestamp.getDumpsysEpochTimestamp(), 0); assertEquals(6.5577447E7, alarmDumpsysTimestamp.getDumpsysElapsedTimestamp(), 0); } @Test public void fileNotFound() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(false); String[] array_alarm_info_start = getMockedFileData(); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(array_alarm_info_start); AlarmDumpsysTimestamp alarmDumpsysTimestamp = null; alarmDumpsysTimestamp = traceDataReader.readData(traceFolder, new Date((long) (1.412361675045E9 * 1000)), 0, "4.0.4", 65524.92); assertEquals(alarmDumpsysTimestamp,null); } @Test public void readData_Exception_readAllLine() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenThrow(new IOException("Exception_readAllLine")); AlarmDumpsysTimestamp alarmDumpsysTimestamp = null; alarmDumpsysTimestamp = traceDataReader.readData(traceFolder, new Date((long) (1.412361675045E9 * 1000)), 0, "4.0.4", 65524.92); assertTrue(alarmDumpsysTimestamp == null); }
BluetoothInfoReaderImpl extends PeripheralBase implements IBluetoothInfoReader { @Override public List<BluetoothInfo> readData(String directory, double startTime, double traceDuration) { List<BluetoothInfo> bluetoothInfos = new ArrayList<BluetoothInfo>(); this.activeBluetoothDuration = 0; String filepath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.BLUETOOTH_FILE; if (!filereader.fileExist(filepath)) { return bluetoothInfos; } double beginTime = 0.0; double endTime; double dLastTimeStamp = 0.0; double dActiveDuration = 0.0; BluetoothState prevBtState = null; BluetoothState btState = null; BluetoothState lastState = null; String firstLine; String strLineBuf; String[] lines = null; try { lines = filereader.readAllLine(filepath); } catch (IOException e1) { LOGGER.error("failed reading Bluetooth info file: " + filepath); } if (lines != null && lines.length > 0) { firstLine = lines[0]; String strFieldsFirstLine[] = firstLine.split(" "); if (strFieldsFirstLine.length == 2) { try { beginTime = Util.normalizeTime(Double.parseDouble(strFieldsFirstLine[0]), startTime); if (TraceDataConst.BLUETOOTH_CONNECTED.equals(strFieldsFirstLine[1])) { prevBtState = BluetoothState.BLUETOOTH_CONNECTED; } else if (TraceDataConst.BLUETOOTH_DISCONNECTED.equals(strFieldsFirstLine[1])) { prevBtState = BluetoothState.BLUETOOTH_DISCONNECTED; } else if (TraceDataConst.BLUETOOTH_OFF.equals(strFieldsFirstLine[1])) { prevBtState = BluetoothState.BLUETOOTH_TURNED_OFF; } else if (TraceDataConst.BLUETOOTH_ON.equals(strFieldsFirstLine[1])) { prevBtState = BluetoothState.BLUETOOTH_TURNED_ON; } else { LOGGER.warn("Unknown bluetooth state: " + firstLine); prevBtState = BluetoothState.BLUETOOTH_UNKNOWN; } lastState = prevBtState; dLastTimeStamp = beginTime; } catch (Exception e) { LOGGER.warn("Unexpected error parsing bluetooth event: " + firstLine, e); } } else { LOGGER.warn("Invalid Bluetooth trace entry: " + firstLine); } for (int i = 1; i < lines.length; i++) { strLineBuf = lines[i]; String strFields[] = strLineBuf.split(" "); if (strFields.length == 2) { try { endTime = Util.normalizeTime(Double.parseDouble(strFields[0]), startTime); if (TraceDataConst.BLUETOOTH_CONNECTED.equals(strFields[1])) { btState = BluetoothState.BLUETOOTH_CONNECTED; } else if (TraceDataConst.BLUETOOTH_DISCONNECTED.equals(strFields[1])) { btState = BluetoothState.BLUETOOTH_DISCONNECTED; } else if (TraceDataConst.BLUETOOTH_OFF.equals(strFields[1])) { btState = BluetoothState.BLUETOOTH_TURNED_OFF; } else if (TraceDataConst.BLUETOOTH_ON.equals(strFields[1])) { btState = BluetoothState.BLUETOOTH_TURNED_ON; } else { LOGGER.warn("Unknown bluetooth state: " + strLineBuf); btState = BluetoothState.BLUETOOTH_UNKNOWN; } bluetoothInfos.add(new BluetoothInfo(beginTime, endTime, prevBtState)); if (lastState == BluetoothState.BLUETOOTH_CONNECTED) { dActiveDuration += (endTime - dLastTimeStamp); } lastState = btState; dLastTimeStamp = endTime; prevBtState = btState; beginTime = endTime; } catch (Exception e) { LOGGER.warn("Unexpected error parsing bluetooth event: " + strLineBuf, e); } } else { LOGGER.warn("Invalid Bluetooth trace entry: " + strLineBuf); } } bluetoothInfos.add(new BluetoothInfo(beginTime, traceDuration, prevBtState)); if (lastState == BluetoothState.BLUETOOTH_CONNECTED) { dActiveDuration += Math.max(0, traceDuration - dLastTimeStamp); } this.activeBluetoothDuration = dActiveDuration; } return bluetoothInfos; } @Override List<BluetoothInfo> readData(String directory, double startTime, double traceDuration); @Override double getBluetoothActiveDuration(); }
@Test public void ioException() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenThrow(new IOException("failed on purpose")); bluetoothReader.setFileReader(filereader); List<BluetoothInfo> bluetoothInfo = bluetoothReader.readData("/", 0, 0); assertTrue(bluetoothInfo.size() == 0); } @Test public void nullEntrys() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(null); bluetoothReader.setFileReader(filereader); List<BluetoothInfo> bluetoothInfo = bluetoothReader.readData("/", 0, 0); assertTrue(bluetoothInfo.size() == 0); } @Test public void noLines() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] {}); bluetoothReader.setFileReader(filereader); List<BluetoothInfo> bluetoothInfo = bluetoothReader.readData("/", 0, 0); assertTrue(bluetoothInfo.size() == 0); } @Test public void invalidBluetoothEntry1() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1.413913535177E9 this is InVaLiD" ,"1.413913591806E9 CONNECTED" ,"1.413913610613E9 OFF" ,"1.413913620683E9 DISCONNECTED" ,"1.413913620883E9 CONNECTED" ,"1.413913622533E9 CONNECTED" ,"" }); bluetoothReader.setFileReader(filereader); List<BluetoothInfo> bluetoothInfo = bluetoothReader.readData("/", 0, 0); assertTrue(bluetoothInfo.size() > 0); } @Test public void invalidBluetoothEntry2() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1.413913535177E9 CONNECTED" ,"1.413913591806E9 this is InVaLiD" ,"1.413913610613E9 OFF" ,"1.413913620683E9 DISCONNECTED" ,"1.413913620883E9 CONNECTED" ,"1.413913622533E9 CONNECTED" ,"" }); bluetoothReader.setFileReader(filereader); List<BluetoothInfo> bluetoothInfo = bluetoothReader.readData("/", 0, 0); assertTrue(bluetoothInfo.size() > 0); } @Test public void invalidTimeStamp1() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1.413913535177z9 CONNECTED" ,"1.413913591806E9 CONNECTED" ,"1.413913610613E9 OFF" ,"1.413913620683E9 DISCONNECTED" ,"1.413913620883E9 CONNECTED" ,"1.413913622533E9 CONNECTED" ,"" }); bluetoothReader.setFileReader(filereader); List<BluetoothInfo> bluetoothInfo = bluetoothReader.readData("/", 0, 0); assertTrue(bluetoothInfo.size() == 6); } @Test public void invalidTimeStamp2() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1.413913535177E9 CONNECTED" ,"1.413913591806z9 CONNECTED" ,"1.413913610613E9 OFF" ,"1.413913620683E9 DISCONNECTED" ,"1.413913620883E9 CONNECTED" ,"1.413913622533E9 CONNECTED" ,"" }); bluetoothReader.setFileReader(filereader); List<BluetoothInfo> bluetoothInfo = bluetoothReader.readData("/", 0, 0); assertTrue(bluetoothInfo.size() == 5); } @Test public void readData1() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); String[] arr = new String[] { "1.413913535177E9 CONNECTED" ,"1.413913591806E9 CONNECTED" ,"1.413913610613E9 OFF" ,"1.413913620683E9 DISCONNECTED" ,"1.413913620883E9 CONNECTED" ,"1.413913622533E9 JUNK" ,"" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); List<BluetoothInfo> bluetoothInfo = bluetoothReader.readData("/", 0, 0); assertTrue(bluetoothInfo.size() > 0); assertEquals(1.413913622533E9, bluetoothInfo.get(5).getBeginTimeStamp(), 0); assertEquals(1.413913622533E9, bluetoothInfo.get(4).getEndTimeStamp(), 0); assertEquals(0, bluetoothInfo.get(5).getEndTimeStamp(), 0); assertEquals("BLUETOOTH_UNKNOWN", bluetoothInfo.get(5).getBluetoothState().toString()); assertEquals("BLUETOOTH_DISCONNECTED", bluetoothInfo.get(3).getBluetoothState().toString()); assertEquals("BLUETOOTH_CONNECTED", bluetoothInfo.get(1).getBluetoothState().toString()); assertEquals("BLUETOOTH_TURNED_OFF", bluetoothInfo.get(2).getBluetoothState().toString()); } @Test public void readData2() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1.413913535177E9 CONNECTED" ,"1.413913591806E9 CONNECTED" ,"1.413913610613E9 OFF" ,"1.413913620683E9 DISCONNECTED" ,"1.413913620883E9 CONNECTED" ,"1.413913622533E9 CONNECTED" }); bluetoothReader.setFileReader(filereader); List<BluetoothInfo> bluetoothInfo = bluetoothReader.readData("/", 0, 0); assertTrue(bluetoothInfo.size() > 0); } @Test public void readData3() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1.413913535177E9 DISCONNECTED" ,"1.413913591806E9 CONNECTED" }); bluetoothReader.setFileReader(filereader); List<BluetoothInfo> bluetoothInfo = bluetoothReader.readData("/", 0, 0); assertTrue(bluetoothInfo.size() > 0); } @Test public void readData4() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1.413913535177E9 OFF" ,"1.413913591806E9 CONNECTED" }); bluetoothReader.setFileReader(filereader); List<BluetoothInfo> bluetoothInfo = bluetoothReader.readData("/", 0, 0); assertTrue(bluetoothInfo.size() > 0); } @Test public void readData5() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1.413913535177E9 UNKNOWN" ,"1.413913591806E9 CONNECTED" }); bluetoothReader.setFileReader(filereader); List<BluetoothInfo> bluetoothInfo = bluetoothReader.readData("/", 0, 0); assertTrue(bluetoothInfo.size() > 0); } @Test public void readData6() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1.413913535177E9 DISCONNECTED" ,"this should generate \"Invalid Bluetooth trace entry:...\"" ,"1.413913591806E9 CONNECTED" }); bluetoothReader.setFileReader(filereader); List<BluetoothInfo> bluetoothInfo = bluetoothReader.readData("/", 0, 0); assertTrue(bluetoothInfo.size() > 0); } @Test public void fileDoesntExist(){ Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(false); List<BluetoothInfo> bluetoothInfo = bluetoothReader.readData("/", 0, 0); assertEquals(0, bluetoothInfo.size()); }
BluetoothInfoReaderImpl extends PeripheralBase implements IBluetoothInfoReader { @Override public double getBluetoothActiveDuration() { return activeBluetoothDuration; } @Override List<BluetoothInfo> readData(String directory, double startTime, double traceDuration); @Override double getBluetoothActiveDuration(); }
@Test public void getBluetoothActiveDuration() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); String[] arr = new String[] { "1.413913535177E9 CONNECTED" ,"1.413913591806E9 CONNECTED" ,"1.413913610613E9 OFF" ,"1.413913620683E9 DISCONNECTED" ,"1.413913620883E9 CONNECTED" ,"1.413913622533E9 JUNK" ,"" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); bluetoothReader.readData("/", 0, 0); double activeDuration = bluetoothReader.getBluetoothActiveDuration(); assertEquals(77.086, ((double)Math.round(activeDuration*1000.0))/1000, 0); }
RootedAndroidCollectorImpl implements IDataCollector, IVideoImageSubscriber { @Override public StatusResult stopCollector() { log.info(Util.getMethod() + " stopCollector() for rooted-android-collector"); StatusResult result = new StatusResult(); this.running = false; if (device == null) { return result; } if (device.isEmulator()) { GoogleAnalyticsUtil.getGoogleAnalyticsInstance().sendAnalyticsEvents(GoogleAnalyticsUtil.getAnalyticsEvents().getEmulator(), GoogleAnalyticsUtil.getAnalyticsEvents().getEndTrace()); android.stopTcpDump(device); while (android.isTraceRunning()) { try { Thread.sleep(100); } catch (InterruptedException e) { break; } } result = pullTraceFromEmulator(); } else { GoogleAnalyticsUtil.getGoogleAnalyticsInstance().sendAnalyticsEvents(GoogleAnalyticsUtil.getAnalyticsEvents().getRootedCollector(), GoogleAnalyticsUtil.getAnalyticsEvents().getEndTrace()); stopCollectorInDevice(); result = pullTrace(DEVICECOLLECTORFILENAMES); } if (isVideo()) { stopCaptureVideo(); } return result; } int getMilliSecondsForTimeout(); @Override String getName(); @Override void addDeviceStatusSubscriber(IDeviceStatus devicestatus); @Override void addVideoImageSubscriber(IVideoImageSubscriber subscriber); @Override int getMajorVersion(); @Override String getMinorVersion(); @Override DataCollectorType getType(); @Override boolean isRunning(); @Override String[] getLog(); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, String password); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, boolean isLiveViewVideo, String deviceId, Hashtable<String, Object> extraParams, String password); @Override void timeOutShutdown(); @Override void haltCollectorInDevice(); @Override boolean isTrafficCaptureRunning(int seconds); void startVideoCapture(); @Override StatusResult stopCollector(); @Override void receiveImage(BufferedImage videoimage); @Override String getPassword(); @Override boolean setPassword(String requestPassword); @Override String[] getDeviceSerialNumber(StatusResult status); @Override IAroDevice[] getDevices(StatusResult status); @Override boolean isDeviceDataPulled(); }
@Test public void teststopCollector_returnIsErrorCode211() { StatusResult testResult = rootedAndroidCollectorImpl.stopCollector(); assertEquals(211, testResult.getError().getCode()); } @Test public void teststopCollector_ThrowException() throws TimeoutException, AdbCommandRejectedException, IOException { when(device.getSyncService()).thenThrow(new IOException()); Date date = new Date(); when(videocapture.getVideoStartTime()).thenReturn(date); StatusResult testResult = rootedAndroidCollectorImpl.stopCollector(); assertEquals(211, testResult.getError().getCode()); }
GpsInfoReaderImpl extends PeripheralBase implements IGpsInfoReader { @Override public List<GpsInfo> readData(String directory, double startTime, double traceDuration) { this.gpsActiveDuration = 0; List<GpsInfo> gpsInfos = new ArrayList<GpsInfo>(); String filepath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.GPS_FILE; if (!filereader.fileExist(filepath)) { return gpsInfos; } String[] lines = null; try { lines = filereader.readAllLine(filepath); } catch (IOException e1) { LOGGER.error("failed to read GPS info: " + filepath); } if (lines == null || lines.length < 1) { return gpsInfos; } double dLastActiveTimeStamp = 0.0; double dActiveDuration = 0.0; GpsState prevGpsState = null; GpsState gpsState = null; double beginTime = 0.0; double endTime = 0.0; String firstLine = lines[0]; if (firstLine != null) { String strFieldsFirstLine[] = firstLine.split(" "); if (strFieldsFirstLine.length == 2) { try { beginTime = Util.normalizeTime(Double.parseDouble(strFieldsFirstLine[0]), startTime); if (TraceDataConst.GPS_STANDBY.equals(strFieldsFirstLine[1])) { prevGpsState = GpsState.GPS_STANDBY; } else if (TraceDataConst.GPS_DISABLED.equals(strFieldsFirstLine[1])) { prevGpsState = GpsState.GPS_DISABLED; } else if (TraceDataConst.GPS_ACTIVE.equals(strFieldsFirstLine[1])) { prevGpsState = GpsState.GPS_ACTIVE; if (0.0 == dLastActiveTimeStamp) { dLastActiveTimeStamp = beginTime; } } else { LOGGER.warn("Invalid GPS state: " + firstLine); prevGpsState = GpsState.GPS_UNKNOWN; } if ((!TraceDataConst.GPS_ACTIVE.equals(strFieldsFirstLine[1])) && dLastActiveTimeStamp > 0.0) { dActiveDuration += (beginTime - dLastActiveTimeStamp); dLastActiveTimeStamp = 0.0; } } catch (Exception e) { LOGGER.warn("Unexpected error parsing GPS event: " + firstLine, e); } } String strLineBuf; for (int i = 1; i < lines.length; i++) { strLineBuf = lines[i]; String strFields[] = strLineBuf.split(" "); if (strFields.length == 2) { try { endTime = Util.normalizeTime(Double.parseDouble(strFields[0]), startTime); if (TraceDataConst.GPS_STANDBY.equals(strFields[1])) { gpsState = GpsState.GPS_STANDBY; } else if (TraceDataConst.GPS_DISABLED.equals(strFields[1])) { gpsState = GpsState.GPS_DISABLED; } else if (TraceDataConst.GPS_ACTIVE.equals(strFields[1])) { gpsState = GpsState.GPS_ACTIVE; if (0.0 == dLastActiveTimeStamp) { dLastActiveTimeStamp = endTime; } } else { LOGGER.warn("Invalid GPS state: " + strLineBuf); gpsState = GpsState.GPS_UNKNOWN; } gpsInfos.add(new GpsInfo(beginTime, endTime, prevGpsState)); if ((!TraceDataConst.GPS_ACTIVE.equals(strFields[1])) && dLastActiveTimeStamp > 0.0) { dActiveDuration += (endTime - dLastActiveTimeStamp); dLastActiveTimeStamp = 0.0; } prevGpsState = gpsState; beginTime = endTime; } catch (Exception e) { LOGGER.warn("Unexpected error parsing GPS event: " + strLineBuf, e); } } else { LOGGER.warn("Invalid GPS trace entry: " + strLineBuf); } } gpsInfos.add(new GpsInfo(beginTime, traceDuration, prevGpsState)); if (prevGpsState == GpsState.GPS_ACTIVE) { dActiveDuration += Math.max(0, traceDuration - dLastActiveTimeStamp); } this.gpsActiveDuration = dActiveDuration; Collections.sort(gpsInfos); } return gpsInfos; } @Override double getGpsActiveDuration(); @Override List<GpsInfo> readData(String directory, double startTime, double traceDuration); }
@Test public void readData() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); String[] arr = new String[] { "1.414011237411E9 OFF", "1.414011282953E9 ACTIVE", "1.414011295886E9 PhonyState", "1.414011300035E9 ACTIVE", "1.414011311924E9 STANDBY" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); gpsEventReader.setFileReader(filereader); List<GpsInfo> info = gpsEventReader.readData("/", 0, 0); assertTrue(info.size() > 0); } @Test public void readData1() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); String[] arr = new String[] { "1.414011237411E9 UNKNOWN", "1.414011237411E9 ACTIVE", "1.414011282953E9 ACTIVE", "1.414011295886E9 PhonyState", "1.414011300035E9 ACTIVE", "1.414011311924E9 STANDBY" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); gpsEventReader.setFileReader(filereader); List<GpsInfo> info = gpsEventReader.readData("/", 0, 0); assertTrue(info.size() > 0); } @Test public void readData2() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); String[] arr = new String[] { "1.414011237411E9 UNKNOWN", "1.414011237411E9 ACTIVE", "1.414011282953E9 ACTIVE", "bad data PhonyState", "1.414011300035E9 ACTIVE", "1.414011311924E9 STANDBY" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); gpsEventReader.setFileReader(filereader); List<GpsInfo> info = gpsEventReader.readData("/", 0, 0); assertTrue(info.size() > 0); } @Test public void readData3() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); String[] arr = new String[] { "1.414011237411E9 ACTIVE", "1.414011237411E9 ACTIVE", "1.414011282953E9 ACTIVE", "1.414011295886E9 PhonyState", "1.414011300035E9 ACTIVE", "1.414011311924E9 STANDBY" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); gpsEventReader.setFileReader(filereader); List<GpsInfo> info = gpsEventReader.readData("/", 0, 0); assertTrue(info.size() > 0); } @Test public void readData_firstInStandby() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); String[] arr = new String[] { "1.414011237411E9 STANDBY", "1.414011237411E9 DISABLED", "1.414011282953E9 ACTIVE", "1.414011295886E9 PhonyState", "1.414011300035E9 ACTIVE", "1.414011311924E9 STANDBY" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); gpsEventReader.setFileReader(filereader); List<GpsInfo> info = gpsEventReader.readData("/", 0, 0); assertTrue(info.size() > 0); } @Test public void readData_Exception_readAllLine() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenThrow(new IOException("Exception_readAllLine")); List<GpsInfo> info = gpsEventReader.readData("/", 0, 0); assertTrue(info.size() == 0); }
GpsInfoReaderImpl extends PeripheralBase implements IGpsInfoReader { @Override public double getGpsActiveDuration() { return this.gpsActiveDuration; } @Override double getGpsActiveDuration(); @Override List<GpsInfo> readData(String directory, double startTime, double traceDuration); }
@Test public void getActiveDuration() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); String[] arr = new String[] { "1.414011237411E9 OFF", "1.414011282953E9 ACTIVE", "1.414011295886E9 PhonyState", "1.414011300035E9 ACTIVE", "1.414011311924E9 STANDBY" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); gpsEventReader.setFileReader(filereader); double activeDuration = gpsEventReader.getGpsActiveDuration(); assertEquals(24.822, ((double)Math.round(activeDuration*1000.0))/1000, 0); }
SpeedThrottleEventReaderImpl extends PeripheralBase implements ISpeedThrottleEventReader { @Override public List<SpeedThrottleEvent> readData(String directory) { List<SpeedThrottleEvent> throttleInfo = new ArrayList<SpeedThrottleEvent>(); String filepath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.SPEED_THROTTLE_EVENT; if (!filereader.fileExist(filepath)) { return throttleInfo; } String[] lines = null; try { lines = filereader.readAllLine(filepath); } catch (IOException e1) { LOGGER.error("Failed to open file for Speed Throttle Event: " + filepath, e1); } if(lines != null && lines.length > 0){ for (String strLineBuf : lines) { throttleInfo.add(processThrottleData(strLineBuf)); } } return throttleInfo; } @Override List<SpeedThrottleEvent> readData(String directory); }
@Test public void testReadDataNoFile(){ Mockito.when(fileReader.fileExist(traceFolder)).thenReturn(false); List<SpeedThrottleEvent> throttleInfos = speedThrottleReader.readData(traceFolder); assertNotNull(throttleInfos); assertEquals(0, throttleInfos.size()); } @Test public void testReadData()throws IOException { Mockito.when(fileReader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(fileReader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "DLT , 12288 , 1488927413524", "ULT , 12288 , 1488927433783", "DLT , 102400 , 1488927450230", }); List<SpeedThrottleEvent> throttleInfos = speedThrottleReader.readData(traceFolder); assertNotNull(throttleInfos); assertEquals(3, throttleInfos.size()); assertEquals(SpeedThrottleFlow.DLT, throttleInfos.get(0).getThrottleFlow()); assertEquals(12288, throttleInfos.get(0).getThrottleSpeed()); assertEquals(1488927413524L, throttleInfos.get(0).getTimeStamp()); } @Test public void testReadDataThrowException() throws IOException { Mockito.when(fileReader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(fileReader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "DLT , 12288 , 1488927413524"}); List<SpeedThrottleEvent> throttleInfos = speedThrottleReader.readData(traceFolder); assertNotNull(throttleInfos); }
BatteryInfoReaderImpl extends PeripheralBase implements IBatteryInfoReader { @Override public List<BatteryInfo> readData(String directory, double startTime) { List<BatteryInfo> batteryInfos = new ArrayList<BatteryInfo>(); int previousLevel = 0; int previousTemp = 0; boolean previousState = false; String filepath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.BATTERY_FILE; if (!filereader.fileExist(filepath)) { return batteryInfos; } String[] lines = null; try { lines = filereader.readAllLine(filepath); } catch (IOException e1) { LOGGER.error("failed to open file for battery info: " + filepath); } if (lines != null) { for (String strLineBuf : lines) { String strFields[] = strLineBuf.split(" "); if (strFields.length == 4) { try { double bTimeStamp = Util.normalizeTime(Double.parseDouble(strFields[0]), startTime); int bLevel = Integer.parseInt(strFields[1]); int bTemp = Integer.parseInt(strFields[2]); boolean bState = Boolean.valueOf(strFields[3]); if ((bLevel != previousLevel) || (bTemp != previousTemp) || (bState != previousState)) { batteryInfos.add(new BatteryInfo(bTimeStamp, bState, bLevel, bTemp)); } previousLevel = Integer.parseInt(strFields[1]); previousTemp = Integer.parseInt(strFields[2]); previousState = Boolean.valueOf(strFields[3]); } catch (Exception e) { LOGGER.warn("Unexpected error parsing battery event: " + strLineBuf, e); } } else { LOGGER.warn("Invalid battery_events entry: " + strLineBuf); } } } return batteryInfos; } @Override List<BatteryInfo> readData(String directory, double startTime); }
@Test public void readData() throws IOException{ Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn( new String[] { "1.389038277403E9 33 37 false", "1.389038308374E9 32 37 false", "1.389038365419E9 32 37 false" }); List<BatteryInfo> batteryInfos = batteryreader.readData("/", 0); assertTrue(batteryInfos.size() == 2); } @Test public void duplicateState() throws IOException{ Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn( new String[] { "1.389038277403E9 33 37 false" , "1.389038308374E9 32 37 false" , "1.389038308384E9 32 37 false" , "1.389038365419E9 32 37 false" }); List<BatteryInfo> batteryInfos = batteryreader.readData("/", 0); assertTrue(batteryInfos.size() == 2); } @Test public void invalidLength() throws IOException{ Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn( new String[] { "1.389038277403E9 3 3 37 false", "1.389038308374E9 32 37 false", "1.389038365419E9 32 37 false" }); List<BatteryInfo> batteryInfos = batteryreader.readData("/", 0); assertTrue(batteryInfos.size() == 1); } @Test public void badIntegerParse() throws IOException{ Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn( new String[] { "1.38903827740zE9 33 37 false", "1.389038308374E9 32 37 false", "1.389038365419E9 32 37 false" }); List<BatteryInfo> batteryInfos = batteryreader.readData("/", 0); assertTrue(batteryInfos.size() == 1); } @Test public void readNull() throws IOException{ Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(null); List<BatteryInfo> batteryInfos = batteryreader.readData("/", 0); assertTrue(batteryInfos.size() == 0); } @Test public void readNoLines() throws IOException{ Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn( new String[] {}); List<BatteryInfo> batteryInfos = batteryreader.readData("/", 0); assertTrue(batteryInfos.size() == 0); } @Test public void readAllLineException() throws IOException{ Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenThrow(new IOException("failed on purpose")); List<BatteryInfo> batteryInfos = batteryreader.readData("/", 0); assertTrue(batteryInfos.size() == 0); } @Test public void noFile() throws IOException{ Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(false); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn( new String[] { "1.389038277403E9 33 37 false", "1.389038308374E9 32 37 false", "1.389038365419E9 32 37 false" }); List<BatteryInfo> batteryInfos = batteryreader.readData("/", 0); assertTrue(batteryInfos.size() == 0); }
AlarmInfoReaderImpl extends PeripheralBase implements IAlarmInfoReader { @Override public List<AlarmInfo> readData(String directory, double dumpsysEpochTimestamp, double dumpsysElapsedTimestamp, Date traceDateTime) { List<AlarmInfo> alarmInfos = new ArrayList<AlarmInfo>(); String filepath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.KERNEL_LOG_FILE; double timestamp; double timestampElapsed; double timestampEpoch; double timeDeltaEpochElapsed = dumpsysEpochTimestamp - dumpsysElapsedTimestamp; AlarmType alarmType; String[] lines = null; if (!filereader.fileExist(filepath)) { return alarmInfos; } try { lines = filereader.readAllLine(filepath); } catch (IOException e1) { LOGGER.error("failed to read kernal log file for Alarm Info data: " + filepath); return alarmInfos; } for (String strLineBuf : lines) { if (strLineBuf.indexOf("alarm_timer_triggered") > 0) { String strFields[] = strLineBuf.split(" "); if (strFields.length > 1) { try { timestamp = 0; switch (Integer.parseInt(strFields[strFields.length - 3])) { case 0: alarmType = AlarmType.RTC_WAKEUP; break; case 1: alarmType = AlarmType.RTC; break; case 2: alarmType = AlarmType.ELAPSED_REALTIME_WAKEUP; timestamp = timeDeltaEpochElapsed; break; case 3: alarmType = AlarmType.ELAPSED_REALTIME; timestamp = timeDeltaEpochElapsed; break; default: LOGGER.warn("cannot resolve alarm type: " + timestamp + " type " + Double.parseDouble(strFields[strFields.length - 3])); alarmType = AlarmType.UNKNOWN; break; } timestamp += Double.parseDouble(strFields[strFields.length - 1]) / 1000000; timestampEpoch = timestamp; timestamp = timestamp - traceDateTime.getTime(); timestampElapsed = timestampEpoch - dumpsysEpochTimestamp + dumpsysElapsedTimestamp; alarmInfos.add(new AlarmInfo(timestamp, timestampEpoch, timestampElapsed, alarmType)); } catch (Exception e) { LOGGER.warn("Unexpected error parsing alarm event: " + strLineBuf, e); } } } } return alarmInfos; } @Override List<AlarmInfo> readData(String directory, double dumpsysEpochTimestamp, double dumpsysElapsedTimestamp, Date traceDateTime); }
@Test public void readData_noFile() throws IOException{ String[] arr = getAlarmData(); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); Date traceDateTime = new Date(); Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(false); List<AlarmInfo> list = reader.readData(traceFolder, 123, 124, traceDateTime); assertTrue(list.size() == 0); } @Test public void readData() throws IOException{ String[] arr = getAlarmData(); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); Date traceDateTime = new Date(); Mockito.when(filereader.fileExist(traceFolder + Util.FILE_SEPARATOR + TraceDataConst.FileName.KERNEL_LOG_FILE)).thenReturn(true); List<AlarmInfo> list = reader.readData(traceFolder, 123, 124, traceDateTime); assertTrue(list.size() > 0); } @Test public void readData_IOException() throws IOException{ Mockito.when(filereader.readAllLine(Mockito.anyString())).thenThrow(new IOException("test exception")); Date traceDateTime = new Date(); Mockito.when(filereader.fileExist(traceFolder + Util.FILE_SEPARATOR + TraceDataConst.FileName.KERNEL_LOG_FILE)).thenReturn(true); List<AlarmInfo> list = reader.readData(traceFolder, 123, 124, traceDateTime); assertTrue(list.size() == 0); } @Test public void readData_BadData() throws IOException{ Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "<6>[ 0.000z00] Initializing cgroup subsys cpu" , "<6>[ 1770.877611] alarm_timer_triggered type 0 at 302m2491z4374" , "<MCLL>[ 0.000000] CPU: ARMv7 Processor [412fc082] revision 2 (ARMv7), cr=10c53c7d" }); Date traceDateTime = new Date(); Mockito.when(filereader.fileExist(traceFolder + Util.FILE_SEPARATOR + TraceDataConst.FileName.KERNEL_LOG_FILE)).thenReturn(true); List<AlarmInfo> list = reader.readData(traceFolder, 123, 124, traceDateTime); assertTrue(list.size() == 0); }
CpuActivityReaderImpl extends PeripheralBase implements ICpuActivityReader { @Override public CpuActivityList readData(String directory, double startTime) { String cpuFileName = TraceDataConst.FileName.CPU_FILE; CpuActivityList cpuActivityList = new CpuActivityList(); LOGGER.debug("Reading CPU file..."); String filepath = directory + Util.FILE_SEPARATOR + cpuFileName; if (!filereader.fileExist(filepath)) { LOGGER.warn("cpu file not found: " + cpuFileName); return cpuActivityList; } String[] lines; try { lines = filereader.readAllLine(filepath); } catch (IOException e) { LOGGER.error("Failed to read CPU activity file: " + filepath); return cpuActivityList; } for (String line : lines) { if (!line.trim().isEmpty()) { CpuActivity cpuact = cpuActivityParser.parseCpuLine(line, startTime); cpuActivityList.add(cpuact); } } return cpuActivityList; } @Override CpuActivityList readData(String directory, double startTime); }
@Test public void readData() throws IOException { reader = (CpuActivityReaderImpl)context.getBean(ICpuActivityReader.class); IFileManager filereader = Mockito.mock(IFileManager.class); Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); String[] arr = new String[] {"1.413913535E9 73 /sbin/adbd=14 com.att.android.arodatacollector=5 system_server=4 /system/bin/surfaceflinger=2 com.android.systemui=2 top=1 com.google.process.gapps=1", "1.41391354E9 49 /sbin/adbd=24 /system/bin/surfaceflinger=4 system_server=4 com.android.settings=3 com.android.htcdialer=1 top=1 com.att.android.arodatacollector=1", "1.413913545E9 46 /sbin/adbd=22 system_server=5 com.android.systemui=5 /system/bin/surfaceflinger=4 top=1", "1.41391355E9 60 /sbin/adbd=19 system_server=5 /system/bin/surfaceflinger=4 com.htc.launcher=2 ./data/data/com.att.android.arodatacollector/tcpdump=1 top=1", "1.413913556E9 87 com.android.browser=35 /sbin/adbd=18 ./data/data/com.att.android.arodatacollector/tcpdump=13 /system/bin/surfaceflinger=2 logcat=1 RX_Thread=1 kswapd0=1 system_server=1", "1.413913561E9 88 com.android.browser=38 /sbin/adbd=21 ./data/data/com.att.android.arodatacollector/tcpdump=3 /system/bin/surfaceflinger=2 system_server=1 top=1", "1.413913567E9 85 com.android.browser=38 /sbin/adbd=23 ./data/data/com.att.android.arodatacollector/tcpdump=11 /system/bin/surfaceflinger=2 top=1", "1.413913572E9 51 /sbin/adbd=30 com.android.browser=7 /system/bin/surfaceflinger=3 top=1", "1.413913577E9 41 /sbin/adbd=23 /system/bin/surfaceflinger=5 system_server=2 com.android.browser=1 top=1", "1.413913583E9 38 /sbin/adbd=18 com.android.browser=11 /system/bin/surfaceflinger=2 top=1", "1.413913588E9 93 com.android.browser=42 /sbin/adbd=20 ./data/data/com.att.android.arodatacollector/tcpdump=5 /system/bin/surfaceflinger=1 RX_Thread=1 logcat=1 top=1 system_server=1", "1.413913594E9 92 com.android.browser=23 /sbin/adbd=23 /system/bin/surfaceflinger=3 ./data/data/com.att.android.arodatacollector/tcpdump=2 system_server=1 top=1", "1.413913599E9 81 com.android.browser=22 /sbin/adbd=21 com.android.systemui=6 /system/bin/surfaceflinger=6 system_server=5 ./data/data/com.att.android.arodatacollector/tcpdump=1 top=1", "1.413913604E9 56 /sbin/adbd=29 com.android.systemui=9 /system/bin/surfaceflinger=4 system_server=3 top=1", "1.41391361E9 35 /sbin/adbd=18 /system/bin/surfaceflinger=4 system_server=2 top=1", "1.413913615E9 51 /sbin/adbd=41 /system/bin/surfaceflinger=4 top=2 system_server=1 kworker/0:2=1", "1.413913621E9 47 /sbin/adbd=23 /system/bin/surfaceflinger=5 com.android.settings=4 system_server=3 top=2", "1.413913626E9 56 /sbin/adbd=25 com.android.systemui=7 /system/bin/surfaceflinger=5 system_server=3 top=1", "1.413913632E9 87 com.android.browser=47 /sbin/adbd=21 ./data/data/com.att.android.arodatacollector/tcpdump=4 /system/bin/surfaceflinger=2 top=1 com.att.android.arodatacollector=1", "1.413913637E9 86 com.android.browser=45 /sbin/adbd=24 /system/bin/surfaceflinger=3 ./data/data/com.att.android.arodatacollector/tcpdump=1 top=1", "1.413913642E9 80 com.android.browser=38 /sbin/adbd=26 ./data/data/com.att.android.arodatacollector/tcpdump=9 /system/bin/surfaceflinger=3 top=1", "1.413913648E9 92 com.android.browser=45 /sbin/adbd=20 ./data/data/com.att.android.arodatacollector/tcpdump=8 /system/bin/surfaceflinger=4 system_server=2 top=1 kswapd0=1", "1.413913654E9 51 /sbin/adbd=34 /system/bin/surfaceflinger=2 top=1 com.android.browser=1 kworker/0:2=1","" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); reader.setFileReader(filereader); CpuActivityList info = reader.readData("/", 0.0); assertTrue(info.getCpuActivities().size() == 23); assertTrue("what", info.isProcessSelected("./data/data/com.att.android.arodatacollector")); info.recalculateTotalCpu(); Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(false); reader.setFileReader(filereader); info = reader.readData("/", 0.0); assertTrue(info.getCpuActivities().size() == 0); } @Test public void readData_IOException() throws IOException { reader = (CpuActivityReaderImpl)context.getBean(ICpuActivityReader.class); IFileManager filereader = Mockito.mock(IFileManager.class); Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenThrow(new IOException("test exception")); reader.setFileReader(filereader); CpuActivityList info = reader.readData("/", 0.0); assertTrue(info.getCpuActivities().size() == 0); }
WifiInfoReaderImpl extends PeripheralBase implements IWifiInfoReader { @Override public List<WifiInfo> readData(String directory, double startTime, double traceDuration) { this.wifiActiveDuration = 0; List<WifiInfo> wifiInfos = new ArrayList<WifiInfo>(); String filepath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.WIFI_FILE; if (!filereader.fileExist(filepath)) { return wifiInfos; } double dLastTimeStamp = 0.0; double dActiveDuration = 0.0; double beginTime = 0.0; double endTime = 0.0; String prevMacAddress = null; String prevRssi = null; String prevSsid = null; WifiState prevWifiState = null; WifiState lastWifiState = null; String firstLine; String strLineBuf; String[] lines = null; try { lines = filereader.readAllLine(filepath); } catch (IOException e1) { LOGGER.error("failed to read Wifi info file: " + filepath); } if (lines != null && lines.length > 0) { firstLine = lines[0]; try { String strFieldsFirstLine[] = firstLine.split(" "); if (strFieldsFirstLine.length >= 2) { beginTime = Util.normalizeTime(Double.parseDouble(strFieldsFirstLine[0]), startTime); if (TraceDataConst.WIFI_OFF.equals(strFieldsFirstLine[1])) { prevWifiState = WifiState.WIFI_DISABLED; } else if (TraceDataConst.WIFI_CONNECTED.equals(strFieldsFirstLine[1])) { prevWifiState = WifiState.WIFI_CONNECTED; Matcher matcher = wifiPattern.matcher(firstLine); if (matcher.lookingAt()) { prevMacAddress = matcher.group(1); prevRssi = matcher.group(2); prevSsid = matcher.group(3); } else { LOGGER.warn("Unable to parse wifi connection params: " + firstLine); } } else if (TraceDataConst.WIFI_DISCONNECTED.equals(strFieldsFirstLine[1])) { prevWifiState = WifiState.WIFI_DISCONNECTED; } else if (TraceDataConst.WIFI_CONNECTING.equals(strFieldsFirstLine[1])) { prevWifiState = WifiState.WIFI_CONNECTING; } else if (TraceDataConst.WIFI_DISCONNECTING.equals(strFieldsFirstLine[1])) { prevWifiState = WifiState.WIFI_DISCONNECTING; } else if (TraceDataConst.WIFI_SUSPENDED.equals(strFieldsFirstLine[1])) { prevWifiState = WifiState.WIFI_SUSPENDED; } else { LOGGER.warn("Unknown wifi state: " + firstLine); prevWifiState = WifiState.WIFI_UNKNOWN; } lastWifiState = prevWifiState; dLastTimeStamp = beginTime; } else { LOGGER.warn("Invalid WiFi trace entry: " + firstLine); } } catch (Exception e) { LOGGER.warn("Unexpected error parsing GPS event: " + firstLine, e); } for (int i = 1; i < lines.length; i++) { strLineBuf = lines[i]; String strFields[] = strLineBuf.split(" "); try { if (strFields.length >= 2) { String macAddress = null; String rssi = null; String ssid = null; WifiState wifiState = null; endTime = Util.normalizeTime(Double.parseDouble(strFields[0]), startTime); if (TraceDataConst.WIFI_OFF.equals(strFields[1])) { wifiState = WifiState.WIFI_DISABLED; } else if (TraceDataConst.WIFI_CONNECTED.equals(strFields[1])) { wifiState = WifiState.WIFI_CONNECTED; Matcher matcher = wifiPattern.matcher(strLineBuf); if (matcher.lookingAt()) { macAddress = matcher.group(1); rssi = matcher.group(2); ssid = matcher.group(3); } else { LOGGER.warn("Unable to parse wifi connection params: " + strLineBuf); } } else if (TraceDataConst.WIFI_DISCONNECTED.equals(strFields[1])) { wifiState = WifiState.WIFI_DISCONNECTED; } else if (TraceDataConst.WIFI_CONNECTING.equals(strFields[1])) { wifiState = WifiState.WIFI_CONNECTING; } else if (TraceDataConst.WIFI_DISCONNECTING.equals(strFields[1])) { wifiState = WifiState.WIFI_DISCONNECTING; } else if (TraceDataConst.WIFI_SUSPENDED.equals(strFields[1])) { wifiState = WifiState.WIFI_SUSPENDED; } else { LOGGER.warn("Unknown wifi state: " + strLineBuf); wifiState = WifiState.WIFI_UNKNOWN; } if (!wifiState.equals(lastWifiState)) { wifiInfos.add(new WifiInfo(beginTime, endTime, prevWifiState, prevMacAddress, prevRssi, prevSsid)); if (lastWifiState == WifiState.WIFI_CONNECTED || lastWifiState == WifiState.WIFI_CONNECTING || lastWifiState == WifiState.WIFI_DISCONNECTING) { dActiveDuration += (endTime - dLastTimeStamp); } lastWifiState = wifiState; dLastTimeStamp = endTime; beginTime = endTime; prevWifiState = wifiState; prevMacAddress = macAddress; prevRssi = rssi; prevSsid = ssid; } } else { LOGGER.warn("Invalid WiFi trace entry: " + strLineBuf); } } catch (Exception e) { LOGGER.warn("Unexpected error parsing GPS event: " + strLineBuf, e); } } wifiInfos.add(new WifiInfo(beginTime, traceDuration, prevWifiState, prevMacAddress, prevRssi, prevSsid)); if (lastWifiState == WifiState.WIFI_CONNECTED || lastWifiState == WifiState.WIFI_CONNECTING || lastWifiState == WifiState.WIFI_DISCONNECTING) { dActiveDuration += Math.max(0, traceDuration - dLastTimeStamp); } this.wifiActiveDuration = dActiveDuration; Collections.sort(wifiInfos); } return wifiInfos; } @Override List<WifiInfo> readData(String directory, double startTime, double traceDuration); @Override double getWifiActiveDuration(); }
@Test public void readData() throws IOException { List<WifiInfo> wifiInfos = null; Mockito.when(filereader.fileExist(wifi_events)).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(getMockedFileData()); traceDataReader.setFileReader(filereader); wifiInfos = traceDataReader.readData("", 1.412361724E12, 1412361675045.0); assertEquals(11, wifiInfos.size(),0); assertEquals("WIFI_CONNECTED", wifiInfos.get(0).getWifiState().toString()); assertEquals("84:db:2f:0b:fe:f0", wifiInfos.get(0).getWifiMacAddress()); assertEquals("Elevate-FEF0", wifiInfos.get(0).getWifiSSID()); assertEquals("84:db:2f:0b:fe:f0", wifiInfos.get(0).getWifiMacAddress()); assertEquals("WIFI_DISCONNECTED", wifiInfos.get(1).getWifiState().toString()); } @Test public void readData_NoFile() throws IOException { List<WifiInfo> wifiInfos = null; Mockito.when(filereader.fileExist(wifi_events)).thenReturn(false); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(getMockedFileData()); traceDataReader.setFileReader(filereader); wifiInfos = traceDataReader.readData("", 1.412361724E12, 1412361675045.0); assertEquals(0, wifiInfos.size(),0); } @Test public void readData_Exception_readAllLine() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenThrow(new IOException("Exception_readAllLine")); List<WifiInfo> wifiInfos = traceDataReader.readData(traceFolder, 0, 0); assertTrue(wifiInfos.size() == 0); } @Test public void readData_wifi_disconnected() throws IOException { List<WifiInfo> wifiInfos = null; Mockito.when(filereader.fileExist(wifi_events)).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn( new String[] { "1.41142116305E9 DISCONNECTED" ,"1.411421163196E9 CONNECTED 84:db:2f:0b:fe:f0 -74 Elevate-FEF0"}); traceDataReader.setFileReader(filereader); wifiInfos = traceDataReader.readData("", 1.412361724E12, 1412361675045.0); assertEquals(2, wifiInfos.size(),0); assertEquals("WIFI_DISCONNECTED", wifiInfos.get(0).getWifiState().toString()); } @Test public void readData_wifi_disconnected_duplicated() throws IOException { List<WifiInfo> wifiInfos = null; Mockito.when(filereader.fileExist(wifi_events)).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn( new String[] { "1.41142116305E9 DISCONNECTED" ,"1.41142116315E9 DISCONNECTED" ,"1.411421163196E9 CONNECTED 84:db:2f:0b:fe:f0 -74 Elevate-FEF0"}); traceDataReader.setFileReader(filereader); wifiInfos = traceDataReader.readData("", 1.412361724E12, 1412361675045.0); assertEquals(2, wifiInfos.size(),0); assertEquals("WIFI_DISCONNECTED", wifiInfos.get(0).getWifiState().toString()); } @Test public void readData_wifi_connecting() throws IOException { List<WifiInfo> wifiInfos = null; Mockito.when(filereader.fileExist(wifi_events)).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn( new String[] { "1.41142116305E9 CONNECTING" ,"1.411421163196E9 CONNECTED 84:db:2f:0b:fe:f0 -74 Elevate-FEF0"}); traceDataReader.setFileReader(filereader); wifiInfos = traceDataReader.readData("", 1.412361724E12, 1412361675045.0); assertEquals(2, wifiInfos.size(),0); assertEquals("WIFI_CONNECTING", wifiInfos.get(0).getWifiState().toString()); } @Test public void readData_wifi_disconnecting() throws IOException { List<WifiInfo> wifiInfos = null; Mockito.when(filereader.fileExist(wifi_events)).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn( new String[] { "1.41142116305E9 DISCONNECTING" ,"1.411421163196E9 CONNECTED 84:db:2f:0b:fe:f0 -74 Elevate-FEF0"}); traceDataReader.setFileReader(filereader); wifiInfos = traceDataReader.readData("", 1.412361724E12, 1412361675045.0); assertEquals(2, wifiInfos.size(),0); assertEquals("WIFI_DISCONNECTING", wifiInfos.get(0).getWifiState().toString()); } @Test public void readData_wifi_suspended() throws IOException { List<WifiInfo> wifiInfos = null; Mockito.when(filereader.fileExist(wifi_events)).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn( new String[] { "1.41142116305E9 SUSPENDED" ,"1.411421163196E9 CONNECTED 84:db:2f:0b:fe:f0 -74 Elevate-FEF0"}); traceDataReader.setFileReader(filereader); wifiInfos = traceDataReader.readData("", 1.412361724E12, 1412361675045.0); assertEquals(2, wifiInfos.size(),0); assertEquals("WIFI_SUSPENDED", wifiInfos.get(0).getWifiState().toString()); } @Test public void readData_wifi_unknown() throws IOException { List<WifiInfo> wifiInfos = null; Mockito.when(filereader.fileExist(wifi_events)).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn( new String[] { "1.41142116305E9 UNKNOWN" ,"1.411421163196E9 CONNECTED 84:db:2f:0b:fe:f0 -74 Elevate-FEF0"}); traceDataReader.setFileReader(filereader); wifiInfos = traceDataReader.readData("", 1.412361724E12, 1412361675045.0); assertEquals(2, wifiInfos.size(),0); assertEquals("WIFI_UNKNOWN", wifiInfos.get(0).getWifiState().toString()); } @Test public void readData_wifi_disconnected_line2() throws IOException { List<WifiInfo> wifiInfos = null; Mockito.when(filereader.fileExist(wifi_events)).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn( new String[] { "1.41142116305E9 CONNECTED 84:db:2f:0b:fe:f0 -74 Elevate-FEF0" ,"1.411421163196E9 DISCONNECTED"}); traceDataReader.setFileReader(filereader); wifiInfos = traceDataReader.readData("", 1.412361724E12, 1412361675045.0); assertEquals(2, wifiInfos.size(),0); assertEquals("WIFI_DISCONNECTED", wifiInfos.get(1).getWifiState().toString()); } @Test public void readData_wifi_connecting_line2() throws IOException { List<WifiInfo> wifiInfos = null; Mockito.when(filereader.fileExist(wifi_events)).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn( new String[] { "1.41142116305E9 CONNECTED 84:db:2f:0b:fe:f0 -74 Elevate-FEF0" ,"1.411421163196E9 CONNECTING"}); traceDataReader.setFileReader(filereader); wifiInfos = traceDataReader.readData("", 1.412361724E12, 1412361675045.0); assertEquals(2, wifiInfos.size(),0); assertEquals("WIFI_CONNECTING", wifiInfos.get(1).getWifiState().toString()); } @Test public void readData_wifi_disconnecting_line2() throws IOException { List<WifiInfo> wifiInfos = null; Mockito.when(filereader.fileExist(wifi_events)).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn( new String[] { "1.41142116305E9 CONNECTED 84:db:2f:0b:fe:f0 -74 Elevate-FEF0" , "1.411421163196E9 DISCONNECTING" }); traceDataReader.setFileReader(filereader); wifiInfos = traceDataReader.readData("", 1.412361724E12, 1412361675045.0); assertEquals(2, wifiInfos.size(), 0); assertEquals("WIFI_DISCONNECTING", wifiInfos.get(1).getWifiState().toString()); } @Test public void readData_wifi_suspended_line2() throws IOException { List<WifiInfo> wifiInfos = null; Mockito.when(filereader.fileExist(wifi_events)).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn( new String[] { "1.41142116305E9 CONNECTED 84:db:2f:0b:fe:f0 -74 Elevate-FEF0" ,"1.411421163196E9 SUSPENDED"}); traceDataReader.setFileReader(filereader); wifiInfos = traceDataReader.readData("", 1.412361724E12, 1412361675045.0); assertEquals(2, wifiInfos.size(),0); assertEquals("WIFI_SUSPENDED", wifiInfos.get(1).getWifiState().toString()); } @Test public void readData_wifi_unknown_line2() throws IOException { List<WifiInfo> wifiInfos = null; Mockito.when(filereader.fileExist(wifi_events)).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn( new String[] { "1.41142116305E9 CONNECTED 84:db:2f:0b:fe:f0 -74 Elevate-FEF0" ,"1.411421163196E9 UNKNOWN"}); traceDataReader.setFileReader(filereader); wifiInfos = traceDataReader.readData("", 1.412361724E12, 1412361675045.0); assertEquals(2, wifiInfos.size(),0); assertEquals("WIFI_UNKNOWN", wifiInfos.get(1).getWifiState().toString()); }
RootedAndroidCollectorImpl implements IDataCollector, IVideoImageSubscriber { boolean pushApk(IDevice device) { String filepath = getAROCollectorLocation(); boolean gotLocalAPK = true; if (!filemanager.fileExist(filepath)) { ClassLoader loader = RootedAndroidCollectorImpl.class.getClassLoader(); if (!extractor.extractFiles(filepath, ROOTEDCOLLECTOR_APKNAME, loader)) { gotLocalAPK = false; } } if (gotLocalAPK) { try { device.installPackage(filepath, true); log.debug("installed apk in device"); filemanager.deleteFile(filepath); } catch (InstallException e) { log.error(e.getMessage()); return false; } } else { return false; } return true; } int getMilliSecondsForTimeout(); @Override String getName(); @Override void addDeviceStatusSubscriber(IDeviceStatus devicestatus); @Override void addVideoImageSubscriber(IVideoImageSubscriber subscriber); @Override int getMajorVersion(); @Override String getMinorVersion(); @Override DataCollectorType getType(); @Override boolean isRunning(); @Override String[] getLog(); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, String password); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, boolean isLiveViewVideo, String deviceId, Hashtable<String, Object> extraParams, String password); @Override void timeOutShutdown(); @Override void haltCollectorInDevice(); @Override boolean isTrafficCaptureRunning(int seconds); void startVideoCapture(); @Override StatusResult stopCollector(); @Override void receiveImage(BufferedImage videoimage); @Override String getPassword(); @Override boolean setPassword(String requestPassword); @Override String[] getDeviceSerialNumber(StatusResult status); @Override IAroDevice[] getDevices(StatusResult status); @Override boolean isDeviceDataPulled(); }
@Test public void false_pushApk() throws Exception { when(device.getSyncService()).thenThrow(new IOException()); boolean testResult = rootedAndroidCollectorImpl.pushApk(device); assertEquals(false, testResult); } @Test public void gotLocalAPK_pushApk() throws Exception { when(device.getSyncService()).thenThrow(new IOException()); when(filemanager.fileExist(any(String.class))).thenReturn(true); boolean testResult = rootedAndroidCollectorImpl.pushApk(device); assertEquals(true, testResult); }
WifiInfoReaderImpl extends PeripheralBase implements IWifiInfoReader { @Override public double getWifiActiveDuration() { return this.wifiActiveDuration; } @Override List<WifiInfo> readData(String directory, double startTime, double traceDuration); @Override double getWifiActiveDuration(); }
@Test public void getWifiActiveDuration() throws IOException { Mockito.when(filereader.fileExist(wifi_events)).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn( new String[] { "1.41142116305E9 CONNECTED 84:db:2f:0b:fe:f0 -74 Elevate-FEF0" ,"1.412421163196E9 CONNECTED 00:24:36:a7:08:5a -47 The Rabbit Hole 5GHz"}); traceDataReader.setFileReader(filereader); traceDataReader.readData("", 1.412361724E12, 1412361675045.0); double activeDuration = traceDataReader.getWifiActiveDuration(); assertEquals(1.412361675045E12, activeDuration, 0); }
DeviceDetailReaderImpl extends PeripheralBase implements IDeviceDetailReader { @Override public DeviceDetail readData(String directory) { String filepath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.DEVICEDETAILS_FILE; DeviceDetail device = new DeviceDetail(); if (!filereader.fileExist(filepath)) { return null; } String[] lines = null; try { lines = filereader.readAllLine(filepath); } catch (IOException e) { LOGGER.error("failed to read device detail file: " + filepath); } if (lines == null || lines.length < 1) { return null; } device.setTotalLines(lines.length); device.setCollectorName(lines[0]); device.setDeviceModel(lines[1]); device.setDeviceMake(lines[2]); device.setOsType(lines[3]); device.setOsVersion(lines[4]); device.setCollectorVersion(lines[5]); if (lines.length > 7) { device.setScreenSize(lines[7]); } if (lines.length > 8) { double screenDensity; try { screenDensity = Double.parseDouble(lines[8]); } catch (NumberFormatException e) { screenDensity = 0; } device.setScreenDensity(screenDensity); } return device; } @Override DeviceDetail readData(String directory); }
@Test public void readData() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); String[] arr = new String[] { "com.att.android.arodatacollector", "HTC One X", "HTC", "android", "4.0.4", "3.1.1.7", "-1", "720*1184", ""}; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); DeviceDetail info = reader.readData("/"); assertEquals( "com.att.android.arodatacollector", info.getCollectorName()); assertEquals( "HTC One X", info.getDeviceModel()); assertEquals( "HTC", info.getDeviceMake()); assertEquals( "android", info.getOsType()); assertEquals( "4.0.4", info.getOsVersion()); assertEquals( "3.1.1.7", info.getCollectorVersion()); assertEquals( "720*1184", info.getScreenSize()); assertTrue( info.getTotalLines()>0); }
ScreenRotationReaderImpl extends PeripheralBase implements IScreenRotationReader { @Override public List<UserEvent> readData(String directory, double startTime) { List<UserEvent> userEvents = new ArrayList<UserEvent>(); String filepath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.SCREEN_ROTATIONS_FILE; if(!filereader.fileExist(filepath)){ return userEvents; } String[] lines = null; try { lines = filereader.readAllLine(filepath); } catch (IOException e) { LOGGER.error("failed to read screen rotation file: "+filepath); } if(lines != null){ for(String line: lines) { String[] strFields = line.split(" "); double dTimeStamp = Util.normalizeTime(Double.parseDouble(strFields[0]), startTime); if (strFields[1].contains(TraceDataConst.UserEvent.KEY_LANDSCAPE)) { eventType = UserEventType.SCREEN_LANDSCAPE; } else if (strFields[1].contains(TraceDataConst.UserEvent.KEY_PORTRAIT)) { eventType = UserEventType.SCREEN_PORTRAIT; } userEvents.add(new UserEvent(eventType, dTimeStamp, dTimeStamp + 0.5)); } Collections.sort(userEvents, new UserEventSorting()); } return userEvents; } @Override List<UserEvent> readData(String directory, double startTime); UserEventType getEventType(); }
@Test public void readData() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); String[] arr = new String[] { "1.411421173004E9 portrait", "1.411421193602E9 landscape", "1.411421282459E9 portrait", "1.411421287928E9 landscape" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); screenRotationReader.setFileReader(filereader); List<UserEvent> listScreenRotation = screenRotationReader.readData("/", 0); assertEquals(4, listScreenRotation.size(), 0); assertEquals("SCREEN_PORTRAIT", listScreenRotation.get(0).getEventType().name()); assertEquals("SCREEN_LANDSCAPE", listScreenRotation.get(1).getEventType().name()); assertEquals("SCREEN_PORTRAIT", listScreenRotation.get(2).getEventType().name()); assertEquals("SCREEN_LANDSCAPE", listScreenRotation.get(3).getEventType().name()); assertEquals(1.411421173004E9, listScreenRotation.get(0).getPressTime(), 0); assertEquals(1.411421287928E9, listScreenRotation.get(3).getPressTime(), 0); }
DeviceInfoReaderImpl extends PeripheralBase implements IDeviceInfoReader { @Override public Set<InetAddress> readData(String directory) { String filepath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.DEVICEINFO_FILE; Set<InetAddress> localIPAddresses = new HashSet<InetAddress>(1); if (!filereader.fileExist(filepath)) { return localIPAddresses; } String[] lines = null; try { lines = filereader.readAllLine(filepath); } catch (IOException e) { LOGGER.error("failed to read Device Info file: "+filepath); } if(lines != null){ for(String line: lines) { int index = line.indexOf('%'); try { localIPAddresses.add(InetAddress.getByName(index > 0 ? line.substring(0, index) : line)); } catch (UnknownHostException e) { LOGGER.error("failed to read ip address: "+line); } } } return localIPAddresses; } @Override Set<InetAddress> readData(String directory); }
@Test public void readData() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "10.171.214.81" , "fe80::1a87:96ff:fe80:1735%wlan0" , "" }); Set<InetAddress> info = reader.readData(traceFolder); assertTrue(info.contains(InetAddress.getByName("10.171.214.81"))); assertTrue(info.contains(InetAddress.getByName("fe80::1a87:96ff:fe80:1735"))); assertTrue(info.contains(InetAddress.getByName(""))); } @Test public void readData_UnknownHost() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "mangled 10.171.214.blah" , "mangled fe80::1a87:96ff:fe80:1735%wlan0" , "mangled" }); Set<InetAddress> info = reader.readData(traceFolder); assertTrue(info.size() == 0); } @Test public void readData_NoFile() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(false); Set<InetAddress> info = reader.readData(traceFolder); assertTrue(info.size() == 0); }
CameraInfoReaderImpl extends PeripheralBase implements ICameraInfoReader { @Override public List<CameraInfo> readData(String directory, double startTime, double traceDuration) { this.activeDuration = 0; List<CameraInfo> cameraInfos = new ArrayList<CameraInfo>(); String filepath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.CAMERA_FILE; if (!filereader.fileExist(filepath)) { return cameraInfos; } double beginTime = 0.0; double endTime; double dLastActiveTimeStamp = 0.0; double dActiveDuration = 0.0; CameraState prevCameraState = null; CameraState cameraState = null; String firstLine; String strLineBuf; String[] lines = null; try { lines = filereader.readAllLine(filepath); } catch (IOException e1) { LOGGER.error("failed to read Camera info file: "+filepath); } if (lines != null && lines.length > 0) { firstLine = lines[0]; String strFieldsFirstLine[] = firstLine.split(" "); if (strFieldsFirstLine.length == 2) { try { beginTime = Util.normalizeTime(Double.parseDouble(strFieldsFirstLine[0]),startTime); if (TraceDataConst.CAMERA_ON.equals(strFieldsFirstLine[1])) { prevCameraState = CameraState.CAMERA_ON; if (0.0 == dLastActiveTimeStamp) { dLastActiveTimeStamp = beginTime; } } else if (TraceDataConst.CAMERA_OFF.equals(strFieldsFirstLine[1])) { prevCameraState = CameraState.CAMERA_OFF; } else { LOGGER.warn("Unknown camera state: " + firstLine); prevCameraState = CameraState.CAMERA_UNKNOWN; } if ((!TraceDataConst.CAMERA_ON.equals(strFieldsFirstLine[1])) && dLastActiveTimeStamp > 0.0) { dActiveDuration += (beginTime - dLastActiveTimeStamp); dLastActiveTimeStamp = 0.0; } } catch (Exception e) { LOGGER.warn("Unexpected error in camera events: " + firstLine, e); } } else { LOGGER.warn("Unrecognized camera event: " + firstLine); } for (int i=1;i<lines.length;i++) { strLineBuf = lines[i]; String strFields[] = strLineBuf.split(" "); if (strFields.length == 2) { try { endTime = Util.normalizeTime(Double.parseDouble(strFields[0]),startTime); if (TraceDataConst.CAMERA_ON.equals(strFields[1])) { cameraState = CameraState.CAMERA_ON; if (0.0 == dLastActiveTimeStamp) { dLastActiveTimeStamp = endTime; } } else if (TraceDataConst.CAMERA_OFF.equals(strFields[1])) { cameraState = CameraState.CAMERA_OFF; } else { LOGGER.warn("Unknown camera state: " + strLineBuf); cameraState = CameraState.CAMERA_UNKNOWN; } cameraInfos.add(new CameraInfo(beginTime, endTime, prevCameraState)); if ((!TraceDataConst.CAMERA_ON.equals(strFields[1])) && dLastActiveTimeStamp > 0.0) { dActiveDuration += (endTime - dLastActiveTimeStamp); dLastActiveTimeStamp = 0.0; } prevCameraState = cameraState; beginTime = endTime; } catch (Exception e) { LOGGER.warn("Unexpected error in camera events: "+ strLineBuf, e); } } else { LOGGER.warn("Unrecognized camera event: " + strLineBuf); } } cameraInfos.add(new CameraInfo(beginTime, traceDuration, prevCameraState)); if (cameraState == CameraState.CAMERA_ON) { dActiveDuration += Math.max(0, traceDuration - dLastActiveTimeStamp); } this.activeDuration = dActiveDuration; } return cameraInfos; } @Override List<CameraInfo> readData(String directory, double startTime, double traceDuration); @Override double getActiveDuration(); }
@Test public void readData() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1.413913535177E9 OFF" ,"1.413913591806E9 ON" ,"1.413913610613E9 OFF" ,"1.413913620683E9 ON" ,"1.413913620883E9 OFF" ,"1.413913622533E9 OFF" ,"" }); info = cameraReader.readData(traceFolder, 0, 0); assertTrue(info.size() == 6); } @Test public void readData1() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1.413913535177E9 ON" ,"" }); info = cameraReader.readData(traceFolder, 0, 0); assertTrue(info.size() == 1); } @Test public void readData2() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1.413913535177E9 UNKNOWN" ,"1.413913620683E9 ON" }); info = cameraReader.readData(traceFolder, 0, 0); assertTrue(info.size() == 2); } @Test public void readData3() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1.413913535177E9 ON" ,"1.413913620683E9 UNKNOWN" }); info = cameraReader.readData(traceFolder, 0, 0); assertTrue(info.size() == 2); } @Test public void readData_badData() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1.413badtime5177E9 ON" ,"1.moreBadData683E9 UNKNOWN" }); info = cameraReader.readData(traceFolder, 0, 0); assertTrue(info.size() == 1); } @Test public void readData4() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1.413913535177E9 OFF" ,"1.413913620683E9 OFF" ,"1.413913620783E9 ON" }); info = cameraReader.readData(traceFolder, 0, 0); assertTrue(info.size() == 3); } @Test public void readData_emptyData() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] {}); info = cameraReader.readData(traceFolder, 0, 0); assertTrue(info.size() == 0); } @Test public void readData_nullData() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(null); info = cameraReader.readData(traceFolder, 0, 0); assertTrue(info.size() == 0); } @Test public void readData_Unrecognized() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1.413913535177E9 unrecogized event" ,"1.413913620683E9 O0f" ,"1.413913620783E9 wrong" }); info = cameraReader.readData(traceFolder, 0, 0); assertTrue(info.size() == 3); } @Test public void readData_NoFile() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(false); info = cameraReader.readData(traceFolder, 0, 0); assertTrue(info.size() == 0); } @Test public void readData_Exception_readAllLine() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenThrow(new IOException("Exception_readAllLine")); info = cameraReader.readData(traceFolder, 0, 0); assertTrue(info.size() == 0); }
CameraInfoReaderImpl extends PeripheralBase implements ICameraInfoReader { @Override public double getActiveDuration() { return this.activeDuration; } @Override List<CameraInfo> readData(String directory, double startTime, double traceDuration); @Override double getActiveDuration(); }
@Test public void getActiveDuration() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1.413913535177E9 OFF" ,"1.413913591806E9 ON" ,"1.413913610613E9 OFF" ,"1.413913620683E9 ON" ,"1.413913620883E9 OFF" ,"1.413913622533E9 OFF" ,"" }); info = cameraReader.readData(traceFolder, 0, 0); double activeDuration = cameraReader.getActiveDuration(); assertEquals(19.007, ((double)Math.round(activeDuration*1000.0))/1000, 0); }
AppInfoReaderImpl extends PeripheralBase implements IAppInfoReader { @Override public AppInfo readData(String directory) { AppInfo app = new AppInfo(); String filepath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.APPNAME_FILE; if (!filereader.fileExist(filepath)) { LOGGER.warn("Application info file does not exists."); return app; } String[] lines = null; try { lines = filereader.readAllLine(filepath); } catch (IOException e) { LOGGER.error("failed to open appname file: "+filepath); } if(lines != null && lines.length > 0){ for (String line : lines) { String strFields[]; String appName; String appVer = "n/a"; if (line.charAt(0) == '"') { strFields = line.split("\""); appName = strFields[1]; if (strFields.length > 2) { appVer = strFields[2]; app.getAppVersionMap().put(appName, appVer); } } else { strFields = line.split(" "); appName = strFields[0]; if (strFields.length > 1) { appVer = strFields[1]; app.getAppVersionMap().put(appName, appVer); } } app.getAppInfos().add(appName); } } return app; } @Override AppInfo readData(String directory); }
@Test public void readData() throws IOException{ Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); String[] arr = new String[]{"\"/system/bin/rild\"1.1","./data/data/com.att.android.arodatacollector/tcpdump 4.1"}; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); AppInfo info = reader.readData("/"); assertTrue(info.getAppInfos().size() == 2); assertTrue(info.getAppInfos().get(1).contains("tcpdump")); } @Test public void readDataIoException() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenThrow(new IOException("test exception")); AppInfo info = null; info = reader.readData("/"); assertTrue(info.getAppInfos().size() == 0); } @Test public void readDataNoFile() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(false); AppInfo info = null; info = reader.readData("/"); assertTrue(info.getAppInfos().size() == 0); }
TcpdumpRunner implements Runnable { @Override public void run() { android.startTcpDump(device, seLinuxEnforced, traceName); } TcpdumpRunner(IDevice device, String traceName, IAndroid android, boolean seLinuxEnforced); @Override void run(); }
@Test public void testRun(){ tcprunner.run(); }
RootedAndroidCollectorImpl implements IDataCollector, IVideoImageSubscriber { public int getMilliSecondsForTimeout() { return milliSecondsForTimeout; } int getMilliSecondsForTimeout(); @Override String getName(); @Override void addDeviceStatusSubscriber(IDeviceStatus devicestatus); @Override void addVideoImageSubscriber(IVideoImageSubscriber subscriber); @Override int getMajorVersion(); @Override String getMinorVersion(); @Override DataCollectorType getType(); @Override boolean isRunning(); @Override String[] getLog(); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, String password); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, boolean isLiveViewVideo, String deviceId, Hashtable<String, Object> extraParams, String password); @Override void timeOutShutdown(); @Override void haltCollectorInDevice(); @Override boolean isTrafficCaptureRunning(int seconds); void startVideoCapture(); @Override StatusResult stopCollector(); @Override void receiveImage(BufferedImage videoimage); @Override String getPassword(); @Override boolean setPassword(String requestPassword); @Override String[] getDeviceSerialNumber(StatusResult status); @Override IAroDevice[] getDevices(StatusResult status); @Override boolean isDeviceDataPulled(); }
@Test public void testgetMilliSecondsForTimeout() { int timeout = rootedAndroidCollectorImpl.getMilliSecondsForTimeout(); assertEquals(30000, timeout); }
CpuActivityParserImpl implements ICpuActivityParser { @Override public CpuActivity parseCpuLine(String cpuLine, double pcapTime) { CpuActivity cpuActivity = null; String pattern = "[\\s=]"; String splitLine[] = cpuLine.split(pattern); int numOfElements = splitLine.length; if(numOfElements < (CpuActivity.TOTAL_CPU_INFO_IDX + 1)){ return null; } cpuActivity = new CpuActivity(); double time = Double.parseDouble(splitLine[CpuActivity.TIMESTAMP_IDX]); double timeStamp = Util.normalizeTime(time, pcapTime); double cpuUsageTotal = Double.parseDouble(splitLine[CpuActivity.TOTAL_CPU_INFO_IDX]); double cpuUsageTotalFiltered = cpuUsageTotal; cpuActivity.setTimestamp(timeStamp); cpuActivity.setTotalCpuUsage(cpuUsageTotal); cpuActivity.setCpuUsageTotalFiltered(cpuUsageTotalFiltered); if( (numOfElements >= (CpuActivity.PROCESS_INFO_IDX + 1)) && (((numOfElements - CpuActivity.PROCESS_INFO_IDX) % 2) == 0)) { List<String> processNameList = new ArrayList<String>(); List<Double> cpuProcessUsageList = new ArrayList<Double>(); String procName; String cpuUsage; for (int i = CpuActivity.PROCESS_INFO_IDX; i < splitLine.length; i++) { procName = splitLine[i]; cpuUsage = splitLine[++i]; processNameList.add(procName); cpuProcessUsageList.add(Double.parseDouble(cpuUsage)); } cpuActivity.setProcessNames(processNameList); cpuActivity.setCpuUsages(cpuProcessUsageList); double other = 0.0; for (Double individualCpuUsage : cpuActivity.getCpuUsages()) { other += individualCpuUsage.doubleValue(); } other = cpuUsageTotal - other; cpuActivity.setCpuUsageOther(other); } return cpuActivity; } @Override CpuActivity parseCpuLine(String cpuLine, double pcapTime); }
@Test public void readData() throws IOException { reader = (CpuActivityParserImpl)context.getBean(ICpuActivityParser.class); CpuActivity cpuActivity = reader.parseCpuLine("1.413913604E9 56 /sbin/adbd=29 com.android.systemui=9 /system/bin/surfaceflinger=4 system_server=3 top=1", 1.413913604E9); double usage = cpuActivity.getTotalCpuUsage(); assertEquals(56, usage, 0); }
CpuTemperatureReaderImpl extends PeripheralBase implements ICpuTemperatureReader { @Override public List<TemperatureEvent> readData(String directory, double startTime) { List<TemperatureEvent> temperatureEvents = new ArrayList<TemperatureEvent>(); String filePath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.TEMPERATURE_FILE; if (!filereader.fileExist(filePath)) { return temperatureEvents; } String[] contents = null; try { contents = filereader.readAllLine(filePath); } catch (IOException e) { LOGGER.error("failed to read user event file: " + filePath); } if(contents != null && contents.length > 0){ for (String contentBuf : contents) { if (contentBuf.trim().isEmpty()) { continue; } String splitContents[] = contentBuf.split(" "); if (splitContents.length <= 1) { LOGGER.warn("Found invalid user event entry: " + contentBuf); continue; } double timeStamp = Double.parseDouble(splitContents[0]); if (timeStamp > 1.0e9) { timeStamp = Util.normalizeTime(timeStamp, startTime); } int temperatureC = 0; int temperatureF = 0; if (splitContents.length > 1 && splitContents[0].length() > 0) { temperatureC = Integer.parseInt(splitContents[1]); if (temperatureC != 0) { if (splitContents[1].length() > 2) { temperatureC = temperatureC / (int) Math.pow(10, splitContents[1].length() - 2); } temperatureF = (((temperatureC * 9) / 5) + 32); temperatureEvents.add(new TemperatureEvent(timeStamp, temperatureC, temperatureF)); } } } } return temperatureEvents; } @Override List<TemperatureEvent> readData(String directory, double startTime); }
@Test public void readData() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1414108436 21" ,"1414108436 22" ,"1414108463 23" ,"1414108464 24" ,"1414108466 25" ,"1414108466 26" ,"1414108473 27" ,"1414108473 28" ,"1414108473 29" ,"1414108473 30" ,"1414108473 31" ,"1414108473 32" ,"1414108473 33" ,"1414108473 34" , }); List<TemperatureEvent> listTemperatureEvent = traceDataReader.readData(traceFolder, 0.0); assertEquals(14.0, listTemperatureEvent.size(), 0); assertEquals( 21, listTemperatureEvent.get(0).getcelciusTemperature()); assertEquals( 22, listTemperatureEvent.get(1).getcelciusTemperature()); assertEquals( 23, listTemperatureEvent.get(2).getcelciusTemperature()); assertEquals( 24, listTemperatureEvent.get(3).getcelciusTemperature()); assertEquals( 25, listTemperatureEvent.get(4).getcelciusTemperature()); assertEquals( 26, listTemperatureEvent.get(5).getcelciusTemperature()); assertEquals( 27, listTemperatureEvent.get(6).getcelciusTemperature()); assertEquals( 28, listTemperatureEvent.get(7).getcelciusTemperature()); assertEquals( 29, listTemperatureEvent.get(8).getcelciusTemperature()); assertEquals( 30, listTemperatureEvent.get(9).getcelciusTemperature()); assertEquals( 31, listTemperatureEvent.get(10).getcelciusTemperature()); assertEquals( 32, listTemperatureEvent.get(11).getcelciusTemperature()); assertEquals( 33, listTemperatureEvent.get(12).getcelciusTemperature()); assertEquals( 34, listTemperatureEvent.get(13).getcelciusTemperature()); assertEquals(1414108436, listTemperatureEvent.get(0).getTimeRecorded(), 0); assertEquals(1414108436, listTemperatureEvent.get(1).getTimeRecorded(), 0); assertEquals(1414108463, listTemperatureEvent.get(2).getTimeRecorded(), 0); assertEquals(1414108464, listTemperatureEvent.get(3).getTimeRecorded(), 0); assertEquals(1414108466, listTemperatureEvent.get(4).getTimeRecorded(), 0); assertEquals(1414108466, listTemperatureEvent.get(5).getTimeRecorded(), 0); assertEquals(1414108473, listTemperatureEvent.get(6).getTimeRecorded(), 0); assertEquals(1414108473, listTemperatureEvent.get(7).getTimeRecorded(), 0); assertEquals(1414108473, listTemperatureEvent.get(8).getTimeRecorded(), 0); assertEquals(1414108473, listTemperatureEvent.get(9).getTimeRecorded(), 0); assertEquals(1414108473, listTemperatureEvent.get(10).getTimeRecorded(), 0); assertEquals(1414108473, listTemperatureEvent.get(11).getTimeRecorded(), 0); assertEquals(1414108473, listTemperatureEvent.get(12).getTimeRecorded(), 0); assertEquals(1414108473, listTemperatureEvent.get(13).getTimeRecorded(), 0); } @Test public void readData_InvalidTemperatureEvent() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1414108436.923000 " ,"1414108436.957000 21" }); List<TemperatureEvent> listTemperatureEvent = traceDataReader.readData(traceFolder, 0.0); assertEquals(1.0, listTemperatureEvent.size(), 0); } @Ignore @Test(expected=NumberFormatException.class) public void readData_FailedToParse() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "14141z8436 21" ,"1414108436 22" ,"1414108436 23" ,"1414108463 24" ,"1414108464 25" }); List<TemperatureEvent> listTemperatureEvent = traceDataReader.readData(traceFolder, 0.0); assertEquals(0, listTemperatureEvent.size(), 0); } @Test public void readData_NoFile() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(false); List<TemperatureEvent> listTemperatureEvent = traceDataReader.readData(traceFolder, 0.0); assertEquals(0, listTemperatureEvent.size(), 0); } @Test public void readData_IOException() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenThrow(new IOException("test exception")); List<TemperatureEvent> listTemperatureEvent = null; listTemperatureEvent = traceDataReader.readData(traceFolder, 0.0); assertEquals(0, listTemperatureEvent.size(), 0); }
UserEventReaderImpl extends PeripheralBase implements IUserEventReader { @Override public List<UserEvent> readData(String directory, double eventTime0, double startTime) { List<UserEvent> userEvents = new ArrayList<UserEvent>(); Map<UserEventType, Double> lastEvent = new EnumMap<UserEventType, Double>( UserEventType.class); String filepath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.USER_EVENTS_FILE; String getEventsFilePath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.USER_GETEVENTS_FILE; if(filereader.fileExist(filepath)) { userEvents = readUserInputFile(lastEvent, filepath, startTime, eventTime0); } else if (filereader.fileExist(getEventsFilePath)) { userEvents = readGetEventsFile(directory, eventTime0, startTime); } return userEvents; } List<UserEvent> readGetEventsFile(String directory, double eventTime0, double startTime); @Override List<UserEvent> readData(String directory, double eventTime0, double startTime); }
@Test public void readData() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1414108436.923000 screen press" ,"1414108436.957000 screen release" ,"" ,"1414108463.785000 key volup press" ,"1414108464.059000 key volup release" ,"1414108466.065000 key voldown press" ,"1414108466.396000 key voldown release" ,"1414108473.096000 key power press" ,"1414108473.512000 key power release" ,"1414108473.512000 key ball press" ,"1414108473.512000 key ball release" ,"1414108473.512000 key home press" ,"1414108473.512000 key home release" ,"1414108473.512000 key menu press" ,"1414108473.512000 key menu release" ,"1414108473.512000 key back press" ,"1414108473.512000 key back release" ,"1414108473.512000 key search press" ,"1414108473.512000 key search release" ,"1414108473.512000 key green press" ,"1414108473.512000 key green release" ,"1414108473.512000 key red press" ,"1414108473.512000 key red release" ,"1414108473.512000 key key press" ,"1414108473.512000 key key release" ,"" }); List<UserEvent> listUserEvent = traceDataReader.readData(traceFolder, 0, 0); assertEquals(12.0, listUserEvent.size(), 0); assertEquals("SCREEN_TOUCH", listUserEvent.get(0).getEventType().toString()); assertEquals("KEY_VOLUP", listUserEvent.get(1).getEventType().toString()); assertEquals("KEY_VOLDOWN", listUserEvent.get(2).getEventType().toString()); assertEquals("KEY_POWER", listUserEvent.get(3).getEventType().toString()); assertEquals("KEY_BALL", listUserEvent.get(4).getEventType().toString()); assertEquals("KEY_HOME", listUserEvent.get(5).getEventType().toString()); assertEquals("KEY_MENU", listUserEvent.get(6).getEventType().toString()); assertEquals("KEY_BACK", listUserEvent.get(7).getEventType().toString()); assertEquals(1414108436.923000, listUserEvent.get(0).getPressTime(), 0); assertEquals(1414108436.957000, listUserEvent.get(0).getReleaseTime(), 0); assertEquals(1414108463.785000, listUserEvent.get(1).getPressTime(), 0); assertEquals(1414108464.059000, listUserEvent.get(1).getReleaseTime(), 0); assertEquals(1414108466.065000, listUserEvent.get(2).getPressTime(), 0); assertEquals(1414108466.396000, listUserEvent.get(2).getReleaseTime(), 0); assertEquals(1414108473.096000, listUserEvent.get(3).getPressTime(), 0); assertEquals(1414108473.512000, listUserEvent.get(3).getReleaseTime(), 0); } @Test public void readData_InvalidUserEvent() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1414108436.923000 screen press" ,"1414108436.957000 screen release invalid" ,"1414108436.957000 screen release" ,"1414108463.785000 key green press invalid" ,"1414108464.059000 key green release invalid" }); List<UserEvent> listUserEvent = traceDataReader.readData(traceFolder, 0, 0); assertEquals(1, listUserEvent.size(), 0); } @Ignore @Test(expected=NumberFormatException.class) public void readData_FailedToParse() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "14141z8436.923000 screen press" ,"1414108436.957000 screen release invalid" ,"1414108436.957000 screen release" ,"1414108463.785000 key green press invalid" ,"1414108464.059000 key green release invalid" }); List<UserEvent> listUserEvent = traceDataReader.readData(traceFolder, 0, 0); assertEquals(0, listUserEvent.size(), 0); } @Test public void readData_NoFile() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(false); List<UserEvent> listUserEvent = traceDataReader.readData(traceFolder, 0, 0); assertEquals(0, listUserEvent.size(), 0); } @Test public void readData_IOException() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenThrow(new IOException("test exception")); List<UserEvent> listUserEvent = null; listUserEvent = traceDataReader.readData(traceFolder, 0, 0); assertEquals(0, listUserEvent.size(), 0); }
UserEventReaderImpl extends PeripheralBase implements IUserEventReader { public List<UserEvent> readGetEventsFile(String directory, double eventTime0, double startTime) { List<UserEvent> userEvents = new ArrayList<UserEvent>(); String filePath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.USER_GETEVENTS_FILE; String[] lines = null; try { lines = filereader.readAllLine(filePath); } catch (IOException e) { LOGGER.error("failed to read user event file: " + filePath); } if (lines != null && lines.length > 0) { int idx = 1; double monotonicTime = 0; for (String lineBuf : lines) { if (idx == 1) { String monotonicFields[] = lineBuf.split(" "); if (monotonicFields.length > 2) { monotonicTime = (Double.parseDouble(monotonicFields[2])) / 1000000000; } idx++; continue; } if (lineBuf.trim().isEmpty() || lineBuf.contains("add device") || lineBuf.contains("name:")) { continue; } UserEvent.UserEventType actionType = UserEvent.UserEventType.EVENT_UNKNOWN; if (lineBuf.contains(TraceDataConst.GetEvent.SCREEN)) { actionType = UserEventType.SCREEN_TOUCH; } else if (lineBuf.contains(TraceDataConst.GetEvent.KEY)) { if (lineBuf.contains(TraceDataConst.GetEvent.KEY_POWER)) { actionType = UserEventType.KEY_POWER; } else if (lineBuf.contains(TraceDataConst.GetEvent.KEY_VOLUP)) { actionType = UserEventType.KEY_VOLUP; } else if (lineBuf.contains(TraceDataConst.GetEvent.KEY_VOLDOWN)) { actionType = UserEventType.KEY_VOLDOWN; } else if (lineBuf.contains(TraceDataConst.GetEvent.KEY_HOME)) { actionType = UserEventType.KEY_HOME; } else if (lineBuf.contains(TraceDataConst.GetEvent.KEY_MENU)) { actionType = UserEventType.KEY_MENU; } else if (lineBuf.contains(TraceDataConst.GetEvent.KEY_BACK)) { actionType = UserEventType.KEY_BACK; } else if (lineBuf.contains(TraceDataConst.GetEvent.KEY_SEARCH)) { actionType = UserEventType.KEY_SEARCH; } else { actionType = UserEventType.KEY_KEY; } } else { continue; } String strFields[] = lineBuf.split("]"); if (strFields[0].indexOf('[') != -1) { strFields[0] = strFields[0].substring(strFields[0].indexOf('[') + 1, strFields[0].length()); } String timeArray[] = strFields[0].split(" "); Double currentTime = Double.parseDouble(timeArray[timeArray.length - 1]); double dTimeStamp = currentTime - monotonicTime; userEvents.add(new UserEvent(actionType, dTimeStamp, dTimeStamp)); } } return userEvents; } List<UserEvent> readGetEventsFile(String directory, double eventTime0, double startTime); @Override List<UserEvent> readData(String directory, double eventTime0, double startTime); }
@Test public void readEventsFileData() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "now at 11038786578074 nsecs", "[ 11040.931026] /dev/input/event6: EV_ABS ABS_MT_POSITION_X 0000044b", "[ 11052.610105] /dev/input/event5: EV_KEY KEY_VOLUMEUP DOWN", "[ 11052.610105] /dev/input/event5: EV_KEY KEY_VOLUMEDOWN DOWN", "[ 11052.610105] /dev/input/event5: EV_KEY KEY_POWER DOWN", "[ 11052.610105] /dev/input/event5: EV_KEY KEY_HOME DOWN", "[ 11052.610105] /dev/input/event5: EV_KEY KEY_MENU DOWN", "[ 11052.610105] /dev/input/event5: EV_KEY KEY_SEARCH DOWN", "[ 11052.610105] /dev/input/event5: EV_KEY KEY_BACK DOWN", }); List<UserEvent> listUserEvent = traceDataReader.readGetEventsFile(traceFolder, 0, 0); assertEquals(8.0, listUserEvent.size(), 0); assertEquals("SCREEN_TOUCH", listUserEvent.get(0).getEventType().toString()); assertEquals("KEY_VOLUP", listUserEvent.get(1).getEventType().toString()); }
PatternSearchingHandler implements ISearchingHandler { @Override public SearchingResult search(SearchingPattern pattern, SearchingContent content) { SearchingResultBuilder resultBuilder = new SearchingResultBuilder(); if (!isValidPattern(pattern) || !isValidContent(content)) { return resultBuilder.build(); } Map<Character, List<PatternInfo>> pivotCharMap = initPivotCharMap(pattern); String text = content.get(); for(int i = 0; i < text.length(); i++) { char pivotChar = text.charAt(i); if (!hasRelatedPattern(pivotChar, pivotCharMap)) { continue; } List<PatternInfo> relatedPattern = pivotCharMap.get(pivotChar); for(PatternInfo info : relatedPattern) { if (isValidCandidatePattern(info, text, i)) { String candidate = getValidCandidatePattern(info, pivotChar, text, i); if (candidate == null) { continue; } if (compare(candidate, info)) { resultBuilder.add(candidate, info.getType()); } } } } return resultBuilder.build(); } PatternSearchingHandler(); @Override SearchingResult search(SearchingPattern pattern, SearchingContent content); @Override boolean isValidPattern(SearchingPattern pattern); @Override boolean isValidContent(SearchingContent content); }
@Test public void testUnknownSearchingPattern() { SearchingPattern pattern = null; SearchingContent content = new SearchingContent("abcde"); SearchingResult result = searchingHandler.search(pattern, content); assertNotNull(result); assertEquals(0, result.getWords().size()); } @Test public void testEmptyContent() { SearchingPatternBuilder pattenBuilder = new SearchingPatternBuilder(); pattenBuilder.add("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4},-,3,8,-,7,4", PrivateDataType.regex_phone_number.name()); SearchingContent content = new SearchingContent(null); SearchingResult result = searchingHandler.search(pattenBuilder.build(), content); assertNotNull(result); assertEquals(0, result.getWords().size()); } @Test public void testResultNotFound() { SearchingPatternBuilder pattenBuilder = new SearchingPatternBuilder(); pattenBuilder.add("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4},-,3,8,-,7,4", PrivateDataType.regex_phone_number.name()); String text = "https: SearchingContent content = new SearchingContent(text); SearchingResult result = searchingHandler.search(pattenBuilder.build(), content); assertNotNull(result); assertEquals(0, result.getWords().size()); } @Test public void testResultFound() { SearchingPatternBuilder pattenBuilder = new SearchingPatternBuilder(); pattenBuilder.add("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4},-,3,8,-,7,4", PrivateDataType.regex_phone_number.name()); String text = "https: SearchingContent content = new SearchingContent(text); SearchingResult result = searchingHandler.search(pattenBuilder.build(), content); assertNotNull(result); assertEquals(1, result.getWords().size()); assertEquals("443-237-7431", result.getWords().get(0)); }
NetworkTypeReaderImpl extends PeripheralBase implements INetworkTypeReader { @Override public NetworkTypeObject readData(String directory, double startTime, double traceDuration) { NetworkTypeObject obj = null; List<NetworkBearerTypeInfo> networkTypeInfos = new ArrayList<NetworkBearerTypeInfo>(); List<NetworkType> networkTypesList = new ArrayList<NetworkType>(); String filepath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.NETWORKINFO_FILE; if (!filereader.fileExist(filepath)) { return obj; } String[] lines = null; try { lines = filereader.readAllLine(filepath); } catch (IOException e1) { LOGGER.error("failed to read network info file: " + filepath); } String line; if (lines != null && lines.length > 0) { line = lines[0]; networkTypeInfos.clear(); NetworkType networkType; double beginTime; double endTime; String[] fields = line.split(" "); if (fields.length == 2) { beginTime = Util.normalizeTime(Double.parseDouble(fields[0]), startTime); try { networkType = getNetworkTypeFromCode(Integer.parseInt(fields[1])); } catch (NumberFormatException e) { networkType = NetworkType.none; LOGGER.warn("Invalid network type [" + fields[1] + "]"); } networkTypesList.add(networkType); for (int i = 1; i < lines.length; i++) { line = lines[i]; fields = line.split(" "); if (fields.length == 2) { endTime = Util.normalizeTime(Double.parseDouble(fields[0]), startTime); networkTypeInfos.add(new NetworkBearerTypeInfo(beginTime, endTime, networkType)); try { networkType = getNetworkTypeFromCode(Integer.parseInt(fields[1])); } catch (NumberFormatException e) { networkType = NetworkType.none; LOGGER.warn("Invalid network type [" + fields[1] + "]"); } beginTime = endTime; if (!networkTypesList.contains(networkType)) { networkTypesList.add(networkType); } } } networkTypeInfos.add(new NetworkBearerTypeInfo(beginTime, traceDuration, networkType)); } } obj = new NetworkTypeObject(); obj.setNetworkTypeInfos(networkTypeInfos); obj.setNetworkTypesList(networkTypesList); return obj; } @Override NetworkTypeObject readData(String directory, double startTime, double traceDuration); }
@Test public void readData() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); String[] arr = new String[] { "1.358205538539E9 10", "1.358205540396E9 15", "1.35820554882E9 3", "1.358205549444E9 1", "1.358205552859E9 9", "1.358205564577E9 3", "1.358205565208E9 10", "1.358205565834E9 15", "1.358205572238E9 3", "1.358205572969E9 8", "1.358205584581E9 3", "1.358205586095E9 13", "1.358205590906E9 3", "1.358205591561E9 2", "1.358205594481E9 5", "1.358205605874E9 3", "1.358205606144E9 0", "1.358205607302E9 15", "1.358205614199E9 -1", "1.358205623225E9 -1", "1.358205763101E9 15", "1.358205779064E9 3", "1.358205779663E9 33", "1.358205782276E9 fe", "1.358205790737E9 3", "1.358205791067E9 10", "1.358205801382E9 15", }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); networkTypeReader.setFileReader(filereader); NetworkTypeObject info = networkTypeReader.readData("/", 0, 0); List<NetworkType> listNetworkType = info.getNetworkTypesList(); assertEquals(11, listNetworkType.size(), 0); List<NetworkBearerTypeInfo> listNetworkBearerTypeInfo = info.getNetworkTypeInfos(); assertEquals(27, listNetworkBearerTypeInfo.size(), 0); assertEquals(1.358205538539E9, listNetworkBearerTypeInfo.get(0).getBeginTimestamp(), 0); assertEquals(1.358205801382E9, listNetworkBearerTypeInfo.get(26).getBeginTimestamp(), 0); assertEquals("HSPAP", listNetworkBearerTypeInfo.get(26).getNetworkType().toString()); Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(false); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); info = networkTypeReader.readData("/", 0, 0); assertTrue(listNetworkType != null); Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); arr = new String[] { "1.358205538539E9 bd", "1.358205540396E9 15" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); info = networkTypeReader.readData("/", 0, 0); listNetworkType = info.getNetworkTypesList(); assertEquals(2, listNetworkType.size(), 0); }
LocationReaderImpl extends PeripheralBase implements LocationReader { @Override public List<LocationEvent> readData(String directory, double startTime) { List<LocationEvent> locationEvents = new ArrayList<LocationEvent>(); String filePath = directory + Util.FILE_SEPARATOR + TraceDataConst.FileName.LOCATION_FILE; if (!filereader.fileExist(filePath)) { return locationEvents; } String[] contents = null; try { contents = filereader.readAllLine(filePath); } catch (IOException e) { LOGGER.error("failed to read user event file: " + filePath); } if(contents != null && contents.length > 0){ for (String contentBuf : contents) { if (contentBuf.trim().isEmpty()) { continue; } String splitContents[] = contentBuf.split(" "); if (splitContents.length <= 1) { LOGGER.warn("Found invalid event entry: " + contentBuf); continue; } double timeStamp = Double.parseDouble(splitContents[0]); if (timeStamp > 1.0e9) { timeStamp = Util.normalizeTime(timeStamp, startTime); } double latitude = 0; double longitude = 0; String provider = ""; StringBuffer locality = new StringBuffer(); if (splitContents.length >= 4) { try { latitude = Double.parseDouble(splitContents[1]); longitude = Double.parseDouble(splitContents[2]); provider = splitContents[3]; for (int idx = 4; idx <= (splitContents.length - 1); idx++) { if (locality.length() > 0) { locality.append(' '); } locality.append(splitContents[idx]); } locationEvents .add(new LocationEvent(timeStamp, latitude, longitude, provider, locality.toString())); } catch (Exception e) { LOGGER.warn("Found invalid event entry: " + contentBuf); continue; } } } } return locationEvents; } @Override List<LocationEvent> readData(String directory, double startTime); }
@Test public void readData() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1.487031029351E9 47.7943242 -122.2030202 Loction network", "1.487031045307E9 47.7943242 -122.2030202 Loction network", "1.487031067622E9 47.7943242 -122.2030202 Loction network", "1.487031088777E9 47.7943242 -122.2030202 Loction network", "1.487031108855E9 47.7943242 -122.2030202 Loction network", "1.487031128833E9 47.7942768 -122.2030345 Loction network", "1.48703115131E9 47.7943242 -122.2030202 Loction network", "1.487031172095E9 47.7942768 -122.2030345 Loction network", "1.487031190478E9 47.7942768 -122.2030345 Loction network", "1.487031213376E9 47.7942768 -122.2030345 Loction network", "1.487031231069E9 47.7942768 -122.2030345 Loction network", "1.487031251292E9 47.7942768 -122.2030345 Loction network", "1.487031272251E9 47.7942768 -122.2030345 Loction network", }); List<LocationEvent> listLocationEvent = traceDataReader.readData(traceFolder, 0.0); assertEquals(13.0, listLocationEvent.size(), 0); assertEquals( 47.7943242, listLocationEvent.get(0).getLatitude(), 0); assertEquals( 47.7943242, listLocationEvent.get(1).getLatitude(), 0); assertEquals( 47.7943242, listLocationEvent.get(2).getLatitude(), 0); assertEquals( 47.7943242, listLocationEvent.get(3).getLatitude(), 0); assertEquals( 47.7943242, listLocationEvent.get(4).getLatitude(), 0); assertEquals( 47.7942768, listLocationEvent.get(5).getLatitude(), 0); assertEquals( 47.7943242, listLocationEvent.get(6).getLatitude(), 0); assertEquals( 47.7942768, listLocationEvent.get(7).getLatitude(), 0); assertEquals( 47.7942768, listLocationEvent.get(8).getLatitude(), 0); assertEquals( 47.7942768, listLocationEvent.get(9).getLatitude(), 0); assertEquals( 47.7942768, listLocationEvent.get(10).getLatitude(), 0); assertEquals( 47.7942768, listLocationEvent.get(11).getLatitude(), 0); assertEquals( 47.7942768, listLocationEvent.get(12).getLatitude(), 0); assertEquals( -122.2030202, listLocationEvent.get(0).getLongitude(), 0); assertEquals( -122.2030202, listLocationEvent.get(1).getLongitude(), 0); assertEquals( -122.2030202, listLocationEvent.get(2).getLongitude(), 0); assertEquals( -122.2030202, listLocationEvent.get(3).getLongitude(), 0); assertEquals( -122.2030202, listLocationEvent.get(4).getLongitude(), 0); assertEquals( -122.2030345, listLocationEvent.get(5).getLongitude(), 0); assertEquals( -122.2030202, listLocationEvent.get(6).getLongitude(), 0); assertEquals( -122.2030345, listLocationEvent.get(7).getLongitude(), 0); assertEquals( -122.2030345, listLocationEvent.get(8).getLongitude(), 0); assertEquals( -122.2030345, listLocationEvent.get(9).getLongitude(), 0); assertEquals( -122.2030345, listLocationEvent.get(10).getLongitude(), 0); assertEquals( -122.2030345, listLocationEvent.get(11).getLongitude(), 0); assertEquals( -122.2030345, listLocationEvent.get(12).getLongitude(), 0); } @Test public void readData_InvalidLocationEvent() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1.487031029351E9 ", "1.487031045307E9 47.7943242 -122.2030202 Loction network", }); List<LocationEvent> listLocationEvent = traceDataReader.readData(traceFolder, 0.0); assertEquals(1.0, listLocationEvent.size(), 0); } @Ignore @Test(expected=Exception.class) public void readData_FailedToParse() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] { "1.487031029351E9 47.794dummy3242 -122.2030202 Loction network", }); List<LocationEvent> listLocationEvent = traceDataReader.readData(traceFolder, 0.0); assertEquals(0, listLocationEvent.size(), 0); } @Test public void readData_NoFile() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(false); List<LocationEvent> listLocationEvent = traceDataReader.readData(traceFolder, 0.0); assertEquals(0, listLocationEvent.size(), 0); } @Test public void readData_IOException() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenThrow(new IOException("test exception")); List<LocationEvent> listLocationEvent = null; listLocationEvent = traceDataReader.readData(traceFolder, 0.0); assertEquals(0, listLocationEvent.size(), 0); }
AROServiceImpl implements IAROService { @Override public String getName() { return info.getName(); } @Autowired @Qualifier("jsongenerate") void setJsonreport(IReport jsonreport); @Autowired @Qualifier("htmlgenerate") void setHtmlreport(IReport htmlreport); @Autowired void setPacketAnalyzer(IPacketAnalyzer packetanalyzer); @Autowired void setCacheAnalysis(ICacheAnalysis cacheanalysis); @Autowired @Qualifier("periodicTransfer") void setPeriodicTransfer(IBestPractice periodicTransfer); @Autowired @Qualifier("unnecessaryConnection") void setUnnecessaryConnection(IBestPractice unnecessaryConnection); @Autowired @Qualifier("connectionOpening") void setConnectionOpening(IBestPractice connectionOpening); @Autowired @Qualifier("connectionClosing") void setConnectionClosing(IBestPractice connectionClosing); @Autowired @Qualifier("screenRotation") void setScreenRotation(IBestPractice screenRotation); @Autowired @Qualifier("accessingPeripheral") void setAccessingPeripheral(IBestPractice accessingPeripheral); @Autowired @Qualifier("combineCsJss") void setCombineCsJss(IBestPractice combineCsJss); @Autowired @Qualifier("http10Usage") void setHttp10Usage(IBestPractice http10Usage); @Autowired @Qualifier("cacheControl") void setCacheControl(IBestPractice cacheControl); @Autowired @Qualifier("usingCache") void setUsingCache(IBestPractice usingCache); @Autowired @Qualifier("duplicateContent") void setDuplicateContent(IBestPractice duplicateContent); @Autowired @Qualifier("http4xx5xx") void setHttp4xx5xx(IBestPractice http4xx5xx); @Autowired @Qualifier("simultaneous") void setSimultaneous(IBestPractice simultaneous); @Autowired @Qualifier("multipleSimultaneous") void setMultipleSimultaneous(IBestPractice multipleSimultaneous); @Autowired @Qualifier("http3xx") void setHttp3xx(IBestPractice http3xx); @Autowired @Qualifier("textFileCompression") void setTextFileCompression(IBestPractice textFileCompression); @Autowired @Qualifier("imageSize") void setImageSize(IBestPractice imageSize); @Autowired @Qualifier("imageMetadata") void setImageMdata(IBestPractice imageMetadata); @Autowired @Qualifier("imageCompression") void setImageCompression(IBestPractice imageCompression); @Autowired @Qualifier("imageFormat") void setImageFormat(IBestPractice imageFormat); @Autowired @Qualifier("uiComparator") void setUIComparator(IBestPractice uiComparator); @Autowired @Qualifier("minify") void setMinify(IBestPractice minify); @Autowired @Qualifier("emptyUrl") void setEmptyUrl(IBestPractice emptyUrl); @Autowired @Qualifier("spriteImage") void setSpriteImage(IBestPractice spriteImage); @Autowired @Qualifier("scripts") void setScripts(IBestPractice scripts); @Autowired @Qualifier("async") void setAsync(IBestPractice async); @Autowired @Qualifier("displaynoneincss") void setDisplayNoneInCSS(IBestPractice displaynoneincss); @Autowired @Qualifier("fileorder") void setFileOrder(IBestPractice fileorder); @Autowired @Qualifier("videoStall") void setVideoStallImpl(IBestPractice videoStall); @Autowired @Qualifier("networkComparison") void setVideoNetworkComparisonImpl(IBestPractice networkcomparison); @Autowired @Qualifier("startupDelay") void setVideoStartupDelayImpl(IBestPractice startupdelay); @Autowired @Qualifier("bufferOccupancy") void setVideoBufferOccupancyImpl(IBestPractice bufferoccupancy); @Autowired @Qualifier("tcpConnection") void setTcpconnectionImpl(IBestPractice tcpconnection); @Autowired @Qualifier("chunkPacing") void setChunkpacingImpl(IBestPractice chunkpacing); @Autowired @Qualifier("chunkSize") void setChunksizeImpl(IBestPractice chunksize); @Autowired @Qualifier("videoRedundancy") void setVideoredundancyImpl(IBestPractice videoredundancy); @Autowired @Qualifier("videoConcurrentSession") void setVideoConcurrentSessionImpl(IBestPractice videoConcurrentSession); @Autowired @Qualifier("videoVariableBitrate") void setVideoVariableBitrateImpl(IBestPractice videoVariableBitrate); @Autowired @Qualifier("videoResolutionQuality") void setVideoResolutionQualityImpl(IBestPractice videoResolutionQuality); @Autowired @Qualifier("adaptiveBitrateLadder") void setvideoSegmentQualityImpl(IBestPractice videoSegmentQuality); @Autowired @Qualifier("audioStream") void setSeparateAudioImpl(IBestPractice audioStream); @Autowired @Qualifier("httpsUsage") void setHttpsUsage(IBestPractice httpsUsage); @Autowired @Qualifier("transmissionPrivateData") void setTransmissionPrivateData(IBestPractice transmissionPrivateData); @Autowired @Qualifier("unsecureSSLVersion") void setUnsecureSSLVersion(IBestPractice unsecureSSLVersion); @Autowired @Qualifier("weakCipher") void setWeakCipher(IBestPractice weakCipher); @Autowired @Qualifier("forwardSecrecy") void setForwardSecrecy(IBestPractice forwardSecrecy); @Override String getName(); @Override String getVersion(); @Override IPacketAnalyzer getAnalyzer(); @Override AROTraceData analyzeFile(List<BestPracticeType> requests, String traceFile); @Override AROTraceData analyzeFile(List<BestPracticeType> requests, String traceFile, Profile profile, AnalysisFilter filter); @Override AROTraceData analyzeDirectory(List<BestPracticeType> requests, String traceDirectory); @Override AROTraceData analyzeDirectory(List<BestPracticeType> requests, String traceDirectory, Profile profile, AnalysisFilter filter); @Override List<AbstractBestPracticeResult> analyze(PacketAnalyzerResult result, List<BestPracticeType> requests); @Override boolean isFile(String path); @Override boolean isFileExist(String path); @Override boolean isFolderExist(String path); @Override boolean getHtmlReport(String resultFilePath, AROTraceData results); @Override boolean getJSonReport(String resultFilePath, AROTraceData results); @Override String getDirectory(String path); @Override boolean isFileDirExist(String path); }
@Test public void getNameTest() { when(info.getName()).thenReturn("ARO"); String name = aro.getName(); assertNotNull(name); }
AROServiceImpl implements IAROService { @Override public String getVersion() { return info.getVersion(); } @Autowired @Qualifier("jsongenerate") void setJsonreport(IReport jsonreport); @Autowired @Qualifier("htmlgenerate") void setHtmlreport(IReport htmlreport); @Autowired void setPacketAnalyzer(IPacketAnalyzer packetanalyzer); @Autowired void setCacheAnalysis(ICacheAnalysis cacheanalysis); @Autowired @Qualifier("periodicTransfer") void setPeriodicTransfer(IBestPractice periodicTransfer); @Autowired @Qualifier("unnecessaryConnection") void setUnnecessaryConnection(IBestPractice unnecessaryConnection); @Autowired @Qualifier("connectionOpening") void setConnectionOpening(IBestPractice connectionOpening); @Autowired @Qualifier("connectionClosing") void setConnectionClosing(IBestPractice connectionClosing); @Autowired @Qualifier("screenRotation") void setScreenRotation(IBestPractice screenRotation); @Autowired @Qualifier("accessingPeripheral") void setAccessingPeripheral(IBestPractice accessingPeripheral); @Autowired @Qualifier("combineCsJss") void setCombineCsJss(IBestPractice combineCsJss); @Autowired @Qualifier("http10Usage") void setHttp10Usage(IBestPractice http10Usage); @Autowired @Qualifier("cacheControl") void setCacheControl(IBestPractice cacheControl); @Autowired @Qualifier("usingCache") void setUsingCache(IBestPractice usingCache); @Autowired @Qualifier("duplicateContent") void setDuplicateContent(IBestPractice duplicateContent); @Autowired @Qualifier("http4xx5xx") void setHttp4xx5xx(IBestPractice http4xx5xx); @Autowired @Qualifier("simultaneous") void setSimultaneous(IBestPractice simultaneous); @Autowired @Qualifier("multipleSimultaneous") void setMultipleSimultaneous(IBestPractice multipleSimultaneous); @Autowired @Qualifier("http3xx") void setHttp3xx(IBestPractice http3xx); @Autowired @Qualifier("textFileCompression") void setTextFileCompression(IBestPractice textFileCompression); @Autowired @Qualifier("imageSize") void setImageSize(IBestPractice imageSize); @Autowired @Qualifier("imageMetadata") void setImageMdata(IBestPractice imageMetadata); @Autowired @Qualifier("imageCompression") void setImageCompression(IBestPractice imageCompression); @Autowired @Qualifier("imageFormat") void setImageFormat(IBestPractice imageFormat); @Autowired @Qualifier("uiComparator") void setUIComparator(IBestPractice uiComparator); @Autowired @Qualifier("minify") void setMinify(IBestPractice minify); @Autowired @Qualifier("emptyUrl") void setEmptyUrl(IBestPractice emptyUrl); @Autowired @Qualifier("spriteImage") void setSpriteImage(IBestPractice spriteImage); @Autowired @Qualifier("scripts") void setScripts(IBestPractice scripts); @Autowired @Qualifier("async") void setAsync(IBestPractice async); @Autowired @Qualifier("displaynoneincss") void setDisplayNoneInCSS(IBestPractice displaynoneincss); @Autowired @Qualifier("fileorder") void setFileOrder(IBestPractice fileorder); @Autowired @Qualifier("videoStall") void setVideoStallImpl(IBestPractice videoStall); @Autowired @Qualifier("networkComparison") void setVideoNetworkComparisonImpl(IBestPractice networkcomparison); @Autowired @Qualifier("startupDelay") void setVideoStartupDelayImpl(IBestPractice startupdelay); @Autowired @Qualifier("bufferOccupancy") void setVideoBufferOccupancyImpl(IBestPractice bufferoccupancy); @Autowired @Qualifier("tcpConnection") void setTcpconnectionImpl(IBestPractice tcpconnection); @Autowired @Qualifier("chunkPacing") void setChunkpacingImpl(IBestPractice chunkpacing); @Autowired @Qualifier("chunkSize") void setChunksizeImpl(IBestPractice chunksize); @Autowired @Qualifier("videoRedundancy") void setVideoredundancyImpl(IBestPractice videoredundancy); @Autowired @Qualifier("videoConcurrentSession") void setVideoConcurrentSessionImpl(IBestPractice videoConcurrentSession); @Autowired @Qualifier("videoVariableBitrate") void setVideoVariableBitrateImpl(IBestPractice videoVariableBitrate); @Autowired @Qualifier("videoResolutionQuality") void setVideoResolutionQualityImpl(IBestPractice videoResolutionQuality); @Autowired @Qualifier("adaptiveBitrateLadder") void setvideoSegmentQualityImpl(IBestPractice videoSegmentQuality); @Autowired @Qualifier("audioStream") void setSeparateAudioImpl(IBestPractice audioStream); @Autowired @Qualifier("httpsUsage") void setHttpsUsage(IBestPractice httpsUsage); @Autowired @Qualifier("transmissionPrivateData") void setTransmissionPrivateData(IBestPractice transmissionPrivateData); @Autowired @Qualifier("unsecureSSLVersion") void setUnsecureSSLVersion(IBestPractice unsecureSSLVersion); @Autowired @Qualifier("weakCipher") void setWeakCipher(IBestPractice weakCipher); @Autowired @Qualifier("forwardSecrecy") void setForwardSecrecy(IBestPractice forwardSecrecy); @Override String getName(); @Override String getVersion(); @Override IPacketAnalyzer getAnalyzer(); @Override AROTraceData analyzeFile(List<BestPracticeType> requests, String traceFile); @Override AROTraceData analyzeFile(List<BestPracticeType> requests, String traceFile, Profile profile, AnalysisFilter filter); @Override AROTraceData analyzeDirectory(List<BestPracticeType> requests, String traceDirectory); @Override AROTraceData analyzeDirectory(List<BestPracticeType> requests, String traceDirectory, Profile profile, AnalysisFilter filter); @Override List<AbstractBestPracticeResult> analyze(PacketAnalyzerResult result, List<BestPracticeType> requests); @Override boolean isFile(String path); @Override boolean isFileExist(String path); @Override boolean isFolderExist(String path); @Override boolean getHtmlReport(String resultFilePath, AROTraceData results); @Override boolean getJSonReport(String resultFilePath, AROTraceData results); @Override String getDirectory(String path); @Override boolean isFileDirExist(String path); }
@Test public void getVersionTest() { when(info.getVersion()).thenReturn("5.0"); String version = aro.getVersion(); assertNotNull(version); }
AROServiceImpl implements IAROService { @Override public AROTraceData analyzeFile(List<BestPracticeType> requests, String traceFile) throws IOException { return analyzeFile(requests, traceFile, null, null); } @Autowired @Qualifier("jsongenerate") void setJsonreport(IReport jsonreport); @Autowired @Qualifier("htmlgenerate") void setHtmlreport(IReport htmlreport); @Autowired void setPacketAnalyzer(IPacketAnalyzer packetanalyzer); @Autowired void setCacheAnalysis(ICacheAnalysis cacheanalysis); @Autowired @Qualifier("periodicTransfer") void setPeriodicTransfer(IBestPractice periodicTransfer); @Autowired @Qualifier("unnecessaryConnection") void setUnnecessaryConnection(IBestPractice unnecessaryConnection); @Autowired @Qualifier("connectionOpening") void setConnectionOpening(IBestPractice connectionOpening); @Autowired @Qualifier("connectionClosing") void setConnectionClosing(IBestPractice connectionClosing); @Autowired @Qualifier("screenRotation") void setScreenRotation(IBestPractice screenRotation); @Autowired @Qualifier("accessingPeripheral") void setAccessingPeripheral(IBestPractice accessingPeripheral); @Autowired @Qualifier("combineCsJss") void setCombineCsJss(IBestPractice combineCsJss); @Autowired @Qualifier("http10Usage") void setHttp10Usage(IBestPractice http10Usage); @Autowired @Qualifier("cacheControl") void setCacheControl(IBestPractice cacheControl); @Autowired @Qualifier("usingCache") void setUsingCache(IBestPractice usingCache); @Autowired @Qualifier("duplicateContent") void setDuplicateContent(IBestPractice duplicateContent); @Autowired @Qualifier("http4xx5xx") void setHttp4xx5xx(IBestPractice http4xx5xx); @Autowired @Qualifier("simultaneous") void setSimultaneous(IBestPractice simultaneous); @Autowired @Qualifier("multipleSimultaneous") void setMultipleSimultaneous(IBestPractice multipleSimultaneous); @Autowired @Qualifier("http3xx") void setHttp3xx(IBestPractice http3xx); @Autowired @Qualifier("textFileCompression") void setTextFileCompression(IBestPractice textFileCompression); @Autowired @Qualifier("imageSize") void setImageSize(IBestPractice imageSize); @Autowired @Qualifier("imageMetadata") void setImageMdata(IBestPractice imageMetadata); @Autowired @Qualifier("imageCompression") void setImageCompression(IBestPractice imageCompression); @Autowired @Qualifier("imageFormat") void setImageFormat(IBestPractice imageFormat); @Autowired @Qualifier("uiComparator") void setUIComparator(IBestPractice uiComparator); @Autowired @Qualifier("minify") void setMinify(IBestPractice minify); @Autowired @Qualifier("emptyUrl") void setEmptyUrl(IBestPractice emptyUrl); @Autowired @Qualifier("spriteImage") void setSpriteImage(IBestPractice spriteImage); @Autowired @Qualifier("scripts") void setScripts(IBestPractice scripts); @Autowired @Qualifier("async") void setAsync(IBestPractice async); @Autowired @Qualifier("displaynoneincss") void setDisplayNoneInCSS(IBestPractice displaynoneincss); @Autowired @Qualifier("fileorder") void setFileOrder(IBestPractice fileorder); @Autowired @Qualifier("videoStall") void setVideoStallImpl(IBestPractice videoStall); @Autowired @Qualifier("networkComparison") void setVideoNetworkComparisonImpl(IBestPractice networkcomparison); @Autowired @Qualifier("startupDelay") void setVideoStartupDelayImpl(IBestPractice startupdelay); @Autowired @Qualifier("bufferOccupancy") void setVideoBufferOccupancyImpl(IBestPractice bufferoccupancy); @Autowired @Qualifier("tcpConnection") void setTcpconnectionImpl(IBestPractice tcpconnection); @Autowired @Qualifier("chunkPacing") void setChunkpacingImpl(IBestPractice chunkpacing); @Autowired @Qualifier("chunkSize") void setChunksizeImpl(IBestPractice chunksize); @Autowired @Qualifier("videoRedundancy") void setVideoredundancyImpl(IBestPractice videoredundancy); @Autowired @Qualifier("videoConcurrentSession") void setVideoConcurrentSessionImpl(IBestPractice videoConcurrentSession); @Autowired @Qualifier("videoVariableBitrate") void setVideoVariableBitrateImpl(IBestPractice videoVariableBitrate); @Autowired @Qualifier("videoResolutionQuality") void setVideoResolutionQualityImpl(IBestPractice videoResolutionQuality); @Autowired @Qualifier("adaptiveBitrateLadder") void setvideoSegmentQualityImpl(IBestPractice videoSegmentQuality); @Autowired @Qualifier("audioStream") void setSeparateAudioImpl(IBestPractice audioStream); @Autowired @Qualifier("httpsUsage") void setHttpsUsage(IBestPractice httpsUsage); @Autowired @Qualifier("transmissionPrivateData") void setTransmissionPrivateData(IBestPractice transmissionPrivateData); @Autowired @Qualifier("unsecureSSLVersion") void setUnsecureSSLVersion(IBestPractice unsecureSSLVersion); @Autowired @Qualifier("weakCipher") void setWeakCipher(IBestPractice weakCipher); @Autowired @Qualifier("forwardSecrecy") void setForwardSecrecy(IBestPractice forwardSecrecy); @Override String getName(); @Override String getVersion(); @Override IPacketAnalyzer getAnalyzer(); @Override AROTraceData analyzeFile(List<BestPracticeType> requests, String traceFile); @Override AROTraceData analyzeFile(List<BestPracticeType> requests, String traceFile, Profile profile, AnalysisFilter filter); @Override AROTraceData analyzeDirectory(List<BestPracticeType> requests, String traceDirectory); @Override AROTraceData analyzeDirectory(List<BestPracticeType> requests, String traceDirectory, Profile profile, AnalysisFilter filter); @Override List<AbstractBestPracticeResult> analyze(PacketAnalyzerResult result, List<BestPracticeType> requests); @Override boolean isFile(String path); @Override boolean isFileExist(String path); @Override boolean isFolderExist(String path); @Override boolean getHtmlReport(String resultFilePath, AROTraceData results); @Override boolean getJSonReport(String resultFilePath, AROTraceData results); @Override String getDirectory(String path); @Override boolean isFileDirExist(String path); }
@Test public void analyzeFileNullTest() throws IOException { PacketAnalyzerResult analyze = new PacketAnalyzerResult(); TraceFileResult traceresult = new TraceFileResult(); List<PacketInfo> allpackets = new ArrayList<PacketInfo>(); allpackets.add(new PacketInfo(new Packet(0, 0, 0, 0, null))); analyze.setTraceresult(traceresult); List<BestPracticeType> req = new ArrayList<BestPracticeType>(); req.add(BestPracticeType.UNNECESSARY_CONNECTIONS); AROTraceData testResult = aro.analyzeFile(req, "traffic.cap"); assertEquals(null, testResult.getBestPracticeResults()); } @Test public void analyzeFileTest() throws IOException { PacketAnalyzerResult analyze = new PacketAnalyzerResult(); TraceFileResult traceresult = new TraceFileResult(); List<PacketInfo> allpackets = new ArrayList<PacketInfo>(); allpackets.add(new PacketInfo(new Packet(0, 0, 0, 0, null))); traceresult.setAllpackets(allpackets); analyze.setTraceresult(traceresult); PeriodicTransferResult periodicTransferResult = new PeriodicTransferResult(); List<BestPracticeType> req = new ArrayList<BestPracticeType>(); req.add(BestPracticeType.UNNECESSARY_CONNECTIONS); req.add(BestPracticeType.CONNECTION_CLOSING); req.add(BestPracticeType.CONNECTION_OPENING); req.add(BestPracticeType.PERIODIC_TRANSFER); req.add(BestPracticeType.SCREEN_ROTATION); req.add(BestPracticeType.ACCESSING_PERIPHERALS); req.add(BestPracticeType.COMBINE_CS_JSS); req.add(BestPracticeType.HTTP_1_0_USAGE); req.add(BestPracticeType.CACHE_CONTROL); req.add(BestPracticeType.USING_CACHE); req.add(BestPracticeType.DUPLICATE_CONTENT); req.add(BestPracticeType.HTTP_4XX_5XX); req.add(BestPracticeType.HTTP_3XX_CODE); req.add(BestPracticeType.FILE_COMPRESSION); req.add(BestPracticeType.IMAGE_SIZE); req.add(BestPracticeType.MINIFICATION); req.add(BestPracticeType.EMPTY_URL); req.add(BestPracticeType.SPRITEIMAGE); req.add(BestPracticeType.SCRIPTS_URL); req.add(BestPracticeType.ASYNC_CHECK); req.add(BestPracticeType.DISPLAY_NONE_IN_CSS); req.add(BestPracticeType.FILE_ORDER); req.add(BestPracticeType.MULTI_SIMULCONN); req.add(BestPracticeType.VIDEO_STALL); req.add(BestPracticeType.STARTUP_DELAY); req.add(BestPracticeType.BUFFER_OCCUPANCY); req.add(BestPracticeType.NETWORK_COMPARISON); req.add(BestPracticeType.TCP_CONNECTION); req.add(BestPracticeType.CHUNK_SIZE); req.add(BestPracticeType.CHUNK_PACING); req.add(BestPracticeType.VIDEO_REDUNDANCY); req.add(BestPracticeType.VIDEO_CONCURRENT_SESSION); req.add(BestPracticeType.VIDEO_VARIABLE_BITRATE); req.add(BestPracticeType.HTTPS_USAGE); req.add(BestPracticeType.TRANSMISSION_PRIVATE_DATA); req.add(BestPracticeType.DISPLAY_NONE_IN_CSS); packetanalyzer = Mockito.mock(IPacketAnalyzer.class); aro.setPacketAnalyzer(packetanalyzer); when(packetanalyzer.analyzeTraceFile(any(String.class), any(Profile.class), any(AnalysisFilter.class))) .thenReturn(analyze); when(worker.runTest(any(PacketAnalyzerResult.class))).thenReturn(periodicTransferResult); List<BestPracticeType> list = SettingsUtil.retrieveBestPractices(); SettingsUtil.saveBestPractices(req); try { AROTraceData testResult = aro.analyzeFile(req, "traffic.cap"); assertEquals(TOTAL_BPTESTS, testResult.getBestPracticeResults().size()); } finally { SettingsUtil.saveBestPractices(list); } } @Test public void analyzeFileTest_resultIsNull() throws IOException { when(packetanalyzer.analyzeTraceFile(any(String.class), any(Profile.class), any(AnalysisFilter.class))) .thenReturn(null); List<BestPracticeType> req = new ArrayList<BestPracticeType>(); AROTraceData testResult = aro.analyzeFile(req, "traffic.cap"); assertEquals(104, testResult.getError().getCode()); assertFalse(testResult.isSuccess()); }
AROServiceImpl implements IAROService { @Override public AROTraceData analyzeDirectory(List<BestPracticeType> requests, String traceDirectory) throws IOException { return analyzeDirectory(requests, traceDirectory, null, null); } @Autowired @Qualifier("jsongenerate") void setJsonreport(IReport jsonreport); @Autowired @Qualifier("htmlgenerate") void setHtmlreport(IReport htmlreport); @Autowired void setPacketAnalyzer(IPacketAnalyzer packetanalyzer); @Autowired void setCacheAnalysis(ICacheAnalysis cacheanalysis); @Autowired @Qualifier("periodicTransfer") void setPeriodicTransfer(IBestPractice periodicTransfer); @Autowired @Qualifier("unnecessaryConnection") void setUnnecessaryConnection(IBestPractice unnecessaryConnection); @Autowired @Qualifier("connectionOpening") void setConnectionOpening(IBestPractice connectionOpening); @Autowired @Qualifier("connectionClosing") void setConnectionClosing(IBestPractice connectionClosing); @Autowired @Qualifier("screenRotation") void setScreenRotation(IBestPractice screenRotation); @Autowired @Qualifier("accessingPeripheral") void setAccessingPeripheral(IBestPractice accessingPeripheral); @Autowired @Qualifier("combineCsJss") void setCombineCsJss(IBestPractice combineCsJss); @Autowired @Qualifier("http10Usage") void setHttp10Usage(IBestPractice http10Usage); @Autowired @Qualifier("cacheControl") void setCacheControl(IBestPractice cacheControl); @Autowired @Qualifier("usingCache") void setUsingCache(IBestPractice usingCache); @Autowired @Qualifier("duplicateContent") void setDuplicateContent(IBestPractice duplicateContent); @Autowired @Qualifier("http4xx5xx") void setHttp4xx5xx(IBestPractice http4xx5xx); @Autowired @Qualifier("simultaneous") void setSimultaneous(IBestPractice simultaneous); @Autowired @Qualifier("multipleSimultaneous") void setMultipleSimultaneous(IBestPractice multipleSimultaneous); @Autowired @Qualifier("http3xx") void setHttp3xx(IBestPractice http3xx); @Autowired @Qualifier("textFileCompression") void setTextFileCompression(IBestPractice textFileCompression); @Autowired @Qualifier("imageSize") void setImageSize(IBestPractice imageSize); @Autowired @Qualifier("imageMetadata") void setImageMdata(IBestPractice imageMetadata); @Autowired @Qualifier("imageCompression") void setImageCompression(IBestPractice imageCompression); @Autowired @Qualifier("imageFormat") void setImageFormat(IBestPractice imageFormat); @Autowired @Qualifier("uiComparator") void setUIComparator(IBestPractice uiComparator); @Autowired @Qualifier("minify") void setMinify(IBestPractice minify); @Autowired @Qualifier("emptyUrl") void setEmptyUrl(IBestPractice emptyUrl); @Autowired @Qualifier("spriteImage") void setSpriteImage(IBestPractice spriteImage); @Autowired @Qualifier("scripts") void setScripts(IBestPractice scripts); @Autowired @Qualifier("async") void setAsync(IBestPractice async); @Autowired @Qualifier("displaynoneincss") void setDisplayNoneInCSS(IBestPractice displaynoneincss); @Autowired @Qualifier("fileorder") void setFileOrder(IBestPractice fileorder); @Autowired @Qualifier("videoStall") void setVideoStallImpl(IBestPractice videoStall); @Autowired @Qualifier("networkComparison") void setVideoNetworkComparisonImpl(IBestPractice networkcomparison); @Autowired @Qualifier("startupDelay") void setVideoStartupDelayImpl(IBestPractice startupdelay); @Autowired @Qualifier("bufferOccupancy") void setVideoBufferOccupancyImpl(IBestPractice bufferoccupancy); @Autowired @Qualifier("tcpConnection") void setTcpconnectionImpl(IBestPractice tcpconnection); @Autowired @Qualifier("chunkPacing") void setChunkpacingImpl(IBestPractice chunkpacing); @Autowired @Qualifier("chunkSize") void setChunksizeImpl(IBestPractice chunksize); @Autowired @Qualifier("videoRedundancy") void setVideoredundancyImpl(IBestPractice videoredundancy); @Autowired @Qualifier("videoConcurrentSession") void setVideoConcurrentSessionImpl(IBestPractice videoConcurrentSession); @Autowired @Qualifier("videoVariableBitrate") void setVideoVariableBitrateImpl(IBestPractice videoVariableBitrate); @Autowired @Qualifier("videoResolutionQuality") void setVideoResolutionQualityImpl(IBestPractice videoResolutionQuality); @Autowired @Qualifier("adaptiveBitrateLadder") void setvideoSegmentQualityImpl(IBestPractice videoSegmentQuality); @Autowired @Qualifier("audioStream") void setSeparateAudioImpl(IBestPractice audioStream); @Autowired @Qualifier("httpsUsage") void setHttpsUsage(IBestPractice httpsUsage); @Autowired @Qualifier("transmissionPrivateData") void setTransmissionPrivateData(IBestPractice transmissionPrivateData); @Autowired @Qualifier("unsecureSSLVersion") void setUnsecureSSLVersion(IBestPractice unsecureSSLVersion); @Autowired @Qualifier("weakCipher") void setWeakCipher(IBestPractice weakCipher); @Autowired @Qualifier("forwardSecrecy") void setForwardSecrecy(IBestPractice forwardSecrecy); @Override String getName(); @Override String getVersion(); @Override IPacketAnalyzer getAnalyzer(); @Override AROTraceData analyzeFile(List<BestPracticeType> requests, String traceFile); @Override AROTraceData analyzeFile(List<BestPracticeType> requests, String traceFile, Profile profile, AnalysisFilter filter); @Override AROTraceData analyzeDirectory(List<BestPracticeType> requests, String traceDirectory); @Override AROTraceData analyzeDirectory(List<BestPracticeType> requests, String traceDirectory, Profile profile, AnalysisFilter filter); @Override List<AbstractBestPracticeResult> analyze(PacketAnalyzerResult result, List<BestPracticeType> requests); @Override boolean isFile(String path); @Override boolean isFileExist(String path); @Override boolean isFolderExist(String path); @Override boolean getHtmlReport(String resultFilePath, AROTraceData results); @Override boolean getJSonReport(String resultFilePath, AROTraceData results); @Override String getDirectory(String path); @Override boolean isFileDirExist(String path); }
@Test public void analyzeDirectoryTest() throws IOException { TraceDirectoryResult traceresult = new TraceDirectoryResult(); List<PacketInfo> allpackets = new ArrayList<PacketInfo>(); allpackets.add(new PacketInfo(new Packet(0, 0, 0, 0, null))); traceresult.setAllpackets(allpackets); PacketAnalyzerResult analyze = new PacketAnalyzerResult(); analyze.setTraceresult(traceresult); CacheAnalysis cacheAnalysis = new CacheAnalysis(); PeriodicTransferResult periodicTransferResult = new PeriodicTransferResult(); List<BestPracticeType> req = new ArrayList<BestPracticeType>(); req.add(BestPracticeType.UNNECESSARY_CONNECTIONS); req.add(BestPracticeType.CONNECTION_CLOSING); req.add(BestPracticeType.CONNECTION_OPENING); req.add(BestPracticeType.PERIODIC_TRANSFER); req.add(BestPracticeType.SCREEN_ROTATION); req.add(BestPracticeType.ACCESSING_PERIPHERALS); req.add(BestPracticeType.COMBINE_CS_JSS); req.add(BestPracticeType.HTTP_1_0_USAGE); req.add(BestPracticeType.CACHE_CONTROL); req.add(BestPracticeType.USING_CACHE); req.add(BestPracticeType.DUPLICATE_CONTENT); req.add(BestPracticeType.HTTP_4XX_5XX); req.add(BestPracticeType.HTTP_3XX_CODE); req.add(BestPracticeType.FILE_COMPRESSION); req.add(BestPracticeType.IMAGE_SIZE); req.add(BestPracticeType.MINIFICATION); req.add(BestPracticeType.EMPTY_URL); req.add(BestPracticeType.SPRITEIMAGE); req.add(BestPracticeType.SCRIPTS_URL); req.add(BestPracticeType.ASYNC_CHECK); req.add(BestPracticeType.DISPLAY_NONE_IN_CSS); req.add(BestPracticeType.FILE_ORDER); req.add(BestPracticeType.VIDEO_STALL); req.add(BestPracticeType.STARTUP_DELAY); req.add(BestPracticeType.BUFFER_OCCUPANCY); req.add(BestPracticeType.NETWORK_COMPARISON); req.add(BestPracticeType.TCP_CONNECTION); req.add(BestPracticeType.CHUNK_SIZE); req.add(BestPracticeType.CHUNK_PACING); req.add(BestPracticeType.VIDEO_REDUNDANCY); req.add(BestPracticeType.VIDEO_VARIABLE_BITRATE); req.add(BestPracticeType.HTTPS_USAGE); req.add(BestPracticeType.TRANSMISSION_PRIVATE_DATA); req.add(BestPracticeType.DISPLAY_NONE_IN_CSS); req.add(BestPracticeType.VIDEO_CONCURRENT_SESSION); req.add(BestPracticeType.AUDIO_STREAM); req.add(BestPracticeType.MULTI_SIMULCONN); List<BestPracticeType> list = SettingsUtil.retrieveBestPractices(); SettingsUtil.saveBestPractices(req); when(packetanalyzer.analyzeTraceDirectory(any(String.class), any(Profile.class), any(AnalysisFilter.class))) .thenReturn(analyze); when(worker.runTest(any(PacketAnalyzerResult.class))).thenReturn(periodicTransferResult); when(cacheAnalyzer.analyze(anyListOf(Session.class))).thenReturn(cacheAnalysis); try { AROTraceData testResult = aro.analyzeDirectory(req, Util.getCurrentRunningDir()); assertEquals(null, testResult.getBestPracticeResults()); } finally { SettingsUtil.saveBestPractices(list); } } @Test public void analyzeDirectoryTest_resultIsNull() throws IOException { List<BestPracticeType> req = new ArrayList<BestPracticeType>(); when(packetanalyzer.analyzeTraceDirectory(any(String.class), any(Profile.class), any(AnalysisFilter.class))) .thenReturn(null); AROTraceData testResult = aro.analyzeDirectory(req, Util.getCurrentRunningDir()); assertEquals(108, testResult.getError().getCode()); assertFalse(testResult.isSuccess()); }
PacketAnalyzerImpl implements IPacketAnalyzer { @Override public Statistic getStatistic(List<PacketInfo> packetlist) { Statistic stat = new Statistic(); Set<String> appNames = new HashSet<String>(); List<PacketInfo> packets = packetlist; if (!packets.isEmpty()) { int totalHTTPSBytes = 0; int totalTCPBytes = 0; int totalBytes = 0; double avgKbps = 0; double packetsDuration = 0; List<IPPacketSummary> ipPacketSummary = new ArrayList<IPPacketSummary>(); List<ApplicationPacketSummary> applicationPacketSummary = new ArrayList<ApplicationPacketSummary>(); Map<Integer, Integer> packetSizeToCountMap = new HashMap<Integer, Integer>(); PacketInfo lastPacket = packets.get(packets.size() - 1); Map<String, PacketCounter> appPackets = new HashMap<String, PacketCounter>(); Map<InetAddress, PacketCounter> ipPackets = new HashMap<InetAddress, PacketCounter>(); for (PacketInfo packet : packets) { totalBytes += packet.getLen(); if (packet.getPacket() instanceof TCPPacket) { TCPPacket tcp = (TCPPacket) packet.getPacket(); if ((tcp.isSsl()) || (tcp.getDestinationPort() == 443) || (tcp.getSourcePort() == 443)) { totalHTTPSBytes += packet.getLen(); } totalTCPBytes += packet.getLen(); } String appName = packet.getAppName(); appNames.add(appName); PacketCounter pCounter = appPackets.get(appName); if (pCounter == null) { pCounter = new PacketCounter(); appPackets.put(appName, pCounter); } pCounter.add(packet); if (packet.getPacket() instanceof IPPacket) { Integer packetSize = packet.getPayloadLen(); Integer iValue = packetSizeToCountMap.get(packetSize); if (iValue == null) { iValue = 1; } else { iValue++; } packetSizeToCountMap.put(packetSize, iValue); InetAddress ipAddress = packet.getRemoteIPAddress(); pCounter = ipPackets.get(ipAddress); if (pCounter == null) { pCounter = new PacketCounter(); ipPackets.put(ipAddress, pCounter); } pCounter.add(packet); } } for (Map.Entry<InetAddress, PacketCounter> ipPacketMap : ipPackets.entrySet()) { ipPacketSummary.add(new IPPacketSummary(ipPacketMap.getKey(), ipPacketMap.getValue().getPacketCount(), ipPacketMap.getValue().getTotalBytes())); } for (Map.Entry<String, PacketCounter> appPacketMap : appPackets.entrySet()) { applicationPacketSummary .add(new ApplicationPacketSummary(appPacketMap.getKey(), appPacketMap.getValue().getPacketCount(), appPacketMap.getValue().getTotalBytes())); } packetsDuration = lastPacket.getTimeStamp() - packets.get(0).getTimeStamp(); avgKbps = packetsDuration != 0 ? totalTCPBytes * 8.0 / 1000.0 / packetsDuration : 0.0; stat.setApplicationPacketSummary(applicationPacketSummary); stat.setAppName(appNames); stat.setAverageKbps(avgKbps); stat.setAverageTCPKbps(avgKbps); stat.setIpPacketSummary(ipPacketSummary); stat.setPacketDuration(packetsDuration); stat.setTCPPacketDuration(packetsDuration); stat.setTotalByte(totalBytes); stat.setTotalTCPBytes(totalTCPBytes); stat.setTotalHTTPSByte(totalHTTPSBytes); stat.setTotalPackets(packets.size()); stat.setTotalTCPPackets(packets.size()); stat.setPacketSizeToCountMap(packetSizeToCountMap); } stat.setAppName(appNames); return stat; } @Autowired void setTraceReader(ITraceDataReader traceReader); @Autowired void setRrcStateMachineFactory(IRrcStateMachineFactory rrcStateMachineFactory); @Autowired void setProfileFactory(IProfileFactory profileFactory); @Autowired void setEnergyModelFactory(IEnergyModelFactory energyModelFactory); @Autowired void setBurstCollectionAnalayzer(IBurstCollectionAnalysis burstCollectionAnalysis); @Autowired void setPktTimeRangeUtil(IPktAnazlyzerTimeRangeUtil pktUtil); @Autowired void setVideoStreamingAnalysis(IVideoTrafficCollector videoTrafficCollector); @Override PacketAnalyzerResult analyzeTraceFile(String traceFilePath, Profile profile, AnalysisFilter filter); @Override PacketAnalyzerResult analyzeTraceDirectory(String traceDirectory, Profile profile, AnalysisFilter filter); List<PacketInfo> filterPackets(AnalysisFilter filter, List<PacketInfo> packetsInfo); @Override Statistic getStatistic(List<PacketInfo> packetlist); void generateRequestMap(List<Session> sessionList); Map<Double, HttpRequestResponseInfo> getReqMap(); }
@Test public void test_getStatisticResult() throws UnknownHostException{ InetAddress iAdr = Mockito.mock(InetAddress.class); InetAddress iAdr1 = Mockito.mock(InetAddress.class); Mockito.when(iAdr.getAddress()).thenReturn(new byte[]{89,10,1,1}); Mockito.when(iAdr1.getAddress()).thenReturn(new byte[]{72,12,13,1}); Set<InetAddress> inetSet = new HashSet<InetAddress>(); inetSet.add(iAdr); inetSet.add(iAdr1); DomainNameSystem dns = Mockito.mock(DomainNameSystem.class); Mockito.when(dns.getIpAddresses()).thenReturn(inetSet); Mockito.when(dns.getDomainName()).thenReturn("www.att.com"); UDPPacket udpPacket = Mockito.mock(UDPPacket.class); Mockito.when(udpPacket.isDNSPacket()).thenReturn(true); Mockito.when(udpPacket.getDns()).thenReturn(dns); Mockito.when(udpPacket.getSourcePort()).thenReturn(83); Mockito.when(udpPacket.getDestinationPort()).thenReturn(84); Mockito.when(udpPacket.getDestinationIPAddress()).thenReturn(iAdr); PacketInfo packetInfo1 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo1.getPacket()).thenReturn(udpPacket); Mockito.when(packetInfo1.getDir()).thenReturn(PacketDirection.UPLINK); Mockito.when(packetInfo1.getPayloadLen()).thenReturn(0); Mockito.when(packetInfo1.getLen()).thenReturn(10); Mockito.when(packetInfo1.getAppName()).thenReturn("Test1"); Mockito.when(packetInfo1.getTcpFlagString()).thenReturn("TestString"); Mockito.when(packetInfo1.getTimeStamp()).thenReturn(500d); InetAddress iAdr2 = Mockito.mock(InetAddress.class); Mockito.when(iAdr2.getAddress()).thenReturn(new byte[]{95,10,1,1}); TCPPacket tcpPacket = Mockito.mock(TCPPacket.class); Mockito.when(tcpPacket.getSourcePort()).thenReturn(81); Mockito.when(tcpPacket.getDestinationPort()).thenReturn(82); Mockito.when(tcpPacket.getDestinationIPAddress()).thenReturn(iAdr2); Mockito.when(tcpPacket.isSYN()).thenReturn(true); Mockito.when(tcpPacket.isFIN()).thenReturn(true); Mockito.when(tcpPacket.isRST()).thenReturn(true); Mockito.when(tcpPacket.getTimeStamp()).thenReturn(1000d); PacketInfo packetInfo2 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo2.getPacket()).thenReturn(tcpPacket); Mockito.when(packetInfo2.getDir()).thenReturn(PacketDirection.UPLINK); Mockito.when(packetInfo2.getTcpInfo()).thenReturn(TcpInfo.TCP_ESTABLISH); Mockito.when(packetInfo2.getPayloadLen()).thenReturn(0); Mockito.when(packetInfo2.getLen()).thenReturn(15); Mockito.when(packetInfo2.getAppName()).thenReturn("Test2"); Mockito.when(packetInfo2.getTcpFlagString()).thenReturn("Test2String"); Mockito.when(packetInfo2.getTimeStamp()).thenReturn(10d); TCPPacket tcpPacket2 = Mockito.mock(TCPPacket.class); Mockito.when(tcpPacket2.getSourcePort()).thenReturn(95); Mockito.when(tcpPacket2.getDestinationPort()).thenReturn(99); Mockito.when(tcpPacket2.getDestinationIPAddress()).thenReturn(iAdr2); Mockito.when(tcpPacket2.isSYN()).thenReturn(true); Mockito.when(tcpPacket2.isFIN()).thenReturn(true); Mockito.when(tcpPacket2.isRST()).thenReturn(false); Mockito.when(tcpPacket2.getTimeStamp()).thenReturn(50d); Inet4Address address = (Inet4Address) InetAddress.getByName("192.168.1.4"); PacketInfo packetInfo3 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo3.getPacket()).thenReturn(tcpPacket2); Mockito.when(packetInfo3.getDir()).thenReturn(PacketDirection.UPLINK); Mockito.when(packetInfo3.getTcpInfo()).thenReturn(TcpInfo.TCP_ESTABLISH); Mockito.when(packetInfo3.getPayloadLen()).thenReturn(0); Mockito.when(packetInfo3.getLen()).thenReturn(15); Mockito.when(packetInfo3.getAppName()).thenReturn("Test2"); Mockito.when(packetInfo3.getTcpFlagString()).thenReturn("Test2String"); Mockito.when(packetInfo3.getTimeStamp()).thenReturn(10d); Mockito.when(packetInfo3.getRemoteIPAddress()).thenReturn(address); List<PacketInfo> packetsList = new ArrayList<PacketInfo>(); packetsList.add(packetInfo1); packetsList.add(packetInfo2); packetsList.add(packetInfo3); Statistic testResult = iPacketAnalyzer.getStatistic(packetsList); assertEquals(3,testResult.getTotalPackets()); }
EnergyModelFactoryImpl implements IEnergyModelFactory { @Override public EnergyModel create(Profile profile, double totalRrcEnergy, List<GpsInfo> gpsinfos, List<CameraInfo> camerainfos, List<BluetoothInfo> bluetoothinfos, List<ScreenStateInfo> screenstateinfos) { double gpsActiveEnergy = 0, gpsStandbyEnergy = 0, totalGpsEnergy = 0, totalCameraEnergy = 0; double bluetoothActiveEnergy = 0, bluetoothStandbyEnergy = 0, totalBluetoothEnergy =0; double totalScreenEnergy = 0; EnergyModel model = new EnergyModel(); model.setTotalRrcEnergy(totalRrcEnergy); Iterator<GpsInfo> gpsIter = gpsinfos.iterator(); if (gpsIter.hasNext()) { while (gpsIter.hasNext()) { GpsInfo gps = gpsIter.next(); GpsState gpsState = gps.getGpsState(); switch (gpsState) { case GPS_ACTIVE: gpsActiveEnergy += profile.getPowerGpsActive() * (gps.getEndTimeStamp() - gps.getBeginTimeStamp()); break; case GPS_STANDBY: gpsStandbyEnergy += profile.getPowerGpsStandby() * (gps.getEndTimeStamp() - gps.getBeginTimeStamp()); break; default: break; } } } totalGpsEnergy = gpsActiveEnergy + gpsStandbyEnergy; Iterator<CameraInfo> cameraIter = camerainfos.iterator(); if (cameraIter.hasNext()) { while (cameraIter.hasNext()) { CameraInfo camera = cameraIter.next(); CameraInfo.CameraState cameraState = camera.getCameraState(); if (cameraState == CameraInfo.CameraState.CAMERA_ON) { totalCameraEnergy += profile.getPowerCameraOn() * (camera.getEndTimeStamp() - camera.getBeginTimeStamp()); } } } Iterator<BluetoothInfo> bluetoothIter = bluetoothinfos.iterator(); if (bluetoothIter.hasNext()) { while (bluetoothIter.hasNext()) { BluetoothInfo btInfo = bluetoothIter.next(); if(btInfo == null || btInfo.getBluetoothState() == null) { continue; } switch (btInfo.getBluetoothState()) { case BLUETOOTH_CONNECTED: bluetoothActiveEnergy += profile.getPowerBluetoothActive() * (btInfo.getEndTimeStamp() - btInfo.getBeginTimeStamp()); break; case BLUETOOTH_DISCONNECTED: bluetoothStandbyEnergy += profile.getPowerBluetoothStandby() * (btInfo.getEndTimeStamp() - btInfo.getBeginTimeStamp()); break; default: break; } } } totalBluetoothEnergy = bluetoothActiveEnergy + bluetoothStandbyEnergy; Iterator<ScreenStateInfo> screenIter = screenstateinfos.iterator(); if (screenIter.hasNext()) { while (screenIter.hasNext()) { ScreenStateInfo screenInfo = screenIter.next(); if (screenInfo.getScreenState() == ScreenStateInfo.ScreenState.SCREEN_ON) { totalScreenEnergy += profile.getPowerScreenOn() * (screenInfo.getEndTimeStamp() - screenInfo.getBeginTimeStamp()); } } } model.setBluetoothActiveEnergy(bluetoothActiveEnergy); model.setBluetoothStandbyEnergy(bluetoothStandbyEnergy); model.setGpsActiveEnergy(gpsActiveEnergy); model.setGpsStandbyEnergy(gpsStandbyEnergy); model.setTotalBluetoothEnergy(totalBluetoothEnergy); model.setTotalCameraEnergy(totalCameraEnergy); model.setTotalGpsEnergy(totalGpsEnergy); model.setTotalRrcEnergy(totalRrcEnergy); model.setTotalScreenEnergy(totalScreenEnergy); return model; } @Override EnergyModel create(Profile profile, double totalRrcEnergy, List<GpsInfo> gpsinfos, List<CameraInfo> camerainfos, List<BluetoothInfo> bluetoothinfos, List<ScreenStateInfo> screenstateinfos); }
@Test public void create_Test(){ Date date = new Date(); Profile profile = Mockito.mock(Profile.class); Mockito.when(profile.getPowerGpsActive()).thenReturn(1.0); GpsInfo gpsInfo01 = Mockito.mock(GpsInfo.class); Mockito.when(gpsInfo01.getBeginTimeStamp()).thenReturn(date.getTime()+0.0); Mockito.when(gpsInfo01.getEndTimeStamp()).thenReturn(date.getTime()+1000.0); Mockito.when(gpsInfo01.getGpsState()).thenReturn(GpsState.GPS_ACTIVE); GpsInfo gpsInfo02 = Mockito.mock(GpsInfo.class); Mockito.when(profile.getPowerGpsStandby()).thenReturn(0.5); Mockito.when(gpsInfo02.getBeginTimeStamp()).thenReturn(date.getTime()+0.0); Mockito.when(gpsInfo02.getEndTimeStamp()).thenReturn(date.getTime()+1000.0); Mockito.when(gpsInfo02.getGpsState()).thenReturn(GpsState.GPS_STANDBY); List<GpsInfo> gpsList = new ArrayList<GpsInfo>(); gpsList.add(gpsInfo01); gpsList.add(gpsInfo02); CameraInfo cameraInfo01 = Mockito.mock(CameraInfo.class); Mockito.when(cameraInfo01.getBeginTimeStamp()).thenReturn(date.getTime()+0.0); Mockito.when(cameraInfo01.getEndTimeStamp()).thenReturn(date.getTime()+1000.0); Mockito.when(cameraInfo01.getCameraState()).thenReturn(CameraState.CAMERA_ON); Mockito.when(profile.getPowerCameraOn()).thenReturn(0.3); List<CameraInfo> cameraList = new ArrayList<CameraInfo>(); cameraList.add(cameraInfo01); BluetoothInfo bluetoothInfo01 = Mockito.mock(BluetoothInfo.class); Mockito.when(bluetoothInfo01.getBeginTimeStamp()).thenReturn(date.getTime()+0.0); Mockito.when(bluetoothInfo01.getEndTimeStamp()).thenReturn(date.getTime()+1000.0); Mockito.when(bluetoothInfo01.getBluetoothState()).thenReturn(BluetoothState.BLUETOOTH_CONNECTED); BluetoothInfo bluetoothInfo02 = Mockito.mock(BluetoothInfo.class); Mockito.when(bluetoothInfo02.getBeginTimeStamp()).thenReturn(date.getTime()+0.0); Mockito.when(bluetoothInfo02.getEndTimeStamp()).thenReturn(date.getTime()+1000.0); Mockito.when(bluetoothInfo02.getBluetoothState()).thenReturn(BluetoothState.BLUETOOTH_DISCONNECTED); List<BluetoothInfo> bluetoothList = new ArrayList<BluetoothInfo>(); bluetoothList.add(bluetoothInfo01); bluetoothList.add(bluetoothInfo02); Mockito.when(profile.getPowerBluetoothActive()).thenReturn(1.0); Mockito.when(profile.getPowerBluetoothStandby()).thenReturn(0.5); ScreenStateInfo screenStateInfo01 = Mockito.mock(ScreenStateInfo.class); Mockito.when(screenStateInfo01.getBeginTimeStamp()).thenReturn(date.getTime()+0.0); Mockito.when(screenStateInfo01.getEndTimeStamp()).thenReturn(date.getTime()+1000.0); Mockito.when(screenStateInfo01.getScreenState()).thenReturn(ScreenState.SCREEN_ON); List<ScreenStateInfo> screenStateList = new ArrayList<ScreenStateInfo>(); screenStateList.add(screenStateInfo01); Mockito.when(profile.getPowerScreenOn()).thenReturn(0.3); EnergyModel model = eMdlFctr.create(profile, 0.0, gpsList, cameraList, bluetoothList, screenStateList); assertEquals(1000.0,model.getGpsActiveEnergy(),0.0); assertEquals(500.0,model.getGpsStandbyEnergy(),0.0); assertEquals(1500.0,model.getTotalGpsEnergy(),0.0); assertEquals(300.0,model.getTotalCameraEnergy(),0.0); assertEquals(1000.0,model.getBluetoothActiveEnergy(),0.0); assertEquals(500.0,model.getBluetoothStandbyEnergy(),0.0); assertEquals(1500.0,model.getTotalBluetoothEnergy(),0.0); assertEquals(300.0,model.getTotalScreenEnergy(),0.0); }
PktAnazlyzerTimeRangeImpl implements IPktAnazlyzerTimeRangeUtil { @Override public AbstractTraceResult getTimeRangeResult(TraceDirectoryResult result, TimeRange timeRange) { TraceDirectoryResult resultForTimeRange = result; getUserEventsForTheTimeRange(resultForTimeRange, timeRange.getBeginTime(), timeRange.getEndTime()); getScreenInfosForTheTimeRange(resultForTimeRange, timeRange.getBeginTime(), timeRange.getEndTime()); getBluetoothInfosForTheTimeRange(resultForTimeRange, timeRange.getBeginTime(), timeRange.getEndTime()); getGpsInfosForTheTimeRange(resultForTimeRange, timeRange.getBeginTime(), timeRange.getEndTime()); getRadioInfosForTheTimeRange(resultForTimeRange, timeRange.getBeginTime(), timeRange.getEndTime()); getBatteryInfosForTheTimeRange(resultForTimeRange, timeRange.getBeginTime(), timeRange.getEndTime()); getWifiInfosForTheTimeRange(resultForTimeRange, timeRange.getBeginTime(), timeRange.getEndTime()); getNetworkInfosForTheTimeRange(resultForTimeRange, timeRange.getBeginTime(), timeRange.getEndTime()); getCameraInfosForTheTimeRange(resultForTimeRange, timeRange.getBeginTime(), timeRange.getEndTime()); return resultForTimeRange; } PktAnazlyzerTimeRangeImpl(); @Override AbstractTraceResult getTimeRangeResult(TraceDirectoryResult result, TimeRange timeRange); }
@Test public void getTimeRangeResultTest(){ TraceDirectoryResult result = new TraceDirectoryResult(); List<UserEvent> userEvents = new ArrayList<UserEvent>(); userEvents.add(new UserEvent(UserEventType.KEY_HOME, 4.0, 3.0)); result.setUserEvents(userEvents); List<GpsInfo> gpsInfos = new ArrayList<GpsInfo>(); gpsInfos.add(new GpsInfo(0.0, 0.9, GpsState.GPS_ACTIVE)); gpsInfos.add(new GpsInfo(1.0,4.0, GpsState.GPS_ACTIVE)); gpsInfos.add(new GpsInfo(1.4,12.0, GpsState.GPS_ACTIVE)); gpsInfos.add(new GpsInfo(12.4,14.0, GpsState.GPS_ACTIVE)); result.setGpsInfos(gpsInfos); List<BluetoothInfo> bluetoothInfos = new ArrayList<BluetoothInfo>(); bluetoothInfos.add(new BluetoothInfo(0.0, 3.0, BluetoothState.BLUETOOTH_CONNECTED)); bluetoothInfos.add(new BluetoothInfo(4.0, 10.0,BluetoothState.BLUETOOTH_CONNECTED)); bluetoothInfos.add(new BluetoothInfo(1.0, 13.0,BluetoothState.BLUETOOTH_DISCONNECTED)); bluetoothInfos.add(new BluetoothInfo(11.0, 16.0,BluetoothState.BLUETOOTH_CONNECTED)); result.setBluetoothInfos(bluetoothInfos); List<CameraInfo> cameraInfos = new ArrayList<CameraInfo>(); cameraInfos.add(new CameraInfo(0.0, 1.0, CameraState.CAMERA_ON)); cameraInfos.add(new CameraInfo(3.0, 7.0, CameraState.CAMERA_ON)); cameraInfos.add(new CameraInfo(8.0,14.0, CameraState.CAMERA_ON)); cameraInfos.add(new CameraInfo(1.0,14.0, CameraState.CAMERA_ON)); cameraInfos.add(new CameraInfo(12.0,15.0,CameraState.CAMERA_ON)); result.setCameraInfos(cameraInfos); List<ScreenStateInfo> screenStateInfos = new ArrayList<ScreenStateInfo>(); ScreenStateInfo screenInfo01 = new ScreenStateInfo(0.0, 1.0, ScreenState.SCREEN_ON, " ", 5); ScreenStateInfo screenInfo02 = new ScreenStateInfo(1.0,12.0,ScreenState.SCREEN_ON,"",3) ; ScreenStateInfo screenInfo03 = new ScreenStateInfo(5.0,9.0,ScreenState.SCREEN_ON,"",2) ; ScreenStateInfo screenInfo04 = new ScreenStateInfo(12.0,15.0,ScreenState.SCREEN_ON,"",4) ; screenStateInfos.add(screenInfo01); screenStateInfos.add(screenInfo02); screenStateInfos.add(screenInfo03); screenStateInfos.add(screenInfo04); result.setScreenStateInfos(screenStateInfos); List<RadioInfo> radioInfos = new ArrayList<RadioInfo>(); radioInfos.add(new RadioInfo(0.0, 3.0)); radioInfos.add(new RadioInfo(4.0, 8.0)); result.setRadioInfos(radioInfos); List<BatteryInfo> batteryInfos = new ArrayList<BatteryInfo>(); batteryInfos.add(new BatteryInfo(3.0, true, 2, 3)); result.setBatteryInfos(batteryInfos); List<WifiInfo> wifiInfos = new ArrayList<WifiInfo>(); wifiInfos.add(new WifiInfo(1.0, 2.0, WifiState.WIFI_CONNECTED, "", "", "")); wifiInfos.add(new WifiInfo(1.0,5.0,WifiState.WIFI_CONNECTING, "","","")); wifiInfos.add(new WifiInfo(1.4,13.0,WifiState.WIFI_CONNECTING, "","","")); wifiInfos.add(new WifiInfo(9.0,13.0,WifiState.WIFI_CONNECTING, "","","")); result.setWifiInfos(wifiInfos); List<NetworkType> networkTypesList = new ArrayList<NetworkType>(); networkTypesList.add(NetworkType.LTE); result.setNetworkTypesList(networkTypesList); List<NetworkBearerTypeInfo> networkTypeInfos = new ArrayList<NetworkBearerTypeInfo>(); networkTypeInfos.add(new NetworkBearerTypeInfo(1.0, 3.0, NetworkType.HSPA)); networkTypeInfos.add(new NetworkBearerTypeInfo(8.0, 12.0, NetworkType.HSPA)); result.setNetworkTypeInfos(networkTypeInfos); TimeRange timeRange = new TimeRange(2.00, 11.00); TraceDirectoryResult testResult = (TraceDirectoryResult)pktTimeUtil.getTimeRangeResult(result, timeRange); assertEquals(1,testResult.getBatteryInfos().size()); assertEquals(2,testResult.getGpsInfos().size()); assertEquals(1,testResult.getBatteryInfos().size()); assertEquals(5,testResult.getCameraInfos().size()); assertEquals(2,testResult.getScreenStateInfos().size()); assertEquals(1,testResult.getRadioInfos().size()); assertEquals(3,testResult.getWifiInfos().size()); assertEquals(2,testResult.getNetworkTypeInfos().size()); }
SessionManagerImpl implements ISessionManager { public List<Session> processPacketsAndAssembleSessions(List<PacketInfo> packets) { List<Session> sessions = new ArrayList<>(); List<PacketInfo> udpPackets = new ArrayList<>(); Map<InetAddress, String> hostMap = new HashMap<>(); Map<String, Session> udpSessions = new LinkedHashMap<>(); Map<String, PacketInfo> dnsRequestDomains = new HashMap<>(); Map<String, List<Session>> tcpSessions = new LinkedHashMap<>(); Map<InetAddress, PacketInfo> dnsResponsePackets = new HashMap<>(); if (packets != null) { for (PacketInfo packetInfo : packets) { Packet packet = packetInfo.getPacket(); if (packet instanceof UDPPacket) { udpPackets.add(packetInfo); if (((UDPPacket) packet).isDNSPacket()) { DomainNameSystem dns = ((UDPPacket) packet).getDns(); if (dns != null && dns.isResponse()) { for (InetAddress inet : dns.getIpAddresses()) { hostMap.put(inet, dns.getDomainName()); dnsResponsePackets.put(inet, packetInfo); } } else if (dns != null && !dns.isResponse()) { dnsRequestDomains.put(dns.getDomainName(), packetInfo); } } associatePacketToUDPSessionAndPopulateCollections(sessions, udpSessions, packetInfo, (UDPPacket) packet); } if (packet instanceof TCPPacket) { TCPPacket tcpPacket = (TCPPacket) packet; packetInfo.setTcpInfo(null); Session session = associatePacketToTCPSessionAndPopulateCollections(sessions, tcpSessions, packetInfo, tcpPacket); populateTCPPacketInfo(packetInfo, tcpPacket); session.setSsl(session.isSsl() ? session.isSsl() : tcpPacket.isSsl()); if (tcpPacket.isDecrypted()) { tcpPacket.setDataOffset(0); session.setDecrypted(true); } if (session.getDnsResponsePacket() == null && dnsResponsePackets.containsKey(session.getRemoteIP())) { session.setDnsResponsePacket(dnsResponsePackets.get(session.getRemoteIP())); session.setDomainName((((UDPPacket) (session.getDnsResponsePacket()).getPacket()).getDns()).getDomainName()); } if (session.getDnsRequestPacket() == null && StringUtils.isNotBlank(session.getDomainName()) && dnsRequestDomains.containsKey(session.getDomainName())) { session.setRemoteHostName(session.getDomainName()); session.setDnsRequestPacket(dnsRequestDomains.get(session.getDomainName())); } else { session.setRemoteHostName(hostMap.get(session.getRemoteIP())); } if (tcpPacket.isSslHandshake()) { session.setLastSslHandshakePacket(packetInfo); } if (packetInfo.getAppName() != null) { session.getAppNames().add(packetInfo.getAppName()); } } } } Collections.sort(sessions); analyzeRequestResponses(sessions); return sessions; } SessionManagerImpl(); @Autowired void setByteArrayLineReader(IByteArrayLineReader reader); void setiOSSecureTracePath(String tracePath); List<Session> processPacketsAndAssembleSessions(List<PacketInfo> packets); }
@Ignore @Test public void assembleSessionTest(){ Date date = new Date(); InetAddress iAdr = null; InetAddress iAdr1 = null; try { iAdr = InetAddress.getByAddress(new byte[]{89,10,1,1}); iAdr1 = InetAddress.getByAddress(new byte[]{89,10,1,1}); } catch (UnknownHostException e) { e.printStackTrace(); } Set<InetAddress> inetSet = new HashSet<InetAddress>(); inetSet.add(iAdr); inetSet.add(iAdr1); IPPacket ipPack = Mockito.mock(IPPacket.class); Mockito.when(ipPack.getDestinationIPAddress()).thenReturn(iAdr1); Mockito.when(ipPack.getSourceIPAddress()).thenReturn(iAdr); Mockito.when(ipPack.getLen()).thenReturn(20); Mockito.when(ipPack.getPacketLength()).thenReturn(20); Mockito.when(ipPack.getPayloadLen()).thenReturn(20); DomainNameSystem dns = Mockito.mock(DomainNameSystem.class); Mockito.when(dns.getIpAddresses()).thenReturn(inetSet); Mockito.when(dns.getDomainName()).thenReturn("www.att.com"); Mockito.when(dns.isResponse()).thenReturn(true); Mockito.when(dns.getCname()).thenReturn("ATT"); Mockito.when(dns.getPacket()).thenReturn(ipPack); UDPPacket udpPacket = Mockito.mock(UDPPacket.class); Mockito.when(udpPacket.isDNSPacket()).thenReturn(true); Mockito.when(udpPacket.getDns()).thenReturn(dns); Mockito.when(udpPacket.getSourcePort()).thenReturn(83); Mockito.when(udpPacket.getDestinationPort()).thenReturn(84); Mockito.when(udpPacket.getSourceIPAddress()).thenReturn(iAdr); Mockito.when(udpPacket.getDestinationIPAddress()).thenReturn(iAdr1); PacketInfo packetInfo1 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo1.getPacket()).thenReturn(udpPacket); Mockito.when(packetInfo1.getDir()).thenReturn(PacketDirection.UPLINK); Mockito.when(packetInfo1.getPayloadLen()).thenReturn(10); Mockito.when(packetInfo1.getLen()).thenReturn(10); Mockito.when(packetInfo1.getAppName()).thenReturn("Test1"); Mockito.when(packetInfo1.getTcpFlagString()).thenReturn("TestString"); InetAddress iAdr2 = null; InetAddress iAdr3 = null; try { iAdr2 = InetAddress.getByAddress(new byte[]{89,10,1,1}); iAdr3 = InetAddress.getByAddress(new byte[]{89,10,1,1}); } catch (UnknownHostException e) { e.printStackTrace(); } TCPPacket tcpPacket = Mockito.mock(TCPPacket.class); Mockito.when(tcpPacket.getSourcePort()).thenReturn(81); Mockito.when(tcpPacket.getDestinationPort()).thenReturn(82); Mockito.when(tcpPacket.getDestinationIPAddress()).thenReturn(iAdr2); Mockito.when(tcpPacket.getSourceIPAddress()).thenReturn(iAdr2); Mockito.when(tcpPacket.getAckNumber()).thenReturn(0L); Mockito.when(tcpPacket.getLen()).thenReturn(50); Mockito.when(tcpPacket.isSYN()).thenReturn(true); Mockito.when(tcpPacket.isFIN()).thenReturn(true); Mockito.when(tcpPacket.isRST()).thenReturn(true); Mockito.when(tcpPacket.getSequenceNumber()).thenReturn(20L); Mockito.when(tcpPacket.getTimeStamp()).thenReturn((double)date.getTime()-3000); PacketInfo packetInfo2 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo2.getPacket()).thenReturn(tcpPacket); Mockito.when(packetInfo2.getDir()).thenReturn(PacketDirection.UPLINK); Mockito.when(packetInfo2.getTcpInfo()).thenReturn(TcpInfo.TCP_ESTABLISH); Mockito.when(packetInfo2.getPayloadLen()).thenReturn(20); Mockito.when(packetInfo2.getLen()).thenReturn(15); Mockito.when(packetInfo2.getAppName()).thenReturn("Test2"); Mockito.when(packetInfo2.getTcpFlagString()).thenReturn("Test2String"); TCPPacket tcpPacket2 = Mockito.mock(TCPPacket.class); Mockito.when(tcpPacket2.getSourcePort()).thenReturn(95); Mockito.when(tcpPacket2.getDestinationPort()).thenReturn(99); Mockito.when(tcpPacket2.getDestinationIPAddress()).thenReturn(iAdr3); Mockito.when(tcpPacket2.getSourceIPAddress()).thenReturn(iAdr3); Mockito.when(tcpPacket.getAckNumber()).thenReturn(0L); Mockito.when(tcpPacket2.isSYN()).thenReturn(true); Mockito.when(tcpPacket2.isFIN()).thenReturn(true); Mockito.when(tcpPacket2.isRST()).thenReturn(true); Mockito.when(tcpPacket.getSequenceNumber()).thenReturn(1L); Mockito.when(tcpPacket2.getTimeStamp()).thenReturn(10000d); PacketInfo packetInfo3 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo3.getPacket()).thenReturn(tcpPacket2); Mockito.when(packetInfo3.getDir()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(packetInfo3.getTcpInfo()).thenReturn(TcpInfo.TCP_ACK_RECOVER); Mockito.when(packetInfo3.getPayloadLen()).thenReturn(30); Mockito.when(packetInfo3.getLen()).thenReturn(20); Mockito.when(packetInfo3.getAppName()).thenReturn("Test3"); Mockito.when(packetInfo3.getTcpFlagString()).thenReturn("Test3String"); InetAddress iAdr4 = Mockito.mock(InetAddress.class); InetAddress iAdr5 = Mockito.mock(InetAddress.class); Mockito.when(iAdr4.getAddress()).thenReturn(new byte[]{89,10,5,1}); Mockito.when(iAdr4.getHostAddress()).thenReturn("@microfoft"); Mockito.when(iAdr4.getHostName()).thenReturn("microfoft"); Mockito.when(iAdr5.getAddress()).thenReturn(new byte[]{72,12,23,1}); Mockito.when(iAdr5.getHostAddress()).thenReturn("@apple"); Mockito.when(iAdr5.getHostName()).thenReturn("apple"); Set<InetAddress> inetSet1 = new HashSet<InetAddress>(); inetSet1.add(iAdr4); inetSet1.add(iAdr5); IPPacket ipPack1 = Mockito.mock(IPPacket.class); Mockito.when(ipPack1.getDestinationIPAddress()).thenReturn(iAdr5); Mockito.when(ipPack1.getSourceIPAddress()).thenReturn(iAdr4); Mockito.when(ipPack1.getLen()).thenReturn(30); Mockito.when(ipPack1.getPacketLength()).thenReturn(40); Mockito.when(ipPack1.getPayloadLen()).thenReturn(40); DomainNameSystem dns1 = Mockito.mock(DomainNameSystem.class); Mockito.when(dns1.getIpAddresses()).thenReturn(inetSet); Mockito.when(dns1.getDomainName()).thenReturn("www.att.com"); Mockito.when(dns1.isResponse()).thenReturn(false); Mockito.when(dns1.getCname()).thenReturn("ATT"); Mockito.when(dns1.getPacket()).thenReturn(ipPack1); UDPPacket udpPacket1 = Mockito.mock(UDPPacket.class); Mockito.when(udpPacket1.isDNSPacket()).thenReturn(true); Mockito.when(udpPacket1.getDns()).thenReturn(dns1); Mockito.when(udpPacket1.getSourcePort()).thenReturn(90); Mockito.when(udpPacket1.getSourceIPAddress()).thenReturn(iAdr4); Mockito.when(udpPacket1.getDestinationPort()).thenReturn(91); Mockito.when(udpPacket1.getDestinationIPAddress()).thenReturn(iAdr5); PacketInfo packetInfo4 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo4.getPacket()).thenReturn(udpPacket); Mockito.when(packetInfo4.getDir()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(packetInfo4.getPayloadLen()).thenReturn(30); Mockito.when(packetInfo4.getLen()).thenReturn(10); Mockito.when(packetInfo4.getAppName()).thenReturn("Test2"); Mockito.when(packetInfo4.getTcpFlagString()).thenReturn("TestString2"); PacketInfo packetInfo5 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo5.getPacket()).thenReturn(tcpPacket); Mockito.when(packetInfo5.getDir()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(packetInfo5.getTcpInfo()).thenReturn(TcpInfo.TCP_ESTABLISH); Mockito.when(packetInfo5.getPayloadLen()).thenReturn(20); Mockito.when(packetInfo5.getLen()).thenReturn(15); Mockito.when(packetInfo5.getAppName()).thenReturn("Test2"); Mockito.when(packetInfo5.getTcpFlagString()).thenReturn("Test2String"); UDPPacket udpPacket2 = Mockito.mock(UDPPacket.class); Mockito.when(udpPacket2.isDNSPacket()).thenReturn(true); Mockito.when(udpPacket2.getDns()).thenReturn(dns1); Mockito.when(udpPacket2.getSourcePort()).thenReturn(90); Mockito.when(udpPacket2.getSourceIPAddress()).thenReturn(iAdr4); Mockito.when(udpPacket2.getDestinationPort()).thenReturn(91); Mockito.when(udpPacket2.getDestinationIPAddress()).thenReturn(iAdr5); PacketInfo packetInfo6 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo6.getPacket()).thenReturn(udpPacket); Mockito.when(packetInfo6.getDir()).thenReturn(PacketDirection.UNKNOWN); Mockito.when(packetInfo6.getPayloadLen()).thenReturn(30); Mockito.when(packetInfo6.getLen()).thenReturn(10); Mockito.when(packetInfo6.getAppName()).thenReturn("Test2"); Mockito.when(packetInfo6.getTcpFlagString()).thenReturn("TestString2"); List<PacketInfo> packetsList = new ArrayList<PacketInfo>(); packetsList.add(packetInfo1); packetsList.add(packetInfo2); packetsList.add(packetInfo3); packetsList.add(packetInfo4); packetsList.add(packetInfo5); packetsList.add(packetInfo6); List<Session> sessionsList = sessionMgr.processPacketsAndAssembleSessions(packetsList); assertEquals(5,sessionsList.size()); } @Ignore @Test public void assembleSessionTest1(){ Date date = new Date(); InetAddress iAdr = Mockito.mock(InetAddress.class); Mockito.when(iAdr.getAddress()).thenReturn(new byte[]{89,10,1,1}); Mockito.when(iAdr.getHostAddress()).thenReturn("@att"); Mockito.when(iAdr.getHostName()).thenReturn("att"); InetAddress iAdr1 = Mockito.mock(InetAddress.class); Mockito.when(iAdr1.getAddress()).thenReturn(new byte[]{89,10,1,1}); Mockito.when(iAdr1.getHostAddress()).thenReturn("@att"); Mockito.when(iAdr1.getHostName()).thenReturn("att"); Set<InetAddress> inetSet = new HashSet<InetAddress>(); inetSet.add(iAdr); inetSet.add(iAdr1); IPPacket ipPack = Mockito.mock(IPPacket.class); Mockito.when(ipPack.getDestinationIPAddress()).thenReturn(iAdr1); Mockito.when(ipPack.getSourceIPAddress()).thenReturn(iAdr); Mockito.when(ipPack.getLen()).thenReturn(20); Mockito.when(ipPack.getPacketLength()).thenReturn(20); Mockito.when(ipPack.getPayloadLen()).thenReturn(10); DomainNameSystem dns = Mockito.mock(DomainNameSystem.class); Mockito.when(dns.getIpAddresses()).thenReturn(inetSet); Mockito.when(dns.getDomainName()).thenReturn("www.att.com"); Mockito.when(dns.isResponse()).thenReturn(true); Mockito.when(dns.getCname()).thenReturn("ATT"); Mockito.when(dns.getPacket()).thenReturn(ipPack); UDPPacket udpPacket = Mockito.mock(UDPPacket.class); Mockito.when(udpPacket.isDNSPacket()).thenReturn(false); Mockito.when(udpPacket.getDns()).thenReturn(dns); Mockito.when(udpPacket.getSourcePort()).thenReturn(83); Mockito.when(udpPacket.getDestinationPort()).thenReturn(84); Mockito.when(udpPacket.getSourceIPAddress()).thenReturn(iAdr); Mockito.when(udpPacket.getDestinationIPAddress()).thenReturn(iAdr1); PacketInfo packetInfo1 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo1.getPacket()).thenReturn(udpPacket); Mockito.when(packetInfo1.getDir()).thenReturn(PacketDirection.UPLINK); Mockito.when(packetInfo1.getPayloadLen()).thenReturn(20); Mockito.when(packetInfo1.getLen()).thenReturn(10); Mockito.when(packetInfo1.getAppName()).thenReturn("Test1"); Mockito.when(packetInfo1.getTcpFlagString()).thenReturn("TestString"); InetAddress iAdr2 = Mockito.mock(InetAddress.class); Mockito.when(iAdr2.getAddress()).thenReturn(new byte[]{89,10,1,1}); Mockito.when(iAdr2.getHostAddress()).thenReturn("@att"); Mockito.when(iAdr2.getHostName()).thenReturn("att"); TCPPacket tcpPacket = Mockito.mock(TCPPacket.class); Mockito.when(tcpPacket.getSourcePort()).thenReturn(81); Mockito.when(tcpPacket.getDestinationPort()).thenReturn(82); Mockito.when(tcpPacket.getDestinationIPAddress()).thenReturn(iAdr2); Mockito.when(tcpPacket.getSourceIPAddress()).thenReturn(iAdr2); Mockito.when(tcpPacket.getAckNumber()).thenReturn(0L); Mockito.when(tcpPacket.getLen()).thenReturn(50); Mockito.when(tcpPacket.isSYN()).thenReturn(true); Mockito.when(tcpPacket.isFIN()).thenReturn(true); Mockito.when(tcpPacket.isRST()).thenReturn(true); Mockito.when(tcpPacket.getSequenceNumber()).thenReturn(-3L); Mockito.when(tcpPacket.getTimeStamp()).thenReturn((double)date.getTime()-3000); PacketInfo packetInfo2 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo2.getPacket()).thenReturn(tcpPacket); Mockito.when(packetInfo2.getDir()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(packetInfo2.getTcpInfo()).thenReturn(TcpInfo.TCP_ESTABLISH); Mockito.when(packetInfo2.getPayloadLen()).thenReturn(10); Mockito.when(packetInfo2.getLen()).thenReturn(15); Mockito.when(packetInfo2.getAppName()).thenReturn("Test2"); Mockito.when(packetInfo2.getTcpFlagString()).thenReturn("Test2String"); InetAddress iAdr3 = Mockito.mock(InetAddress.class); Mockito.when(iAdr3.getAddress()).thenReturn(new byte[]{89,10,1,1}); Mockito.when(iAdr3.getHostAddress()).thenReturn("@att"); Mockito.when(iAdr3.getHostName()).thenReturn("att"); TCPPacket tcpPacket2 = Mockito.mock(TCPPacket.class); Mockito.when(tcpPacket2.getSourcePort()).thenReturn(95); Mockito.when(tcpPacket2.getDestinationPort()).thenReturn(99); Mockito.when(tcpPacket2.getDestinationIPAddress()).thenReturn(iAdr3); Mockito.when(tcpPacket2.getSourceIPAddress()).thenReturn(iAdr3); Mockito.when(tcpPacket.getAckNumber()).thenReturn(0L); Mockito.when(tcpPacket2.isSYN()).thenReturn(true); Mockito.when(tcpPacket2.isFIN()).thenReturn(true); Mockito.when(tcpPacket2.isRST()).thenReturn(true); Mockito.when(tcpPacket.getSequenceNumber()).thenReturn(1L); Mockito.when(tcpPacket2.getTimeStamp()).thenReturn(10000d); PacketInfo packetInfo3 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo3.getPacket()).thenReturn(tcpPacket2); Mockito.when(packetInfo3.getDir()).thenReturn(PacketDirection.UPLINK); Mockito.when(packetInfo3.getTcpInfo()).thenReturn(TcpInfo.TCP_ACK_RECOVER); Mockito.when(packetInfo3.getPayloadLen()).thenReturn(30); Mockito.when(packetInfo3.getLen()).thenReturn(20); Mockito.when(packetInfo3.getAppName()).thenReturn("Test3"); Mockito.when(packetInfo3.getTcpFlagString()).thenReturn("Test3String"); InetAddress iAdr4 = Mockito.mock(InetAddress.class); InetAddress iAdr5 = Mockito.mock(InetAddress.class); Mockito.when(iAdr4.getAddress()).thenReturn(new byte[]{89,10,5,1}); Mockito.when(iAdr4.getHostAddress()).thenReturn("@microfoft"); Mockito.when(iAdr4.getHostName()).thenReturn("microfoft"); Mockito.when(iAdr5.getAddress()).thenReturn(new byte[]{72,12,23,1}); Mockito.when(iAdr5.getHostAddress()).thenReturn("@apple"); Mockito.when(iAdr5.getHostName()).thenReturn("apple"); Set<InetAddress> inetSet1 = new HashSet<InetAddress>(); inetSet1.add(iAdr4); inetSet1.add(iAdr5); IPPacket ipPack1 = Mockito.mock(IPPacket.class); Mockito.when(ipPack1.getDestinationIPAddress()).thenReturn(iAdr5); Mockito.when(ipPack1.getSourceIPAddress()).thenReturn(iAdr4); Mockito.when(ipPack1.getLen()).thenReturn(30); Mockito.when(ipPack1.getPacketLength()).thenReturn(40); Mockito.when(ipPack1.getPayloadLen()).thenReturn(40); DomainNameSystem dns1 = Mockito.mock(DomainNameSystem.class); Mockito.when(dns1.getIpAddresses()).thenReturn(inetSet); Mockito.when(dns1.getDomainName()).thenReturn("www.microsft.com"); Mockito.when(dns1.isResponse()).thenReturn(false); Mockito.when(dns1.getCname()).thenReturn("microsoft"); Mockito.when(dns1.getPacket()).thenReturn(ipPack1); UDPPacket udpPacket1 = Mockito.mock(UDPPacket.class); Mockito.when(udpPacket1.isDNSPacket()).thenReturn(true); Mockito.when(udpPacket1.getDns()).thenReturn(dns1); Mockito.when(udpPacket1.getSourcePort()).thenReturn(90); Mockito.when(udpPacket1.getSourceIPAddress()).thenReturn(iAdr4); Mockito.when(udpPacket1.getDestinationPort()).thenReturn(91); Mockito.when(udpPacket1.getDestinationIPAddress()).thenReturn(iAdr5); PacketInfo packetInfo4 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo4.getPacket()).thenReturn(udpPacket); Mockito.when(packetInfo4.getDir()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(packetInfo4.getPayloadLen()).thenReturn(20); Mockito.when(packetInfo4.getLen()).thenReturn(10); Mockito.when(packetInfo4.getAppName()).thenReturn("Test2"); Mockito.when(packetInfo4.getTcpFlagString()).thenReturn("TestString2"); PacketInfo packetInfo5 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo5.getPacket()).thenReturn(tcpPacket); Mockito.when(packetInfo5.getDir()).thenReturn(PacketDirection.UPLINK); Mockito.when(packetInfo5.getTcpInfo()).thenReturn(TcpInfo.TCP_ESTABLISH); Mockito.when(packetInfo5.getPayloadLen()).thenReturn(20); Mockito.when(packetInfo5.getLen()).thenReturn(15); Mockito.when(packetInfo5.getAppName()).thenReturn("Test2"); Mockito.when(packetInfo5.getTcpFlagString()).thenReturn("Test2String"); UDPPacket udpPacket2 = Mockito.mock(UDPPacket.class); Mockito.when(udpPacket2.isDNSPacket()).thenReturn(true); Mockito.when(udpPacket2.getDns()).thenReturn(dns1); Mockito.when(udpPacket2.getSourcePort()).thenReturn(90); Mockito.when(udpPacket2.getSourceIPAddress()).thenReturn(iAdr4); Mockito.when(udpPacket2.getDestinationPort()).thenReturn(91); Mockito.when(udpPacket2.getDestinationIPAddress()).thenReturn(iAdr5); PacketInfo packetInfo6 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo6.getPacket()).thenReturn(udpPacket); Mockito.when(packetInfo6.getDir()).thenReturn(PacketDirection.UNKNOWN); Mockito.when(packetInfo6.getPayloadLen()).thenReturn(30); Mockito.when(packetInfo6.getLen()).thenReturn(10); Mockito.when(packetInfo6.getAppName()).thenReturn("Test2"); Mockito.when(packetInfo6.getTcpFlagString()).thenReturn("TestString2"); InetAddress iAdr6 = Mockito.mock(InetAddress.class); Mockito.when(iAdr6.getAddress()).thenReturn(new byte[]{60,100,1,1}); Mockito.when(iAdr6.getHostAddress()).thenReturn("@hari"); Mockito.when(iAdr6.getHostName()).thenReturn("hari"); TCPPacket tcpPacket6 = Mockito.mock(TCPPacket.class); Mockito.when(tcpPacket6.getSourcePort()).thenReturn(95); Mockito.when(tcpPacket6.getDestinationPort()).thenReturn(96); Mockito.when(tcpPacket6.getDestinationIPAddress()).thenReturn(iAdr6); Mockito.when(tcpPacket6.getSourceIPAddress()).thenReturn(iAdr6); Mockito.when(tcpPacket6.getAckNumber()).thenReturn(1L); Mockito.when(tcpPacket6.getLen()).thenReturn(50); Mockito.when(tcpPacket6.isSYN()).thenReturn(true); Mockito.when(tcpPacket6.isFIN()).thenReturn(true); Mockito.when(tcpPacket6.isRST()).thenReturn(false); Mockito.when(tcpPacket6.getSequenceNumber()).thenReturn(5L); Mockito.when(tcpPacket6.getTimeStamp()).thenReturn((double)date.getTime()-20000); PacketInfo packetInfo7 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo7.getPacket()).thenReturn(tcpPacket); Mockito.when(packetInfo7.getDir()).thenReturn(PacketDirection.UNKNOWN); Mockito.when(packetInfo7.getTcpInfo()).thenReturn(TcpInfo.TCP_ACK_DUP); Mockito.when(packetInfo7.getPayloadLen()).thenReturn(10); Mockito.when(packetInfo7.getLen()).thenReturn(15); Mockito.when(packetInfo7.getAppName()).thenReturn("Test2"); Mockito.when(packetInfo7.getTcpFlagString()).thenReturn("Test2String"); List<PacketInfo> packetsList = new ArrayList<PacketInfo>(); packetsList.add(packetInfo1); packetsList.add(packetInfo2); packetsList.add(packetInfo3); packetsList.add(packetInfo4); packetsList.add(packetInfo5); packetsList.add(packetInfo6); packetsList.add(packetInfo7); List<Session> sessionsList = sessionMgr.processPacketsAndAssembleSessions(packetsList); assertEquals(5,sessionsList.size()); }