在 factory boy 中使用 Faker 清除唯一缓存

您所在的位置:网站首页 python刷新缓存 在 factory boy 中使用 Faker 清除唯一缓存

在 factory boy 中使用 Faker 清除唯一缓存

2023-04-22 14:04| 来源: 网络整理| 查看: 265

I am using Faker from inside factory boy and we are getting duplicate values that are making our tests fail. Faker has the ability to generate unique values, but it has a finite number of values for a given provider like first_name. We have 100s of tests and after a while all the unique values have been used and we get a UniquenessException. I read there is a unique.clear() method which clears the already seen values, however, this seems not to work. I instrumented faker/proxy.py to log when clear is called and what the length of the already seen values is and although clear is called the length continues to increase. I am thinking it's an issue with scope, but I have tried it many different ways. Faker is called from our factories. I have tried calling it from an autouse function run before each test, and even at the start of each test. I need to instantiate Faker to call the clear function - perhaps each time I do that it is not the same instance the factories use.

Further instrumenting the faker code shows that when faker is called to get some data it's one instance (the same one every time), but when clear is called it's a different instance. Need to get a handle for the instance the data is being generated from.

How can I do that?

解决方案

我已经解决了这个问题。我将此添加到 conftest:

@pytest.fixture(scope="session") def fake(): return factory.Faker._get_faker() @pytest.fixture(autouse=True) def run_before_and_after_tests(fake): """Fixture to execute code before and after a test is run""" # Setup: this code runs before each test fake.unique.clear() yield # this is where the testing happens # Teardown : this code runs after each test

现在,在与我们用来获取数据的 faker 实例相同的 faker 实例中,每次测试之前都会调用 clear,已经清除了缓存,我没有看到任何重复的密钥问题。

程序员说:42岁了,突然觉得研发前途渺茫

中国程序员数量达755万,全球排名第二

为什么都说程序员找不到女朋友,但是身边程序猿的却没一个单身的?

程序员说:30岁以上你还死磕技术,别说拿高薪,可能你连饭碗都会保不住

程序员被开除,老板:“有你参与的项目全黄了!”

笑话:一个测试工程师走进一家酒吧

笑话:面试官:请拿出一段体现你水平的代码。我: sudo rm -rf /*面试官:这体现了你哪方面能力?

python精选:Python 办公实战!​按姓名拆分 Excel 为单独文件,微信自动发给相应联系人

网友说:做开发,不被领导喜欢怎么办?

网友说:我奉劝各位,一定不能在职场透露自己的家庭条件



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3