【问题标题】:Django test DoesNotExist: Contact matching query does not existDjango测试DoesNotExist:联系人匹配查询不存在
【发布时间】:2013-07-12 10:05:06
【问题描述】:

我正在尝试运行我的第一个测试。测试失败:

DoesNotExist:联系人匹配查询不存在。查找参数为 {'mobile': '07000000000'}

我似乎在设置功能中创建了用户联系人,为什么它不可用?

谢谢

test.py

class BatchTestCase(TestCase):

    def setup(self):
         user = User.objects.get(username='glynjackson')
         contact = Contact.objects.get(mobile="07000000000", contact_owner=user, group=None)


    def test_get_contact(self):
        contact = Contact.objects.get(mobile='07000000000')
        self.assertEqual(contact.full_name(), 'Got Contact')

完全错误

ERROR: test_get_contact (sms.tests.test_sms_simulation.BatchTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/user/Documents/workspace/example/sms/tests/test_sms_simulation.py", line 18, in test_get_contact
    contact = Contact.objects.get(mobile='07000000000')
  File "/Users/user/Documents/workspace/example/django-env/lib/python2.7/site-packages/django/db/models/manager.py", line 143, in get
    return self.get_query_set().get(*args, **kwargs)
  File "/Users/user/Documents/workspace/example/django-env/lib/python2.7/site-packages/django/db/models/query.py", line 389, in get
    (self.model._meta.object_name, kwargs))
DoesNotExist: Contact matching query does not exist. Lookup parameters were {'mobile': '07000000000'}

【问题讨论】:

    标签: python django


    【解决方案1】:

    您应该使用setUp 方法,而不是setup。在运行每个测试之前调用此方法。

    class BatchTestCase(TestCase):
    
        def setUp(self):
             # create test objects here
    
        # ...
    

    【讨论】:

      【解决方案2】:

      get 不会在数据库中创建记录,而是尝试实际获取记录。它在数据库中找不到这样的记录并引发错误 DoesNotExist。

      你应该使用类似的东西:

      contact = Contact(mobile="07000000000", contact_owner=user, group=None)
      contact.save()
      

      【讨论】:

        猜你喜欢
        • 2014-09-22
        • 2021-07-11
        • 2022-01-10
        • 1970-01-01
        • 2013-07-27
        • 1970-01-01
        • 2018-02-23
        • 1970-01-01
        • 2021-02-08
        相关资源
        最近更新 更多