Skip to content

Commit 67c8a85

Browse files
committed
WIP
1 parent b4e32a1 commit 67c8a85

File tree

3 files changed

+252
-9
lines changed

3 files changed

+252
-9
lines changed

test/asynchronous/test_dns.py

Lines changed: 220 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,220 @@
1+
# Copyright 2017 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+
"""Run the SRV support tests."""
16+
from __future__ import annotations
17+
18+
import glob
19+
import json
20+
import os
21+
import pathlib
22+
import sys
23+
24+
sys.path[0:0] = [""]
25+
26+
from test.asynchronous import (
27+
AsyncIntegrationTest,
28+
AsyncPyMongoTestCase,
29+
async_client_context,
30+
unittest,
31+
)
32+
from test.utils import async_wait_until
33+
34+
from pymongo.common import validate_read_preference_tags
35+
from pymongo.errors import ConfigurationError
36+
from pymongo.uri_parser import parse_uri, split_hosts
37+
38+
_IS_SYNC = False
39+
40+
41+
class TestDNSRepl(AsyncPyMongoTestCase):
42+
if _IS_SYNC:
43+
TEST_PATH = os.path.join(
44+
pathlib.Path(__file__).resolve().parent, "srv_seedlist", "replica-set"
45+
)
46+
else:
47+
TEST_PATH = os.path.join(
48+
pathlib.Path(__file__).resolve().parent.parent, "srv_seedlist", "replica-set"
49+
)
50+
load_balanced = False
51+
52+
@async_client_context.require_replica_set
53+
def asyncSetUp(self):
54+
pass
55+
56+
57+
class TestDNSLoadBalanced(AsyncPyMongoTestCase):
58+
if _IS_SYNC:
59+
TEST_PATH = os.path.join(
60+
pathlib.Path(__file__).resolve().parent, "srv_seedlist", "load-balanced"
61+
)
62+
else:
63+
TEST_PATH = os.path.join(
64+
pathlib.Path(__file__).resolve().parent.parent, "srv_seedlist", "load-balanced"
65+
)
66+
load_balanced = True
67+
68+
@async_client_context.require_load_balancer
69+
def asyncSetUp(self):
70+
pass
71+
72+
73+
class TestDNSSharded(AsyncPyMongoTestCase):
74+
if _IS_SYNC:
75+
TEST_PATH = os.path.join(pathlib.Path(__file__).resolve().parent, "srv_seedlist", "sharded")
76+
else:
77+
TEST_PATH = os.path.join(
78+
pathlib.Path(__file__).resolve().parent.parent, "srv_seedlist", "sharded"
79+
)
80+
load_balanced = False
81+
82+
@async_client_context.require_mongos
83+
def asyncSetUp(self):
84+
pass
85+
86+
87+
def create_test(test_case):
88+
async def run_test(self):
89+
uri = test_case["uri"]
90+
seeds = test_case.get("seeds")
91+
num_seeds = test_case.get("numSeeds", len(seeds or []))
92+
hosts = test_case.get("hosts")
93+
num_hosts = test_case.get("numHosts", len(hosts or []))
94+
95+
options = test_case.get("options", {})
96+
if "ssl" in options:
97+
options["tls"] = options.pop("ssl")
98+
parsed_options = test_case.get("parsed_options")
99+
# See DRIVERS-1324, unless tls is explicitly set to False we need TLS.
100+
needs_tls = not (options and (options.get("ssl") is False or options.get("tls") is False))
101+
if needs_tls and not async_client_context.tls:
102+
self.skipTest("this test requires a TLS cluster")
103+
if not needs_tls and async_client_context.tls:
104+
self.skipTest("this test requires a non-TLS cluster")
105+
106+
if seeds:
107+
seeds = split_hosts(",".join(seeds))
108+
if hosts:
109+
hosts = frozenset(split_hosts(",".join(hosts)))
110+
111+
if seeds or num_seeds:
112+
result = parse_uri(uri, validate=True)
113+
if seeds is not None:
114+
self.assertEqual(sorted(result["nodelist"]), sorted(seeds))
115+
if num_seeds is not None:
116+
self.assertEqual(len(result["nodelist"]), num_seeds)
117+
if options:
118+
opts = result["options"]
119+
if "readpreferencetags" in opts:
120+
rpts = validate_read_preference_tags(
121+
"readPreferenceTags", opts.pop("readpreferencetags")
122+
)
123+
opts["readPreferenceTags"] = rpts
124+
self.assertEqual(result["options"], options)
125+
if parsed_options:
126+
for opt, expected in parsed_options.items():
127+
if opt == "user":
128+
self.assertEqual(result["username"], expected)
129+
elif opt == "password":
130+
self.assertEqual(result["password"], expected)
131+
elif opt == "auth_database" or opt == "db":
132+
self.assertEqual(result["database"], expected)
133+
134+
hostname = next(iter(async_client_context.client.nodes))[0]
135+
# The replica set members must be configured as 'localhost'.
136+
if hostname == "localhost":
137+
copts = async_client_context.default_client_options.copy()
138+
# Remove tls since SRV parsing should add it automatically.
139+
copts.pop("tls", None)
140+
if async_client_context.tls:
141+
# Our test certs don't support the SRV hosts used in these
142+
# tests.
143+
copts["tlsAllowInvalidHostnames"] = True
144+
145+
client = AsyncPyMongoTestCase.unmanaged_simple_client(uri, **copts)
146+
if num_seeds is not None:
147+
self.assertEqual(len(client._topology_settings.seeds), num_seeds)
148+
if hosts is not None:
149+
await async_wait_until(
150+
lambda: hosts == client.nodes, "match test hosts to client nodes"
151+
)
152+
if num_hosts is not None:
153+
await async_wait_until(
154+
lambda: num_hosts == len(client.nodes), "wait to connect to num_hosts"
155+
)
156+
if test_case.get("ping", True):
157+
await client.admin.command("ping")
158+
# XXX: we should block until SRV poller runs at least once
159+
# and re-run these assertions.
160+
await client.close()
161+
else:
162+
try:
163+
parse_uri(uri)
164+
except (ConfigurationError, ValueError):
165+
pass
166+
else:
167+
self.fail("failed to raise an exception")
168+
169+
return run_test
170+
171+
172+
def create_tests(cls):
173+
for filename in glob.glob(os.path.join(cls.TEST_PATH, "*.json")):
174+
test_suffix, _ = os.path.splitext(os.path.basename(filename))
175+
with open(filename) as dns_test_file:
176+
test_method = create_test(json.load(dns_test_file))
177+
setattr(cls, "test_" + test_suffix, test_method)
178+
179+
180+
create_tests(TestDNSRepl)
181+
create_tests(TestDNSLoadBalanced)
182+
create_tests(TestDNSSharded)
183+
184+
185+
class TestParsingErrors(AsyncPyMongoTestCase):
186+
async def test_invalid_host(self):
187+
self.assertRaisesRegex(
188+
ConfigurationError,
189+
"Invalid URI host: mongodb is not",
190+
self.simple_client,
191+
"mongodb+srv://mongodb",
192+
)
193+
self.assertRaisesRegex(
194+
ConfigurationError,
195+
"Invalid URI host: mongodb.com is not",
196+
self.simple_client,
197+
"mongodb+srv://mongodb.com",
198+
)
199+
self.assertRaisesRegex(
200+
ConfigurationError,
201+
"Invalid URI host: an IP address is not",
202+
self.simple_client,
203+
"mongodb+srv://127.0.0.1",
204+
)
205+
self.assertRaisesRegex(
206+
ConfigurationError,
207+
"Invalid URI host: an IP address is not",
208+
self.simple_client,
209+
"mongodb+srv://[::1]",
210+
)
211+
212+
213+
class IsolatedAsyncioTestCaseInsensitive(AsyncIntegrationTest):
214+
async def test_connect_case_insensitive(self):
215+
client = self.simple_client("mongodb+srv://TEST1.TEST.BUILD.10GEN.cc/")
216+
self.assertGreater(len(client.topology_description.server_descriptions()), 1)
217+
218+
219+
if __name__ == "__main__":
220+
unittest.main()

test/test_dns.py

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,22 +18,35 @@
1818
import glob
1919
import json
2020
import os
21+
import pathlib
2122
import sys
2223

2324
sys.path[0:0] = [""]
2425

25-
from test import IntegrationTest, PyMongoTestCase, client_context, unittest
26+
from test import (
27+
IntegrationTest,
28+
PyMongoTestCase,
29+
client_context,
30+
unittest,
31+
)
2632
from test.utils import wait_until
2733

2834
from pymongo.common import validate_read_preference_tags
2935
from pymongo.errors import ConfigurationError
3036
from pymongo.uri_parser import parse_uri, split_hosts
3137

38+
_IS_SYNC = True
39+
3240

3341
class TestDNSRepl(PyMongoTestCase):
34-
TEST_PATH = os.path.join(
35-
os.path.dirname(os.path.realpath(__file__)), "srv_seedlist", "replica-set"
36-
)
42+
if _IS_SYNC:
43+
TEST_PATH = os.path.join(
44+
pathlib.Path(__file__).resolve().parent, "srv_seedlist", "replica-set"
45+
)
46+
else:
47+
TEST_PATH = os.path.join(
48+
pathlib.Path(__file__).resolve().parent.parent, "srv_seedlist", "replica-set"
49+
)
3750
load_balanced = False
3851

3952
@client_context.require_replica_set
@@ -42,9 +55,14 @@ def setUp(self):
4255

4356

4457
class TestDNSLoadBalanced(PyMongoTestCase):
45-
TEST_PATH = os.path.join(
46-
os.path.dirname(os.path.realpath(__file__)), "srv_seedlist", "load-balanced"
47-
)
58+
if _IS_SYNC:
59+
TEST_PATH = os.path.join(
60+
pathlib.Path(__file__).resolve().parent, "srv_seedlist", "load-balanced"
61+
)
62+
else:
63+
TEST_PATH = os.path.join(
64+
pathlib.Path(__file__).resolve().parent.parent, "srv_seedlist", "load-balanced"
65+
)
4866
load_balanced = True
4967

5068
@client_context.require_load_balancer
@@ -53,7 +71,12 @@ def setUp(self):
5371

5472

5573
class TestDNSSharded(PyMongoTestCase):
56-
TEST_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "srv_seedlist", "sharded")
74+
if _IS_SYNC:
75+
TEST_PATH = os.path.join(pathlib.Path(__file__).resolve().parent, "srv_seedlist", "sharded")
76+
else:
77+
TEST_PATH = os.path.join(
78+
pathlib.Path(__file__).resolve().parent.parent, "srv_seedlist", "sharded"
79+
)
5780
load_balanced = False
5881

5982
@client_context.require_mongos
@@ -188,7 +211,6 @@ def test_invalid_host(self):
188211
class TestCaseInsensitive(IntegrationTest):
189212
def test_connect_case_insensitive(self):
190213
client = self.simple_client("mongodb+srv://TEST1.TEST.BUILD.10GEN.cc/")
191-
self.addCleanup(client.close)
192214
self.assertGreater(len(client.topology_description.server_descriptions()), 1)
193215

194216

tools/synchro.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,7 @@ def async_only_test(f: str) -> bool:
205205
"test_custom_types.py",
206206
"test_database.py",
207207
"test_data_lake.py",
208+
"test_dns.py",
208209
"test_encryption.py",
209210
"test_grid_file.py",
210211
"test_logger.py",

0 commit comments

Comments
 (0)