马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
基础利用
Pytest 测试用例实当代码
- import pytest
- from server.service import Service
- @pytest.fixture
- def service():
- return Service(logger)
- class TestService:
- @classmethod
- def setup_class(cls):
- """
- 初始化设置一次
- :return:
- """
- logger.info("{}----类初始化设置".format(cls.__name__))
- @classmethod
- def teardown_class(cls):
- """
- 结束后,清除设置
- :return:
- """
- logger.info("{}----类清除设置".format(cls.__name__))
- def setup_method(self):
- """
- 执行每个方法前,初始化
- :return:
- """
- logger.info("{}----执行每个方法前,初始化".format(self.__module__))
- def teardown_method(self):
- """
- 执行每个方法后,清除设置
- :return:
- """
- logger.info("{}----执行每个方法后,清除设置".format(self.__module__)
复制代码 可在类中添加类前后和方法前后固定执行的利用。
界说一个测试实例
- @pytest.mark.parametrize(
- ['params', 'expected'], # 也可使用字符串传入'params, expected'传入
- [
- (
- {
- "title": "测试用例"
- },
- Code.OK
- ), # 第一组测试参数
- ]
- )
- def test_add(self, service, params, expected):
- result = dialogue_service.add_dialogue(**params)
- assert result.code == Code.OK
复制代码
假设TestService类在test_service.py中,运行该类,添加main方法,之后在该文件目录下运行命令python test.service.py
- if __name__ == '__main__':
- pytest.main()
复制代码 运行测试类中一个测试用例
可在测试函数函数上添加标识装饰器@pytest.mark.[运行名称],如pytest.marks.add
- @pytest.mark.add
- def test_add(self, service, params, expected):
- result = service.add(**params)
- assert result.code == Code.OK
复制代码 假如过需要添加参数,则标识按如下方式添加:
- @pytest.mark.parametrize(
- ['params', 'expected'],
- [
- pytest.param(
- {"title": "测试用例",},
- Code.OK,
- marks=pytest.mark.add
- ),
- ]
- )
- def test_add(self, service, params, expected):
- result = service.add(**params)
- assert result.code == Code.OK
复制代码 运行命令:pytest -m add
或直接利用命令,指定要运行的测试用例:pytest test_service.py::TestService:test_add
项目包引入路径题目
- import os
- import sys
- current_path = os.getcwd()
- sys.path.append(os.path.join(current_path.split('project_name')[0], 'project_name')) # 不添加测试时无法找到正确路径
复制代码 将当前项目路径添加到系统中。
参考:
Python自动化测试框架unittest与pytest的区别_pytest和unittest哪个好-CSDN博客
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |