开发者

Create random data for testing

Does anyone know of an app that would generate an xml file filled out with random data?

My app has an importer that should handle almost all sizes and structure of xml files, and I'd like to test this.

To be clear; not only do all element names and values need to be random, but also the tree structure itself. There should 开发者_Go百科be random numbers of child branches, each with further random branches and so on.

Similarly, is there an application that would create the same sort of random data for Json files?


Step 1. Define a template for the repeating elements in the XML.

t= string.Template( """<sometag><data>${data}</data><moredata>${moredata}</moredata></sometag>""" )

Step 2. Generate random values.

import random
args = dict(
    data = random.random(),
    moredata= random.random()
)

Step 3. Insert random values into the template.

t.substitute( **args )

You can, without much work, easily generate lots of random XML. Want names instead of numbers?

def random_name( size=8 ):
    return "".join( random.choice(string.ascii_letters) for x in range(size) )

Want variable-length names?

def random_variable_len_name( mean_size= 8, std_size= 2 ):
    size= int(random.gauss( mean_size, std_size ))
    return random_name( size )

The possibilities are endless, and really simple to implement.


Random JSON is even easier.

import json
import random
args = dict(
    data = random.random(),
    moredata= random.random()
)
json.dumps( [args] )        

If "random" confuses you, consider this.

t1 = string.Template( """<sometag>${body}</sometag>""" )
t2 = string.Template( """<othertag attr="$attr">$data</othertag>""" )
t3 = string.Template( """<moretag attr="$attr">$data</moretag>""" )
elements = random.randint(0,4)
body= [ random.choice([t2,t3]).substitute( attr=random.random(), data= random_name() ) for x in range(elements) ]
t1.substitute( body="".join( body ) )

That, for example, will create random tags within another tag.


For XML files, you may want to consider XML Generator by Stylus Studios. You'll have to define the XML structure ahead of time, but the data will be random. It's not a free product, but you can download the trial and see if it fits your needs.

For generating random JSON, a good suggestion has been posted on SO here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜