DevOps工具链之自动化UI测试-IOS(下)

谈谈IOS开发中的自动化UI测试—Jenkins加上Appium、Macaca等

Posted by Marco Liu on June 22, 2018

“Hope for the best. ”

使用python3+behave写测试用例

python元素定位

python的BDD框架,参考这里

除了官方提供的Appium-Python-Client框架,还有一个非官方由网易开源的python客户端facebook-wda,facebook-wda这个库的功能非常强大,可以取代appium,不过只支持python,Appium支持多种脚本编写。

写单元测试推荐使用ruby,ruby_lib相对于Appium-Python-Client功能更强大、api更完善,当然facebook-wda的功能也很强大、完善,你也可以使用python+facebook-wda来写

环境准备

1、安装python3

brew install python3

2、安装Appium-Python-Client

pip3 install Appium-Python-Client

3、安装Behave

pip3 install behave

4、查看Behave支持的语言

behave --lang-list

5、查看对应语言的关键字

behave --lang-help zh-CN
Translations for Chinese simplified / 简体中文
             And: 而且<
      Background: 背景
             But: 但是<
        Examples: 例子
         Feature: 功能
           Given: 假如<
        Scenario: 场景
Scenario Outline: 场景大纲
            Then: 那么<
            When: <

创建一个iOS测试工程

写测试脚本

1、创建如下目录结构

├── app # 待测app
   └── TestApp.app
└── features
    ├── calculate.feature # behave待测功能定义
    ├── environment.py # 环境配置
    └── steps
        └── step.py # 测试steps

2、测试求和功能

创建calculate.feature,输入如下内容

#language: zh-CN
功能: 求和
    场景: 计算两个数相加
        假如 第一个值输入 10
        而且 第二个值输入 20
         点击 求和按钮
        那么 结果应该为30

3、配置环境

创建environment.py,输入如下内容

# -*- coding: utf-8 -*
import os
from appium import webdriver
 
def before_feature(context, feature):
    app = '/Users/yangfangming/Desktop/TestDemo/app/TestApp.app'
    context.driver = webdriver.Remote(
        command_executor='http://127.0.0.1:4723/wd/hub',
        desired_capabilities={
            'app': app,
            'platformName': 'ios',
            'deviceName': 'iPhone 8',
            'platformVersion': '11.1',
            'bundleId': 'com.yfm.TestApp'
        })
 
def after_feature(context, feature):
    context.driver.quit()

4、创建steps

创建step.py,输入如下内容

# -*- coding: utf-8 -*
from behave import *
 
@given(u'第一个值输入 10')
def step_impl(context):
    el = context.driver.find_element_by_accessibility_id('textfield1')
    el.clear()
    el.set_value("10")
 
 
 
@given(u'第二个值输入 20')
def step_impl(context):
    el = context.driver.find_element_by_accessibility_id('textfield2')
    el.clear()
    el.set_value("20")
 
 
@when(u'点击 求和按钮')
def step_impl(context):
    el = context.driver.find_element_by_accessibility_id('sum')
    el.click()
 
 
@then(u'结果应该为30')
def step_impl(context):
    # el = context.driver.find_element_by_accessibility_id('result')
    el = context.driver.find_element_by_class_name('XCUIElementTypeStaticText')
    actual = el.get_attribute('value')
    print(actual)
    assert actual=='30', 'result is 30'

运行测试

behave
# 或者
behave --lang zh-CN

参考

https://github.com/appium/python-client

https://github.com/serhatbolsu/appium-python-bdd/blob/master/testhive/features/steps/steps.py

https://github.com/behave/behave

http://www.runoob.com/python3/python3-tutorial.html

—— Marco 后记于 2018.06