pytest -- 中文文檔

前言

零基礎1小時快速入門pytest自動化測試教程,全套項目框架實戰

pytest配置文件可以改變pytest的運行方式,它是一個固定的文件pytest.ini文件,讀取配置信息,按指定的方式去運行

非test文件

pytest里面有些文件是非test文件

  • pytest.ini:pytest的主配置文件,可以改變pytest的默認行為
  • conftest.py:測試用例的一些fixture配置
  • _init_.py:識別該文件夾為python的package包

查看pytest.ini的配置選項

cmd執行

pytest --help

找到這部分內容

[pytest] ini-options in the first pytest.ini|tox.ini|setup.cfg file found:markers (linelist):   markers for test functionsempty_parameter_set_mark (string):default marker for empty parametersetsnorecursedirs (args): directory patterns to avoid for recursiontestpaths (args):     directories to search for tests when no files or directories are given in the command line.usefixtures (args):   list of default fixtures to be used with this projectpython_files (args):  glob-style file patterns for Python test module discoverypython_classes (args):prefixes or glob names for Python test class discoverypython_functions (args):prefixes or glob names for Python test function and method discoverydisable_test_id_escaping_and_forfeit_all_rights_to_community_support (bool):disable string escape non-ascii characters, might cause unwanted side effects(use at your ownrisk)console_output_style (string):console output: "classic", or with additional progress information ("progress" (percentage) |"count").xfail_strict (bool):  default for the strict parameter of xfail markers when not given explicitly (default: False)enable_assertion_pass_hook (bool):Enables the pytest_assertion_pass hook.Make sure to delete any previously generated pyc cachefiles.junit_suite_name (string):Test suite name for JUnit reportjunit_logging (string):Write captured log messages to JUnit report: one of no|log|system-out|system-err|out-err|alljunit_log_passing_tests (bool):Capture log information for passing tests to JUnit report:junit_duration_report (string):Duration time to report: one of total|calljunit_family (string):Emit XML for schema: one of legacy|xunit1|xunit2doctest_optionflags (args):option flags for doctestsdoctest_encoding (string):encoding used for doctest filescache_dir (string):   cache directory path.filterwarnings (linelist):Each line specifies a pattern for warnings.filterwarnings. Processed after -W/--pythonwarnings.log_print (bool):     default value for --no-print-logslog_level (string):   default value for --log-levellog_format (string):  default value for --log-formatlog_date_format (string):default value for --log-date-formatlog_cli (bool):       enable log display during test run (also known as "live logging").log_cli_level (string):default value for --log-cli-levellog_cli_format (string):default value for --log-cli-formatlog_cli_date_format (string):default value for --log-cli-date-formatlog_file (string):    default value for --log-filelog_file_level (string):default value for --log-file-levellog_file_format (string):default value for --log-file-formatlog_file_date_format (string):default value for --log-file-date-formatlog_auto_indent (string):default value for --log-auto-indentfaulthandler_timeout (string):Dump the traceback of all threads if a test takes more than TIMEOUT seconds to finish. Notavailable on Windows.addopts (args):       extra command line optionsminversion (string):  minimally required pytest versionrsyncdirs (pathlist): list of (relative) paths to be rsynced for remote distributed testing.rsyncignore (pathlist):list of (relative) glob-style paths to be ignored for rsyncing.looponfailroots (pathlist):directories to check for changes

pytest.ini應該放哪里?

就放在項目根目錄下 ,不要亂放,不要亂起其他名字

接下來講下常用的配置項

marks

作用:測試用例中添加了?@pytest.mark.webtest?裝飾器,如果不添加marks選項的話,就會報warnings

格式:list列表類型

寫法:

[pytest]
markers =weibo: this is weibo pagetoutiao: toutiaoxinlang: xinlang

xfail_strict

作用:設置xfail_strict = True可以讓那些標記為@pytest.mark.xfail但實際通過顯示XPASS的測試用例被報告為失敗

格式:True 、False(默認),1、0

寫法:

[pytest]# mark標記說明
markers =weibo: this is weibo pagetoutiao: toutiaoxinlang: xinlangxfail_strict = True

具體代碼栗子

未設置?xfail_strict = True?時,測試結果顯示XPASS

@pytest.mark.xfail()
def test_case1():a = "a"b = "b"assert a != b

collecting ... collected 1 item

02斷言異常.py::test_case1 XPASS [100%]

============================= 1 xpassed in 0.02s ==============================

已設置?xfail_strict = True?時,測試結果顯示failed

collecting ... collected 1 item02斷言異常.py::test_case1 FAILED                                         [100%]
02斷言異常.py:54 (test_case1)
[XPASS(strict)] ================================== FAILURES ===================================
_________________________________ test_case1 __________________________________
[XPASS(strict)] 
=========================== short test summary info ===========================
FAILED 02斷言異常.py::test_case1
============================== 1 failed in 0.02s ==============================

addopts

作用:addopts參數可以更改默認命令行選項,這個當我們在cmd輸入一堆指令去執行用例的時候,就可以用該參數代替了,省去重復性的敲命令工作

比如:想測試完生成報告,失敗重跑兩次,一共運行兩次,通過分布式去測試,如果在cmd中寫的話,命令會很長

pytest -v --rerun=2 --count=2 --html=report.html --self-contained-html -n=auto

每次都這樣敲不太現實,addopts就可以完美解決這個問題

[pytest]# mark
markers =weibo: this is weibo pagetoutiao: toutiaoxinlang: xinlangxfail_strict = True# 命令行參數
addopts = -v --reruns=1 --count=2 --html=reports.html --self-contained-html -n=auto

加了addopts之后,我們在cmd中只需要敲pytest就可以生效了!!

log_cli

作用:控制臺實時輸出日志

格式:log_cli=True 或False(默認),或者log_cli=1 或 0

log_cli=0的運行結果

log_cli=1的運行結果

結論

很明顯,加了log_cli=1之后,可以清晰看到哪個package下的哪個module下的哪個測試用例是否passed還是failed;

所以平時測試代碼是否有問題的情況下推薦加!!!但如果拿去批量跑測試用例的話不建議加,誰知道會不會影響運行性能呢?

norecursedirs

作用:pytest?收集測試用例時,會遞歸遍歷所有子目錄,包括某些你明知道沒必要遍歷的目錄,遇到這種情況,可以使用?norecursedirs 參數簡化?pytest?的搜索工作【還是挺有用的!!!】

默認設置:?norecursedirs = .* build dist CVS _darcs {arch} *.egg?

正確寫法:多個路徑用空格隔開

[pytest]norecursedirs = .* build dist CVS _darcs {arch} *.egg venv src resources log report util

更改測試用例收集規則

pytest默認的測試用例收集規則

  • 文件名以 test_*.py 文件和?*_test.py
  • 以??test_ 開頭的函數
  • 以??Test 開頭的類,不能包含 __init__ 方法
  • 以??test_?開頭的類里面的方法

我們是可以修改或者添加這個用例收集規則的;當然啦,是建議在原有的規則上添加的,如下配置

[pytest]python_files =     test_*  *_test  test*
python_classes =   Test*   test*
python_functions = test_*  test*

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/922320.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/922320.shtml
英文地址,請注明出處:http://en.pswp.cn/news/922320.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

硬件開發2-ARM裸機開發3-IMX6ULL - 引入中斷

一、鋪墊引入中斷 → 按鍵1、概要:實現按鍵控制發光二極管和蜂鳴器輸入類型的外設:按鍵(key)2、參考手冊內容完成配置過程(1)key 按鍵原理圖(2)core 內核中命名 -- UART1 CTS&#x…

Ansible的 Playbook 模式詳解

目錄一、Playbook模式1.1 Playbook 的優勢1.2 Playbook 的組成1.3 安裝 httpd 服務案例1.4 Playbook 命令及常用參數1.5 Playbook 的語法 —— 權限相關1. remote_user2. become3. become_method1.6 Playbook 的通知與觸發機制1. notify2. handlers3. 使用示例4. 使用場景1.6 P…

猿輔導Java后臺開發面試題及參考答案

int 與 Integer 的區別是什么?若創建數量龐大的數字時使用 Integer,會對重復數字創建新對象嗎?int 是 Java 中的基本數據類型,直接存儲數值,占用 4 個字節,默認值為 0,不需要通過 new 關鍵字創建…

代碼隨想錄學習摘抄day9(回溯1-11)

一個樸實無華的目錄定義:回溯法也可以叫做回溯搜索法,它是一種搜索的方式。應用場景:回溯法解決的問題都可以抽象為樹形結構代碼模板題型第77題. 組合思路:每次從集合中選取元素,可選擇的范圍隨著選擇的進行而收縮&…

Altium Designer(AD24)打開工程文件的幾種方法

??《專欄目錄》 目錄 1,概述 2,源文件 2,菜單欄 4,工具欄 5,注意事項 1,概述 本文介紹幾種打開工程文件的方法。 2,源文件 找到工程的源文件存儲路徑,找到.PrjPcb的源工程文件,雙擊打開。 2,菜單欄 第1步:執行File→Open, 第2步:找到工程文件的存儲路徑,并選中…

Linux嵌入式自學筆記(基于野火EBF6ULL):2.點燈與ubuntu安裝

一、點燈登錄root:賬號:root ; 密碼:root點燈命令:echo 0 > /sys/class/leds/red/brightness #關閉red燈 echo 0 > /sys/class/leds/blue/brightness #關閉blue燈 echo 0 > /sys/class/leds/green/brightness …

【Java實戰?】Java實戰:MyBatis-Plus 開啟MySQL數據庫高效操作之旅

目錄 一、MyBatis-Plus 環境集成 1.1 項目依賴引入 1.2 數據庫配置 1.3 代碼生成器使用 二、核心 CRUD 操作實現 2.1 基礎查詢 2.2 數據新增與修改 2.3 復雜查詢場景 三、性能優化與高級特性 3.1 緩存配置 3.2 樂觀鎖實現 3.3 字段自動填充 四、實戰案例:用戶管理模塊開發 4.1…

開學季干貨——知識梳理與經驗分享

技術文章大綱:開學季干貨——知識梳理與經驗分享目標受眾分析明確文章面向的學生群體(如大學生、高中生) 分析不同群體的核心需求(課程準備、時間管理、工具使用) 結合技術場景(如數字筆記、在線協作&#…

Linux《線程(上)》

通過之前的學習我們已經了解了操作系統當中的基本的概念包括進程、基礎IO、磁盤文件存儲等,但是到目前為止我們還未了解到線程相關的概念,這就使得當前我們對操作系統的認知還不是完整的,現在我們是還是無法理解一個進程當中是如何同時的執行…

為什么知識復用時缺乏場景化指導影響實用性

知識復用時因缺乏場景化指導而嚴重影響實用性,其根本原因在于知識的價值本質上根植于其應用情境。脫離了場景的“純知識”往往是抽象、片面且難以行動的。這導致了認知鴻溝的產生、隱性知識的流失、決策風險的增加、以及學習遷移效率的低下。當使用者面對一份缺乏“…

擁抱直覺與創造力:走進VibeCoding的新世界

引言 在傳統觀念里,編程是一項高度理性、邏輯嚴密的活動,開發者需要像建筑師一樣,用代碼一行行地精確構建數字世界。然而,隨著人工智能技術的飛速發展,一種全新的編程理念和體驗正在興起——它就是 VibeCoding&#xf…

HTTP的Web服務測試在Python中的實現

在Web開發領域,對HTTP Web服務進行測試是確保服務穩定性和可靠性的關鍵步驟。Python作為一種功能強大的編程語言,提供了多種工具和庫來簡化這一過程。本文將介紹如何在Python中實現HTTP的Web服務測試。首先,Python的requests庫是測試HTTP Web…

Android Studio 構建項目時 Gradle 下載失敗的解決方案

一、問題原因分析根據錯誤日志:下載地址 https://services.gradle.org/distributions/gradle-8.1-bin.zip 連接超時(10秒)。可能原因:網絡環境限制(如公司防火墻、地區網絡屏蔽)。代理配置未生效或配置錯誤…

mysql 與 MongoDB 的分片

MySQL 和 MongoDB 作為不同類型數據庫的代表(關系型 vs 文檔型),其分片機制在設計理念、實現方式和適用場景上存在顯著差異。兩者的分片核心目標一致——通過水平擴展(Scale Out)解決單節點存儲容量和性能瓶頸,但因數據模型、事務支持和分布式設計理念的不同,形成了截然…

Coze源碼分析-資源庫-創建知識庫-前端源碼-核心邏輯與接口

創建知識庫邏輯 1. 表單驗證系統 文件位置:frontend/packages/data/knowledge/knowledge-modal-base/src/create-knowledge-modal-v2/features/add-type-content/coze-knowledge/index.tsx 知識庫創建表單的驗證規則: // 知識庫名稱驗證規則 const nameV…

歐拉函數 | 定義 / 性質 / 應用

注:本文為 “歐拉函數” 相關合輯。 略作重排,未整理去重。 如有內容異常,請看原文。 歐拉函數最全總結 jiet07 已于 2024-10-22 10:00:54 修改 一、歐拉函數的引入 首先引入互質關系: 如果兩個正整數,除了 111 以…

ubuntu git push每次都要輸入密碼怎么解決只輸入一次密碼

在 Ubuntu 下使用 Git 時,如果每次 push 都需要重復輸入密碼,可以通過配置 Git 憑證存儲來解決。以下是幾種常用方法: 🔑 方法一:使用 Git 憑證緩存(推薦) 設置憑證緩存(默認 15 分鐘…

【機械故障】使用fir濾波器實現數據擬合

使用fir濾波器實現數據擬合 提示:學習筆記 使用fir濾波器實現數據擬合使用fir濾波器實現數據擬合一、問題建模二、 構建矩陣方程(關鍵步驟)三、最小二乘解四、重要注意事項4.1 濾波器長度 M4.2 數據的預處理4.3 延遲問題4.4 性能評估一、問題…

STC8H系列-高級PWM-兩相步進電機-細分驅動

兩相步進電機, STC8H系列 用高級PWM實現SPWM細分驅動 /************* 功能說明 ************** 用B組高級PWM細分驅動2相4線小型步進電機, 支持1、2、4、8、16、32、64細分, 比如1.8度的電機4細分到0.45度. 本程序用于演示SPWM多細分直接驅動2相4線小型步進電機…

內網環境下ubuntu 20.04搭建深度學習環境總結

2025年9月更新,隨著人工智能的發展,現在深度學習環境配置越來越簡單了,常用的pytorch、paddle(3.x)等深度學習庫安裝的時候自帶了cuda和cudnn的python包,不需要在操作系統層面自己安裝,配置環境…