aboutsummaryrefslogtreecommitdiff
path: root/tests/unit/future/test_polling.py
blob: c67de064add58d2d73b879a0ae3b12fa4eddff4b (plain)
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
# Copyright 2017, Google LLC
#
# 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.

import concurrent.futures
import threading
import time

import mock
import pytest

from google.api_core import exceptions
from google.api_core.future import polling


class PollingFutureImpl(polling.PollingFuture):
    def done(self):
        return False

    def cancel(self):
        return True

    def cancelled(self):
        return False

    def running(self):
        return True


def test_polling_future_constructor():
    future = PollingFutureImpl()
    assert not future.done()
    assert not future.cancelled()
    assert future.running()
    assert future.cancel()


def test_set_result():
    future = PollingFutureImpl()
    callback = mock.Mock()

    future.set_result(1)

    assert future.result() == 1
    future.add_done_callback(callback)
    callback.assert_called_once_with(future)


def test_set_exception():
    future = PollingFutureImpl()
    exception = ValueError("meep")

    future.set_exception(exception)

    assert future.exception() == exception
    with pytest.raises(ValueError):
        future.result()

    callback = mock.Mock()
    future.add_done_callback(callback)
    callback.assert_called_once_with(future)


def test_invoke_callback_exception():
    future = PollingFutureImplWithPoll()
    future.set_result(42)

    # This should not raise, despite the callback causing an exception.
    callback = mock.Mock(side_effect=ValueError)
    future.add_done_callback(callback)
    callback.assert_called_once_with(future)


class PollingFutureImplWithPoll(PollingFutureImpl):
    def __init__(self):
        super(PollingFutureImplWithPoll, self).__init__()
        self.poll_count = 0
        self.event = threading.Event()

    def done(self):
        self.poll_count += 1
        self.event.wait()
        self.set_result(42)
        return True


def test_result_with_polling():
    future = PollingFutureImplWithPoll()

    future.event.set()
    result = future.result()

    assert result == 42
    assert future.poll_count == 1
    # Repeated calls should not cause additional polling
    assert future.result() == result
    assert future.poll_count == 1


class PollingFutureImplTimeout(PollingFutureImplWithPoll):
    def done(self):
        time.sleep(1)
        return False


def test_result_timeout():
    future = PollingFutureImplTimeout()
    with pytest.raises(concurrent.futures.TimeoutError):
        future.result(timeout=1)


def test_exception_timeout():
    future = PollingFutureImplTimeout()
    with pytest.raises(concurrent.futures.TimeoutError):
        future.exception(timeout=1)


class PollingFutureImplTransient(PollingFutureImplWithPoll):
    def __init__(self, errors):
        super(PollingFutureImplTransient, self).__init__()
        self._errors = errors

    def done(self):
        if self._errors:
            error, self._errors = self._errors[0], self._errors[1:]
            raise error("testing")
        self.poll_count += 1
        self.set_result(42)
        return True


def test_result_transient_error():
    future = PollingFutureImplTransient(
        (
            exceptions.TooManyRequests,
            exceptions.InternalServerError,
            exceptions.BadGateway,
        )
    )
    result = future.result()
    assert result == 42
    assert future.poll_count == 1
    # Repeated calls should not cause additional polling
    assert future.result() == result
    assert future.poll_count == 1


def test_callback_background_thread():
    future = PollingFutureImplWithPoll()
    callback = mock.Mock()

    future.add_done_callback(callback)

    assert future._polling_thread is not None

    # Give the thread a second to poll
    time.sleep(1)
    assert future.poll_count == 1

    future.event.set()
    future._polling_thread.join()

    callback.assert_called_once_with(future)


def test_double_callback_background_thread():
    future = PollingFutureImplWithPoll()
    callback = mock.Mock()
    callback2 = mock.Mock()

    future.add_done_callback(callback)
    current_thread = future._polling_thread
    assert current_thread is not None

    # only one polling thread should be created.
    future.add_done_callback(callback2)
    assert future._polling_thread is current_thread

    future.event.set()
    future._polling_thread.join()

    assert future.poll_count == 1
    callback.assert_called_once_with(future)
    callback2.assert_called_once_with(future)