Behave Test for Random Date Generation

  • Share this:

Code introduction


This function is a test function using the Behave framework to generate a random date between the current date and one year ago, and verify if the date is valid.


Technology Stack : Behave, datetime

Code Type : Behave test function

Code Difficulty : Intermediate


                
                    
from behave import given, when, then
import random
import datetime

def generate_random_date():
    """
    Generate a random date between the current date and a year ago.
    """
    start_date = datetime.datetime.now()
    end_date = start_date - datetime.timedelta(days=365)
    random_date = start_date - datetime.timedelta(days=random.randint(0, 365))
    return random_date.strftime('%Y-%m-%d')

def xxx(step):
    """
    This function generates a random date between the current date and a year ago.
    """
    given('a random date is generated')
    date = generate_random_date()
    when('the date is checked')
    then('the date should be between the current date and a year ago')