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

相關文章
相關標籤/搜索