Skip to content

Commit 083b153

Browse files
author
Luke Lovett
committed
PYTHON-765 Allow tests to use an existing user when running with auth enabled.
1 parent ad3a03a commit 083b153

File tree

1 file changed

+21
-8
lines changed

1 file changed

+21
-8
lines changed

test/__init__.py

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
port3 = int(os.environ.get("DB_PORT3", 27019))
3737

3838
db_user = unicode(os.environ.get("DB_USER", "administrator"))
39-
db_pwd = unicode(os.environ.get("DB_PWD", "password"))
39+
db_pwd = unicode(os.environ.get("DB_PASSWORD", "password"))
4040

4141

4242
class AuthContext(object):
@@ -50,11 +50,22 @@ def __init__(self):
5050
if self._server_started_with_auth(command_line):
5151
self.auth_enabled = True
5252
except OperationFailure, e:
53-
if e.code == 13:
53+
msg = e.details.get('errmsg', '')
54+
if e.code == 13 or 'unauthorized' in msg or 'login' in msg:
5455
self.auth_enabled = True
5556
self.restricted_localhost = True
5657
else:
5758
raise
59+
# See if the user has already been set up.
60+
try:
61+
self.client.admin.authenticate(db_user, db_pwd)
62+
self.user_provided = True
63+
except OperationFailure, e:
64+
msg = e.details.get('errmsg', '')
65+
if e.code == 18 or 'auth fails' in msg:
66+
self.user_provided = False
67+
else:
68+
raise
5869

5970
def _server_started_with_auth(self, command_line):
6071
# MongoDB >= 2.0
@@ -72,15 +83,17 @@ def _server_started_with_auth(self, command_line):
7283
return '--auth' in argv or '--keyFile' in argv
7384

7485
def add_user_and_log_in(self):
75-
self.client.admin.add_user(db_user, db_pwd,
76-
roles=('userAdminAnyDatabase',
77-
'readWriteAnyDatabase',
78-
'dbAdminAnyDatabase',
79-
'clusterAdmin'))
86+
if not self.user_provided:
87+
self.client.admin.add_user(db_user, db_pwd,
88+
roles=('userAdminAnyDatabase',
89+
'readWriteAnyDatabase',
90+
'dbAdminAnyDatabase',
91+
'clusterAdmin'))
8092
self.client.admin.authenticate(db_user, db_pwd)
8193

8294
def remove_user_and_log_out(self):
83-
self.client.admin.remove_user(db_user)
95+
if not self.user_provided:
96+
self.client.admin.remove_user(db_user)
8497
self.client.admin.logout()
8598
self.client.disconnect()
8699

0 commit comments

Comments
 (0)