Robot Framework — Generating Random Dates of birth
I’m a big fan of Robot Framework an automated browser testing framework written in Python making use of Selenium. If you haven’t tried it then I suggest giving it a go.
Anyway I had the need to create random data and one of these fields was a date for birth. I also needed the ability to have a minimum date of birth, so I hacked together the following snippet to do this.
Please note that this function has the following limitations
- a maximum date of birth of Jan 1 1970 (as I use the epoch timestamp)
- For similar reasons you can’t overflow at the other end past 2038.
- The minimum age isn’t strictly enforced. Ideally it should be matched down to the day. However this function will never return you someone younger than ${minimumAge} so it is probably not a huge deal
So my implementation looks something like this
generateRandonDateOfBirth
[Arguments] ${minimumAge}=13
${date}= Get Current Date
${currentTimeStamp}= Convert Date ${date} epoch exclude_millis=yes
${currentYear}= Convert Date ${date} result_format=%Y
${compareYear}= Convert To Integer ${currentYear}
${numberYears}= Convert To Integer ${minimumAge}
${compareYear}= Run Keyword Evaluate ${compareYear}-${numberYears}${secsPerYear}= Set Variable 31557600
${subtractSeconds}= Run Keyword Evaluate ${minimumAge}*${secsPerYear}
${minAgeTimeStamp}= Run Keyword Evaluate ${currentTimeStamp}-${subtractSeconds}
${execStr}= Set Variable random.randint(1, ${minAgeTimeStamp})
:FOR ${i} IN RANGE 100
\ ${randDate}= Evaluate ${execStr} modules=random,sys
\ ${randomYear}= Convert Date ${randDate} result_format=%Y
\ Exit For Loop If ${compareYear} > ${randomYear}
${randYear}= Convert Date ${randDate} result_format=%Y
${randMonth}= Convert Date ${randDate} result_format=%m
${randDay}= Convert Date ${randDate} result_format=%d
[Return] ${randYear} ${randMonth} ${randDay}
So the first part converts minimum age into the oldest birth year that a random person can have.
The next section works out the maximum timestamp since epoch that a person could have. This is the upper bounds for the random number generator.
${execStr} is the string that gets Executed in the loop.
The loop is used to ensure that random person does exceed the age requirement.
Hope it is useful to people out there.