pytest中pytest_addoption用法 动态添加命令行参数 (钩子函数)

pytest中pytest_addoption的使用 说明 在日常的UI自动化测试中,可能使用涉及到多个场景,例如测试、预发、生产环境,这就需要我们进行环境切换,如果在不同的环境下我们要指定不同的系统配置,每次修改框架代码配置这个很不自动化,给测试造成了不必要的麻烦。 针对这种情况,pytest提供了一种方法:pytest_addoption注册参数,使用这个注册参数就可以解决了这种问题,可以在执行用例、命令的时候传递参数。 用法 pytest_addoption注册参数一般和内置 fixture pyt... 阅读详情

考虑场景:

  1. 我们的自动化用例需要支持在不同测试环境运行,有时候在dev环境运行,有时候在test环境运行;
  2. 有时候需要根据某个参数不同的参数值,执行不同的业务逻辑;

上面的场景我们都可以通过“在命令行中输入参数,然后用例中接收这个参数,通过判断这个参数的值来做不同的逻辑”来实现。那么我们的需求就变为pytest中如何自定义一个命令行参数呢?这时候我们就需要用到pytest的钩子函数:pytest_addoption

通过conftest.py配置
  新建一个conftest.py文件,然后在conftest.py文件中通过pytest_addoption方法来添加命令行参数,通过定义的fixture来获得参数的值。

# file_name: conftest.py


import pytest


def pytest_addoption(parser):
	# 注册自定义参数cmdopt到配置对象
    parser.addoption(
        "--cmdopt", action="store", default="type1", help="my option: type1 or type2"
    )
    # 注册自定义参数env到配置对象
    parser.addoption(
        "--env", action="store", default="dev", help="env:表示测试环境,默认dev环境"
    )


@pytest.fixture()
def cmdopt(pytestconfig):
	# 从配置对象获取cmdopt的值
    return pytestconfig.getoption("cmdopt")


@pytest.fixture()
def env(request):
	# 从配置对象获取env的值
    return request.config.getoption("--env")

上面conftest.py文件中新增了两个命令行参数:–cmdopt和–env;然后定义了两个fixture,在测试用例中想要获得参数–cmdopt的值,就可以调用cmdopt函数;调用env函数可以获取参数–env的值。
编写测试用例:

# file_name: test_option.py

import pytest


def test_option(env):
    if env == 'dev':
        print("当前测试环境为:{},域名切换为开发环境".format(env))
    elif env == 
Pytest教程__Hook函数pytest_addoption(parser):定义自己的命令行参数(14-1) 新建一个conftest.py文件然后在conftest.py文件中通过pytest_addoption方法来添加命令行参数,通过定义的fixture来获得参数的值。# pytest_addoption(parser) 定义自己的命令行参数的固定写法# 定义 --env_opt 参数名# 定义 --run_level 参数名# 参数说明:# default:当命令行不调用参数时的默认值# help:在帮助中显示的说明。 阅读详情

相关推荐

Pytest教程:Pytest命令行选项详解(很详细)

在使用 pytest 进行测试时,熟悉 pytest 的命令行选项非常重要,这将有助于减少错误和提高测试效率。

旦莫的博客 8246

如何在Android上使用OpenCV进行摄像头标定

如何在Android上使用OpenCV进行摄像头标定,我们这里使用官方一个例程,其实并不难,只是网上的资料少了而已。相机标定是计算机视觉工作的前提,为了确定相机矩阵和畸变参数。

花草的博客 3440

VC Spyglass CDC实战:如何快速定位和解决重汇聚问题(附详细调试步骤)

本文深入探讨了在SoC设计中利用VC Spyglass进行CDC验证时,如何高效定位和解决棘手的重汇聚问题。通过实战演练,详细解析了重汇聚的本质、VC Spyglass的检测逻辑,并提供了从报告筛选、GUI原理图分析到制定设计修复或约束豁免方案的全套调试步骤,帮助工程师快速攻克这一常见验证难题。

weixin_29219539的博客 753

【基于51】红外寻迹智能小车 - 代码篇

这是一个基于C51单片机的红外巡线智能小车,是一个适合嵌入式单片机、C语言初学者练习的小Demo,文章提供完整的项目思路、免费的源代码。

ZER00000001的博客 3万+

Nginx反向代理MinIO私有桶签名失效?一招解决Host头校验问题

本文详细解析了Nginx反向代理MinIO私有桶时出现的签名失效问题,重点解决了Host头校验导致的"SignatureDoesNotMatch"错误。通过精准配置proxy_set_header保持Host头一致性,并提供了二级目录代理和调试指南,帮助开发者高效解决这一常见技术难题。

weixin_29201313的博客 321

无符号整数、带符号整数溢出问题

让我们详细讲解一下带符号整数溢出和无符号整数溢出问题中,符号标志位 (SF)、零标志位 (ZF) 和进位标志位 (CF) 的行为方式

weixin_49342084的博客 2088

寄存器与计数器设计(Verilog)

always @(posedge Reset or posedge Clock)//请在括号中补充敏感信号列表。always @(negedge Resetn , posedge Clock)//请在括号中补充敏感信号列表。always @(negedge Resetn,posedge Clock)//请在括号中补充敏感信号列表。//为了便于自动评测,请勿更改n的值。//为了便于自动评测,请勿更改n的值。//为了便于自动评测,请勿更改n的值。//为了便于自动评测,请勿更改n的值。

M_inherit的博客 362

华为OD机试真题2026双机位C卷 Java&Go 实现【用户入网定期复评】

用户开立支付账户,在开户完成后立即对用户进行一次风险模型评级,输出一个评分风险,评分范围1-100,等区间的分为5个等级,1-19为等级1,20-39为等级2,40-59为等级3,60-79为等级4,80-100为等级5,系统每天会任务对全量入网用户进行计算复评时间,输出评分给出新的风险等级。复评规则如下:

MISAYAONE的博客 149

Arduino与震动马达模块握手

震动马达模块采用采用高品质手机震动马达,适用于震动感互动产品的制作,可穿戴智能设备震动提醒,适合作为非可听指示器的小型振动马达。当输入为高电平时电动机会震动,就像你的静音模式的手机一样。

vor234的博客 5847

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

上一篇: python上下文管理器
下一篇: 什么是SDK
一叶知秋的BLOG
博客等级 码龄8年 99粉丝 97原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一叶知秋的BLOG

创作不易 请多多关注

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值