Reputation: 53
I want to generate 5 test cases which gives random data in json format as given below.
{
"password2": "password@123",
"email": "[email protected]",
"username": "user123",
"first_name": "first",
"last_name": "last",
"phone":"1234567890",
"city":"Paris",
"about":"This is information about developer"
}
The code below gives 5 test cases, but with similar details. I want to generate 5 different test case with all different details. Thank you in advance.
Code:
from faker import Faker
import random
class LoginData:
fake = Faker()
password = "password@123"
email = fake.email()
username = fake.first_name()
first_name = fake.first_name()
last_name = fake.last_name()
phone = random.randint(9000000000, 9999999999)
city = fake.city()
about = "This is a sample text : about"
def get_json(self):
p = {
'password': self.password,
'email': self.email,
'username': self.first_name,
'first_name': self.first_name,
'last_name': self.last_name,
'phone': self.phone,
'city': self.city,
'about': self.about
}
return p
logindata = LoginData()
def input_data(x):
for i in range(0, x):
print(logindata.get_json())
def main():
no_of_input = 5
input_data(no_of_input)
main()
Upvotes: 2
Views: 5888
Reputation: 4383
If I understand correctly, the problem is that you want to generate different data every time. To do that, you need to:
Currently the LoginData
attributes are generated when the class is defined. If you want them to be different for each instance, make them instance attributes and set them in the __init__()
method.
You need to create a new LoginData
instance in every iteration of the for loop in input_data()
.
Code:
from faker import Faker
import random
class LoginData:
def __init__(self):
fake = Faker()
self.password = "password@123"
self.email = fake.email()
self.username = fake.first_name()
self.first_name = fake.first_name()
self.last_name = fake.last_name()
self.phone = random.randint(9000000000, 9999999999)
self.city = fake.city()
self.about = "This is a sample text : about"
def get_json(self):
p = {
'password': self.password,
'email': self.email,
'username': self.first_name,
'first_name': self.first_name,
'last_name': self.last_name,
'phone': self.phone,
'city': self.city,
'about': self.about
}
return p
def input_data(x):
for i in range(0, x):
logindata = LoginData()
print(logindata.get_json())
def main():
no_of_input = 5
input_data(no_of_input)
main()
Note that get_json()
still returns a Python dict, not JSON. For JSON, you can use the json
module in the standard library:
import json
and in get_json()
return json.dumps(p)
Upvotes: 1