pytest踩坑记:NameError: name 'pytest' is not defined


背景

在使用pytest-ordering插件的时候,运行case报错:NameError: name 'pytest' is not defined。实际case如下:

test_demo.py

@pytest.mark.run(order=2)
def test_login():
    assert True

@pytest.mark.run(order=1)
def test_reg():
    assert True

然后执行pytest:运行如下图。

 

分析

我的pytest是用pip3安装的,该环境上存在多个python3解释器(python3.5和python3.8),于是我怀疑是pytest执行脚本时没有找到正确的python3解释器。

查看下当下默认python3的解释器版本:python3 -V

如图,python3使用的是python3.8.2,而上图中pytest也打印是python3.8.2。

于是我修改test_demo.py:指定执行器路径为python3(文件头添加python解释器路径):

#/usr/bin/env python3
@pytest.mark.run(order=2) def test_login(): assert True @pytest.mark.run(order=1) def test_reg(): assert True

然后我再次执行该脚本,仍旧报错。

难不成是pytest安装出了问题?尝试在python3导入pytest:python3 -c 'import pytest'。

如图,python3导入pytest的包也没问题。那是不是需要在脚本里面指定导入pytest包呢?

在testcase脚本加入:import pytest。

#/usr/bin/env python3
import pytest
@pytest.mark.run(order=2)
def test_login():
    assert True

@pytest.mark.run(order=1)
def test_reg():
    assert True

重新运行,顺利通过了!

这个问题确实比较诡异,但是反观整个过程,主要出在测试case没有遵循python的脚本的几个基础规范:

  1. 指定python解释器:如#!/usr/bin/env python3。(如果是python2的话,可以写成#!/usr/bin/env python2)
  2. 在脚本显式导入使用到的package,连装饰器也不例外,如上图import pytest
  3. 指定脚本的编码为utf8:#coding:utf-8 ,防止在添加中文注释或者跨系统执行的时候带来莫名其妙的问题。

如上就是整个问题排查过程,希望对你有帮助~ 

博主:测试生财(一个不为996而996的测开码农)

座右铭:专注测试开发与自动化运维,努力读书思考写作,为内卷的人生奠定财务自由。

内容范畴:技术提升,职场杂谈,事业发展,阅读写作,投资理财,健康人生。

csdn:https://blog.csdn.net/ccgshigao

博客园:https://www.cnblogs.com/qa-freeroad/

51cto:https://blog.51cto.com/14900374

微信公众号:测试生财(定期分享独家内容和资源)

 

 
 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM