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

背景

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

test_demo.pypython

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

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

而后执行pytest:运行以下图。ide

分析

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

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

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

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

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

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

而后我再次执行该脚本,仍旧报错。.net

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

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

在testcase脚本加入:import pytest。

#/usr/bin/env python3import 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 ,防止在添加中文注释或者跨系统执行的时候带来莫名其妙的问题。

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

博主:测试生财

座右铭:专一测试与自动化,致力提升研发效能;经过测试精进完成原始积累,经过读书理财奔向财务自由。

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

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

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

相关文章
相关标签/搜索