Replace plain Mock() calls with autospec=True or Mock(spec)
Affects | Status | Importance | Assigned to | Milestone | |
---|---|---|---|---|---|
Cinder |
In Progress
|
Low
|
Khadija Kamran |
Bug Description
Cinder has some tests with assertion typo's or plain calls to Mock() or MagicMock() resulting in those tests not testing code correctly. One example of that is: https:/
The refactored code would replace plain Mock() calls with Mock(spec) calls
or you can either pass autospec=True to patch() / patch.object() or use the create_autospec() function to create a mock with a spec. We want stronger mocks by using specs, do the right thing where needed to get this.
Using autospec/spec limits the API of mocks to the API of an original object (the spec). This ensures that any assertion typo's or incorrect calls will be caught by raising a TypeError. This makes it easier to identify and fix any errors in the tests, ensuring that they are testing code correctly.
Mock(spec) example:
diff --git a/cinder/
index 9a7a50ff6.
--- a/cinder/
+++ b/cinder/
@@ -20,6 +20,7 @@ import ddt
from cinder.common import constants
from cinder import exception
+ from cinder import context
from cinder.message import message_field
from cinder.tests.unit import fake_constants as fake
from cinder.tests.unit import fake_volume
@@ -231,7 +232,7 @@ class VolumeManagerTe
- ctxt = mock.Mock()
+ ctxt = mock.Mock(
vol = fake_volume.
The refactored code replaces plain calls to Mock() with Mock(spec) calls, which specify the object class that the mock should be based on (in this case, context.
Documentation unittest.
summary: |
- Replace plain Mock() calls with Mock(spec) + Replace plain Mock() calls with autospec=True or Mock(spec) |
tags: | added: tests |
description: | updated |
Changed in cinder: | |
status: | Confirmed → Triaged |
Changed in cinder: | |
status: | Triaged → In Progress |
Fix proposed to branch: master /review. opendev. org/c/openstack /cinder/ +/873905
Review: https:/