【问题标题】:Testing python class object instances测试python类对象实例
【发布时间】:2019-12-19 13:01:42
【问题描述】:

我有这个功能要测试:

def get_django_model(django_model):
    try:
        app_config = apps.get_app_config("myapp")
        model = app_config.get_model(django_model)
        return model
    except Exception:
        raise DjangoModelMissing(f"Missing django model: {django_model}")

这是我的测试:

class ModelInstanceTest(TestCase):
    def test_get_django_model(self):
        model_class = get_djagno_model("Foo")
        self.assertIsInstance(model_class, models.Foo) 

上面的测试失败了,说AssertionError: <class 'models.Foo'> is not an instance of <class 'models.Foo'>

但是,如果我将 assertIsInstance 替换为 assertIs,则测试通过。

有人能解释一下这里发生了什么吗?

这篇文章是相关的,但并没有真正解释不同的结果:Python test to check instance type

【问题讨论】:

  • 一个类确实不是该类的一个实例。
  • 你的测试中还有一个错字get_djagno_model (django)

标签: python django class oop


【解决方案1】:

您的get_django_model 函数返回对 的引用,而不是该类的对象(实例)。所以它不返回一个Fooobject,它返回一个对Foo类的引用。

因此model_class 确实等于models.Foo,但不是models.Foo 的实例。然而,它是type 的一个实例,因此您可以检查:

class ModelInstanceTest(TestCase):

    def test_get_django_model(self):
        model_class = get_djagno_model('Foo')
        self.assertIsInstance(model_class, type)
        self.assertEqual(model_class, models.Foo)

【讨论】:

  • 当你说它返回一个类的引用时,这和说它返回一个元类是一样的吗?
  • @dwvldg:类的类型是元类。所以是的,你可以说model_class 是一个元类的对象。
  • typemeta-class 是同一个东西吗?换句话说,self.assertIsInstance(model_class, type) 只是说model_class 是元类的一个实例吗?是否有另一种方法来测试某物是否是元类的实例?
  • @dwvldg:但没有明确的区别,因为在 Python 中一切都是对象。 type 的类型是 type 等等,所以你可以说“元层次结构”一直持续到无穷大。
猜你喜欢
  • 2014-09-25
  • 2015-12-29
  • 2011-08-09
  • 1970-01-01
  • 2015-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多