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

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

    博主:测试生财

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

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

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

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

     
     
  • 相关阅读:
    [C++] split string by string
    工作三个月心得经验
    Ubuntu Command-Line: Enable Unlimited Scrolling in the Terminal
    What is the PPA and How to do with it ?
    WCF vs ASMX WebService
    The ShortCuts in the ADT (to be continued)
    when does the View.ondraw method get called
    Browsing Storage Resources with Server Explorer
    Get start with Android development
    C++ Frequently asking question
  • 原文地址:https://www.cnblogs.com/qa-freeroad/p/14289491.html
Copyright © 2020-2023  润新知