python的assert断言错误AssertionError处理办法

目录

错误收集

错误分析

解决问题

运行结果


错误收集

D:\Program\Util\python.exe "D:/Program/myUtil/PyCharm 2024.3.5/plugins/python-ce/helpers/pycharm/_jb_pytest_runner.py" --target test_page.py::TestPage 
Testing started at 21:27 ...
Launching pytest with arguments test_page.py::TestPage --no-header --no-summary -q in C:\Users\Administrator\PycharmProjects\selenium_shopping

============================= test session starts =============================
collecting ... collected 3 items

test_page.py::TestPage::test_login_logic[13800138006-123456-8888-True] 
test_page.py::TestPage::test_login_logic[12345678917-123456-8888-False] 
test_page.py::TestPage::test_login_logic[12346578912-123457-8888-False] 

======================== 2 failed, 1 passed in 19.96s =========================
PASSED [ 33%]操作成功
FAILED [ 66%]操作成功

test_page.py:10 (TestPage.test_login_logic[12345678917-123456-8888-False])
self = <test_page.TestPage object at 0x00000225C2F7C410>, phone = '12345678917'
pwd = '123456', v_code = '8888', status = 'False'

    @pytest.mark.parametrize(argnames="phone,pwd,v_code,status", argvalues=yaml.safe_load(open(file="data/login_data.yaml",mode= "r")))
    def test_login_logic(self,phone,pwd,v_code,status):
>       IndexPage().go_to_login().go_to_self_info_page(phone,pwd,v_code).check_info(status=status)

test_page.py:13: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <page.self_info_page.SelfInfoPage object at 0x00000225C2A5B890>
status = 'False'

    def check_info(self,status=False):
        print("操作成功")
    
>       assert self.if_exist_element(by=By.CSS_SELECTOR, express="div > a[title='退出']"), status
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E       AssertionError: False

page\self_info_page.py:15: AssertionError
FAILED [100%]操作成功

test_page.py:10 (TestPage.test_login_logic[12346578912-123457-8888-False])
self = <test_page.TestPage object at 0x00000225C2EF9940>, phone = '12346578912'
pwd = '123457', v_code = '8888', status = 'False'

    @pytest.mark.parametrize(argnames="phone,pwd,v_code,status", argvalues=yaml.safe_load(open(file="data/login_data.yaml",mode= "r")))
    def test_login_logic(self,phone,pwd,v_code,status):
>       IndexPage().go_to_login().go_to_self_info_page(phone,pwd,v_code).check_info(status=status)

test_page.py:13: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <page.self_info_page.SelfInfoPage object at 0x00000225C2F7C550>
status = 'False'

    def check_info(self,status=False):
        print("操作成功")
    
>       assert self.if_exist_element(by=By.CSS_SELECTOR, express="div > a[title='退出']"), status
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E       AssertionError: False

page\self_info_page.py:15: AssertionError

Process finished with exit code 1

错误分析

查看此处的断言代码

发现 我们并没有给断言代码加上处理,加上try: expect: 处理就可以了

解决问题

使用try  expect进行处理之后,报错就解决了

运行结果

可以看到已经解决了

如果修改后依旧没有解决,

运行一下其他的py文件。然后在运行当前文件

随便找一个py文件鼠标右键运行一下,然后在运行你要执行的文件。这个可能是pycharm把当前文件缓存了,再次运行还是运行的旧文件,新文件并没有加载。仅仅是个人感觉,具体也不是很清楚

### Python `assert` 断言的使用方法 #### 基础语法 在 Python 中,`assert` 是一种用于调试程序的有效工具。它的基本语法如下所示: ```python assert condition, error_message ``` 其中,`condition` 表示要验证的条件表达式;如果该条件为假,则触发异常并终止程序运行。可选参数 `error_message` 提供了当断言失败时显示的具体错误信息[^1]。 需要注意的是,在实际编码过程中应避免误用括号书写方式,例如 `(False, "Error")` 这样的形式并不被支持作为断言语句的一部分。 #### 错误处理机制 当 `assert` 后面跟随的布尔值计算结果为 False 时,Python 将引发一个名为 `AssertionError` 的异常,并停止执行后续代码逻辑。这种行为有助于开发者快速定位潜在问题所在位置以及原因分析[^3]。 另外值得注意的一点是,即使省略自定义消息部分,默认情况下也会抛出相应的 Assertion 异常提示用户存在未满足的前提假设情况发生。 #### 实际应用案例 以下是几个关于如何正确运用 `assert` 关键字的例子: ##### 示例一:基础数值比较 ```python def divide(a, b): assert b != 0, '除数不能为零' return a / b print(divide(10, 2)) # 输出5.0 # 如果尝试调用divide(10, 0),将会看到指定的消息:“除数不能为零” ``` ##### 示例二:数据类型校验 利用内置函数 isinstance 来确认传入变量是否符合预期类别需求。 ```python def process_string(s): assert isinstance(s,str), f'输入 {s} 不是一个字符串!' print(f'Processing "{s}"...') process_string('hello') # 正确路径下的正常打印操作 try: process_string([1,2]) # 抛出带有特定描述性的 AssertionError except Exception as e: print(e) # 屏幕上显示出错详情:"输入 [1, 2]不是一个字符串!" ``` 上述两个例子展示了不同场景下合理设置前置约束的重要性——既保护算法免受非法输入干扰又能增强整体健壮性[^4][^5]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值