例如,我的Django测试中有以下逻辑:
from rest_framework.test import APITestCase, APIClient
import unittest
from mock import patch
from rest_framework.reverse import reverse
from rest_framework import status
from django.test import TestCase
from django.contrib.auth.models import User
class APITest(unittest.TestCase):
def setUp(self):
self.client = APIClient(enforce_csrf_checks=False)
self.user = User.objects.create_user('test_user', 'test_user@test.com', 'password')
self.user.save()
def test_auth_get(self):
with patch('app.views.RabbitMq.run_rabbitmq'):
self.client.login(username='test_user', password='password')
self.client.force_authenticate(user=self.user)
response = self.client.get(reverse('user-list'), format='json')
print response
self.assertEqual(response.status_code, 200)
根据这个urls.py:
from django.conf.urls import patterns, include, url
from rest_framework import routers
from views import UserViewSet, GroupViewSet
router = routers.SimpleRouter()
router.register(r'users', UserViewSet)
router.register(r'groups', GroupViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
我想在views.py中模拟run_rabbitmq:
from django.contrib.auth.models import User, Group
import pika
from django.http import HttpResponse
from rest_framework import viewsets
from serializers import UserSerializer, GroupSerializer
class RabbitMq:
def __init__(self):
pass
def run_rabbitmq(self):
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='test')
channel.basic_publish(exchange='', routing_key='test', body='Hello World!')
connection.close()
def rabbitmq_wrap(OriginalClass):
orig_init = OriginalClass.__init__
def __init__(self, *args, **kws):
rabbit = RabbitMq()
rabbit.run_rabbitmq()
orig_init(self, *args, **kws)
OriginalClass.__init__ = __init__
return OriginalClass
@rabbitmq_wrap
class Record:
def __init__(self):
pass # here is the logic of writing to database
class UserViewSet(viewsets.ModelViewSet, Rabbitmq):
record = Record()
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
queryset = Group.objects.all()
serializer_class = GroupSerializer
def my_view(request):
return HttpResponse('<h1>Hello!</h1>')
以某种方式它什么都不做。既不返回也不处理某些东西,只是没有(例如在测试时发送短信等),就像它只有一个“通行证”一样。
让this如何在装饰器内部模拟实例?