Python date string testing -
in python based application, user can enter dates in format of dd/mm/yy date separator variations(like can use /,- or space seperator). therefore these valid dates:
10/02/2009 07 22 2009 09-08-2008 9-9/2008 11/4 2010 03/07-2009 09-01 2010
now in order test it, need create list of such dates, not sure how auto generate random combinations of these date strings seperators.
this started doing:
date = ['10', '10', '2010'] seperators = ['/', '-', ' '] s in seperators: new_date = s.join(date)
i think previous answers didn't much. if choose "day" number 1-31 , "month" number 1-12 in test data, productive code must raise exceptions somewhere - 02/31/2013 should not accepted!
therefore, should create random, valid dates , create strings them arbitrarily chosen format strings. code does:
import datetime import time import random separators = ["/",",","-"," "] prefixes = [""," "] def random_datetime(min_date, max_date): since_epoch_min = time.mktime(min_date.timetuple()) since_epoch_max = time.mktime(max_date.timetuple()) random_time = random.randint(since_epoch_min, since_epoch_max) return datetime.datetime.fromtimestamp(random_time) def random_date_string_with_random_separators(dt): prefix = random.choice(prefixes) sep1 = random.choice(separators) sep2 = random.choice(separators) format_string = "{}%m{}%d{}%y".format(prefix, sep1, sep2) return dt.strftime(format_string) min_date = datetime.datetime(2012,01,01) max_date = datetime.datetime(2013,01,01) in range(10): print random_date_string_with_random_separators( random_datetime(min_date, max_date) )
this should cover cases (if take more ten values).
nevertheless, have 2 remarks:
don't use random data test-input
you'll never know if someday test fail, maybe don't catch possible problems data generated. in case should o.k., it's not practice (if have choice). alternatively, create well-thought set of hard-coded input strings cover corner cases. , if someday tests fail, know it's no random effect.
use well-tested code
for task describe, there's library that! use dateutil
. have fantastic datetime-parser swallows throw @ it. example:
from dateutil import parser in range(10): date_string = random_date_string_with_random_separators( random_datetime(min_date, max_date) ) parsed_datetime = parser.parse(date_string) print date_string, parsed_datetime.strftime("%m/%d/%y")
output:
01 05,2012 01/05/2012 05 17-2012 05/17/2012 06-07-2012 06/07/2012 10 31,2012 10/31/2012 10/04,2012 10/04/2012 11 16,2012 11/16/2012 03/23 2012 03/23/2012 02-26-2012 02/26/2012 01,12-2012 01/12/2012 12-21 2012 12/21/2012
then can sure works. dateutil
has tons of unit tests , "just work". , best code can write code don't have test.
Comments
Post a Comment