我正在为以下函数编写pytest单元测试
from datetime import datetime
def validate_timestamp(timestamp):
"""Confirm that the passed in string is in the proper format %Y%m%d_%H"""
try:
ts = datetime.strptime(str(timestamp),'%Y%m%d_%H')
except:
raise ValueErro
我有一个如下所示的类:
class Positive(object):
def __init__(self, item):
self._validate_item(item)
self.item = item
def _validate_item(self, item):
if item <= 0:
raise ValueError("item should be positive.")
我想为_validate_item()编写一个单元测试,如下所示:
class Positive
这是代码:
# mean_var-_std.py
def calculate(list):
if len(list) < 9:
print("List must contain nine numbers.")
raise ValueError
else:
return 0
这是单元测试:
import unittest
import mean_var_std
# the test case
class UnitTests(unittest.TestCase):
def test_calculate
我在python中有一个coroutine (增强生成器),在数据结束后执行一些代码:
def mycoroutine():
try:
while True:
data = (yield)
print data
finally:
raise ValueError
print "END"
co = mycoroutine()
co.next()
for i in (1,2,3):
co.send(i)
不会引发ValueError异常,但解释器只需打印:
Exception ValueError: ValueErro
我有麻烦和困难朝圣者的潜入python 3单元测试章节。我在rotest2.py中运行了完全相同的代码。在示例中提供的代码中没有处理异常。我把这本书上的例子演绎成一个更小的片段:
TestCase1.py
import unittest
class ToRomanBadInput(unittest.TestCase):
def test_too_large(self):
'''to_roman should fail with large input'''
self.assertRaises(roman2
下面,我有一个函数来捕捉未被发现的异常。是否有任何方法可以编写一个单元测试,以执行uncaught_exception_handler()函数,但正常退出测试?
import logging
def config_logger():
# logger setup here
def init_uncaught_exception_logger(logger):
'''Setup an exception handler to log uncaught exceptions.
This is typically called once per
我仍然在学习单元测试,因此无法判断在下面的test_iterators.py测试用例中是否缺少什么东西。有人能帮助我理解为什么ValueError不能在统一测试中被提高吗?以下是脚本:
iterators.py
"""
Simple class to count from zero to N
"""
class count_to(object):
def __init__(self, nber):
self.nber = nber
def __iter__(self):
return count_
我正在使用Python语言中的max(list)和min(list)查找列表的最大值和最小值。然而,我想知道如何管理空列表。
例如,如果列表是一个空的列表[],程序会引发'ValueError: min() arg is an empty sequence',但我想知道如何让程序只打印'empty list or invalid input'而不是崩溃。如何管理这些错误?
我是单元测试的新手,我想要一些关于这个主题的指导。该函数首先验证datetime是否为字符串,如果是,则验证它是否为正确的ISO格式。
if not isinstance(timestamp,str):
raise ValueError("timestamp must be a string")
try:
datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S')
return True
except ValueError:
return True
如何确定要在单元测试中包含哪些内容,以及应
我正试图通过pytest (单元测试)获得更多的技能。
当一个类被实例化时,如果没有一个必须有参数,我试着测试是否会引发异常。
我试图为此创建一个夹具,但这导致了一个问题,即当调用该夹具时,它试图使用缺少的参数在其中创建类,并在pytest实际上断言引发异常之前引发我的异常。
我设法克服了这一点,没有使用夹具,只是在测试函数中实例化类,但我想知道是否有更好的方法来使用一个夹具。
示例类:
class MyClass(object):
def __init__(self, must_have_parameter=None):
if not must_have_paramete
我刚刚发现了attrs,它实际上对我即将到来的项目来说是很棒的。在玩的时候,我发现了一些我无法解释的行为。
我有一段代码:
from attr import attrs, attrib, Factory
def validate_dict(instance, attribute, value):
if not isinstance(value, dict):
raise ValueError(f"Attribute `{attribute.name}` has to be of type dict(), not {type(value)}!")
@a
我在我正在使用的代码中发现了类似这样的东西:
[], my_variable = my_function(a, b)
其中,my_function的输出如下:
return some_dict, some_list
这似乎是可行的--系统的单元测试不会失败,但是当我在python控制台上尝试这样做(将字典赋值给"[]")时,它会引发:
ValueError: too many values to unpack
你见过这样的东西吗?如何将字典(或其他内容)赋给空列表常量"[]“?
或者不是,测试遗漏了一些东西。
我试图在异常内部引发一个异常,但没有得到外部异常和回溯的错误消息,并且只打印了嘿。然而,如果我把一个字符串而不是k或m放在这里,我就会被困在这里。 The output, which I would need without the traceback def division(k, m):
try:
k / m
except TypeError:
raise ValueError ('hey') from None
return k / m
除下列例外情况外,此单元测试失败:
def test_vote_form_with_multiple_choices_allowed_and_submitted(self):
"""
If multiple choices are allowed and submitted, the form should be valid.
"""
vote_form = VoteForm({'choice': [1, 2]}, instance=create_question('Dummy questi
我的问题看起来很简单,但我没有找到任何关于这个问题的帖子。我需要自己的从ValueError派生的自定义异常类来打印预期的类型(标准错误消息)以及输入的类型(带有自定义文本)。
class MyOwnException(ValueError):
...
try:
raise MyOwnException ( int('str') ) #not sure what to do here, as I only want to
#raise the exception if incorrec
在函数中,我想确保参数a和b具有相同的长度。如果不遵守,我想对此提出一个例外。我知道,ValueError是指一个参数本身不符合某些特定标准的例外情况。在这种情况下,在参数之间有标准的情况下,ValueError是否是一个适当的错误?如果没有,任何标准的Python异常都更合适吗?
def func(a, b):
if len(a) != len(b):
raise ValueError("list a and list b must have the same length")
我使用ThreadPoolExecutor来执行一个导致错误的函数。当一个错误在线程中引起(并且它没有被处理),它看起来就像是终止了那个线程,但是没有打印任何东西到stderr或者导致程序崩溃。这一切为什么要发生?我是否可以使任何线程中的未处理错误导致整个程序崩溃?或者,它可以印在某个地方,这样我就能看到发生了什么。
我注意到这个错误可以在一个try-catch块中捕获,所以它肯定是被引发的。如果调用相同的函数而不使用线程,则会按预期的方式引发错误。
from concurrent.futures import ThreadPoolExecutor
import time
def erro
我是个学习蟒蛇的新手。请看下面的代码(来自Goodrich等人在Python中的数据结构和算法)。
age = -1 # an initially invalid choice
while age <= 0:
try:
age = int(input('Enter your age in years: '))
if age <= 0:
print('Your age must be positive.')
except ValueError:
print(