0
0
PyTesttesting~10 mins

Testing with external services in PyTest - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the requests library for testing external services.

PyTest
import [1]
Drag options to blanks, or click blank then click option'
Arequests
Bpytest
Cunittest
Djson
Attempts:
3 left
💡 Hint
Common Mistakes
Importing pytest instead of requests
Importing unittest which is for unit tests, not HTTP calls
2fill in blank
medium

Complete the code to mock the external HTTP GET request using pytest and requests.

PyTest
def test_api_call(mocker):
    mock_get = mocker.patch('requests.[1]')
    mock_get.return_value.status_code = 200
    response = requests.get('http://example.com')
    assert response.status_code == 200
Drag options to blanks, or click blank then click option'
Aget
Bdelete
Cput
Dpost
Attempts:
3 left
💡 Hint
Common Mistakes
Patching the wrong HTTP method like post or put
Not patching the requests method at all
3fill in blank
hard

Fix the error in the test by completing the assertion to check the mocked JSON response.

PyTest
def test_api_json_response(mocker):
    mock_get = mocker.patch('requests.get')
    mock_get.return_value.status_code = 200
    mock_get.return_value.json = lambda: {'key': 'value'}
    response = requests.get('http://example.com')
    assert response.json() [1] {'key': 'value'}
Drag options to blanks, or click blank then click option'
Ain
B!=
Cis
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'is' which checks identity, not equality
Using '!=' which checks for inequality
4fill in blank
hard

Fill both blanks to create a pytest fixture that mocks requests.post and returns a 201 status code.

PyTest
@pytest.fixture
def mock_post(mocker):
    mock = mocker.patch('requests.[1]')
    mock.return_value.status_code = [2]
    return mock
Drag options to blanks, or click blank then click option'
Apost
Bget
Cput
D201
Attempts:
3 left
💡 Hint
Common Mistakes
Patching the wrong HTTP method
Using incorrect status code like 200 instead of 201
5fill in blank
hard

Fill all three blanks to write a test that uses the mock_post fixture and asserts the response status code is 201.

PyTest
def test_create_resource(mock_post):
    response = requests.[1]('http://example.com/resource')
    assert response.[2] == [3]
Drag options to blanks, or click blank then click option'
Apost
Bstatus_code
C201
Dget
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'get' instead of 'post' for creation
Checking wrong attribute like 'json' instead of 'status_code'
Expecting wrong status code like 200