使用factory_boy从父工厂继承Params

时间:2018-03-08 16:32:31

标签: python factory-boy

我希望儿童工厂延长其父母的Params。我认为扩展params比重复它们更可取。我试过让子类中的Params字面上从父Params继承,如下所示:

import factory


class BaseFactory(factory.Factory):
    class Params:
        configuration_one = True

class MyFactory(BaseFactory):
    class Params(BaseFactory.Params):
        configuration_two = False

这是失败的例外:

AttributeError                            Traceback (most recent call last)
<ipython-input-5-cc609d2c781d> in <module>()
      6         configuration_one = True
      7
----> 8 class MyFactory(BaseFactory):
      9     class Params(BaseFactory.Params):
     10         configuration_two = False

<ipython-input-5-cc609d2c781d> in MyFactory()
      7
      8 class MyFactory(BaseFactory):
----> 9     class Params(BaseFactory.Params):
     10         configuration_two = False
     11

AttributeError: type object 'BaseFactory' has no attribute 'Params'

导致此错误的原因是什么?是否有一种惯用的方式来实现我的目标?

版本

Python - 2.7.12

factory_boy - 2.9.2

2 个答案:

答案 0 :(得分:0)

我正在朝着相同的目标努力。我想干燥我的工厂,因为我使用的是多态模型。

坏消息是factoryboy DSL从属性中删除了Meta和Params类。我不确定为什么要这样做,可能简化了他们从父工厂继承pre和post var的方式吗?我认为他们正在尝试从红宝石效仿FactoryGirl,但由于python ...而没有猴子补丁的能力。

这是相关文档。

https://factoryboy.readthedocs.io/en/latest/internals.html?highlight=params

祝你好运。

PS。通过将父Param类放在父Factory之外,我走得更远,但是它仍然无法正常工作。

import factory 

class BaseParam:
  foo=True,
  bar=False 

class MyFactory(factory.Factory):
  class Meta:
    abstract=False
    model=Yolo

  class Params(BaseParam):
    baz=factory.Trait(
      foo=False
    )

MyFactory(baz=True)

给我这个

TypeError: 'foo' is an invalid keyword argument for this function

因此,Param显然不会继承任何东西,也不充当普通类。

答案 1 :(得分:0)

我想出了一种使用装饰器的方法

In [47]: import factory 
    ...: 
    ...:   
    ...: def with_base_params(target_factory):
    ...:   class NewClass(target_factory):
    ...:     class Params:
    ...:       baz=factory.Trait(
    ...:         name="chandeeland",
    ...:         address="123 fake st"
    ...:       )
    ...:   return NewClass
    ...: 
    ...: @with_base_params
    ...: class MyFactory(factory.Factory):
    ...:   class Meta:
    ...:     abstract=False
    ...:     model=Contact
    ...: 
    ...:   name = "someone else"
    ...: 
    ...: a = MyFactory()
    ...: a.name == "someone else"
    ...: a.address == None
    ...: 
    ...: b = MyFactory(name="another name")
    ...: b.name == "another name"
    ...: b.address == None
    ...: 
    ...: c = MyFactory(baz=True)
    ...: c.name == "chandeeland"
    ...: c.address == "123 fake st"
    ...: 
Out[47]: True

它并不完美,您不能扩展参数,但是可以使用