How can I write tests that populate raw_post_data and request.FILES ['myfile']

I have something like this:

def upload_something(request): data = {} if request.FILES: raw_file = request.FILES['myfile'].read() else: raw_file = request.raw_post_data 

I can't seem to write unit-test that fills raw_post_data , how would I do that? I just want to send an image file. I am trying to create a test case when I read raw_post_data and these are errors with:

You cannot access raw_post_data after reading from the request data stream

+4
source share
4 answers

You can use the mockery. Some examples are available here and in the docs here.


Update

Kit, I think it really depends on your test case. But in general, you should not directly use raw_post_data. Instead, it should be fixed, as in the example below:

 from mock import Mock, MagicMock class SomeTestCase(TestCase): def testRawPostData(self): ... request = Mock(spec=request) request.raw_post_data = 'myrawdata' print request.raw_post_data # prints 'myrawdata' file_mock = MagicMock(spec=file) file_mock.read.return_value = 'myfiledata' request.FILES = {'myfile': file_mock} print request.FILES['myfile'].read() # prints 'myfiledata' 
+1
source

The error message that the interpreter gives is correct. After accessing the POST data through if request.FILES you will no longer be able to access raw_post_data. If in your actual code (and not in tests) you get to this line, it will be an error with the same message. Basically, you need two separate forms-based POSTS views and direct POST files.

+1
source

I guess you guessed it, but since the answers are almost out of date with the deprecated raw_post_data, I thought I would post.

 def test_xml_payload(self): data = '<?xml version="1.0" encoding="UTF-8"?><blah></blah>' response = self.client.post(reverse('my_url'), data=data, content_type='application/xml') def my_view(request): xml = request.body 
+1
source

I took this ad here

 c = Client() f = open('wishlist.doc') c.post('/customers/wishes/', {'name': 'fred', 'attachment': f}) f.close() 

The client is a special class for checking your views. This is an example of sending files to your view. This is part of the Django testing framework.

0
source

Source: https://habr.com/ru/post/1387442/


All Articles