|
| 1 | +# Copyright 2024 Google LLC All rights reserved. |
| 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 | + |
| 15 | +import time |
| 16 | +import random |
| 17 | +import threading |
| 18 | +import unittest |
| 19 | +from google.cloud.spanner_v1._helpers import AtomicCounter |
| 20 | + |
| 21 | +class TestAtomicCounter(unittest.TestCase): |
| 22 | + def test_initialization(self): |
| 23 | + ac_default = AtomicCounter() |
| 24 | + assert ac_default.value == 0 |
| 25 | + |
| 26 | + ac_1 = AtomicCounter(1) |
| 27 | + assert ac_1.value == 1 |
| 28 | + |
| 29 | + ac_negative_1 = AtomicCounter(-1) |
| 30 | + assert ac_negative_1.value == -1 |
| 31 | + |
| 32 | + def test_increment(self): |
| 33 | + ac = AtomicCounter() |
| 34 | + result_default = ac.increment() |
| 35 | + assert result_default == 1 |
| 36 | + assert ac.value == 1 |
| 37 | + |
| 38 | + result_with_value = ac.increment(2) |
| 39 | + assert result_with_value == 3 |
| 40 | + assert ac.value == 3 |
| 41 | + result_plus_100 = ac.increment(100) |
| 42 | + assert result_plus_100 == 103 |
| 43 | + |
| 44 | + def test_plus_call(self): |
| 45 | + ac = AtomicCounter() |
| 46 | + ac += 1 |
| 47 | + assert ac.value == 1 |
| 48 | + |
| 49 | + n = ac + 2 |
| 50 | + assert n == 3 |
| 51 | + assert ac.value == 1 |
| 52 | + |
| 53 | + n = 200 + ac |
| 54 | + assert n == 201 |
| 55 | + assert ac.value == 1 |
| 56 | + |
| 57 | + |
| 58 | + def test_multiple_threads_incrementing(self): |
| 59 | + ac = AtomicCounter() |
| 60 | + n = 200 |
| 61 | + m = 10 |
| 62 | + |
| 63 | + def do_work(): |
| 64 | + for i in range(m): |
| 65 | + ac.increment() |
| 66 | + |
| 67 | + threads = [] |
| 68 | + for i in range(n): |
| 69 | + th = threading.Thread(target=do_work) |
| 70 | + threads.append(th) |
| 71 | + th.start() |
| 72 | + |
| 73 | + time.sleep(0.3) |
| 74 | + |
| 75 | + random.shuffle(threads) |
| 76 | + for th in threads: |
| 77 | + th.join() |
| 78 | + assert th.is_alive() == False |
| 79 | + |
| 80 | + # Finally the result should be n*m |
| 81 | + assert ac.value == n*m |
0 commit comments