gallly
gallly

Reputation: 1211

Random data for test automation in python

I am using unittest and selenium to automate my browser testing.

How would I go about making a test which I can run multiple times, where a user creates a ticket. The ticket has to has a title name, each time I run the test I want the title name to be random.

I would like the format: "Test ticket, 1 | Test ticket, 2..."

Upvotes: 4

Views: 5287

Answers (3)

kenorb
kenorb

Reputation: 166687

You can define the following functions in your test:

import random, string

def random_word(self, length=6, chars=string.ascii_lowercase):
   return ''.join(random.choice(chars) for i in range(length))

def random_id(self, size=6, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

def random_number(self, length=3):
    return ''.join(random.choice(string.digits) for i in range(length))

and similar.

See also:

Upvotes: 0

Johannes Jasper
Johannes Jasper

Reputation: 921

If you just need the string Test ticket,1 ... it is:

from random import randint
randomString = "Test ticket, " + randint(min,max)

If you want to generate random strings you could use

''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(max))

You also might want to think about preventing strings to be equal. In that case you could create a range(min,max) and use random.shuffle()

Upvotes: 2

Andy Hayden
Andy Hayden

Reputation: 375685

The faker module offers some functionality to populate several different types of data:

import faker
f = faker.Faker()

In [11]: f.
f.city            f.full_address    f.phonenumber     f.zip_code
f.company         f.last_name       f.state
f.email           f.lorem           f.street_address
f.first_name      f.name            f.username

In [11]: f.city()
Out[11]: u'Treyview'

.

If you are going to test randomly, I recommend randomly generating a seed (and logging it), that way you can recreate any failing tests. What you don't want is tests which fail but it's unclear why (i.e. if testing again, with different random values, passes).

Upvotes: 8

Related Questions