Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

You cannot access body after reading from request's data stream after starting py.test

Good afternoon.

I'm testing api based on django-rest-framework using pytest. I have the following method that creates a new object (method taken from here):

class JSONResponse(HttpResponse):
    """
    An HttpResponse that renders its content into JSON.
    """

    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)


@csrf_exempt
@api_view(('POST',))
@permission_classes((IsAuthenticated, ))
def create_transaction(request):
    """
    The method takes the data in JSON-format.
    If the data is correct Transaction object will created, otherwise it returns an error also in JSON-format.
    """

    stream = StringIO('[' + request.raw_post_data + ']')
    data = JSONParser().parse(stream)
    serializer = NewTransactionSerializer(data=data, many=True)
    if serializer.is_valid():
        serializer.save()
        return JSONResponse(serializer.data, status=201)
    else:
        return JSONResponse(serializer.errors, status=400)

I wrote to it next test:

@pytest.mark.django_db
def test_create_method(client):
    correct_data = '''{ "var1": "111",
                        "var2": "222",
                        "var3": 2 }'''
    client.login(username='[email protected]', password='test')
    data = json.loads(correct_data)
    response  = client.post('/rest2/create_transaction/', data, format='json')
    content = json.loads(response.content)
    assert content[0]['var1'] == '111'
    assert content[0]['var2'] == '222'
    assert content[0]['var3'] == 2
    assert response['Content-Type'] == 'application/json'
    assert response.status_code == 201

When starting pytest displays the following: Exception: You cannot access body after reading from request's data stream. Its broke when i post data to url. When I run the same code in the shell, the code runs without problems. I am new to testing, may miss something, help please.

like image 837
aphex Avatar asked Jan 27 '14 12:01

aphex


1 Answers

If you're using django-rest-framework, then you can just use request.data instead of trying to parse json from the request yourself

http://www.django-rest-framework.org/api-guide/requests/

 stream = StringIO('[' + request.raw_post_data + ']')
 data = JSONParser().parse(stream)

this can be replaced with

data = request.data
like image 73
Anatoly Bubenkov Avatar answered Oct 13 '22 09:10

Anatoly Bubenkov