我希望这个python函数处理用户输入,不提供非整数值(例如小数),否则通过异常处理。
# a function that takes an integer and returns its factorial
def factorial(x):
try:
if x == 0:
return (0)
else:
pro = 1
for i in range(1, x + 1):
pro *= i
except(ValueError, Ty
在工作中,我遇到了这种方法,它困扰着我。方法的名称、文档和实现并不真正适合(并且传递为true使条件变为假),我不明白有这样一个方法的意义(这是production代码):
# @brief An utility method that raises if the singleton is not in a good
# state
#@param expect_instanciated bool : if True we expect that the class is
# allready instanciated, else not
# @throw RuntimeError
@clas
我正在使用库发出一个HTTP请求。如果请求失败,将引发异常。例如(截断和简化):
main.py
from requests import get
def make_request():
r = get("https://httpbin.org/get")
r.raise_for_status()
我使用编写了一个模拟请求的测试。
test_main.py
from unittest import mock
from unittest.mock import patch
import pytest
from requests import HTTPErro
看一下下面的测试用例:
def test_1_check_version(self):
try:
self.version()
print('\n')
except cx_Oracle.DatabaseError as error_message:
print("Sorry Connection could not be established because "+str(error_message))
上面是我用Python的Unittest编写的许多测试用例的测试用例,现在我正在运行它来检查数据
如何正确地拒绝在Python构造函数中创建对象?考虑一个对象:
class Triangle:
def __init__(self, a, b, c):
sides = [a, b, c]
sides.sort()
if sides[0]+sides[1] < sides[2]:
return None
self._a = a
self._b = b
self._c = c
如果边对于三角形来说不是逻辑的,我想拒绝创建一个三角形对象。返回None不会阻止Tria
我正试图编写一个测试用例,以检查代码是否在except块中。
如果出现异常,我的方法foo()不会抛出/引发它,它只记录信息。
我尝试过使用,但后来我意识到这对我不起作用,因为我没有引发异常。
在Python文档中,可以清楚地说:
测试使用也传递给assertRaises()的任何位置或关键字参数调用可调用时是否会引发异常。如果引发异常,则测试通过;如果引发另一个异常,则为错误;如果未引发异常,则测试将失败。
因此,如果我有以下方法:
def foo():
try:
# Something that will cause an exception
exc
当我试图获得异常的值时,这个值是不正确的。
import pytest
class CustomException(Exception):
"""Custom Exception"""
def raise_custom_exception():
raise CustomException("This is a test exception")
def test_custom_exception():
with pytest.raises(CustomException) as exe
我有麻烦和困难朝圣者的潜入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
假设我们有两个类,Class A具有一个自定义错误,这个错误经常被抛出,并且它是其功能的一部分。
#a.py
class AError(Exception):
"""This exception flags a functional error"""
pass
class A(object):
def work(self):
"""Throws AError when it is tired"""
raise AError() #This exception is r
如果我想要引发一个错误,如果x是空的,我可以执行如下操作:
x = ...
if not x: raise SomeException(...)
或者:
assert x, "Some Exception"
我的问题是,是否可以将异常/断言作为逻辑语句的一部分来执行,或者它是否属于python语法的一部分,即它必须是它自己的单独语句,我的意思是执行以下操作:
z = x**2 or raise SomeException("Value cannot be zero")
或者:
z = x**2 or assert x...
或者:
z = x**2, asser