中间件日志记录限制Django 1.11

时间:2017-10-06 08:01:28

标签: python django django-rest-framework integration-testing

背景
我有集成测试,工作正常,但后来我失败了 添加了自定义的middleware

def test_mobile_update_customer(self):
    user = User.objects.create(username='warhead')
    self.client.force_authenticate(user=user)
    mommy.make(Customer, family_name='IBM', created_user=self.soken_staff, updated_user=self.soken_staff)
    data = {
        "family_name": "C0D1UM"
    }
    customer = Customer.objects.first()
    res = self.client.patch(reverse('api:customer-detail', kwargs={'pk': customer.id}), data=data)
    self.assertEqual(200, res.status_code)
    customer.refresh_from_db()
    self.assertEqual('C0D1UM', customer.family_name)
    self.assertEqual('spearhead', customer.created_user.username)
    self.assertEqual('warhead', customer.updated_user.username)

问题:
中间件用Exception

打破它
  File "/Users/el/Code/norak-cutter/soken/soken-web/soken_web/middleware.py", line 47, in process_request
    data['PATCH'] = json.loads(request.body)
  File "/Users/el/.pyenv/versions/soken/lib/python3.6/site-packages/django/http/request.py", line 264, in body
    raise RawPostDataException("You cannot access body after reading from request's data stream")
django.http.request.RawPostDataException: You cannot access body after reading from request's data stream

问题是在data api完成工作之前已经读过RESTful。 然后该程序引发了异常。

def process_request(self, request):

    if request.path.startswith('/api/'):
        data = collections.OrderedDict()
        data["user"] = request.user.username
        data["path"] = request.path
        data["method"] = request.method
        data["content-type"] = request.content_type
        if request.method == 'GET':
            data['GET'] = request.GET
        elif request.method == 'POST':
            data['POST'] = request.POST

        # https://stackoverflow.com/questions/4994789/django-where-are-the-params-stored-on-a-put-delete-request
        # elif request.method == 'PUT':
        #     data['PUT'] = json.loads(request.body)

        # test_mobile_update_customer
        # raise RawPostDataException("You cannot access body after reading from request's data stream")
        # django.http.request.RawPostDataException: You cannot access body after reading from request's data stream
        # elif request.method == 'PATCH':
        #     data['PATCH'] = json.loads(request.body)
        elif request.method == 'DELETE':
            pass
        self.__uuid = str(uuid.uuid4())
        request_logger.info(f'{self.__uuid} {json.dumps(data)}')

UPDATE2
尝试:
我更改了client构造函数,请参阅https://github.com/encode/django-rest-framework/issues/2774

def test_mobile_update_customer(self):
    user = User.objects.create(username='warhead')
    # self.client.force_authenticate(user=user)
    from django.test import Client
    client = Client()
    client.force_login(user)
    mommy.make(Customer, family_name='IBM', created_user=self.soken_staff, updated_user=self.soken_staff)
    data = {
        "family_name": "C0D1UM"
    }
    customer = Customer.objects.first()
    res = client.patch(reverse('api:customer-detail', kwargs={'pk': customer.id}), data=data, content_type='application/json')
    self.assertEqual(200, res.status_code)
    customer.refresh_from_db()
    self.assertEqual('C0D1UM', customer.family_name)
    self.assertEqual('spearhead', customer.created_user.username)
    self.assertEqual('warhead', customer.updated_user.username)

它不起作用。 Client误解了有效载荷

>>> res.content
b'{"detail":"JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)"}'

解决方法:
我不知道这对所有情况都是正确的,但我解决了这个问题 test.py https://gist.github.com/elcolie/88eb7c90cfca1c369a020ac232c7fbcc
middleware.py https://gist.github.com/elcolie/5d9b1a2f890a0efcb46fdb95c0e90908
result.py https://gist.github.com/elcolie/298e595b404c1a5839ed8dd584d2f07f

问题:
如何在我的中间件不会破坏测试用例的同时对PATCH进行集成测试?

现在我必须选择其中一个。

0 个答案:

没有答案