Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add iterator support for AbstractJob #5136

Merged
merged 1 commit into from
Mar 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cirq-google/cirq_google/engine/abstract_job.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ def calibration_results(self) -> Sequence['calibration_result.CalibrationResult'
"""

def __iter__(self) -> Iterator[cirq.Result]:
return iter(self.results())
yield from self.results()

# pylint: disable=function-redefined
@overload
Expand Down
34 changes: 30 additions & 4 deletions cirq-google/cirq_google/engine/abstract_job_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Dict, List, TYPE_CHECKING
import pytest
import numpy as np
import cirq
from cirq_google.engine.abstract_job import AbstractJob

if TYPE_CHECKING:
Expand Down Expand Up @@ -83,17 +86,40 @@ def batched_results(self):
pass

def results(self):
return list(range(5))
return list(
cirq.ResultDict(params={}, measurements={'a': np.asarray([t])}) for t in range(5)
)

def calibration_results(self):
pass


def test_instantiation_and_iteration():
job = MockJob()

# Test length
assert len(job) == 5
assert job[3] == 3

# Test direct indexing
assert job[3].measurements['a'][0] == 3

# Test iterating through for loop
count = 0
for num in job:
assert num == count
for result in job:
assert result.measurements['a'][0] == count
count += 1

# Test iterator using iterator
iterator = iter(job)
result = next(iterator)
assert result.measurements['a'][0] == 0
result = next(iterator)
assert result.measurements['a'][0] == 1
result = next(iterator)
assert result.measurements['a'][0] == 2
result = next(iterator)
assert result.measurements['a'][0] == 3
result = next(iterator)
assert result.measurements['a'][0] == 4
with pytest.raises(StopIteration):
next(iterator)