Commit 9870c69b by 云天羽

删除文件

parent 1df893b5
import pymysql
from Homework_files.APITesting_LZJ.common.read_ini import ReadIni
class DB:
def __init__(self):
ini = ReadIni()
try:
self.conn = pymysql.connect(
host=ini.connect_database_msg("host"),
port=int(ini.connect_database_msg("port")),
user=ini.connect_database_msg("user"),
password=ini.connect_database_msg("pwd"),
database=ini.connect_database_msg("database"),
charset="utf8"
)
self.cursor = self.conn.cursor()
except Exception as e:
print("链接数据库出错,错误为:", e)
raise e
def close(self):
self.cursor.close()
self.conn.close()
def delete(self, sql_sentence):
try:
self.cursor.execute(sql_sentence)
except Exception as e:
print("执行删除的sql语句时报错,错误为:", e)
raise e
else:
self.conn.commit()
def select(self, sql_sentence):
try:
self.cursor.execute(sql_sentence)
except Exception as e:
print("执行查询的sql语句时报错,错误为:", e)
raise e
else:
select_result = self.cursor.fetchall()
if select_result:
return select_result[0][0]
if __name__ == '__main__':
db = DB()
sql = """SELECT ID_ FROM uc_demension WHERE `CODE_`="test_dem_xyz_123";"""
print(db.select(sql))
\ No newline at end of file
import logging
import os
import time
from Homework_files.APITesting_LZJ.common.read_basic_ini import ReadBasicIni
def get_log():
logger = logging.getLogger()
logger.setLevel(level=logging.DEBUG)
log_name = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime(time.time())) + ".log"
log_dir = ReadBasicIni().get_log_dir("log")
log_path = os.path.join(log_dir, log_name)
file_handler = logging.FileHandler(log_path, mode="a", encoding="utf-8")
log_format = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
file_handler.setFormatter(log_format)
logger.addHandler(file_handler)
return logger
import os, configparser
class ReadBasicIni:
def __init__(self):
self.data_config_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data_config")
ini_path = os.path.join(self.data_config_path, "basic_config.ini")
self.conf = configparser.ConfigParser()
self.conf.read(ini_path, encoding="utf-8")
def get_url(self, key):
try:
return self.conf.get("host", key)
except Exception as e:
raise e
def sql_connect_msg(self, key):
try:
return self.conf.get("sql", key)
except Exception as e:
raise e
def get_log_dir(self, key):
try:
dir_name = self.conf.get("report", key)
except Exception as e:
raise e
else:
report_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "report")
return os.path.join(report_path, dir_name)
\ No newline at end of file
import openpyxl
from Homework_files.APITesting_LZJ.common.read_ini import ReadIni
from Homework_files.APITesting_LZJ.common.read_json import read_json
class ReadExcel:
def __init__(self):
self.ini = ReadIni()
case_data_path = self.ini.get_file_path("case")
expect_data_path = self.ini.get_file_path("expect")
sql_data_path = self.ini.get_file_path("sql")
excel_path = self.ini.get_file_path("excel")
self.case_data_dict = read_json(case_data_path)
self.expect_data_dict = read_json(expect_data_path)
self.sql_data_dict = read_json(sql_data_path)
table_name = self.ini.get_table_name("table")
try:
wb = openpyxl.load_workbook(excel_path)
self.ws = wb[table_name]
except Exception as e:
print("加载工作簿和获取工作表时报错,错误为:", e)
raise e
def __get_cell_value(self, column: str, row: int) -> str:
try:
cell_value = self.ws[column + str(row)].value
except Exception as e:
print("获取指定单元格数据报错,错误为:", e)
raise e
else:
if cell_value is None:
return None
elif cell_value.strip():
return cell_value.strip()
def module_name(self, row):
return self.__get_cell_value("B", row)
def api_name(self, row):
return self.__get_cell_value("C", row)
def req_method(self, row):
return self.__get_cell_value("F", row)
def req_url(self, row):
host = self.ini.get_url("test_host")
path = self.__get_cell_value("G", row)
if path is not None:
return host+path
else:
return None
def case_mime(self, row):
mime = self.__get_cell_value("H", row)
if mime is not None:
return mime.lower()
else:
return None
def case_data(self, row):
case_data_key = self.__get_cell_value("i", row)
if case_data_key is not None:
module_name = self.module_name(row)
api_name = self.api_name(row)
return self.case_data_dict[module_name][api_name][case_data_key]
else:
return None
def expect_data(self, row):
expect_data_key = self.__get_cell_value("j", row)
if expect_data_key is not None:
module_name = self.module_name(row)
api_name = self.api_name(row)
return self.expect_data_dict[module_name][api_name][expect_data_key]
else:
return None
def sql_type(self, row):
sql_sentence_type = self.__get_cell_value("k", row)
if sql_sentence_type is not None:
return sql_sentence_type.lower()
else:
return None
def sql_data(self, row):
sql_data_key = self.__get_cell_value("l", row)
if sql_data_key is not None:
module_name = self.module_name(row)
api_name = self.api_name(row)
return self.sql_data_dict[module_name][api_name][sql_data_key]
else:
return None
def update_key(self, row):
return self.__get_cell_value("m", row)
def get_data(self):
data_list = []
for row in range(2, self.ws.max_row+1):
req_method = self.req_method(row)
req_url = self.req_url(row)
case_mime = self.case_mime(row)
case_data = self.case_data(row)
expect_data = self.expect_data(row)
sql_type = self.sql_type(row)
sql_data = self.sql_data(row)
update_key = self.update_key(row)
if req_method is not None and req_url is not None:
row_list = [req_method, req_url, case_mime, case_data, expect_data, sql_type, sql_data, update_key]
data_list.append(row_list)
else:
return data_list
if __name__ == '__main__':
excel = ReadExcel()
print(excel.get_data())
\ No newline at end of file
import configparser
import os
class ReadIni:
def __init__(self):
self.data_config_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data_config")
ini_path = os.path.join(self.data_config_path, "config.ini")
self.conf = configparser.ConfigParser()
self.conf.read(ini_path, encoding="utf-8")
def get_file_path(self, key):
try:
file_name = self.conf.get("file", key)
except Exception as e:
print("获取文件的名称时,传入的key错误,错误为:", e)
raise e
else:
return os.path.join(self.data_config_path, file_name)
def get_url(self, key):
try:
return self.conf.get("host", key)
except Exception as e:
print("获取被测系统的域名时,传入的key错误,错误为:", e)
raise e
def get_table_name(self, key):
try:
return self.conf.get("table_name", key)
except Exception as e:
print("获取工作表名称时,传入的key错误,错误为:", e)
raise e
def connect_database_msg(self, key):
try:
return self.conf.get("sql", key)
except Exception as e:
print("获取数据库链接的配置信息时发生错误,错误为:", e)
raise e
if __name__ == '__main__':
ini = ReadIni()
print(ini.get_file_path('excel'))
\ No newline at end of file
import json
import os
def read_json(file_path):
if os.path.isfile(file_path) and file_path.endswith(".json"):
try:
with open(file_path, mode="r", encoding="utf-8") as f:
return json.load(f)
except Exception as e:
print("读取json文件时发生错误,请查看json文件的内容是否正常,错误为:", e)
raise e
else:
raise FileNotFoundError("传入的json文件路径错误")
if __name__ == '__main__':
path = r'D:\Project\PythonDoc\test61\test61\APIAutoTest_v2\data_config\case_data1.json'
print(read_json(path))
\ No newline at end of file
-- "a/APITesting_LZJ/data_config/\345\274\240\344\270\211/APIAutoTest.xlsx"
-- "a/APITesting_LZJ/data_config/\345\274\240\344\270\211/case_data.json"
-- "a/APITesting_LZJ/data_config/\345\274\240\344\270\211/config.ini"
-- "a/APITesting_LZJ/data_config/\345\274\240\344\270\211/expect.json"
-- "a/APITesting_LZJ/data_config/\345\274\240\344\270\211/sql_data.json"
-- "a/APITesting_LZJ/data_config/\346\235\216\345\233\233/case_data.json"
-- "a/APITesting_LZJ/data_config/\346\235\216\345\233\233/config.ini"
-- "a/APITesting_LZJ/data_config/\346\235\216\345\233\233/expect.json"
-- "a/APITesting_LZJ/data_config/\346\235\216\345\233\233/sql_data.json"
-- "a/APITesting_LZJ/data_config/\346\235\216\345\233\233/\346\235\216\345\233\233.xlsx"
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title id="head-title">bpm_report.html</title>
<style type="text/css">body {
font-family: Helvetica, Arial, sans-serif;
font-size: 12px;
/* do not increase min-width as some may use split screens */
min-width: 800px;
color: #999;
}
h1 {
font-size: 24px;
color: black;
}
h2 {
font-size: 16px;
color: black;
}
p {
color: black;
}
a {
color: #999;
}
table {
border-collapse: collapse;
}
/******************************
* SUMMARY INFORMATION
******************************/
#environment td {
padding: 5px;
border: 1px solid #e6e6e6;
vertical-align: top;
}
#environment tr:nth-child(odd) {
background-color: #f6f6f6;
}
#environment ul {
margin: 0;
padding: 0 20px;
}
/******************************
* TEST RESULT COLORS
******************************/
span.passed,
.passed .col-result {
color: green;
}
span.skipped,
span.xfailed,
span.rerun,
.skipped .col-result,
.xfailed .col-result,
.rerun .col-result {
color: orange;
}
span.error,
span.failed,
span.xpassed,
.error .col-result,
.failed .col-result,
.xpassed .col-result {
color: red;
}
.col-links__extra {
margin-right: 3px;
}
/******************************
* RESULTS TABLE
*
* 1. Table Layout
* 2. Extra
* 3. Sorting items
*
******************************/
/*------------------
* 1. Table Layout
*------------------*/
#results-table {
border: 1px solid #e6e6e6;
color: #999;
font-size: 12px;
width: 100%;
}
#results-table th,
#results-table td {
padding: 5px;
border: 1px solid #e6e6e6;
text-align: left;
}
#results-table th {
font-weight: bold;
}
/*------------------
* 2. Extra
*------------------*/
.logwrapper {
max-height: 230px;
overflow-y: scroll;
background-color: #e6e6e6;
}
.logwrapper.expanded {
max-height: none;
}
.logwrapper.expanded .logexpander:after {
content: "collapse [-]";
}
.logwrapper .logexpander {
z-index: 1;
position: sticky;
top: 10px;
width: max-content;
border: 1px solid;
border-radius: 3px;
padding: 5px 7px;
margin: 10px 0 10px calc(100% - 80px);
cursor: pointer;
background-color: #e6e6e6;
}
.logwrapper .logexpander:after {
content: "expand [+]";
}
.logwrapper .logexpander:hover {
color: #000;
border-color: #000;
}
.logwrapper .log {
min-height: 40px;
position: relative;
top: -50px;
height: calc(100% + 50px);
border: 1px solid #e6e6e6;
color: black;
display: block;
font-family: "Courier New", Courier, monospace;
padding: 5px;
padding-right: 80px;
white-space: pre-wrap;
}
div.media {
border: 1px solid #e6e6e6;
float: right;
height: 240px;
margin: 0 5px;
overflow: hidden;
width: 320px;
}
.media-container {
display: grid;
grid-template-columns: 25px auto 25px;
align-items: center;
flex: 1 1;
overflow: hidden;
height: 200px;
}
.media-container--fullscreen {
grid-template-columns: 0px auto 0px;
}
.media-container__nav--right,
.media-container__nav--left {
text-align: center;
cursor: pointer;
}
.media-container__viewport {
cursor: pointer;
text-align: center;
height: inherit;
}
.media-container__viewport img,
.media-container__viewport video {
object-fit: cover;
width: 100%;
max-height: 100%;
}
.media__name,
.media__counter {
display: flex;
flex-direction: row;
justify-content: space-around;
flex: 0 0 25px;
align-items: center;
}
.collapsible td:not(.col-links) {
cursor: pointer;
}
.collapsible td:not(.col-links):hover::after {
color: #bbb;
font-style: italic;
cursor: pointer;
}
.col-result {
width: 130px;
}
.col-result:hover::after {
content: " (hide details)";
}
.col-result.collapsed:hover::after {
content: " (show details)";
}
#environment-header h2:hover::after {
content: " (hide details)";
color: #bbb;
font-style: italic;
cursor: pointer;
font-size: 12px;
}
#environment-header.collapsed h2:hover::after {
content: " (show details)";
color: #bbb;
font-style: italic;
cursor: pointer;
font-size: 12px;
}
/*------------------
* 3. Sorting items
*------------------*/
.sortable {
cursor: pointer;
}
.sortable.desc:after {
content: " ";
position: relative;
left: 5px;
bottom: -12.5px;
border: 10px solid #4caf50;
border-bottom: 0;
border-left-color: transparent;
border-right-color: transparent;
}
.sortable.asc:after {
content: " ";
position: relative;
left: 5px;
bottom: 12.5px;
border: 10px solid #4caf50;
border-top: 0;
border-left-color: transparent;
border-right-color: transparent;
}
.hidden, .summary__reload__button.hidden {
display: none;
}
.summary__data {
flex: 0 0 550px;
}
.summary__reload {
flex: 1 1;
display: flex;
justify-content: center;
}
.summary__reload__button {
flex: 0 0 300px;
display: flex;
color: white;
font-weight: bold;
background-color: #4caf50;
text-align: center;
justify-content: center;
align-items: center;
border-radius: 3px;
cursor: pointer;
}
.summary__reload__button:hover {
background-color: #46a049;
}
.summary__spacer {
flex: 0 0 550px;
}
.controls {
display: flex;
justify-content: space-between;
}
.filters,
.collapse {
display: flex;
align-items: center;
}
.filters button,
.collapse button {
color: #999;
border: none;
background: none;
cursor: pointer;
text-decoration: underline;
}
.filters button:hover,
.collapse button:hover {
color: #ccc;
}
.filter__label {
margin-right: 10px;
}
</style>
</head>
<body>
<h1 id="title">bpm_report.html</h1>
<p>Report generated on 15-Jul-2024 at 11:28:38 by <a href="https://pypi.python.org/pypi/pytest-html">pytest-html</a>
v4.1.1</p>
<div id="environment-header">
<h2>Environment</h2>
</div>
<table id="environment"></table>
<!-- TEMPLATES -->
<template id="template_environment_row">
<tr>
<td></td>
<td></td>
</tr>
</template>
<template id="template_results-table__body--empty">
<tbody class="results-table-row">
<tr id="not-found-message">
<td colspan="4">No results found. Check the filters.</th>
</tr>
</template>
<template id="template_results-table__tbody">
<tbody class="results-table-row">
<tr class="collapsible">
</tr>
<tr class="extras-row">
<td class="extra" colspan="4">
<div class="extraHTML"></div>
<div class="media">
<div class="media-container">
<div class="media-container__nav--left"><</div>
<div class="media-container__viewport">
<img src="" />
<video controls>
<source src="" type="video/mp4">
</video>
</div>
<div class="media-container__nav--right">></div>
</div>
<div class="media__name"></div>
<div class="media__counter"></div>
</div>
<div class="logwrapper">
<div class="logexpander"></div>
<div class="log"></div>
</div>
</td>
</tr>
</tbody>
</template>
<!-- END TEMPLATES -->
<div class="summary">
<div class="summary__data">
<h2>Summary</h2>
<div class="additional-summary prefix">
</div>
<p class="run-count">0 test took 0 ms.</p>
<p class="filter">(Un)check the boxes to filter the results.</p>
<div class="summary__reload">
<div class="summary__reload__button hidden" onclick="location.reload()">
<div>There are still tests running. <br />Reload this page to get the latest results!</div>
</div>
</div>
<div class="summary__spacer"></div>
<div class="controls">
<div class="filters">
<input checked="true" class="filter" name="filter_checkbox" type="checkbox" data-test-result="failed" disabled/>
<span class="failed">0 Failed,</span>
<input checked="true" class="filter" name="filter_checkbox" type="checkbox" data-test-result="passed" disabled/>
<span class="passed">0 Passed,</span>
<input checked="true" class="filter" name="filter_checkbox" type="checkbox" data-test-result="skipped" disabled/>
<span class="skipped">0 Skipped,</span>
<input checked="true" class="filter" name="filter_checkbox" type="checkbox" data-test-result="xfailed" disabled/>
<span class="xfailed">0 Expected failures,</span>
<input checked="true" class="filter" name="filter_checkbox" type="checkbox" data-test-result="xpassed" disabled/>
<span class="xpassed">0 Unexpected passes,</span>
<input checked="true" class="filter" name="filter_checkbox" type="checkbox" data-test-result="error" />
<span class="error">1 Errors,</span>
<input checked="true" class="filter" name="filter_checkbox" type="checkbox" data-test-result="rerun" disabled/>
<span class="rerun">0 Reruns</span>
</div>
<div class="collapse">
<button id="show_all_details">Show all details</button>&nbsp;/&nbsp;<button id="hide_all_details">Hide all details</button>
</div>
</div>
</div>
<div class="additional-summary summary">
</div>
<div class="additional-summary postfix">
</div>
</div>
<table id="results-table">
<thead id="results-table-head">
<tr>
<th class="sortable" data-column-type="result">Result</th>
<th class="sortable" data-column-type="testId">Test</th>
<th class="sortable" data-column-type="duration">Duration</th>
<th>Links</th>
</tr>
</thead>
</table>
</body>
<footer>
<div id="data-container" data-jsonblob="{&#34;environment&#34;: {&#34;Python&#34;: &#34;3.12.3&#34;, &#34;Platform&#34;: &#34;Windows-11-10.0.22631-SP0&#34;, &#34;Packages&#34;: {&#34;pytest&#34;: &#34;8.2.2&#34;, &#34;pluggy&#34;: &#34;1.5.0&#34;}, &#34;Plugins&#34;: {&#34;Faker&#34;: &#34;25.8.0&#34;, &#34;html&#34;: &#34;4.1.1&#34;, &#34;metadata&#34;: &#34;3.1.1&#34;}}, &#34;tests&#34;: {&#34;Homework_files/APITesting_LZJ/test_case/__init__.py&#34;: [{&#34;extras&#34;: [], &#34;result&#34;: &#34;Error&#34;, &#34;testId&#34;: &#34;Homework_files/APITesting_LZJ/test_case/__init__.py::collect&#34;, &#34;duration&#34;: &#34;0 ms&#34;, &#34;resultsTableRow&#34;: [&#34;&lt;td class=\&#34;col-result\&#34;&gt;Error&lt;/td&gt;&#34;, &#34;&lt;td class=\&#34;col-testId\&#34;&gt;Homework_files/APITesting_LZJ/test_case/__init__.py::collect&lt;/td&gt;&#34;, &#34;&lt;td class=\&#34;col-duration\&#34;&gt;0 ms&lt;/td&gt;&#34;, &#34;&lt;td class=\&#34;col-links\&#34;&gt;&lt;/td&gt;&#34;], &#34;log&#34;: &#34;Homework_files\\APITesting_LZJ\\test_case\\__init__.py:17: in &amp;lt;module&amp;gt;\n log = get_logs()\nHomework_files\\APITesting_LZJ\\test_case\\__init__.py:12: in get_logs\n file_handler = logging.FileHandler(log_path, mode=&amp;quot;a&amp;quot;, encoding=&amp;quot;utf-8&amp;quot;)\n..\\..\\Python\u672c\u4f53\\Lib\\logging\\__init__.py:1231: in __init__\n StreamHandler.__init__(self, self._open())\n..\\..\\Python\u672c\u4f53\\Lib\\logging\\__init__.py:1263: in _open\n return open_func(self.baseFilename, self.mode,\nE FileNotFoundError: [Errno 2] No such file or directory: &amp;#x27;F:\\\\Python\u5de5\u4f5c\\\\Python\u9879\u76ee\u6587\u4ef6\\\\python_base\\\\Homework_files\\\\APITesting_LZJ\\\\test_case\\\\report\\\\result_log\\\\2024_07_15_11_28_38.log&amp;#x27;\n&#34;}]}, &#34;renderCollapsed&#34;: [&#34;passed&#34;], &#34;initialSort&#34;: &#34;result&#34;, &#34;title&#34;: &#34;bpm_report.html&#34;}"></div>
<script>
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
const { getCollapsedCategory, setCollapsedIds } = require('./storage.js')
class DataManager {
setManager(data) {
const collapsedCategories = [...getCollapsedCategory(data.renderCollapsed)]
const collapsedIds = []
const tests = Object.values(data.tests).flat().map((test, index) => {
const collapsed = collapsedCategories.includes(test.result.toLowerCase())
const id = `test_${index}`
if (collapsed) {
collapsedIds.push(id)
}
return {
...test,
id,
collapsed,
}
})
const dataBlob = { ...data, tests }
this.data = { ...dataBlob }
this.renderData = { ...dataBlob }
setCollapsedIds(collapsedIds)
}
get allData() {
return { ...this.data }
}
resetRender() {
this.renderData = { ...this.data }
}
setRender(data) {
this.renderData.tests = [...data]
}
toggleCollapsedItem(id) {
this.renderData.tests = this.renderData.tests.map((test) =>
test.id === id ? { ...test, collapsed: !test.collapsed } : test,
)
}
set allCollapsed(collapsed) {
this.renderData = { ...this.renderData, tests: [...this.renderData.tests.map((test) => (
{ ...test, collapsed }
))] }
}
get testSubset() {
return [...this.renderData.tests]
}
get environment() {
return this.renderData.environment
}
get initialSort() {
return this.data.initialSort
}
}
module.exports = {
manager: new DataManager(),
}
},{"./storage.js":8}],2:[function(require,module,exports){
const mediaViewer = require('./mediaviewer.js')
const templateEnvRow = document.getElementById('template_environment_row')
const templateResult = document.getElementById('template_results-table__tbody')
function htmlToElements(html) {
const temp = document.createElement('template')
temp.innerHTML = html
return temp.content.childNodes
}
const find = (selector, elem) => {
if (!elem) {
elem = document
}
return elem.querySelector(selector)
}
const findAll = (selector, elem) => {
if (!elem) {
elem = document
}
return [...elem.querySelectorAll(selector)]
}
const dom = {
getStaticRow: (key, value) => {
const envRow = templateEnvRow.content.cloneNode(true)
const isObj = typeof value === 'object' && value !== null
const values = isObj ? Object.keys(value).map((k) => `${k}: ${value[k]}`) : null
const valuesElement = htmlToElements(
values ? `<ul>${values.map((val) => `<li>${val}</li>`).join('')}<ul>` : `<div>${value}</div>`)[0]
const td = findAll('td', envRow)
td[0].textContent = key
td[1].appendChild(valuesElement)
return envRow
},
getResultTBody: ({ testId, id, log, extras, resultsTableRow, tableHtml, result, collapsed }) => {
const resultBody = templateResult.content.cloneNode(true)
resultBody.querySelector('tbody').classList.add(result.toLowerCase())
resultBody.querySelector('tbody').id = testId
resultBody.querySelector('.collapsible').dataset.id = id
resultsTableRow.forEach((html) => {
const t = document.createElement('template')
t.innerHTML = html
resultBody.querySelector('.collapsible').appendChild(t.content)
})
if (log) {
// Wrap lines starting with "E" with span.error to color those lines red
const wrappedLog = log.replace(/^E.*$/gm, (match) => `<span class="error">${match}</span>`)
resultBody.querySelector('.log').innerHTML = wrappedLog
} else {
resultBody.querySelector('.log').remove()
}
if (collapsed) {
resultBody.querySelector('.collapsible > td')?.classList.add('collapsed')
resultBody.querySelector('.extras-row').classList.add('hidden')
} else {
resultBody.querySelector('.collapsible > td')?.classList.remove('collapsed')
}
const media = []
extras?.forEach(({ name, format_type, content }) => {
if (['image', 'video'].includes(format_type)) {
media.push({ path: content, name, format_type })
}
if (format_type === 'html') {
resultBody.querySelector('.extraHTML').insertAdjacentHTML('beforeend', `<div>${content}</div>`)
}
})
mediaViewer.setup(resultBody, media)
// Add custom html from the pytest_html_results_table_html hook
tableHtml?.forEach((item) => {
resultBody.querySelector('td[class="extra"]').insertAdjacentHTML('beforeend', item)
})
return resultBody
},
}
module.exports = {
dom,
htmlToElements,
find,
findAll,
}
},{"./mediaviewer.js":6}],3:[function(require,module,exports){
const { manager } = require('./datamanager.js')
const { doSort } = require('./sort.js')
const storageModule = require('./storage.js')
const getFilteredSubSet = (filter) =>
manager.allData.tests.filter(({ result }) => filter.includes(result.toLowerCase()))
const doInitFilter = () => {
const currentFilter = storageModule.getVisible()
const filteredSubset = getFilteredSubSet(currentFilter)
manager.setRender(filteredSubset)
}
const doFilter = (type, show) => {
if (show) {
storageModule.showCategory(type)
} else {
storageModule.hideCategory(type)
}
const currentFilter = storageModule.getVisible()
const filteredSubset = getFilteredSubSet(currentFilter)
manager.setRender(filteredSubset)
const sortColumn = storageModule.getSort()
doSort(sortColumn, true)
}
module.exports = {
doFilter,
doInitFilter,
}
},{"./datamanager.js":1,"./sort.js":7,"./storage.js":8}],4:[function(require,module,exports){
const { redraw, bindEvents, renderStatic } = require('./main.js')
const { doInitFilter } = require('./filter.js')
const { doInitSort } = require('./sort.js')
const { manager } = require('./datamanager.js')
const data = JSON.parse(document.getElementById('data-container').dataset.jsonblob)
function init() {
manager.setManager(data)
doInitFilter()
doInitSort()
renderStatic()
redraw()
bindEvents()
}
init()
},{"./datamanager.js":1,"./filter.js":3,"./main.js":5,"./sort.js":7}],5:[function(require,module,exports){
const { dom, find, findAll } = require('./dom.js')
const { manager } = require('./datamanager.js')
const { doSort } = require('./sort.js')
const { doFilter } = require('./filter.js')
const {
getVisible,
getCollapsedIds,
setCollapsedIds,
getSort,
getSortDirection,
possibleFilters,
} = require('./storage.js')
const removeChildren = (node) => {
while (node.firstChild) {
node.removeChild(node.firstChild)
}
}
const renderStatic = () => {
const renderEnvironmentTable = () => {
const environment = manager.environment
const rows = Object.keys(environment).map((key) => dom.getStaticRow(key, environment[key]))
const table = document.getElementById('environment')
removeChildren(table)
rows.forEach((row) => table.appendChild(row))
}
renderEnvironmentTable()
}
const addItemToggleListener = (elem) => {
elem.addEventListener('click', ({ target }) => {
const id = target.parentElement.dataset.id
manager.toggleCollapsedItem(id)
const collapsedIds = getCollapsedIds()
if (collapsedIds.includes(id)) {
const updated = collapsedIds.filter((item) => item !== id)
setCollapsedIds(updated)
} else {
collapsedIds.push(id)
setCollapsedIds(collapsedIds)
}
redraw()
})
}
const renderContent = (tests) => {
const sortAttr = getSort(manager.initialSort)
const sortAsc = JSON.parse(getSortDirection())
const rows = tests.map(dom.getResultTBody)
const table = document.getElementById('results-table')
const tableHeader = document.getElementById('results-table-head')
const newTable = document.createElement('table')
newTable.id = 'results-table'
// remove all sorting classes and set the relevant
findAll('.sortable', tableHeader).forEach((elem) => elem.classList.remove('asc', 'desc'))
tableHeader.querySelector(`.sortable[data-column-type="${sortAttr}"]`)?.classList.add(sortAsc ? 'desc' : 'asc')
newTable.appendChild(tableHeader)
if (!rows.length) {
const emptyTable = document.getElementById('template_results-table__body--empty').content.cloneNode(true)
newTable.appendChild(emptyTable)
} else {
rows.forEach((row) => {
if (!!row) {
findAll('.collapsible td:not(.col-links', row).forEach(addItemToggleListener)
find('.logexpander', row).addEventListener('click',
(evt) => evt.target.parentNode.classList.toggle('expanded'),
)
newTable.appendChild(row)
}
})
}
table.replaceWith(newTable)
}
const renderDerived = () => {
const currentFilter = getVisible()
possibleFilters.forEach((result) => {
const input = document.querySelector(`input[data-test-result="${result}"]`)
input.checked = currentFilter.includes(result)
})
}
const bindEvents = () => {
const filterColumn = (evt) => {
const { target: element } = evt
const { testResult } = element.dataset
doFilter(testResult, element.checked)
const collapsedIds = getCollapsedIds()
const updated = manager.renderData.tests.map((test) => {
return {
...test,
collapsed: collapsedIds.includes(test.id),
}
})
manager.setRender(updated)
redraw()
}
const header = document.getElementById('environment-header')
header.addEventListener('click', () => {
const table = document.getElementById('environment')
table.classList.toggle('hidden')
header.classList.toggle('collapsed')
})
findAll('input[name="filter_checkbox"]').forEach((elem) => {
elem.addEventListener('click', filterColumn)
})
findAll('.sortable').forEach((elem) => {
elem.addEventListener('click', (evt) => {
const { target: element } = evt
const { columnType } = element.dataset
doSort(columnType)
redraw()
})
})
document.getElementById('show_all_details').addEventListener('click', () => {
manager.allCollapsed = false
setCollapsedIds([])
redraw()
})
document.getElementById('hide_all_details').addEventListener('click', () => {
manager.allCollapsed = true
const allIds = manager.renderData.tests.map((test) => test.id)
setCollapsedIds(allIds)
redraw()
})
}
const redraw = () => {
const { testSubset } = manager
renderContent(testSubset)
renderDerived()
}
module.exports = {
redraw,
bindEvents,
renderStatic,
}
},{"./datamanager.js":1,"./dom.js":2,"./filter.js":3,"./sort.js":7,"./storage.js":8}],6:[function(require,module,exports){
class MediaViewer {
constructor(assets) {
this.assets = assets
this.index = 0
}
nextActive() {
this.index = this.index === this.assets.length - 1 ? 0 : this.index + 1
return [this.activeFile, this.index]
}
prevActive() {
this.index = this.index === 0 ? this.assets.length - 1 : this.index -1
return [this.activeFile, this.index]
}
get currentIndex() {
return this.index
}
get activeFile() {
return this.assets[this.index]
}
}
const setup = (resultBody, assets) => {
if (!assets.length) {
resultBody.querySelector('.media').classList.add('hidden')
return
}
const mediaViewer = new MediaViewer(assets)
const container = resultBody.querySelector('.media-container')
const leftArrow = resultBody.querySelector('.media-container__nav--left')
const rightArrow = resultBody.querySelector('.media-container__nav--right')
const mediaName = resultBody.querySelector('.media__name')
const counter = resultBody.querySelector('.media__counter')
const imageEl = resultBody.querySelector('img')
const sourceEl = resultBody.querySelector('source')
const videoEl = resultBody.querySelector('video')
const setImg = (media, index) => {
if (media?.format_type === 'image') {
imageEl.src = media.path
imageEl.classList.remove('hidden')
videoEl.classList.add('hidden')
} else if (media?.format_type === 'video') {
sourceEl.src = media.path
videoEl.classList.remove('hidden')
imageEl.classList.add('hidden')
}
mediaName.innerText = media?.name
counter.innerText = `${index + 1} / ${assets.length}`
}
setImg(mediaViewer.activeFile, mediaViewer.currentIndex)
const moveLeft = () => {
const [media, index] = mediaViewer.prevActive()
setImg(media, index)
}
const doRight = () => {
const [media, index] = mediaViewer.nextActive()
setImg(media, index)
}
const openImg = () => {
window.open(mediaViewer.activeFile.path, '_blank')
}
if (assets.length === 1) {
container.classList.add('media-container--fullscreen')
} else {
leftArrow.addEventListener('click', moveLeft)
rightArrow.addEventListener('click', doRight)
}
imageEl.addEventListener('click', openImg)
}
module.exports = {
setup,
}
},{}],7:[function(require,module,exports){
const { manager } = require('./datamanager.js')
const storageModule = require('./storage.js')
const genericSort = (list, key, ascending, customOrder) => {
let sorted
if (customOrder) {
sorted = list.sort((a, b) => {
const aValue = a.result.toLowerCase()
const bValue = b.result.toLowerCase()
const aIndex = customOrder.findIndex((item) => item.toLowerCase() === aValue)
const bIndex = customOrder.findIndex((item) => item.toLowerCase() === bValue)
// Compare the indices to determine the sort order
return aIndex - bIndex
})
} else {
sorted = list.sort((a, b) => a[key] === b[key] ? 0 : a[key] > b[key] ? 1 : -1)
}
if (ascending) {
sorted.reverse()
}
return sorted
}
const durationSort = (list, ascending) => {
const parseDuration = (duration) => {
if (duration.includes(':')) {
// If it's in the format "HH:mm:ss"
const [hours, minutes, seconds] = duration.split(':').map(Number)
return (hours * 3600 + minutes * 60 + seconds) * 1000
} else {
// If it's in the format "nnn ms"
return parseInt(duration)
}
}
const sorted = list.sort((a, b) => parseDuration(a['duration']) - parseDuration(b['duration']))
if (ascending) {
sorted.reverse()
}
return sorted
}
const doInitSort = () => {
const type = storageModule.getSort(manager.initialSort)
const ascending = storageModule.getSortDirection()
const list = manager.testSubset
const initialOrder = ['Error', 'Failed', 'Rerun', 'XFailed', 'XPassed', 'Skipped', 'Passed']
storageModule.setSort(type)
storageModule.setSortDirection(ascending)
if (type?.toLowerCase() === 'original') {
manager.setRender(list)
} else {
let sortedList
switch (type) {
case 'duration':
sortedList = durationSort(list, ascending)
break
case 'result':
sortedList = genericSort(list, type, ascending, initialOrder)
break
default:
sortedList = genericSort(list, type, ascending)
break
}
manager.setRender(sortedList)
}
}
const doSort = (type, skipDirection) => {
const newSortType = storageModule.getSort(manager.initialSort) !== type
const currentAsc = storageModule.getSortDirection()
let ascending
if (skipDirection) {
ascending = currentAsc
} else {
ascending = newSortType ? false : !currentAsc
}
storageModule.setSort(type)
storageModule.setSortDirection(ascending)
const list = manager.testSubset
const sortedList = type === 'duration' ? durationSort(list, ascending) : genericSort(list, type, ascending)
manager.setRender(sortedList)
}
module.exports = {
doInitSort,
doSort,
}
},{"./datamanager.js":1,"./storage.js":8}],8:[function(require,module,exports){
const possibleFilters = [
'passed',
'skipped',
'failed',
'error',
'xfailed',
'xpassed',
'rerun',
]
const getVisible = () => {
const url = new URL(window.location.href)
const settings = new URLSearchParams(url.search).get('visible')
const lower = (item) => {
const lowerItem = item.toLowerCase()
if (possibleFilters.includes(lowerItem)) {
return lowerItem
}
return null
}
return settings === null ?
possibleFilters :
[...new Set(settings?.split(',').map(lower).filter((item) => item))]
}
const hideCategory = (categoryToHide) => {
const url = new URL(window.location.href)
const visibleParams = new URLSearchParams(url.search).get('visible')
const currentVisible = visibleParams ? visibleParams.split(',') : [...possibleFilters]
const settings = [...new Set(currentVisible)].filter((f) => f !== categoryToHide).join(',')
url.searchParams.set('visible', settings)
window.history.pushState({}, null, unescape(url.href))
}
const showCategory = (categoryToShow) => {
if (typeof window === 'undefined') {
return
}
const url = new URL(window.location.href)
const currentVisible = new URLSearchParams(url.search).get('visible')?.split(',').filter(Boolean) ||
[...possibleFilters]
const settings = [...new Set([categoryToShow, ...currentVisible])]
const noFilter = possibleFilters.length === settings.length || !settings.length
noFilter ? url.searchParams.delete('visible') : url.searchParams.set('visible', settings.join(','))
window.history.pushState({}, null, unescape(url.href))
}
const getSort = (initialSort) => {
const url = new URL(window.location.href)
let sort = new URLSearchParams(url.search).get('sort')
if (!sort) {
sort = initialSort || 'result'
}
return sort
}
const setSort = (type) => {
const url = new URL(window.location.href)
url.searchParams.set('sort', type)
window.history.pushState({}, null, unescape(url.href))
}
const getCollapsedCategory = (renderCollapsed) => {
let categories
if (typeof window !== 'undefined') {
const url = new URL(window.location.href)
const collapsedItems = new URLSearchParams(url.search).get('collapsed')
switch (true) {
case !renderCollapsed && collapsedItems === null:
categories = ['passed']
break
case collapsedItems?.length === 0 || /^["']{2}$/.test(collapsedItems):
categories = []
break
case /^all$/.test(collapsedItems) || collapsedItems === null && /^all$/.test(renderCollapsed):
categories = [...possibleFilters]
break
default:
categories = collapsedItems?.split(',').map((item) => item.toLowerCase()) || renderCollapsed
break
}
} else {
categories = []
}
return categories
}
const getSortDirection = () => JSON.parse(sessionStorage.getItem('sortAsc')) || false
const setSortDirection = (ascending) => sessionStorage.setItem('sortAsc', ascending)
const getCollapsedIds = () => JSON.parse(sessionStorage.getItem('collapsedIds')) || []
const setCollapsedIds = (list) => sessionStorage.setItem('collapsedIds', JSON.stringify(list))
module.exports = {
getVisible,
hideCategory,
showCategory,
getCollapsedIds,
setCollapsedIds,
getSort,
setSort,
getSortDirection,
setSortDirection,
getCollapsedCategory,
possibleFilters,
}
},{}]},{},[4]);
</script>
</footer>
</html>
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
import requests
from Homework_files.APITesting_LZJ.common.read_ini import ReadIni
class RequestMethod:
def __init__(self):
login_url = ReadIni().get_url("test_host") + "/auth"
login_data = {"username": "admin", "password": "FMgcBcmzaLp5J8AFyR8XF0MhHRpBhHNFQyDn7HI2nBO0B9RgCEnhVjvXjLMNjwoRKp01dwHueQGZbZcsEdAQQwY1QXvJrr8Z4Jv2Wn5UCC4IKuH9cIeevsc2zSEMmKULN9FJV4e9DBbnTMoxHqyawMlxVN/pidjeA0kkXjOsBE8="}
self.bpm_session = requests.sessions.Session()
self.bpm_session.headers["Authorization"] = "Bearer "+self.bpm_session.post(url=login_url, json=login_data).json()["token"]
def request_all(self, req_method, req_url, req_mime, case_data):
if req_mime == "application/json" or req_mime == "json":
return self.bpm_session.request(method=req_method, url=req_url, json=case_data)
elif req_mime == "application/x-www-form-urlencoded" or req_mime == "x-www-form-urlencoded" or req_mime == "form":
return self.bpm_session.request(method=req_method, url=req_url, data=case_data)
elif req_mime == "multipart/form-data" or req_mime == "form-data":
return self.bpm_session.request(method=req_method, url=req_url, files=case_data)
elif req_mime == "query" or req_mime == "params":
return self.bpm_session.request(method=req_method, url=req_url, params=case_data)
elif req_mime is None:
return self.bpm_session.request(method=req_method, url=req_url)
else:
raise ValueError("传入媒体类型的值错误,请自行封装")
\ No newline at end of file
import functools
import logging
import os
import time
def get_logs():
logger = logging.getLogger()
logger.setLevel(level=logging.DEBUG)
log_name = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime(time.time())) + ".log"
log_dir = os.path.join(os.path.join(os.path.dirname(__file__), "report"), "result_log")
log_path = os.path.join(log_dir, log_name)
file_handler = logging.FileHandler(log_path, mode="a", encoding="utf-8")
log_format = logging.Formatter('%(asctime)s - %(levelname)s: %(message)s')
file_handler.setFormatter(log_format)
logger.addHandler(file_handler)
return logger
log = get_logs()
def log_decorator(func_name):
@functools.wraps(func_name)
def inner(*arg, **kwargs):
try:
log.info(f"执行的功能名称为:{func_name.__name__}, 功能所在的文件为:{func_name.__code__.co_filename}, 所在的行为:{func_name.__code__.co_firstlineno}")
value = func_name(*arg, **kwargs)
except Exception as e:
log.error(f"执行的功能名称为:{func_name.__name__}, 功能所在的文件为:{func_name.__code__.co_filename}, 所在的行为:{func_name.__code__.co_firstlineno}报错,错误为:{e}")
raise e
else:
return value
return inner
\ No newline at end of file
import pytest
data_dict = {}
def set_value(key, value):
data_dict[key] = value
def get_value(key):
if key in data_dict.keys():
return data_dict[key]
else:
return "not fount"
@pytest.fixture(scope="session")
def set_depends_value():
yield set_value
@pytest.fixture(scope="session")
def get_depends_value():
yield get_value
\ No newline at end of file
import random
import string
import pytest
import requests
case_datas = [
[{"code": "需要更新"}, {"isDelete":"0"}],
[{"code": ""}, {"message":"必填:code维度编码必填!"}],
[{"": "abctest"}, {"message":"Required String parameter 'code' is not present"}]
]
class TestBPM:
host = "http://36.139.193.99:8088"
@pytest.mark.dependency()
def test_login(self, set_depends_value):
login_url = self.host + "/auth"
login_data = {"username": "admin",
"password": "FMgcBcmzaLp5J8AFyR8XF0MhHRpBhHNFQyDn7HI2nBO0B9RgCEnhVjvXjLMNjwoRKp01dwHueQGZbZcsEdAQQwY1QXvJrr8Z4Jv2Wn5UCC4IKuH9cIeevsc2zSEMmKULN9FJV4e9DBbnTMoxHqyawMlxVN/pidjeA0kkXjOsBE8="}
res = requests.request(method="post", url=login_url, json=login_data)
try:
assert "超级管理员" in res.text
except AssertionError:
raise AssertionError("断言失败")
else:
token = res.json().get("token")
set_depends_value("TOKEN", token)
@pytest.mark.dependency(depends=["TestBPM::test_login"])
def test_add_dem(self, get_depends_value, set_depends_value):
add_dem_url = self.host + "/api/demension/v1/dem/addDem"
dem_code = "".join(random.sample(string.ascii_letters, 12))
add_dem_data = {
"code": dem_code,
"description": "",
"isDefault": 0,
"name": "测试"+"".join(random.sample(string.ascii_letters, 8))
}
token = get_depends_value("TOKEN")
res = requests.post(url=add_dem_url, json=add_dem_data, headers={"Authorization": "Bearer "+token})
try:
assert "成功" in res.text
except AssertionError:
raise AssertionError("断言失败")
else:
set_depends_value("demCode", dem_code)
@pytest.mark.parametrize("case_data, expect_data", case_datas)
@pytest.mark.dependency(depends=["TestBPM::test_add_dem"])
def test_get_dem_msg(self, get_depends_value, set_depends_value, case_data, expect_data):
get_dem_msg_url = self.host + "/api/demension/v1/dem/getDem"
token = get_depends_value("TOKEN")
if "code" in case_data.keys():
if case_data["code"] == "需要更新":
case_data["code"] = get_depends_value("demCode")
res = requests.get(url=get_dem_msg_url, params=case_data, headers={"Authorization": "Bearer "+token})
try:
for key in expect_data:
assert expect_data[key] == res.json().get(key)
except AssertionError:
raise AssertionError("断言失败")
else:
if "id" in res.json():
dem_id = res.json()["id"]
set_depends_value("demId", dem_id)
print("断言成功")
@pytest.mark.dependency(depends=["TestBPM::test_get_dem_msg"])
def test_org(self, get_depends_value):
print(get_depends_value("TOKEN"))
print(get_depends_value("demId"))
print(get_depends_value("demCode"))
\ No newline at end of file
USERNAME = "张三"
USERNAME = "张三"
\ No newline at end of file
import pytest
import pytest
from Homework_files.APITesting_LZJ.common.db import DB
from Homework_files.APITesting_LZJ.request_method.request_method import RequestMethod
@pytest.fixture(scope="session")
def req_fix():
req = RequestMethod()
yield req
@pytest.fixture(scope="session")
def db_fix():
db = DB()
yield db
db.close()
\ No newline at end of file
import pytest
import pytest
from Homework_files.APITesting_LZJ.common.read_excel import ReadExcel
from Homework_files.APITesting_LZJ.test_case import log_decorator
from Homework_files.APITesting_LZJ.test_case.test_张三 import USERNAME
class TestBPM:
@log_decorator
@pytest.mark.parametrize("case_method, case_url, case_mime, case_data, expect_data, sql_type, sql_data, update_key", ReadExcel(USERNAME).get_data())
def test_bpm(self, req_fix, db_fix, case_method, case_url, case_mime, case_data, expect_data, sql_type, sql_data, update_key):
print(case_method, case_url, case_mime, case_data, expect_data, sql_type, sql_data, update_key)
if sql_type == "delete":
db_fix.delete(sql_data)
elif sql_type == "select":
select_result = db_fix.select(sql_data)
case_data[update_key] = select_result
elif sql_type == "select|delete" or sql_type == "delete|select":
db_fix.delete(sql_data["delete"])
select_result = db_fix.select(sql_data["select"])
case_data[update_key] = select_result
result = req_fix.request_all(req_method=case_method, req_url=case_url, req_mime=case_mime, case_data=case_data)
print(result.text)
try:
for key in expect_data:
assert expect_data[key] == result.json().get(key)
except AssertionError:
raise AssertionError(f"断言失败, 用例数据为:{case_data}, 期望数据为:{expect_data}, 服务器返回的数据为:{result.text}")
else:
print("断言成功")
\ No newline at end of file
# -*-coding:utf-8 -*- #
# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName: test61
# FileName: __init__.py
# Author: lao_zhao
# Datetime: 2024/7/12 16:53
# Description:
#
# ---------------------------------------------------------------------------
USERNAME = "李四"
\ No newline at end of file
# -*-coding:utf-8 -*- #
# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName: test61
# FileName: conftest.py
# Author: lao_zhao
# Datetime: 2024/7/12 14:40
# Description:
#
# ---------------------------------------------------------------------------
import pytest
from APIAutoTest_v3_1.common.db import DB
from APIAutoTest_v3_1.request_method.request_method import RequestMethod
@pytest.fixture(scope="session")
def req_fix():
req = RequestMethod()
yield req
@pytest.fixture(scope="session")
def db_fix():
db = DB()
yield db
db.close()
\ No newline at end of file
# -*-coding:utf-8 -*- #
# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName: test61
# FileName: test_case.py
# Author: lao_zhao
# Datetime: 2024/7/12 14:38
# Description:
#
# ---------------------------------------------------------------------------
import pytest
from APIAutoTest_v3_1.common.read_excel import ReadExcel
from APIAutoTest_v3_1.test_case.test_李四 import USERNAME
class TestBPM:
@pytest.mark.parametrize("case_method, case_url, case_mime, case_data, expect_data, sql_type, sql_data, update_key", ReadExcel(USERNAME).get_data())
def test_bpm(self, req_fix, db_fix, case_method, case_url, case_mime, case_data, expect_data, sql_type, sql_data, update_key):
print(case_method, case_url, case_mime, case_data, expect_data, sql_type, sql_data, update_key)
# 判断sql语句类型是否为delete,如果是,使用DB类对象调用delete方法执行删除的sql语句
if sql_type == "delete":
# 使用DB类对象调用delete方法执行删除的sql语句, DB类对象就是自定义固件db_fix
db_fix.delete(sql_data)
# 判断sql语句的类型是否为select,如果是,使用DB类对象调用select方法执行查询语句,并接收查询的结果
elif sql_type == "select":
# 使用DB类对象调用select方法执行查询语句,并接收查询的结果
select_result = db_fix.select(sql_data)
# 将查询结果更新到用例数据中
case_data[update_key] = select_result
# 判断sql语句的类型是否为select|delete 或者 delete|select ,如果是,使用DB类对象执行sql语句
elif sql_type == "select|delete" or sql_type == "delete|select":
# 使用DB类对象调用delete方法执行删除的sql语句。
db_fix.delete(sql_data["delete"])
# 使用DB类对象调用select方法执行查询的sql语句, 并接收查询的结果
select_result = db_fix.select(sql_data["select"])
# 将查询结果更新到用例数据中
case_data[update_key] = select_result
result = req_fix.request_all(req_method=case_method, req_url=case_url, req_mime=case_mime, case_data=case_data)
print(result.text)
try:
for key in expect_data:
assert expect_data[key] == result.json().get(key)
except AssertionError:
raise AssertionError("断言失败,描述失败的原因")
else:
print("断言成功")
\ No newline at end of file
接口自动化框架
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment