Detailed explanation in one article! Appium automated testing

Table of contents

Foreword:

Appinum prerequisite knowledge

Andriod SDK

Element acquisition—UI Automator

adb command practice

adb common commands

summary

Package and Activity

Activity page layout elements

monkey profile

monkey event

Introduction to Operational Events

monkey parameter

Event class parameters

Constraint class parameters

Debug class parameters

Comprehensive Case of Monkey Parameter Application

Introduction to the Monkey Scripting API

monkey log management

monkeyrunner

MonkeyRunner API

Appius

Appium components

Capability

Capability Launch App Demo

appium element positioning

UIAutomator

Toast

Screenshots


Foreword:

Appium is an open source tool for automating mobile device applications. It has cross-platform features and can be tested on various mobile devices such as iOS and Android. Appium provides a set of APIs, developers can use a variety of programming languages ​​to write automation scripts.

Appinum prerequisite knowledge

app types and differences

Andriod SDK

Element acquisition—UI Automator

adb command practice

Android Debug Bridge

adb (Android Debug Bridge) is a general-purpose command-line tool that allows you to communicate with an emulator instance or a connected Android device. It facilitates various device operations such as installation and commissioning of applications.

Tips: Find the adb tool in android_sdk/platform-tools/, and then configure the environment variable according to its specific path. Then start cmd and enter 'adb' to see if the configuration is successful.

How adb works

When starting an adb client, the client first checks for an already running adb server process. If not, it will start the server process. When the server starts, it binds to local TCP port 5037 and listens for commands sent from adb clients—all adb clients use port 5037 to communicate with the adb server.

enable adb debugging

To use adb on a device connected via USB, you must enable USB debugging in the device system settings (under Developer options).

On devices running Android 4.2 and higher, the Developer options screen is hidden by default. To bring it up, go to Settings > About phone and tap the Build number seven times. Go back to the previous screen, at the bottom you can find Developer options.

Note: When you connect a device running Android 4.2.2 or higher, a dialog will appear asking you to accept the RSA key to allow debugging on this computer. This security mechanism protects user devices by ensuring that USB debugging and other ADB commands can only be performed if you are able to unlock the device and confirm the dialog.

adb common commands

Check adb version

adb  version

Connect to the Yeshen simulator (the simulator and the real machine connection are demonstrated here respectively)

adb connect 127.0.0.1:62001

Tips:

The ports of the Yeshen simulator are regular, the first simulator port is 62001, the second simulator port is 62025, the third is 62025+1, and so on.

  • Emulator 1: Android 4.4.2 Address: 127.0.0.1:62001

  • Emulator 2: Andriod 5.1.1 Address: 127.0.0.1:62025

  • More details: Detailed explanation of adb commands for Yeshen Android emulator

View device information

adb devices

If the following prompt appears:

adb server version (31) doesn't match this client (36); killing...
  • Reason: The adb version is wrong, the version of the Android SDK is inconsistent with the adb version of the emulator

  • Solution: Replace the adb of the Android SDK with the adb of the emulator. Emulator adb path: {Installation Path}\Nox\bin

adb shell

The bottom layer of the android device is the linux system. The shell is the character interactive interface of the linux system.

adb shell 
#Enter the specified device shell 
adb -s 127.0.0.1:62001 shell 
 
#Exit adb shell 
exit

After entering the adb shell, there are two status displays: # means root authority, $ means no root authority

root@android:/ #
 
shell@mx4:/ $

The root user is the only super administrator in the system, and it has the same authority as the operating system. Some apps that require root privileges, such as ad blocking, require root privileges to uninstall apps pre-installed on the system. But the problem is that root is more capable than the Windows system administrator, enough to delete most of the files in the entire system, causing the system to be completely destroyed and cannot be used again. Therefore, it is very dangerous to use root to perform improper operations. If it is mild, it may crash, and if it is serious, it may not even be able to boot. Therefore, in Unix, Linux, and Android, root is generally not recommended unless it is really needed.

Install the apk on the device

adb install | -r <apkName> -r Overwrite the original installation file -s You can specify the device 
eg: 
 
#Default installation 
adb install "C:\Users\Shuqing\Desktop\Appium Automated Test Tutorial\wandoujia.apk" 
 
#Overwrite installation 
adb install -r "C:\Users\Shuqing\Desktop\Appium Automated Test Tutorial\wandoujia.apk" 
 
#Specify the device to install 
adb -s 127.0.0.1:62001 install C:\Users\Shuqing\Desktop\Appium\kaoyan3.1.0.apk Automated Testing Tutorial\wandoujia.apk"

If you encounter an error: Failure [INSTALL_FAILED_INVALID_URI]

Solution: Execute the following command on the cmd command line:

  • The first step, adb remount

  • The second step, adb shell

  • The third step, cd /data

  • The fourth step, chmod 777 local

  • Reinstall apk, ok.

uninstall apk

1. First enter the /data/app directory of the device to find the app package name

adb shell
cd /data/app/

2. Execute the command to delete

adb uninstall | -k <apkName> uninstall software 
 
adb uninstall com.wandoujia.phoenix2

Tips: After installation, the package name system will add numbers such as -1 at the end, which must be removed to successfully uninstall. The software name is the package name, do not include .apk

-k Add the -k parameter to uninstall the software but keep the configuration and cache files.

View the application package name installed on the device

adb shell pm list package

file read write

Write files from PC to device

adb push <local path> <device path> 
eg: 
adb push C:\Users\Shuqing\Desktop\kyb.txt /sdcard 
C:\Users\Shuqing\Desktop\kyb.txt: 1 file pushed. 0.1 MB/s ( 462 bytes in 0.005s)

Read files from device to PC

adb pull <remote> <local>
eg:
adb pull /sdcard/server.log  C:\Users\Shuqing\Desktop
/sdcard/server.log: 1 file pulled. 0.0 MB/s (196 bytes in 0.004s)

Note: Due to permission issues, you cannot directly pull to the root directory of the computer disk, otherwise an error will be reported:

C:\Users\Shuqing>adb pull /sdcard/server.log  D:\\
adb: error: cannot create file/directory 'D:\\': No such file or directory

Screenshots

$ adb shell screencap /sdcard/screen.png
adb pull /sdcard/screen.png  C:\Users\Shuqing\Desktop

adb service startup and shutdown

adb kill-server close adb service 
adb start-server open adb service

Tips: If port 5037 is occupied, you can use the following command to release the port

C:\Users\Shuqing> netstat -ano | findstr "5037"
  TCP    127.0.0.1:5037         0.0.0.0:0              LISTENING       11072
  TCP    127.0.0.1:5037         127.0.0.1:59519        TIME_WAIT       0
 
taskkill -f -pid XXX

summary

  1. adb is a very important tool for automation

  2. At present, many PC client mobile assistants are also packaged based on the adb connection principle.

  3. Commonly used adb commands can be encapsulated into bat commands, which can be run at any time. like:

adbdevices.bat

adb devices
pause

AdbConnect.bat

adb connect 127.0.0.1:62025
adb devices
pause

Package and Activity

adb shell pm list package View all package packages

Package

Package package. It's just that this Package is unique in our app, just like your ID number. When we do app automation, we need to know its Package. If we know the Package, we also know which app we need to automate. Note that the package name is different from the .apk file.

Activity

In Android, activity is the foundation of all programs, and the process of all programs runs in activity. Activity can be regarded as the most frequently encountered by developers, and it is also one of the most basic modules in android. In the Android program, the activity generally represents a screen of the mobile phone screen. If the mobile phone is compared to a browser, then the activity is equivalent to a web page. You can add some Button, Checkbox and other controls in the activity, you can see that the concept of activity is quite similar to the concept of web page.

Generally, an android application is composed of multiple activities, and these multiple activities can jump to each other. For example, after pressing a Button button, it may jump to other activities, which is slightly different from webpage jumps, and the jumps between activities may return values.

Tips: The life cycle of activity: "generate, run, destroy", but many methods onCreate (creation), onStart (activation), onResume (resume), onPause (pause), onStop (stop), onDestroy ( Destroy), onRestart (restart).

Activity acquisition

R&D provided

aapt

aapt is the Android Asset Packaging Tool, in the build-tools directory of the SDK. The tool can view, create, update archive attachments in ZIP format (zip, jar, apk). Resource files can also be compiled into binary files. Get the command as follows:

aapt dump badging xxxx.apk
aapt dump badging xxxx.apk | find "launchable-activity"

You can configure appt to the environment variable (Path in the system variable), so that it is more convenient to run, appt path: \Andriod_SDK\build-tools{version}

Activity page layout elements

FrameLayout

FrameLayout is the simplest layout. All controls placed in the layout are stacked in the upper left corner of the screen according to the hierarchy. Controls added later overwrite previous controls.

LinearLayout

LinearLayout arranges child elements in vertical or horizontal order, and each child element is located after the previous element. If it is arranged vertically, it will be a structure with N rows and one column, and each row will only have one element, regardless of the width of the element; if it is arranged horizontally, it will be a structure with one row and N columns. If you build a structure with two rows and two columns, the usual way is to arrange two elements vertically first, and each element contains a LinearLayout for horizontal arrangement.

RelativeLayout

RelativeLayout allows child elements to specify their position relative to their parent or sibling elements, which is one of the most commonly used layout methods in actual layout.

AbsoluteLayout

AbsoluteLayout is an absolute position layout. The android:layout_x and android:layout_y attributes of the child elements in this layout will take effect and are used to describe the coordinate position of the child element. The upper left corner of the screen is the coordinate origin (0,0). The first 0 represents the abscissa, and the value increases when moving to the right, and the second 0 represents the ordinate, and the value increases when moving downward. Child elements in this layout can overlap each other. In actual development, this layout format is usually not used,

TableLayout

TableLayout is a table layout, suitable for the layout format of N rows and N columns. A TableLayout consists of many TableRows, and a TableRow represents a row in the TableLayout.

TextView

Usually used to display text.

ImageView

Usually used to display pictures.

monkey profile

Introduction to Monkey

In the field of Android's official automated testing, there is a very famous "monkey" called Monkey. Once this "monkey" is started, it will make the Android application under test jump around like a monkey and run around. People often use this "monkey" to stress test the program under test, check and evaluate the stability of the program under test.

Moneky path

The Monkey program comes with the Android system. Its startup script is the Monkey file located in the /system/bin directory of the Android system, and its jar package is the Monkey.jar file located in the /system/framework directory of the Android system. Users mainly start Monkey through the adb command. When Monkey is running, it will generate a pseudo-random event stream according to the configuration of command line parameters, and execute corresponding test events on the Android device. At the same time, Monkey will also monitor the test system, and will perform special processing when the following three situations occur:

  • If Monkey is limited to run on a specific package, when it detects an operation that attempts to switch to other packages, it will be blocked.

  • If the application crashes or receives any out-of-control exception, Monkey will record the corresponding error log, and judge whether to stop or continue to run according to the command line parameters.

  • If an application not responding (application not responding) error occurs in the application, Monkey will record the corresponding error log, and judge whether to stop or continue to run according to the command line parameters.

  • According to the selected different levels of feedback information, you can also see the execution process report and generated events in Monkey.

Monkey startup steps

  1. connect mobile device

  2. After the connection is successful, enter the command

adb shell

Enter the specified directory

cd /system/bin

4. Enter the monkey command and see the following prompt, indicating that the startup is successful.

Force close the monkey

  1. adb shell ps View all running processes

  2. Find out com.android.commands.monkey process PID

  3. adb shell kill pid kill monkey process

monkey command

The monkey command format is as follows:

$ adb shell monkey [options] <event-count>
  • [options] refers to the parameters that monkey can pass in, which is optional (if options are not specified, Monkey will start in no feedback mode, and send events to all packages installed in the target environment arbitrarily)

  • Refers to the number of events sent randomly. For example: Entering 100 means executing 100 pseudo-random events, which is a mandatory option.

monkey event

Touch event, gesture time, two-finger zoom event, track event, screen rotation event, basic navigation event, main navigation event, system key event, start Activity event, keyboard event, other types of events

Introduction to Operational Events

The random event stream executed by Monkey contains 11 major events, namely touch event, gesture event, two-finger zoom event, track event, screen rotation event, basic navigation event, main navigation event, system button event, start Activity event, keyboard events, other types of events. Monkey uses these 11 major events to simulate the user's routine operations and conduct a stability test on the mobile app. Let's take a closer look at these 11 major events.

1. Touch events

A touch event refers to the operation of pressing and lifting somewhere on the screen, and its event percentage can be configured through the –pct-touch parameter. It can be seen from the log that Monkey executes the external output of this event. This event consists of a set of Touch (ACTION_DOWN) and Touch (ACTION_UP) events, and the actual operation seen on the mobile phone is similar to a click.

2. Gesture events

Gesture events refer to the operations of pressing, moving randomly, and lifting somewhere on the screen, that is, straight-line sliding operations. Its event percentage can be configured by the --pct-motion parameter.

This event is composed of an ACTION_DOWN event, a series of ACTION_MOVE events and an ACTION_UP event. The actual operation seen on the mobile phone is a straight-line sliding operation without turning.

3. Two-finger zoom event

The two-finger zoom event refers to the operation of pressing two places on the screen at the same time, moving at the same time, and finally lifting at the same time, that is, the zoom in and out gesture operation on the smart phone. Its event percentage can be configured by the --pct-pinchzoom parameter. From the external output log of Monkey executing this event, we can see:

The event starts with an ACTION_DOWN event and an ACTION_POINTER_DOWN event, which simulates two fingers clicking at the same time; the middle is a series of ACTION_MOVE events, that is, two fingers slide linearly on the screen at the same time; the end is an ACTION_POINTER_UP event and an ACTION_UP Event composition, that is, two fingers are released at the same time.

4. Track events

Track events consist of one or more random movements, sometimes followed by clicks. A long time ago, Android phones had a trackball, and this event is a simulated trackball operation. Most of the current mobile phones do not have a trackball, but the trackball event includes a curve sliding operation. If the program under test needs a curve sliding, this parameter can be selected. Its event percentage can be configured by the --pct-trackball parameter. From the external output log of Monkey executing this event, we can see:

This event is composed of a series of Trackball (ACTION_MOVE) events. Observe the operation on the mobile phone, that is, a series of curved sliding operations.

5. Screen rotation event

The screen rotation event is a hidden event, which is not recorded in the official Android documentation. It actually simulates the horizontal and vertical screen switching of Android phones. Its event percentage can be configured through the --pct-rotation parameter. From the external output log of Monkey executing this event, we can see: [Code] This event is composed of a rotation event, where degree represents the direction of rotation, clockwise rotation, 0 represents the direction of rotation of 90 degrees, and 1 represents the direction of rotation of 180 degrees Direction, 2 means the direction of rotation 270 degrees, 3 means the direction of rotation 360 degrees. During the execution process, you can see that the mobile phone screen is constantly switching between the horizontal and vertical screens.

6. Basic Navigation Events

The basic navigation event refers to the operation of clicking the up, down, left, and right buttons of the direction input device. Now there are few up, down, left, and right buttons on the mobile phone, and this kind of event is generally used less. Its event percentage can be configured by the --pct-nav parameter. From the external output log of Monkey executing this event, we can see:

The event is composed of a Key (ACTION_DOWN) and a Key (ACTION_UP), and the four direction keys of up, down, left, and right are clicked.

7. Main Navigation Events

The primary navigation event refers to the operation of clicking the "primary navigation" button. These buttons usually cause actions in the UI interface, such as the middle key of the keyboard, the back button, and the menu button. Its event percentage can be configured by the --pct-majornav parameter. From the external output log of Monkey executing this event, we can see: [Code] This event is composed of a Key (ACTION_DOWN) and a Key (ACTION_UP), and the clicked keys are the middle key and the menu key.

8. System key events

The system button event refers to the operation of clicking the button reserved by the system, such as clicking the Home button, the return button, and the volume adjustment button. Its event percentage can be configured through the --pct-syskeys parameter. From the external output log of Monkey executing this event, we can see: [Code] This event is composed of a Key (ACTION_DOWN) and a Key (ACTION_UP), and the clicks are the above-mentioned several system keys.

9. Start the Activity event

The start Activity event refers to the operation of starting an Activity on the mobile phone. At random time intervals, Monkey will execute a startActivity() method as a way to cover as much as possible all activities in the package under test. Its event percentage can be configured by the --pct-appswitch parameter. From the external output log of Monkey executing this event, we can see: [Code] This event is composed of a Switch operation. From the perspective of the mobile phone, the above operation actually opens a com.android of the application com.android.settings Activity interface of .settings.Settings.

10. Keyboard events

Keyboard events are mainly keyboard-related operations. For example, click on the input box, the keyboard pops up, click on an area outside the input box, and the keyboard retracts. Its event percentage can be configured by the --pct-flip parameter. You can see from the log that Monkey executes the event and outputs externally: [Code] As shown in the log, here is mainly the opening and closing operation of the keyboard.

11. Other types of events

Other types of events include all other events except the above-mentioned 10 events, such as key presses, buttons on other uncommonly used devices, etc. The event percentage can be configured through the –pct-anyevent parameter. From the external output log of Monkey executing this event, we can see: [Code] This event is composed of a Key (ACTION_DOWN) and a Key (ACTION_UP), and the clicked keys are other system keys, such as letter keys and number keys wait. Because mobile phones rarely have letter keys or number keys, this event is generally used less.

monkey parameter

Parameter Classification

  • General Class Parameters

  • Event class parameters

  • Constraint class parameters

  • Debug class parameters

General Class Parameters

General class parameters include help parameters and log information parameters. The help parameter is used to output instructions for using the Monkey command; the log information parameter divides the log into three levels, and the higher the level, the more detailed the log information.

1. Help class parameters

monkey -h

2. Log level

$ adb shell monkey -v <event-count>

-v: Print out log information, each -v will increase the level of feedback information. The more -v, the more detailed the log information, but currently supports up to 3 -v, namely:

Event class parameters

The function of the event parameter is to regulate the random event so that it operates according to the setting, such as setting the percentage of various events, setting the seed value used for event generation, and so on. The frequency parameter mainly limits the time interval of event execution.

1. Execute the specified script

$ adb shell monkey -f <scriptfile> <event-count>
 
eg:
$ adb shell monkey -f /mnt/sdcard/test1

2. Pseudo-random number generation seed value

Use the -s command to repeat the previous pseudo-random operation. Every time a pseudo-random event operation is performed, a seed value will be generated by default 
$ adb shell monkey -s <seed> <event-count> 
 
eg: 
$ adb shell monkey -s 666 100

3. Set the interval If you want to add a fixed interval between each command, you can use the --throttle (note that the front is –) command.

$ adb shell monkey --throttle <milliseconds>
eg:
$ adb shell monkey --throttle 3000  5

–throttle: Followed by time, the unit is ms (), indicating a fixed delay between events (that is, the time between execution of each instruction). If this option is not connected, monkey will not delay.

4. Adjust touch event percentage

Remember to use --pct-touch if you wish to adjust the percentage of touch events.

$ adb shell monkey --pct-touch
eg:
$ adb shell monkey -v -v --pct-touch 100 200

–pct-touch: Percentage of subsequent touch events

Note: A touch event is not just a button, it generally refers to a down-up event that occurs at a certain position.

5. Adjust the percentage of gesture events

$ adb shell monkey --pct-motion
eg:
$ adb shell monkey -v -v --pct-motion 100 200

6. Adjust the percentage of app launch events

Remember to use --pct-app-switch if you wish to adjust the percentage of app launch events.

$ adb shell monkey --pct-appswtich <percent>

–pct-appswitch: Followed by the percentage of application start events.

Application startup events (activity launches) are commonly known as opening applications, by calling the startActivity() method to open all applications under the package to the maximum extent.

7. Adjust the screen rotation event percentage

$ adb shell monkey --pct-rotation <percent>

--pct-rotation is followed by the scale value of the screen rotation event.

8. Other parameters

Constraint class parameters

**1.** Package Constraints

-p: Followed by one or more package names (), if the application needs to access activities in other packages, the related packages also need to be specified here. If no package is specified, monkey will allow the system to start activities in all packages.

$ adb shell monkey -p <allowed-package-name> <event-count>
eg:
$ adb shell monkey -p com.tal.kaoyan 500
 
$ adb shell monkey -p com.tal.kaoyan -p com.tencent.mm 500

2. activity**** class constraints

If you want to limit the monkey to one or a few categories, use the following command:

adb shell monkey -c <main-category> <event-count>

The following command means to run the Activity of the Intent.CATEGORY_LAUNCHER category and send 1000 random events.

$ adb shell monkey -c Intent.CATEGORY_LAUNCHER  1000

Debug class parameters

**1.**Continue to send events after the application crashes

If you want monkey to continue sending events after the application crashes, you need to use the --ignore-crashes command

$ adb shell monkey --ignore-crashes <event-count>

After setting this option, when the application crashes or a runaway exception occurs, monkey will continue to run until the count is complete. If this option is not set, monkey will stop running when encountering the above crashes or exceptions.

**2.** Timeout error to continue sending events

If you want monkey to continue sending events after any timeout errors occur, you need to use the --ignore-timeouts command.

$ adb shell monkey --ignore-timeouts

–ignore-timeouts: After setting this option, when any timeout error (such as ANR, Application Not Responding) occurs in the application, monkey will continue to run until the count is completed. If you don't set this option, monkey will stop running when encountering such timeout dialogs.

**3.**Continue to send events after an application permission error occurs

If you want monkey to continue sending events after an application permission error occurs, you need to use the --ignore-security-exceptions command.

$ adb shell monkey --ignore-security-exceptions

--ignore-security-exceptions: After setting this option, when any permission error occurs in the application (such as launching an Activity that requires certain permissions), monkey will continue to run until the count is complete. If this option is not set, monkey will stop running on such permission errors.

4. Other

Comprehensive Case of Monkey Parameter Application

testing scenarios

Test the Android version of the Kaoyanbang app. The test hopes to use Monkey to simulate random user operations, and check whether the application under test is abnormal (application crash or unresponsive).

demand analysis

1. The test is a specified application, so you need to use -p to specify the package name of the tested app: com.tal.kaoyan

2. The purpose of this test is to simulate user operations, so it is necessary to make the events executed by Monkey as close as possible to the user's routine operations, so that the possible problems that may occur during the user's use can be found to the greatest extent. So some adjustments need to be made to the percentage of events executed by Monkey:

Touch events and gesture events are the most common operations for users, so adjust the proportion of these two events to 40% and 25% through –pct-touch and –pct-motion; the target application contains multiple activities, in order to cover Most of the activities, so adjust the proportion of activity switching events to 10% through –pct-appswitch; the tested application has many problems of switching between horizontal and vertical screens in the test, this scene must also be paid attention to, so through – pct-rotation adjusts the horizontal and vertical screen switching events to 10%.

3. Use the -s parameter to specify the seed value for command execution. Monkey will generate the corresponding event flow according to the seed value. The event flow generated by the same seed is exactly the same. The seed value is specified here to facilitate problem reproduction when the test finds a problem.

4. Use the --throttle parameter to control the time interval between each operation of Monkey. Specify the time interval between operations. On the one hand, it is hoped to be closer to the user's operation scene, and normal user operations will have a certain time interval; on the other hand It is also not desirable to cause the system to crash due to too frequent operations, especially when performing tests on relatively low-end mobile phones. Therefore, the monkey is set to a fixed delay of 0.4 seconds for each operation through --throttle.

5. Use the –ignore-crashs and –ignore-timeouts parameters to enable Monkey to continue executing when it encounters an accident. When executing the Monkey test, it will terminate unexpectedly due to the application crash or no response, so you need to add the limit parameter –ignore to the command -crash and --ignore-timeouts allow Monkey to record relevant information in the log when it encounters a crash or does not respond, and continue to perform subsequent tests.

6. Use -v to specify the verbose level of the log. Monkey's log output has 3 levels: the higher the log level, the higher the verbose level. In order to facilitate the positioning of the problem, here the log is set to -v -v.

test command

adb shell monkey -p com.tal.kaoyan
--pct-touch 40 --pct-motion 25 
--pct-appswitch 10
--pct-rotation 5
-s 1666 --throttle 400
--ignore-crashes
--ignore-timeouts
-v -v  200

Introduction to the Monkey Scripting API

LaunchActivity(pkg_name, cl_name): Launch the Activity of the application. Parameters: package name and started Activity.

Tap(x, y, tapDuration): Simulates a finger tap event. Parameters: x, y are the coordinates of the control, tapDuration is the duration of the click, this parameter can be omitted.

UserWait(sleepTime): sleep for a period of time

DispatchPress(keyName): Press a key. Parameters: keycode. RotateScreen(rotationDegree, persist): Rotate the screen. Parameters: rotationDegree is the rotation angle, eg 1 means 90 degrees; persist means whether it is fixed after rotation, 0 means recovery after rotation, and non-zero means fixed.

DispatchString(input): input string.

DispatchFlip(true/false): Open or close the soft keyboard.

PressAndHold(x, y, pressDuration): Simulate a long press event.

Drag(xStart, yStart, xEnd, yEnd, stepCount): Used to simulate a drag operation.

PinchZoom(x1Start, y1Start, x1End, y1End, x2Start, y2Start, x2End, y2End, stepCount): Simulate a zoom gesture.

LongPress(): Long press for 2 seconds.

DeviceWakeUp(): Wake up the screen.

PowerLog(power_log_type, test_case_status): Simulate battery power information.

WriteLog(): Write battery information to sd card.

RunCmd(cmd): Run shell commands.

DispatchPointer(downtime, eventTime, action, x, yxpressure, size, metastate, xPrecision, yPrecision, device, edgeFlags): Send a single gesture to the specified location.

DispatchPointer(downtime, eventTime, action, x, yxpressure, size, metastate, xPrecision, yPrecision, device, edgeFilags): Send key messages.

LaunchInstrumentation(test_name, runner_name): Run an instrumentation test case.

DispatchTrackball: Simulates sending trackball events.

ProfileWait: Wait for 5 seconds.

StartCaptureFramerate(): Get the frame rate.

EndCaptureFramerate(input): End capture frame rate.

Monkey script format

The script mainly includes two parts, one part is the header file information, and the other part is the specific monkey command

type = raw events  
count = 1  
speed = 1.0  
//下面为monkey命令  
start data >>   
具体的monkey脚本内容

write script

kyb.txt

#头文件信息
 
type = raw events 
 
count = 1
 
speed = 1.0
 
#启动测试
start data >>
 
LaunchActivity(com.tal.kaoyan,com.tal.kaoyan.ui.activity.SplashActivity)
UserWait(2000)
 
Tap(624,900,1000) #点击取消升级
UserWait(2000)
 
Tap(806,64,1000) #点击跳过
UserWait(2000)
 
Tap(217,378,1000) #点击用户名输入框
DispatchString(zxw1234)
UserWait(2000)
 
Tap(197,461,1000) #点击密码输入框
DispatchString(zxw123456)
UserWait(2000)
 
Tap(343,637,1000) #点击登录按钮
 
 

execute script

After the script is written, it is transferred to the mobile device and then executed.

adb push C:\Users\Shuqing\Desktop\kyb1.txt /sdcard
 
adb shell monkey -f /sdcard/kyb1.txt -v 1

Results of the

C:\Users\Shuqing>adb shell monkey -f /sdcard/kyb.txt -v 1
:Monkey: seed=1524592021303 count=1
:IncludeCategory: android.intent.category.LAUNCHER
:IncludeCategory: android.intent.category.MONKEY
Replaying 0 events with speed 1.0
:Switch: #Intent;action=android.intent.action.MAIN;category=android.intent.category.LAUNCHER;launchFlags=0x10200000;component=com.tal.kaoyan/.ui.activity.SplashActivity;end
    // Allowing start of Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.tal.kaoyan/.ui.activity.SplashActivity } in package com.tal.kaoyan
:Sending Touch (ACTION_DOWN): 0:(267.0,1233.0)
    // Allowing start of Intent { act=com.android.systemui.recent.action.TOGGLE_RECENTS cmp=com.android.systemui/.recent.RecentsActivity } in package com.android.systemui
:Sending Touch (ACTION_UP): 0:(267.0,1233.0)
Events injected: 5
:Sending rotation degree=0, persist=false
:Dropped: keys=0 pointers=0 trackballs=0 flips=0 rotations=0
## Network stats: elapsed time=7201ms (0ms mobile, 0ms wifi, 7201ms not connected)
// Monkey finished

Precautions

When writing the header file code, pay attention to reserve spaces on both sides of "=", otherwise the following error will appear.

java.lang.NumberFormatException: Invalid int: ""

monkey log management

Log management role

Monkey log management is a very important part of Monkey testing. Through log management analysis, it is possible to obtain whether the current test object is abnormal during the test process, and the probability of occurrence. At the same time, it can also obtain the corresponding error information to help the development and positioning. Solve the problem.

monkey log save method

  1. save in PC

  2. save on phone

  3. Standard stream and error stream are stored separately

save in PC

>adb shell monkey [option] <count> >d:\monkey.txt
 
eg:
C:\Users\Shuqing>adb shell monkey -v -v 100 >d:\monkeylog.txt

save on phone

C:\Users\Shuqing>adb shell
monkey -v 100 >/sdcard/monkeylog.log

Note: It cannot be written as C:\Users\Shuqing>adb shell monkey -f /sdcard/kyb.txt -v 1 > /mnt/sdcard/monkey.log, otherwise an error "The system cannot find the specified path" will be reported.

Standard stream and error stream are stored separately

  • Standard stream and error stream are saved separately, the code is as follows:

Monkey [option] <count> 1>/sdcard/monkey.txt 2>/sdcard/error.txt
 
C:\Users\Shuqing>adb shell monkey -v 100 1>d:\monkey.log  2>d:\error.log

After executing the above command, the running log and exception log of Monkey will be saved separately. At this time, the running log of Monkey will be saved in the monkey.txt file, and the exception log will be saved in the error.txt under the D disk.

Log content analysis

Run the command:

adb shell monkey -v 100

monkeyrunner

Introduction to monkeyrunner

The MonkeyRunner tool is written using Jython (Python implemented in the Java programming language), and it provides multiple APIs. Through the monkeyrunner API, a Python program can be written to simulate the operation and control of the Android device app, test its stability, and take screenshots. Conveniently document problems as they arise.

monkeyrunner path: Andriod_SDK\tools

Monkey Runner Features

  1. Multi-device control: API can implement test suites across multiple devices by launching all emulators at once;

  2. Functional Test: Automatically execute a functional test for the application, and then observe a screenshot of the output.

  3. Extensible automation: because monkeyrunner is an API toolkit, you can develop a whole system based on Python modules to control Android devices;

The difference between Monkeyrunner and Monkey

There is no direct relationship between monkeyrunner and money. Monkey runs the adb shell command directly on the device to generate random events for testing. In comparison, monkeyrunner controls the device by sending specific commands and events through the API.

monkeyrunner environment construction

  • Install and configure the jdk environment

  • install android sdk

  • Install python installation configuration tutorial

  • Monkeyrunner environment variable configuration: {Path}\Andriod_SDK\tools

Installation result detection

Enter the command in the console: monkeyrunner displays the following content, indicating that the installation is successful

C:\Users\Shuqing>monkeyrunner
Jython 2.5.3 (2.5:c56500f08d34+, Aug 13 2012, 14:54:35)
[Java HotSpot(TM) 64-Bit Server VM (Oracle Corporation)] on java1.8.0_05
>>>

Tips: To exit the monkeyrunner command line mode, you can use the shortcut key ctrl+D to exit.

MonkeyRunner API

The MonkeyRunner tool has three main classes:

  1. MonkeyRunner

  2. MonkeyDevice

  3. MonkeyImage

1.MonkeyRunner class:

MonkeyRunner provides methods for connecting the real machine and the simulator, input, pause, and alert boxes.

common method

waitForConnection(float timeout,string deviceid),
from com.android.monkeyrunner import MonkeyRunner as mr
print("connect devices...")
 
device=mr.waitForConnection()
# device=mr.waitForConnection(5,'127.0.0.1:62001')

2.MonkeyDevice class

The MonkeyDevice class provides methods for installing and uninstalling program packages, starting an Activity, sending button and click events, and running test packages.

common method

  • installPackage (string path) install package

  • removePackage (string package) remove package

  • startActivity (string uri, string action, string data, string mimetype, iterable categories dictionary extras, component component, flags) 启动

  • touch (integer x, integer y, integer type) 点击

touch**** parameter description

integer x, x coordinate value.

integer y, y coordinate value.

integer type,key event类型(如DOWN、UP、DOWN_AND_UP)。

DOWN is a press event, UP is a popup event, DOWN_AND_UP is a press popup event.

drag (tuple start, tuple end, float duration, integer steps)

The details of drag**** parameters are as follows:

tuple start, the starting position of dragging, which is the (x, y) coordinate point of tuple type.

tuple end, the end position of dragging, which is the (x, y) coordinate point of tuple type.

float duration, the duration of the dragging gesture, the default is 1.0s.

-integer steps, the number of steps for interpolation points, the default value is 10.

Code

kyb_start.py

from com.android.monkeyrunner import MonkeyRunner as mr
from com.android.monkeyrunner import MonkeyDevice as md 
print("connect devices...")
device=mr.waitForConnection()
print("install app...")
device.installPackage(r'C:\Users\Shuqing\Desktop\kaoyan3.1.0.apk')
package = 'com.tal.kaoyan'
activity = 'com.tal.kaoyan.ui.activity.SplashActivity'
runComponent = package + '/' + activity 
print("launch App...")
device.startActivity(component=runComponent)
 
 

code execution method

monkeyrunner scripfile
 
C:\Users\Shuqing>monkeyrunner E:\monkeyrunner_script\kyb.py

3.MonkeyImage class

The MonkeyImage class is used to save test screenshots in various formats during the test process, and can perform image comparison.

common method

  • takeSnapshot() takes a screenshot

  • writeToFile() saves the image file to the specified file path

usage example

from com.android.monkeyrunner import MonkeyImage as mi  
print("takeSnapshot")
screenshot=device.takeSnapshot()  
screenshot.writeToFile(r'E:\monkeyrunner_script\test.png','png')

Comprehensive Practice

testing scenarios

  • Connect the device, automatically install and start the Kaoyanbang app

  • After starting, log in to the account (account zxw1234, password: zxw123456), then take a screenshot and save it to the specified file location.

Idea analysis

  • connect device

  • install apps

  • start app

  • Enter username and password and click the login button

  • screenshot

Script implementation

kyb_login.py

from com.android.monkeyrunner import MonkeyRunner as mr
from com.android.monkeyrunner import MonkeyDevice as md
from com.android.monkeyrunner import MonkeyImage as mi
 
print("connect devices...")
 
device=mr.waitForConnection()
 
print(" install app")
device.installPackage(r'C:\Users\Shuqing\Desktop\kaoyan3.1.0.apk')
 
print("launch app...")
package='com.tal.kaoyan'
activity='com.tal.kaoyan.ui.activity.SplashActivity'
runComponent=package+'/'+activity
 
device.startActivity(component=runComponent)
mr.sleep(3)
 
print("touch cancel button")
device.touch(618,895,'DOWN_AND_UP')
mr.sleep(1)
 
print("touch skip button")
device.touch(804,67,'DOWN_AND_UP')
mr.sleep(1)
 
print("input username and password")
device.touch(57,373,'DOWN_AND_UP')
mr.sleep(2)
device.type('zxw1234')
 
device.touch(152,480,'DOWN_AND_UP')
mr.sleep(2)
device.type('zxw123456')
mr.sleep(2)
 
print("touch login button")
device.touch(331,634,'DOWN_AND_UP')
 
print("takeSnapshot")
screenshot=device.takeSnapshot()
screenshot.writeToFile(r'D:\monkeyrunner\kyb.png','png')
 
 

Precautions

method call error

AttributeError: type object 'com.android.monkeyrunner.XXXXX' has no attribute XXXXXX

Check whether the called method name is spelled incorrectly, especially pay attention to case sensitivity.

character encoding error

SyntaxError: Non-ASCII character in file 'E:\monkeyrunner_script\kyb.py', but no encoding declared;

Need to add # at the top of the code -- coding: utf-8 -- or remove the Chinese characters in the code

Appius

Introduction to Appium

Appium is an open source test automation framework that can be used for native, hybrid and mobile web application testing. It drives iOS, Android and Windows applications using the WebDriver protocol.

  • Appium official website

  • Appium github main page

  • Official Chinese document

  • Appium Official Forum

  • Testerhome Chinese Community

Advantages of Appium

  • Can support both android and ios across platforms

  • Support multiple languages, java, python, php, Ruby, etc.

  • Don't worry about complicated environment

  • If you have selenium experience, get started directly.

Principles of Appium Architecture

  • Android (version > 4.3): UIAutomator, the UI automation testing tool that comes with the system after Android 4.3.

  • Android (version ≤4.3): Selendroid, an automated testing tool based on the Android Instrumentation framework.

  • iOS: UIAutomation (a template in the instruments framework), a UI automation testing tool that comes with the iOS system.

Operating principle

We run automated test scripts on our computer (client) and call the interface of webdriver. After appium server receives the commands sent from our client, he will convert these commands into commands recognized by UIautomator, and then UIautomator will run them on the device. Execute automation.

The architectural principle of Appium is shown in the figure above. It consists of two parts: the client (Appium Client) and the server (Appium Server). The client and the server communicate through the JSON Wire Protocol.

Appium server

The Appium server is the core of the Appium framework. It is an HTTP server implemented based on Node.js. The main function of the Appium server is to accept the connection initiated from the Appium client, monitor the command sent from the client, send the command to bootstrap.jar (bootstrap.js for iOS mobile phone) for execution, and reply the execution result of the command through HTTP Feedback to Appium client.

Bootstrap.jar。

Bootstrap.jar is an application running on the Android phone, which acts as a TCP server on the phone. When the Appium server needs to run a command, the Appium server will establish TCP communication with Bootstrap.jar and send the command to Bootstrap.jar; Bootstrap.jar is responsible for running the test command.

Appium client.

It mainly refers to the client library of the WebDriver protocol that implements the Appium function. It is responsible for establishing a connection with the Appium server and sending the instructions of the test script to the Appium server. The existing client library is implemented in multiple languages, including Ruby, Python, Java, JavaScript (Node.js), Object C, PHP, and C#. Appium's tests are developed on the basis of these Libraries.

Appium components

App Server

Appium Server is the server side of Appium - a web interface service, implemented using Node.js. Refer to the official website for explanation.

Desktop App

Appium Desktop is an open-source application for Mac, Windows and Linux that gives you the power of Appium Automation Server in a beautiful and flexible user interface. It is a combination of several Appium related tools:

  1. Graphical interface for Appium Server. You can set options, start/stop the server, view logs, etc... You also don't need to use Node's NPM to install Appium because the Node runtime is bundled with Appium Desktop.

  2. You can use the Inspector to view elements of your application, get basic information about them, and perform basic interactions with them.

GUI app

Appium GUI is the predecessor of Appium desktop. This also encapsulates the Appium server into a graphical interface, lowering the threshold of use, just like the original operating system Dos is to type commands, followed by a graphical interface operating system, such as Windows system. Many beginners should be familiar with the following interface. This is the Windows version of the Appium GUI interface. Testers can manually start and configure related server services. If this is not used, a command is required to start the service. Because most of the tutorials are explained based on this GUI, many people think it is this when they say Appium.

Appium Clients

Because Appium is a C/S structure, there must be a client if there is a server. Appium Clients is the client, which will send a request session to the server Appium Server to perform automated tasks. Just like our browser accesses the webpage, the browser is the client, and the server sends the request to obtain the data through the operation. We can use different client browsers (IE, Firefox, Chrome) to visit a website. Appium clients can be implemented using different languages, such as Python, java, etc. See the table below for details:

Language/Framework Github Repo and Installation Instructions
Ruby https://github.com/appium/ruby_lib
Python https://github.com/appium/python-client
Java https://github.com/appium/java-client
JavaScript (Node.js) https://github.com/admc/wd
Objective C https://github.com/appium/selenium-objective-c
PHP https://github.com/appium/php-client
C# (.NET) https://github.com/appium/appium-dotnet-driver
RobotFramework https://github.com/jollychang/robotframework-appiumlibrary

App-desktop

Appium-desktop main interface contains three menus Simple, Advanced, Presets

Capability

What is Capability

The function of the desired capability is to configure the Appium session. They tell the Appium server which platforms and applications you want to automate.

Desired Capabilities is a collection of key-value pairs for a setting, where the key corresponds to the name of the setting and the value corresponds to the value of the setting. (For example: "platformName": "Android") Desired Capabilities are mainly used to notify the Appium server to establish the required Session.

Session

The communication between Appium's client and server must be carried out in the context of a Session. When the client initiates communication, it will first send a JSON object called "Desired Capabilities" to the server. After the server receives the data, it creates a session and returns the session ID to the client. The client can then use the session ID to send subsequent commands.

Explanation of common Capability configuration

Capability official complete document

Anyone who has learned about Capability will find a problem. In fact, it is mainly divided into three parts: public part, ios part, android part. If you want to use ios for android, it is impossible, so, honestly understand each What are the platforms and what are their functions. Below we introduce some common and commonly used options, and those marked in red are commonly used options.

Public Capability

Android unique Capability

ios unique Capability

Capability Launch App Demo

New Session Window session establishment

  • Automatic Server local AppiumServer service

  • Custom Server: This is useful, for example, if you want to start an Inspector session against an Appium server running on another computer in your network.

  • Sauce Labs: If you don't have access to the iOS Simulator on your machine, you can leverage your Sauce Labs account to start an Appium session in the cloud.

  • TestObject: You can also take advantage of TestObject's real device cloud for real-device testing.

  • headspin: Use a remote device to create a session.

desired capability parameter Josin

{
  "platformName": "Android",
  "platformVersion": "5.1.1",
  "deviceName": "127.0.0.1:62025",
  "appPackage": "com.tal.kaoyan",
  "appActivity": "com.tal.kaoyan.ui.activity.SplashActivity",
  "noReset": true
}

The new Session window allows you to construct a set of desired capabilities for launching an Appium session. You can start a session against the currently running Appium Desktop server (the default), or you can start a session against various other endpoints.

Because Appium Desktop's own server is not required, you can enter a new session window without starting the Appium Desktop server. Just click on "File" (Windows/Linux) or "Appium" (Mac) and select "New Session..." and it will open a new session window without having to start a local server. In this case, attaching to the local server is disabled.

Inspector element acquisition

After the startup is successful, you can use the Inspector to obtain the element space. Note: The default element positioning is somewhat inaccurate. You need to switch to the second coordinate point positioning option and then switch back to achieve accurate positioning. insert image description here

appium element positioning

element positioning

Like web automation testing, the most important link in the app automation testing process is element positioning. Only when elements are accurately positioned can operations on related elements be performed, such as input, click, drag, slide, etc. Appium provides many methods of element positioning, such as id positioning, name positioning, class positioning, hierarchical positioning, etc... Next, we will practice and use these positioning techniques for everyone.

Element positioning method

  • id

  • name

  • class name

  • List positioning

  • relative positioning

  • Xpath positioning

  • H5 page element positioning

  • Uiautomator positioning

UIAutomator

Introduction to UIAutomator Positioning

UIAutomator element positioning is a positioning method natively supported by the Android system. Although it is similar to xpath, it is more useful than it, and supports all attribute positioning of elements. The positioning principle is to find elements through the android uiautomator class library that comes with android. The Appium element positioning method is actually encapsulated based on Uiautomator.

Use the method find_element_by_android_uiautomator() to locate UiAutomator elements.

positioning method

  • id positioning

  • text positioning

  • class name positioning

id positioning

The id location is based on the element's resource-id attribute, and you can use the UiSelector().resourceId() method.

text positioning

Text positioning is to locate according to the text attribute value of the element, new UiSelector()

class name positioning

The same as the Appium class positioning method, it is also positioned according to the class attribute of the element.

element wait

think

In the automation process, the appearance of elements is affected by various factors such as network environment and equipment performance. Therefore, the loading time of the element may be inconsistent, which will cause an error when the element cannot be located and time out, but in fact the element is loaded normally, but it appears later. So how to solve this problem?

element waiting

Setting element waiting can more flexibly set the waiting time for locating elements, thereby enhancing the robustness of scripts and improving execution efficiency.

element wait type

forced wait

Set a fixed waiting time, use the sleep() method to achieve

from time import sleep 
#force to wait for 5 seconds 
sleep(5)

implicit wait

Implicit wait is the waiting time set for all elements

driver.implicitly_wait(20)

explicit wait

Explicit waiting is the waiting time set for an element.

The format parameters of the method WebDriverWait are as follows:

from selenium.webdriver.support.ui import WebDriverWait
 
WebDriverWait(driver, timeout, poll_frequency=0.5, ignored_exceptions=None)
driver : WebDriver
timeout : 最长超时时间,默认以秒为单位
poll_frequency : 休眠时间的间隔时间,默认为0.5秒
ignored_exceptions : 超时后的异常信息,默认情况下抛NoSuchElementException异常。

WebDriverWait() is generally used in conjunction with until() or until_not() methods. In addition, lambda provides a method for dynamically creating functions at runtime.

from selenium.webdriver.support.ui import WebDriverWait
WebDriverWait(driver,10).until(lambda x:x.find_element_by_id("elementID"))

Toast

Introduction to Toast

Toast in Android is a simple message prompt box. When the view is shown to the user, it appears as a float in the application. Unlike Dialog, it never gets focus and cannot be clicked.

Toast

The idea of ​​a class is to be as unobtrusive as possible, while still displaying information to the user that you want them to see. Moreover, the display time of Toast is limited, and it usually disappears in about 3 seconds. Therefore, using traditional element positioning tools, we cannot locate Toast elements (the legendary low-key luxury has connotations).

Appium Toast content acquisition

Appium 1.6.3 began to support the recognition of Toast content, mainly based on UiAutomator2, so the following parameters need to be configured in Capablity:

desired_caps['automationName']='uiautomator2'

Install appium-uiautomator2-driver: The installation command is as follows:

cnpm install appium-uiautomator2-driver

Note: When the Toast content is in Chinese, the top must be commented #

coding=utf-8 Otherwise, text recognition will fail due to codec.

Screenshots

application background

During the actual operation of the automation project, various exceptions may occur in the App in many cases. In order to better locate the problem, in addition to capturing the log, we also need to take a screenshot of the device status at runtime. So as to achieve a "pictures have the truth" effect.

screenshot method

method 1

save_screenshot() 该方法直接保存当前屏幕截图到当前脚本所在文件位置。
driver.save_screenshot('login.png')

Method 2

get_screenshot_as_file(self, filename)

Save screenshots until specified

 As someone who has been here, I also hope that everyone will avoid some detours, and I hope it can help you. (WEB automated testing, app automated testing, interface automated testing, continuous integration, automated test development, big factory interview questions, resume templates, etc.), I believe it can make you better progress! 

Just leave [Automated Test] [Automated Test Communication]: 574737577 (remark ccc) icon-default.png?t=N4P3http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=8hUKwUHn9HhVpR8qWhqfT2u-kU-3hpsF&authKey=47BBG1nwHVOka38EQeJevQFCP%2BeVEf% 2Bpd8QqotS1%2FqyJdrGAo1A6%2BfS9ef3wJij2&noverify=0&group_code=574737577

 

 

Guess you like

Origin blog.csdn.net/Free355/article/details/131227325
Recommended