|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import pytest |
| 16 | +from unittest import mock |
| 17 | +import openfermion.testing.wrapped as wrapped |
| 18 | + |
| 19 | + |
| 20 | +class MockCirqTesting: |
| 21 | + @property |
| 22 | + def retry_once_with_later_random_values(self): |
| 23 | + raise AttributeError("No such attribute") |
| 24 | + |
| 25 | + |
| 26 | +class MockCirq: |
| 27 | + testing = MockCirqTesting() |
| 28 | + |
| 29 | + |
| 30 | +def test_retry_once_fallback_success(): |
| 31 | + with mock.patch('openfermion.testing.wrapped.cirq', MockCirq()): |
| 32 | + |
| 33 | + call_count = 0 |
| 34 | + |
| 35 | + @wrapped.retry_once_with_later_random_values |
| 36 | + def successful_test(): |
| 37 | + nonlocal call_count |
| 38 | + call_count += 1 |
| 39 | + return "Success" |
| 40 | + |
| 41 | + assert successful_test() == "Success" |
| 42 | + assert call_count == 1 |
| 43 | + |
| 44 | + |
| 45 | +def test_retry_once_fallback_flaky(): |
| 46 | + with mock.patch('openfermion.testing.wrapped.cirq', MockCirq()): |
| 47 | + |
| 48 | + call_count = 0 |
| 49 | + |
| 50 | + @wrapped.retry_once_with_later_random_values |
| 51 | + def flaky_test(): |
| 52 | + nonlocal call_count |
| 53 | + call_count += 1 |
| 54 | + if call_count == 1: |
| 55 | + raise AssertionError("Failed first time") |
| 56 | + return "Success" |
| 57 | + |
| 58 | + with pytest.warns( |
| 59 | + UserWarning, match="Retrying in case we got a failing seed from pytest-randomly." |
| 60 | + ): |
| 61 | + assert flaky_test() == "Success" |
| 62 | + |
| 63 | + assert call_count == 2 |
| 64 | + |
| 65 | + |
| 66 | +def test_retry_once_fallback_failure(): |
| 67 | + with mock.patch('openfermion.testing.wrapped.cirq', MockCirq()): |
| 68 | + |
| 69 | + call_count = 0 |
| 70 | + |
| 71 | + @wrapped.retry_once_with_later_random_values |
| 72 | + def failing_test(): |
| 73 | + nonlocal call_count |
| 74 | + call_count += 1 |
| 75 | + raise AssertionError("Failed both times") |
| 76 | + |
| 77 | + with pytest.warns( |
| 78 | + UserWarning, match="Retrying in case we got a failing seed from pytest-randomly." |
| 79 | + ): |
| 80 | + with pytest.raises(AssertionError, match="Failed both times"): |
| 81 | + failing_test() |
| 82 | + |
| 83 | + assert call_count == 2 |
0 commit comments