Unable to get testname while calling pytest execution from python or subprocess

371 Views Asked by At

I am trying to create test runner python file, that executes the pytest.exe in particular testcase folder and send the results via email.

Here is my code:

test_runner.py:

try:
    command = "pytest.exe {app} > {log}".format(app=app_folder, log = log_name)
    os.system(command)
except:
    send_mail()

I use the following code in conftest.py to add screenshots to pytest-html report. In conftest.py:

@pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):

pytest_html = item.config.pluginmanager.getplugin('html')
outcome = yield
report = outcome.get_result()
extra = getattr(report, 'extra', [])
if pytest_html:
    xfail = hasattr(report, 'wasxfail')
    if (report.skipped and xfail) or (report.failed and not xfail):
        test_case = str(item._testcase).strip(")")
        function_name = test_case.split(" ")[0]
        file_and_class_name = ((test_case.split(" ")[1]).split("."))[-2:]
        file_name = ".".join(file_and_class_name) + "." + function_name

Issue is, when I run the command "pytest.exe app_folder" in windows command prompt it is able to discover the test cases and execute them and get the results. But when I call the command from .py file either using os.command or subprocess it fails with the following exception:

\conftest.py", line 85, in pytest_runtest_makereport
INTERNALERROR>     test_case = str(item._testcase).strip(")")
INTERNALERROR> AttributeError: 'TestCaseFunction' object has no attribute 
'_testcase'

Can anyone please help me to understand whats happening here? or any other way to get the testcase name?

Update:

To overcome this issue, I alternatively used the TestResult object from pytest_runtest_makereport hook to get the test case details.

@pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):
    outcome = yield
    report = outcome.get_result()

In the above example, report variable contain the TestResult object. This can be manipulated to get the testcase/class/module name.

1

There are 1 best solutions below

0
On

you can use shell=True option with subprocess to get the desired result

from subprocess import Popen
command='pytest.exe app_folder'   #you can paste whole command which you run in cmd
p1=Popen(command,shell=True)

This would solve your purpose