我有一个继承自APITestCase的测试类。此测试类有一个测试用例,它尝试模拟一个被调用的函数,以便在被测试的视图中的另一个对象引发异常。但是,我的异常永远不会被模拟引发。如果我不从APITestCase继承,测试用例基本上按预期工作。
APITestCase是否隐藏或阻止异常传播?
这是我的观点文件:
class Foo(object):
def bar(self):
pass
class Foo2(object):
def bar2(self, f):
f = Foo()
f.bar()
class JobListRest(generics.ListAPIView, generics.CreateAPIView):
queryset = Job.objects.all()
serializer_class = JobSerializer
"""
List all jobs, or create a new job.
"""
@csrf_exempt
def get(self, request, format=None):
jobs = Job.objects.all()
serializer = JobSerializer(jobs, many=True)
return Response(serializer.data)
@csrf_exempt
def post(self, request, format=None):
foo = Foo()
foo.bar()
serializer = JobSerializer(data=request.data)
if serializer.is_valid():
job = serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
异常 NOT 被抬起
class JobPostTest(APITestCase):
def setUp(self):
self.valid_job = """{
'name': 'foo',
'tasks':
[
{
'name':'test_task'
}
]
}"""
@patch('app.views.Foo')
def test_create_job_fails(self, mock):
error = ValidationError
mock.bar.side_effect = error
with self.assertRaises(error):
self.client.post('/api/jobs/', self.valid_job, format='json')
异常 会被提升
class FooTest(TestCase):
@patch('app.views.Foo')
def test_bar(self, mock):
mock.bar.side_effect=ValidationError
foo2 = Foo2()
self.assertRaises(ValidationError, foo2.bar2(1))