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 [email protected](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 python3import [email protected](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




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章