2

I have just recently started working with Django as a part of my job. I am completely new to it, and I was working on a practice project while learning django.

I ask user to enter a phrase or a word in a search bar, and I return 50 results from twitter that have those words in the status message. The code works fine, and I have done some unit testing on it. Now I wanted to test the twitter API(Twython) that I am using, and I figured out I can use Mock or patch for doing it, but I am not able to understand how to go about it. I have read a couple of Documentations on Mocking but couldn't understand it very well.

Here is the snippet of my code

def search(request):

searches = []
query = ""
if request.method == "POST":
    twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    query = request.POST.get('q', '')
    search_results = twitter.search(q=query, count=50)

    for tweet in search_results['statuses']:
        tweets = "Date : %s,\n Tweet : %s" % (tweet['created_at'], tweet['text'])
        searches.append(tweets)

return render(request, "search.html", {
    "results": searches,
    "query1": query
})

Can someone please suggest how I can test this line using mock:

search_results = twitter.search(q=query, count=50)
Joshua Dwire
  • 5,415
  • 5
  • 29
  • 50
Arpit
  • 21
  • 1

1 Answers1

2

It sounds like you're asking "How do I patch out Twython to have twitter.search(...) return a list I specify and/or check what it's been called with"?

If that's the case, you could patch out the Twython class in your test with a mock, and then do your assertions on that. Something like:

with patch("yourapp.views.view_module.Twython") as twython_mock:
    twython_mock.return_value.search.return_value = {} # What you want to set the search call to return
    # Call your view function

twython_mock.assert_called_with(...) # If you want to check what was called in line 4
twython_mock.return_value.search.assert_called_with(...) # If you want to check what q and count are
Dan
  • 1,314
  • 1
  • 9
  • 18