本文为博主原创,未经授权,严禁转载及使用。
本文链接:https://blog.csdn.net/zyooooxie/article/details/124680302
日常测试时,有时候需要大量的‘测试数据’,手工去搞 有些不方便、不快捷,本期分享下我的一些做法。
【实际这篇博客推迟发布N个月】
个人博客:https://blog.csdn.net/zyooooxie
【以下所有内容仅为个人项目经历,如有不同,纯属正常】
faker:构造 假数据
https://pypi.org/project/Faker/
"""
@blog: https://blog.csdn.net/zyooooxie
"""
import faker
import datetime
from collections import Counter
def test_cn():
# https://faker.readthedocs.io/en/master/locales/zh_CN.html
# https://pypi.org/project/Faker/
# faker.Faker can take a locale as an argument, to return localized data.
# If no localized provider is found, the factory falls back to the default LCID string for US english, ie: en_US.
f = faker.Faker(locale='zh_CN') # to create and initialize a faker generator
# # the generator also provide a seed() method, which seeds the shared random number generator.
# # Calling the same methods with the same version of faker and seed produces the same results.
# faker.Faker.seed(123456)
# faker.providers.address
print(f.address())
print(f.city())
print(f.province())
print(f.country())
print(f.country_code())
print(f.postcode())
# faker.providers.date_time 提供方法中 很多参数 都是支持datetime.date, datetime.datetime
print(f.date()) # Get a date string between January 1, 1970 and now.
print(f.date(end_datetime=datetime.datetime(year=1970, month=1, day=5)))
print(f.date(end_datetime=datetime.datetime(year=1970, month=1, day=5), pattern='%y-%m-%d'))
print(f.date(end_datetime=datetime.date(year=1970, month=1, day=5)))
faker_datetime_date = f.date_between(start_date=datetime.datetime(year=2021, month=12, day=1),
end_date=datetime.datetime(year=2022, month=1, day=1))
print(faker_datetime_date, type(faker_datetime_date))
date_str = faker_datetime_date.strftime('%Y-%m-%d %H:%M:%S')
print(date_str)
print(f.date_between(start_date=datetime.date(year=2021, month=12, day=1),
end_date=datetime.date(year=2022, month=1, day=1)))
print(f.date_this_month(before_today=True)) # Gets a Date object for the current month.
print(f.date_this_month(after_today=True, before_today=False))
print(f.date_this_year()) # Gets a Date object for the current year.
print(f.date_this_year(after_today=True))
print(f.date_time_this_month()) # Gets a datetime object for the current month.
print(f.date_time_this_month(after_now=True))
print(f.date_time_this_year()) # Gets a datetime object for the current year.
print(f.date_time_this_year(after_now=True))
faker_datetime = f.date_time_between(start_date=datetime.datetime(year=2021, month=7, day=1),
end_date=datetime.datetime(year=2021, month=8, day=1))
print(faker_datetime, type(faker_datetime))
time_str = faker_datetime.strftime('%Y-%m-%d %H:%M:%S')
print(time_str, type(time_str))
print(f.date_time_between(start_date=datetime.date(year=2021, month=7, day=1),
end_date=datetime.date(year=2021, month=8, day=1)))
print(f.date_time()) # Get a datetime object for a date between January 1, 1970 and now
print(f.date_time(end_datetime=datetime.datetime(year=1970, month=1, day=5)))
print(f.date_time(end_datetime=datetime.date(year=1970, month=1, day=5)))
print(f.time()) # Get a time string (24h format by default)
print(f.time(pattern='%I:%M:%S'))
print(f.unix_time()) # Get a timestamp between January 1, 1970 and now
print(f.unix_time(start_datetime=datetime.date(year=2022, month=1, day=1),
end_datetime=datetime.date(year=2022, month=1, day=2)))
print(f.unix_time(start_datetime=datetime.datetime(year=2022, month=1, day=1),
end_datetime=datetime.datetime(year=2022, month=1, day=2)))
print(f.am_pm())
print(f.day_of_month())
print(f.day_of_week())
print(f.month_name())
print(f.month())
# faker.providers.company
print(f.company())
print(f.bs())
# faker.providers.internet
print(f.free_email())
print(f.image_url())
print(f.uri()) # 统一资源标识符
print(f.url()) # 统一资源定位符
print(f.user_name()) # 用户名
# faker.providers.job
print(f.job())
# faker.providers.lorem
print(f.paragraphs()) # Generate a list of paragraphs. nb: int = 3,
print(f.paragraphs(nb=5))
# The nb_sentences argument controls how many sentences the paragraph will contain,
# and setting variable_nb_sentences to False will generate the exact amount,
# while setting it to True (default) will generate a random amount (+/-40%, minimum of 1) using randomize_nb_elements().
print(f.paragraph()) # nb_sentences: int = 3,
print(f.paragraph(nb_sentences=5, variable_nb_sentences=False))
# The nb_words argument controls how many words the sentence will contain,
# and setting variable_nb_words to False will generate the exact amount,
# while setting it to True (default) will generate a random amount (+/-40%, minimum of 1) using randomize_nb_elements().
print(f.sentence()) # nb_words: int = 6
print(f.sentence(nb_words=10, variable_nb_words=False))
print(f.word())
print(f.words()) # nb: int = 3
print(f.words(nb=8))
print(f.words(nb=10, unique=True))
# faker.providers.person
print(f.first_name())
print(f.last_name())
print(f.name())
# faker.providers.phone_number
print(f.phone_number())
print(f.phonenumber_prefix())
def test_other_locales():
# f = faker.Faker(locale='zh_TW') # 繁体中文
# f = faker.Faker(locale='en_US') # 默认为en_US
pass
def test_Standard_Providers():
# https://faker.readthedocs.io/en/master/providers/baseprovider.html
f = faker.Faker()
print(f.random_digit()) # 0~9随机数 Generate a random digit (0 to 9)
print(f.random_digit_not_null()) # 1~9的随机数 Generate a random non-zero digit (1 to 9)
print(f.random_int()) # min: int = 0, max: int = 9999, step: int = 1
print(f.random_int(max=999999999, min=1))
print(f.random_int(1, 20))
print(f.random_letter()) # Generate a random ASCII letter (a-z and A-Z)
print(f.random_number()) # If digits is None (default), its value will be set to a random integer from 1 to 9.
print(f.random_number(
digits=3)) # digits代表 生成的数字位数,要小于等于;If fix_len is False (default), all integers that do not exceed the number of digits can be generated.
print(f.random_number(digits=3,
fix_len=True)) # If fix_len is True, only integers with the exact number of digits can be generated
print(
f.file_extension()) # If category is None, a random category will be used. The list of valid categories include: 'audio', 'image', 'office', 'text', and 'video'.
print(f.file_extension(category='audio'))
print(f.file_name())
print(f.file_name(category='text'))
print(f.file_name(category='image', extension='jpeg'))
print(f.boolean())
print(f.boolean(chance_of_getting_true=25))
print(f.null_boolean()) # Generate None, True, or False, each with equal probability.
print(f.md5())
print(f.password())
print(f.password(length=12))
print(f.uuid4())
print(f.uuid4().replace('-', ''))
# https://faker.readthedocs.io/en/master/providers/faker.providers.profile.html
print(f.profile())
print(f.simple_profile())
# https://faker.readthedocs.io/en/master/providers/faker.providers.python.html
# 很多方法的参数nb_elements: int = 10
print(f.pydecimal(), type(f.pydecimal()))
print(f.pydecimal(left_digits=2, right_digits=4))
print(f.pydecimal(min_value=100, max_value=900))
print(f.pydict())
print(f.pydict(nb_elements=5))
print(f.pyfloat(), type(f.pyfloat()))
print(f.pyfloat(right_digits=2, left_digits=2))
print(f.pyfloat(min_value=100, max_value=900))
print(f.pyint())
print(f.pyint(min_value=1000, max_value=9000, step=500))
print(f.pyiterable())
print(f.pyiterable(nb_elements=5))
print(f.pylist())
print(f.pylist(nb_elements=5))
print(f.pyset())
print(f.pyset(nb_elements=5))
print(f.pystr())
print(f.pystr(min_chars=10, max_chars=20)) # Random of random length between min and max characters.
print(f.pytuple())
print(f.pytuple(nb_elements=5))
def test_1():
# Unique values
# Through use of the .unique property on the generator, you can guarantee that any generated values are unique for this specific instance.
f = faker.Faker()
u1 = [f.unique.name() for _ in range(500)]
print([(k, v) for k, v in Counter(u1).items() if v != 1])
u2 = [f.name() for _ in range(500)]
print([(k, v) for k, v in Counter(u2).items() if v != 1])
实际场景
Fiddler:AutoResponder 构造 假的响应值
AutoResponder 可以对 抓到的请求 Add Rule,可以 重定向到本地文件,也可以 直接指定响应结果。
"""
@blog: https://blog.csdn.net/zyooooxie
"""
def create_response_body(user_num: int = 100):
f = faker.Faker()
res_dict = dict.fromkeys(['errorCode', 'errorMessage'])
now_str = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
res_dict.update(success=True, date=now_str, notSuccess=False)
abc = [f.first_name() for _ in range(user_num)]
obj_dict = {'list': abc, 'otherObj': None}
res_dict.update(obj=obj_dict)
print(json.dumps(res_dict))
if __name__ == '__main__':
pass
# create_response_body(user_num=60)
Fiddler:Composer 发请求
我用Fiddler 主要抓包;知道它能发请求,做接口测试,但我觉得 很鸡肋,然后 就被打脸了。
Composer 可以直接将 抓到的请求 拖过来,篡改数据(请求头、请求体、URL、请求方法)
【对我而言,最‘懒’的玩法:某些请求 Cookie带有身份信息,可以拿来就用】
"""
@blog: https://blog.csdn.net/zyooooxie
"""
def create_request_body(user_num: int = 100):
f = faker.Faker()
abc = [f.first_name() for _ in range(user_num)]
type1 = 1
type2 = 2
type3 = 3
res = {'type': type2, 'user': abc}
print(json.dumps(res))
if __name__ == '__main__':
pass
# create_request_body(101)
创建某参数值
这是外部系统的 某个接口文档:
"""
@blog: https://blog.csdn.net/zyooooxie
"""
def get_str(res: bytes, create_len: int) -> str:
"""
bytes转str,
:param res:
:param create_len:
:return: 转化后的str
"""
abc = res[:create_len]
while True:
try:
res = abc.decode(encoding="utf-8", errors="strict")
except UnicodeDecodeError:
print('error')
abc = abc[:len(abc) - 1]
else:
print('get_str()执行后', len(abc), len(res))
return res
def create_bytes_str(create_len: int, bytes_str: bool, en_zh: str = 'en') -> str:
"""
返回一个 小于等于create_len 的str
:param create_len:
:param bytes_str:2种类型
:param en_zh:初始生成数据时,分中文、英文
:return:
"""
f = faker.Faker('zh_CN')
if en_zh == 'en':
res = f.pystr(min_chars=create_len, max_chars=create_len)
else:
words_list = f.words(nb=create_len // 2) # words生成的是 [2个字,]
res = ''.join(words_list)
print('生成字符串', res, type(res), len(res))
if bytes_str:
res_1 = bytes(res, encoding='utf-8')
print('转成bytes类型', res_1, len(res_1))
res = get_str(res_1, create_len)
print('最后的结果', res, type(res), len(res))
return res
if __name__ == '__main__':
pass
# create_bytes_str(88, True)
# create_bytes_str(88, True, 'zh')
# create_bytes_str(88, False)
create_bytes_str(88, False, 'zh')
本文链接:https://blog.csdn.net/zyooooxie/article/details/124680302
交流技术 欢迎+QQ 153132336 zy
个人博客 https://blog.csdn.net/zyooooxie