Developer's Diary
Software development, with Terry Ebdon
10-Jun-2020 Data generation

Random

I've been working on a Grails web app. The app needs to hold user information for adults and children.

class User {
String firstName
String lastName
String email
Date dateOfBirth
Boolean fullMember
// ...
}

Obviously I need some test data, and a decent amount of it. I used randat.com to create the initial dataset, but that was trickier than I expected. The site can't generate dates. It can handle ages, but only for adults. I selected the youngest available age range and ran with this configuration:

I thought that would be good enough, with some Bootstrap.groovy code to handle the age to date conversion. The down-loaded CSV file has unnecessary double quotes, and the email addresses use randatmail.com. I fixed both issues with a global replace, in VS Code, to give a file like this:

First Name,Last Name,Age,Email
Frederick,Barrett,25,f.barrett@example.com
Kimberly,Harris,18,k.harris@example.com
...

The file has a fatal flaw, RANDAT has allocated the same email address to several users. The final Boostrap code has to infer the date of birth and generate a new email address. In retrospect I should have used RANDAT for just the name fields and added everything else myself, it would have been faster and simpler.

Loading the users

private loadRandomUsers() {
println "Begin loading random users."
File csv = new File('users.csv')
if ( csv.exists() ) {
csv.eachLine { line ->
def bits = line.split(',')
if ( bits[2] != 'Age' ) { // Skip the CSV header line
def first = bits[0]
def last = bits[1]
new User(
email: emailAddress( first, last ),
firstName: first,
lastName: last,
dateOfBirth: birthDateFromAge( bits[2] ),
fullMember: true
).save( failOnError: true )
}
}
}
println "End loading random users."
}

Generate email address

private String emailAddress( String first, String last ) {
"${first}.${last}@example.com"
}

Infer date of birth

The user table has to include children to test the app. Four years is subtracted from the age to force some kids into the dataset. The final ages will be in the range 14 to 26.

private birthDateFromAge( def age ) {
new Date( new Date().year - age.toInteger() - 4, 6, 15 )
}

03-JUN-2020 👈 Top of page 👉 11-JUN-2020

© 2020 Terry Ebdon.

Find me coding on GitHub, networking on LinkedIn, answering questions on Stack Exchange and hanging out on twitter.