I have a question about unittest.
How to make a test to see if is there an exception?
an example:
Datum(3,32,2012)
If i call class Datum like this, where month is not in range (>31), it's everything OK, it throws an Exception and thats OK. But I want to make an unittest if Exception is OK, if is catching an exception ok..?
I made some test but and these were only with True values, and they are ok. I have no idea how to test in this way.. and search on internet..
thanks for reply.
import date,datetime
class Datum():
def __init__(self,day,month,year):
try:
d=int(day)
dvm=stevilodnivmesecu(month,year)
if (d>=1 and d<=dvm):
self.d=d
else:
raise Exception("Day out of moth range")
except:
raise ValueError("Day is not a number")
try:
m=int(month)
if m>=1 and m<=12:
self.m=m
else:
raise Exception("Month out of range")
except:
raise ValueError("Month is not a number")
try:
l=int(year)
if l>=1000 and l<=9999:
self.l=l
else:
raise Exception("Year is out of range")
except:
raise ValueError("Year is not a number")
def __repr__(self):
return repr(self.d)+"."+repr(self.m)+"."+repr(self.l)
def monthrange(month,year):
if month==2:
if jeprestopno(year)==True:
return 29
elif jeprestopno(year)==False:
return 28
elif month>=1 and month<=7:
if month%2!=0:
return 31
elif month>7 and month<=12:
if month%2==0:
return 31
elif month>=1 and month<=7:
if month%2==0:
return 30
elif month>7 and month<=12:
if month%2!=0:
return 30
else:
pass
def oneplusyear(year):
if year%4==0 or (year!=100 and year%4==0) or (year%400==0 and year%100==0):
return True
else:
return False
Use
self.assertRaises(ValueError,Datum,3,32,2012)
in your unittest.TestCase test to assert that Datum(3,32,2012) raises a ValueError.
Reference:
Documentation on the various types of asserts you can make in
TestCases.
Related
I know similar questions have been asked and answered before like here: How do I check if a string is a number (float or Int ) in Python?
However, it does not provide the answer I'm looking for. What I'm trying to do is this:
def is_int_or_float(s):
try:
a = float(s)
return 1 if s.count('.')==0 else 2
except ValueError:
return -1
val = input("Enter your value: ")
data = is_int_or_float(val)
print(data)
What if User enters => "22" # Then Above code will gives -1.Please help me to resolve this With Exception handling (User Message)
Try this:
def is_int_or_float(value):
try:
tmp = float(value)
return 1 if tmp.is_integer() else 2
except ValueError:
return -1
And testing:
>>> is_int_or_float("a")
-1
>>> is_int_or_float("22")
1
>>> is_int_or_float("22.646")
2
>>> is_int_or_float("22.64.6")
-1
>>> is_int_or_float("22.000")
1
>>> is_int_or_float("1e-4")
2
You can create a simple handle for that.
Check the code. You need to implements you exception handle logic.
class AbstractHandler:
def is_float(self):
raise NotImplementedError
def is_int(self):
raise NotImplementedError
def verify(self):
raise NotImplementedError
class Handler(AbstractHandler):
def is_float(self, number):
try:
float(number)
return True
except ValueError:
# Your exception handler here
return False
def is_int(self, number):
try:
int(number)
return True
except ValueError:
# Your exception handler here
return False
def verify(self, var):
if self.is_float(var) or self.is_int(var):
return True
else:
return False
def is_number(var):
"""
Verify if input is a instance of int or float
Args:
var (str): input to be verified
"""
handler = Handler()
return handler.verify(var)
Some tests:
1 is True
1.1 is True
1.1.1 is False
One way to check, for example integer, use isinstance:
x = 1
if isinstance(x, int):
# Do something
I am trying to write a function that validates a package that contains 2 dates (beginning and end), a destination and a price
Initially, I tried to write a function that "creates" dates and puts them in a list and then compares them to find out if the end date was lower than the beginning but I figured that was too complicated so I resorted to the datetime inbuilt module
However, when I try to run the test function, it fails and it outputs this error message
File "C:\Users\Anon\Desktop\Fac\FP\pythonProject\main.py", line 65, in valideaza_pachet
raise Exception(err)
Exception: wrong dates!
I assume that I must have messed up a condition in the valideaza_pachet() function, but I don't understand what I did wrong
The code:
import time
import calendar
from datetime import date, datetime
def creeaza_pachet(data_i, data_s, dest, pret):
# function that creates a tourism package, data_i = beginning date, data_s = end date, dest = destination and pret = price
return {
"data_i": data_i,
"data_s": data_s,
"dest": dest,
"pret": pret
}
def get_data_i(pachet):
# functie that returns the beginning date of the package
return pachet["data_i"]
def get_data_s(pachet):
# functie that returns the end date of the package
return pachet["data_s"]
def get_destinatie(pachet):
# functie that returns the destination of the package
return pachet["dest"]
def get_pret(pachet):
# functie that returns the price of the package
# input: pachet - un pachet
# output: pretul float > 0 al pachetului
return pachet["pret"]
def valideaza_pachet(pachet):
#functie that validates if a package was correctly introduced or not
#it raises an Exception as ex if any of the conditions aren't met
err = ""
if get_data_i(pachet) < get_data_s(pachet):
err += "wrong dates!" # if the end date is lower than the beginning date
if get_destinatie(pachet) == " ":
err += "wrong destination!"
if get_pret(pachet) <= 0:
err += "wrong price!"
if len(err) > 0:
raise Exception(err)
def test_valideaza_pachet():
pachet = creeaza_pachet(datetime.strptime('24/08/2021',"%d/%m/%Y"), datetime.strptime('26/08/2021',"%d/%m/%Y"), "Galati", 9000.1)
valideaza_pachet(pachet)
pachet_gresit = creeaza_pachet(datetime.strptime('24/08/2021',"%d/%m/%Y"), datetime.strptime('22/08/2021',"%d/%m/%Y"), "Galati", 9000.1)
try:
valideaza_pachet(pachet_gresit)
assert False
except Exception as ex:
assert (str(ex) == "wrong dates!\n")
alt_pachet = creeaza_pachet(datetime.strptime('24/08/2021',"%d/%m/%Y"), datetime.strptime('22/08/2021',"%d/%m/%Y"), " ", -904)
try:
valideaza_pachet(alt_pachet)
assert False
except Exception as ex:
assert(str(ex) == "wrong dates!\nwrong destination!\nwrong price!\n")
def test_creeaza_pachet():
data_i_string = '24/08/2021'
data_i = datetime.strptime(data_i_string, "%d/%m/%Y")
data_s_string = '26/08/2021'
data_s = datetime.strptime(data_s_string, "%d/%m/%Y")
dest = "Galati"
pret = 9000.1
pachet = creeaza_pachet(data_i,data_s,dest,pret)
assert (get_data_i(pachet) == data_i)
assert (get_data_s(pachet) == data_s)
assert (get_destinatie(pachet) == dest)
assert (abs(get_pret(pachet) - pret) < 0.0001)
def run_teste():
test_creeaza_pachet()
test_valideaza_pachet()
def run():
pass
def main():
run()
run_teste()
main()
This is more of a code review and kind of off-topic here but... First,
drop all assert False - these won't do anything useful
drop the getter functions, that just makes things convoluted (just use dict[key] in the code as long as you don't use custom class)
drop unnecessary imports like calendar
you might also want to drop the run and main functions (again convoluted) - just call the functions you need
Then you could change valideaza_pachet to raise specific value errors:
def valideaza_pachet(pachet):
if pachet["data_i"] >= pachet["data_s"]:
raise ValueError("start date must be < end date")
if pachet["dest"] == " ":
raise ValueError("destination must not be empty")
if pachet["pret"] <= 0:
raise ValueError("price must be >= 0")
# returns None if no exception was raised
Now to test a valid package, you would just do
valideaza_pachet(pachet) # no exception expected
Testing an invalid package is a bit more complicated without a class that can be unit-tested (see e.g. here) - but you can catch the exception and use the else clause of the try/except to raise an AssertionError that says you wanted an exception:
try:
valideaza_pachet(pachet_gresit)
except Exception as ex:
print(f"successfully received exception: {ex}")
else:
raise AssertionError("validation should have raised an Exception")
or even
assert str(ex) == "start date must be < end date", f"got '{ex}', expected 'start date must be < end date'"
in place of the print statement.
I want to write a function that check a condition (with custom exceptions) and if no exceptions are raised it applies a function and return the result.
# Custom exceptions
class NegativeNumber(Exception):
pass
class BigNumber(Exception):
pass
def add_two(number):
return number + 2
def apply_function(number, f):
def check_condition(number, f):
try:
if number < 0:
raise NegativeNumber
if number > 10:
raise BigNumber
except NegativeNumber:
return ("Negative Number")
except BigNumber:
return ("Big Number")
return (f(number))
return check_condition(number, f)
apply_function(5, add_two)
Can be this code written better using decorators?
You've already done most of it. I modified your function name and the structure of your code a bit. This should be what you are looking for:
# Custom exceptions
class NegativeNumber(Exception):
pass
class BigNumber(Exception):
pass
def check_exceptions(f):
def wrapped(number):
try:
if number < 0:
raise NegativeNumber
if number > 10:
raise BigNumber
except NegativeNumber:
return "Negative Number"
except BigNumber:
return "Big Number"
return f(number)
return wrapped
#check_exceptions
def add_two(number):
return number + 2
for num in (-1, 5, 15):
print(add_two(num))
Output:
Negative Number
7
Big Number
Hi I'm pretty new to Python and I've just started to learn about errors and exceptions.I have this function in a class that inserts a line at a given index called num.I know python will raise an error if no num is given but I want to raise my own error.How do I do that?This is what I tried. But the error raised is still the default error?
def insertNum(self, num, line):
if num== None:
raise Exception("Num not specified.")
else:
self.list.insert(num, line)
return self.list
You can use try...except statement.
def insertNum(num, line):
try:
list.insert(num, line)
return list
except:
print('custom error')
You can set the default value of num to None and then check if the value is None.
def insertNum(self, line, num=None):
if num is None:
raise Exception("Num not specified.")
else:
self.list.insert(num, line)
return self.list
If you pass only one parameter to the insertNum method, num will be set the None (the default value) and will raise the exception.
If you don't want to change the order of the arguments, you can use this:
def insertNum(self, num, line=None):
if line is None:
raise Exception("Num not specified.")
else:
self.list.insert(num, line)
return self.list
A simple demonstration for how default arguments work:
>>> def foo(bar, baz=None):
... print(bar, baz)
...
>>> foo(1, 2)
1 2
>>> foo(2)
2 None
I suggest you read about exceptions and errors
But the main idea is that you catch errors and then you handle them the way you like.
try:
#do something
except Exception as e:
# error occured
print("A wild error appeared")
wrap your function with another function that will have try and except` and there you could raise what ever error/exception you want.
def wrapper_func(self, num, line):
try:
self.insertNum(num, line)
except Exception as e:
raise Exception("whatever you want")
New to Python, so I'm sure this is a noob question, but Googling isn't availing me of a clear answer.
Given the following function which is intended to ensure that the user input is a string, why can't I (or how can I) add a print statement when the exception is triggered? The print statement I've inserted there doesn't work.
def string_checker(action):
try:
check = isinstance(action, basestring)
if check == True:
return True
except ValueError:
print "We need a string here!"
return None
action = "words"
string_checker(action)
This may do what you want:
def string_checker(action):
try:
assert isinstance(action, basestring)
return True
except AssertionError:
print "We need a string here!"
return None
action = "words"
string_checker(action)
string_checker(21)
But you could also return "We need a string here!" instead of printing it, or return False, for consistency.
The problem is that you're never raising a value error if action isn't a string. Try this:
def string_checker(action):
try:
check = isinstance(action, basestring)
if check:
return True
else:
raise ValueError
except ValueError:
print "We need a string here!"
return None
But really, I don't think you need an exception. This should work fine:
def string_checker(action):
try:
check = isinstance(action, basestring)
if check:
return True
else:
print "We need a string here!"
return None
I'm not sure I understand. This appears to print "We need a string here!":
def string_checker(action):
try:
raise ValueError()
check = isinstance(action, basestring)
if check == True:
return True
except ValueError:
print "We need a string here!"
return None
action = "words"
string_checker(action)
raw_input('#')
Note the raise ValueError() in the try. Are you sure an exception is being thrown?