Bird
0
0

You have a Flask route that calls an external API using requests.get. How can you mock this call in your test to always return a JSON response {"status": "ok"} with status code 200?

hard📝 Conceptual Q8 of 15
Flask - Testing Flask Applications
You have a Flask route that calls an external API using requests.get. How can you mock this call in your test to always return a JSON response {"status": "ok"} with status code 200?
APatch <code>requests.post</code> and set <code>mock_post.return_value.status_code = 200</code>
BPatch <code>requests.get</code> and set <code>mock_get.return_value.text = '{"status": "ok"}'</code> only
CPatch <code>requests.get</code> and set <code>mock_get.return_value.json.return_value = {"status": "ok"}</code> and <code>mock_get.return_value.status_code = 200</code>
DCall the real API and check the response
Step-by-Step Solution
Solution:
  1. Step 1: Patch the correct method

    Patch requests.get since the route uses it.
  2. Step 2: Mock JSON response

    Set mock_get.return_value.json.return_value to the desired JSON dict.
  3. Step 3: Mock status code

    Set mock_get.return_value.status_code = 200 to simulate success.
  4. Final Answer:

    Patch requests.get and set json.return_value and status_code -> Option C
  5. Quick Check:

    Mock both json() and status_code for full response [OK]
Quick Trick: Mock both .json() and .status_code for API responses [OK]
Common Mistakes:
MISTAKES
  • Mocking only text attribute
  • Patching wrong method
  • Not mocking json() method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Flask Quizzes