用例:在pytest测试套件中@fixture,如果缺少其配置的命令行选项,我将引发异常。我已经使用以下方法为此夹具编写了一个测试xfail:
import pytest
from <module> import <exception>
@pytest.mark.xfail(raises=<exception>)
def test_fixture_with_missing_options_raises_exception(rc_visard):
pass
Run Code Online (Sandbox Code Playgroud)
但是,运行测试后的输出并未将测试声明为通过,而是“xfailed”:
============================== 1 xfailed in 0.15 seconds ========================
Run Code Online (Sandbox Code Playgroud)
除此之外,我无法测试是否fixture会引发特定缺失命令行选项的异常。
有没有更好的方法来做到这一点?我可以pytest以某种方式模拟命令行选项,我不需要通过pytest --<commandline-option-a> <test-file-name>::<test-name>.
我试图解决如何使用pytest从测试文件中获取测试名称的列表我已经做到这一点:
$ pytest --collect-only my_test_file.py
============================================================================================= test session starts ==============================================================================================
platform darwin -- Python 3.6.4, pytest-3.2.5, py-1.5.2, pluggy-0.4.0
rootdir: /Users/.../automation, inifile:
plugins: xdist-1.20.1, metadata-1.7.0, html-1.17.0, forked-0.2, cloud-2.0.0
collected 6 items
<Module 'my_test_file.py'>
<UnitTestCase 'TestFile'>
<TestCaseFunction 'test_general'>
<TestCaseFunction 'test_search_0'>
<TestCaseFunction 'test_search_1'>
<TestCaseFunction 'test_search_2'>
<TestCaseFunction 'test_search_3'>
<TestCaseFunction 'test_search_4'>
Run Code Online (Sandbox Code Playgroud)
虽然这是一个良好的开端,但它是太多的信息.我应该通过什么来获取测试名称本身的列表?
y=np.log10(train_set["SalePrice"])
Run Code Online (Sandbox Code Playgroud)
我如何找到这个的反面??我希望它返回到原始值而不是缩放值
我有一个名为pytools的 python 包。它包含一个基于 cython 的子模块nms。
当我用 安装根包 pytools 时sudo python -H setup.py,根包似乎安装正确。
但是安装没有复制编译nms.so到/usr/local/lib/python2.7/dist-packages/pytools/nms/.
而当我在 ipython 中导入 pytools 时,遇到了一个错误:
导入错误:无法导入名称 nms
如果我手动复制pytools/nms/nms.so到/usr/local/lib/python2.7/dist-packages/pytools/nms/,问题就解决了。
这是我setup.py的根包:
import os
import numpy
from distutils.core import setup, Extension
from Cython.Build import cythonize
exec(open('pytools/version.py').read())
exts = [Extension(name='nms',
sources=["_nms.pyx", "nms.c"],
include_dirs=[numpy.get_include()])
]
setup(name='pytools',
version=__version__,
description='python tools',
url='http://kaiz.xyz/pytools',
author_email='zhaok1206@gmail.com',
license='MIT',
packages=['pytools', 'pytools.nms'],
#packages=['pytools'],
zip_safe=False
)
Run Code Online (Sandbox Code Playgroud)
和setup.py子包nms:
from distutils.core import setup, …Run Code Online (Sandbox Code Playgroud) 在独立pytest测试用例中,我想使用断言unittest.TestCase.assertNotIn(和unittest其他断言),而不依赖任何uniittest模块。使用python-assert之类的库是最佳实践吗?
我需要使用来声明一条错误消息py.test,
import pandas as pd
import numpy as np
from inv_exception_store import InvAmtValError
MAX_INV_VAL = 10000000.0
MIN_INV_VAL = 0.0
class Invoices:
def __init__(self, data=None):
if data is None:
self.__invoices = pd.Series([], dtype=np.float32)
else:
self.__invoices = pd.Series(pd.Series(data).astype(np.float32))
def addInvoice(self, amount):
try:
if self.__invoices.size > MAX_INV_SIZE:
raise InvNumError
elif amount > MAX_INV_VAL or amount < MIN_INV_VAL:
raise InvAmtValError(amount)
else:
self.__invoices = self.__invoices.append(pd.Series(amount).astype(np.float32), ignore_index=True)
except (InvNumError, InvAmtValError) as e:
print(str(e))
class InvAmtValError(Exception):
def __init__(self, amount, message=None):
if message is None:
if …Run Code Online (Sandbox Code Playgroud) 我创建了一个pytest.ini文件,
addopts = --resultlog=log.txt
Run Code Online (Sandbox Code Playgroud)
这会创建一个日志文件,但我想在每次运行测试时创建一个新的日志文件。
我是 pytest 的新手,如果我在阅读文档时遗漏了任何内容,请原谅我。
谢谢
我已经完成了这个小包,我想在我的社区中分发。它现在在 test.pypi 上,当我想尝试安装它时,它给出了找不到依赖项的错误。
设置文件
...
install_requires=[
'defcon>=0.6.0',
'fonttools>=3.31.0'
]
...
Run Code Online (Sandbox Code Playgroud)
抛出这个错误
ERROR: Could not find a version that satisfies the requirement defcon>=0.6.0 (from sameWidther==0.6) (from versions: none)
ERROR: No matching distribution found for defcon>=0.6.0 (from sameWidther==0.6)
Run Code Online (Sandbox Code Playgroud)
但是当我手动安装时,它可以工作
pip install 'fonttools>=3.6.0'
pip install 'defcon>=0.6.0'
Run Code Online (Sandbox Code Playgroud) 我有一个代码,我需要检查输入的密码是否为空。如果是,则打印消息并退出脚本。
我正在使用pytest验证此代码并使用固定装置捕获输出capsys。但capsys.readouterr()没有捕获输出。
要测试的代码
def get_password():
password = getpass.getpass('Password required :', stream=None)
if not password:
print("NoPasswordError: Password not provided.Exiting from run")
'''return -1'''
sys.exit(-1)
else:
return password
Run Code Online (Sandbox Code Playgroud)
py测试代码
def test_input_validation_nopass(self,getpass,capsys):
getpass.return_value = ''
get_password()
out, err = capsys.readouterr()
sys.stdout.write(out)
assert re.match('NoPasswordError',out,re.I)
Run Code Online (Sandbox Code Playgroud)
但是,如果我删除sys.exit并放置return,则会捕获输出。目前我收到以下错误:
pytest -q UnitTest.py -k test_input_validation_nopass -rx -rP
F [100%]
=============================================================================== FAILURES ================================================================================
________________________________________________________________ TestClass.test_input_validation_nopass _________________________________________________________________
self = <UnitTest_buildUpgrade.TestClass object at 0x10d179978>, getpass = <MagicMock name='getpass' id='4514617832'>
capsys = <_pytest.capture.CaptureFixture …Run Code Online (Sandbox Code Playgroud) 我有一个类方法,它接受一个列表并根据函数确定该列表是否有效。
我想在存储为静态变量的三个列表上测试它,因为它们稍后在代码中的其他单元测试中使用。
def test__validate(self):
decoder = Validator()
slow_valid = Validator.validate(TestValidator.list_slow)
med_valid = Validator.validate(TestValidator.list_med)
fast_valid = Validator.validate(TestValidator.list_fast)
assert slow_valid == True
assert med_valid == False
assert fast_valid == False
Run Code Online (Sandbox Code Playgroud)
删除多个断言语句的正确方法是什么?
我是否定义了多个版本,test__validate或者从最佳实践的角度来看,多个断言语句是否可以?