Здравствуйте, я думал, как мне вызвать этот BDD-файл Pytest из другого файла Python и записать результаты его завершения? В настоящее время он вызывается CMD py -m pytest -vvv -qsteps.py -o log_cli=true --log-cli-level=DEBUG --capture=tee-sys --feature=Test --alluredir allure-results . (Извините, я бы разместил больше кода, но переполнение стека не позволяет мне)
import teradatasql,pytest,logging,re,warnings,sys,allure
from typing import List, Dict
from ApplicationProperties import ApplicationProperties as AP
import StringBuilder,AllureReports
from pytest_bdd import given,when,then,scenarios, parsers
import pandas as pd
warnings.filterwarnings('ignore')
COL_DELIM = "|"
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
LOG = logging.getLogger(__name__)
ROW_MAX_LENGTH = 100
props = AP()
shost = props.getDbHost()
suser = props.getDbUser()
spassword = props.getDbPass()
slogmech = props.getDbLogMech()
environment=props.getEnvironment()
featurefilename = "../features/"
n = len(sys.argv)
for i in range(1, n):
if "--feature" in sys.argv:
args = sys.argv
argRemoveParameter = args.split("=")
featurefilename = featurefilename +argRemoveParameter[1]
LOG.debug(featurefilename)
scenarios(featurefilename)
actusult = None
@pytest.fixture(autouse=True)
def setUp():
conn = getConnection()
yield conn
#def tearDown():
#global conn
#close(conn)
#request.addfinalizer(tearDown)
#problems here not parses examples table
@given(parsers.parse("{parameters}"), target_fixture="parameters",converters={"parameters": str})
def ParseParmeters(parameters):
return parameters
@when(parsers.parse("I execute the query:\n{queryTemplate}"), target_fixture="actualResult")
@when(parsers.parse("SQL to execute:\n{queryTemplate}"), target_fixture="actualResult")
def whenIExecuteTheQuery(setUp,parameters,queryTemplate):
global LOG
LOG.debug("QueryTemplate=" + queryTemplate + "/n Parameters: " + parameters)
query = populateParameters(parameters, queryTemplate)
print(query)
addSqlAsAttachment("query", query)
LOG.debug("Executing query:" + query)
try:
stat = setUp
#rs = stat.execute(query)
rs = pd.read_sql(query, stat)
LOG.debug("Got result: \n" + rs.to_string())
#actualResult =asMaps(rs)
#LOG.debug("Got result: \n" + actualResult)
return rs
except Exception as error:
LOG.error("Error executing query: " + query, error)
raise Exception(error)
finally:
close(stat)
@then(parsers.parse("EXPECTED_RESULT={expectedResult}"))
def actiontaken(actualResult, expectedResult):
#used to be called then
global LOG
LOG.debug("expectedResult=" + expectedResult + "/n text: " + actualResult.to_string())
if ("NO_ROWS_RETURNED".upper() == expectedResult.upper()):
assert actualResult is not None, "Result set is not empty: " + actualResult.to_string()
else:
AssertionError("Unsupported EXPECTED_RESULT token!")
@then("I will get empty result set")
def actiontaken(actualResult):
#used to be called then
global LOG
LOG.debug("Result" + actualResult.to_string())
assert actualResult is not None, "Result set is not empty: " + actualResult.to_string()
@then(parsers.parse("I will get the following result set: {result}"))
def thenIWillGetTheFollowingResult(actualResult,expectedTable):
##expect a parser of table to be here ##
expectedTableString = createTable(expectedTable.getRows())
actualTableString = createTable(actualResult)
expectedResult = [expectedTable.getRows()]
for expected in expectedResult:
for actual in actualResult:
if expected == actual:
actualResult.remove(actual)
expectedResult.remove(expected)
tablereturn = StringBuilder()
tablereturn.append("Expected:\n" + expectedTableString);
tablereturn.append("\nActual:\n" + actualTableString);
if actualResult.size() > 0:
unexpectedTableString = createTable(actualResult);
tablereturn.append("\nUnexpected:\n" + unexpectedTableString);
if expectedResult.size() > 0:
notFound = createTable(expectedResult);
tablereturn.append("\nNot Found:\n" + notFound);
#send to allure reports
allure.attach( str(tablereturn),"ResultSets",attachment_type=allure.attachment_type.TXT);
#ExamplesAwareReporter.addTextAttachment("ResultSets.txt", str(tablereturn));
assert actualResult is None and expectedResult is None ,"Unexpected rows count:" + actualResult.size() + "; Not found rows count: " + expectedResult.size()
Подробнее здесь: https://stackoverflow.com/questions/786 ... t-bdd-file
Как программировать вызов файла Pytest BDD ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Осколок pytest-bdd Не удалось установить новое соединение: [WinError 10061]
Anonymous » » в форуме Python - 0 Ответы
- 32 Просмотры
-
Последнее сообщение Anonymous
-