|
| 1 | +# Copyright 2015 MongoDB, Inc. |
| 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 | +"""Test the topology module.""" |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import json |
| 19 | +import os |
| 20 | +import sys |
| 21 | +from pathlib import Path |
| 22 | + |
| 23 | +sys.path[0:0] = [""] |
| 24 | + |
| 25 | +from test import unittest |
| 26 | +from test.asynchronous import AsyncPyMongoTestCase |
| 27 | + |
| 28 | +from pymongo.read_preferences import MovingAverage |
| 29 | + |
| 30 | +_IS_SYNC = False |
| 31 | + |
| 32 | +# Location of JSON test specifications. |
| 33 | +if _IS_SYNC: |
| 34 | + TEST_PATH = os.path.join(Path(__file__).resolve().parent, "server_selection/rtt") |
| 35 | +else: |
| 36 | + TEST_PATH = os.path.join(Path(__file__).resolve().parent.parent, "server_selection/rtt") |
| 37 | + |
| 38 | + |
| 39 | +class TestAllScenarios(AsyncPyMongoTestCase): |
| 40 | + pass |
| 41 | + |
| 42 | + |
| 43 | +def create_test(scenario_def): |
| 44 | + def run_scenario(self): |
| 45 | + moving_average = MovingAverage() |
| 46 | + |
| 47 | + if scenario_def["avg_rtt_ms"] != "NULL": |
| 48 | + moving_average.add_sample(scenario_def["avg_rtt_ms"]) |
| 49 | + |
| 50 | + if scenario_def["new_rtt_ms"] != "NULL": |
| 51 | + moving_average.add_sample(scenario_def["new_rtt_ms"]) |
| 52 | + |
| 53 | + self.assertAlmostEqual(moving_average.get(), scenario_def["new_avg_rtt"]) |
| 54 | + |
| 55 | + return run_scenario |
| 56 | + |
| 57 | + |
| 58 | +def create_tests(): |
| 59 | + for dirpath, _, filenames in os.walk(TEST_PATH): |
| 60 | + dirname = os.path.split(dirpath)[-1] |
| 61 | + |
| 62 | + for filename in filenames: |
| 63 | + with open(os.path.join(dirpath, filename)) as scenario_stream: |
| 64 | + scenario_def = json.load(scenario_stream) |
| 65 | + |
| 66 | + # Construct test from scenario. |
| 67 | + new_test = create_test(scenario_def) |
| 68 | + test_name = f"test_{dirname}_{os.path.splitext(filename)[0]}" |
| 69 | + |
| 70 | + new_test.__name__ = test_name |
| 71 | + setattr(TestAllScenarios, new_test.__name__, new_test) |
| 72 | + |
| 73 | + |
| 74 | +create_tests() |
| 75 | + |
| 76 | +if __name__ == "__main__": |
| 77 | + unittest.main() |
0 commit comments