Skip to content

Commit 7ff4898

Browse files
committed
Improve test suite primary discovery
1 parent 295bd96 commit 7ff4898

1 file changed

Lines changed: 20 additions & 12 deletions

File tree

test/__init__.py

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
import os
1919
import sys
20+
import time
2021
import warnings
2122

2223
import pymongo
@@ -49,18 +50,25 @@ def _split_host_port(host_port):
4950
# When testing against a replica set, 'host' and 'port' need
5051
# to represent the primary.
5152
try:
52-
_ismaster = pymongo.MongoClient(host, port).admin.command('ismaster')
53-
# Master slave topologies don't use setName. The members also aren't
54-
# aware of one another (e.g. ismaster doesn't have a 'hosts' field).
55-
if 'setName' in _ismaster:
56-
_primary = _ismaster['primary']
57-
host, port = _split_host_port(_primary)
58-
_secondaries = set(_ismaster['hosts']) - set([_primary])
59-
for _idx, _host_port in enumerate(_secondaries):
60-
_host, _port = _split_host_port(_host_port)
61-
# Enumerate doesn't accept a start argument until python 2.6.
62-
setattr(sys.modules[__name__], "host%d" % (_idx + 1,), _host)
63-
setattr(sys.modules[__name__], "port%d" % (_idx + 1,), _port)
53+
# Try to find the primary for 10 seconds.
54+
for _ in range(10):
55+
_ismaster = pymongo.MongoClient(host, port).admin.command('ismaster')
56+
# Master slave topologies don't use setName. The members also aren't
57+
# aware of one another (e.g. ismaster doesn't have a 'hosts' field).
58+
if 'setName' in _ismaster:
59+
_primary = _ismaster.get('primary')
60+
# No primary (yet?)
61+
if _primary is None:
62+
time.sleep(1)
63+
continue
64+
host, port = _split_host_port(_primary)
65+
_secondaries = set(_ismaster['hosts']) - set([_primary])
66+
for _idx, _host_port in enumerate(_secondaries):
67+
_host, _port = _split_host_port(_host_port)
68+
# Enumerate doesn't accept a start argument until python 2.6.
69+
setattr(sys.modules[__name__], "host%d" % (_idx + 1,), _host)
70+
setattr(sys.modules[__name__], "port%d" % (_idx + 1,), _port)
71+
break
6472
except ConnectionFailure:
6573
pass
6674

0 commit comments

Comments
 (0)