0

我正在尝试编写一些单元测试,并为此创建了一些虚拟对象。我有一个speaker部分看起来像这样的模型:

class speaker(models.Model):
    name = models.CharField(max_length=255)
    email = models.CharField(max_length=255, primary_key=True)
    ...

和一个talk部分看起来像这样的类:

class talk(models.Model):
    title = models.CharField(max_length = 255) 
    ...
    speakers = models.ManyToManyField('speaker') 
    ...

我的测试设置如下所示:

class TalkTest(TestCase):
    def setUp(self):

        speaker.objects.create(
            name = "John Smith",
            email = "john@john.com"
            )

        talk.objects.create(
            title = "Writing unit tests",
            summary = "How to write unit tests",
            speakers = "john@john.com"
            )

    def test_talk_URLs(self):
        testSpeak = speaker.objects.get(name="John Smith")
        testTalk = talk.objects.get(title="Writing unit tests")

        self.assertEqual(testSpeak.email, "john@john.com")

但是我收到以下回溯错误

======================================================================
ERROR: test_talk_URLs (core.tests.TalkTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/rony/Documents/rehab-lightning-talks/core/tests.py", line 43, in setUp
speakers = "1"
File "/home/rony/Documents/rehab-lightning-talks/venv/local/lib/python2.7/site-packages/django/db/models/manager.py", line 149, in create
return self.get_query_set().create(**kwargs)
File "/home/rony/Documents/rehab-lightning-talks/venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 414, in create
obj = self.model(**kwargs)
File "/home/rony/Documents/rehab-lightning-talks/venv/local/lib/python2.7/site-packages/django/db/models/base.py", line 415, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
TypeError: 'speakers' is an invalid keyword argument for this function

----------------------------------------------------------------------

我没有正确引用外键吗?

4

1 回答 1

1

这是关于 ManyToMany 字段的问题,而不是 ForeignKeys。

对于 M2M,您不能将其作为其中的一部分进行create- 您需要在之后设置它(因为 m2m 关系实际上是第三个链接表中的记录,因此您需要原始模型的 PK,您只能得到创建后)。

    john = speaker.objects.create(
        name = "John Smith",
        email = "john@john.com"
    )

    unit = talk.objects.create(
        title = "Writing unit tests",
        summary = "How to write unit tests",
    )

    unit.speakers.add(john)

我还应该注意,这不是一个好的单元测试。模型实例创建和保存的机制通过 Django 自己的测试得到了很好的测试。您的单元测试应该测试您的实际逻辑。

于 2013-10-03T14:45:29.767 回答