Bird
0
0

What is wrong with this Flask test code that tries to mock requests.post?

medium📝 Debug Q14 of 15
Flask - Testing Flask Applications
What is wrong with this Flask test code that tries to mock requests.post?
from unittest.mock import patch
import requests

def send_data():
    response = requests.post('http://example.com', data={'key': 'value'})
    return response.ok

with patch('requests.post') as mock_post:
    mock_post.ok = True
    print(send_data())
Amock_post.ok should be set on return_value, not mock_post
Bpatch target should be 'requests.get' not 'requests.post'
Csend_data should use requests.get instead of post
Dmock_post.ok is correct and code works fine
Step-by-Step Solution
Solution:
  1. Step 1: Identify mock object usage

    mock_post is the mock for requests.post function, its return_value simulates the response object.
  2. Step 2: Correct attribute assignment

    Setting mock_post.ok sets attribute on the function mock, not the response. It should be mock_post.return_value.ok = True.
  3. Final Answer:

    mock_post.ok should be set on return_value, not mock_post -> Option A
  4. Quick Check:

    Mock response attributes go on return_value [OK]
Quick Trick: Set mock response attributes on return_value [OK]
Common Mistakes:
MISTAKES
  • Setting attributes on mock function instead of return_value
  • Confusing post with get method
  • Assuming code works without fixing mock

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Flask Quizzes