工厂调用备用构造函数(classmethod)

Esk*_*app 3 python testing class-method python-3.x factory-boy

我正在努力找到一种方法来factory_boy使用定义为a的备用构造函数来创建类Factory(我使用版本2.11.1和Python 3)@classmethod.

因此,假设我们有一个用于构建具有默认构造函数的2D点对象的类,另外还有2个:

class Point:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    @classmethod
    def fromlist(cls, coords):  # alternate constructor from list
        return cls(coords[0], coords[1])

    @classmethod
    def duplicate(cls, obj):  # alternate constructor from another Point
        return cls(obj.x, obj.y)
Run Code Online (Sandbox Code Playgroud)

我创建了一个基本的Point工厂:

import factory

class PointFactory(factory.Factory):
    class Meta:
        model = Point
        inline_args = ('x', 'y')

    x = 1.
    y = 2.
Run Code Online (Sandbox Code Playgroud)

默认情况下,它似乎调用__init__类的构造函数,这似乎非常合乎逻辑.我不能找到一种方法,通过inline_argscoords使用可选的构造fromlist.有办法吗?

这是我第一次在工作和建造工厂的经历,所以我也可能在网上查找错误的关键字......

Mar*_*ers 5

关键factory_boy是要使生成测试实例变得容易.你只需要打电话PointFactory() ,你就完成了,你有其余代码的测试实例.此用例不需要使用任何替代构造函数.工厂只会使用主构造函数.

如果您认为必须定义factory_boy工厂来测试您的额外构造函数,那么您就误解了它们的用法.使用factory_boy工厂为要测试的其他代码创建测试数据.你不会用它们来测试Point类(除了生成测试数据以传递你的一个构造函数).

请注意,inline_args只有在构造函数根本不接受关键字参数时才需要.你的Point()班级没有这样的限制; x并且y可以用作位置和关键字参数.你可以安全地inline_args从你的定义中删除,工厂无论如何都会工作.

如果必须使用其他构造函数之一(因为无法使用主构造函数创建测试数据),只需将特定构造函数方法作为模型传递:

class PointListFactory(factory.Factory):
    class Meta:
        model = Point.fromlist

    coords = (1., 2.)
Run Code Online (Sandbox Code Playgroud)