I wish to do pytest on a function, namely "date_validation", which checks whether a birth date is valid but somehow pytest was unable to access the month variable after the map() and .split() methods.
The answers I found here pertain to the main code which are subjected to the testing and not the test itself. My main code seemed to be working fine but not pytest. Please help.
The relevant part of the code is as below:
# Function to check whether date format was input correctly**
def check_format(date_of_birth):
date_format = "%d/%m/%Y"
try:
dateObject = datetime.datetime.strptime(date_of_birth, date_format)
return True
except ValueError:
return False
# Function to check whether date is valid**
def date_validation(date_of_birth):
if check_format(date_of_birth) is True:
day, month, year = map(int, date_of_birth.split("/"))
if month in [1, 3, 5, 7, 8, 10, 12]:
max_days = 31
elif month in [4, 6, 9, 11]:
max_days = 30
elif year%4 == 0 and year%100 != 0 or year%400 == 0: # Conditions for month of February
max_days = 29
else:
max_days = 28
The following is my pytest error message:
date_of_birth = '32/01/1990'
def date_validation(date_of_birth):
if check_format(date_of_birth) is True:
day, month, year = map(int, date_of_birth.split("/"))
> if month in [1, 3, 5, 7, 8, 10, 12]:
E UnboundLocalError: cannot access local variable 'month' where it is not associated with a value
project.py:39: UnboundLocalError
How can I let the variables be recognised by pytest?
I tried pre-defining the variables within my test but that did not work. For example,
def test_date_format():
day = 32
month = 1
year = 1990
assert date_validation("32/01/1990") == <print out stating that 32 is out of range>