0

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>
  • 2
    This has nothing to do with Pytest. This is a general Python question. As for the answer: what happens if `check_format(date_of_birth)` turns out to _not_ be `True`? – shadowtalker Apr 19 '23 at 03:01
  • Problem is that `if check_format(date_of_birth) is True:` doesn't hold, so `month` is not defined in the next command. – Quang Hoang Apr 19 '23 at 03:01
  • 1
    You shouldn’t write `if x is True:`, by the way. Just use `if x:`. – Ry- Apr 19 '23 at 03:10
  • Thanks for the comments. I have resolved the matter but in another way. It turns out that pytest was unable to detect my map() method, so I used the int() method on each variable and it resolved the issue. – Alvin Khah Apr 21 '23 at 12:02

0 Answers0