代码改变世界

python+appium+unittest做app自动化测试

2024-04-22 17:14  加个小鸡腿  阅读(66)  评论(0编辑  收藏  举报

如果想了解pytest框架的自动化测试,可以参考我的另一篇博客:

python+appium+pytest做app自动化测试

1.需要安装一些列的软件:

(1)java

(2)android sdk:  https://www.cnblogs.com/chenxiaomeng/p/16544481.html

(3)Appium Server GUI

(4) Appium Inspector  (3和4老版本是一个)

2.打开Appium Server GUI

直接点击startServer即可,使用默认配置

 3.打开 Appium Inspector

remote path需要修改成/wd/hub,查看连接设备的安卓版本号,使用adb device查看设备名称,写上对应的包名和启动名称,可以用adb am start执行看看,如下:

 至于automationName写UiAutomator2还是UiAutomator1,需要根据你的安卓版本来定,【1不行就试试2,或者百度下】

 然后点击右下角的‘start session’就可以打开会话,连接到app的功能页面,也可以在pc上看到安卓上的app的页面,然后就可以使用id或者text或者xpath之类的方式查找元素并点击

3.python代码

from appium import webdriver
import unittest

class SimpleAppiumTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        server_url = 'http://localhost:4723/wd/hub'
        desired_caps = {}
        desired_caps['platformName'] = 'Android'
        desired_caps['platformVersion'] = '8.1.0'
        desired_caps['deviceName'] = '2c7c688a'
        desired_caps['appPackage'] = 'com.hhh.aaa.xxx.test'  # 应用的包名
        desired_caps['appActivity'] = 'com.hhh.aaa.xxx.test.MainActivity'  # 应用的主Activity
        cls.driver = webdriver.Remote(server_url, desired_caps)

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

    def test_find_and_click_element(self):
        # 假设有一个id为my_button的按钮
        button = self.driver.find_element_by_id('com.hhh.aaa.xxx.test:id/apiCastBtn')
        button.click()
        self.assertTrue(True, "Button click action performed")

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(SimpleAppiumTest)
    unittest.TextTestRunner(verbosity=2).run(suite)

这里你可能会遇到一个desired_caps的报错:

AttributeError: 'NoneType' object has no attribute 'to_capabilities'

这是因为Appium-Python-Client版本太高导致的,命令行降低版本即可,pycharm也需要需要降低版本,参考:https://blog.csdn.net/qq_63010259/article/details/133905117

4.执行测试

上面的python代码我们定义文件名为appiumtest.py,执行自动化测试时,只要时以test开头的case都会执行,可单个执行,也可全部执行

在cmd命令行输入:python appiumtest.py 

结果:

表示test_find_and_click_element这个用例执行通过

 5.可以添加其他cast,只要是test开头的都会执行,另外可以尝试生成好看一点的测试报告

最后部分代码稍微改良下就可以得到一个简陋版本的测试报告:

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(SimpleAppiumTest)
    with open('test_result.txt','w',encoding='utf-8') as tf:
        unittest.TextTestRunner(verbosity=2,stream=tf).run(suite)

当前目录下会生成一个test_result.txt的文件,记录了case的执行情况,如下: