-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathconftest.py
More file actions
372 lines (305 loc) · 10.8 KB
/
Copy pathconftest.py
File metadata and controls
372 lines (305 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# Copyright 2020 IonQ, Inc. (www.ionq.com)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# pylint: disable=redefined-outer-name
"""global pytest fixtures"""
import pytest
from requests_mock import Mocker, adapter as rm_adapter
from qiskit_ionq import ionq_backend, ionq_job, ionq_provider
from qiskit_ionq.helpers import compress_to_metadata_string
def _def_results_template(job_id):
"""A template for the results field in a job response."""
return {
"histogram": {
# v0.4 returns a relative path - the client prefixes it with the base URL
# https://docs.ionq.com/api-reference/v0.4/jobs/get-job
"url": f"/v0.4/jobs/{job_id}/results/histogram"
},
"probabilities": {"url": f"/v0.4/jobs/{job_id}/results/probabilities"},
"shots": {"url": f"/v0.4/jobs/{job_id}/results/shots"},
}
class MockBackend(ionq_backend.IonQBackend):
"""A mock backend for testing super-class behavior in isolation."""
def __init__(self, provider, *, name: str = "ionq_mock_backend"):
"""
Build a minimal mock backend that satisfies BackendV2.
"""
super().__init__(
provider=provider,
name=name,
description="IonQ Mock Backend",
gateset="qis",
num_qubits=11,
simulator=True,
max_shots=10_000,
)
def dummy_job_response(
job_id, target="mock_backend", status="completed", job_settings=None, children=None
):
"""A dummy response payload for `job_id`.
Args:
job_id (str): An arbitrary job id.
target (str): Backend target string.
status (str): A provided status string.
job_settings (dict): Settings provided to the API.
children (list): A list of child job IDs.
Returns:
dict: A json response dict.
"""
qiskit_header = compress_to_metadata_string(
{
"qubit_labels": [["q", 0], ["q", 1]],
"n_qubits": 2,
"qreg_sizes": [["q", 2]],
"clbit_labels": [["c", 0], ["c", 1]],
"memory_slots": 2,
"creg_sizes": [["c", 2]],
"name": job_id,
"global_phase": 0,
}
)
response = {
"status": status,
"predicted_execution_time": 4,
"metadata": {
"qobj_id": "test_qobj_id",
"shots": "1234",
"sampler_seed": "42",
"output_length": "2",
"qiskit_header": qiskit_header,
},
"execution_time": 8,
"qubits": 2,
"type": "circuit",
"request": 1600000000,
"start": 1600000001,
"response": 1600000002,
"backend": target,
"results": _def_results_template(job_id),
"id": job_id,
"settings": (job_settings or {}),
"name": "test_name",
}
if children is not None:
response["children"] = children
return response
def dummy_mapped_job_response(
job_id, target="mock_backend", status="completed", job_settings=None, children=None
):
"""A dummy mapped response payload for `job_id`.
Args:
job_id (str): An arbitrary job id.
target (str): Backend target string.
status (str): A provided status string.
job_settings (dict): Settings provided to the API.
children (list): A list of child job IDs.
Returns:
dict: A json response dict.
"""
qiskit_header = compress_to_metadata_string(
{
"qubit_labels": [["q", 0], ["q", 1]],
"n_qubits": 2,
"qreg_sizes": [["q", 2]],
"clbit_labels": [["c", 0], ["c", 1]],
"memory_slots": 2,
"creg_sizes": [["c", 2]],
"name": job_id,
"global_phase": 0,
"meas_mapped": [1, 0],
}
)
response = {
"status": status,
"predicted_execution_time": 4,
"metadata": {
"qobj_id": "test_qobj_id",
"shots": "1234",
"sampler_seed": "42",
"output_length": "2",
"qiskit_header": qiskit_header,
},
"execution_time": 8,
"qubits": 2,
"type": "circuit",
"request": 1600000000,
"start": 1600000001,
"response": 1600000002,
"backend": target,
"results": _def_results_template(job_id),
"id": job_id,
"settings": (job_settings or {}),
"name": "test_name",
}
if children is not None:
response["children"] = children
return response
def dummy_multi_parent_response(job_id, child_job_ids, status="completed"):
"""Multicircuit parent response with ``metadata: null`` and empty ``stats``,
matching the wire shape returned for jobs submitted outside qiskit.
Args:
job_id (str): The parent job id.
child_job_ids (list[str]): Child job ids.
status (str): Job status string.
Returns:
dict: A json response dict.
"""
url = f"/v0.4/jobs/{job_id}/results/probabilities/aggregated"
return {
"id": job_id,
"type": "ionq.multi-circuit.v1",
"status": status,
"name": f"{len(child_job_ids)} circuits",
"metadata": None,
"backend": "simulator",
"child_job_ids": child_job_ids,
"settings": {},
"stats": {},
"results": {"probabilities": {"url": url}},
"execution_duration_ms": 0,
}
def dummy_failed_job(job_id):
"""A dummy response payload for a failed job.
Args:
job_id (str): An arbitrary job id.
Returns:
dict: A json response dict.
"""
qiskit_header = compress_to_metadata_string(
{
"qubit_labels": [["q", 0], ["q", 1]],
"n_qubits": 2,
"qreg_sizes": [["q", 2]],
"clbit_labels": [["c", 0], ["c", 1]],
"memory_slots": 2,
"creg_sizes": [["c", 2]],
"name": job_id,
"global_phase": 0,
}
)
return {
"failure": {"error": "example error", "code": "ExampleError"},
"status": "failed",
"metadata": {"shots": "1", "qiskit_header": qiskit_header},
"type": "circuit",
"request": 1600000000,
"response": 1600000002,
"backend": "qpu",
"results": _def_results_template(job_id),
"id": job_id,
}
def _default_requests_mock(**kwargs):
"""Create a default `requests_mock.Mocker` for use in tests.
Args:
kwargs (dict): Any additional kwargs to create the mocker with.
Returns:
:class:`request_mock.Mocker`: A requests mocker.
"""
mocker_kwargs = {"real_http": False, **kwargs}
mocker = Mocker(**mocker_kwargs)
return mocker
def pytest_sessionstart(session):
"""pytest hook for global test session start
Args:
session (:class:`pytest.Session`): A pytest session object.
"""
session.global_requests_mock = _default_requests_mock()
session.global_requests_mock.start()
session.global_requests_mock.register_uri(
rm_adapter.ANY,
rm_adapter.ANY,
status_code=599,
text="UNHANDLED REQUEST. PLEASE MOCK WITH requests_mock.",
)
def pytest_sessionfinish(session):
"""pytest hook for global test session end
Args:
session (:class:`pytest.Session`): A pytest session object.
"""
session.global_requests_mock.stop()
del session.global_requests_mock
@pytest.fixture()
def provider():
"""Fixture for injecting a test provider.
Returns:
IonQProvider: A provider suitable for testing.
"""
return ionq_provider.IonQProvider("token")
@pytest.fixture()
def mock_backend(provider):
"""A fixture instance of the :class:`MockBackend`.
Args:
provider (IonQProvider): An IonQProvider fixture.
Returns:
MockBackenbd: An instance of :class:`MockBackend`
"""
return MockBackend(provider)
@pytest.fixture()
def qpu_backend(provider):
"""Get the QPU backend from a provider.
Args:
provider (IonQProvider): Injected provider from :meth:`provider`.
Returns:
IonQQPUBackend: An instance of an IonQQPUBackend.
"""
return provider.get_backend("ionq_qpu")
@pytest.fixture()
def simulator_backend(provider):
"""Get the QPU backend from a provider.
Args:
provider (IonQProvider): Injected provider from :meth:`provider`.
Returns:
IonQQPUBackend: An instance of an IonQQPUBackend.
"""
return provider.get_backend("ionq_simulator")
@pytest.fixture()
def formatted_result(provider):
"""Fixture for auto-injecting a formatted IonQJob result object into a
a sub-class of ``unittest.TestCase``.
Args:
provider (IonQProvider): Injected provider from :meth:`provider`.
Returns:
Result: A qiskit result from making a fake API call with StubbedClient.
"""
# Dummy job ID for formatted results fixture.
job_id = "test_id"
settings = {"lorem": {"ipsum": "dolor"}}
# Create a backend and client to use for accessing the job.
backend = provider.get_backend("ionq_qpu.aria-1")
backend.set_options(job_settings=settings)
client = backend._create_client()
# Create the request path for accessing the dummy job:
path = client.make_path("jobs", job_id)
results_path = client.make_path("jobs", job_id, "results", "probabilities")
# mock a job response
with _default_requests_mock() as requests_mock:
# Mock the response with our dummy job response.
requests_mock.get(
path, json=dummy_job_response(job_id, "qpu.aria-1", "completed", settings)
)
requests_mock.get(results_path, json={"0": 0.5, "2": 0.499999})
# Create the job (this calls self.status(), which will fetch the job).
job = ionq_job.IonQJob(backend, job_id, client)
# Yield so that the mock context manager properly unwinds.
yield job.result()