[Pytest][Part 3]檢測python package狀態

?

目錄

實現需求1:

檢查python package狀態——pkg_resource

hook實現自動檢測包狀態

conftest.py

hook鉤子函數


Part1:

https://blog.csdn.net/x1987200567/article/details/144915315?spm=1001.2014.3001.5501

從這里開始逐個實現Part1中的需求

實現需求1:

測試開始前檢查測試需要的python package是否安裝完成,若未安裝完成,則安裝缺失的package

檢查python package狀態——pkg_resource

python中的pkg_resource庫是用來管理python中的包的,這個庫提供了檢查python安裝包的API:

pkg_resources.require()

import pkg_resources
package = "pytest-repeat>=0.9.1"#若已安裝對應版本的包,則返回對應的包以及相關聯的包信息,否則返回exceptiontry:pkg_resources.require(package)except pkg_resources.DistributionNotFound:print(f"package not found {package}")except pkg_resources.VersionConflict:print(f"package version is wrong {package}")

?當require沒有找到相應的package時就會返回不同的exception,那么根據這些不同的exception來install 或者upgrade 對應的包。

import pkg_resources
package = "pytest-repeat>=0.9.1"#若已安裝對應版本的包,則返回對應的包以及相關聯的包信息,否則返回exceptiontry:pkg_resources.require(package)except pkg_resources.DistributionNotFound:subprocess.check_call([sys.executable, "-m", "pip", "install", package])except pkg_resources.VersionConflict:subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", package])else:print(f"{package} is already meet requirement")

上面執行Install和upgrade的操作時用到了這一行代碼

subprocess.check_call([sys.executable, "-m", "pip", "install", package])

subprocess 是python中用于執行cmd命令的一個庫,check_call()是其中一個方法。當check_all()執行成功時返回0,失敗時返回非0。接收一個list作為參數。

def check_call(*popenargs, **kwargs):"""Run command with arguments.  Wait for command to complete.  Ifthe exit code was zero then return, otherwise raiseCalledProcessError.  The CalledProcessError object will have thereturn code in the returncode attribute.The arguments are the same as for the call function.  Example:check_call(["ls", "-l"])"""

所以實現python package檢測的完整實現代碼如下:

import subprocess
import sys
import pkg_resourcesdef check_package_status(requirements_file='requirements.txt'):"""use to check if python packages needed in test are all installed , if not , install package:param requirements_file: python package needed in the test:return:"""logger.info("checking required python package status.....")try:with open(requirements_file, 'r') as file:requirements = file.readlines()for requirement in requirements:package = requirement.strip()try:pkg_resources.require(package)except pkg_resources.DistributionNotFound:logger.info(f"{package} is not installed. Installing...")subprocess.check_call([sys.executable, "-m", "pip", "install", package])except pkg_resources.VersionConflict as e:logger.error(f"Version conflict for {package}: {e}. Updating...")subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", package])else:logger.info(f"{package} is already installed.")except Exception as e:logger.exception(f"Error while checking/installing packages: {e}")

hook實現自動檢測包狀態

上面已經實現了包檢測這個功能,那么下面的問題是如何實現每次測試開始之前都自動檢測包的狀態。pytest中提供的hook鉤子函數這個功能可以幫我們快速實現這個需求。

conftest.py

這里放一段官方的介紹,大概意思是conftest.py是一個共享test fixture的文件,所有的test fixture 都定義在conftest.py中。作用范圍可以是整個項目,也可以是文件夾內。如果作用域是整個項目,那么需要放在項目的根目錄下。

The?conftest.py?file serves as a means of providing fixtures for an entire directory. Fixtures defined in a?conftest.py?can be used by any test in that package without needing to import them (pytest will automatically discover them).

You can have multiple nested directories/packages containing your tests, and each directory can have its own?conftest.py?with its own fixtures, adding on to the ones provided by the?conftest.py?files in parent directories.

hook鉤子函數

hook也是在conftest.py中實現的,實現方式比較簡單。pytest_sessionstart()是pytest提供的一個鉤子函數,在session被創建之后,收集和執行測試case之前被調用,所以可以執行一些測試前的配置和檢查工作。

pytest_sessionstart(session)[source]

Called after the?Session?object has been created and before performing collection and entering the run test loop.

Parameters

session?(pytest.Session) – The pytest session object.

Return type

None

?

def check_package_status(requirements_file='requirements.txt'):pass# 測試開始時檢查當前的測試配置
@pytest.hookimpl(tryfirst=True)
def pytest_sessionstart(session):check_package_status()

這樣就完成了測試開始前對python package的自動檢測和安裝功能。完整代碼為:

import pkg_resources
import subprocess
import sys
import utils.TestLogger as testLoggerlogger = testLogger.TefLogger().get_logger()def check_package_status(requirements_file='requirements.txt'):"""use to check if python packages needed in test are all installed , if not , install package:param requirements_file: python package needed in the test:return:"""logger.info("checking required python package status.....")try:with open(requirements_file, 'r') as file:requirements = file.readlines()for requirement in requirements:package = requirement.strip()try:pkg_resources.require(package)except pkg_resources.DistributionNotFound:logger.info(f"{package} is not installed. Installing...")subprocess.check_call([sys.executable, "-m", "pip", "install", package])except pkg_resources.VersionConflict as e:logger.error(f"Version conflict for {package}: {e}. Updating...")subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", package])else:logger.info(f"{package} is already installed.")except Exception as e:logger.exception(f"Error while checking/installing packages: {e}")# 測試開始前檢查當前的測試配置
@pytest.hookimpl(tryfirst=True)
def pytest_sessionstart(session):check_package_status()

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

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

相關文章

自定義時間范圍選擇組件使用教程(基于 Vue 3 + Element Plus)

🕓 自定義時間范圍選擇組件使用教程(基于 Vue 3 Element Plus)? 一個靈活實用的時間范圍選擇器,支持開始時間、結束時間、快捷時間選項、本地雙向綁定、插槽擴展等功能。–📘 一、功能介紹 該組件基于 Element Plus …

YOLOv8 模型轉換 ONNX 后 C# 調用異常:一個參數引發的跨平臺適配難題

一、問題背景:從 Python 訓練到 C# 部署的跨平臺需求 作為一名 C# 開發者,我在完成 YOLOv8 模型訓練(使用 Ultralytics 官方框架,訓練數據為自定義目標檢測數據集,輸入尺寸 640x640,訓練輪次 100 輪&#…

Apache Cloudberry 亮相 2025 IvorySQL 生態大會暨 PostgreSQL 高峰論壇

6 月 27 日至 28 日,IvorySQL 2025 生態大會暨 PostgreSQL 高峰論壇在泉城濟南順利召開。本屆大會由 IvorySQL 開源數據庫社區主辦、瀚高基礎軟件股份有限公司承辦,吸引了來自國內外的數據庫技術專家、開發者與開源愛好者齊聚一堂,聚焦數據庫…

CMake之CMakeLists.txt語法規則

本文主要參考正點原子的應用開發手冊,僅作為本人學習筆記使用。 目錄 cmake 的使用方法其實還是非常簡單的,重點在于編寫 CMakeLists.txt,CMakeLists.txt 的語法規則也簡單,并沒有 Makefile的語法規則那么復雜難以理解&#xff01…

Mysql專題復習

重點內容:1. Mysql架構:客戶端 Server層 存儲引擎2. 索引數據結構:B樹4. 索引優化:覆蓋索引、排序、JOIN、分頁; COUNT; 索引下推;單/雙路排序5. 數據庫事務; 鎖;隔離級別&#xff…

CLIP的tokenizer詳解

一、bytes_to_unicodedef bytes_to_unicode():"""Returns list of utf-8 byte and a corresponding list of unicode strings.The reversible bpe codes work on unicode strings.This means you need a large # of unicode characters in your vocab if you wa…

【如何判斷Linux系統是Ubuntu還是CentOS】

要確定您的操作系統是 Ubuntu 還是 CentOS,可以通過以下方法快速檢查: 方法 1:通過終端命令(推薦) 在終端中執行以下命令之一: 查看 /etc/os-release 文件 cat /etc/os-releaseUbuntu 特征:顯示…

RISCV Linux 虛擬內存精講系列二 -- Linux 入口 head.S

通過 Linux 的構建系統,即 Linux 源代碼的根目錄下的 Makefile,能夠找到 vmlinux 的鏈接文件,從而能夠查看其入口代碼 head.S:_start, 如下: Linux 構建系統主Makefile: vmlinux.lds: head.S: 找到該入口后&#xff0c…

springAI學習:Advisors

spring AI Advisors類似于攔截器,會對請求的prompt做出特定的修改和增強(比如傳入歷史溝通記錄、搜索信息等等),以達到完善prompt的目的。通過Advisors API,開發人員可以創建更為復雜、可重用、可維護的AI組件。下面介…

MySQL CDC與Kafka整合指南:構建實時數據管道的完整方案

一、引言:現代數據架構的實時化需求 在數字化轉型浪潮中,實時數據已成為企業的核心資產。傳統批處理ETL(每天T1)已無法滿足以下場景需求: 實時風險監控(金融交易)即時個性化推薦(電商…

MATLAB | 繪圖復刻(二十一)| 扇形熱圖+小提琴圖

前段時間在小紅書刷到了一個很有特色的熱力圖,由大佬滾筒洗衣機創作,感覺很有意思,嘗試 MATLAB 復刻: 作者使用的是 python 代碼,趕快去瞅瞅。 復刻效果 正文部分 0.數據準備 數據需要一個用來畫熱圖的矩陣以及一個…

批量PDF轉換工具,一鍵轉換Word Excel

軟件介紹 今天為大家推薦一款高效的Office文檔批量轉換工具,能夠快速將Word和Excel文件批量轉換為PDF格式。 軟件特點 這款名為"五五Excel word批量轉PDF"的工具體積小巧,不到2M大小,卻能實現強大的批量轉換功能&#xff0c…

面試150 基本計算器

思路 利用棧(stack)來保存進入括號前的計算狀態(包括當前計算結果和符號),以便在括號結束后正確恢復計算上下文。代碼通過遍歷字符串,識別數字、加號、減號和括號。遇到數字時構造完整數值;遇到…

源哈希(sh)解析

源哈希(Source Hashing)是一種負載均衡算法,它根據請求的源 IP 地址(或其他標識符)生成哈希值,然后根據這個哈希值將請求分配到特定的后端服務實例。這種方法常用于確保來自同一客戶端的請求始終被路由到同…

axios的使用以及封裝

前言: 在現代前端開發中,網絡請求是不可避免的核心功能之一。無論是獲取后端數據、提交表單信息,還是與第三方 API 交互,高效且可靠的 HTTP 請求庫至關重要。axios 作為一款基于 Promise 的 HTTP 客戶端,憑借其簡潔的 …

github上部署自己的靜態項目

前置知識1、要在github部署項目要提交打包后的靜態文件(html,css,js)到倉庫里2、我們看下github所提供給我們的部署方式有啥,如下所見;要么是/root文件夾(就說倉庫里全是打包后的產物:html,css,js要全部放到…

能源管理綜合平臺——分布式能源項目一站式監控

綜合性的能源企業管理面臨著項目多、分布散、信息孤島等問題,分布式的多項目能源在線監控管理平臺是一種集成了多個能源項目的數據采集、監控、分析和管理的系統。平臺集成GIS能力,能夠展示項目的整體分布態勢,對不同地點、不同類型的能源項目…

修改阿里云vps為自定義用戶登錄

win系統上找到控制面板-->用戶賬戶-->更改賬戶類型點擊更改賬戶類型,此時我們看到vps的默認管理員賬戶Administrator。為了防止vps被別人使用默認賬戶Administrator攻擊,我們添加一個用戶賬戶,點擊添加用戶賬戶。 用戶名建議奇葩點&…

Linux: perf: debug問題一例,cpu使用率上升大約2%;多線程如何細化cpu及perf數據分析

文章目錄 前提面臨的問題內核級別函數的差別繼續debug總結根據pid前提 一個進程安置在一個CPU上,新功能上線之后,固定量的業務打起來,占用的CPU是42%。之前沒有新功能的情況下,CPU占用是40%。差了大約2%。而且這個進程里的線程數非常多,有50多個線程。從差距看變化不大,…

計算階梯電費

實現一個 Python 程序,根據使用的電量(從控制臺中讓用戶輸入)計算需要交的電費,電量分為兩個階梯,小于 200 度和大于 200 度,如果電量小于等于 200 度,電價就是 0.5 元/度,如果電量大…