用模板做网站会被盗吗/网站如何优化

用模板做网站会被盗吗,网站如何优化,陕西省安康市建行 网站,域名 备案 没有网站吗这里写目录标题 PytestInitRun3. 根据命令行选项将不同的值传递给测试函数 Report1. 向测试报告标题添加信息2. 分析测试持续时间 pytest --durations33. 增量测试 - 测试步骤--junitxml{report}.xml1. testsuite1.1 在测试套件级别添加属性节点 record_testsuite_property 2. …

这里写目录标题

  • Pytest
    • Init
    • Run
      • 3. 根据命令行选项将不同的值传递给测试函数
    • Report
      • 1. 向测试报告标题添加信息
      • 2. 分析测试持续时间 `pytest --durations=3`
      • 3. 增量测试 - 测试步骤
      • --junitxml={report}.xml
        • 1. testsuite
          • 1.1 在测试套件级别添加属性节点 record_testsuite_property
        • 2. testcase
          • 2.1 记录测试的其他信息 record_property
          • 2.2 向testcase元素添加额外的xml属性 record_xml_attribute
    • Hooks
    • other plugin 好玩好用的

Pytest

Init

Run

  1. 更改配置pytest.ini与项目同级
# content of pytest.ini
# Example 1: have pytest look for "check" instead of "test"
[pytest]
;更改目录递归
norecursedirs = .svn _build tmp*;更改命名约定
python_files = check_*.py
python_classes = Check
python_functions = *_check
;可以通过在模式之间添加空格来检查多个 glob 模式
;python_files = test_*.py example_*.py;将命令行参数解释
;addopts = --tb=short
;addopts = --pyargs
;export PYTEST_ADDOPTS="-v"
addopts = -vv --html-report=report.html
  1. 引进@pytest.mark.parametrize中ids导致编码乱码
def pytest_collection_modifyitems(items):for item in items:item.name = item.name.encode('utf-8').decode('unicode-escape')item._nodeid = item._nodeid.encode('utf-8').decode('unicode-escape')
  1. 定义自己对失败断言的解释 pytest_assertrepr_compare(config, op, left, right)

    • config (Config) – The pytest config object.
    • op (str) – The operator, e.g. “==”, “!=”, “not in”.
    • left (object) – The left operand.
    • right (object) – The right operand.
# content of conftest.py
from test_foocompare import Foodef pytest_assertrepr_compare(op, left, right):if isinstance(left, Foo) and isinstance(right, Foo) and op == "==":return ["Comparing Foo instances:",f"   vals: {left.val} != {right.val}",]
# content of test_foocompare.py
class Foo:def __init__(self, val):self.val = valdef __eq__(self, other):return self.val == other.valdef test_compare():f1 = Foo(1)f2 = Foo(2)assert f1 == f2

output

$ pytest -q test_foocompare.py
F                                                                    [100%]
================================= FAILURES =================================
_______________________________ test_compare _______________________________def test_compare():f1 = Foo(1)f2 = Foo(2)
>       assert f1 == f2
E       assert Comparing Foo instances:
E            vals: 1 != 2test_foocompare.py:12: AssertionError
========================= short test summary info ==========================
FAILED test_foocompare.py::test_compare - assert Comparing Foo instances:
1 failed in 0.12s

3. 根据命令行选项将不同的值传递给测试函数

# content of conftest.py
import pytestdef pytest_addoption(parser):parser.addoption("--cmdopt", action="store", default="type1", help="my option: type1 or type2")@pytest.fixture
def cmdopt(request):return request.config.getoption("--cmdopt")
# content of test_sample.py
def test_answer(cmdopt):if cmdopt == "type1":print("first")elif cmdopt == "type2":print("second")assert 0  # to see what was printed

output

# ************
# 没有提供参数
# ************
$ pytest -q test_sample.py 
F                                                                    [100%]
================================= FAILURES =================================
_______________________________ test_answer ________________________________cmdopt = 'type1'def test_answer(cmdopt):if cmdopt == "type1":print("first")elif cmdopt == "type2":print("second")
>       assert 0  # to see what was printed
E       assert 0test_sample.py:6: AssertionError
--------------------------- Captured stdout call ---------------------------
first
========================= short test summary info ==========================
FAILED test_sample.py::test_answer - assert 0
1 failed in 0.12s# ************
# 提供参数
# ************
$ pytest -q --cmdopt=type2
F                                                                    [100%]
================================= FAILURES =================================
_______________________________ test_answer ________________________________cmdopt = 'type2'def test_answer(cmdopt):if cmdopt == "type1":print("first")elif cmdopt == "type2":print("second")
>       assert 0  # to see what was printed
E       assert 0test_sample.py:6: AssertionError
--------------------------- Captured stdout call ---------------------------
second
========================= short test summary info ==========================
FAILED test_sample.py::test_answer - assert 0
1 failed in 0.12s
  • 如果需要更详细信息
# content of conftest.py
import pytestdef type_checker(value):msg = "cmdopt must specify a numeric type as typeNNN"if not value.startswith("type"):raise pytest.UsageError(msg)try:int(value[4:])except ValueError:raise pytest.UsageError(msg)return valuedef pytest_addoption(parser):parser.addoption("--cmdopt",action="store",default="type1",help="my option: type1 or type2",type=type_checker,)

output

$ pytest -q --cmdopt=type3
ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: argument --cmdopt: invalid choice: 'type3' (choose from 'type1', 'type2')

Report

1. 向测试报告标题添加信息

1.1

# content of conftest.pydef pytest_report_header(config):return "project deps: mylib-1.1"

output

$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
project deps: mylib-1.1
rootdir: /home/sweet/project
collected 0 items========================== no tests ran in 0.12s ===========================

1.2 返回字符串列表,这些字符串将被视为多行信息

# content of conftest.pydef pytest_report_header(config):if config.get_verbosity() > 0:return ["info1: did you know that ...", "did you?"]

output 仅在使用“-v”运行时才会添加信息

$ pytest -v
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
cachedir: .pytest_cache
info1: did you know that ...
did you?
rootdir: /home/sweet/project
collecting ... collected 0 items========================== no tests ran in 0.12s ===========================

2. 分析测试持续时间 pytest --durations=3

# content of test_some_are_slow.py
import timedef test_funcfast():time.sleep(0.1)def test_funcslow1():time.sleep(0.2)def test_funcslow2():time.sleep(0.3)

output

$ pytest --durations=3
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 3 itemstest_some_are_slow.py ...                                            [100%]=========================== slowest 3 durations ============================
0.30s call     test_some_are_slow.py::test_funcslow2
0.20s call     test_some_are_slow.py::test_funcslow1
0.10s call     test_some_are_slow.py::test_funcfast
============================ 3 passed in 0.12s =============================

3. 增量测试 - 测试步骤

如果前置步骤其中一个步骤失败,则后续步骤将预期失败。

# content of conftest.pyfrom typing import Dict, Tupleimport pytest# store history of failures per test class name and per index in parametrize (if parametrize used)
_test_failed_incremental: Dict[str, Dict[Tuple[int, ...], str]] = {}def pytest_runtest_makereport(item, call):if "incremental" in item.keywords:# incremental marker is usedif call.excinfo is not None:# the test has failed# retrieve the class name of the testcls_name = str(item.cls)# retrieve the index of the test (if parametrize is used in combination with incremental)parametrize_index = (tuple(item.callspec.indices.values())if hasattr(item, "callspec")else ())# retrieve the name of the test functiontest_name = item.originalname or item.name# store in _test_failed_incremental the original name of the failed test_test_failed_incremental.setdefault(cls_name, {}).setdefault(parametrize_index, test_name)def pytest_runtest_setup(item):if "incremental" in item.keywords:# retrieve the class name of the testcls_name = str(item.cls)# check if a previous test has failed for this classif cls_name in _test_failed_incremental:# retrieve the index of the test (if parametrize is used in combination with incremental)parametrize_index = (tuple(item.callspec.indices.values())if hasattr(item, "callspec")else ())# retrieve the name of the first test function to fail for this class name and indextest_name = _test_failed_incremental[cls_name].get(parametrize_index, None)# if name found, test has failed for the combination of class name & test nameif test_name is not None:pytest.xfail(f"previous test failed ({test_name})")
# content of test_step.pyimport pytest@pytest.mark.incremental
class TestUserHandling:def test_login(self):passdef test_modification(self):assert 0def test_deletion(self):passdef test_normal():pass

output

$ pytest -rx
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 4 itemstest_step.py .Fx.                                                    [100%]================================= FAILURES =================================
____________________ TestUserHandling.test_modification ____________________self = <test_step.TestUserHandling object at 0xdeadbeef0001>def test_modification(self):
>       assert 0
E       assert 0test_step.py:11: AssertionError
========================= short test summary info ==========================
XFAIL test_step.py::TestUserHandling::test_deletion - reason: previous test failed (test_modification)
================== 1 failed, 2 passed, 1 xfailed in 0.12s ==================

–junitxml={report}.xml

https://docs.pytest.org/en/stable/reference/reference.html
pytest v6.0+ 默认 xunit2 不支持 testcase添加属性
建议设置

  • pytest.ini中配置junit_family=xunit1
  • pytest -o junit_family=xunit1
<?xml version="1.0" encoding="utf-8"?>
<testsuites><testsuite name="pytest" errors="0" failures="0" skipped="0" tests="2" time="0.113"timestamp="2025-03-10T14:53:08.040765+08:00" hostname="Ding-Perlis-MP1Y70F1"><testcase classname="set_classname" name="set_name" file="test_case.py" line="49" time="0.006"/><testcase classname="set_classname" name="set_name" file="test_case.py" line="49" time="0.001"/></testsuite>
</testsuites>
1. testsuite
1.1 在测试套件级别添加属性节点 record_testsuite_property

支持xunit2

import pytest@pytest.fixture(scope="session", autouse=True)
def log_global_env_facts(record_testsuite_property):record_testsuite_property("ARCH", "PPC")record_testsuite_property("STORAGE_TYPE", "CEPH")class TestMe:def test_foo(self):assert True

output


<testsuite errors="0" failures="0" name="pytest" skipped="0" tests="1" time="0.006"><properties><property name="ARCH" value="PPC"/><property name="STORAGE_TYPE" value="CEPH"/></properties><testcase classname="test_me.TestMe" file="test_me.py" line="16" name="test_foo" time="0.000243663787842"/>
</testsuite>
2. testcase
2.1 记录测试的其他信息 record_property

请注意,使用此功能将中断对最新JUnitXML架构的架构验证。当与某些CI服务器一起使用时,这可能是一个问题

  • 方法一 test_case.py
def test_function(record_property):record_property("example_key", 1)assert True
  • 方法二 contest.py
# content of conftest.pydef pytest_collection_modifyitems(session, config, items):for item in items:for marker in item.iter_markers(name="test_id"):test_id = marker.args[0]item.user_properties.append(("test_id", test_id))# content of test_function.py
import pytest@pytest.mark.test_id(1501)
def test_function():assert True

output


<templt><testcase classname="test_function" file="test_function.py" line="0" name="test_function" time="0.0009"><properties><property name="example_key" value="1"/></properties></testcase><testcase classname="test_function" file="test_function.py" line="0" name="test_function" time="0.0009"><properties><property name="test_id" value="1501"/></properties></testcase>
</templt>
2.2 向testcase元素添加额外的xml属性 record_xml_attribute

record_xml_attribute 是一个实验性的特性,它的接口在未来的版本中可能会被更强大和通用的东西所取代。然而,功能本身将保持不变
请注意,使用此功能将中断对最新JUnitXML架构的架构验证。当与某些CI服务器一起使用时,这可能是一个问题

  • 方法一 test_case.py
import pytest@pytest.mark.parametrize("case", ["case1", "case2"])
def test_case(case, record_xml_attribute):record_xml_attribute('classname', 'set_classname')  # 重写 valuerecord_xml_attribute('name', 'set_name')  # 重写 valuerecord_xml_attribute('index', '123')  # 新增 key, valueprint("hello world")assert True
  • 方法二 contest.py
# edit to contest.py
import pytest@pytest.fixture(autouse=True)
def record_index(record_xml_attribute):record_xml_attribute('index', '123')  # 新增 key, value
  • output
<?xml version="1.0" encoding="utf-8"?>
<testsuites><testsuite name="pytest" errors="0" failures="0" skipped="0" tests="2" time="0.113"timestamp="2025-03-10T14:53:08.040765+08:00" hostname="Ding-Perlis-MP1Y70F1"><testcase classname="set_classname" name="set_name" file="test_case.py" line="49" index="123" time="0.006"><system-out>hello world</system-out></testcase><testcase classname="set_classname" name="set_name" file="test_case.py" line="49" index="123" time="0.001"/></testsuite>
</testsuites>

Hooks

other plugin 好玩好用的

  • pytest_html_merger https://github.com/akavbathen/pytest_html_merger
    pip install pytest_html_merger 合并pytest_html报告
    export PATH="$HOME/.lcoal/bin:$PATH"
    pytest_html_merger -i /path/to/your/html/reports -o /path/to/output/report/merged.html
    
  • pytest-tally https://github.com/jeffwright13/pytest-tally
    pip install pytest-tally可在控制台、应用程序或浏览器中显示测试运行进度
    cd project # 与main.py同级
    python main.py
    pytest xxx# tally
    tally-rich
    tally-flask
    tally-tk
    
    https://github.com/jeffwright13/pytest-tally
  • pytest-sugarhttps://pypi.org/project/pytest-sugar/
    pip install pytest-sugar改变 pytest 的默认外观(例如进度条、立即显示失败的测试)
    https://pypi.org/project/pytest-sugar/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/897478.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

初始化E9环境,安装Sqlserver数据库

title: 初始化E9环境,安装Sqlserver数据库 date: 2025-03-10 19:27:19 tags: E9SqlServer初始化E9环境,安装Sqlserver数据库 安装E9本地环境安装Sql server 数据库1、检查SQL Server服务是否开启2、检查SQL Server网络网络配置是否开启创建一个ecology数据库点击初始化数据库…

在WSL2-Ubuntu中安装CUDA12.8、cuDNN、Anaconda、Pytorch并验证安装

#记录工作 提示&#xff1a;整个过程最好先开启系统代理&#xff0c;也可以用镜像源&#xff0c;确保有官方发布的最新特性和官方库的完整和兼容性支持。 期间下载会特别慢&#xff0c;需要在系统上先开启代理&#xff0c;然后WSL设置里打开网络模式“Mirrored”,以设置WSL自动…

SQLAlchemy系列教程:如何执行原生SQL

Python中的数据库交互提供了高级API。但是&#xff0c;有时您可能需要执行原始SQL以提高效率或利用数据库特定的特性。本指南介绍在SQLAlchemy框架内执行原始SQL。 在SQLAlchemy中执行原生SQL SQLAlchemy虽然以其对象-关系映射&#xff08;ORM&#xff09;功能而闻名&#xff…

基于SpringBoot的手机销售网站设计与实现(源码+SQL脚本+LW+部署讲解等)

专注于大学生项目实战开发,讲解,毕业答疑辅导&#xff0c;欢迎高校老师/同行前辈交流合作✌。 技术范围&#xff1a;SpringBoot、Vue、SSM、HLMT、小程序、Jsp、PHP、Nodejs、Python、爬虫、数据可视化、安卓app、大数据、物联网、机器学习等设计与开发。 主要内容&#xff1a;…

Spring(五)容器-依赖注入的三种方式

目录 总结&#xff1a;通用的三种注入方式 1 字段注入 2 构造器注入 3 set注入 总结&#xff1a;通用的三种注入方式 优先使用构造器注入谨慎使用 Setter 注入避免滥用字段注入 通过构造器传入依赖&#xff0c;确保对象创建时即完成初始化。通过 Setter 方法注入依赖&#x…

Python贝壳网二手小区数据爬取(2025年3月更)

文章目录 一、代码整体架构解析二、各部分代码详解1. main()主函数解析2. 会话初始化&#xff08;伪装浏览器身份&#xff09;3. 动态参数生成&#xff08;反爬虫核心机制&#xff09;4. 列表页抓取&#xff08;获取小区列表&#xff09;5. 列表页解析&#xff08;提取小区信息…

使用服务器搭建一个专属的密码管理工具Vaultwarden

一、服务器配置与Docker环境 ‌实例选型与系统准备‌ ‌推荐配置‌&#xff1a;‌1核2GB内存‌&#xff08;莱卡云L1型实例&#xff09;&#xff0c;Vaultwarden资源占用低&#xff0c;适合轻量级部署‌34。‌操作系统‌&#xff1a;选择 ‌Ubuntu 22.04 LTS‌&#xff0c;兼容…

IO学习---->线程

1.创建两个线程&#xff0c;分支线程1拷贝文件的前一部分&#xff0c;分支线程2拷贝文件的后一部分 #include <head.h> sem_t sem; long half_size 0; // 全局变量&#xff0c;供所有线程共享void* product(void *arg) {FILE *src fopen("IO.text", "…

深度学习分词器char-level实战详解

一、三种分词器基本介绍 word-level&#xff1a;将文本按照空格或者标点分割成单词&#xff0c;但是词典大小太大 subword-level&#xff1a;词根分词&#xff08;主流&#xff09; char-level&#xff1a;将文本按照字母级别分割成token 二、charlevel代码 导包&#xff1…

基于SpringBoot实现旅游酒店平台功能六

一、前言介绍&#xff1a; 1.1 项目摘要 随着社会的快速发展和人民生活水平的不断提高&#xff0c;旅游已经成为人们休闲娱乐的重要方式之一。人们越来越注重生活的品质和精神文化的追求&#xff0c;旅游需求呈现出爆发式增长。这种增长不仅体现在旅游人数的增加上&#xff0…

git规范提交之commitizen conventional-changelog-cli 安装

一、引言 使用规范的提交信息可以让项目更加模块化、易于维护和理解&#xff0c;同时也便于自动化工具&#xff08;如发布工具或 Changelog 生成器&#xff09;解析和处理提交记录。 通过编写符合规范的提交消息&#xff0c;可以让团队和协作者更好地理解项目的变更历史和版本…

前端实现版本更新自动检测✅

&#x1f916; 作者简介&#xff1a;水煮白菜王&#xff0c;一位资深前端劝退师 &#x1f47b; &#x1f440; 文章专栏&#xff1a; 前端专栏 &#xff0c;记录一下平时在博客写作中&#xff0c;总结出的一些开发技巧和知识归纳总结✍。 感谢支持&#x1f495;&#x1f495;&a…

postman接口请求中的 Raw是什么

前言 在现代的网络开发中&#xff0c;API 的使用已经成为数据交换的核心方式之一。然而&#xff0c;在与 API 打交道时&#xff0c;关于如何发送请求体&#xff08;body&#xff09;内容类型的问题常常困扰着开发者们&#xff0c;尤其是“raw”和“json”这两个术语之间的区别…

SQL29 计算用户的平均次日留存率

SQL29 计算用户的平均次日留存率 计算用户的平均次日留存率_牛客题霸_牛客网 题目&#xff1a;现在运营想要查看用户在某天刷题后第二天还会再来刷题的留存率。 示例&#xff1a;question_practice_detail -- 输入&#xff1a; DROP TABLE IF EXISTS question_practice_detai…

深度学习分类回归(衣帽数据集)

一、步骤 1 加载数据集fashion_minst 2 搭建class NeuralNetwork模型 3 设置损失函数&#xff0c;优化器 4 编写评估函数 5 编写训练函数 6 开始训练 7 绘制损失&#xff0c;准确率曲线 二、代码 导包&#xff0c;打印版本号&#xff1a; import matplotlib as mpl im…

Midjourney绘图参数详解:从基础到高级的全面指南

引言 Midjourney作为当前最受欢迎的AI绘图工具之一&#xff0c;其强大的参数系统为用户提供了丰富的创作可能性。本文将深入解析Midjourney的各项参数&#xff0c;帮助开发者更好地掌握这一工具&#xff0c;提升创作效率和质量。 一、基本参数配置 1. 图像比例调整 使用--ar…

音频进阶学习十九——逆系统(简单进行回声消除)

文章目录 前言一、可逆系统1.定义2.解卷积3.逆系统恢复原始信号过程4.逆系统与原系统的零极点关系 二、使用逆系统去除回声获取原信号的频谱原系统和逆系统幅频响应和相频响应使用逆系统恢复原始信号整体代码如下 总结 前言 在上一篇音频进阶学习十八——幅频响应相同系统、全…

vue3 使用sass变量

1. 在<style>中使用scss定义的变量和css变量 1. 在/style/variables.scss文件中定义scss变量 // scss变量 $menuText: #bfcbd9; $menuActiveText: #409eff; $menuBg: #304156; // css变量 :root {--el-menu-active-color: $menuActiveText; // 活动菜单项的文本颜色--el…

gbase8s rss集群通信流程

什么是rss RSS是一种将数据从主服务器复制到备服务器的方法 实例级别的复制 (所有启用日志记录功能的数据库) 基于逻辑日志的复制技术&#xff0c;需要传输大量的逻辑日志,数据库需启用日志模式 通过网络持续将数据复制到备节点 如果主服务器发生故障&#xff0c;那么备用服务…

熵与交叉熵详解

前言 本文隶属于专栏《机器学习数学通关指南》&#xff0c;该专栏为笔者原创&#xff0c;引用请注明来源&#xff0c;不足和错误之处请在评论区帮忙指出&#xff0c;谢谢&#xff01; 本专栏目录结构和参考文献请见《机器学习数学通关指南》 ima 知识库 知识库广场搜索&#…