需求如下:
在《通讯录》应用中,进添加联系人页面,在姓名和电话栏中,输入对应的数据。
注意:因为appium每次启动应用时都会"重置应用",才会出现本地保存,若不想重置,可直接在启动参数加一行代码,
desired_caps['noReset'] = True
方法:Appium+PO模式+Pytest框架数据参数化
1. 项目结构如下:
项目结构在上一节已经介绍了,这里不重复介绍。
base_action.py
from selenium.webdriver.support.wait import WebDriverWait
class BaseAction:
def __init__(self, driver):
self.driver = driver
def find_element(self, location, timeout=10, poll=1):
"""
:param location: 元素位置
:param timeout: 设置10秒
:param poll: 多少秒找一次
:return:
"""
location_by, location_value = location
wait = WebDriverWait(self.driver, timeout, poll)
return wait.until(lambda x: x.find_element(location_by, location_value))
def find_elements(self, location, timeout=10, poll=1):
location_by, location_value = location
wait = WebDriverWait(self.driver, timeout, poll)
return wait.until(lambda x: x.find_elements(location_by, location_value))
def click(self, location):
self.find_element(location).click()
def input(self, location, text):
self.find_element(location).send_keys(text)
base_driver.py
from appium import webdriver
def init_driver():
desired_caps = dict()
# 设备信息
desired_caps["platformName"] = "Android"
desired_caps["platformVersion"] = "5.1"
desired_caps["deviceName"] = "192.168.56.101:5555"
# app信息
desired_caps["appPackage"] = "com.android.contacts"
desired_caps["appActivity"] = ".activities.PeopleActivity"
# 不重置应用
desired_caps["noReset"] = True
return webdriver.Remote("http://127.0.0.1:4723/wd/hub",desired_caps)
contact_list_page.py
from selenium.webdriver.common.by import By
from base.base_action import BaseAction
class ContactListPage(BaseAction):
# 添加联系人
add_contact_button = By.ID, "com.android.contacts:id/floating_action_button"
# 点击添加联系人
def click_add_contact(self):
self.click(self.add_contact_button)
new_contact_page.py
from selenium.webdriver.common.by import By
from base.base_action import BaseAction
class NewContactPage(BaseAction):
# 姓名输入框
name_edit_text = By.XPATH, "//*[@text='姓名']"
# 电话输入框
phone_edit_text = By.XPATH, "//*[@text='电话']"
# 输入姓名
def input_name(self, text):
self.input(self.name_edit_text, text)
# 输入电话
def input_phone(self, text):
self.input(self.phone_edit_text, text)
test_contact.py
import time
import pytest
from base.base_driver import init_driver
from page.page import Page
class TestContact:
def setup(self):
self.driver = init_driver()
self.page = Page(self.driver)
def teardown(self):
time.sleep(5)
self.driver.quit()
@pytest.mark.parametrize(("name", "phone"), [("猪猪夏", "18511111111"), ("猪猪杨", "18500000000")])
def test_contact(self, name, phone):
# 主页 - 点击 - 新建联系人
self.page.contact_list.click_add_contact()
# 新建联系人 - 输入 姓名
self.page.new_contact.input_name(name)
# 新建联系人 - 输入 电话
self.page.new_contact.input_phone(phone)
if __name__ == '__main__':
pytest.main([])
pytest.ini
[pytest]
# 添加命令行参数
addopts = -vs --html=./report/report.html --reruns 0
# 文件搜索路径
testpaths = ./scripts
# 文件名称
python_files = test_*.py
# 类名称
python_classes = Test*
# 方法名称
python_functions = test_*
2. 运行方式:
右键运行test_contact.py文件。