我正在尝试编写一些单元测试,我正在为此创建一些虚拟对象。我有一个模型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
----------------------------------------------------------------------
我没有正确引用外键吗?
答案 0 :(得分: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自己的测试很好地测试了模型实例创建和保存的机制。您的单元测试应该测试您的实际逻辑。