1# Copyright 2015 gRPC authors.
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#     http://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"""Tests for grpc.framework.foundation.logging_pool."""
15
16import threading
17import unittest
18
19from grpc.framework.foundation import logging_pool
20
21_POOL_SIZE = 16
22
23
24class _CallableObject(object):
25    def __init__(self):
26        self._lock = threading.Lock()
27        self._passed_values = []
28
29    def __call__(self, value):
30        with self._lock:
31            self._passed_values.append(value)
32
33    def passed_values(self):
34        with self._lock:
35            return tuple(self._passed_values)
36
37
38class LoggingPoolTest(unittest.TestCase):
39    def testUpAndDown(self):
40        pool = logging_pool.pool(_POOL_SIZE)
41        pool.shutdown(wait=True)
42
43        with logging_pool.pool(_POOL_SIZE) as pool:
44            self.assertIsNotNone(pool)
45
46    def testTaskExecuted(self):
47        test_list = []
48
49        with logging_pool.pool(_POOL_SIZE) as pool:
50            pool.submit(lambda: test_list.append(object())).result()
51
52        self.assertTrue(test_list)
53
54    def testException(self):
55        with logging_pool.pool(_POOL_SIZE) as pool:
56            raised_exception = pool.submit(lambda: 1 / 0).exception()
57
58        self.assertIsNotNone(raised_exception)
59
60    def testCallableObjectExecuted(self):
61        callable_object = _CallableObject()
62        passed_object = object()
63        with logging_pool.pool(_POOL_SIZE) as pool:
64            future = pool.submit(callable_object, passed_object)
65        self.assertIsNone(future.result())
66        self.assertSequenceEqual(
67            (passed_object,), callable_object.passed_values()
68        )
69
70
71if __name__ == "__main__":
72    unittest.main(verbosity=2)
73