Package: testdata
TestdataGenerate Random Test Data.These are just a bunch of handy functions designed to make it easier to test your code.To use testdata in your tests, just import it into your testing module:import testdataTo install, use Pip:pip install testdataOr, with Pip using Github:pip install --upgrade "git+https://github.com/Jaymon/testdata#egg=testdata"FunctionalityThis is an overview of some of the functions and classes found in the Testdata module, there are other functions (likeget_birthday) that aren't listed here, for the complete list just look at thesource. Any methods on any child class that extendstestdata.base.TestDatawill be available attestdata.<METHOD-NAME>.patchPatching modules and classespatch(mod,**patches)Patches a module, instance, or class with the given patches.Suppose you had a module like this:# module foo.bardefboom():return1classFooPatch(object):@classmethoddefbam(cls):returnboom()Now you can easily patch it for testing:defmock_boom():return2foo_bar=testdata.patch('foo.bar',boom=mock_boom)printfoo_bar.FooPatch.bam()# 2# but you can also just pass in objects or modulesfromfoo.barimportFooPatchFooPatch=testdata.patch(FooPatch,boom=mock_boom)printFooPatch.bam()# 2fromfooimportbarbar=testdata.patch(bar,boom=mock_boom)printbar.FooPatch.bam()# 2Patching class instancesYou can also patch a specific instanceSuppose you had a module like this:# module foo.barclassFoo(object):defboom(self):return1Now you can easily patch it for testing:defmock_boom():return2foo=Foo()foo_patched=testdata.patch(foo,boom=mock_boom)printfoo_patched.boom()# 2# be aware though, the original instance was modified, foo_patched == fooprintfoo.boom()# 2runRun a command on the command liner=testdata.run("echo 1")print(r)# 1fetchRequest a urlr=testdata.fetch("http://example.com")print(r.code)# 200print(r.body)# the html body of example.comcaptureOutput buffering, handy when you want to make sure logging or print statements are doing what you think they should be doing.withtestdata.capture()asc:print("foo")if"foo"inc:print("foo was captured")ThreadingA wrapper around python's builtinthreading.Threadclass that bubbles errors up to the main thread because, by default, python's threading classes suppress errors, this makes it annoying when using threads for testing.NOTE- This is buggier than I would like.defrun():raiseValueError("join_2")thread=testdata.Thread(target=run)thread.start()print(thread.exception)File ServerSometimes you need to test fetching remote filesimportrequestsserver=testdata.create_fileserver({"foo.txt":["foo"],"bar.txt":["bar"],})withserver:# the with handles starting and stopping the serverres=testdata.fetch(server.url("foo.txt"))print(res.body)# fooenvironmentChange your environment with this context manager, if you don't pass in an object as the first value it will default toos.environwithtestdata.enviroment(FOO=1):print(os.environ["FOO"])# 1print(os.environ["FOO"])# raises KeyError# you can also modify objects:d={}withtestdata.enviroment(d,FOO=1):print(d["FOO"])# 1print(d["FOO"])# raises KeyErrorcreate_dircreate_dir(path="",tmpdir="")create a directory hierarchybase_dir="/tmp"d=testdata.create_dir("/foo/bar",base_dir)printd# /tmp/foo/barcreate_dirscreate_dirs(dirs,tmpdir="")Create a bunch of files and folderstestdata.create_dirs({"foo":{"bar":{"che.txt":["line 1","line 2"],}}})create_filecreate_file(data="",path="",tmpdir="",encoding="")create a file with contentsbase_dir="/tmp"f=testdata.create_file(path="/foo/bar.txt",data="The file contents",tmpdir=base_dir)printf# /tmp/foo/bar.txtcreate_filescreate_files(file_dict,tmpdir="")Create a whole bunch of files, thefile_dictkey is the filename, the value is the contents of the file.
Thefile_dictis very similar to thecreate_modulesparammodule_dictfile_dict={"foo/bar.txt":"the foo file contents","baz.txt":"the baz file contents",}f=testdata.create_files(file_dict)get_fileget_file(path="",tmpdir="")This will return aFilepathinstance that you can manipulate but unlikecreate_fileit won't actually create the file, just give you a path to a file that could be created.create_modulecreate_module(data="",modpath="",tmpdir="",make_importable=True)create a module with python contents that can be importedbase_dir="/tmp"f=testdata.create_module(modpath="foo.bar",data="class Che(object): pass",tmpdir=base_dir)printf# /tmp/foo/bar.pycreate_modulescreate_modules(module_dict,tmpdir="",make_importable=True)create a whole bunch of modules at oncef=testdata.create_modules({"foo.bar":"class Che(object): pass","foo.bar.baz":"class Boom(object): pass","foo.che":"class Bam(object): pass",})get_asciiget_ascii(str_size=0)return a string of ascii characters>>> testdata.get_ascii()
u'IFUKzVAauqgyRY6OV'get_md5get_md5(val="")return an md5 hash of val (if passed in) or a random val if val is empty>>> testdata.get_md5()
'e165765400b30772f1d9b3975ce77320'get_hashget_hash(str_size=32)return a random hash>>> testdata.get_hash()
"jYw3HseUl8GLoMc8QejLYFogC2lUYoUs"get_boolget_bool()return a boolean (eitherTrueorFalse)>>> testdata.get_bool()
False
>>> testdata.get_bool()
Trueget_floatget_float(min_size=None,max_size=None)return a floating point number betweenmin_sizeandmax_size.>>> testdata.get_float()
2.932229899095845e+307get_intget_int(min_size=1,max_size=sys.maxsize)return an integer betweenmin_sizeandmax_size.>>> testdata.get_int()
3820706953806377295get_nameget_name(name_count=2,as_str=True)returns a random name that can be outside the ascii range (eg, name can be unicode)>>> testdata.get_name()
u'jamel clarke-cabrera'get_emailget_email(name=u'')returns a random email address in the ascii range.>>> testdata.get_email()
u'shelley@gmail.com'get_strget_str(str_size=0,chars=None)return random characters, which can be unicode.>>> testdata.get_str()
"q\x0bwZ\u79755\ud077\u027aYm\ud0d8JK\x07\U0010df418tx\x16"get_urlget_url()return a random url.>>> testdata.get_url()
u'https://sK6rxrCa626TkQddTyf.com'get_wordsget_words(word_count=0,as_str=True)return a random amount of words, which can be unicode.>>> testdata.get_words()
"\u043f\u043e\u043d\u044f\u0442\u044c \u043c\u043e\u0436\u043d\u043e felis, habitasse ultrices Nam \u0436\u0435\u043d\u0430"get_past_datetimeget_past_datetime([now])return a datetime guaranteed to be in the past fromnow>>> testdata.get_past_datetime()
datetime.datetime(2000, 4, 2, 13, 40, 11, 133351)get_future_datetimeget_future_datetime([now])return a datetime guaranteed to be in the future fromnow>>> testdata.get_future_datetime()
datetime.datetime(2017, 8, 3, 15, 54, 58, 670249)get_between_datetimeget_between_datetime(start[,stop])return a datetime guaranteed to be in the future fromstartand in the past fromstop>>> start = datetime.datetime.utcnow() - datetime.timedelta(days=100)
>>> testdata.get_between_datetime(start)
datetime.datetime(2017, 8, 3, 15, 54, 58, 670249)DevelopmentTestingTesting on MacOS:$ python -m unittest testdata_testDependenciesDevelopment needsdatatypeson the path. This is kind of a strange thing because datatypes depends ontestdatafor testing. Makingdatatypesavailable totestdatafor development should be as easy as:export PYTHONPATH=$PYTHONPATH:/path/to/dir/containing/datatypes