"A long article teaches you how to use appium in all aspects"

With the increasing popularity of mobile applications, testing of mobile applications has become an important part of software development. Python, as an easy-to-learn, powerful programming language, is particularly suitable for this kind of testing. This article will introduce in detail how to use Python for APP testing, and come with an example.

Python and Appium: a powerful combination

When conducting APP testing, we usually use automated testing tools. Among them, Appium is a very popular open source mobile application automation testing tool that can support Android and iOS application testing. One of its main advantages is that you can write test scripts in any programming language you like, as long as the language can create HTTP requests. Among them, Python is a language widely recommended by the Appium community.

Preparation

Before starting, you need to install some necessary tools:

Python: You can download and install it from the Python official website.

Appium: You can download and install it from the Appium official website.

Appium-Python-Client: This is a Python library that allows you to control Appium using Python. You can install it using pip: pip install Appium-Python-Client.

Example: APP testing using Python and Appium
This is a basic testing example where we will test a simple calculator APP. First, we need to import the necessary libraries:

from appium import webdriver
from appium.webdriver.common.mobileby import MobileBy

Next, we need to set startup parameters:

desired_caps = {}
desired_caps['platformName'] = 'Android'  # 你的设备系统
desired_caps['platformVersion'] = '8.1.0'  # 你的设备系统版本
desired_caps['deviceName'] = 'emulator-5554'  # 你的设备名称
desired_caps['appPackage'] = 'com.android.calculator2'  # 你的APP的包名
desired_caps['appActivity'] = 'com.android.calculator2.Calculator'  # 你的APP的主Activity

Then, we create a driver:

driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

Now we can start writing our test script. For example, we can test the addition function of the calculator:

driver.find_element(MobileBy.ID, "com.android.calculator2:id/digit_2").click()
driver.find_element(MobileBy.ID, "com.android.calculator2:id/op_add").click()
driver.find_element(MobileBy.ID, "com.android.calculator2:id/digit_3").click()
driver.find_element(MobileBy.ID, "com.android.calculator2:id/eq").click()

result = driver.find_element(MobileBy.ID, "com.android.calculator2:id/result").text
assert result == '5'

Finally, we need to shut down the driver:

driver.quit()

Through this simple example, you can see the power of Python and Appium. You can easily locate elements, click on them, and check whether the results are as expected.

Advanced usage: automated testing

What we introduced above is a simple test example, but in actual development, we may need to conduct a large number of automated tests. To achieve this goal, we can use some advanced techniques, such as Python's unittest module.

Unittest is one of Python's standard libraries, providing a wealth of assertion methods and ways to organize tests. Here is a basic example of APP automation testing using unittest:

import unittest
from appium import webdriver
from appium.webdriver.common.mobileby import MobileBy


class TestCalculator(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        desired_caps = {}
        desired_caps['platformName'] = 'Android'
        desired_caps['platformVersion'] = '8.1.0'
        desired_caps['deviceName'] = 'emulator-5554'
        desired_caps['appPackage'] = 'com.android.calculator2'
        desired_caps['appActivity'] = 'com.android.calculator2.Calculator'
        cls.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

    def test_addition(self):
        self.driver.find_element(MobileBy.ID, "com.android.calculator2:id/digit_2").click()
        self.driver.find_element(MobileBy.ID, "com.android.calculator2:id/op_add").click()
        self.driver.find_element(MobileBy.ID, "com.android.calculator2:id/digit_3").click()
        self.driver.find_element(MobileBy.ID, "com.android.calculator2:id/eq").click()

        result = self.driver.find_element(MobileBy.ID, "com.android.calculator2:id/result").text
        self.assertEqual(result, '5')

    @classmethod
    def tearDownClass(cls):
        cls.driver.quit()


if __name__ == '__main__':
    unittest.main()

In this example, we created a TestCalculator class that inherits from unittest.TestCase. In this class, we can write multiple test methods, each method is a complete test and can be run independently. The setUpClass and tearDownClass methods will be run before all tests start and after all tests end. Usually we do some initialization and cleanup work here.

1. Use Page Object Model (POM)

POM is a design pattern used to create more readable and maintainable automated test code. In this mode, you will create a Python class for each APP page. This class contains all operations related to this page. In this way, your test code no longer directly deals with page elements, but with these abstract Page Objects, which makes your code easier to understand and modify.

class LoginPage:
    def __init__(self, driver):
        self.driver = driver

    def enter_username(self, username):
        self.driver.find_element(MobileBy.ID, "username_field").send_keys(username)

    def enter_password(self, password):
        self.driver.find_element(MobileBy.ID, "password_field").send_keys(password)

    def click_login_button(self):
        self.driver.find_element(MobileBy.ID, "login_button").click()

# 在测试中使用
login_page = LoginPage(driver)
login_page.enter_username('testuser')
login_page.enter_password('testpass')
login_page.click_login_button()

2. Use Appium’s Touch Action and Multi Touch

Appium provides Touch Action and Multi Touch APIs, allowing you to simulate various complex user gestures, such as sliding, dragging, multi-touch, etc. These functions allow you to simulate user operations more realistically and test more usage scenarios.

from appium.webdriver.common.touch_action import TouchAction

# 执行一个滑动操作
action = TouchAction(driver)
action.press(x=100, y=100).move_to(x=200, y=200).release().perform()

# 多点触控示例
from appium.webdriver.common.multi_action import MultiAction
action1 = TouchAction(driver).press(x=100, y=100).move_to(x=200, y=200).release()
action2 = TouchAction(driver).press(x=200, y=200).move_to(x=100, y=100).release()

multi_action = MultiAction(driver)
multi_action.add(action1, action2)
multi_action.perform()

3. Use Appium’s positioning strategy

In addition to the basic id, class name and xpath positioning strategies, Appium also provides many advanced positioning strategies. For example, you can use the image positioning strategy to target elements that do not have an explicit id or class name, and you can use accessibility ids to target elements that have special tags added to improve accessibility.

# 使用 image 定位
driver.find_element(MobileBy.IMAGE, "path_to_your_image.png")

# 使用 accessibility id 定位
driver.find_element(MobileBy.ACCESSIBILITY_ID, "your_accessibility_id")

4. Using Appium’s logs and reports

Appium provides rich logging and reporting functions, allowing you to debug your test code more conveniently and understand the execution of the test. You can use Appium's server log to view the detailed execution process of the test. You can also use various third-party reporting tools, such as Allure, to generate more beautiful and detailed test reports.

# 启动 Appium server 时设置 log 参数
appium --log /path/to/your/logfile.txt
# 使用 pytest 和 Allure 生成测试报告
def test_example():
    driver.find_element(MobileBy.ID, "some_id").click()
    assert driver.find_element(MobileBy.ID, "another_id").text == 'expected_text'

Then, run pytest and use the Allure plugin:

pytest --alluredir=/your/allure/result/directory
allure serve /your/allure/result/directory

5. Use Python’s parallel and asynchronous features

Python provides a wealth of parallel and asynchronous features so you can run your tests more efficiently. For example, you can use the threading or multiprocessing module to run multiple tests in parallel, and you can also use the asyncio module to write asynchronous test code, so that your test can handle multiple tasks at the same time and improve testing efficiency.

# 使用 threading 并行运行测试
import threading

def test_one():
    ...

def test_two():
    ...

thread_one = threading.Thread(target=test_one)
thread_two = threading.Thread(target=test_two)

thread_one.start()
thread_two.start()

thread_one.join()
thread_two.join()

Asynchronous programming is more complex and may require more in-depth study. Here's a simple example:

import asyncio

async def test_one():
    ...

async def test_two():
    ...

await asyncio.gather(test_one(), test_two())

These examples are simple and just to give you a general idea. In actual use, you may need to perform more complex operations based on your actual situation.

Finally, I would like to thank everyone who reads my article carefully. Reciprocity is always necessary. Although it is not a very valuable thing, if you can use it, you can take it directly:

Insert image description here

This information should be the most comprehensive and complete preparation warehouse for [software testing] friends. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey. I hope it can also help you!

Guess you like

Origin blog.csdn.net/NHB456789/article/details/132918929