1.微信小程序自动化测试pytest版-阅读unittest版

MiniTest中有基于unittest进行封装,但是由于unittest相比于pytest灵活度上有些劣势,所以使用pytest来重新处理

官网例子

https://minitest.weixin.qq.com/#/minium/Python/readme

先阅读官网提供的例子

项目结构

.
├── test
│   └── __init__.py
│   └── first_test.py
└── config.json

first_test.py

#!/usr/bin/env python3
import minium
class FirstTest(minium.MiniTest):
    def test_get_system_info(self):
        sys_info = self.mini.get_system_info()
        self.logger.info(f'SDKVersion is: {sys_info.get("SDKVersion")}')  # 可以使用self.logger打印一些log
        self.assertIn("SDKVersion", sys_info)

config.json

{
  "project_path": "path/to/project",
  "dev_tool_path": "path/to/cli",
  "debug_mode": "debug"
}

运行

minitest -m test.first_test -c config.json -g

如果想要直接运行需要使用

if __name__ == "__main__":
    import unittest
    loaded_suite = unittest.TestLoader().loadTestsFromTestCase(FirstTest)
    result = unittest.TextTestRunner().run(loaded_suite)
    print(result)

使用pytest

启动小程序

阅读minium.MiniTest类

可以发现它的前置部分在_miniClassSetUp

@classmethod
def _miniClassSetUp(cls):
    logger.debug("=====================")
    logger.debug("Testing class:%s" % cls.__name__)
    logger.debug("=====================")
    super(MiniTest, cls)._miniClassSetUp()
    if not cls.CONFIG.report_usage:
        minium.miniprogram.base_driver.minium_log.existFlag = 1

    native, mini, miniprogram = init_miniprogram(cls.CONFIG)
    cls.native = native
    cls.mini = mini
    if cls.CONFIG.need_perf:  # start get perf thread
        cls.native.start_get_perf(timeinterval=0.8)
    cls.DEVICE_INFO["system_info"] = miniprogram.system_info

它主要的事情就是调用init_miniprogram(cls.CONFIG)拿到native, mini, miniprogram

所以写一个操作的类

class Mini:
    native = None
    appId = ""
    appName = ""
    _app = None
    driver = None
    config = {}

    def __init__(self, driver=None):
        # 基础配置
        self.base_config = {
            "project_path": PROJECT_PATH,
            "dev_tool_path": DEV_TOOL_PATH,
            "auto_authorize": True,
            "outputs": LOG_PATH,
        }
        if driver:
            self.native, self.mini = driver

    def open(self, config: dict = None):
        if config is None:
            config = {}
        self.config = {**self.base_config, **config}
        logger.info(f"使用「{self.config}」启动小程序")
        self.native, self.mini, miniprogram = init_miniprogram(MiniConfig(self.config))
        self.driver = self.native, self.mini

将启动小程序写到conftest.py中

@pytest.fixture(scope='session')
def mini():
    with allure.step("初始化小程序"):
        mini = Mini()
        mini.open()
    yield mini
    mini.quit()

操作小程序

官网的例子中进行小程序的操作使用的是 self.app和self.page

应为每次切换页面都需要重新使用get_current_page方法获取当前页面信息

所以需要将对应的property也放到新写的Mini类中

@property
def app(self) -> minium.App:
    if not self.mini:
        raise MiniAppError("未启动小程序")
    return self._app or (self.mini and self.mini.app)


@property
def page(self) -> minium.Page:
    if not self.mini:
        raise MiniAppError("未启动小程序")
    return self.mini.app.get_current_page()

优化步骤

为了让报告中步骤更明显,对元素对象进行对象化封装

class Locator:
    def __init__(self, element, wait_sec=5, by_type='css', locator_name='', desc='', inner_text=None,
                 text_contains=None, value=None):
        """

        @param element: 定位语句
        @param wait_sec: 等待时间 默认3秒
        @param by_type: 定位方式 只支持xpath/css
        @param locator_name: 变量名
        @param desc: 描述
        @param inner_text: inner_text
        @param value: value
        @param text_contains: 包含的文字
        """
        self.element = element
        self.wait_sec = wait_sec
        self.by_type = by_type
        self.inner_text = inner_text
        self.text_contains = text_contains
        self.value = value
        self.locator_name = locator_name
        self.desc = desc

查找元素

def find_element(self, locator: Locator):
    wait_sec = locator.wait_sec
    by_type = locator.by_type
    element = locator.element
    inner_text = locator.inner_text
    value = locator.value
    text_contains = locator.text_contains

    el = self.page.get_element(
          selector=element,
          inner_text=inner_text,
          text_contains=text_contains,
          value=value,
          max_timeout=wait_sec,
      )

    return el

点击元素

@allure.step("点击「{locator}」")
def click(self, locator: Locator, many: bool = False, num: int = 0):
    """
    点击元素
    :param locator:
    :param many: 是否会定位到多个
    :param num: 定位到多个后选择其中某一个
    :return:
    """
    if many:
        ele = self.find_element(locator)[num]
    else:
        ele = self.find_element(locator)
    ele.click()

这样一个元素就是

me = Locator('view', inner_text='我的', desc='底部导航-我的')
screen_animation = Locator('view', text_contains='上滑看看', desc='开屏动画-上滑看看按钮')

操作这个元素就是

@compose(feature="设计圈小程序", story="账号操作", title='登录')
def test_login(home_page, me_page, login_page):
    with allure.step("进入「我的」"):
        try:
            home_page.move(home_page.screen_animation, 0, 500, 500)
        except Exception as e:
            logger.error(f"上滑开屏动画失败:{e}")
        home_page.click(home_page.me)

测试报告中展示就是

1c24849d39b651e065af3208ad24fac8.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值