Answer the question
In order to leave comments, you need to log in
How to put a mock on a class object or on a class in such a way that it doesn't do anything?
For example, I have this logic on the test side in 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', '[email protected]', '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)
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')),
]
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>')
Answer the question
In order to leave comments, you need to log in
with patch.object('app.views.RabbitMq', 'run_rabbitmq'):
# bla bla bla
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question