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

background

When using the pytest-ordering plugin, an error was reported when running the case: NameError: name'pytest' is not defined. The actual case is as follows:

test_demo.py

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

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

Then execute pytest: run as shown below.

analysis

My pytest was installed with pip3, and there are multiple python3 interpreters (python3.5 and python3.8) in this environment, so I suspect that pytest did not find the correct python3 interpreter when executing the script.

Check the current default python3 interpreter version: python3 -V

As shown in the figure, python3 uses python3.8.2, and pytest in the above figure also prints python3.8.2.

So I modified test_demo.py: Specify the executor path to python3 (add the python interpreter path to the file header):

#/usr/bin/env [email protected](order=2)
def test_login():
    assert True

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

Then I executed the script again, still reporting errors.

Could it be a problem with the pytest installation? Try to import pytest in python3: python3 -c'import pytest'.

As shown in the figure, python3 can import the pytest package. Is it necessary to specify the import pytest package in the script?

Add in the testcase script: 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

Re-run and passed!

This question is really weird, but in contrast to the whole process, the main reason is that the test case did not follow the basic specifications of the python script:

  1. Specify the python interpreter: such as #!/usr/bin/env python3. (If it is python2, it can be written as #!/usr/bin/env python2)
  2. Explicitly import the package used in the script, even the decorator is no exception, as shown above import pytest
  3. The encoding of the specified script is utf8:#coding:utf-8, to prevent inexplicable problems when adding Chinese comments or executing across systems.

The above is the entire troubleshooting process, I hope it helps you~ 

Blogger: Test to make money

Motto: Focus on testing and automation, and strive to improve R&D efficiency; through testing and diligence to complete the original accumulation, through reading and financial management to financial freedom.

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

Blog Park: https://www.cnblogs.com/qa-freeroad/

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




Guess you like

Origin blog.51cto.com/14900374/2602899