使用 factory_boy 和 randint 时生成重复值的问题

Issue with duplicate values generated when using factory_boy and randint

我发现在使用 randint 和 factory_boy 时生成了重复值。检查每个对象的资产时我的测试失败。在工厂调用create()时两者的条码也是一样的。

我是否需要在创建每个对象之前提供不同的种子?

文件

seed/factories.py

import factory
from A1.models import *
from random import randint, random
faker = Factory.create()

class AssetFactory(factory.DjangoModelFactory):

    class Meta:
        model = Asset

asset = "ABC" + str(randint(0000, 9999))
barcode = "AA" + randint(111111, 999999)
user = factory.lazy_attribute(lambda x: faker.name())

tests.py

def test_randomCreation(self):
    new_asset = AssetFactory.create()
    new_asset2 = AssetFactory.create()
    self.assertNotEqual(new_asset.asset, new_asset2.asset)  #FAILS

A1/models.py

class Asset(models.Model):
    asset =  models.CharField(max_length=255, verbose_name="Asset")
    barcode = models.CharField(max_length=255)
    user = models.CharField(max_length=255)

有人可以指出我正确的方向吗? 提前致谢!!

Python 语言的设计方式,您的代码无法运行。

严格等同于:

_RANDOM_ASSET = "ABC" + str(randint(0000, 9999))
_RANDOM_BARCODE = "AA" + str(randint(111111, 999999))

class AssetFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.Asset
    asset = _RANDOM_ASSET
    barcode = _RANDOM_BARCODE
    user = factory.LazyAttribute(lambda x: faker.name())

您已为 assetbarcode 固定了一个随机值,因此通过该工厂生成的每个对象都将具有完全相同的值。

正确的方法是使用各种内置声明:

class AssetFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.Asset

    asset = factory.fuzzy.FuzzyText(length=4, prefix='ABC', chars=string.digits)
    barcode = factory.fuzzy.FuzzyText(length=6, prefix='AA', chars=string.digits)
    user = factory.Faker('name')