【自动化测试】pytest 用例执行中print日志实时输出

author: jwensh

date: 20231130

pycharm 中 pytest 用例执行中 print 日志 standout 实时命令行输出

使用场景

在进行 websocket 接口进行测试的时候,希望有一个 case 是一直执行并接受接口返回的数据

python 复制代码
def on_message(ws, message):
    message = json.loads(message)
    if message is not None and message['total'] > 0:
        print(datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"), message)


class TestWss(unittest.TestCase):

    def test_bttc_todos(self):
        websocket.enableTrace(False)
        address = "*****"
        url = "{}/test/todos/{}".format(BASE_ENV_URL, address)
        ws = websocket.WebSocketApp(url,
                                    on_open=on_open,
                                    on_message=on_message,
                                    on_error=on_error,
                                    on_close=on_close)
        ws.run_forever(dispatcher=rel)  # 这里回一直卡住不然程序停止
        rel.signal(2, rel.abort)  # Keyboard Interrupt
        rel.dispatch()

直接点击 pycharm 上测试方法左侧的执行按钮

是没有任何 on_message 的日志输出

想要 on_message 中的日志能够实时打印,可以修改 pytest 的执行参数

修改参数来达到实时输出日志的效果

  • 设置 pycharm 执行测试使用的工具
    • 第三步设置成 pytest (pytest 也是兼容 nose 和 unittest, 所以推荐 )
  • 在用例用例/调试配置里设置命令的其他参数
    • --capture=no 或者 -s (pytest -h 就能看到参数)

再次执行用例就能有实时日志了

  • 最后: 构建自动化测试用例时,添加简洁且饱含核心信息的日志是非常有必要的。除了添加 pytest 参数形式来展示实时日志,还可以使用 logging 模块来实现运行测试用例的实时输出。
  • 可以按自己的需求来,如果只是调试什么的,可以直接用参数
  • 如果是想要保留测试过程的重要数据,建议使用 logging
相关推荐
Warren9816 小时前
Pytest Fixture 作用域详解:Function、Class、Module、Session 怎么选
面试·职场和发展·单元测试·pytest·pip·模块测试·jira
我的xiaodoujiao2 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 44--将自动化测试结果自动推送至钉钉工作群聊
前端·python·测试工具·ui·pytest
我的xiaodoujiao2 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 45--生成项目需要的requirements.txt依赖文件
python·学习·测试工具·pytest
月明长歌2 天前
全栈测试修炼指南:从接口策略到 Python+Pytest+Allure 企业级架构
python·架构·pytest
一晌小贪欢2 天前
Python 测试利器:使用 pytest 高效编写和管理单元测试
python·单元测试·pytest·python3·python测试
我送炭你添花3 天前
Pelco KBD300A 模拟器:20.搭建pytest集成测试基础框架 + 模拟器闭环测试
python·集成测试·pytest
我送炭你添花4 天前
Pelco KBD300A 模拟器:18. 按依赖顺序 + 复杂度由低到高逐步推进pytest单元测试
python·单元测试·log4j·pytest
生活很暖很治愈4 天前
Pytest-order插件
python·测试工具·测试用例·pytest
测试人社区—66796 天前
2025区块链分层防御指南:AI驱动的安全测试实战策略
开发语言·驱动开发·python·appium·pytest
我送炭你添花7 天前
pytest 入门指南:从零开始掌握 Python 测试框架的核心概念与使用方法
chrome·python·pytest