You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

执行uiautomator dump时触发Pytest线程未处理异常警告问题排查

问题:pytest执行uiautomator dump触发PytestUnhandledThreadExceptionWarning

在pytest测试中,仅执行uiautomator dump并拉取生成的文件到本地时,会触发PytestUnhandledThreadExceptionWarning;注释掉uiautomator dump语句后,警告不再出现。

原测试代码

def test_android(adb):
    adb_output = adb.shell(command="uiautomator dump", assert_ok=True, timeout=10)
    assert "UI hierchary dumped to" in adb_output

    adb.pull(on_device_path="/sdcard/window_dump.xml", local_path="ui.xml", timeout=10)
    print("Pulled file!")

警告产生原因

uiautomator dump命令在Android系统内部是通过后台线程执行UI层级抓取操作的。你使用的adb客户端库在执行shell命令时,没有正确处理该命令内部线程抛出的异常;或者该命令的后台线程异常未被测试主线程捕获,导致pytest检测到未处理的线程异常,从而触发PytestUnhandledThreadExceptionWarning。

另外原代码中uiautomator dump的超时时间仅10秒,可能因命令执行超时触发内部线程异常,进一步导致警告出现。

解决后的测试代码

改用Pythonthreading模块拆分任务,并延长uiautomator dump的超时时间后,警告不再出现,所有线程正常运行:

import threading
import pytest

def thread1_sub(adb):
    print("Create xml file with current activity layout.")
    adb_output = adb.shell(command="uiautomator dump", assert_ok=True, timeout=300)
    assert "UI hierchary dumped to" in adb_output

def thread2_sub(adb):
    print("Pull created xml file to loacal path.")
    adb.pull(on_device_path="/sdcard/window_dump.xml", local_path="ui.xml", timeout=10)
 
def test_android(adb):
    thread1 = threading.Thread(target=thread1_sub, args=(adb,), name="Thread1")
    thread2 = threading.Thread(target=thread2_sub, args=(adb,), name="Thread2")
    print("START: Current active thread count: ", threading.active_count())
    thread1.start()
    thread2.start()
    thread2.join()

内容的提问来源于stack exchange,提问作者FotisK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 18:25:18