测试分享之构造假数据

本文为博主原创,未经授权,严禁转载及使用。
本文链接: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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
“泰迪杯”数据分析技能赛是一场面向大学生的数据分析比赛,旨在提高参赛选手的数据分析能力和实践技能。2023 年的比赛b 题是关于企业财务数据分析与造识别,这是一个非常实际和挑战性的课题。在这个题目中,参赛选手需要运用数据分析技能,对企业的财务数据进行深入分析,并且识别出可能存在的造行为。 首先,参赛选手需要对企业的财务数据进行收集和整理,包括资产负债表、利润表、现金流量表等重要的财务报表。然后,他们需要利用统计分析和数据挖掘的方法,对这些数据进行分析和建模,从中发现潜在的异常模式和规律。比如,他们可以通过比对历年财务数据的变化趋势,来找出异常波动和不符合常规的情况。 除此之外,参赛选手还需要了解财务造的常见手法和特征,比如虚增收入、操纵成本、滥用会计估计等。通过对比企业的财务数据和这些特征,他们可以识别出可能存在的财务造行为,并进一步进行深入分析和验证。 最后,参赛选手要结合实际案例和理论知识,对识别出的财务造行为进行解释和评估,提出有效的应对措施和建议。这需要他们对企业经营环境和产业特点有深入了解,能够把数据分析结果与实际情况相结合,为企业的风险防控和决策提供有力支持。 总的来说,这个比赛题目既考验了参赛选手的数据分析技能,也考察了他们对财务管理和风险控制方面的综合能力。希望参赛选手们能够在比赛中充分发挥自己的专业知识和创新能力,为企业财务数据分析与造识别这一重要领域带来新思路和解决方案。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值