How to use score method of io.appium.java_client.service.local.AppiumServiceBuilder class

Best io.appium code snippet using io.appium.java_client.service.local.AppiumServiceBuilder.score

AppiumPlugin.java

Source:AppiumPlugin.java Github

copy

Full Screen

...433 thisSession.stopSessionTiming();434 thisSession.computeTimeSession();435 436 if(StateController.getTesterName().length() > 0) {437 thisSession.getCurrent().getPage().updateHighscore(StateController.getTesterName());438 GamificationUtils.writeHighScorePage(thisSession.getCurrent().getPage());439 440 GamificationUtils.writeNewInteractionInPage(thisSession);441 }442 443 if(driver!=null)444 {445 446 try {447 //Runtime.getRuntime().exec("adb -s emulator-5554 emu kill");448 Runtime.getRuntime().exec("adb shell pm clear " + activity_name);449 } catch (IOException e) {450 // TODO Auto-generated catch block451 e.printStackTrace();452 }453 driver.quit();454 }455 456 System.out.println(thisSession.getStringTiming());457 thisSession.getRoot().printTiming();458 thisSession.printTree();459 GamificationUtils.writeSession(thisSession);460 461 Stats currentSessionStats = stComputer.computeStats(thisSession);462 GamificationUtils.saveStats(stComputer.getStatsMap());463 System.out.println("Il numero di nuovi widget è: " + thisSession.getTotalNewWidgets());464 Map<String,String> recap = GamificationUtils.parseStatsForRecap(currentSessionStats);465 RecapGUI gui = new RecapGUI(recap);466 }467 public void storeHomeState()468 {469 saveCookies();470 if(actualState!=null)471 {472 actualState.putMetadata("cookies", true);473 }474 }475 476 //TODO: need to be adapted to appium?477 public String[] getProductViews()478 {479 return new String[] {"Chrome", "Firefox"};480 }481 482 483 public BufferedImage getCapture() throws WebDriverException, IOException484 {485 if(StateController.isOngoingSession())486 {487 if (pagesrchaschanged) {488 489 BufferedImage image = null;490 491 image = getScreenshotWithAppium();492 if(image!=null)493 {494 // Update the status of all widgets495 //long time_before_verifyandreplace = System.currentTimeMillis();496 verifyAndReplaceWidgets();497 //long time_after_verifyandreplace = System.currentTimeMillis();498 //System.out.println("time to verifyandreplace = " + (time_after_verifyandreplace - time_before_verifyandreplace));499 }500 return image;501 }502 else {503 System.out.println("no screen update - not updating");504 return null;505 }506 }507 else508 {509 return null;510 }511 }512 public void changeState()513 {514 actualState=StateController.getCurrentState();515 if(actualState.getMetadata("cookies")!=null)516 {517 loadCookies();518 }519 }520 521 //execute a click action on the center of a widget just by x and y coordinates (not using appium)522 //to be used when a unique widget cannot be identified through id, text or content description523 public void performAdbClick(Action action) {524 525 526 if (action instanceof LeftClickAction) {527 528 LeftClickAction leftClickAction=(LeftClickAction) action;529 //Widget locatedWidget=StateController.getWidgetAt(actualState, leftClickAction.getLocation());530 int x = (int) leftClickAction.getLocation().getX();531 int y = (int) leftClickAction.getLocation().getY();532 533 534 System.out.println("trying to launch /c\"" + adbPath + "\\adb\" shell input mouse tap " + x + " " + y );535 //adb shell input mouse tap 523 126536 ProcessBuilder builder = new ProcessBuilder(537 "cmd.exe", "/c\"", adbPath + "\\adb\" shell input mouse tap " + x + " " + y);538 try {539 Process p = builder.start();540 System.out.println("Tap performed at x=" + x + ", y= " + y + "con codice " + p.waitFor());541 } catch (IOException e) {542 // TODO Auto-generated catch block543 e.printStackTrace();544 } catch(InterruptedException e) {545 System.err.println("Errore nella wait del processo:" + e.getMessage() );546 System.err.println(e.getStackTrace());547 }548 }549 }550 551 552 553 public void performAction(Action action)554 {555 556 if(!StateController.isRunningSession() || (StateController.isToolbarVisible() && StateController.getMode()==Mode.MANUAL && !"AugmentedToolbar".equalsIgnoreCase(action.getCreatedByPlugin())))557 {558 // Only perform actions during a running session and not showing toolbar559 return;560 }561 System.out.println(">STARTING PERFORMACTION");562 563 long time_performaction_before = System.currentTimeMillis();564 565 if(action instanceof MouseScrollAction)566 {567 MouseScrollAction mouseScrollAction=(MouseScrollAction)action;568 StateController.setSelectedWidgetNo(StateController.getSelectedWidgetNo()+mouseScrollAction.getRotation());569 return;570 }571 572 else if(action instanceof TypeAction)573 {574 575 //type action should be the same because they are managed all by the GUI576 577 TypeAction typeAction=(TypeAction)action;578 KeyEvent keyEvent=typeAction.getKeyEvent();579 int keyCode = keyEvent.getKeyCode();580 char keyChar = keyEvent.getKeyChar();581 if(keyCode==KeyEvent.VK_ENTER)582 {583 // Send keyboardInput to selected widget (if any)584 StateController.addKeyboardInput("[ENTER]");585 586 Widget locatedWidget=StateController.getWidgetAt(actualState, typeAction.getLocation());587 //GAMIFICATION: record interaction in the page588 thisSession.newInteraction(GamificationUtils.logInformationAndroid(locatedWidget));589 590 performTypeActionOnWidgetAppium(locatedWidget, action);591 592 if(locatedWidget.getWidgetVisibility()==WidgetVisibility.HIDDEN || locatedWidget.getWidgetVisibility()==WidgetVisibility.SUGGESTION)593 {594 locatedWidget.setWidgetVisibility(WidgetVisibility.VISIBLE);595 locatedWidget.setCreatedBy(StateController.getTesterName());596 locatedWidget.setCreatedDate(new Date());597 locatedWidget.setCreatedProductVersion(StateController.getProductVersion());598 }599 600 }601 else if(keyCode==KeyEvent.VK_DELETE || keyCode==KeyEvent.VK_BACK_SPACE)602 {603 if(StateController.getKeyboardInput().length()>0)604 {605 StateController.removeLastKeyboardInput();606 }607 else608 {609 // Remove selected widget610 Widget locatedWidget=StateController.getWidgetAt(actualState, typeAction.getLocation());611 if(locatedWidget!=null)612 {613 StateController.displayMessage("Press y to remove the selected widget");614 // 5 seconds to press y615 widgetToRemove=locatedWidget;616 widgetRemoveUntilTime=System.currentTimeMillis()+5000;617 }618 }619 }620 else if(keyChar=='y' && widgetToRemove!=null && widgetRemoveUntilTime>System.currentTimeMillis())621 {622 actualState.removeWidget(widgetToRemove);623 widgetToRemove=null;624 StateController.displayMessageHide();625 }626 else if(keyCode==KeyEvent.VK_ESCAPE)627 {628 StateController.clearKeyboardInput();629 }630 else if(keyCode==KeyEvent.VK_SPACE)631 {632 StateController.addKeyboardInput(" ");633 }634 else if(keyCode==KeyEvent.VK_UP)635 {636 StateController.setSelectedWidgetNo(StateController.getSelectedWidgetNo()-1);637 }638 else if(keyCode==KeyEvent.VK_DOWN)639 {640 StateController.setSelectedWidgetNo(StateController.getSelectedWidgetNo()+1);641 }642 else643 {644 if(StateController.getKeyboardInput().length()==0)645 {646 // First typed char - remember the time647 startTypeTime=System.currentTimeMillis();648 }649 StateController.addKeyboardInput(getKeyText(keyChar));650 }651 652 System.out.println("exiting perform action");653 long time_performaction_after = System.currentTimeMillis();654 long time_performaction = time_performaction_after - time_performaction_before;655 System.out.println("time to performaction = " + time_performaction);656 }657 658 659 660 if (action instanceof LeftClickAction) { 661 662 663 //left mouse click on a widget664 LeftClickAction leftClickAction=(LeftClickAction) action;665 System.out.println("this is a left click at " + leftClickAction.getLocation());666 667 //temporary mgmt of back, menu and home buttons668 //back button management should be managed by adding the back button to the available buttons in the getavailablewidgets669 if (leftClickAction.getLocation().x > 200 && leftClickAction.getLocation().x < 300 &&670 leftClickAction.getLocation().y > 1800 && leftClickAction.getLocation().x < 1900 ) {671 672 driver.pressKeyCode(AndroidKeyCode.BACK);673 return;674 }675 676 677 else if (leftClickAction.getLocation().x > 490 && leftClickAction.getLocation().x < 590 &&678 leftClickAction.getLocation().y > 1800 && leftClickAction.getLocation().x < 1900 ) {679 680 driver.pressKeyCode(AndroidKeyCode.HOME);681 682 }683 684 685 else if (leftClickAction.getLocation().x > 780 && leftClickAction.getLocation().x < 880 &&686 leftClickAction.getLocation().y > 1800 && leftClickAction.getLocation().x < 1900 ) {687 688 driver.pressKeyCode(AndroidKeyCode.MENU);689 690 }691 Widget locatedWidget=StateController.getWidgetAt(actualState, leftClickAction.getLocation());692 693 694 if (locatedWidget == null) {695 696 System.out.println("located widget is null!");697 }698 699 if(locatedWidget!=null)700 {701 702 703 if(locatedWidget.getWidgetType()==WidgetType.ACTION)704 {705 706 707 if (locatedWidget.getWidgetSubtype()==WidgetSubtype.TYPE_ACTION) {708 thisSession.newInteraction(GamificationUtils.logInformationAndroid(locatedWidget));709 performTypeActionOnWidgetAppium(locatedWidget, leftClickAction);710 //GAMIFICATION: type action, debug and try to record interaction711 712 if(locatedWidget.getWidgetVisibility()==WidgetVisibility.HIDDEN || locatedWidget.getWidgetVisibility()==WidgetVisibility.SUGGESTION)713 {714 locatedWidget.setWidgetVisibility(WidgetVisibility.VISIBLE);715 locatedWidget.setCreatedBy(StateController.getTesterName());716 locatedWidget.setCreatedDate(new Date());717 locatedWidget.setCreatedProductVersion(StateController.getProductVersion());718 }719 }720 721 else if(locatedWidget.getWidgetSubtype()==WidgetSubtype.LEFT_CLICK_ACTION) {722 //TODO: debug these case, try to debug723 724 AppState prima = StateController.getCurrentState();725 MobilePage p = (MobilePage) thisSession.getCurrent().getPage();726 p.setScoutState(prima);727 728 if (locatedWidget.getMetadata("id") != null && !locatedWidget.getMetadata("id").toString().equals("")) { 729 try { driver.findElementById(locatedWidget.getMetadata("id").toString()).click(); }730 catch (Exception e) { e.printStackTrace(); }731 732 }733 734 else if (locatedWidget.getMetadata("text") != null && !locatedWidget.getMetadata("text").toString().equals("")) {735 try { driver.findElement(By.xpath("//*[@text='" + locatedWidget.getMetadata("text") + "']")).click(); }736 catch (Exception e) { e.printStackTrace(); }737 }738 739 else if (locatedWidget.getMetadata("content-desc") != null && !locatedWidget.getMetadata("content-desc").toString().equals("")) {740 try { driver.findElement(By.xpath("//*[@content-desc='" + locatedWidget.getMetadata("content-desc") + "']")).click(); }741 742 catch (Exception e) { e.printStackTrace(); }743 }744 745 else { 746 System.out.println("done by click");747 performAdbClick(action);748 }749 750 thisSession.newInteraction(GamificationUtils.logInformationAndroid(locatedWidget));751 752 //TODO STATE MGMT NOT FULLY DONE BY NOW753 if(locatedWidget.getWidgetVisibility()==WidgetVisibility.HIDDEN || locatedWidget.getWidgetVisibility()==WidgetVisibility.SUGGESTION)754 {755 locatedWidget.setWidgetVisibility(WidgetVisibility.VISIBLE);756 locatedWidget.setComment(null);757 StateController.insertWidget(locatedWidget, locatedWidget.getNextState());758 }759 else760 {761 StateController.performWidget(locatedWidget);762 }763 764 thisSession.setActiveWidgetCurrentPage(thisSession.getCurrent().getPage().getHighlightedWidgets() +1);765 766 //GAMIFICATION: controllo se ho cliccato sull'easter egg767 if (locatedWidget.getMetadata("id") != null) {768 if(thisSession.getCurrent().getPage().getSonWithEasterEgg()!= null)769 if(thisSession.getCurrent().getPage().getSonWithEasterEgg().equals(locatedWidget.getMetadata("id"))) {770 if(thisSession.getCurrent().getPage().getEasterEggStartPoint() == null) {771 thisSession.getCurrent().getPage().setHasEasterEgg(true);772 int width=StateController.getProductViewWidth();773 int height=StateController.getProductViewHeight();774 int x = (int)(Math.random() * (width - 30));775 int y = (int)(Math.random() * (height - 50));776 thisSession.getCurrent().getPage().setEasterEggStartPoint(x, y);777 isEasterEggAssigned = false; 778 }779 }780 }781 782 thisSession.stopPageTiming();783 784 //GamificationUtils.writeNewInteractionInPage(thisSession);785 786 //GAMIFICATION: verifica del fragment:787 ArrayList<String> state = getAppState(thisSession.getMainActivity());788 plugin.Node current = thisSession.getCurrent(); 789 plugin.Node n = thisSession.updateState(state);790 if(n != null) {791 //cambia lo stato, quindi aggiorniamo highscore792 thisSession.getCurrent().getPage().updateHighscore(StateController.getTesterName());793 GamificationUtils.writeHighScorePage(thisSession.getCurrent().getPage());794 //e scriviamo le interazioni nuove795 GamificationUtils.writeNewInteractionInPage(thisSession);796 797 thisSession.setCurrent(n);798 799 if(n.equals(current)) {//non era presente, quindi aggiungo il figlio800 801 p = (MobilePage) thisSession.newNode(state).getPage();802 p.setScoutState(StateController.getCurrentState());803 804 805 System.out.println("Ho creato in nuovo nodo con stato: " + p.getState());806 807 } else {//ho ripescato uno stato precedente808 MobilePage mp = (MobilePage) n.getPage();809 if(mp != null)810 StateController.setCurrentState(mp.getScoutState());811 812 //thisSession.setActiveWidgetCurrentPage(mp.getScoutState().getNonHiddenWidgets().size());813 thisSession.reloadMap();814 System.out.println("Ho ripescato il nodo con stato: " + p.getState());815 }816 817 thisState = state;818 } else {819 // lo stato è rimasto invariato820 StateController.setCurrentState(prima);821 System.out.println("Lo stato è rimasto lo stesso: " + p.getState());822 }823 824 thisSession.startPageTiming();825 826 //thisState = state;827 828 }829 830 831 }832 833 else if(locatedWidget.getWidgetType()==WidgetType.CHECK) {834 835 836 if (StateController.getKeyboardInput().length() > 0 && locatedWidget.getWidgetVisibility()==WidgetVisibility.VISIBLE) {837 838 if(StateController.getKeyboardInput().indexOf("{")>=0 && StateController.getKeyboardInput().indexOf("}")>=0)839 {840 // An expression841 locatedWidget.setValidExpression(StateController.getKeyboardInput());842 }843 else844 {845 // Report an issue846 createIssue(locatedWidget, StateController.getKeyboardInput());847 }848 StateController.clearKeyboardInput();849 }850 851 else852 {853 if(locatedWidget.getWidgetVisibility()==WidgetVisibility.HIDDEN)854 {855 locatedWidget.setWidgetVisibility(WidgetVisibility.VISIBLE);856 locatedWidget.setCreatedBy(StateController.getTesterName());857 locatedWidget.setCreatedDate(new Date());858 locatedWidget.setCreatedProductVersion(StateController.getProductVersion());859 }860 }861 862 //GAMIFICATION: record interaction in this page863 thisSession.newInteraction(GamificationUtils.logInformationAndroid(locatedWidget)); 864 }865 866 867 else if(locatedWidget.getWidgetType()==WidgetType.ISSUE)868 {869 if(locatedWidget.getWidgetVisibility()==WidgetVisibility.VISIBLE)870 {871 locatedWidget.setWidgetType(WidgetType.CHECK);872 locatedWidget.setResolvedBy(StateController.getTesterName());873 locatedWidget.setResolvedDate(new Date());874 locatedWidget.setResolvedProductVersion(StateController.getProductVersion());875 Widget matchingWidget=(Widget)locatedWidget.getMetadata("matching_widget");876 if(matchingWidget!=null)877 {878 String matchingText=(String)matchingWidget.getMetadata("text");879 if(matchingText!=null)880 {881 locatedWidget.setValidExpression("{text} = "+matchingText);882 }883 }884 StateController.clearKeyboardInput();885 886 //GAMIFICATION: record interaction in this page887 thisSession.newInteraction(GamificationUtils.logInformationAndroid(locatedWidget));888 }889 } else {890 //non ho riconosciuto cosa è accaduto, ma devo comunque riportare il click891 AppState prima = StateController.getCurrentState();892 MobilePage p = (MobilePage) thisSession.getCurrent().getPage();893 System.out.println("done by click");894 performAdbClick(action);895 896 //GAMIFICATION: controllo se ho cliccato sull'easter egg897 if (locatedWidget.getMetadata("id") != null) {898 if(thisSession.getCurrent().getPage().getSonWithEasterEgg()!= null)899 if(thisSession.getCurrent().getPage().getSonWithEasterEgg().equals(locatedWidget.getMetadata("id"))) {900 if(thisSession.getCurrent().getPage().getEasterEggStartPoint() == null) {901 thisSession.getCurrent().getPage().setHasEasterEgg(true);902 int width=StateController.getProductViewWidth();903 int height=StateController.getProductViewHeight();904 int x = (int)(Math.random() * (width - 30));905 int y = (int)(Math.random() * (height - 50));906 thisSession.getCurrent().getPage().setEasterEggStartPoint(x, y);907 isEasterEggAssigned = false; 908 }909 }910 }911 912 thisSession.stopPageTiming();913 914 //GamificationUtils.writeNewInteractionInPage(thisSession);915 916 //GAMIFICATION: verifica del fragment:917 ArrayList<String> state = getAppState(thisSession.getMainActivity());918 plugin.Node current = thisSession.getCurrent(); 919 plugin.Node n = thisSession.updateState(state);920 if(n != null) {921 922 StateController.insertWidget(locatedWidget, locatedWidget.getNextState());923 //cambia lo stato, quindi aggiorniamo highscore924 thisSession.getCurrent().getPage().updateHighscore(StateController.getTesterName());925 GamificationUtils.writeHighScorePage(thisSession.getCurrent().getPage());926 //e scriviamo le interazioni nuove927 GamificationUtils.writeNewInteractionInPage(thisSession);928 929 thisSession.setCurrent(n);930 931 if(n.equals(current)) {//non era presente, quindi aggiungo il figlio932 933 p = (MobilePage) thisSession.newNode(state).getPage();934 p.setScoutState(StateController.getCurrentState());935 936 937 System.out.println("Ho creato in nuovo nodo con stato: " + p.getState());938 939 } else {//ho ripescato uno stato precedente940 MobilePage mp = (MobilePage) n.getPage();941 if(mp != null)942 StateController.setCurrentState(mp.getScoutState());943 944 //thisSession.setActiveWidgetCurrentPage(mp.getScoutState().getNonHiddenWidgets().size());945 thisSession.reloadMap();946 System.out.println("Ho ripescato il nodo con stato: " + p.getState());947 }948 949 950 thisState = state;951 } else {952 // lo stato è rimasto invariato953 StateController.setCurrentState(prima);954 System.out.println("Lo stato è rimasto lo stesso: " + p.getState());955 }956 957 thisSession.startPageTiming();958 }959 }960 961 long time_performaction_after = System.currentTimeMillis();962 long time_performaction = time_performaction_after - time_performaction_before;963 System.out.println("time to performaction = " + time_performaction);964 System.out.println("ENDING PERFORMACTION");965 }966 967 }968 969 970 971 972 private void performTypeActionOnWidgetAppium(Widget locatedWidget, Action action) {973 974 975 976 String text = StateController.getKeyboardInput();977 978 979 System.out.println("received to type: " + text);980 if(seleniumKeyTag==null)981 {982 seleniumKeyTag=new String[]{"[ENTER]", "[TAB]", "[DELETE]", "[ESCAPE]", "[BACKSPACE]", "[UP]", "[DOWN]", "[LEFT]", "[RIGHT]", "[PAGE_UP]", "[PAGE_DOWN]", "[HOME]", "[END]", "[F1]", "[F2]", "[F3]", "[F4]", "[F5]", "[F6]", "[F7]", "[F8]", "[F9]", "[F10]", "[F11]", "[F12]", "[NUMPAD_ADD]", "[NUMPAD_SUBTRACT]", "[NUMPAD_MULTIPLY]", "[NUMPAD_DIVIDE]"};983 seleniumKeyValue=new String[]{Keys.RETURN.toString(), Keys.TAB.toString(), Keys.DELETE.toString(), Keys.ESCAPE.toString(), Keys.BACK_SPACE.toString(), Keys.UP.toString(), Keys.DOWN.toString(), Keys.LEFT.toString(), Keys.RIGHT.toString(), Keys.PAGE_UP.toString(), Keys.PAGE_DOWN.toString(), Keys.HOME.toString(), Keys.END.toString(), Keys.F1.toString(), Keys.F2.toString(), Keys.F3.toString(), Keys.F4.toString(), Keys.F5.toString(), Keys.F6.toString(), Keys.F7.toString(), Keys.F8.toString(), Keys.F9.toString(), Keys.F10.toString(), Keys.F11.toString(), Keys.F12.toString(), Keys.ADD.toString(), Keys.SUBTRACT.toString(), Keys.MULTIPLY.toString(), Keys.DIVIDE.toString()};984 }985 if (locatedWidget.getWidgetType() == WidgetType.ACTION && locatedWidget.getWidgetSubtype() == WidgetSubtype.TYPE_ACTION) {986 987 try988 {989 990 String stringtotype = text.split("\\[ENTER\\]")[0];991 992 993 if(stringtotype.length()>0)994 {995 996 997 System.out.println("we have keyboard input to type");998 // We have keyboard input to type999 MobileElement element;1000 if (locatedWidget.getMetadata("id") != null && !locatedWidget.getMetadata("id").toString().equals("")) { 1001 try { 1002 1003 element = driver.findElementById(locatedWidget.getMetadata("id").toString());1004 if (element != null) { System.out.println("found element"); } 1005 element.sendKeys(stringtotype);1006 }1007 catch (Exception e) { e.printStackTrace(); }1008 }1009 1010 else if (locatedWidget.getMetadata("text") != null && !locatedWidget.getMetadata("text").toString().equals("")) {1011 try { 1012 System.out.println("found by text");1013 element = driver.findElement(By.xpath("//*[@text='" + locatedWidget.getMetadata("text") + "']"));1014 element.clear();1015 element.sendKeys(stringtotype); 1016 }1017 catch (Exception e) { e.printStackTrace(); }1018 }1019 1020 else if (locatedWidget.getMetadata("content-desc") != null && !locatedWidget.getMetadata("content-desc").toString().equals("")) {1021 try { 1022 System.out.println("found by contdesc");1023 element = driver.findElement(By.xpath("//*[@content-desc='" + locatedWidget.getMetadata("content-desc") + "']"));1024 element.clear();1025 element.sendKeys(stringtotype); 1026 }1027 1028 catch (Exception e) { e.printStackTrace(); }1029 }1030 }1031 else1032 {1033 1034 System.out.println("left click on a widget");1035 1036 System.out.println("must execute a click on " + printWidgetNoText(locatedWidget));1037 1038 if (locatedWidget.getMetadata("id") != null && !locatedWidget.getMetadata("id").toString().equals("")) { 1039 try { driver.findElementById(locatedWidget.getMetadata("id").toString()).click(); }1040 catch (Exception e) { e.printStackTrace(); }1041 }1042 1043 else if (locatedWidget.getMetadata("text") != null && !locatedWidget.getMetadata("text").toString().equals("")) {1044 try { driver.findElement(By.xpath("//*[@text='" + locatedWidget.getMetadata("text") + "']")).click(); }1045 catch (Exception e) { e.printStackTrace(); }1046 }1047 1048 else if (locatedWidget.getMetadata("content-desc") != null && !locatedWidget.getMetadata("content-desc").toString().equals("")) {1049 try { driver.findElement(By.xpath("//*[@content-desc='" + locatedWidget.getMetadata("content-desc") + "']")).click(); }1050 catch (Exception e) { e.printStackTrace(); }1051 }1052 else { 1053 performAdbClick(action);1054 }1055 1056 1057 1058 }1059 1060 StateController.clearKeyboardInput();1061 1062 }1063 1064 1065 1066 1067 1068 1069 catch (Exception e) {1070 e.printStackTrace();1071 }1072 }1073 1074 1075 else if (locatedWidget.getWidgetType() == WidgetType.CHECK) {1076 1077 if(StateController.getKeyboardInput().length()>0 && locatedWidget.getWidgetVisibility()==WidgetVisibility.VISIBLE)1078 {1079 // Report an issue1080 if(StateController.getKeyboardInput().endsWith("[ENTER]"))1081 {1082 StateController.removeLastKeyboardInput();1083 }1084 if(StateController.getKeyboardInput().indexOf("{")>=0 && StateController.getKeyboardInput().indexOf("}")>=0)1085 {1086 // An expression1087 locatedWidget.setValidExpression(StateController.getKeyboardInput());1088 }1089 else1090 {1091 // Report an issue1092 createIssue(locatedWidget, StateController.getKeyboardInput());1093 }1094 StateController.clearKeyboardInput();1095 } 1096 }1097 //System.out.println("exiting performtype");1098 1099 }1100 1101 //TODO1102 private void createIssue(Widget widget, String reportedText)1103 {1104 widget.setWidgetType(WidgetType.ISSUE);1105 widget.setWidgetVisibility(WidgetVisibility.VISIBLE);1106 widget.setReportedText(reportedText);1107 widget.setReportedBy(StateController.getTesterName());1108 widget.setReportedDate(new Date());1109 widget.setReportedProductVersion(StateController.getProductVersion());1110 Widget matchingWidget=(Widget)widget.getMetadata("matching_widget");1111 if(matchingWidget!=null)1112 {1113 String matchingText=(String)matchingWidget.getMetadata("text");1114 if(matchingText!=null)1115 {1116 widget.setValidExpression("{text} = "+matchingText);1117 }1118 }1119 if(startTypeTime>0)1120 {1121 long deltaTime=System.currentTimeMillis()-startTypeTime;1122 startTypeTime=0;1123 widget.putMetadata("report_issue_time", deltaTime);1124 }1125 }1126 1127 /**1128 * Verify that visible widgets are still valid and replace hidden widgets1129 */1130 private synchronized void verifyAndReplaceWidgets()1131 {1132 1133 1134 //System.out.println("we're inside verify and replace widgets");1135 try1136 {1137 List<Widget> availableWidgets=getAvailableWidgetsAppium();1138 if(availableWidgets==null)1139 {1140 return;1141 }1142 List<Widget> hiddenAvailableWidgets=new ArrayList<Widget>();1143 List<Widget> nonHiddenWidgets=actualState.getNonHiddenWidgets();1144 hiddenAvailableWidgets.addAll(availableWidgets);1145 /*for(Widget widget:availableWidgets)1146 {1147 hiddenAvailableWidgets.add(widget);1148 }*/1149 for(Widget widget:nonHiddenWidgets)1150 {1151 1152 1153 if(actualState!=StateController.getCurrentState())1154 {1155 // The state has been changed - abort1156 return;1157 }1158 if(widget.getWidgetSubtype()==WidgetSubtype.GO_HOME_ACTION)1159 {1160 // The Go Home widget is always located1161 widget.setWidgetStatus(WidgetStatus.LOCATED);1162 }1163 else1164 {1165 WidgetMatch widgetMatch=findBestMatchingWidget(widget, availableWidgets);1166 //System.out.println("we're here;");1167 if (widgetMatch==null) {1168 //System.out.println("widgetmatch for widget " + widget.getMetadata("id") + " is null");1169 }1170 if(widgetMatch!=null)1171 {1172 Widget matchingWidget=widgetMatch.getWidget2();1173 widget.putMetadata("matching_widget", matchingWidget);1174 if(widget.getValidExpression()!=null)1175 {1176 if(matchingWidget.evaluateExpression(widget.getValidExpression()))1177 {1178 //System.out.println("widget " + widget.getMetadata("id") + " is valid");1179 // Expression is valid1180 widget.setWidgetStatus(WidgetStatus.VALID);1181 widget.setComment(widget.getValidExpression());1182 }1183 else1184 {1185 // Expression not valid1186 //System.out.println("widget " + widget.getMetadata("id") + " is located");1187 widget.setWidgetStatus(WidgetStatus.LOCATED);1188 String comment=matchingWidget.getReplacedParameters(widget.getValidExpression());1189 if(comment.length()>60)1190 {1191 comment=widget.getValidExpression();1192 }1193 widget.setComment(comment);1194 }1195 }1196 else1197 {1198 //System.out.println("widget " + widget.getMetadata("id") + " is located");1199 widget.setWidgetStatus(WidgetStatus.LOCATED);1200 }1201 hiddenAvailableWidgets.remove(widget);1202 }1203 else1204 {1205 // Could not locate widget1206 //System.out.println("widget " + widget.getMetadata("id") + " is unlocated");1207 widget.setWidgetStatus(WidgetStatus.UNLOCATED);1208 }1209 }1210 }1211 1212 //TODO: filter list is possibol? eventuale generazione easter egg -- 790 selenium plugin1213 actualState.replaceHiddenWidgets(hiddenAvailableWidgets, "SeleniumPlugin");1214 1215 //questo filtro potrebbe non servire poiché è difficile che esistano widget così piccoli1216 List<Widget> l = hiddenAvailableWidgets.stream()1217 .filter(w -> (w.getLocationArea().height > 1 && w.getLocationArea().width > 1))1218 .collect(Collectors.toList());1219 1220 if(thisSession != null) {1221 //questo serve per i bug noti1222 /*Long x = l.stream()1223 .filter(w -> w.getMetadata("text") != null)1224 .map(w -> w.getMetadata("text"))1225 .filter(text -> knownBug.contains(text))1226 .count();*/1227 1228 1229 if(!isEasterEggAssigned && thisSession.getCurrent().getPage().getSonWithEasterEgg() == null) {1230 //l'easter egg è assegnato ad un widget cliccabile e con un id non nullo1231 List<String> eggable = l.stream()1232 /*.filter( w -> isClickableWidgetAppium(w))1233 .map( w -> w.getMetadata("id").toString())1234 .collect(Collectors.toList());*/1235 .filter(w -> w.getWidgetType() == WidgetType.ACTION)1236 .filter(w -> w.getWidgetSubtype() == WidgetSubtype.LEFT_CLICK_ACTION && w.getMetadata("id") != null)1237 .map( w -> w.getMetadata("id").toString())1238 .collect(Collectors.toList());1239 //tolto perché serviva per riconoscere il javascript1240 //.filter( o -> !(o.contains("#") || o.contains("javascript:") || o.contains("mailto:") || o.contains("tel:") || o.contains("ftp://") || o.length() <= 0) || (o.contains("#") && o.contains("?")))1241 1242 1243 /*if(x != 0) {1244 thisSession.setBugCount(thisSession.getBugCount() + 1);1245 }*/1246 1247 if(eggable.size() > 0) {1248 int max = eggable.size() -1;1249 int index = (int)(Math.random() * max);1250 thisSession.getCurrent().getPage().setSonWithEasterEgg(eggable.get(index));1251 //leadToEasterEgg = eggable.get(index);1252 System.out.println("The easter egg is " + eggable.get(index));1253 isEasterEggAssigned = true;1254 }1255 }1256 1257 //System.out.println("La lista filtrata ha " + l.size() + " elementi");1258 //System.out.println("La lista non filtrata ha " + hiddenAvailableWidgets.size() + " elementi");1259 1260 thisSession.setActiveWidgetCurrentPage(nonHiddenWidgets.size());1261 //we use only the widgets that fits in the page1262 thisSession.setTotalWidgetCurrentPage(l.size());1263 }1264 }1265 catch(Exception e)1266 {1267 }1268 }1269 /**1270 * @param widget1271 * @param availableWidgets1272 * @return The best matching widget in availableWidgets1273 */1274 private WidgetMatch findBestMatchingWidget(Widget widget, List<Widget> availableWidgets)1275 {1276 int bestScore=0;1277 WidgetMatch bestWidgetMatch=null;1278 1279 for(Widget availableWidget:availableWidgets)1280 {1281 WidgetMatch widgetMatch=matchScoreAppium(widget, availableWidget);1282 if(widgetMatch!=null)1283 {1284 if(widgetMatch.getScore()>bestScore)1285 {1286 bestScore=widgetMatch.getScore();1287 bestWidgetMatch=widgetMatch;1288 }1289 }1290 }1291 1292 if(bestScore<40)1293 {1294 // Match is not good enough1295 return null;1296 }1297 return bestWidgetMatch;1298 }1299 private boolean isClickableWidgetAppium(Widget widget) {1300 //in this case it is possible to use the android layout "clickable" property1301 String clickable=(String)widget.getMetadata("clickable");1302 if (clickable.equals("true")) return true;1303 else return false;1304 1305 }1306 1307 private boolean isTypeWidgetAppium(Widget widget) {1308 1309 String widgetclass = (String) widget.getMetadata("type");1310 if (widgetclass.equals("android.widget.EditText")) { return true; }1311 1312 return false;1313 }1314 1315 private boolean isLongClickableWidgetAppium (Widget widget) {1316 1317 String longclickable = (String) widget.getMetadata("long-clickable");1318 if (longclickable.equals("true")) return true;1319 else return false;1320 }1321 1322 private boolean isCheckWidgetAppium (Widget widget) {1323 1324 String text = (String) widget.getMetadata("text");1325 if (text.trim().length() > 0) { 1326 //System.out.println("text is " + text);1327 return true; }1328 1329 String widgetclass = (String) widget.getMetadata("type");1330 if (widgetclass.contains("android.widget.TextView")) { 1331 //System.out.println("widgetclass is " + text);1332 return true; }1333 1334 return false;1335 }1336 1337 /**1338 * Calculate a weighted match percent1339 * @param widget11340 * @param widget21341 * @return A match or null1342 */1343 1344 1345 1346 private WidgetMatch matchScoreAppium(Widget widget1, Widget widget2) {1347 1348 1349 1350 String id1=(String)widget1.getMetadata("id");1351 String type1=(String)widget1.getMetadata("type");1352 String text1=(String)widget1.getMetadata("text");1353 String contdesc1=(String)widget1.getMetadata("content-desc");1354 Rectangle locationArea1=widget1.getLocationArea();1355 1356 String id2=(String)widget2.getMetadata("id");1357 String type2=(String)widget2.getMetadata("type");1358 String text2=(String)widget2.getMetadata("text");1359 String contdesc2=(String)widget2.getMetadata("content-desc");1360 Rectangle locationArea2=widget2.getLocationArea();1361 1362 if (type1==null || type2==null || !type1.equalsIgnoreCase(type2)) {1363 return null;1364 //different class1365 }1366 1367 int score = 0;1368 int totalScore = 0;1369 1370 if(bothContainsValue(text1, text2))1371 {1372 if(text1.length()>5)1373 {1374 // Long text1375 totalScore+=100;1376 if(text1.equals(text2))1377 {1378 score+=100;1379 }1380 else if(text1.equalsIgnoreCase(text2))1381 {1382 score+=50;1383 }1384 }1385 else1386 {1387 // Short text1388 totalScore+=50;1389 if(text1.equals(text2))1390 {1391 score+=50;1392 }1393 else if(text1.equalsIgnoreCase(text2))1394 {1395 score+=30;1396 }1397 }1398 }1399 1400 if(bothContainsValue(id1, id2))1401 {1402 totalScore+=100;1403 if(id1.equals(id2))1404 {1405 score+=100;1406 }1407 }1408 1409 if(bothContainsValue(contdesc1, contdesc2))1410 {1411 totalScore+=50;1412 if(id1.equals(id2))1413 {1414 score+=50;1415 }1416 }1417 1418 if(bothContainsValue(type1, type2))1419 {1420 totalScore+=20;1421 if(type1.equals(type2))1422 {1423 score+=20;1424 }1425 }1426 if(locationArea1!=null && locationArea2!=null)1427 {1428 totalScore+=20;1429 if(Math.abs(locationArea1.getX()-locationArea2.getX())<5 && Math.abs(locationArea1.getY()-locationArea2.getY())<5)1430 {1431 score+=20;1432 }1433 else if(Math.abs(locationArea1.getX()-locationArea2.getX())<5 || Math.abs(locationArea1.getY()-locationArea2.getY())<5)1434 {1435 score+=10;1436 }1437 totalScore+=10;1438 if(Math.abs(locationArea1.getWidth()-locationArea2.getWidth())<5 && Math.abs(locationArea1.getHeight()-locationArea2.getHeight())<5)1439 {1440 score+=20;1441 }1442 else if(Math.abs(locationArea1.getWidth()-locationArea2.getWidth())<5 || Math.abs(locationArea1.getHeight()-locationArea2.getHeight())<5)1443 {1444 score+=10;1445 }1446 }1447 if(totalScore==0)1448 {1449 return null;1450 }1451 1452 return new WidgetMatch(widget1, widget2, score);1453 1454 1455 }1456 1457 //RC: utility function1458 private boolean bothContainsValue(String value1, String value2)1459 {1460 if(value1!=null && value2!=null && value1.trim().length()>0 && value2.trim().length()>0)1461 {1462 return true;1463 }1464 return false;1465 }1466 ...

Full Screen

Full Screen

AppiumClientTest.java

Source:AppiumClientTest.java Github

copy

Full Screen

...81 82 // 设备时间83 // System.out.println(driver.getDeviceTime());84 AppiumServiceBuilder builder = new AppiumServiceBuilder();85 builder.score(capabilities(true));86 AppiumDriverLocalService.buildService(builder);87 // 88 //AppiumDriverLocalService localService = AppiumDriverLocalService.buildDefaultService(builder);89 AppiumDriverLocalService localService = AppiumDriverLocalService.buildService(builder);90 //localService.start();91 //localService.start();92 93 //localService.stop();94 95 } catch (Exception e) {96 log.error("testAppiumClient =====> ", e);97 }98 }99 100 /**101 * 102 * 描述: 登录动作103 * @author qye.zheng104 * 105 */106 //@DisplayName("test")107 @Test108 public void testLogin() {109 try {110 //File app = new File("C:\\Users\\dell\\AppData\\Local\\Temp\\ctripA.apk");111 URL serverUrl = new URL("http://127.0.0.1:4723/wd/hub");112 AppiumDriver<MobileElement> driver = new AppiumDriver<>(serverUrl, capabilities(true));113 // 会话ID,每次连接生成一个,22e4db34-2daa-4c06-9285-742058f87deb114 //driver.getAppStringMap();115 //Map<String, String> stringMap = driver.getAppStringMap(Locale.getDefault().getLanguage());116 //Map<String, String> stringMap = driver.getAppStringMap();117 //Set<String> keys = stringMap.keySet();118 119 //keys.forEach(x -> System.out.println(stringMap.get(x)));120 121 //ScreenOrientation orientation = driver.getOrientation();122 123 MobileElement element = null;124 // 启动应用125 //driver.launchApp();126 //driver.findElementByClassName("cpt-choose-box cpt-choose-box-pop");127 //element = driver.findElementByClassName("android.widget.ImageView");128 //element = driver.findElementByXPath("//div[@class=' cpt-choose-box cpt-choose-box-pop']");129 //System.out.println(element.getText());130 //driver.getKeyboard().pressKey("A");131 132 133 //driver.rotation();134 135 //System.out.println(orientation.name() + ", " + orientation.ordinal());136 // 休眠若干秒,等待APP准备就绪137 TimeUnit.SECONDS.sleep(2);138 //driver.close();139 List<MobileElement> elements = null;140 By by = null;141 //driver.closeApp();142 by = By.xpath("//android.widget.TextView[@text='我的']");143 element = driver.findElement(by);144 // 点击145 element.click();146 147 TimeUnit.SECONDS.sleep(1);148 // 点击 [登录]149 by = By.xpath("//android.widget.Button[contains(@text,'登录')]");150 element = driver.findElement(by);151 // 点击152 element.click();153 154 TimeUnit.SECONDS.sleep(2);155 // 点击第一个元素,账号输入框156 by = By.xpath("//android.widget.EditText");157 elements = driver.findElements(by);158 // 输入账号159 elements.get(0).sendKeys("15018750787");160 // 输入密码161 elements.get(1).sendKeys("a123b456");162 163 // 点击登录164 by = By.xpath("//android.widget.RelativeLayout[@resource-id='ctrip.android.login:id/rlLoginBtn']/android.widget.Button");165 element = driver.findElement(by);166 element.click(); 167 168 // 重置APP,清空缓存169 //driver.resetApp();170 // 171 //driver.quit();172 173 174 175 } catch (Exception e) {176 log.error("testLogin =====> ", e);177 }178 }179 180 /**181 * 182 * 描述: 退出登录183 * @author qye.zheng184 * 185 */186 //@DisplayName("test")187 @Test188 public void testLogout() {189 try {190 //File app = new File("C:\\Users\\dell\\AppData\\Local\\Temp\\ctripA.apk");191 URL serverUrl = new URL("http://127.0.0.1:4723/wd/hub");192 AppiumDriver<MobileElement> driver = new AppiumDriver<>(serverUrl, capabilities(true));193 // 会话ID,每次连接生成一个,22e4db34-2daa-4c06-9285-742058f87deb194 //driver.getAppStringMap();195 //Map<String, String> stringMap = driver.getAppStringMap(Locale.getDefault().getLanguage());196 //Map<String, String> stringMap = driver.getAppStringMap();197 //Set<String> keys = stringMap.keySet();198 199 //keys.forEach(x -> System.out.println(stringMap.get(x)));200 201 //ScreenOrientation orientation = driver.getOrientation();202 203 MobileElement element = null;204 // 启动应用205 //driver.launchApp();206 //driver.findElementByClassName("cpt-choose-box cpt-choose-box-pop");207 //element = driver.findElementByClassName("android.widget.ImageView");208 //element = driver.findElementByXPath("//div[@class=' cpt-choose-box cpt-choose-box-pop']");209 //System.out.println(element.getText());210 //driver.getKeyboard().pressKey("A");211 212 213 //driver.rotation();214 215 //System.out.println(orientation.name() + ", " + orientation.ordinal());216 // 休眠若干秒,等待APP准备就绪217 TimeUnit.SECONDS.sleep(1);218 //driver.close();219 List<MobileElement> elements = null;220 By by = null;221 //driver.closeApp();222 223 by = By.xpath("//android.widget.TextView[@text='我的']");224 element = driver.findElement(by);225 // 点击226 element.click();227 228 // 点击头像229 by = By.xpath("//android.widget.ImageView[@resource-id='ctrip.android.myctrip:id/ivAvatar']");230 element = driver.findElement(by);231 // 点击232 element.click();233 234 TimeUnit.SECONDS.sleep(1);235 // 点击退出登录236 by = By.xpath("//android.widget.Button[@resource-id='ctrip.android.myctrip:id/myctrip_loginout_btn']");237 element = driver.findElement(by);238 // 点击239 element.click();240 241 // 点击确认退出242 by = By.xpath("//android.widget.TextView[@resource-id='ctrip.android.view:id/right_btn']");243 element = driver.findElement(by);244 element.click(); 245 246 // 重置APP,清空缓存247 //driver.resetApp();248 // 249 //driver.quit();250 251 252 253 } catch (Exception e) {254 log.error("testLogout =====> ", e);255 }256 }257 258 /**259 * 260 * 描述: 261 * @author qye.zheng262 * 263 */264 //@DisplayName("test")265 @Test266 public void testFindByXPath() {267 try {268 //File app = new File("C:\\Users\\dell\\AppData\\Local\\Temp\\ctripA.apk");269 URL serverUrl = new URL("http://127.0.0.1:4723/wd/hub");270 AppiumDriver<MobileElement> driver = new AppiumDriver<>(serverUrl, capabilities(true));271 // 会话ID,每次连接生成一个,22e4db34-2daa-4c06-9285-742058f87deb272 //driver.getAppStringMap();273 //Map<String, String> stringMap = driver.getAppStringMap(Locale.getDefault().getLanguage());274 //Map<String, String> stringMap = driver.getAppStringMap();275 //Set<String> keys = stringMap.keySet();276 277 //keys.forEach(x -> System.out.println(stringMap.get(x)));278 279 //ScreenOrientation orientation = driver.getOrientation();280 281 MobileElement element = null;282 // 启动应用283 //driver.launchApp();284 //driver.findElementByClassName("cpt-choose-box cpt-choose-box-pop");285 //element = driver.findElementByClassName("android.widget.ImageView");286 //element = driver.findElementByXPath("//div[@class=' cpt-choose-box cpt-choose-box-pop']");287 //System.out.println(element.getText());288 //driver.getKeyboard().pressKey("A");289 290 291 //driver.rotation();292 293 //System.out.println(orientation.name() + ", " + orientation.ordinal());294 // 休眠若干秒,等待APP准备就绪295 TimeUnit.SECONDS.sleep(1);296 //driver.close();297 List<MobileElement> elements = null;298 //driver.closeApp();299/* By by = By.xpath("//android.widget.TextView[@resource-id='ctrip.android.view:id/tab_title']");300 elements = driver.findElements(by);301 System.out.println(elements.size());302 303 for (MobileElement e : elements) {304 System.out.println(e.getText());305 }*/306 By by = null;307 // 点击第一个元素,账号输入框308 by = By.xpath("//android.widget.EditText");309 elements = driver.findElements(by);310 // 点击311 //element.click();312 //element.sendKeys("15018750788");313 314 elements.get(0).sendKeys("15018750787");315 316 elements.get(1).sendKeys("a123b456");317 318 by = By.xpath("//android.widget.RelativeLayout[@resource-id='ctrip.android.login:id/rlLoginBtn']/android.widget.Button");319 element = driver.findElement(by);320 element.click();321 //322 323/* for (MobileElement e : elements) {324 System.out.println(e.getText());325 }*/326 327 328 329 //driver.getKeyboard().pressKey("15018750711");330 331 332 // 重置APP,清空缓存333 //driver.resetApp();334 // 335 //driver.quit();336 337 338 339 } catch (Exception e) {340 log.error("testFindByXPath =====> ", e);341 }342 }343 344 /**345 * 346 * 描述: 347 * @author qye.zheng348 * 349 */350 //@DisplayName("test")351 @Test352 public void testGetAppString() {353 try {354 //File app = new File("C:\\Users\\dell\\AppData\\Local\\Temp\\ctripA.apk");355 URL serverUrl = new URL("http://127.0.0.1:4723/wd/hub");356 AppiumDriver<MobileElement> driver = new AppiumDriver<>(serverUrl, capabilities(true));357 // 会话ID,每次连接生成一个,22e4db34-2daa-4c06-9285-742058f87deb358 //driver.getAppStringMap();359 //Map<String, String> stringMap = driver.getAppStringMap(Locale.getDefault().getLanguage());360 //Map<String, String> stringMap = driver.getAppStringMap();361 //Set<String> keys = stringMap.keySet();362 363 //keys.forEach(x -> System.out.println(stringMap.get(x)));364 365 //ScreenOrientation orientation = driver.getOrientation();366 367 MobileElement element = null;368 // 启动应用369 //driver.launchApp();370 driver.findElementByClassName("cpt-choose-box cpt-choose-box-pop");371 //element = driver.findElementByClassName("android.widget.ImageView");372 //element = driver.findElementByXPath("/div[@class=' cpt-choose-box cpt-choose-box-pop']");373 System.out.println(element.getText());374 //driver.getKeyboard().pressKey("A");375 376 377 //driver.rotation();378 379 //System.out.println(orientation.name() + ", " + orientation.ordinal());380 381 //driver.close();382 383 //driver.closeApp();384 385 386 // 重置APP,清空缓存387 //driver.resetApp();388 // 389 //driver.quit();390 391 392 393 } catch (Exception e) {394 log.error("testAppiumClient =====> ", e);395 }396 }397 398 /**399 * 400 * 描述: 401 * @author qye.zheng402 * 403 */404 //@DisplayName("test")405 @Test406 public void testAppiumDriver() {407 try {408 //File app = new File("C:\\Users\\dell\\AppData\\Local\\Temp\\ctripA.apk");409 URL serverUrl = new URL("http://127.0.0.1:4723/wd/hub");410 AppiumDriver<MobileElement> driver = new AppiumDriver<>(serverUrl, capabilities(true));411 // 会话ID,每次连接生成一个,22e4db34-2daa-4c06-9285-742058f87deb412 413 //localService.stop();414 415 // 退出目标 APP416 //driver.quit();417 418 } catch (Exception e) {419 log.error("testAppiumDriver =====> ", e);420 }421 }422 423 /**424 * 425 * 描述: 426 * @author qye.zheng427 * 428 */429 //@DisplayName("test")430 @Test431 public void testTouch() {432 try {433 //File app = new File("C:\\Users\\dell\\AppData\\Local\\Temp\\ctripA.apk");434 URL serverUrl = new URL("http://127.0.0.1:4723/wd/hub");435 AppiumDriver<MobileElement> driver = new AppiumDriver<>(serverUrl, capabilities(true));436 437 // 438 TouchAction<AndroidTouchAction> action = new TouchAction<>(driver);439 MobileElement element = null;440 //element = driver.findElementById("ba4defec-e8dd-43f0-9672-03235e355cbb");441 //element = driver.findElementByXPath("/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout[1]/android.widget.FrameLayout/android.widget.FrameLayout[1]/android.view.ViewGroup/android.widget.FrameLayout[1]/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout[1]/android.widget.LinearLayout/android.widget.FrameLayout/android.support.v4.view.ViewPager/android.widget.RelativeLayout/android.widget.ImageView");442 //action.tap(TapOptions.tapOptions()).perform();443 //element.click();444 Point point = null;445 // [0,0][720,393]446 point = new Point(720, 393);447 //448 action.press(PointOption.point(point)).perform();449 450 451 // 释放452 //action.release();453 454 // 取消455 //action.cancel();456 457 //localService.stop();458 459 // 退出目标 APP460 //driver.quit();461 462 } catch (Exception e) {463 log.error("testTouch =====> ", e);464 }465 }466 467 /**468 * 469 * 描述: 470 * @author qye.zheng471 * 472 */473 //@DisplayName("test")474 @Test475 public void testAppiumServiceBuilder() {476 try {477 URL appiumServerUrl = new URL("http://127.0.0.1:4723/wd/hub");478 //AppiumDriver<MobileElement> driver = new AppiumDriver<>(appiumServerUrl, capabilities);479 // 会话ID,每次连接生成一个,22e4db34-2daa-4c06-9285-742058f87deb480 //System.out.println(driver.getSessionId());481 482 // 设备时间483 // System.out.println(driver.getDeviceTime());484 AppiumServiceBuilder builder = new AppiumServiceBuilder().withCapabilities(capabilities(true))485 .withIPAddress("127.0.0.1").usingPort(4723);486/* builder.usingPort(4723);487 builder.withIPAddress("127.0.0.1");488 builder.score(capabilities);*/489 // 490 AppiumDriverLocalService localService = builder.build();491 492 //localService.start();493 //localService.start();494 495 //localService.stop();496 497 } catch (Exception e) {498 log.error("testAppiumServiceBuilder =====> ", e);499 }500 }501 502 /**...

Full Screen

Full Screen

AppiumServiceBuilder.java

Source:AppiumServiceBuilder.java Github

copy

Full Screen

...81 withEnvironment(System.getenv());82 }83 /**84 * Provides a measure of how strongly this {@link DriverService} supports the given85 * {@code capabilities}. A score of 0 or less indicates that this {@link DriverService} does not86 * support instances of {@link org.openqa.selenium.WebDriver} that require {@code capabilities}.87 * Typically, the score is generated by summing the number of capabilities that the driver88 * service directly supports that are unique to the driver service (that is, things like89 * "{@code proxy}" don't tend to count to the score).90 * Higher the score, higher the possibility of getting grid sessions created sooner.91 */92 @Override93 public int score(Capabilities capabilities) {94 int score = 0;95 if (capabilities.getCapability(PLATFORM_NAME) != null) {96 score++;97 }98 String browserName = capabilities.getBrowserName();99 if (Browser.CHROME.is(browserName) || browserName.equalsIgnoreCase(MobileBrowserType.ANDROID)100 || Browser.SAFARI.is(browserName)) {101 score++;102 }103 return score;104 }105 private static File validatePath(@Nullable String fullPath, String errMsg) {106 if (fullPath == null) {107 throw new InvalidServerInstanceException(errMsg);108 }109 File result = new File(fullPath);110 if (!result.exists()) {111 throw new InvalidServerInstanceException(errMsg);112 }113 return result;114 }115 private static File findBinary(String name, String errMsg) {116 return validatePath(new ExecutableFinder().find(name), errMsg);117 }...

Full Screen

Full Screen

SelendroidWidgetTest.java

Source:SelendroidWidgetTest.java Github

copy

Full Screen

...67 @Override public void checkACommonWidget() {68 assertTrue(rottenTomatoesApp.getSimpleMovieCount() >= 1);69 Movie movie = rottenTomatoesApp.getASimpleMovie(0);70 assertTrue(!StringUtils.isBlank(movie.title()));71 assertTrue(!StringUtils.isBlank(movie.score()));72 assertNotNull(movie.getPoster());73 movie.goToReview();74 driver.getPageSource(); //forcing the refreshing hierarchy75 rottenTomatoesApp.checkSimpleReview();76 }77 @Override78 @Test public void checkAnAnnotatedWidget() {79 assertTrue(rottenTomatoesApp.getAnnotatedMovieCount() >= 1);80 Movie movie = rottenTomatoesApp.getAnAnnotatedMovie(0);81 assertTrue(!StringUtils.isBlank(movie.title()));82 assertTrue(!StringUtils.isBlank(movie.score()));83 assertNotNull(movie.getPoster());84 movie.goToReview();85 driver.getPageSource(); //forcing the refreshing hierarchy86 rottenTomatoesApp.checkAnnotatedReview();87 }88 @Override89 @Test public void checkAnExtendedWidget() {90 assertTrue(rottenTomatoesApp.getExtendeddMovieCount() >= 1);91 Movie movie = rottenTomatoesApp.getAnExtendedMovie(0);92 assertTrue(!StringUtils.isBlank(movie.title()));93 assertTrue(!StringUtils.isBlank(movie.score()));94 assertNotNull(movie.getPoster());95 movie.goToReview();96 driver.getPageSource(); //forcing the refreshing hierarchy97 rottenTomatoesApp.checkExtendedReview();98 }99 @Override100 @Test public void checkTheLocatorOverridingOnAWidget() {101 duration.setTime(5);102 try {103 assertTrue(rottenTomatoesApp.getFakedMovieCount() == 0);104 } catch (Exception e) {105 if (!NoSuchElementException.class.isAssignableFrom(e.getClass())) {106 throw e;107 }...

Full Screen

Full Screen

SelendroidCombinedWidgetTest.java

Source:SelendroidCombinedWidgetTest.java Github

copy

Full Screen

...69 @Override public void checkACommonWidget() {70 assertTrue(rottenTomatoes.getSimpleMovieCount() >= 1);71 Movie movie = rottenTomatoes.getASimpleMovie(0);72 assertTrue(!StringUtils.isBlank(movie.title()));73 assertTrue(!StringUtils.isBlank(movie.score()));74 assertNotNull(movie.getPoster());75 movie.goToReview();76 driver.getPageSource(); //forcing the refreshing hierarchy77 rottenTomatoes.checkSimpleReview();78 }79 @Override80 @Test public void checkAnAnnotatedWidget() {81 assertTrue(rottenTomatoes.getAnnotatedMovieCount() >= 1);82 Movie movie = rottenTomatoes.getAnAnnotatedMovie(0);83 assertTrue(!StringUtils.isBlank(movie.title()));84 assertTrue(!StringUtils.isBlank(movie.score()));85 assertNotNull(movie.getPoster());86 movie.goToReview();87 driver.getPageSource(); //forcing the refreshing hierarchy88 rottenTomatoes.checkAnnotatedReview();89 }90 @Override91 @Test public void checkAnExtendedWidget() {92 assertTrue(rottenTomatoes.getExtendeddMovieCount() >= 1);93 Movie movie = rottenTomatoes.getAnExtendedMovie(0);94 assertTrue(!StringUtils.isBlank(movie.title()));95 assertTrue(!StringUtils.isBlank(movie.score()));96 assertNotNull(movie.getPoster());97 movie.goToReview();98 driver.getPageSource(); //forcing the refreshing hierarchy99 rottenTomatoes.checkExtendedReview();100 }101 @Override102 @Test public void checkTheLocatorOverridingOnAWidget() {103 duration.setTime(5);104 try {105 assertTrue(rottenTomatoes.getFakedMovieCount() == 0);106 } catch (Exception e) {107 if (!NoSuchElementException.class.isAssignableFrom(e.getClass())) {108 throw e;109 }...

Full Screen

Full Screen

SmokeTest.java

Source:SmokeTest.java Github

copy

Full Screen

...44 MobileElement listView = driver.findElement(By.className("android.widget.ListView"));45 List<MobileElement> listViewItems = driver.findElements(By.xpath("//android.widget.ListView/android.widget.RelativeLayout"));46 for (int i = 0; i < 3; i++) {47 listViewItems.get(i).tap(1, 500);48 MobileElement score = driver.findElement(By.id("com.codepath.example.rottentomatoes:id/tvAudienceScore"));49 System.out.println("Score: " + score.getText());50 driver.navigate().back();51 listView = driver.findElement(By.className("android.widget.ListView"));52 }53 }54 @AfterClass55 public static void afterClass() {56 if (service != null)57 service.stop();58 }59}...

Full Screen

Full Screen

score

Using AI Code Generation

copy

Full Screen

1package appium;2import io.appium.java_client.service.local.AppiumServiceBuilder;3public class AppiumServiceBuilderExample {4 public static void main(String[] args) {5 AppiumServiceBuilder builder = new AppiumServiceBuilder();6 builder.withIPAddress("

Full Screen

Full Screen

score

Using AI Code Generation

copy

Full Screen

1appiumServiceBuilder.score(5);2appiumDriverLocalService.startAppium();3appiumDriverLocalService.stopAppium();4appiumDriverLocalService.startAppium();5appiumDriverLocalService.stopAppium();6appiumDriverLocalService.startAppium();7appiumDriverLocalService.stopAppium();8appiumDriverLocalService.startAppium();9appiumDriverLocalService.stopAppium();10appiumDriverLocalService.startAppium();11appiumDriverLocalService.stopAppium();12appiumDriverLocalService.startAppium();13appiumDriverLocalService.stopAppium();

Full Screen

Full Screen

score

Using AI Code Generation

copy

Full Screen

1import java.io.IOException;2import io.appium.java_client.service.local.AppiumDriverLocalService;3import io.appium.java_client.service.local.AppiumServiceBuilder;4public class AppiumServer {5 public static void main(String[] args) throws IOException, InterruptedException {6 AppiumDriverLocalService service=AppiumDriverLocalService.buildService(new AppiumServiceBuilder().usingAnyFreePort());7 service.start();8 System.out.println("Appium server is started");9 System.out.println("port number is "+service.getUrl().getPort());10 Thread.sleep(5000);11 service.stop();12 System.out.println("Appium server is stopped");13 }14}15import java.io.IOException;16import io.appium.java_client.service.local.AppiumDriverLocalService;17import io.appium.java_client.service.local.AppiumServiceBuilder;18public class AppiumServer {19 public static void main(String[] args) throws IOException, InterruptedException {20 AppiumDriverLocalService service=AppiumDriverLocalService.buildService(new AppiumServiceBuilder().usingPort(4723));21 service.start();22 System.out.println("Appium server is started");23 System.out.println("port number is "+service.getUrl().getPort());24 Thread.sleep(5000);25 service.stop();26 System.out.println("Appium server is stopped");27 }28}29import java.io.IOException;30import io.appium.java_client.service.local.AppiumDriverLocalService;31import io.appium.java_client.service.local.AppiumServiceBuilder;32public class AppiumServer {33 public static void main(String[] args) throws IOException, InterruptedException {

Full Screen

Full Screen

score

Using AI Code Generation

copy

Full Screen

1public class AppiumServiceBuilder {2public int score() {3return 100;4}5}6public class AppiumServiceBuilder {7public int score() {8return 100;9}10}11public class AppiumServiceBuilder {12public int score() {13return 100;14}15}16public class AppiumServiceBuilder {17public int score() {18return 100;19}20}21public class AppiumServiceBuilder {22public int score() {23return 100;24}25}26public class AppiumServiceBuilder {27public int score() {28return 100;29}30}31public class AppiumServiceBuilder {32public int score() {33return 100;34}35}36public class AppiumServiceBuilder {37public int score() {38return 100;39}40}41public class AppiumServiceBuilder {42public int score() {43return 100;44}45}46public class AppiumServiceBuilder {47public int score() {48return 100;49}50}51public class AppiumServiceBuilder {52public int score() {53return 100;54}55}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run io.appium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful