我已经编写了一个TestCase来检查需要教师对象的视图。
class ShowTeacherViewTest(TestCase):
@classmethod
def setUpTestData(cls):
gender = Gender.objects.create(gender='Male')
gender_id = gender.id
Teacher.objects.create(
gender_id=gender_id,
first_name='Maria',
last_name='Santana',)
def test_view_uses_correct_template(self):
teacher = Teacher.objects.first().id
response = self.client.get(reverse('get_student'), {'teacher': teacher})
self.assertEqual(response.status_code, 200)
当我运行“ manage.py测试应用程序”时,一切正常。
如果我正在运行“ manage.py测试”,则该错误消失:
self.model._meta.object_name
students.gender.Gender.DoesNotExist: Gender matching query does not exist.
由于一些外键,我还在其他模型测试中使用了这些教师对象。那么,在每次测试之前重置test_db可能还是必要?
这是完整的追溯:
Traceback (most recent call last):
File "/Users/user/django/venv/teaching/tests/test_get_students.py", line 157, in test_view_uses_correct_template
response = self.client.get(reverse('get_student'), {'student': student})
File "/Users/user/anaconda3/envs/venv/lib/python3.7/site-packages/django/test/client.py", line 527, in get
response = super().get(path, data=data, secure=secure, **extra)
File "/Users/user/anaconda3/envs/venv/lib/python3.7/site-packages/django/test/client.py", line 339, in get
**extra,
File "/Users/user/anaconda3/envs/venv/lib/python3.7/site-packages/django/test/client.py", line 414, in generic
return self.request(**r)
File "/Users/user/anaconda3/envs/venv/lib/python3.7/site-packages/django/test/client.py", line 495, in request
raise exc_value
File "/Users/user/anaconda3/envs/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/user/anaconda3/envs/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/user/anaconda3/envs/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/user/django/venv/teaching/get_students.py", line 55, in get_student
image = get_alibi_pic(image, gender, student)
File "/Users/user/django/venv/teaching/get_students.py", line 27, in get_alibi_pic
gender_male = Gender.objects.get(pk=1)
File "/Users/user/anaconda3/envs/venv/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/user/anaconda3/envs/venv/lib/python3.7/site-packages/django/db/models/query.py", line 399, in get
self.model._meta.object_name
students.gender.Gender.DoesNotExist: Gender matching query does not exist.
答案 0 :(得分:0)
回溯显示此行失败:
gender_male = Gender.objects.get(pk=1)
通常不应在代码或测试中使用硬性主键。当您使用manage.py test
运行所有测试时,正在使用不同的主键创建对象,因此get(pk=1)
失败。
如果您确实需要在代码中对pk进行硬编码,则需要在测试类中使用正确的pk创建对象:
gender = Gender.objects.create(pk=1, gender='Male')
但是,更好的解决办法是更改代码,以使其不使用硬编码的pk。
gender_male = Gender.objects.get(gender='Male')