Skip to content

Commit 36be3f4

Browse files
committed
Use mock.patch.dict to mock the google.colab module
1 parent 6c0f01f commit 36be3f4

1 file changed

Lines changed: 4 additions & 13 deletions

File tree

cirq-google/cirq_google/engine/qcs_notebook_test.py

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
import sys
1516
import unittest.mock as mock
1617
import pytest
1718

@@ -97,13 +98,9 @@ def test_get_qcs_objects_for_notebook_no_processors(engine_mock):
9798
_ = get_qcs_objects_for_notebook()
9899

99100

101+
@mock.patch.dict('sys.modules', {'google.colab': mock.Mock()})
100102
@mock.patch('cirq_google.engine.qcs_notebook.get_engine')
101103
def test_get_qcs_objects_for_notebook_auth_succeeds(engine_mock):
102-
# force google.colab to import
103-
auth_mock = mock.Mock()
104-
import sys
105-
106-
sys.modules['google.colab'] = auth_mock
107104
fake_processor = cg.engine.SimulatedLocalProcessor(
108105
processor_id='tester', project_name='mock_project', device=cg.Sycamore
109106
)
@@ -116,16 +113,12 @@ def test_get_qcs_objects_for_notebook_auth_succeeds(engine_mock):
116113
assert result.project_id == 'mock_project'
117114
assert len(result.device.metadata.qubit_set) == 54
118115

119-
del sys.modules['google.colab']
120-
121116

117+
@mock.patch.dict('sys.modules', {'google.colab': mock.Mock()})
122118
@mock.patch('cirq_google.engine.qcs_notebook.get_engine')
123119
def test_get_qcs_objects_for_notebook_auth_fails(engine_mock):
124-
# force google.colab to import
125-
auth_mock = mock.Mock()
126-
import sys
120+
auth_mock = sys.modules['google.colab']
127121

128-
sys.modules['google.colab'] = auth_mock
129122
auth_mock.auth.authenticate_user = mock.Mock(side_effect=Exception('mock auth failure'))
130123
fake_processor = cg.engine.SimulatedLocalProcessor(
131124
processor_id='tester', project_name='mock_project', device=cg.Sycamore
@@ -139,5 +132,3 @@ def test_get_qcs_objects_for_notebook_auth_fails(engine_mock):
139132
assert not result.signed_in
140133
assert result.is_simulator
141134
assert result.project_id == 'fake_project'
142-
143-
del sys.modules['google.colab']

0 commit comments

Comments
 (0)