0
0
PyTesttesting~10 mins

unittest.mock.patch 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 patch the 'requests.get' method in the test.

PyTest
from unittest.mock import patch

@patch('[1]')
def test_fetch_data(mock_get):
    mock_get.return_value.status_code = 200
    assert mock_get.return_value.status_code == 200
Drag options to blanks, or click blank then click option'
Arequests.get
Brequests.post
Cos.path.exists
Djson.load
Attempts:
3 left
💡 Hint
Common Mistakes
Patching the wrong method like 'requests.post'.
Forgetting to patch the method as a string.
2fill in blank
medium

Complete the code to patch 'open' function in the 'builtins' module for the test.

PyTest
from unittest.mock import patch

@patch('[1]')
def test_file_read(mock_open):
    mock_open.return_value.read.return_value = 'data'
    with open('file.txt') as f:
        content = f.read()
    assert content == 'data'
Drag options to blanks, or click blank then click option'
Aio.open
Bos.open
Cbuiltins.open
Dopen.file
Attempts:
3 left
💡 Hint
Common Mistakes
Patching 'os.open' instead of 'builtins.open'.
Using incorrect module names.
3fill in blank
hard

Fix the error in patching the 'datetime.datetime.now' method correctly.

PyTest
from unittest.mock import patch
import datetime

@patch('[1]')
def test_time(mock_now):
    mock_now.return_value = datetime.datetime(2020, 1, 1)
    assert datetime.datetime.now() == datetime.datetime(2020, 1, 1)
Drag options to blanks, or click blank then click option'
Adatetime.datetime
Bdatetime.datetime.now
Cdatetime.now
Ddatetime.now.now
Attempts:
3 left
💡 Hint
Common Mistakes
Patching 'datetime.now' which does not exist.
Patching the class instead of the method.
4fill in blank
hard

Fill both blanks to patch 'module.Class.method' and set the mock return value.

PyTest
from unittest.mock import patch

@patch('[1]')
def test_method(mock_method):
    mock_method.return_value = [2]
    result = mock_method()
    assert result == 42
Drag options to blanks, or click blank then click option'
Amodule.Class.method
B42
C100
Dmodule.method
Attempts:
3 left
💡 Hint
Common Mistakes
Patching the wrong method path.
Setting the wrong return value.
5fill in blank
hard

Fill all three blanks to patch 'package.module.func', set return value, and assert call count.

PyTest
from unittest.mock import patch

@patch('[1]')
def test_func(mock_func):
    mock_func.return_value = [2]
    mock_func()
    mock_func()
    assert mock_func.call_count == [3]
Drag options to blanks, or click blank then click option'
Apackage.module.func
BTrue
C2
DFalse
Attempts:
3 left
💡 Hint
Common Mistakes
Incorrect patch path.
Wrong return value type.
Wrong call count assertion.