3

I am trying to write unit test for a class which is having a POST method for uploading documents to web based django application. Here is my view class for which I want to write unit test:

class SOP(APIView):
authentication_classes = (authentication.TokenAuthentication,)
def post(self,request):
    returnDict={}
    returnDict['msg']='File not uploaded'
    #if form.is_valid():        
    newdoc = Document(sopFile = request.FILES['sopFile'])
    newdoc.save()

    returnDict['msg']='File uploaded'
    returnDict['fileName']=newdoc.sopFile.name
    # Redirect to the document list after POST
    return Response(returnDict)

As my django application is using forms.py for uploading a file so I am putting that code also along with this:

from django import forms
class DocumentForm(forms.Form):
docfile = forms.FileField(
    label='Select a file',
    help_text='max. 42 megabytes'
)

I have tried to write test case using RequestFactory() and TestCase() but I am not able to figure how to write unit test for this type of class/views...

0

2 Answers 2

4

You can use the test client from Django. It's very easy to use.

Example from Django docs:

>>> c = Client()
>>> with open('wishlist.doc') as fp:
...     c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp})
Sign up to request clarification or add additional context in comments.

1 Comment

then I think I am doing something else wrong.. my terminal shows me that "Test label 'lib.SOPTestCase.testWithRequestFactory' does not refer to a test"... BTW thank you so much
0

You could try mocking what you need with something like this.

1 Comment

I'm confused by this, could you give an example of how you'd mock this out? Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.